repo_name
stringlengths
7
70
file_path
stringlengths
9
215
context
list
import_statement
stringlengths
47
10.3k
token_num
int64
643
100k
cropped_code
stringlengths
62
180k
all_code
stringlengths
62
224k
next_line
stringlengths
9
1.07k
gold_snippet_index
int64
0
117
created_at
stringlengths
25
25
level
stringclasses
9 values
Man2Dev/N-Queen
lib/jfreechart-1.0.19/tests/org/jfree/chart/renderer/xy/XYAreaRenderer2Test.java
[ { "identifier": "JFreeChart", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/JFreeChart.java", "snippet": "public class JFreeChart implements Drawable, TitleChangeListener,\r\n PlotChangeListener, Serializable, Cloneable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -3470703747817429120L;\r\n\r\n /** Information about the project. */\r\n public static final ProjectInfo INFO = new JFreeChartInfo();\r\n\r\n /** The default font for titles. */\r\n public static final Font DEFAULT_TITLE_FONT\r\n = new Font(\"SansSerif\", Font.BOLD, 18);\r\n\r\n /** The default background color. */\r\n public static final Paint DEFAULT_BACKGROUND_PAINT\r\n = UIManager.getColor(\"Panel.background\");\r\n\r\n /** The default background image. */\r\n public static final Image DEFAULT_BACKGROUND_IMAGE = null;\r\n\r\n /** The default background image alignment. */\r\n public static final int DEFAULT_BACKGROUND_IMAGE_ALIGNMENT = Align.FIT;\r\n\r\n /** The default background image alpha. */\r\n public static final float DEFAULT_BACKGROUND_IMAGE_ALPHA = 0.5f;\r\n\r\n /**\r\n * The key for a rendering hint that can suppress the generation of a \r\n * shadow effect when drawing the chart. The hint value must be a \r\n * Boolean.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static final RenderingHints.Key KEY_SUPPRESS_SHADOW_GENERATION\r\n = new RenderingHints.Key(0) {\r\n @Override\r\n public boolean isCompatibleValue(Object val) {\r\n return val instanceof Boolean;\r\n }\r\n };\r\n \r\n /**\r\n * Rendering hints that will be used for chart drawing. This should never\r\n * be <code>null</code>.\r\n */\r\n private transient RenderingHints renderingHints;\r\n\r\n /** A flag that controls whether or not the chart border is drawn. */\r\n private boolean borderVisible;\r\n\r\n /** The stroke used to draw the chart border (if visible). */\r\n private transient Stroke borderStroke;\r\n\r\n /** The paint used to draw the chart border (if visible). */\r\n private transient Paint borderPaint;\r\n\r\n /** The padding between the chart border and the chart drawing area. */\r\n private RectangleInsets padding;\r\n\r\n /** The chart title (optional). */\r\n private TextTitle title;\r\n\r\n /**\r\n * The chart subtitles (zero, one or many). This field should never be\r\n * <code>null</code>.\r\n */\r\n private List subtitles;\r\n\r\n /** Draws the visual representation of the data. */\r\n private Plot plot;\r\n\r\n /** Paint used to draw the background of the chart. */\r\n private transient Paint backgroundPaint;\r\n\r\n /** An optional background image for the chart. */\r\n private transient Image backgroundImage; // todo: not serialized yet\r\n\r\n /** The alignment for the background image. */\r\n private int backgroundImageAlignment = Align.FIT;\r\n\r\n /** The alpha transparency for the background image. */\r\n private float backgroundImageAlpha = 0.5f;\r\n\r\n /** Storage for registered change listeners. */\r\n private transient EventListenerList changeListeners;\r\n\r\n /** Storage for registered progress listeners. */\r\n private transient EventListenerList progressListeners;\r\n\r\n /**\r\n * A flag that can be used to enable/disable notification of chart change\r\n * events.\r\n */\r\n private boolean notify;\r\n\r\n /**\r\n * Creates a new chart based on the supplied plot. The chart will have\r\n * a legend added automatically, but no title (although you can easily add\r\n * one later).\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(Plot plot) {\r\n this(null, null, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. A default font\r\n * ({@link #DEFAULT_TITLE_FONT}) is used for the title, and the chart will\r\n * have a legend added automatically.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(String title, Plot plot) {\r\n this(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. The\r\n * <code>createLegend</code> argument specifies whether or not a legend\r\n * should be added to the chart.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param titleFont the font for displaying the chart title\r\n * (<code>null</code> permitted).\r\n * @param plot controller of the visual representation of the data\r\n * (<code>null</code> not permitted).\r\n * @param createLegend a flag indicating whether or not a legend should\r\n * be created for the chart.\r\n */\r\n public JFreeChart(String title, Font titleFont, Plot plot,\r\n boolean createLegend) {\r\n\r\n ParamChecks.nullNotPermitted(plot, \"plot\");\r\n\r\n // create storage for listeners...\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.notify = true; // default is to notify listeners when the\r\n // chart changes\r\n\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n // added the following hint because of \r\n // http://stackoverflow.com/questions/7785082/\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n this.borderVisible = false;\r\n this.borderStroke = new BasicStroke(1.0f);\r\n this.borderPaint = Color.black;\r\n\r\n this.padding = RectangleInsets.ZERO_INSETS;\r\n\r\n this.plot = plot;\r\n plot.addChangeListener(this);\r\n\r\n this.subtitles = new ArrayList();\r\n\r\n // create a legend, if requested...\r\n if (createLegend) {\r\n LegendTitle legend = new LegendTitle(this.plot);\r\n legend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));\r\n legend.setFrame(new LineBorder());\r\n legend.setBackgroundPaint(Color.white);\r\n legend.setPosition(RectangleEdge.BOTTOM);\r\n this.subtitles.add(legend);\r\n legend.addChangeListener(this);\r\n }\r\n\r\n // add the chart title, if one has been specified...\r\n if (title != null) {\r\n if (titleFont == null) {\r\n titleFont = DEFAULT_TITLE_FONT;\r\n }\r\n this.title = new TextTitle(title, titleFont);\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n this.backgroundPaint = DEFAULT_BACKGROUND_PAINT;\r\n\r\n this.backgroundImage = DEFAULT_BACKGROUND_IMAGE;\r\n this.backgroundImageAlignment = DEFAULT_BACKGROUND_IMAGE_ALIGNMENT;\r\n this.backgroundImageAlpha = DEFAULT_BACKGROUND_IMAGE_ALPHA;\r\n\r\n }\r\n\r\n /**\r\n * Returns the collection of rendering hints for the chart.\r\n *\r\n * @return The rendering hints for the chart (never <code>null</code>).\r\n *\r\n * @see #setRenderingHints(RenderingHints)\r\n */\r\n public RenderingHints getRenderingHints() {\r\n return this.renderingHints;\r\n }\r\n\r\n /**\r\n * Sets the rendering hints for the chart. These will be added (using the\r\n * {@code Graphics2D.addRenderingHints()} method) near the start of the\r\n * {@code JFreeChart.draw()} method.\r\n *\r\n * @param renderingHints the rendering hints ({@code null} not permitted).\r\n *\r\n * @see #getRenderingHints()\r\n */\r\n public void setRenderingHints(RenderingHints renderingHints) {\r\n ParamChecks.nullNotPermitted(renderingHints, \"renderingHints\");\r\n this.renderingHints = renderingHints;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setBorderVisible(boolean)\r\n */\r\n public boolean isBorderVisible() {\r\n return this.borderVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isBorderVisible()\r\n */\r\n public void setBorderVisible(boolean visible) {\r\n this.borderVisible = visible;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the chart border (if visible).\r\n *\r\n * @return The border stroke.\r\n *\r\n * @see #setBorderStroke(Stroke)\r\n */\r\n public Stroke getBorderStroke() {\r\n return this.borderStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the chart border (if visible).\r\n *\r\n * @param stroke the stroke.\r\n *\r\n * @see #getBorderStroke()\r\n */\r\n public void setBorderStroke(Stroke stroke) {\r\n this.borderStroke = stroke;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the chart border (if visible).\r\n *\r\n * @return The border paint.\r\n *\r\n * @see #setBorderPaint(Paint)\r\n */\r\n public Paint getBorderPaint() {\r\n return this.borderPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the chart border (if visible).\r\n *\r\n * @param paint the paint.\r\n *\r\n * @see #getBorderPaint()\r\n */\r\n public void setBorderPaint(Paint paint) {\r\n this.borderPaint = paint;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the padding between the chart border and the chart drawing area.\r\n *\r\n * @return The padding (never <code>null</code>).\r\n *\r\n * @see #setPadding(RectangleInsets)\r\n */\r\n public RectangleInsets getPadding() {\r\n return this.padding;\r\n }\r\n\r\n /**\r\n * Sets the padding between the chart border and the chart drawing area,\r\n * and sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param padding the padding (<code>null</code> not permitted).\r\n *\r\n * @see #getPadding()\r\n */\r\n public void setPadding(RectangleInsets padding) {\r\n ParamChecks.nullNotPermitted(padding, \"padding\");\r\n this.padding = padding;\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the main chart title. Very often a chart will have just one\r\n * title, so we make this case simple by providing accessor methods for\r\n * the main title. However, multiple titles are supported - see the\r\n * {@link #addSubtitle(Title)} method.\r\n *\r\n * @return The chart title (possibly <code>null</code>).\r\n *\r\n * @see #setTitle(TextTitle)\r\n */\r\n public TextTitle getTitle() {\r\n return this.title;\r\n }\r\n\r\n /**\r\n * Sets the main title for the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners. If you do not want a title for the\r\n * chart, set it to <code>null</code>. If you want more than one title on\r\n * a chart, use the {@link #addSubtitle(Title)} method.\r\n *\r\n * @param title the title (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(TextTitle title) {\r\n if (this.title != null) {\r\n this.title.removeChangeListener(this);\r\n }\r\n this.title = title;\r\n if (title != null) {\r\n title.addChangeListener(this);\r\n }\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Sets the chart title and sends a {@link ChartChangeEvent} to all\r\n * registered listeners. This is a convenience method that ends up calling\r\n * the {@link #setTitle(TextTitle)} method. If there is an existing title,\r\n * its text is updated, otherwise a new title using the default font is\r\n * added to the chart. If <code>text</code> is <code>null</code> the chart\r\n * title is set to <code>null</code>.\r\n *\r\n * @param text the title text (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(String text) {\r\n if (text != null) {\r\n if (this.title == null) {\r\n setTitle(new TextTitle(text, JFreeChart.DEFAULT_TITLE_FONT));\r\n }\r\n else {\r\n this.title.setText(text);\r\n }\r\n }\r\n else {\r\n setTitle((TextTitle) null);\r\n }\r\n }\r\n\r\n /**\r\n * Adds a legend to the plot and sends a {@link ChartChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param legend the legend (<code>null</code> not permitted).\r\n *\r\n * @see #removeLegend()\r\n */\r\n public void addLegend(LegendTitle legend) {\r\n addSubtitle(legend);\r\n }\r\n\r\n /**\r\n * Returns the legend for the chart, if there is one. Note that a chart\r\n * can have more than one legend - this method returns the first.\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #getLegend(int)\r\n */\r\n public LegendTitle getLegend() {\r\n return getLegend(0);\r\n }\r\n\r\n /**\r\n * Returns the nth legend for a chart, or <code>null</code>.\r\n *\r\n * @param index the legend index (zero-based).\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #addLegend(LegendTitle)\r\n */\r\n public LegendTitle getLegend(int index) {\r\n int seen = 0;\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title subtitle = (Title) iterator.next();\r\n if (subtitle instanceof LegendTitle) {\r\n if (seen == index) {\r\n return (LegendTitle) subtitle;\r\n }\r\n else {\r\n seen++;\r\n }\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Removes the first legend in the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @see #getLegend()\r\n */\r\n public void removeLegend() {\r\n removeSubtitle(getLegend());\r\n }\r\n\r\n /**\r\n * Returns the list of subtitles for the chart.\r\n *\r\n * @return The subtitle list (possibly empty, but never <code>null</code>).\r\n *\r\n * @see #setSubtitles(List)\r\n */\r\n public List getSubtitles() {\r\n return new ArrayList(this.subtitles);\r\n }\r\n\r\n /**\r\n * Sets the title list for the chart (completely replaces any existing\r\n * titles) and sends a {@link ChartChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param subtitles the new list of subtitles (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public void setSubtitles(List subtitles) {\r\n if (subtitles == null) {\r\n throw new NullPointerException(\"Null 'subtitles' argument.\");\r\n }\r\n setNotify(false);\r\n clearSubtitles();\r\n Iterator iterator = subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n if (t != null) {\r\n addSubtitle(t);\r\n }\r\n }\r\n setNotify(true); // this fires a ChartChangeEvent\r\n }\r\n\r\n /**\r\n * Returns the number of titles for the chart.\r\n *\r\n * @return The number of titles for the chart.\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public int getSubtitleCount() {\r\n return this.subtitles.size();\r\n }\r\n\r\n /**\r\n * Returns a chart subtitle.\r\n *\r\n * @param index the index of the chart subtitle (zero based).\r\n *\r\n * @return A chart subtitle.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public Title getSubtitle(int index) {\r\n if ((index < 0) || (index >= getSubtitleCount())) {\r\n throw new IllegalArgumentException(\"Index out of range.\");\r\n }\r\n return (Title) this.subtitles.get(index);\r\n }\r\n\r\n /**\r\n * Adds a chart subtitle, and notifies registered listeners that the chart\r\n * has been modified.\r\n *\r\n * @param subtitle the subtitle (<code>null</code> not permitted).\r\n *\r\n * @see #getSubtitle(int)\r\n */\r\n public void addSubtitle(Title subtitle) {\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Adds a subtitle at a particular position in the subtitle list, and sends\r\n * a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param index the index (in the range 0 to {@link #getSubtitleCount()}).\r\n * @param subtitle the subtitle to add (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.6\r\n */\r\n public void addSubtitle(int index, Title subtitle) {\r\n if (index < 0 || index > getSubtitleCount()) {\r\n throw new IllegalArgumentException(\r\n \"The 'index' argument is out of range.\");\r\n }\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(index, subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Clears all subtitles from the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void clearSubtitles() {\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n t.removeChangeListener(this);\r\n }\r\n this.subtitles.clear();\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Removes the specified subtitle and sends a {@link ChartChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param title the title.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void removeSubtitle(Title title) {\r\n this.subtitles.remove(title);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the plot for the chart. The plot is a class responsible for\r\n * coordinating the visual representation of the data, including the axes\r\n * (if any).\r\n *\r\n * @return The plot.\r\n */\r\n public Plot getPlot() {\r\n return this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as a {@link CategoryPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link CategoryPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public CategoryPlot getCategoryPlot() {\r\n return (CategoryPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as an {@link XYPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link XYPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public XYPlot getXYPlot() {\r\n return (XYPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns a flag that indicates whether or not anti-aliasing is used when\r\n * the chart is drawn.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAntiAlias(boolean)\r\n */\r\n public boolean getAntiAlias() {\r\n Object val = this.renderingHints.get(RenderingHints.KEY_ANTIALIASING);\r\n return RenderingHints.VALUE_ANTIALIAS_ON.equals(val);\r\n }\r\n\r\n /**\r\n * Sets a flag that indicates whether or not anti-aliasing is used when the\r\n * chart is drawn.\r\n * <P>\r\n * Anti-aliasing usually improves the appearance of charts, but is slower.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #getAntiAlias()\r\n */\r\n public void setAntiAlias(boolean flag) {\r\n Object hint = flag ? RenderingHints.VALUE_ANTIALIAS_ON \r\n : RenderingHints.VALUE_ANTIALIAS_OFF;\r\n this.renderingHints.put(RenderingHints.KEY_ANTIALIASING, hint);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the current value stored in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING}.\r\n *\r\n * @return The hint value (possibly <code>null</code>).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public Object getTextAntiAlias() {\r\n return this.renderingHints.get(RenderingHints.KEY_TEXT_ANTIALIASING);\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} to either\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_ON} or\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_OFF}, then sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public void setTextAntiAlias(boolean flag) {\r\n if (flag) {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\r\n }\r\n else {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);\r\n }\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param val the new value (<code>null</code> permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(boolean)\r\n */\r\n public void setTextAntiAlias(Object val) {\r\n this.renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, val);\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the paint used for the chart background.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundPaint(Paint)\r\n */\r\n public Paint getBackgroundPaint() {\r\n return this.backgroundPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to fill the chart background and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundPaint()\r\n */\r\n public void setBackgroundPaint(Paint paint) {\r\n\r\n if (this.backgroundPaint != null) {\r\n if (!this.backgroundPaint.equals(paint)) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (paint != null) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image for the chart, or <code>null</code> if\r\n * there is no image.\r\n *\r\n * @return The image (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundImage(Image)\r\n */\r\n public Image getBackgroundImage() {\r\n return this.backgroundImage;\r\n }\r\n\r\n /**\r\n * Sets the background image for the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param image the image (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundImage()\r\n */\r\n public void setBackgroundImage(Image image) {\r\n\r\n if (this.backgroundImage != null) {\r\n if (!this.backgroundImage.equals(image)) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (image != null) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image alignment. Alignment constants are defined\r\n * in the <code>org.jfree.ui.Align</code> class in the JCommon class\r\n * library.\r\n *\r\n * @return The alignment.\r\n *\r\n * @see #setBackgroundImageAlignment(int)\r\n */\r\n public int getBackgroundImageAlignment() {\r\n return this.backgroundImageAlignment;\r\n }\r\n\r\n /**\r\n * Sets the background alignment. Alignment options are defined by the\r\n * {@link org.jfree.ui.Align} class.\r\n *\r\n * @param alignment the alignment.\r\n *\r\n * @see #getBackgroundImageAlignment()\r\n */\r\n public void setBackgroundImageAlignment(int alignment) {\r\n if (this.backgroundImageAlignment != alignment) {\r\n this.backgroundImageAlignment = alignment;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha-transparency for the chart's background image.\r\n *\r\n * @return The alpha-transparency.\r\n *\r\n * @see #setBackgroundImageAlpha(float)\r\n */\r\n public float getBackgroundImageAlpha() {\r\n return this.backgroundImageAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha-transparency for the chart's background image.\r\n * Registered listeners are notified that the chart has been changed.\r\n *\r\n * @param alpha the alpha value.\r\n *\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void setBackgroundImageAlpha(float alpha) {\r\n\r\n if (this.backgroundImageAlpha != alpha) {\r\n this.backgroundImageAlpha = alpha;\r\n fireChartChanged();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not change events are sent to\r\n * registered listeners.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNotify(boolean)\r\n */\r\n public boolean isNotify() {\r\n return this.notify;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not listeners receive\r\n * {@link ChartChangeEvent} notifications.\r\n *\r\n * @param notify a boolean.\r\n *\r\n * @see #isNotify()\r\n */\r\n public void setNotify(boolean notify) {\r\n this.notify = notify;\r\n // if the flag is being set to true, there may be queued up changes...\r\n if (notify) {\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area) {\r\n draw(g2, area, null, null);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer). This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D area, ChartRenderingInfo info) {\r\n draw(g2, area, null, info);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param chartArea the area within which the chart should be drawn.\r\n * @param anchor the anchor point (in Java2D space) for the chart\r\n * (<code>null</code> permitted).\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D chartArea, Point2D anchor,\r\n ChartRenderingInfo info) {\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_STARTED, 0));\r\n \r\n EntityCollection entities = null;\r\n // record the chart area, if info is requested...\r\n if (info != null) {\r\n info.clear();\r\n info.setChartArea(chartArea);\r\n entities = info.getEntityCollection();\r\n }\r\n if (entities != null) {\r\n entities.add(new JFreeChartEntity((Rectangle2D) chartArea.clone(),\r\n this));\r\n }\r\n\r\n // ensure no drawing occurs outside chart area...\r\n Shape savedClip = g2.getClip();\r\n g2.clip(chartArea);\r\n\r\n g2.addRenderingHints(this.renderingHints);\r\n\r\n // draw the chart background...\r\n if (this.backgroundPaint != null) {\r\n g2.setPaint(this.backgroundPaint);\r\n g2.fill(chartArea);\r\n }\r\n\r\n if (this.backgroundImage != null) {\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundImageAlpha));\r\n Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,\r\n this.backgroundImage.getWidth(null),\r\n this.backgroundImage.getHeight(null));\r\n Align.align(dest, chartArea, this.backgroundImageAlignment);\r\n g2.drawImage(this.backgroundImage, (int) dest.getX(),\r\n (int) dest.getY(), (int) dest.getWidth(),\r\n (int) dest.getHeight(), null);\r\n g2.setComposite(originalComposite);\r\n }\r\n\r\n if (isBorderVisible()) {\r\n Paint paint = getBorderPaint();\r\n Stroke stroke = getBorderStroke();\r\n if (paint != null && stroke != null) {\r\n Rectangle2D borderArea = new Rectangle2D.Double(\r\n chartArea.getX(), chartArea.getY(),\r\n chartArea.getWidth() - 1.0, chartArea.getHeight()\r\n - 1.0);\r\n g2.setPaint(paint);\r\n g2.setStroke(stroke);\r\n g2.draw(borderArea);\r\n }\r\n }\r\n\r\n // draw the title and subtitles...\r\n Rectangle2D nonTitleArea = new Rectangle2D.Double();\r\n nonTitleArea.setRect(chartArea);\r\n this.padding.trim(nonTitleArea);\r\n\r\n if (this.title != null && this.title.isVisible()) {\r\n EntityCollection e = drawTitle(this.title, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title currentTitle = (Title) iterator.next();\r\n if (currentTitle.isVisible()) {\r\n EntityCollection e = drawTitle(currentTitle, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n }\r\n\r\n Rectangle2D plotArea = nonTitleArea;\r\n\r\n // draw the plot (axes and data visualisation)\r\n PlotRenderingInfo plotInfo = null;\r\n if (info != null) {\r\n plotInfo = info.getPlotInfo();\r\n }\r\n this.plot.draw(g2, plotArea, anchor, null, plotInfo);\r\n\r\n g2.setClip(savedClip);\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_FINISHED, 100));\r\n }\r\n\r\n /**\r\n * Creates a rectangle that is aligned to the frame.\r\n *\r\n * @param dimensions the dimensions for the rectangle.\r\n * @param frame the frame to align to.\r\n * @param hAlign the horizontal alignment.\r\n * @param vAlign the vertical alignment.\r\n *\r\n * @return A rectangle.\r\n */\r\n private Rectangle2D createAlignedRectangle2D(Size2D dimensions,\r\n Rectangle2D frame, HorizontalAlignment hAlign,\r\n VerticalAlignment vAlign) {\r\n double x = Double.NaN;\r\n double y = Double.NaN;\r\n if (hAlign == HorizontalAlignment.LEFT) {\r\n x = frame.getX();\r\n }\r\n else if (hAlign == HorizontalAlignment.CENTER) {\r\n x = frame.getCenterX() - (dimensions.width / 2.0);\r\n }\r\n else if (hAlign == HorizontalAlignment.RIGHT) {\r\n x = frame.getMaxX() - dimensions.width;\r\n }\r\n if (vAlign == VerticalAlignment.TOP) {\r\n y = frame.getY();\r\n }\r\n else if (vAlign == VerticalAlignment.CENTER) {\r\n y = frame.getCenterY() - (dimensions.height / 2.0);\r\n }\r\n else if (vAlign == VerticalAlignment.BOTTOM) {\r\n y = frame.getMaxY() - dimensions.height;\r\n }\r\n\r\n return new Rectangle2D.Double(x, y, dimensions.width,\r\n dimensions.height);\r\n }\r\n\r\n /**\r\n * Draws a title. The title should be drawn at the top, bottom, left or\r\n * right of the specified area, and the area should be updated to reflect\r\n * the amount of space used by the title.\r\n *\r\n * @param t the title (<code>null</code> not permitted).\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param area the chart area, excluding any existing titles\r\n * (<code>null</code> not permitted).\r\n * @param entities a flag that controls whether or not an entity\r\n * collection is returned for the title.\r\n *\r\n * @return An entity collection for the title (possibly <code>null</code>).\r\n */\r\n protected EntityCollection drawTitle(Title t, Graphics2D g2,\r\n Rectangle2D area, boolean entities) {\r\n\r\n ParamChecks.nullNotPermitted(t, \"t\");\r\n ParamChecks.nullNotPermitted(area, \"area\");\r\n Rectangle2D titleArea;\r\n RectangleEdge position = t.getPosition();\r\n double ww = area.getWidth();\r\n if (ww <= 0.0) {\r\n return null;\r\n }\r\n double hh = area.getHeight();\r\n if (hh <= 0.0) {\r\n return null;\r\n }\r\n RectangleConstraint constraint = new RectangleConstraint(ww,\r\n new Range(0.0, ww), LengthConstraintType.RANGE, hh,\r\n new Range(0.0, hh), LengthConstraintType.RANGE);\r\n Object retValue = null;\r\n BlockParams p = new BlockParams();\r\n p.setGenerateEntities(entities);\r\n if (position == RectangleEdge.TOP) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.TOP);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), Math.min(area.getY() + size.height,\r\n area.getMaxY()), area.getWidth(), Math.max(area.getHeight()\r\n - size.height, 0));\r\n }\r\n else if (position == RectangleEdge.BOTTOM) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.BOTTOM);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth(),\r\n area.getHeight() - size.height);\r\n }\r\n else if (position == RectangleEdge.RIGHT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.RIGHT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n\r\n else if (position == RectangleEdge.LEFT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.LEFT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX() + size.width, area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n else {\r\n throw new RuntimeException(\"Unrecognised title position.\");\r\n }\r\n EntityCollection result = null;\r\n if (retValue instanceof EntityBlockResult) {\r\n EntityBlockResult ebr = (EntityBlockResult) retValue;\r\n result = ebr.getEntityCollection();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height) {\r\n return createBufferedImage(width, height, null);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n ChartRenderingInfo info) {\r\n return createBufferedImage(width, height, BufferedImage.TYPE_INT_ARGB,\r\n info);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param imageType the image type.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n int imageType,\r\n ChartRenderingInfo info) {\r\n BufferedImage image = new BufferedImage(width, height, imageType);\r\n Graphics2D g2 = image.createGraphics();\r\n draw(g2, new Rectangle2D.Double(0, 0, width, height), null, info);\r\n g2.dispose();\r\n return image;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param imageWidth the image width.\r\n * @param imageHeight the image height.\r\n * @param drawWidth the width for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param drawHeight the height for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param info optional object for collection chart dimension and entity\r\n * information.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int imageWidth,\r\n int imageHeight,\r\n double drawWidth,\r\n double drawHeight,\r\n ChartRenderingInfo info) {\r\n\r\n BufferedImage image = new BufferedImage(imageWidth, imageHeight,\r\n BufferedImage.TYPE_INT_ARGB);\r\n Graphics2D g2 = image.createGraphics();\r\n double scaleX = imageWidth / drawWidth;\r\n double scaleY = imageHeight / drawHeight;\r\n AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);\r\n g2.transform(st);\r\n draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,\r\n info);\r\n g2.dispose();\r\n return image;\r\n\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the chart. JFreeChart is not a UI component, so\r\n * some other object (for example, {@link ChartPanel}) needs to capture\r\n * the click event and pass it onto the JFreeChart object.\r\n * If you are not using JFreeChart in a client application, then this\r\n * method is not required.\r\n *\r\n * @param x x-coordinate of the click (in Java2D space).\r\n * @param y y-coordinate of the click (in Java2D space).\r\n * @param info contains chart dimension and entity information\r\n * (<code>null</code> not permitted).\r\n */\r\n public void handleClick(int x, int y, ChartRenderingInfo info) {\r\n\r\n // pass the click on to the plot...\r\n // rely on the plot to post a plot change event and redraw the chart...\r\n this.plot.handleClick(x, y, info.getPlotInfo());\r\n\r\n }\r\n\r\n /**\r\n * Registers an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted).\r\n *\r\n * @see #removeChangeListener(ChartChangeListener)\r\n */\r\n public void addChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.add(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted)\r\n *\r\n * @see #addChangeListener(ChartChangeListener)\r\n */\r\n public void removeChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.remove(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a default {@link ChartChangeEvent} to all registered listeners.\r\n * <P>\r\n * This method is for convenience only.\r\n */\r\n public void fireChartChanged() {\r\n ChartChangeEvent event = new ChartChangeEvent(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartChangeEvent event) {\r\n if (this.notify) {\r\n Object[] listeners = this.changeListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartChangeListener.class) {\r\n ((ChartChangeListener) listeners[i + 1]).chartChanged(\r\n event);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Registers an object for notification of progress events relating to the\r\n * chart.\r\n *\r\n * @param listener the object being registered.\r\n *\r\n * @see #removeProgressListener(ChartProgressListener)\r\n */\r\n public void addProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.add(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the object being deregistered.\r\n *\r\n * @see #addProgressListener(ChartProgressListener)\r\n */\r\n public void removeProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.remove(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartProgressEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartProgressEvent event) {\r\n\r\n Object[] listeners = this.progressListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartProgressListener.class) {\r\n ((ChartProgressListener) listeners[i + 1]).chartProgress(event);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Receives notification that a chart title has changed, and passes this\r\n * on to registered listeners.\r\n *\r\n * @param event information about the chart title change.\r\n */\r\n @Override\r\n public void titleChanged(TitleChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Receives notification that the plot has changed, and passes this on to\r\n * registered listeners.\r\n *\r\n * @param event information about the plot change.\r\n */\r\n @Override\r\n public void plotChanged(PlotChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Tests this chart for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof JFreeChart)) {\r\n return false;\r\n }\r\n JFreeChart that = (JFreeChart) obj;\r\n if (!this.renderingHints.equals(that.renderingHints)) {\r\n return false;\r\n }\r\n if (this.borderVisible != that.borderVisible) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.borderStroke, that.borderStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.borderPaint, that.borderPaint)) {\r\n return false;\r\n }\r\n if (!this.padding.equals(that.padding)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.title, that.title)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.subtitles, that.subtitles)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.plot, that.plot)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(\r\n this.backgroundPaint, that.backgroundPaint\r\n )) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundImage,\r\n that.backgroundImage)) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlignment != that.backgroundImageAlignment) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlpha != that.backgroundImageAlpha) {\r\n return false;\r\n }\r\n if (this.notify != that.notify) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.borderStroke, stream);\r\n SerialUtilities.writePaint(this.borderPaint, stream);\r\n SerialUtilities.writePaint(this.backgroundPaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.borderStroke = SerialUtilities.readStroke(stream);\r\n this.borderPaint = SerialUtilities.readPaint(stream);\r\n this.backgroundPaint = SerialUtilities.readPaint(stream);\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n // register as a listener with sub-components...\r\n if (this.title != null) {\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n getSubtitle(i).addChangeListener(this);\r\n }\r\n this.plot.addChangeListener(this);\r\n }\r\n\r\n /**\r\n * Prints information about JFreeChart to standard output.\r\n *\r\n * @param args no arguments are honored.\r\n */\r\n public static void main(String[] args) {\r\n System.out.println(JFreeChart.INFO.toString());\r\n }\r\n\r\n /**\r\n * Clones the object, and takes care of listeners.\r\n * Note: caller shall register its own listeners on cloned graph.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the chart is not cloneable.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n JFreeChart chart = (JFreeChart) super.clone();\r\n\r\n chart.renderingHints = (RenderingHints) this.renderingHints.clone();\r\n // private boolean borderVisible;\r\n // private transient Stroke borderStroke;\r\n // private transient Paint borderPaint;\r\n\r\n if (this.title != null) {\r\n chart.title = (TextTitle) this.title.clone();\r\n chart.title.addChangeListener(chart);\r\n }\r\n\r\n chart.subtitles = new ArrayList();\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n Title subtitle = (Title) getSubtitle(i).clone();\r\n chart.subtitles.add(subtitle);\r\n subtitle.addChangeListener(chart);\r\n }\r\n\r\n if (this.plot != null) {\r\n chart.plot = (Plot) this.plot.clone();\r\n chart.plot.addChangeListener(chart);\r\n }\r\n\r\n chart.progressListeners = new EventListenerList();\r\n chart.changeListeners = new EventListenerList();\r\n return chart;\r\n }\r\n\r\n}\r" }, { "identifier": "LegendItem", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/LegendItem.java", "snippet": "public class LegendItem implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -797214582948827144L;\r\n\r\n /**\r\n * The dataset.\r\n *\r\n * @since 1.0.6\r\n */\r\n private Dataset dataset;\r\n\r\n /**\r\n * The series key.\r\n *\r\n * @since 1.0.6\r\n */\r\n private Comparable seriesKey;\r\n\r\n /** The dataset index. */\r\n private int datasetIndex;\r\n\r\n /** The series index. */\r\n private int series;\r\n\r\n /** The label. */\r\n private String label;\r\n\r\n /**\r\n * The label font ({@code null} is permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n private Font labelFont;\r\n\r\n /**\r\n * The label paint ({@code null} is permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n private transient Paint labelPaint;\r\n\r\n /** The attributed label (if null, fall back to the regular label). */\r\n private transient AttributedString attributedLabel;\r\n\r\n /**\r\n * The description (not currently used - could be displayed as a tool tip).\r\n */\r\n private String description;\r\n\r\n /** The tool tip text. */\r\n private String toolTipText;\r\n\r\n /** The url text. */\r\n private String urlText;\r\n\r\n /** A flag that controls whether or not the shape is visible. */\r\n private boolean shapeVisible;\r\n\r\n /** The shape. */\r\n private transient Shape shape;\r\n\r\n /** A flag that controls whether or not the shape is filled. */\r\n private boolean shapeFilled;\r\n\r\n /** The paint. */\r\n private transient Paint fillPaint;\r\n\r\n /**\r\n * A gradient paint transformer.\r\n *\r\n * @since 1.0.4\r\n */\r\n private GradientPaintTransformer fillPaintTransformer;\r\n\r\n /** A flag that controls whether or not the shape outline is visible. */\r\n private boolean shapeOutlineVisible;\r\n\r\n /** The outline paint. */\r\n private transient Paint outlinePaint;\r\n\r\n /** The outline stroke. */\r\n private transient Stroke outlineStroke;\r\n\r\n /** A flag that controls whether or not the line is visible. */\r\n private boolean lineVisible;\r\n\r\n /** The line. */\r\n private transient Shape line;\r\n\r\n /** The stroke. */\r\n private transient Stroke lineStroke;\r\n\r\n /** The line paint. */\r\n private transient Paint linePaint;\r\n\r\n /**\r\n * The shape must be non-null for a LegendItem - if no shape is required,\r\n * use this.\r\n */\r\n private static final Shape UNUSED_SHAPE = new Line2D.Float();\r\n\r\n /**\r\n * The stroke must be non-null for a LegendItem - if no stroke is required,\r\n * use this.\r\n */\r\n private static final Stroke UNUSED_STROKE = new BasicStroke(0.0f);\r\n\r\n /**\r\n * Creates a legend item with the specified label. The remaining\r\n * attributes take default values.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n *\r\n * @since 1.0.10\r\n */\r\n public LegendItem(String label) {\r\n this(label, Color.black);\r\n }\r\n\r\n /**\r\n * Creates a legend item with the specified label and fill paint. The\r\n * remaining attributes take default values.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n * @param paint the paint ({@code null} not permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public LegendItem(String label, Paint paint) {\r\n this(label, null, null, null, new Rectangle2D.Double(-4.0, -4.0, 8.0,\r\n 8.0), paint);\r\n }\r\n\r\n /**\r\n * Creates a legend item with a filled shape. The shape is not outlined,\r\n * and no line is visible.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n * @param description the description ({@code null} permitted).\r\n * @param toolTipText the tool tip text ({@code null} permitted).\r\n * @param urlText the URL text ({@code null} permitted).\r\n * @param shape the shape ({@code null} not permitted).\r\n * @param fillPaint the paint used to fill the shape ({@code null}\r\n * not permitted).\r\n */\r\n public LegendItem(String label, String description,\r\n String toolTipText, String urlText,\r\n Shape shape, Paint fillPaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ true, shape,\r\n /* shape filled = */ true, fillPaint,\r\n /* shape outlined */ false, Color.black, UNUSED_STROKE,\r\n /* line visible */ false, UNUSED_SHAPE, UNUSED_STROKE,\r\n Color.black);\r\n\r\n }\r\n\r\n /**\r\n * Creates a legend item with a filled and outlined shape.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n * @param description the description ({@code null} permitted).\r\n * @param toolTipText the tool tip text ({@code null} permitted).\r\n * @param urlText the URL text ({@code null} permitted).\r\n * @param shape the shape ({@code null} not permitted).\r\n * @param fillPaint the paint used to fill the shape ({@code null}\r\n * not permitted).\r\n * @param outlineStroke the outline stroke ({@code null} not\r\n * permitted).\r\n * @param outlinePaint the outline paint ({@code null} not\r\n * permitted).\r\n */\r\n public LegendItem(String label, String description, String toolTipText, \r\n String urlText, Shape shape, Paint fillPaint, Stroke outlineStroke, \r\n Paint outlinePaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ true, shape,\r\n /* shape filled = */ true, fillPaint,\r\n /* shape outlined = */ true, outlinePaint, outlineStroke,\r\n /* line visible */ false, UNUSED_SHAPE, UNUSED_STROKE,\r\n Color.black);\r\n\r\n }\r\n\r\n /**\r\n * Creates a legend item using a line.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n * @param description the description ({@code null} permitted).\r\n * @param toolTipText the tool tip text ({@code null} permitted).\r\n * @param urlText the URL text ({@code null} permitted).\r\n * @param line the line ({@code null} not permitted).\r\n * @param lineStroke the line stroke ({@code null} not permitted).\r\n * @param linePaint the line paint ({@code null} not permitted).\r\n */\r\n public LegendItem(String label, String description, String toolTipText, \r\n String urlText, Shape line, Stroke lineStroke, Paint linePaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ false, UNUSED_SHAPE,\r\n /* shape filled = */ false, Color.black,\r\n /* shape outlined = */ false, Color.black, UNUSED_STROKE,\r\n /* line visible = */ true, line, lineStroke, linePaint);\r\n }\r\n\r\n /**\r\n * Creates a new legend item.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n * @param description the description (not currently used,\r\n * <code>null</code> permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text (<code>null</code> permitted).\r\n * @param shapeVisible a flag that controls whether or not the shape is\r\n * displayed.\r\n * @param shape the shape (<code>null</code> permitted).\r\n * @param shapeFilled a flag that controls whether or not the shape is\r\n * filled.\r\n * @param fillPaint the fill paint (<code>null</code> not permitted).\r\n * @param shapeOutlineVisible a flag that controls whether or not the\r\n * shape is outlined.\r\n * @param outlinePaint the outline paint (<code>null</code> not permitted).\r\n * @param outlineStroke the outline stroke (<code>null</code> not\r\n * permitted).\r\n * @param lineVisible a flag that controls whether or not the line is\r\n * visible.\r\n * @param line the line.\r\n * @param lineStroke the stroke (<code>null</code> not permitted).\r\n * @param linePaint the line paint (<code>null</code> not permitted).\r\n */\r\n public LegendItem(String label, String description,\r\n String toolTipText, String urlText,\r\n boolean shapeVisible, Shape shape,\r\n boolean shapeFilled, Paint fillPaint,\r\n boolean shapeOutlineVisible, Paint outlinePaint,\r\n Stroke outlineStroke,\r\n boolean lineVisible, Shape line,\r\n Stroke lineStroke, Paint linePaint) {\r\n\r\n ParamChecks.nullNotPermitted(label, \"label\");\r\n ParamChecks.nullNotPermitted(fillPaint, \"fillPaint\");\r\n ParamChecks.nullNotPermitted(lineStroke, \"lineStroke\");\r\n ParamChecks.nullNotPermitted(outlinePaint, \"outlinePaint\");\r\n ParamChecks.nullNotPermitted(outlineStroke, \"outlineStroke\");\r\n this.label = label;\r\n this.labelPaint = null;\r\n this.attributedLabel = null;\r\n this.description = description;\r\n this.shapeVisible = shapeVisible;\r\n this.shape = shape;\r\n this.shapeFilled = shapeFilled;\r\n this.fillPaint = fillPaint;\r\n this.fillPaintTransformer = new StandardGradientPaintTransformer();\r\n this.shapeOutlineVisible = shapeOutlineVisible;\r\n this.outlinePaint = outlinePaint;\r\n this.outlineStroke = outlineStroke;\r\n this.lineVisible = lineVisible;\r\n this.line = line;\r\n this.lineStroke = lineStroke;\r\n this.linePaint = linePaint;\r\n this.toolTipText = toolTipText;\r\n this.urlText = urlText;\r\n }\r\n\r\n /**\r\n * Creates a legend item with a filled shape. The shape is not outlined,\r\n * and no line is visible.\r\n *\r\n * @param label the label (<code>null</code> not permitted).\r\n * @param description the description (<code>null</code> permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text (<code>null</code> permitted).\r\n * @param shape the shape (<code>null</code> not permitted).\r\n * @param fillPaint the paint used to fill the shape (<code>null</code>\r\n * not permitted).\r\n */\r\n public LegendItem(AttributedString label, String description,\r\n String toolTipText, String urlText,\r\n Shape shape, Paint fillPaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ true, shape,\r\n /* shape filled = */ true, fillPaint,\r\n /* shape outlined = */ false, Color.black, UNUSED_STROKE,\r\n /* line visible = */ false, UNUSED_SHAPE, UNUSED_STROKE,\r\n Color.black);\r\n\r\n }\r\n\r\n /**\r\n * Creates a legend item with a filled and outlined shape.\r\n *\r\n * @param label the label (<code>null</code> not permitted).\r\n * @param description the description (<code>null</code> permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text (<code>null</code> permitted).\r\n * @param shape the shape (<code>null</code> not permitted).\r\n * @param fillPaint the paint used to fill the shape (<code>null</code>\r\n * not permitted).\r\n * @param outlineStroke the outline stroke (<code>null</code> not\r\n * permitted).\r\n * @param outlinePaint the outline paint (<code>null</code> not\r\n * permitted).\r\n */\r\n public LegendItem(AttributedString label, String description,\r\n String toolTipText, String urlText,\r\n Shape shape, Paint fillPaint,\r\n Stroke outlineStroke, Paint outlinePaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ true, shape,\r\n /* shape filled = */ true, fillPaint,\r\n /* shape outlined = */ true, outlinePaint, outlineStroke,\r\n /* line visible = */ false, UNUSED_SHAPE, UNUSED_STROKE,\r\n Color.black);\r\n }\r\n\r\n /**\r\n * Creates a legend item using a line.\r\n *\r\n * @param label the label (<code>null</code> not permitted).\r\n * @param description the description (<code>null</code> permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text (<code>null</code> permitted).\r\n * @param line the line (<code>null</code> not permitted).\r\n * @param lineStroke the line stroke (<code>null</code> not permitted).\r\n * @param linePaint the line paint (<code>null</code> not permitted).\r\n */\r\n public LegendItem(AttributedString label, String description,\r\n String toolTipText, String urlText,\r\n Shape line, Stroke lineStroke, Paint linePaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ false, UNUSED_SHAPE,\r\n /* shape filled = */ false, Color.black,\r\n /* shape outlined = */ false, Color.black, UNUSED_STROKE,\r\n /* line visible = */ true, line, lineStroke, linePaint);\r\n }\r\n\r\n /**\r\n * Creates a new legend item.\r\n *\r\n * @param label the label (<code>null</code> not permitted).\r\n * @param description the description (not currently used,\r\n * <code>null</code> permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text (<code>null</code> permitted).\r\n * @param shapeVisible a flag that controls whether or not the shape is\r\n * displayed.\r\n * @param shape the shape (<code>null</code> permitted).\r\n * @param shapeFilled a flag that controls whether or not the shape is\r\n * filled.\r\n * @param fillPaint the fill paint (<code>null</code> not permitted).\r\n * @param shapeOutlineVisible a flag that controls whether or not the\r\n * shape is outlined.\r\n * @param outlinePaint the outline paint (<code>null</code> not permitted).\r\n * @param outlineStroke the outline stroke (<code>null</code> not\r\n * permitted).\r\n * @param lineVisible a flag that controls whether or not the line is\r\n * visible.\r\n * @param line the line (<code>null</code> not permitted).\r\n * @param lineStroke the stroke (<code>null</code> not permitted).\r\n * @param linePaint the line paint (<code>null</code> not permitted).\r\n */\r\n public LegendItem(AttributedString label, String description,\r\n String toolTipText, String urlText,\r\n boolean shapeVisible, Shape shape,\r\n boolean shapeFilled, Paint fillPaint,\r\n boolean shapeOutlineVisible, Paint outlinePaint,\r\n Stroke outlineStroke,\r\n boolean lineVisible, Shape line, Stroke lineStroke,\r\n Paint linePaint) {\r\n\r\n ParamChecks.nullNotPermitted(label, \"label\");\r\n ParamChecks.nullNotPermitted(fillPaint, \"fillPaint\");\r\n ParamChecks.nullNotPermitted(lineStroke, \"lineStroke\");\r\n ParamChecks.nullNotPermitted(line, \"line\");\r\n ParamChecks.nullNotPermitted(linePaint, \"linePaint\");\r\n ParamChecks.nullNotPermitted(outlinePaint, \"outlinePaint\");\r\n ParamChecks.nullNotPermitted(outlineStroke, \"outlineStroke\");\r\n this.label = characterIteratorToString(label.getIterator());\r\n this.attributedLabel = label;\r\n this.description = description;\r\n this.shapeVisible = shapeVisible;\r\n this.shape = shape;\r\n this.shapeFilled = shapeFilled;\r\n this.fillPaint = fillPaint;\r\n this.fillPaintTransformer = new StandardGradientPaintTransformer();\r\n this.shapeOutlineVisible = shapeOutlineVisible;\r\n this.outlinePaint = outlinePaint;\r\n this.outlineStroke = outlineStroke;\r\n this.lineVisible = lineVisible;\r\n this.line = line;\r\n this.lineStroke = lineStroke;\r\n this.linePaint = linePaint;\r\n this.toolTipText = toolTipText;\r\n this.urlText = urlText;\r\n }\r\n\r\n /**\r\n * Returns a string containing the characters from the given iterator.\r\n *\r\n * @param iterator the iterator (<code>null</code> not permitted).\r\n *\r\n * @return A string.\r\n */\r\n private String characterIteratorToString(CharacterIterator iterator) {\r\n int endIndex = iterator.getEndIndex();\r\n int beginIndex = iterator.getBeginIndex();\r\n int count = endIndex - beginIndex;\r\n if (count <= 0) {\r\n return \"\";\r\n }\r\n char[] chars = new char[count];\r\n int i = 0;\r\n char c = iterator.first();\r\n while (c != CharacterIterator.DONE) {\r\n chars[i] = c;\r\n i++;\r\n c = iterator.next();\r\n }\r\n return new String(chars);\r\n }\r\n\r\n /**\r\n * Returns the dataset.\r\n *\r\n * @return The dataset.\r\n *\r\n * @since 1.0.6\r\n *\r\n * @see #setDatasetIndex(int)\r\n */\r\n public Dataset getDataset() {\r\n return this.dataset;\r\n }\r\n\r\n /**\r\n * Sets the dataset.\r\n *\r\n * @param dataset the dataset.\r\n *\r\n * @since 1.0.6\r\n */\r\n public void setDataset(Dataset dataset) {\r\n this.dataset = dataset;\r\n }\r\n\r\n /**\r\n * Returns the dataset index for this legend item.\r\n *\r\n * @return The dataset index.\r\n *\r\n * @since 1.0.2\r\n *\r\n * @see #setDatasetIndex(int)\r\n * @see #getDataset()\r\n */\r\n public int getDatasetIndex() {\r\n return this.datasetIndex;\r\n }\r\n\r\n /**\r\n * Sets the dataset index for this legend item.\r\n *\r\n * @param index the index.\r\n *\r\n * @since 1.0.2\r\n *\r\n * @see #getDatasetIndex()\r\n */\r\n public void setDatasetIndex(int index) {\r\n this.datasetIndex = index;\r\n }\r\n\r\n /**\r\n * Returns the series key.\r\n *\r\n * @return The series key.\r\n *\r\n * @since 1.0.6\r\n *\r\n * @see #setSeriesKey(Comparable)\r\n */\r\n public Comparable getSeriesKey() {\r\n return this.seriesKey;\r\n }\r\n\r\n /**\r\n * Sets the series key.\r\n *\r\n * @param key the series key.\r\n *\r\n * @since 1.0.6\r\n */\r\n public void setSeriesKey(Comparable key) {\r\n this.seriesKey = key;\r\n }\r\n\r\n /**\r\n * Returns the series index for this legend item.\r\n *\r\n * @return The series index.\r\n *\r\n * @since 1.0.2\r\n */\r\n public int getSeriesIndex() {\r\n return this.series;\r\n }\r\n\r\n /**\r\n * Sets the series index for this legend item.\r\n *\r\n * @param index the index.\r\n *\r\n * @since 1.0.2\r\n */\r\n public void setSeriesIndex(int index) {\r\n this.series = index;\r\n }\r\n\r\n /**\r\n * Returns the label.\r\n *\r\n * @return The label (never <code>null</code>).\r\n */\r\n public String getLabel() {\r\n return this.label;\r\n }\r\n\r\n /**\r\n * Returns the label font.\r\n *\r\n * @return The label font (possibly <code>null</code>).\r\n *\r\n * @since 1.0.11\r\n */\r\n public Font getLabelFont() {\r\n return this.labelFont;\r\n }\r\n\r\n /**\r\n * Sets the label font.\r\n *\r\n * @param font the font (<code>null</code> permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setLabelFont(Font font) {\r\n this.labelFont = font;\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the label.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @since 1.0.11\r\n */\r\n public Paint getLabelPaint() {\r\n return this.labelPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the label.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setLabelPaint(Paint paint) {\r\n this.labelPaint = paint;\r\n }\r\n\r\n /**\r\n * Returns the attributed label.\r\n *\r\n * @return The attributed label (possibly <code>null</code>).\r\n */\r\n public AttributedString getAttributedLabel() {\r\n return this.attributedLabel;\r\n }\r\n\r\n /**\r\n * Returns the description for the legend item.\r\n *\r\n * @return The description (possibly <code>null</code>).\r\n *\r\n * @see #setDescription(java.lang.String) \r\n */\r\n public String getDescription() {\r\n return this.description;\r\n }\r\n\r\n /**\r\n * Sets the description for this legend item.\r\n *\r\n * @param text the description (<code>null</code> permitted).\r\n *\r\n * @see #getDescription()\r\n * @since 1.0.14\r\n */\r\n public void setDescription(String text) {\r\n this.description = text;\r\n }\r\n\r\n /**\r\n * Returns the tool tip text.\r\n *\r\n * @return The tool tip text (possibly <code>null</code>).\r\n *\r\n * @see #setToolTipText(java.lang.String) \r\n */\r\n public String getToolTipText() {\r\n return this.toolTipText;\r\n }\r\n\r\n /**\r\n * Sets the tool tip text for this legend item.\r\n *\r\n * @param text the text (<code>null</code> permitted).\r\n *\r\n * @see #getToolTipText()\r\n * @since 1.0.14\r\n */\r\n public void setToolTipText(String text) {\r\n this.toolTipText = text;\r\n }\r\n\r\n /**\r\n * Returns the URL text.\r\n *\r\n * @return The URL text (possibly <code>null</code>).\r\n *\r\n * @see #setURLText(java.lang.String) \r\n */\r\n public String getURLText() {\r\n return this.urlText;\r\n }\r\n\r\n /**\r\n * Sets the URL text.\r\n *\r\n * @param text the text (<code>null</code> permitted).\r\n *\r\n * @see #getURLText()\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setURLText(String text) {\r\n this.urlText = text;\r\n }\r\n\r\n /**\r\n * Returns a flag that indicates whether or not the shape is visible.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setShapeVisible(boolean)\r\n */\r\n public boolean isShapeVisible() {\r\n return this.shapeVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the shape is visible.\r\n *\r\n * @param visible the new flag value.\r\n *\r\n * @see #isShapeVisible()\r\n * @see #isLineVisible()\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setShapeVisible(boolean visible) {\r\n this.shapeVisible = visible;\r\n }\r\n\r\n /**\r\n * Returns the shape used to label the series represented by this legend\r\n * item.\r\n *\r\n * @return The shape (never <code>null</code>).\r\n *\r\n * @see #setShape(java.awt.Shape) \r\n */\r\n public Shape getShape() {\r\n return this.shape;\r\n }\r\n\r\n /**\r\n * Sets the shape for the legend item.\r\n *\r\n * @param shape the shape (<code>null</code> not permitted).\r\n *\r\n * @see #getShape()\r\n * @since 1.0.14\r\n */\r\n public void setShape(Shape shape) {\r\n ParamChecks.nullNotPermitted(shape, \"shape\");\r\n this.shape = shape;\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not the shape is filled.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean isShapeFilled() {\r\n return this.shapeFilled;\r\n }\r\n\r\n /**\r\n * Returns the fill paint.\r\n *\r\n * @return The fill paint (never <code>null</code>).\r\n */\r\n public Paint getFillPaint() {\r\n return this.fillPaint;\r\n }\r\n\r\n /**\r\n * Sets the fill paint.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setFillPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.fillPaint = paint;\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the shape outline\r\n * is visible.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean isShapeOutlineVisible() {\r\n return this.shapeOutlineVisible;\r\n }\r\n\r\n /**\r\n * Returns the line stroke for the series.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n */\r\n public Stroke getLineStroke() {\r\n return this.lineStroke;\r\n }\r\n \r\n /**\r\n * Sets the line stroke.\r\n * \r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n * \r\n * @since 1.0.18\r\n */\r\n public void setLineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.lineStroke = stroke;\r\n }\r\n\r\n /**\r\n * Returns the paint used for lines.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n */\r\n public Paint getLinePaint() {\r\n return this.linePaint;\r\n }\r\n\r\n /**\r\n * Sets the line paint.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setLinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.linePaint = paint;\r\n }\r\n\r\n /**\r\n * Returns the outline paint.\r\n *\r\n * @return The outline paint (never <code>null</code>).\r\n */\r\n public Paint getOutlinePaint() {\r\n return this.outlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the outline paint.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setOutlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.outlinePaint = paint;\r\n }\r\n\r\n /**\r\n * Returns the outline stroke.\r\n *\r\n * @return The outline stroke (never <code>null</code>).\r\n *\r\n * @see #setOutlineStroke(java.awt.Stroke) \r\n */\r\n public Stroke getOutlineStroke() {\r\n return this.outlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the outline stroke.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getOutlineStroke()\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setOutlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.outlineStroke = stroke;\r\n }\r\n\r\n /**\r\n * Returns a flag that indicates whether or not the line is visible.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setLineVisible(boolean) \r\n */\r\n public boolean isLineVisible() {\r\n return this.lineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the line shape is visible for\r\n * this legend item.\r\n *\r\n * @param visible the new flag value.\r\n *\r\n * @see #isLineVisible()\r\n * @since 1.0.14\r\n */\r\n public void setLineVisible(boolean visible) {\r\n this.lineVisible = visible;\r\n }\r\n\r\n /**\r\n * Returns the line.\r\n *\r\n * @return The line (never <code>null</code>).\r\n *\r\n * @see #setLine(java.awt.Shape)\r\n * @see #isLineVisible() \r\n */\r\n public Shape getLine() {\r\n return this.line;\r\n }\r\n\r\n /**\r\n * Sets the line.\r\n *\r\n * @param line the line (<code>null</code> not permitted).\r\n *\r\n * @see #getLine()\r\n * @since 1.0.14\r\n */\r\n public void setLine(Shape line) {\r\n ParamChecks.nullNotPermitted(line, \"line\");\r\n this.line = line;\r\n }\r\n\r\n /**\r\n * Returns the transformer used when the fill paint is an instance of\r\n * <code>GradientPaint</code>.\r\n *\r\n * @return The transformer (never <code>null</code>).\r\n *\r\n * @since 1.0.4\r\n *\r\n * @see #setFillPaintTransformer(GradientPaintTransformer)\r\n */\r\n public GradientPaintTransformer getFillPaintTransformer() {\r\n return this.fillPaintTransformer;\r\n }\r\n\r\n /**\r\n * Sets the transformer used when the fill paint is an instance of\r\n * <code>GradientPaint</code>.\r\n *\r\n * @param transformer the transformer (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.4\r\n *\r\n * @see #getFillPaintTransformer()\r\n */\r\n public void setFillPaintTransformer(GradientPaintTransformer transformer) {\r\n ParamChecks.nullNotPermitted(transformer, \"transformer\");\r\n this.fillPaintTransformer = transformer;\r\n }\r\n\r\n /**\r\n * Tests this item for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof LegendItem)) {\r\n return false;\r\n }\r\n LegendItem that = (LegendItem) obj;\r\n if (this.datasetIndex != that.datasetIndex) {\r\n return false;\r\n }\r\n if (this.series != that.series) {\r\n return false;\r\n }\r\n if (!this.label.equals(that.label)) {\r\n return false;\r\n }\r\n if (!AttributedStringUtilities.equal(this.attributedLabel,\r\n that.attributedLabel)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.description, that.description)) {\r\n return false;\r\n }\r\n if (this.shapeVisible != that.shapeVisible) {\r\n return false;\r\n }\r\n if (!ShapeUtilities.equal(this.shape, that.shape)) {\r\n return false;\r\n }\r\n if (this.shapeFilled != that.shapeFilled) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.fillPaint, that.fillPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.fillPaintTransformer,\r\n that.fillPaintTransformer)) {\r\n return false;\r\n }\r\n if (this.shapeOutlineVisible != that.shapeOutlineVisible) {\r\n return false;\r\n }\r\n if (!this.outlineStroke.equals(that.outlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) {\r\n return false;\r\n }\r\n if (!this.lineVisible == that.lineVisible) {\r\n return false;\r\n }\r\n if (!ShapeUtilities.equal(this.line, that.line)) {\r\n return false;\r\n }\r\n if (!this.lineStroke.equals(that.lineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.linePaint, that.linePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.labelFont, that.labelFont)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.labelPaint, that.labelPaint)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns an independent copy of this object (except that the clone will\r\n * still reference the same dataset as the original\r\n * <code>LegendItem</code>).\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the legend item cannot be cloned.\r\n *\r\n * @since 1.0.10\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n LegendItem clone = (LegendItem) super.clone();\r\n if (this.seriesKey instanceof PublicCloneable) {\r\n PublicCloneable pc = (PublicCloneable) this.seriesKey;\r\n clone.seriesKey = (Comparable) pc.clone();\r\n }\r\n // FIXME: Clone the attributed string if it is not null\r\n clone.shape = ShapeUtilities.clone(this.shape);\r\n if (this.fillPaintTransformer instanceof PublicCloneable) {\r\n PublicCloneable pc = (PublicCloneable) this.fillPaintTransformer;\r\n clone.fillPaintTransformer = (GradientPaintTransformer) pc.clone();\r\n\r\n }\r\n clone.line = ShapeUtilities.clone(this.line);\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream (<code>null</code> not permitted).\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeAttributedString(this.attributedLabel, stream);\r\n SerialUtilities.writeShape(this.shape, stream);\r\n SerialUtilities.writePaint(this.fillPaint, stream);\r\n SerialUtilities.writeStroke(this.outlineStroke, stream);\r\n SerialUtilities.writePaint(this.outlinePaint, stream);\r\n SerialUtilities.writeShape(this.line, stream);\r\n SerialUtilities.writeStroke(this.lineStroke, stream);\r\n SerialUtilities.writePaint(this.linePaint, stream);\r\n SerialUtilities.writePaint(this.labelPaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream (<code>null</code> not permitted).\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.attributedLabel = SerialUtilities.readAttributedString(stream);\r\n this.shape = SerialUtilities.readShape(stream);\r\n this.fillPaint = SerialUtilities.readPaint(stream);\r\n this.outlineStroke = SerialUtilities.readStroke(stream);\r\n this.outlinePaint = SerialUtilities.readPaint(stream);\r\n this.line = SerialUtilities.readShape(stream);\r\n this.lineStroke = SerialUtilities.readStroke(stream);\r\n this.linePaint = SerialUtilities.readPaint(stream);\r\n this.labelPaint = SerialUtilities.readPaint(stream);\r\n }\r\n\r\n}\r" }, { "identifier": "TestUtilities", "path": "lib/jfreechart-1.0.19/tests/org/jfree/chart/TestUtilities.java", "snippet": "public class TestUtilities {\n\n /**\n * Returns <code>true</code> if the collections contains any object that\n * is an instance of the specified class, and <code>false</code> otherwise.\n *\n * @param collection the collection.\n * @param c the class.\n *\n * @return A boolean.\n */\n public static boolean containsInstanceOf(Collection collection, Class c) {\n Iterator iterator = collection.iterator();\n while (iterator.hasNext()) {\n Object obj = iterator.next();\n if (obj != null && obj.getClass().equals(c)) {\n return true;\n }\n }\n return false;\n }\n\n public static Object serialised(Object original) {\n Object result = null;\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n ObjectOutput out;\n try {\n out = new ObjectOutputStream(buffer);\n out.writeObject(original);\n out.close();\n ObjectInput in = new ObjectInputStream(\n new ByteArrayInputStream(buffer.toByteArray()));\n result = in.readObject();\n in.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n return result;\n }\n \n}" }, { "identifier": "NumberAxis", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/axis/NumberAxis.java", "snippet": "public class NumberAxis extends ValueAxis implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 2805933088476185789L;\r\n\r\n /** The default value for the autoRangeIncludesZero flag. */\r\n public static final boolean DEFAULT_AUTO_RANGE_INCLUDES_ZERO = true;\r\n\r\n /** The default value for the autoRangeStickyZero flag. */\r\n public static final boolean DEFAULT_AUTO_RANGE_STICKY_ZERO = true;\r\n\r\n /** The default tick unit. */\r\n public static final NumberTickUnit DEFAULT_TICK_UNIT = new NumberTickUnit(\r\n 1.0, new DecimalFormat(\"0\"));\r\n\r\n /** The default setting for the vertical tick labels flag. */\r\n public static final boolean DEFAULT_VERTICAL_TICK_LABELS = false;\r\n\r\n /**\r\n * The range type (can be used to force the axis to display only positive\r\n * values or only negative values).\r\n */\r\n private RangeType rangeType;\r\n\r\n /**\r\n * A flag that affects the axis range when the range is determined\r\n * automatically. If the auto range does NOT include zero and this flag\r\n * is TRUE, then the range is changed to include zero.\r\n */\r\n private boolean autoRangeIncludesZero;\r\n\r\n /**\r\n * A flag that affects the size of the margins added to the axis range when\r\n * the range is determined automatically. If the value 0 falls within the\r\n * margin and this flag is TRUE, then the margin is truncated at zero.\r\n */\r\n private boolean autoRangeStickyZero;\r\n\r\n /** The tick unit for the axis. */\r\n private NumberTickUnit tickUnit;\r\n\r\n /** The override number format. */\r\n private NumberFormat numberFormatOverride;\r\n\r\n /** An optional band for marking regions on the axis. */\r\n private MarkerAxisBand markerBand;\r\n\r\n /**\r\n * Default constructor.\r\n */\r\n public NumberAxis() {\r\n this(null);\r\n }\r\n\r\n /**\r\n * Constructs a number axis, using default values where necessary.\r\n *\r\n * @param label the axis label (<code>null</code> permitted).\r\n */\r\n public NumberAxis(String label) {\r\n super(label, NumberAxis.createStandardTickUnits());\r\n this.rangeType = RangeType.FULL;\r\n this.autoRangeIncludesZero = DEFAULT_AUTO_RANGE_INCLUDES_ZERO;\r\n this.autoRangeStickyZero = DEFAULT_AUTO_RANGE_STICKY_ZERO;\r\n this.tickUnit = DEFAULT_TICK_UNIT;\r\n this.numberFormatOverride = null;\r\n this.markerBand = null;\r\n }\r\n\r\n /**\r\n * Returns the axis range type.\r\n *\r\n * @return The axis range type (never <code>null</code>).\r\n *\r\n * @see #setRangeType(RangeType)\r\n */\r\n public RangeType getRangeType() {\r\n return this.rangeType;\r\n }\r\n\r\n /**\r\n * Sets the axis range type.\r\n *\r\n * @param rangeType the range type (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeType()\r\n */\r\n public void setRangeType(RangeType rangeType) {\r\n ParamChecks.nullNotPermitted(rangeType, \"rangeType\");\r\n this.rangeType = rangeType;\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the flag that indicates whether or not the automatic axis range\r\n * (if indeed it is determined automatically) is forced to include zero.\r\n *\r\n * @return The flag.\r\n */\r\n public boolean getAutoRangeIncludesZero() {\r\n return this.autoRangeIncludesZero;\r\n }\r\n\r\n /**\r\n * Sets the flag that indicates whether or not the axis range, if\r\n * automatically calculated, is forced to include zero.\r\n * <p>\r\n * If the flag is changed to <code>true</code>, the axis range is\r\n * recalculated.\r\n * <p>\r\n * Any change to the flag will trigger an {@link AxisChangeEvent}.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #getAutoRangeIncludesZero()\r\n */\r\n public void setAutoRangeIncludesZero(boolean flag) {\r\n if (this.autoRangeIncludesZero != flag) {\r\n this.autoRangeIncludesZero = flag;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag that affects the auto-range when zero falls outside the\r\n * data range but inside the margins defined for the axis.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAutoRangeStickyZero(boolean)\r\n */\r\n public boolean getAutoRangeStickyZero() {\r\n return this.autoRangeStickyZero;\r\n }\r\n\r\n /**\r\n * Sets a flag that affects the auto-range when zero falls outside the data\r\n * range but inside the margins defined for the axis.\r\n *\r\n * @param flag the new flag.\r\n *\r\n * @see #getAutoRangeStickyZero()\r\n */\r\n public void setAutoRangeStickyZero(boolean flag) {\r\n if (this.autoRangeStickyZero != flag) {\r\n this.autoRangeStickyZero = flag;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the tick unit for the axis.\r\n * <p>\r\n * Note: if the <code>autoTickUnitSelection</code> flag is\r\n * <code>true</code> the tick unit may be changed while the axis is being\r\n * drawn, so in that case the return value from this method may be\r\n * irrelevant if the method is called before the axis has been drawn.\r\n *\r\n * @return The tick unit for the axis.\r\n *\r\n * @see #setTickUnit(NumberTickUnit)\r\n * @see ValueAxis#isAutoTickUnitSelection()\r\n */\r\n public NumberTickUnit getTickUnit() {\r\n return this.tickUnit;\r\n }\r\n\r\n /**\r\n * Sets the tick unit for the axis and sends an {@link AxisChangeEvent} to\r\n * all registered listeners. A side effect of calling this method is that\r\n * the \"auto-select\" feature for tick units is switched off (you can\r\n * restore it using the {@link ValueAxis#setAutoTickUnitSelection(boolean)}\r\n * method).\r\n *\r\n * @param unit the new tick unit (<code>null</code> not permitted).\r\n *\r\n * @see #getTickUnit()\r\n * @see #setTickUnit(NumberTickUnit, boolean, boolean)\r\n */\r\n public void setTickUnit(NumberTickUnit unit) {\r\n // defer argument checking...\r\n setTickUnit(unit, true, true);\r\n }\r\n\r\n /**\r\n * Sets the tick unit for the axis and, if requested, sends an\r\n * {@link AxisChangeEvent} to all registered listeners. In addition, an\r\n * option is provided to turn off the \"auto-select\" feature for tick units\r\n * (you can restore it using the\r\n * {@link ValueAxis#setAutoTickUnitSelection(boolean)} method).\r\n *\r\n * @param unit the new tick unit (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n * @param turnOffAutoSelect turn off the auto-tick selection?\r\n */\r\n public void setTickUnit(NumberTickUnit unit, boolean notify,\r\n boolean turnOffAutoSelect) {\r\n\r\n ParamChecks.nullNotPermitted(unit, \"unit\");\r\n this.tickUnit = unit;\r\n if (turnOffAutoSelect) {\r\n setAutoTickUnitSelection(false, false);\r\n }\r\n if (notify) {\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the number format override. If this is non-null, then it will\r\n * be used to format the numbers on the axis.\r\n *\r\n * @return The number formatter (possibly <code>null</code>).\r\n *\r\n * @see #setNumberFormatOverride(NumberFormat)\r\n */\r\n public NumberFormat getNumberFormatOverride() {\r\n return this.numberFormatOverride;\r\n }\r\n\r\n /**\r\n * Sets the number format override. If this is non-null, then it will be\r\n * used to format the numbers on the axis.\r\n *\r\n * @param formatter the number formatter (<code>null</code> permitted).\r\n *\r\n * @see #getNumberFormatOverride()\r\n */\r\n public void setNumberFormatOverride(NumberFormat formatter) {\r\n this.numberFormatOverride = formatter;\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the (optional) marker band for the axis.\r\n *\r\n * @return The marker band (possibly <code>null</code>).\r\n *\r\n * @see #setMarkerBand(MarkerAxisBand)\r\n */\r\n public MarkerAxisBand getMarkerBand() {\r\n return this.markerBand;\r\n }\r\n\r\n /**\r\n * Sets the marker band for the axis.\r\n * <P>\r\n * The marker band is optional, leave it set to <code>null</code> if you\r\n * don't require it.\r\n *\r\n * @param band the new band (<code>null</code> permitted).\r\n *\r\n * @see #getMarkerBand()\r\n */\r\n public void setMarkerBand(MarkerAxisBand band) {\r\n this.markerBand = band;\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Configures the axis to work with the specified plot. If the axis has\r\n * auto-scaling, then sets the maximum and minimum values.\r\n */\r\n @Override\r\n public void configure() {\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n }\r\n\r\n /**\r\n * Rescales the axis to ensure that all data is visible.\r\n */\r\n @Override\r\n protected void autoAdjustRange() {\r\n\r\n Plot plot = getPlot();\r\n if (plot == null) {\r\n return; // no plot, no data\r\n }\r\n\r\n if (plot instanceof ValueAxisPlot) {\r\n ValueAxisPlot vap = (ValueAxisPlot) plot;\r\n\r\n Range r = vap.getDataRange(this);\r\n if (r == null) {\r\n r = getDefaultAutoRange();\r\n }\r\n\r\n double upper = r.getUpperBound();\r\n double lower = r.getLowerBound();\r\n if (this.rangeType == RangeType.POSITIVE) {\r\n lower = Math.max(0.0, lower);\r\n upper = Math.max(0.0, upper);\r\n }\r\n else if (this.rangeType == RangeType.NEGATIVE) {\r\n lower = Math.min(0.0, lower);\r\n upper = Math.min(0.0, upper);\r\n }\r\n\r\n if (getAutoRangeIncludesZero()) {\r\n lower = Math.min(lower, 0.0);\r\n upper = Math.max(upper, 0.0);\r\n }\r\n double range = upper - lower;\r\n\r\n // if fixed auto range, then derive lower bound...\r\n double fixedAutoRange = getFixedAutoRange();\r\n if (fixedAutoRange > 0.0) {\r\n lower = upper - fixedAutoRange;\r\n }\r\n else {\r\n // ensure the autorange is at least <minRange> in size...\r\n double minRange = getAutoRangeMinimumSize();\r\n if (range < minRange) {\r\n double expand = (minRange - range) / 2;\r\n upper = upper + expand;\r\n lower = lower - expand;\r\n if (lower == upper) { // see bug report 1549218\r\n double adjust = Math.abs(lower) / 10.0;\r\n lower = lower - adjust;\r\n upper = upper + adjust;\r\n }\r\n if (this.rangeType == RangeType.POSITIVE) {\r\n if (lower < 0.0) {\r\n upper = upper - lower;\r\n lower = 0.0;\r\n }\r\n }\r\n else if (this.rangeType == RangeType.NEGATIVE) {\r\n if (upper > 0.0) {\r\n lower = lower - upper;\r\n upper = 0.0;\r\n }\r\n }\r\n }\r\n\r\n if (getAutoRangeStickyZero()) {\r\n if (upper <= 0.0) {\r\n upper = Math.min(0.0, upper + getUpperMargin() * range);\r\n }\r\n else {\r\n upper = upper + getUpperMargin() * range;\r\n }\r\n if (lower >= 0.0) {\r\n lower = Math.max(0.0, lower - getLowerMargin() * range);\r\n }\r\n else {\r\n lower = lower - getLowerMargin() * range;\r\n }\r\n }\r\n else {\r\n upper = upper + getUpperMargin() * range;\r\n lower = lower - getLowerMargin() * range;\r\n }\r\n }\r\n\r\n setRange(new Range(lower, upper), false, false);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Converts a data value to a coordinate in Java2D space, assuming that the\r\n * axis runs along one edge of the specified dataArea.\r\n * <p>\r\n * Note that it is possible for the coordinate to fall outside the plotArea.\r\n *\r\n * @param value the data value.\r\n * @param area the area for plotting the data.\r\n * @param edge the axis location.\r\n *\r\n * @return The Java2D coordinate.\r\n *\r\n * @see #java2DToValue(double, Rectangle2D, RectangleEdge)\r\n */\r\n @Override\r\n public double valueToJava2D(double value, Rectangle2D area,\r\n RectangleEdge edge) {\r\n\r\n Range range = getRange();\r\n double axisMin = range.getLowerBound();\r\n double axisMax = range.getUpperBound();\r\n\r\n double min = 0.0;\r\n double max = 0.0;\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n min = area.getX();\r\n max = area.getMaxX();\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n max = area.getMinY();\r\n min = area.getMaxY();\r\n }\r\n if (isInverted()) {\r\n return max\r\n - ((value - axisMin) / (axisMax - axisMin)) * (max - min);\r\n }\r\n else {\r\n return min\r\n + ((value - axisMin) / (axisMax - axisMin)) * (max - min);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Converts a coordinate in Java2D space to the corresponding data value,\r\n * assuming that the axis runs along one edge of the specified dataArea.\r\n *\r\n * @param java2DValue the coordinate in Java2D space.\r\n * @param area the area in which the data is plotted.\r\n * @param edge the location.\r\n *\r\n * @return The data value.\r\n *\r\n * @see #valueToJava2D(double, Rectangle2D, RectangleEdge)\r\n */\r\n @Override\r\n public double java2DToValue(double java2DValue, Rectangle2D area,\r\n RectangleEdge edge) {\r\n\r\n Range range = getRange();\r\n double axisMin = range.getLowerBound();\r\n double axisMax = range.getUpperBound();\r\n\r\n double min = 0.0;\r\n double max = 0.0;\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n min = area.getX();\r\n max = area.getMaxX();\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n min = area.getMaxY();\r\n max = area.getY();\r\n }\r\n if (isInverted()) {\r\n return axisMax\r\n - (java2DValue - min) / (max - min) * (axisMax - axisMin);\r\n }\r\n else {\r\n return axisMin\r\n + (java2DValue - min) / (max - min) * (axisMax - axisMin);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Calculates the value of the lowest visible tick on the axis.\r\n *\r\n * @return The value of the lowest visible tick on the axis.\r\n *\r\n * @see #calculateHighestVisibleTickValue()\r\n */\r\n protected double calculateLowestVisibleTickValue() {\r\n double unit = getTickUnit().getSize();\r\n double index = Math.ceil(getRange().getLowerBound() / unit);\r\n return index * unit;\r\n }\r\n\r\n /**\r\n * Calculates the value of the highest visible tick on the axis.\r\n *\r\n * @return The value of the highest visible tick on the axis.\r\n *\r\n * @see #calculateLowestVisibleTickValue()\r\n */\r\n protected double calculateHighestVisibleTickValue() {\r\n double unit = getTickUnit().getSize();\r\n double index = Math.floor(getRange().getUpperBound() / unit);\r\n return index * unit;\r\n }\r\n\r\n /**\r\n * Calculates the number of visible ticks.\r\n *\r\n * @return The number of visible ticks on the axis.\r\n */\r\n protected int calculateVisibleTickCount() {\r\n double unit = getTickUnit().getSize();\r\n Range range = getRange();\r\n return (int) (Math.floor(range.getUpperBound() / unit)\r\n - Math.ceil(range.getLowerBound() / unit) + 1);\r\n }\r\n\r\n /**\r\n * Draws the axis on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param cursor the cursor location.\r\n * @param plotArea the area within which the axes and data should be drawn\r\n * (<code>null</code> not permitted).\r\n * @param dataArea the area within which the data should be drawn\r\n * (<code>null</code> not permitted).\r\n * @param edge the location of the axis (<code>null</code> not permitted).\r\n * @param plotState collects information about the plot\r\n * (<code>null</code> permitted).\r\n *\r\n * @return The axis state (never <code>null</code>).\r\n */\r\n @Override\r\n public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,\r\n Rectangle2D dataArea, RectangleEdge edge,\r\n PlotRenderingInfo plotState) {\r\n\r\n AxisState state;\r\n // if the axis is not visible, don't draw it...\r\n if (!isVisible()) {\r\n state = new AxisState(cursor);\r\n // even though the axis is not visible, we need ticks for the\r\n // gridlines...\r\n List ticks = refreshTicks(g2, state, dataArea, edge);\r\n state.setTicks(ticks);\r\n return state;\r\n }\r\n\r\n // draw the tick marks and labels...\r\n state = drawTickMarksAndLabels(g2, cursor, plotArea, dataArea, edge);\r\n\r\n if (getAttributedLabel() != null) {\r\n state = drawAttributedLabel(getAttributedLabel(), g2, plotArea, \r\n dataArea, edge, state);\r\n \r\n } else {\r\n state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);\r\n }\r\n createAndAddEntity(cursor, state, dataArea, edge, plotState);\r\n return state;\r\n\r\n }\r\n\r\n /**\r\n * Creates the standard tick units.\r\n * <P>\r\n * If you don't like these defaults, create your own instance of TickUnits\r\n * and then pass it to the setStandardTickUnits() method in the\r\n * NumberAxis class.\r\n *\r\n * @return The standard tick units.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n * @see #createIntegerTickUnits()\r\n */\r\n public static TickUnitSource createStandardTickUnits() {\r\n return new NumberTickUnitSource();\r\n }\r\n\r\n /**\r\n * Returns a collection of tick units for integer values.\r\n *\r\n * @return A collection of tick units for integer values.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n * @see #createStandardTickUnits()\r\n */\r\n public static TickUnitSource createIntegerTickUnits() {\r\n return new NumberTickUnitSource(true);\r\n }\r\n\r\n /**\r\n * Creates a collection of standard tick units. The supplied locale is\r\n * used to create the number formatter (a localised instance of\r\n * <code>NumberFormat</code>).\r\n * <P>\r\n * If you don't like these defaults, create your own instance of\r\n * {@link TickUnits} and then pass it to the\r\n * <code>setStandardTickUnits()</code> method.\r\n *\r\n * @param locale the locale.\r\n *\r\n * @return A tick unit collection.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n */\r\n public static TickUnitSource createStandardTickUnits(Locale locale) {\r\n NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);\r\n return new NumberTickUnitSource(false, numberFormat);\r\n }\r\n\r\n /**\r\n * Returns a collection of tick units for integer values.\r\n * Uses a given Locale to create the DecimalFormats.\r\n *\r\n * @param locale the locale to use to represent Numbers.\r\n *\r\n * @return A collection of tick units for integer values.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n */\r\n public static TickUnitSource createIntegerTickUnits(Locale locale) {\r\n NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);\r\n return new NumberTickUnitSource(true, numberFormat);\r\n }\r\n\r\n /**\r\n * Estimates the maximum tick label height.\r\n *\r\n * @param g2 the graphics device.\r\n *\r\n * @return The maximum height.\r\n */\r\n protected double estimateMaximumTickLabelHeight(Graphics2D g2) {\r\n RectangleInsets tickLabelInsets = getTickLabelInsets();\r\n double result = tickLabelInsets.getTop() + tickLabelInsets.getBottom();\r\n\r\n Font tickLabelFont = getTickLabelFont();\r\n FontRenderContext frc = g2.getFontRenderContext();\r\n result += tickLabelFont.getLineMetrics(\"123\", frc).getHeight();\r\n return result;\r\n }\r\n\r\n /**\r\n * Estimates the maximum width of the tick labels, assuming the specified\r\n * tick unit is used.\r\n * <P>\r\n * Rather than computing the string bounds of every tick on the axis, we\r\n * just look at two values: the lower bound and the upper bound for the\r\n * axis. These two values will usually be representative.\r\n *\r\n * @param g2 the graphics device.\r\n * @param unit the tick unit to use for calculation.\r\n *\r\n * @return The estimated maximum width of the tick labels.\r\n */\r\n protected double estimateMaximumTickLabelWidth(Graphics2D g2,\r\n TickUnit unit) {\r\n\r\n RectangleInsets tickLabelInsets = getTickLabelInsets();\r\n double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();\r\n\r\n if (isVerticalTickLabels()) {\r\n // all tick labels have the same width (equal to the height of the\r\n // font)...\r\n FontRenderContext frc = g2.getFontRenderContext();\r\n LineMetrics lm = getTickLabelFont().getLineMetrics(\"0\", frc);\r\n result += lm.getHeight();\r\n }\r\n else {\r\n // look at lower and upper bounds...\r\n FontMetrics fm = g2.getFontMetrics(getTickLabelFont());\r\n Range range = getRange();\r\n double lower = range.getLowerBound();\r\n double upper = range.getUpperBound();\r\n String lowerStr, upperStr;\r\n NumberFormat formatter = getNumberFormatOverride();\r\n if (formatter != null) {\r\n lowerStr = formatter.format(lower);\r\n upperStr = formatter.format(upper);\r\n }\r\n else {\r\n lowerStr = unit.valueToString(lower);\r\n upperStr = unit.valueToString(upper);\r\n }\r\n double w1 = fm.stringWidth(lowerStr);\r\n double w2 = fm.stringWidth(upperStr);\r\n result += Math.max(w1, w2);\r\n }\r\n\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Selects an appropriate tick value for the axis. The strategy is to\r\n * display as many ticks as possible (selected from an array of 'standard'\r\n * tick units) without the labels overlapping.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area defined by the axes.\r\n * @param edge the axis location.\r\n */\r\n protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea,\r\n RectangleEdge edge) {\r\n\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n selectHorizontalAutoTickUnit(g2, dataArea, edge);\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n selectVerticalAutoTickUnit(g2, dataArea, edge);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Selects an appropriate tick value for the axis. The strategy is to\r\n * display as many ticks as possible (selected from an array of 'standard'\r\n * tick units) without the labels overlapping.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area defined by the axes.\r\n * @param edge the axis location.\r\n */\r\n protected void selectHorizontalAutoTickUnit(Graphics2D g2,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n double tickLabelWidth = estimateMaximumTickLabelWidth(g2,\r\n getTickUnit());\r\n\r\n // start with the current tick unit...\r\n TickUnitSource tickUnits = getStandardTickUnits();\r\n TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());\r\n double unit1Width = lengthToJava2D(unit1.getSize(), dataArea, edge);\r\n\r\n // then extrapolate...\r\n double guess = (tickLabelWidth / unit1Width) * unit1.getSize();\r\n\r\n NumberTickUnit unit2 = (NumberTickUnit) tickUnits.getCeilingTickUnit(\r\n guess);\r\n double unit2Width = lengthToJava2D(unit2.getSize(), dataArea, edge);\r\n\r\n tickLabelWidth = estimateMaximumTickLabelWidth(g2, unit2);\r\n if (tickLabelWidth > unit2Width) {\r\n unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);\r\n }\r\n\r\n setTickUnit(unit2, false, false);\r\n\r\n }\r\n\r\n /**\r\n * Selects an appropriate tick value for the axis. The strategy is to\r\n * display as many ticks as possible (selected from an array of 'standard'\r\n * tick units) without the labels overlapping.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area in which the plot should be drawn.\r\n * @param edge the axis location.\r\n */\r\n protected void selectVerticalAutoTickUnit(Graphics2D g2, \r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n double tickLabelHeight = estimateMaximumTickLabelHeight(g2);\r\n\r\n // start with the current tick unit...\r\n TickUnitSource tickUnits = getStandardTickUnits();\r\n TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());\r\n double unitHeight = lengthToJava2D(unit1.getSize(), dataArea, edge);\r\n double guess = unit1.getSize();\r\n if (unitHeight > 0) {\r\n // then extrapolate...\r\n guess = (tickLabelHeight / unitHeight) * unit1.getSize();\r\n }\r\n NumberTickUnit unit2 = (NumberTickUnit) tickUnits.getCeilingTickUnit(\r\n guess);\r\n double unit2Height = lengthToJava2D(unit2.getSize(), dataArea, edge);\r\n\r\n tickLabelHeight = estimateMaximumTickLabelHeight(g2);\r\n if (tickLabelHeight > unit2Height) {\r\n unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);\r\n }\r\n\r\n setTickUnit(unit2, false, false);\r\n\r\n }\r\n\r\n /**\r\n * Calculates the positions of the tick labels for the axis, storing the\r\n * results in the tick label list (ready for drawing).\r\n *\r\n * @param g2 the graphics device.\r\n * @param state the axis state.\r\n * @param dataArea the area in which the plot should be drawn.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n @Override\r\n public List refreshTicks(Graphics2D g2, AxisState state, \r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List result = new java.util.ArrayList();\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n result = refreshTicksHorizontal(g2, dataArea, edge);\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n result = refreshTicksVertical(g2, dataArea, edge);\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the positions of the tick labels for the axis, storing the\r\n * results in the tick label list (ready for drawing).\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area in which the data should be drawn.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n protected List refreshTicksHorizontal(Graphics2D g2,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List result = new java.util.ArrayList();\r\n\r\n Font tickLabelFont = getTickLabelFont();\r\n g2.setFont(tickLabelFont);\r\n\r\n if (isAutoTickUnitSelection()) {\r\n selectAutoTickUnit(g2, dataArea, edge);\r\n }\r\n\r\n TickUnit tu = getTickUnit();\r\n double size = tu.getSize();\r\n int count = calculateVisibleTickCount();\r\n double lowestTickValue = calculateLowestVisibleTickValue();\r\n\r\n if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {\r\n int minorTickSpaces = getMinorTickCount();\r\n if (minorTickSpaces <= 0) {\r\n minorTickSpaces = tu.getMinorTickCount();\r\n }\r\n for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {\r\n double minorTickValue = lowestTickValue \r\n - size * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR, minorTickValue,\r\n \"\", TextAnchor.TOP_CENTER, TextAnchor.CENTER,\r\n 0.0));\r\n }\r\n }\r\n for (int i = 0; i < count; i++) {\r\n double currentTickValue = lowestTickValue + (i * size);\r\n String tickLabel;\r\n NumberFormat formatter = getNumberFormatOverride();\r\n if (formatter != null) {\r\n tickLabel = formatter.format(currentTickValue);\r\n }\r\n else {\r\n tickLabel = getTickUnit().valueToString(currentTickValue);\r\n }\r\n TextAnchor anchor, rotationAnchor;\r\n double angle = 0.0;\r\n if (isVerticalTickLabels()) {\r\n anchor = TextAnchor.CENTER_RIGHT;\r\n rotationAnchor = TextAnchor.CENTER_RIGHT;\r\n if (edge == RectangleEdge.TOP) {\r\n angle = Math.PI / 2.0;\r\n }\r\n else {\r\n angle = -Math.PI / 2.0;\r\n }\r\n }\r\n else {\r\n if (edge == RectangleEdge.TOP) {\r\n anchor = TextAnchor.BOTTOM_CENTER;\r\n rotationAnchor = TextAnchor.BOTTOM_CENTER;\r\n }\r\n else {\r\n anchor = TextAnchor.TOP_CENTER;\r\n rotationAnchor = TextAnchor.TOP_CENTER;\r\n }\r\n }\r\n\r\n Tick tick = new NumberTick(new Double(currentTickValue),\r\n tickLabel, anchor, rotationAnchor, angle);\r\n result.add(tick);\r\n double nextTickValue = lowestTickValue + ((i + 1) * size);\r\n for (int minorTick = 1; minorTick < minorTickSpaces;\r\n minorTick++) {\r\n double minorTickValue = currentTickValue\r\n + (nextTickValue - currentTickValue)\r\n * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR,\r\n minorTickValue, \"\", TextAnchor.TOP_CENTER,\r\n TextAnchor.CENTER, 0.0));\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the positions of the tick labels for the axis, storing the\r\n * results in the tick label list (ready for drawing).\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area in which the plot should be drawn.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n protected List refreshTicksVertical(Graphics2D g2,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List result = new java.util.ArrayList();\r\n result.clear();\r\n\r\n Font tickLabelFont = getTickLabelFont();\r\n g2.setFont(tickLabelFont);\r\n if (isAutoTickUnitSelection()) {\r\n selectAutoTickUnit(g2, dataArea, edge);\r\n }\r\n\r\n TickUnit tu = getTickUnit();\r\n double size = tu.getSize();\r\n int count = calculateVisibleTickCount();\r\n double lowestTickValue = calculateLowestVisibleTickValue();\r\n\r\n if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {\r\n int minorTickSpaces = getMinorTickCount();\r\n if (minorTickSpaces <= 0) {\r\n minorTickSpaces = tu.getMinorTickCount();\r\n }\r\n for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {\r\n double minorTickValue = lowestTickValue\r\n - size * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR, minorTickValue,\r\n \"\", TextAnchor.TOP_CENTER, TextAnchor.CENTER,\r\n 0.0));\r\n }\r\n }\r\n\r\n for (int i = 0; i < count; i++) {\r\n double currentTickValue = lowestTickValue + (i * size);\r\n String tickLabel;\r\n NumberFormat formatter = getNumberFormatOverride();\r\n if (formatter != null) {\r\n tickLabel = formatter.format(currentTickValue);\r\n }\r\n else {\r\n tickLabel = getTickUnit().valueToString(currentTickValue);\r\n }\r\n\r\n TextAnchor anchor;\r\n TextAnchor rotationAnchor;\r\n double angle = 0.0;\r\n if (isVerticalTickLabels()) {\r\n if (edge == RectangleEdge.LEFT) {\r\n anchor = TextAnchor.BOTTOM_CENTER;\r\n rotationAnchor = TextAnchor.BOTTOM_CENTER;\r\n angle = -Math.PI / 2.0;\r\n }\r\n else {\r\n anchor = TextAnchor.BOTTOM_CENTER;\r\n rotationAnchor = TextAnchor.BOTTOM_CENTER;\r\n angle = Math.PI / 2.0;\r\n }\r\n }\r\n else {\r\n if (edge == RectangleEdge.LEFT) {\r\n anchor = TextAnchor.CENTER_RIGHT;\r\n rotationAnchor = TextAnchor.CENTER_RIGHT;\r\n }\r\n else {\r\n anchor = TextAnchor.CENTER_LEFT;\r\n rotationAnchor = TextAnchor.CENTER_LEFT;\r\n }\r\n }\r\n\r\n Tick tick = new NumberTick(new Double(currentTickValue),\r\n tickLabel, anchor, rotationAnchor, angle);\r\n result.add(tick);\r\n\r\n double nextTickValue = lowestTickValue + ((i + 1) * size);\r\n for (int minorTick = 1; minorTick < minorTickSpaces;\r\n minorTick++) {\r\n double minorTickValue = currentTickValue\r\n + (nextTickValue - currentTickValue)\r\n * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR,\r\n minorTickValue, \"\", TextAnchor.TOP_CENTER,\r\n TextAnchor.CENTER, 0.0));\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Returns a clone of the axis.\r\n *\r\n * @return A clone\r\n *\r\n * @throws CloneNotSupportedException if some component of the axis does\r\n * not support cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n NumberAxis clone = (NumberAxis) super.clone();\r\n if (this.numberFormatOverride != null) {\r\n clone.numberFormatOverride\r\n = (NumberFormat) this.numberFormatOverride.clone();\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * Tests the axis for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof NumberAxis)) {\r\n return false;\r\n }\r\n NumberAxis that = (NumberAxis) obj;\r\n if (this.autoRangeIncludesZero != that.autoRangeIncludesZero) {\r\n return false;\r\n }\r\n if (this.autoRangeStickyZero != that.autoRangeStickyZero) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.tickUnit, that.tickUnit)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.numberFormatOverride,\r\n that.numberFormatOverride)) {\r\n return false;\r\n }\r\n if (!this.rangeType.equals(that.rangeType)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a hash code for this object.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n return super.hashCode();\r\n }\r\n\r\n}\r" }, { "identifier": "XYPlot", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/XYPlot.java", "snippet": "public class XYPlot extends Plot implements ValueAxisPlot, Pannable, Zoomable,\r\n RendererChangeListener, Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 7044148245716569264L;\r\n\r\n /** The default grid line stroke. */\r\n public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f,\r\n BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f,\r\n new float[] {2.0f, 2.0f}, 0.0f);\r\n\r\n /** The default grid line paint. */\r\n public static final Paint DEFAULT_GRIDLINE_PAINT = Color.lightGray;\r\n\r\n /** The default crosshair visibility. */\r\n public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false;\r\n\r\n /** The default crosshair stroke. */\r\n public static final Stroke DEFAULT_CROSSHAIR_STROKE\r\n = DEFAULT_GRIDLINE_STROKE;\r\n\r\n /** The default crosshair paint. */\r\n public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.blue;\r\n\r\n /** The resourceBundle for the localization. */\r\n protected static ResourceBundle localizationResources\r\n = ResourceBundleWrapper.getBundle(\r\n \"org.jfree.chart.plot.LocalizationBundle\");\r\n\r\n /** The plot orientation. */\r\n private PlotOrientation orientation;\r\n\r\n /** The offset between the data area and the axes. */\r\n private RectangleInsets axisOffset;\r\n\r\n /** The domain axis / axes (used for the x-values). */\r\n private Map<Integer, ValueAxis> domainAxes;\r\n\r\n /** The domain axis locations. */\r\n private Map<Integer, AxisLocation> domainAxisLocations;\r\n\r\n /** The range axis (used for the y-values). */\r\n private Map<Integer, ValueAxis> rangeAxes;\r\n\r\n /** The range axis location. */\r\n private Map<Integer, AxisLocation> rangeAxisLocations;\r\n\r\n /** Storage for the datasets. */\r\n private Map<Integer, XYDataset> datasets;\r\n\r\n /** Storage for the renderers. */\r\n private Map<Integer, XYItemRenderer> renderers;\r\n\r\n /**\r\n * Storage for the mapping between datasets/renderers and domain axes. The\r\n * keys in the map are Integer objects, corresponding to the dataset\r\n * index. The values in the map are List objects containing Integer\r\n * objects (corresponding to the axis indices). If the map contains no\r\n * entry for a dataset, it is assumed to map to the primary domain axis\r\n * (index = 0).\r\n */\r\n private Map<Integer, List<Integer>> datasetToDomainAxesMap;\r\n\r\n /**\r\n * Storage for the mapping between datasets/renderers and range axes. The\r\n * keys in the map are Integer objects, corresponding to the dataset\r\n * index. The values in the map are List objects containing Integer\r\n * objects (corresponding to the axis indices). If the map contains no\r\n * entry for a dataset, it is assumed to map to the primary domain axis\r\n * (index = 0).\r\n */\r\n private Map<Integer, List<Integer>> datasetToRangeAxesMap;\r\n\r\n /** The origin point for the quadrants (if drawn). */\r\n private transient Point2D quadrantOrigin = new Point2D.Double(0.0, 0.0);\r\n\r\n /** The paint used for each quadrant. */\r\n private transient Paint[] quadrantPaint\r\n = new Paint[] {null, null, null, null};\r\n\r\n /** A flag that controls whether the domain grid-lines are visible. */\r\n private boolean domainGridlinesVisible;\r\n\r\n /** The stroke used to draw the domain grid-lines. */\r\n private transient Stroke domainGridlineStroke;\r\n\r\n /** The paint used to draw the domain grid-lines. */\r\n private transient Paint domainGridlinePaint;\r\n\r\n /** A flag that controls whether the range grid-lines are visible. */\r\n private boolean rangeGridlinesVisible;\r\n\r\n /** The stroke used to draw the range grid-lines. */\r\n private transient Stroke rangeGridlineStroke;\r\n\r\n /** The paint used to draw the range grid-lines. */\r\n private transient Paint rangeGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether the domain minor grid-lines are visible.\r\n *\r\n * @since 1.0.12\r\n */\r\n private boolean domainMinorGridlinesVisible;\r\n\r\n /**\r\n * The stroke used to draw the domain minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Stroke domainMinorGridlineStroke;\r\n\r\n /**\r\n * The paint used to draw the domain minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Paint domainMinorGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether the range minor grid-lines are visible.\r\n *\r\n * @since 1.0.12\r\n */\r\n private boolean rangeMinorGridlinesVisible;\r\n\r\n /**\r\n * The stroke used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Stroke rangeMinorGridlineStroke;\r\n\r\n /**\r\n * The paint used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Paint rangeMinorGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not the zero baseline against the domain\r\n * axis is visible.\r\n *\r\n * @since 1.0.5\r\n */\r\n private boolean domainZeroBaselineVisible;\r\n\r\n /**\r\n * The stroke used for the zero baseline against the domain axis.\r\n *\r\n * @since 1.0.5\r\n */\r\n private transient Stroke domainZeroBaselineStroke;\r\n\r\n /**\r\n * The paint used for the zero baseline against the domain axis.\r\n *\r\n * @since 1.0.5\r\n */\r\n private transient Paint domainZeroBaselinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not the zero baseline against the range\r\n * axis is visible.\r\n */\r\n private boolean rangeZeroBaselineVisible;\r\n\r\n /** The stroke used for the zero baseline against the range axis. */\r\n private transient Stroke rangeZeroBaselineStroke;\r\n\r\n /** The paint used for the zero baseline against the range axis. */\r\n private transient Paint rangeZeroBaselinePaint;\r\n\r\n /** A flag that controls whether or not a domain crosshair is drawn..*/\r\n private boolean domainCrosshairVisible;\r\n\r\n /** The domain crosshair value. */\r\n private double domainCrosshairValue;\r\n\r\n /** The pen/brush used to draw the crosshair (if any). */\r\n private transient Stroke domainCrosshairStroke;\r\n\r\n /** The color used to draw the crosshair (if any). */\r\n private transient Paint domainCrosshairPaint;\r\n\r\n /**\r\n * A flag that controls whether or not the crosshair locks onto actual\r\n * data points.\r\n */\r\n private boolean domainCrosshairLockedOnData = true;\r\n\r\n /** A flag that controls whether or not a range crosshair is drawn..*/\r\n private boolean rangeCrosshairVisible;\r\n\r\n /** The range crosshair value. */\r\n private double rangeCrosshairValue;\r\n\r\n /** The pen/brush used to draw the crosshair (if any). */\r\n private transient Stroke rangeCrosshairStroke;\r\n\r\n /** The color used to draw the crosshair (if any). */\r\n private transient Paint rangeCrosshairPaint;\r\n\r\n /**\r\n * A flag that controls whether or not the crosshair locks onto actual\r\n * data points.\r\n */\r\n private boolean rangeCrosshairLockedOnData = true;\r\n\r\n /** A map of lists of foreground markers (optional) for the domain axes. */\r\n private Map foregroundDomainMarkers;\r\n\r\n /** A map of lists of background markers (optional) for the domain axes. */\r\n private Map backgroundDomainMarkers;\r\n\r\n /** A map of lists of foreground markers (optional) for the range axes. */\r\n private Map foregroundRangeMarkers;\r\n\r\n /** A map of lists of background markers (optional) for the range axes. */\r\n private Map backgroundRangeMarkers;\r\n\r\n /**\r\n * A (possibly empty) list of annotations for the plot. The list should\r\n * be initialised in the constructor and never allowed to be\r\n * <code>null</code>.\r\n */\r\n private List<XYAnnotation> annotations;\r\n\r\n /** The paint used for the domain tick bands (if any). */\r\n private transient Paint domainTickBandPaint;\r\n\r\n /** The paint used for the range tick bands (if any). */\r\n private transient Paint rangeTickBandPaint;\r\n\r\n /** The fixed domain axis space. */\r\n private AxisSpace fixedDomainAxisSpace;\r\n\r\n /** The fixed range axis space. */\r\n private AxisSpace fixedRangeAxisSpace;\r\n\r\n /**\r\n * The order of the dataset rendering (REVERSE draws the primary dataset\r\n * last so that it appears to be on top).\r\n */\r\n private DatasetRenderingOrder datasetRenderingOrder\r\n = DatasetRenderingOrder.REVERSE;\r\n\r\n /**\r\n * The order of the series rendering (REVERSE draws the primary series\r\n * last so that it appears to be on top).\r\n */\r\n private SeriesRenderingOrder seriesRenderingOrder\r\n = SeriesRenderingOrder.REVERSE;\r\n\r\n /**\r\n * The weight for this plot (only relevant if this is a subplot in a\r\n * combined plot).\r\n */\r\n private int weight;\r\n\r\n /**\r\n * An optional collection of legend items that can be returned by the\r\n * getLegendItems() method.\r\n */\r\n private LegendItemCollection fixedLegendItems;\r\n\r\n /**\r\n * A flag that controls whether or not panning is enabled for the domain\r\n * axis/axes.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean domainPannable;\r\n\r\n /**\r\n * A flag that controls whether or not panning is enabled for the range\r\n * axis/axes.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean rangePannable;\r\n\r\n /**\r\n * The shadow generator (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n private ShadowGenerator shadowGenerator;\r\n\r\n /**\r\n * Creates a new <code>XYPlot</code> instance with no dataset, no axes and\r\n * no renderer. You should specify these items before using the plot.\r\n */\r\n public XYPlot() {\r\n this(null, null, null, null);\r\n }\r\n\r\n /**\r\n * Creates a new plot with the specified dataset, axes and renderer. Any\r\n * of the arguments can be <code>null</code>, but in that case you should\r\n * take care to specify the value before using the plot (otherwise a\r\n * <code>NullPointerException</code> may be thrown).\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n * @param domainAxis the domain axis (<code>null</code> permitted).\r\n * @param rangeAxis the range axis (<code>null</code> permitted).\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n */\r\n public XYPlot(XYDataset dataset, ValueAxis domainAxis, ValueAxis rangeAxis,\r\n XYItemRenderer renderer) {\r\n super();\r\n this.orientation = PlotOrientation.VERTICAL;\r\n this.weight = 1; // only relevant when this is a subplot\r\n this.axisOffset = RectangleInsets.ZERO_INSETS;\r\n\r\n // allocate storage for datasets, axes and renderers (all optional)\r\n this.domainAxes = new HashMap<Integer, ValueAxis>();\r\n this.domainAxisLocations = new HashMap<Integer, AxisLocation>();\r\n this.foregroundDomainMarkers = new HashMap();\r\n this.backgroundDomainMarkers = new HashMap();\r\n\r\n this.rangeAxes = new HashMap<Integer, ValueAxis>();\r\n this.rangeAxisLocations = new HashMap<Integer, AxisLocation>();\r\n this.foregroundRangeMarkers = new HashMap();\r\n this.backgroundRangeMarkers = new HashMap();\r\n\r\n this.datasets = new HashMap<Integer, XYDataset>();\r\n this.renderers = new HashMap<Integer, XYItemRenderer>();\r\n\r\n this.datasetToDomainAxesMap = new TreeMap();\r\n this.datasetToRangeAxesMap = new TreeMap();\r\n\r\n this.annotations = new java.util.ArrayList();\r\n\r\n this.datasets.put(0, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n\r\n this.renderers.put(0, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n\r\n this.domainAxes.put(0, domainAxis);\r\n mapDatasetToDomainAxis(0, 0);\r\n if (domainAxis != null) {\r\n domainAxis.setPlot(this);\r\n domainAxis.addChangeListener(this);\r\n }\r\n this.domainAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT);\r\n\r\n this.rangeAxes.put(0, rangeAxis);\r\n mapDatasetToRangeAxis(0, 0);\r\n if (rangeAxis != null) {\r\n rangeAxis.setPlot(this);\r\n rangeAxis.addChangeListener(this);\r\n }\r\n this.rangeAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT);\r\n\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n\r\n this.domainGridlinesVisible = true;\r\n this.domainGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.domainGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.domainMinorGridlinesVisible = false;\r\n this.domainMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.domainMinorGridlinePaint = Color.white;\r\n\r\n this.domainZeroBaselineVisible = false;\r\n this.domainZeroBaselinePaint = Color.black;\r\n this.domainZeroBaselineStroke = new BasicStroke(0.5f);\r\n\r\n this.rangeGridlinesVisible = true;\r\n this.rangeGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.rangeMinorGridlinesVisible = false;\r\n this.rangeMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeMinorGridlinePaint = Color.white;\r\n\r\n this.rangeZeroBaselineVisible = false;\r\n this.rangeZeroBaselinePaint = Color.black;\r\n this.rangeZeroBaselineStroke = new BasicStroke(0.5f);\r\n\r\n this.domainCrosshairVisible = false;\r\n this.domainCrosshairValue = 0.0;\r\n this.domainCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.domainCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n\r\n this.rangeCrosshairVisible = false;\r\n this.rangeCrosshairValue = 0.0;\r\n this.rangeCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.rangeCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n this.shadowGenerator = null;\r\n }\r\n\r\n /**\r\n * Returns the plot type as a string.\r\n *\r\n * @return A short string describing the type of plot.\r\n */\r\n @Override\r\n public String getPlotType() {\r\n return localizationResources.getString(\"XY_Plot\");\r\n }\r\n\r\n /**\r\n * Returns the orientation of the plot.\r\n *\r\n * @return The orientation (never <code>null</code>).\r\n *\r\n * @see #setOrientation(PlotOrientation)\r\n */\r\n @Override\r\n public PlotOrientation getOrientation() {\r\n return this.orientation;\r\n }\r\n\r\n /**\r\n * Sets the orientation for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param orientation the orientation (<code>null</code> not allowed).\r\n *\r\n * @see #getOrientation()\r\n */\r\n public void setOrientation(PlotOrientation orientation) {\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n if (orientation != this.orientation) {\r\n this.orientation = orientation;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the axis offset.\r\n *\r\n * @return The axis offset (never <code>null</code>).\r\n *\r\n * @see #setAxisOffset(RectangleInsets)\r\n */\r\n public RectangleInsets getAxisOffset() {\r\n return this.axisOffset;\r\n }\r\n\r\n /**\r\n * Sets the axis offsets (gap between the data area and the axes) and sends\r\n * a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param offset the offset (<code>null</code> not permitted).\r\n *\r\n * @see #getAxisOffset()\r\n */\r\n public void setAxisOffset(RectangleInsets offset) {\r\n ParamChecks.nullNotPermitted(offset, \"offset\");\r\n this.axisOffset = offset;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the domain axis with index 0. If the domain axis for this plot\r\n * is <code>null</code>, then the method will return the parent plot's\r\n * domain axis (if there is a parent plot).\r\n *\r\n * @return The domain axis (possibly <code>null</code>).\r\n *\r\n * @see #getDomainAxis(int)\r\n * @see #setDomainAxis(ValueAxis)\r\n */\r\n public ValueAxis getDomainAxis() {\r\n return getDomainAxis(0);\r\n }\r\n\r\n /**\r\n * Returns the domain axis with the specified index, or {@code null} if \r\n * there is no axis with that index.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The axis ({@code null} possible).\r\n *\r\n * @see #setDomainAxis(int, ValueAxis)\r\n */\r\n public ValueAxis getDomainAxis(int index) {\r\n ValueAxis result = this.domainAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot xy = (XYPlot) parent;\r\n result = xy.getDomainAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the domain axis for the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axis the new axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis()\r\n * @see #setDomainAxis(int, ValueAxis)\r\n */\r\n public void setDomainAxis(ValueAxis axis) {\r\n setDomainAxis(0, axis);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis(int)\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public void setDomainAxis(int index, ValueAxis axis) {\r\n setDomainAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainAxis(int)\r\n */\r\n public void setDomainAxis(int index, ValueAxis axis, boolean notify) {\r\n ValueAxis existing = getDomainAxis(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.domainAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the domain axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setRangeAxes(ValueAxis[])\r\n */\r\n public void setDomainAxes(ValueAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setDomainAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the location of the primary domain axis.\r\n *\r\n * @return The location (never <code>null</code>).\r\n *\r\n * @see #setDomainAxisLocation(AxisLocation)\r\n */\r\n public AxisLocation getDomainAxisLocation() {\r\n return (AxisLocation) this.domainAxisLocations.get(0);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary domain axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainAxisLocation()\r\n */\r\n public void setDomainAxisLocation(AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainAxisLocation()\r\n */\r\n public void setDomainAxisLocation(AxisLocation location, boolean notify) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Returns the edge for the primary domain axis (taking into account the\r\n * plot's orientation).\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getDomainAxisLocation()\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getDomainAxisEdge() {\r\n return Plot.resolveDomainAxisLocation(getDomainAxisLocation(),\r\n this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the number of domain axes.\r\n *\r\n * @return The axis count.\r\n *\r\n * @see #getRangeAxisCount()\r\n */\r\n public int getDomainAxisCount() {\r\n return this.domainAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the domain axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #clearRangeAxes()\r\n */\r\n public void clearDomainAxes() {\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.removeChangeListener(this);\r\n }\r\n }\r\n this.domainAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the domain axes.\r\n */\r\n public void configureDomainAxes() {\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the location for a domain axis. If this hasn't been set\r\n * explicitly, the method returns the location that is opposite to the\r\n * primary domain axis location.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The location (never {@code null}).\r\n *\r\n * @see #setDomainAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getDomainAxisLocation(int index) {\r\n AxisLocation result = this.domainAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getDomainAxisLocation());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location for a domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> not permitted for index\r\n * 0).\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the axis location for a domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n * @param location the location (<code>null</code> not permitted for\r\n * index 0).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n * @see #setRangeAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.domainAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the edge for a domain axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getRangeAxisEdge(int)\r\n */\r\n public RectangleEdge getDomainAxisEdge(int index) {\r\n AxisLocation location = getDomainAxisLocation(index);\r\n return Plot.resolveDomainAxisLocation(location, this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the range axis for the plot. If the range axis for this plot is\r\n * <code>null</code>, then the method will return the parent plot's range\r\n * axis (if there is a parent plot).\r\n *\r\n * @return The range axis.\r\n *\r\n * @see #getRangeAxis(int)\r\n * @see #setRangeAxis(ValueAxis)\r\n */\r\n public ValueAxis getRangeAxis() {\r\n return getRangeAxis(0);\r\n }\r\n\r\n /**\r\n * Sets the range axis for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxis()\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public void setRangeAxis(ValueAxis axis) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n // plot is likely registered as a listener with the existing axis...\r\n ValueAxis existing = getRangeAxis();\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.rangeAxes.put(0, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the location of the primary range axis.\r\n *\r\n * @return The location (never <code>null</code>).\r\n *\r\n * @see #setRangeAxisLocation(AxisLocation)\r\n */\r\n public AxisLocation getRangeAxisLocation() {\r\n return (AxisLocation) this.rangeAxisLocations.get(0);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary range axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeAxisLocation()\r\n */\r\n public void setRangeAxisLocation(AxisLocation location) {\r\n // delegate...\r\n setRangeAxisLocation(0, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary range axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRangeAxisLocation()\r\n */\r\n public void setRangeAxisLocation(AxisLocation location, boolean notify) {\r\n // delegate...\r\n setRangeAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Returns the edge for the primary range axis.\r\n *\r\n * @return The range axis edge.\r\n *\r\n * @see #getRangeAxisLocation()\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getRangeAxisEdge() {\r\n return Plot.resolveRangeAxisLocation(getRangeAxisLocation(),\r\n this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the range axis with the specified index, or {@code null} if \r\n * there is no axis with that index.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The axis ({@code null} possible).\r\n *\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public ValueAxis getRangeAxis(int index) {\r\n ValueAxis result = this.rangeAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot xy = (XYPlot) parent;\r\n result = xy.getRangeAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets a range axis and sends a {@link PlotChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxis(int)\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis) {\r\n setRangeAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a range axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRangeAxis(int)\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis, boolean notify) {\r\n ValueAxis existing = getRangeAxis(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.rangeAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the range axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setDomainAxes(ValueAxis[])\r\n */\r\n public void setRangeAxes(ValueAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setRangeAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the number of range axes.\r\n *\r\n * @return The axis count.\r\n *\r\n * @see #getDomainAxisCount()\r\n */\r\n public int getRangeAxisCount() {\r\n return this.rangeAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the range axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #clearDomainAxes()\r\n */\r\n public void clearRangeAxes() {\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.removeChangeListener(this);\r\n }\r\n }\r\n this.rangeAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the range axes.\r\n *\r\n * @see #configureDomainAxes()\r\n */\r\n public void configureRangeAxes() {\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the location for a range axis. If this hasn't been set\r\n * explicitly, the method returns the location that is opposite to the\r\n * primary range axis location.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The location (never {@code null}).\r\n *\r\n * @see #setRangeAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getRangeAxisLocation(int index) {\r\n AxisLocation result = this.rangeAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getRangeAxisLocation());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location for a range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location) {\r\n // delegate...\r\n setRangeAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the axis location for a domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> not permitted for\r\n * index 0).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #setDomainAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.rangeAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the edge for a range axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getRangeAxisEdge(int index) {\r\n AxisLocation location = getRangeAxisLocation(index);\r\n return Plot.resolveRangeAxisLocation(location, this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the primary dataset for the plot.\r\n *\r\n * @return The primary dataset (possibly <code>null</code>).\r\n *\r\n * @see #getDataset(int)\r\n * @see #setDataset(XYDataset)\r\n */\r\n public XYDataset getDataset() {\r\n return getDataset(0);\r\n }\r\n\r\n /**\r\n * Returns the dataset with the specified index, or {@code null} if there\r\n * is no dataset with that index.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The dataset (possibly {@code null}).\r\n *\r\n * @see #setDataset(int, XYDataset)\r\n */\r\n public XYDataset getDataset(int index) {\r\n return (XYDataset) this.datasets.get(index);\r\n }\r\n\r\n /**\r\n * Sets the primary dataset for the plot, replacing the existing dataset if\r\n * there is one.\r\n *\r\n * @param dataset the dataset ({@code null} permitted).\r\n *\r\n * @see #getDataset()\r\n * @see #setDataset(int, XYDataset)\r\n */\r\n public void setDataset(XYDataset dataset) {\r\n setDataset(0, dataset);\r\n }\r\n\r\n /**\r\n * Sets a dataset for the plot and sends a change event to all registered\r\n * listeners.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n *\r\n * @see #getDataset(int)\r\n */\r\n public void setDataset(int index, XYDataset dataset) {\r\n XYDataset existing = getDataset(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.datasets.put(index, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n\r\n // send a dataset change event to self...\r\n DatasetChangeEvent event = new DatasetChangeEvent(this, dataset);\r\n datasetChanged(event);\r\n }\r\n\r\n /**\r\n * Returns the number of datasets.\r\n *\r\n * @return The number of datasets.\r\n */\r\n public int getDatasetCount() {\r\n return this.datasets.size();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified dataset, or {@code -1} if the\r\n * dataset does not belong to the plot.\r\n *\r\n * @param dataset the dataset ({@code null} not permitted).\r\n *\r\n * @return The index or -1.\r\n */\r\n public int indexOf(XYDataset dataset) {\r\n for (Map.Entry<Integer, XYDataset> entry: this.datasets.entrySet()) {\r\n if (dataset == entry.getValue()) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular domain axis. All data will be plotted\r\n * against axis zero by default, no mapping is required for this case.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index.\r\n *\r\n * @see #mapDatasetToRangeAxis(int, int)\r\n */\r\n public void mapDatasetToDomainAxis(int index, int axisIndex) {\r\n List axisIndices = new java.util.ArrayList(1);\r\n axisIndices.add(new Integer(axisIndex));\r\n mapDatasetToDomainAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToDomainAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n Integer key = new Integer(index);\r\n this.datasetToDomainAxesMap.put(key, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular range axis. All data will be plotted\r\n * against axis zero by default, no mapping is required for this case.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index.\r\n *\r\n * @see #mapDatasetToDomainAxis(int, int)\r\n */\r\n public void mapDatasetToRangeAxis(int index, int axisIndex) {\r\n List axisIndices = new java.util.ArrayList(1);\r\n axisIndices.add(new Integer(axisIndex));\r\n mapDatasetToRangeAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToRangeAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n Integer key = new Integer(index);\r\n this.datasetToRangeAxesMap.put(key, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * This method is used to perform argument checking on the list of\r\n * axis indices passed to mapDatasetToDomainAxes() and\r\n * mapDatasetToRangeAxes().\r\n *\r\n * @param indices the list of indices (<code>null</code> permitted).\r\n */\r\n private void checkAxisIndices(List<Integer> indices) {\r\n // axisIndices can be:\r\n // 1. null;\r\n // 2. non-empty, containing only Integer objects that are unique.\r\n if (indices == null) {\r\n return; // OK\r\n }\r\n int count = indices.size();\r\n if (count == 0) {\r\n throw new IllegalArgumentException(\"Empty list not permitted.\");\r\n }\r\n Set<Integer> set = new HashSet<Integer>();\r\n for (Integer item : indices) {\r\n if (set.contains(item)) {\r\n throw new IllegalArgumentException(\"Indices must be unique.\");\r\n }\r\n set.add(item);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the number of renderer slots for this plot.\r\n *\r\n * @return The number of renderer slots.\r\n *\r\n * @since 1.0.11\r\n */\r\n public int getRendererCount() {\r\n return this.renderers.size();\r\n }\r\n\r\n /**\r\n * Returns the renderer for the primary dataset.\r\n *\r\n * @return The item renderer (possibly <code>null</code>).\r\n *\r\n * @see #setRenderer(XYItemRenderer)\r\n */\r\n public XYItemRenderer getRenderer() {\r\n return getRenderer(0);\r\n }\r\n\r\n /**\r\n * Returns the renderer with the specified index, or {@code null}.\r\n *\r\n * @param index the renderer index (must be &gt;= 0).\r\n *\r\n * @return The renderer (possibly {@code null}).\r\n *\r\n * @see #setRenderer(int, XYItemRenderer)\r\n */\r\n public XYItemRenderer getRenderer(int index) {\r\n return (XYItemRenderer) this.renderers.get(index);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the primary dataset and sends a change event to \r\n * all registered listeners. If the renderer is set to <code>null</code>, \r\n * no data will be displayed.\r\n *\r\n * @param renderer the renderer ({@code null} permitted).\r\n *\r\n * @see #getRenderer()\r\n */\r\n public void setRenderer(XYItemRenderer renderer) {\r\n setRenderer(0, renderer);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the dataset with the specified index and sends a \r\n * change event to all registered listeners. Note that each dataset should \r\n * have its own renderer, you should not use one renderer for multiple \r\n * datasets.\r\n *\r\n * @param index the index (must be &gt;= 0).\r\n * @param renderer the renderer.\r\n *\r\n * @see #getRenderer(int)\r\n */\r\n public void setRenderer(int index, XYItemRenderer renderer) {\r\n setRenderer(index, renderer, true);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the dataset with the specified index and, if \r\n * requested, sends a change event to all registered listeners. Note that \r\n * each dataset should have its own renderer, you should not use one \r\n * renderer for multiple datasets.\r\n *\r\n * @param index the index (must be &gt;= 0).\r\n * @param renderer the renderer.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRenderer(int)\r\n */\r\n public void setRenderer(int index, XYItemRenderer renderer, \r\n boolean notify) {\r\n XYItemRenderer existing = getRenderer(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.renderers.put(index, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the renderers for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param renderers the renderers (<code>null</code> not permitted).\r\n */\r\n public void setRenderers(XYItemRenderer[] renderers) {\r\n for (int i = 0; i < renderers.length; i++) {\r\n setRenderer(i, renderers[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the dataset rendering order.\r\n *\r\n * @return The order (never <code>null</code>).\r\n *\r\n * @see #setDatasetRenderingOrder(DatasetRenderingOrder)\r\n */\r\n public DatasetRenderingOrder getDatasetRenderingOrder() {\r\n return this.datasetRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the rendering order and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. By default, the plot renders the primary dataset\r\n * last (so that the primary dataset overlays the secondary datasets).\r\n * You can reverse this if you want to.\r\n *\r\n * @param order the rendering order (<code>null</code> not permitted).\r\n *\r\n * @see #getDatasetRenderingOrder()\r\n */\r\n public void setDatasetRenderingOrder(DatasetRenderingOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.datasetRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the series rendering order.\r\n *\r\n * @return the order (never <code>null</code>).\r\n *\r\n * @see #setSeriesRenderingOrder(SeriesRenderingOrder)\r\n */\r\n public SeriesRenderingOrder getSeriesRenderingOrder() {\r\n return this.seriesRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the series order and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. By default, the plot renders the primary series\r\n * last (so that the primary series appears to be on top).\r\n * You can reverse this if you want to.\r\n *\r\n * @param order the rendering order (<code>null</code> not permitted).\r\n *\r\n * @see #getSeriesRenderingOrder()\r\n */\r\n public void setSeriesRenderingOrder(SeriesRenderingOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.seriesRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified renderer, or <code>-1</code> if the\r\n * renderer is not assigned to this plot.\r\n *\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n *\r\n * @return The renderer index.\r\n */\r\n public int getIndexOf(XYItemRenderer renderer) {\r\n for (Map.Entry<Integer, XYItemRenderer> entry \r\n : this.renderers.entrySet()) {\r\n if (entry.getValue() == renderer) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the renderer for the specified dataset (this is either the\r\n * renderer with the same index as the dataset or, if there isn't a \r\n * renderer with the same index, the default renderer). If the dataset\r\n * does not belong to the plot, this method will return {@code null}.\r\n *\r\n * @param dataset the dataset ({@code null} permitted).\r\n *\r\n * @return The renderer (possibly {@code null}).\r\n */\r\n public XYItemRenderer getRendererForDataset(XYDataset dataset) {\r\n int datasetIndex = indexOf(dataset);\r\n if (datasetIndex < 0) {\r\n return null;\r\n } \r\n XYItemRenderer result = this.renderers.get(datasetIndex);\r\n if (result == null) {\r\n result = getRenderer();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the weight for this plot when it is used as a subplot within a\r\n * combined plot.\r\n *\r\n * @return The weight.\r\n *\r\n * @see #setWeight(int)\r\n */\r\n public int getWeight() {\r\n return this.weight;\r\n }\r\n\r\n /**\r\n * Sets the weight for the plot and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param weight the weight.\r\n *\r\n * @see #getWeight()\r\n */\r\n public void setWeight(int weight) {\r\n this.weight = weight;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the domain gridlines are visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setDomainGridlinesVisible(boolean)\r\n */\r\n public boolean isDomainGridlinesVisible() {\r\n return this.domainGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the domain grid-lines are\r\n * visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isDomainGridlinesVisible()\r\n */\r\n public void setDomainGridlinesVisible(boolean visible) {\r\n if (this.domainGridlinesVisible != visible) {\r\n this.domainGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the domain minor gridlines are visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setDomainMinorGridlinesVisible(boolean)\r\n *\r\n * @since 1.0.12\r\n */\r\n public boolean isDomainMinorGridlinesVisible() {\r\n return this.domainMinorGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the domain minor grid-lines\r\n * are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isDomainMinorGridlinesVisible()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlinesVisible(boolean visible) {\r\n if (this.domainMinorGridlinesVisible != visible) {\r\n this.domainMinorGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the grid-lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlineStroke(Stroke)\r\n */\r\n public Stroke getDomainGridlineStroke() {\r\n return this.domainGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the grid lines plotted against the domain axis, and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>stroke</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainGridlineStroke()\r\n */\r\n public void setDomainGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke for the minor grid-lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainMinorGridlineStroke(Stroke)\r\n *\r\n * @since 1.0.12\r\n */\r\n\r\n public Stroke getDomainMinorGridlineStroke() {\r\n return this.domainMinorGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the minor grid lines plotted against the domain\r\n * axis, and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>stroke</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainMinorGridlineStroke()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainMinorGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the grid lines (if any) plotted against the domain\r\n * axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlinePaint(Paint)\r\n */\r\n public Paint getDomainGridlinePaint() {\r\n return this.domainGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the grid lines plotted against the domain axis, and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>paint</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainGridlinePaint()\r\n */\r\n public void setDomainGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the minor grid lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainMinorGridlinePaint(Paint)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Paint getDomainMinorGridlinePaint() {\r\n return this.domainMinorGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the minor grid lines plotted against the domain axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>paint</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainMinorGridlinePaint()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainMinorGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range axis grid is visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeGridlinesVisible(boolean)\r\n */\r\n public boolean isRangeGridlinesVisible() {\r\n return this.rangeGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the range axis grid lines\r\n * are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeGridlinesVisible()\r\n */\r\n public void setRangeGridlinesVisible(boolean visible) {\r\n if (this.rangeGridlinesVisible != visible) {\r\n this.rangeGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlineStroke(Stroke)\r\n */\r\n public Stroke getRangeGridlineStroke() {\r\n return this.rangeGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the grid lines plotted against the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlineStroke()\r\n */\r\n public void setRangeGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the grid lines (if any) plotted against the range\r\n * axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlinePaint(Paint)\r\n */\r\n public Paint getRangeGridlinePaint() {\r\n return this.rangeGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the grid lines plotted against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlinePaint()\r\n */\r\n public void setRangeGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range axis minor grid is visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeMinorGridlinesVisible(boolean)\r\n *\r\n * @since 1.0.12\r\n */\r\n public boolean isRangeMinorGridlinesVisible() {\r\n return this.rangeMinorGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the range axis minor grid\r\n * lines are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeMinorGridlinesVisible()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlinesVisible(boolean visible) {\r\n if (this.rangeMinorGridlinesVisible != visible) {\r\n this.rangeMinorGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlineStroke(Stroke)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Stroke getRangeMinorGridlineStroke() {\r\n return this.rangeMinorGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the minor grid lines plotted against the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlineStroke()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeMinorGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlinePaint(Paint)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Paint getRangeMinorGridlinePaint() {\r\n return this.rangeMinorGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the minor grid lines plotted against the range axis\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlinePaint()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeMinorGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a zero baseline is\r\n * displayed for the domain axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setDomainZeroBaselineVisible(boolean)\r\n */\r\n public boolean isDomainZeroBaselineVisible() {\r\n return this.domainZeroBaselineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the zero baseline is\r\n * displayed for the domain axis, and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #isDomainZeroBaselineVisible()\r\n */\r\n public void setDomainZeroBaselineVisible(boolean visible) {\r\n this.domainZeroBaselineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used for the zero baseline against the domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setDomainZeroBaselineStroke(Stroke)\r\n */\r\n public Stroke getDomainZeroBaselineStroke() {\r\n return this.domainZeroBaselineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the zero baseline for the domain axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getRangeZeroBaselineStroke()\r\n */\r\n public void setDomainZeroBaselineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainZeroBaselineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the zero baseline (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainZeroBaselinePaint(Paint)\r\n */\r\n public Paint getDomainZeroBaselinePaint() {\r\n return this.domainZeroBaselinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the zero baseline plotted against the domain axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getDomainZeroBaselinePaint()\r\n */\r\n public void setDomainZeroBaselinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainZeroBaselinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a zero baseline is\r\n * displayed for the range axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n */\r\n public boolean isRangeZeroBaselineVisible() {\r\n return this.rangeZeroBaselineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the zero baseline is\r\n * displayed for the range axis, and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isRangeZeroBaselineVisible()\r\n */\r\n public void setRangeZeroBaselineVisible(boolean visible) {\r\n this.rangeZeroBaselineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used for the zero baseline against the range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselineStroke(Stroke)\r\n */\r\n public Stroke getRangeZeroBaselineStroke() {\r\n return this.rangeZeroBaselineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the zero baseline for the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselineStroke()\r\n */\r\n public void setRangeZeroBaselineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeZeroBaselineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the zero baseline (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselinePaint(Paint)\r\n */\r\n public Paint getRangeZeroBaselinePaint() {\r\n return this.rangeZeroBaselinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the zero baseline plotted against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselinePaint()\r\n */\r\n public void setRangeZeroBaselinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeZeroBaselinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the domain tick bands. If this is\r\n * <code>null</code>, no tick bands will be drawn.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setDomainTickBandPaint(Paint)\r\n */\r\n public Paint getDomainTickBandPaint() {\r\n return this.domainTickBandPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the domain tick bands.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getDomainTickBandPaint()\r\n */\r\n public void setDomainTickBandPaint(Paint paint) {\r\n this.domainTickBandPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the range tick bands. If this is\r\n * <code>null</code>, no tick bands will be drawn.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setRangeTickBandPaint(Paint)\r\n */\r\n public Paint getRangeTickBandPaint() {\r\n return this.rangeTickBandPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the range tick bands.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getRangeTickBandPaint()\r\n */\r\n public void setRangeTickBandPaint(Paint paint) {\r\n this.rangeTickBandPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the origin for the quadrants that can be displayed on the plot.\r\n * This defaults to (0, 0).\r\n *\r\n * @return The origin point (never <code>null</code>).\r\n *\r\n * @see #setQuadrantOrigin(Point2D)\r\n */\r\n public Point2D getQuadrantOrigin() {\r\n return this.quadrantOrigin;\r\n }\r\n\r\n /**\r\n * Sets the quadrant origin and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param origin the origin (<code>null</code> not permitted).\r\n *\r\n * @see #getQuadrantOrigin()\r\n */\r\n public void setQuadrantOrigin(Point2D origin) {\r\n ParamChecks.nullNotPermitted(origin, \"origin\");\r\n this.quadrantOrigin = origin;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the specified quadrant.\r\n *\r\n * @param index the quadrant index (0-3).\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setQuadrantPaint(int, Paint)\r\n */\r\n public Paint getQuadrantPaint(int index) {\r\n if (index < 0 || index > 3) {\r\n throw new IllegalArgumentException(\"The index value (\" + index\r\n + \") should be in the range 0 to 3.\");\r\n }\r\n return this.quadrantPaint[index];\r\n }\r\n\r\n /**\r\n * Sets the paint used for the specified quadrant and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the quadrant index (0-3).\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getQuadrantPaint(int)\r\n */\r\n public void setQuadrantPaint(int index, Paint paint) {\r\n if (index < 0 || index > 3) {\r\n throw new IllegalArgumentException(\"The index value (\" + index\r\n + \") should be in the range 0 to 3.\");\r\n }\r\n this.quadrantPaint[index] = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #addDomainMarker(Marker, Layer)\r\n * @see #clearDomainMarkers()\r\n */\r\n public void addDomainMarker(Marker marker) {\r\n // defer argument checking...\r\n addDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for the domain axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void addDomainMarker(Marker marker, Layer layer) {\r\n addDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Clears all the (foreground and background) domain markers and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void clearDomainMarkers() {\r\n if (this.backgroundDomainMarkers != null) {\r\n Set<Integer> keys = this.backgroundDomainMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearDomainMarkers(key);\r\n }\r\n this.backgroundDomainMarkers.clear();\r\n }\r\n if (this.foregroundDomainMarkers != null) {\r\n Set<Integer> keys = this.foregroundDomainMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearDomainMarkers(key);\r\n }\r\n this.foregroundDomainMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Clears the (foreground and background) domain markers for a particular\r\n * renderer and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the renderer index.\r\n *\r\n * @see #clearRangeMarkers(int)\r\n */\r\n public void clearDomainMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundDomainMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis (that the renderer is mapped to), however this is\r\n * entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #clearDomainMarkers(int)\r\n * @see #addRangeMarker(int, Marker, Layer)\r\n */\r\n public void addDomainMarker(int index, Marker marker, Layer layer) {\r\n addDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis (that the renderer is mapped to), however this is\r\n * entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addDomainMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ParamChecks.nullNotPermitted(layer, \"layer\");\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker) {\r\n return removeDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker, Layer layer) {\r\n return removeDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer) {\r\n return removeDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and, if requested,\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ArrayList markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (ArrayList) this.foregroundDomainMarkers.get(\r\n new Integer(index));\r\n }\r\n else {\r\n markers = (ArrayList) this.backgroundDomainMarkers.get(\r\n new Integer(index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Adds a marker for the range axis and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #addRangeMarker(Marker, Layer)\r\n */\r\n public void addRangeMarker(Marker marker) {\r\n addRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for the range axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #addRangeMarker(int, Marker, Layer)\r\n */\r\n public void addRangeMarker(Marker marker, Layer layer) {\r\n addRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Clears all the range markers and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @see #clearRangeMarkers()\r\n */\r\n public void clearRangeMarkers() {\r\n if (this.backgroundRangeMarkers != null) {\r\n Set<Integer> keys = this.backgroundRangeMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearRangeMarkers(key);\r\n }\r\n this.backgroundRangeMarkers.clear();\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Set<Integer> keys = this.foregroundRangeMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearRangeMarkers(key);\r\n }\r\n this.foregroundRangeMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #clearRangeMarkers(int)\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer) {\r\n addRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Clears the (foreground and background) range markers for a particular\r\n * renderer.\r\n *\r\n * @param index the renderer index.\r\n */\r\n public void clearRangeMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(Marker marker) {\r\n return removeRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(Marker marker, Layer layer) {\r\n return removeRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer) {\r\n return removeRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background) (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ParamChecks.nullNotPermitted(layer, \"layer\");\r\n List markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (List) this.foregroundRangeMarkers.get(\r\n new Integer(index));\r\n }\r\n else {\r\n markers = (List) this.backgroundRangeMarkers.get(\r\n new Integer(index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @see #getAnnotations()\r\n * @see #removeAnnotation(XYAnnotation)\r\n */\r\n public void addAnnotation(XYAnnotation annotation) {\r\n addAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addAnnotation(XYAnnotation annotation, boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n this.annotations.add(annotation);\r\n annotation.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n * @see #getAnnotations()\r\n */\r\n public boolean removeAnnotation(XYAnnotation annotation) {\r\n return removeAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeAnnotation(XYAnnotation annotation, boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n boolean removed = this.annotations.remove(annotation);\r\n annotation.removeChangeListener(this);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Returns the list of annotations.\r\n *\r\n * @return The list of annotations.\r\n *\r\n * @since 1.0.1\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n */\r\n public List getAnnotations() {\r\n return new ArrayList(this.annotations);\r\n }\r\n\r\n /**\r\n * Clears all the annotations and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n */\r\n public void clearAnnotations() {\r\n for (XYAnnotation annotation : this.annotations) {\r\n annotation.removeChangeListener(this);\r\n }\r\n this.annotations.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the shadow generator for the plot, if any.\r\n *\r\n * @return The shadow generator (possibly <code>null</code>).\r\n *\r\n * @since 1.0.14\r\n */\r\n public ShadowGenerator getShadowGenerator() {\r\n return this.shadowGenerator;\r\n }\r\n\r\n /**\r\n * Sets the shadow generator for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setShadowGenerator(ShadowGenerator generator) {\r\n this.shadowGenerator = generator;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Calculates the space required for all the axes in the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateAxisSpace(Graphics2D g2,\r\n Rectangle2D plotArea) {\r\n AxisSpace space = new AxisSpace();\r\n space = calculateRangeAxisSpace(g2, plotArea, space);\r\n Rectangle2D revPlotArea = space.shrink(plotArea, null);\r\n space = calculateDomainAxisSpace(g2, revPlotArea, space);\r\n return space;\r\n }\r\n\r\n /**\r\n * Calculates the space required for the domain axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateDomainAxisSpace(Graphics2D g2, \r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the domain axis...\r\n if (this.fixedDomainAxisSpace != null) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getLeft(),\r\n RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n }\r\n else if (this.orientation == PlotOrientation.VERTICAL) {\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n }\r\n }\r\n else {\r\n // reserve space for the domain axes...\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n RectangleEdge edge = getDomainAxisEdge(\r\n findDomainAxisIndex(axis));\r\n space = axis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the space required for the range axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateRangeAxisSpace(Graphics2D g2, \r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the range axis...\r\n if (this.fixedRangeAxisSpace != null) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n }\r\n else if (this.orientation == PlotOrientation.VERTICAL) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getLeft(),\r\n RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n }\r\n }\r\n else {\r\n // reserve space for the range axes...\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n RectangleEdge edge = getRangeAxisEdge(\r\n findRangeAxisIndex(axis));\r\n space = axis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Trims a rectangle to integer coordinates.\r\n *\r\n * @param rect the incoming rectangle.\r\n *\r\n * @return A rectangle with integer coordinates.\r\n */\r\n private Rectangle integerise(Rectangle2D rect) {\r\n int x0 = (int) Math.ceil(rect.getMinX());\r\n int y0 = (int) Math.ceil(rect.getMinY());\r\n int x1 = (int) Math.floor(rect.getMaxX());\r\n int y1 = (int) Math.floor(rect.getMaxY());\r\n return new Rectangle(x0, y0, (x1 - x0), (y1 - y0));\r\n }\r\n\r\n /**\r\n * Draws the plot within the specified area on a graphics device.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the plot area (in Java2D space).\r\n * @param anchor an anchor point in Java2D space (<code>null</code>\r\n * permitted).\r\n * @param parentState the state from the parent plot, if there is one\r\n * (<code>null</code> permitted).\r\n * @param info collects chart drawing information (<code>null</code>\r\n * permitted).\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor,\r\n PlotState parentState, PlotRenderingInfo info) {\r\n\r\n // if the plot area is too small, just return...\r\n boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW);\r\n boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW);\r\n if (b1 || b2) {\r\n return;\r\n }\r\n\r\n // record the plot area...\r\n if (info != null) {\r\n info.setPlotArea(area);\r\n }\r\n\r\n // adjust the drawing area for the plot insets (if any)...\r\n RectangleInsets insets = getInsets();\r\n insets.trim(area);\r\n\r\n AxisSpace space = calculateAxisSpace(g2, area);\r\n Rectangle2D dataArea = space.shrink(area, null);\r\n this.axisOffset.trim(dataArea);\r\n\r\n dataArea = integerise(dataArea);\r\n if (dataArea.isEmpty()) {\r\n return;\r\n }\r\n createAndAddEntity((Rectangle2D) dataArea.clone(), info, null, null);\r\n if (info != null) {\r\n info.setDataArea(dataArea);\r\n }\r\n\r\n // draw the plot background and axes...\r\n drawBackground(g2, dataArea);\r\n Map axisStateMap = drawAxes(g2, area, dataArea, info);\r\n\r\n PlotOrientation orient = getOrientation();\r\n\r\n // the anchor point is typically the point where the mouse last\r\n // clicked - the crosshairs will be driven off this point...\r\n if (anchor != null && !dataArea.contains(anchor)) {\r\n anchor = null;\r\n }\r\n CrosshairState crosshairState = new CrosshairState();\r\n crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY);\r\n crosshairState.setAnchor(anchor);\r\n\r\n crosshairState.setAnchorX(Double.NaN);\r\n crosshairState.setAnchorY(Double.NaN);\r\n if (anchor != null) {\r\n ValueAxis domainAxis = getDomainAxis();\r\n if (domainAxis != null) {\r\n double x;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n x = domainAxis.java2DToValue(anchor.getX(), dataArea,\r\n getDomainAxisEdge());\r\n }\r\n else {\r\n x = domainAxis.java2DToValue(anchor.getY(), dataArea,\r\n getDomainAxisEdge());\r\n }\r\n crosshairState.setAnchorX(x);\r\n }\r\n ValueAxis rangeAxis = getRangeAxis();\r\n if (rangeAxis != null) {\r\n double y;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n y = rangeAxis.java2DToValue(anchor.getY(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n else {\r\n y = rangeAxis.java2DToValue(anchor.getX(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n crosshairState.setAnchorY(y);\r\n }\r\n }\r\n crosshairState.setCrosshairX(getDomainCrosshairValue());\r\n crosshairState.setCrosshairY(getRangeCrosshairValue());\r\n Shape originalClip = g2.getClip();\r\n Composite originalComposite = g2.getComposite();\r\n\r\n g2.clip(dataArea);\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n getForegroundAlpha()));\r\n\r\n AxisState domainAxisState = (AxisState) axisStateMap.get(\r\n getDomainAxis());\r\n if (domainAxisState == null) {\r\n if (parentState != null) {\r\n domainAxisState = (AxisState) parentState.getSharedAxisStates()\r\n .get(getDomainAxis());\r\n }\r\n }\r\n\r\n AxisState rangeAxisState = (AxisState) axisStateMap.get(getRangeAxis());\r\n if (rangeAxisState == null) {\r\n if (parentState != null) {\r\n rangeAxisState = (AxisState) parentState.getSharedAxisStates()\r\n .get(getRangeAxis());\r\n }\r\n }\r\n if (domainAxisState != null) {\r\n drawDomainTickBands(g2, dataArea, domainAxisState.getTicks());\r\n }\r\n if (rangeAxisState != null) {\r\n drawRangeTickBands(g2, dataArea, rangeAxisState.getTicks());\r\n }\r\n if (domainAxisState != null) {\r\n drawDomainGridlines(g2, dataArea, domainAxisState.getTicks());\r\n drawZeroDomainBaseline(g2, dataArea);\r\n }\r\n if (rangeAxisState != null) {\r\n drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks());\r\n drawZeroRangeBaseline(g2, dataArea);\r\n }\r\n\r\n Graphics2D savedG2 = g2;\r\n BufferedImage dataImage = null;\r\n boolean suppressShadow = Boolean.TRUE.equals(g2.getRenderingHint(\r\n JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION));\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n dataImage = new BufferedImage((int) dataArea.getWidth(),\r\n (int)dataArea.getHeight(), BufferedImage.TYPE_INT_ARGB);\r\n g2 = dataImage.createGraphics();\r\n g2.translate(-dataArea.getX(), -dataArea.getY());\r\n g2.setRenderingHints(savedG2.getRenderingHints());\r\n }\r\n\r\n // draw the markers that are associated with a specific dataset...\r\n for (XYDataset dataset: this.datasets.values()) {\r\n int datasetIndex = indexOf(dataset);\r\n drawDomainMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND);\r\n }\r\n for (XYDataset dataset: this.datasets.values()) {\r\n int datasetIndex = indexOf(dataset);\r\n drawRangeMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND);\r\n }\r\n\r\n // now draw annotations and render data items...\r\n boolean foundData = false;\r\n DatasetRenderingOrder order = getDatasetRenderingOrder();\r\n List<Integer> rendererIndices = getRendererIndices(order);\r\n List<Integer> datasetIndices = getDatasetIndices(order);\r\n // draw background annotations\r\n for (int i : rendererIndices) {\r\n XYItemRenderer renderer = getRenderer(i);\r\n if (renderer != null) {\r\n ValueAxis domainAxis = getDomainAxisForDataset(i);\r\n ValueAxis rangeAxis = getRangeAxisForDataset(i);\r\n renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, \r\n Layer.BACKGROUND, info);\r\n }\r\n }\r\n\r\n // render data items...\r\n for (int datasetIndex : datasetIndices) {\r\n XYDataset dataset = this.getDataset(datasetIndex);\r\n foundData = render(g2, dataArea, datasetIndex, info, \r\n crosshairState) || foundData;\r\n }\r\n\r\n // draw foreground annotations\r\n for (int i : rendererIndices) {\r\n XYItemRenderer renderer = getRenderer(i);\r\n if (renderer != null) {\r\n ValueAxis domainAxis = getDomainAxisForDataset(i);\r\n ValueAxis rangeAxis = getRangeAxisForDataset(i);\r\n renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, \r\n Layer.FOREGROUND, info);\r\n }\r\n }\r\n\r\n // draw domain crosshair if required...\r\n int datasetIndex = crosshairState.getDatasetIndex();\r\n ValueAxis xAxis = this.getDomainAxisForDataset(datasetIndex);\r\n RectangleEdge xAxisEdge = getDomainAxisEdge(getDomainAxisIndex(xAxis));\r\n if (!this.domainCrosshairLockedOnData && anchor != null) {\r\n double xx;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n xx = xAxis.java2DToValue(anchor.getX(), dataArea, xAxisEdge);\r\n }\r\n else {\r\n xx = xAxis.java2DToValue(anchor.getY(), dataArea, xAxisEdge);\r\n }\r\n crosshairState.setCrosshairX(xx);\r\n }\r\n setDomainCrosshairValue(crosshairState.getCrosshairX(), false);\r\n if (isDomainCrosshairVisible()) {\r\n double x = getDomainCrosshairValue();\r\n Paint paint = getDomainCrosshairPaint();\r\n Stroke stroke = getDomainCrosshairStroke();\r\n drawDomainCrosshair(g2, dataArea, orient, x, xAxis, stroke, paint);\r\n }\r\n\r\n // draw range crosshair if required...\r\n ValueAxis yAxis = getRangeAxisForDataset(datasetIndex);\r\n RectangleEdge yAxisEdge = getRangeAxisEdge(getRangeAxisIndex(yAxis));\r\n if (!this.rangeCrosshairLockedOnData && anchor != null) {\r\n double yy;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n yy = yAxis.java2DToValue(anchor.getY(), dataArea, yAxisEdge);\r\n } else {\r\n yy = yAxis.java2DToValue(anchor.getX(), dataArea, yAxisEdge);\r\n }\r\n crosshairState.setCrosshairY(yy);\r\n }\r\n setRangeCrosshairValue(crosshairState.getCrosshairY(), false);\r\n if (isRangeCrosshairVisible()) {\r\n double y = getRangeCrosshairValue();\r\n Paint paint = getRangeCrosshairPaint();\r\n Stroke stroke = getRangeCrosshairStroke();\r\n drawRangeCrosshair(g2, dataArea, orient, y, yAxis, stroke, paint);\r\n }\r\n\r\n if (!foundData) {\r\n drawNoDataMessage(g2, dataArea);\r\n }\r\n\r\n for (int i : rendererIndices) { \r\n drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n for (int i : rendererIndices) {\r\n drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n\r\n drawAnnotations(g2, dataArea, info);\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n BufferedImage shadowImage\r\n = this.shadowGenerator.createDropShadow(dataImage);\r\n g2 = savedG2;\r\n g2.drawImage(shadowImage, (int) dataArea.getX()\r\n + this.shadowGenerator.calculateOffsetX(),\r\n (int) dataArea.getY()\r\n + this.shadowGenerator.calculateOffsetY(), null);\r\n g2.drawImage(dataImage, (int) dataArea.getX(),\r\n (int) dataArea.getY(), null);\r\n }\r\n g2.setClip(originalClip);\r\n g2.setComposite(originalComposite);\r\n\r\n drawOutline(g2, dataArea);\r\n\r\n }\r\n\r\n /**\r\n * Returns the indices of the non-null datasets in the specified order.\r\n * \r\n * @param order the order (<code>null</code> not permitted).\r\n * \r\n * @return The list of indices. \r\n */\r\n private List<Integer> getDatasetIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result;\r\n }\r\n \r\n private List<Integer> getRendererIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Entry<Integer, XYItemRenderer> entry : this.renderers.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result; \r\n }\r\n \r\n /**\r\n * Draws the background for the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n */\r\n @Override\r\n public void drawBackground(Graphics2D g2, Rectangle2D area) {\r\n fillBackground(g2, area, this.orientation);\r\n drawQuadrants(g2, area);\r\n drawBackgroundImage(g2, area);\r\n }\r\n\r\n /**\r\n * Draws the quadrants.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n *\r\n * @see #setQuadrantOrigin(Point2D)\r\n * @see #setQuadrantPaint(int, Paint)\r\n */\r\n protected void drawQuadrants(Graphics2D g2, Rectangle2D area) {\r\n // 0 | 1\r\n // --+--\r\n // 2 | 3\r\n boolean somethingToDraw = false;\r\n\r\n ValueAxis xAxis = getDomainAxis();\r\n if (xAxis == null) { // we can't draw quadrants without a valid x-axis\r\n return;\r\n }\r\n double x = xAxis.getRange().constrain(this.quadrantOrigin.getX());\r\n double xx = xAxis.valueToJava2D(x, area, getDomainAxisEdge());\r\n\r\n ValueAxis yAxis = getRangeAxis();\r\n if (yAxis == null) { // we can't draw quadrants without a valid y-axis\r\n return;\r\n }\r\n double y = yAxis.getRange().constrain(this.quadrantOrigin.getY());\r\n double yy = yAxis.valueToJava2D(y, area, getRangeAxisEdge());\r\n\r\n double xmin = xAxis.getLowerBound();\r\n double xxmin = xAxis.valueToJava2D(xmin, area, getDomainAxisEdge());\r\n\r\n double xmax = xAxis.getUpperBound();\r\n double xxmax = xAxis.valueToJava2D(xmax, area, getDomainAxisEdge());\r\n\r\n double ymin = yAxis.getLowerBound();\r\n double yymin = yAxis.valueToJava2D(ymin, area, getRangeAxisEdge());\r\n\r\n double ymax = yAxis.getUpperBound();\r\n double yymax = yAxis.valueToJava2D(ymax, area, getRangeAxisEdge());\r\n\r\n Rectangle2D[] r = new Rectangle2D[] {null, null, null, null};\r\n if (this.quadrantPaint[0] != null) {\r\n if (x > xmin && y < ymax) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[0] = new Rectangle2D.Double(Math.min(yymax, yy),\r\n Math.min(xxmin, xx), Math.abs(yy - yymax),\r\n Math.abs(xx - xxmin));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[0] = new Rectangle2D.Double(Math.min(xxmin, xx),\r\n Math.min(yymax, yy), Math.abs(xx - xxmin),\r\n Math.abs(yy - yymax));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[1] != null) {\r\n if (x < xmax && y < ymax) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[1] = new Rectangle2D.Double(Math.min(yymax, yy),\r\n Math.min(xxmax, xx), Math.abs(yy - yymax),\r\n Math.abs(xx - xxmax));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[1] = new Rectangle2D.Double(Math.min(xx, xxmax),\r\n Math.min(yymax, yy), Math.abs(xx - xxmax),\r\n Math.abs(yy - yymax));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[2] != null) {\r\n if (x > xmin && y > ymin) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[2] = new Rectangle2D.Double(Math.min(yymin, yy),\r\n Math.min(xxmin, xx), Math.abs(yy - yymin),\r\n Math.abs(xx - xxmin));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[2] = new Rectangle2D.Double(Math.min(xxmin, xx),\r\n Math.min(yymin, yy), Math.abs(xx - xxmin),\r\n Math.abs(yy - yymin));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[3] != null) {\r\n if (x < xmax && y > ymin) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[3] = new Rectangle2D.Double(Math.min(yymin, yy),\r\n Math.min(xxmax, xx), Math.abs(yy - yymin),\r\n Math.abs(xx - xxmax));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[3] = new Rectangle2D.Double(Math.min(xx, xxmax),\r\n Math.min(yymin, yy), Math.abs(xx - xxmax),\r\n Math.abs(yy - yymin));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (somethingToDraw) {\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n getBackgroundAlpha()));\r\n for (int i = 0; i < 4; i++) {\r\n if (this.quadrantPaint[i] != null && r[i] != null) {\r\n g2.setPaint(this.quadrantPaint[i]);\r\n g2.fill(r[i]);\r\n }\r\n }\r\n g2.setComposite(originalComposite);\r\n }\r\n }\r\n\r\n /**\r\n * Draws the domain tick bands, if any.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #setDomainTickBandPaint(Paint)\r\n */\r\n public void drawDomainTickBands(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n Paint bandPaint = getDomainTickBandPaint();\r\n if (bandPaint != null) {\r\n boolean fillBand = false;\r\n ValueAxis xAxis = getDomainAxis();\r\n double previous = xAxis.getLowerBound();\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n double current = tick.getValue();\r\n if (fillBand) {\r\n getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea,\r\n previous, current);\r\n }\r\n previous = current;\r\n fillBand = !fillBand;\r\n }\r\n double end = xAxis.getUpperBound();\r\n if (fillBand) {\r\n getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea,\r\n previous, end);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws the range tick bands, if any.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #setRangeTickBandPaint(Paint)\r\n */\r\n public void drawRangeTickBands(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n Paint bandPaint = getRangeTickBandPaint();\r\n if (bandPaint != null) {\r\n boolean fillBand = false;\r\n ValueAxis axis = getRangeAxis();\r\n double previous = axis.getLowerBound();\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n double current = tick.getValue();\r\n if (fillBand) {\r\n getRenderer().fillRangeGridBand(g2, this, axis, dataArea,\r\n previous, current);\r\n }\r\n previous = current;\r\n fillBand = !fillBand;\r\n }\r\n double end = axis.getUpperBound();\r\n if (fillBand) {\r\n getRenderer().fillRangeGridBand(g2, this, axis, dataArea,\r\n previous, end);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * A utility method for drawing the axes.\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param plotArea the plot area (<code>null</code> not permitted).\r\n * @param dataArea the data area (<code>null</code> not permitted).\r\n * @param plotState collects information about the plot (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A map containing the state for each axis drawn.\r\n */\r\n protected Map<Axis, AxisState> drawAxes(Graphics2D g2, Rectangle2D plotArea,\r\n Rectangle2D dataArea, PlotRenderingInfo plotState) {\r\n\r\n AxisCollection axisCollection = new AxisCollection();\r\n\r\n // add domain axes to lists...\r\n for (ValueAxis axis : this.domainAxes.values()) {\r\n if (axis != null) {\r\n int axisIndex = findDomainAxisIndex(axis);\r\n axisCollection.add(axis, getDomainAxisEdge(axisIndex));\r\n }\r\n }\r\n\r\n // add range axes to lists...\r\n for (ValueAxis axis : this.rangeAxes.values()) {\r\n if (axis != null) {\r\n int axisIndex = findRangeAxisIndex(axis);\r\n axisCollection.add(axis, getRangeAxisEdge(axisIndex));\r\n }\r\n }\r\n\r\n Map axisStateMap = new HashMap();\r\n\r\n // draw the top axes\r\n double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset(\r\n dataArea.getHeight());\r\n Iterator iterator = axisCollection.getAxesAtTop().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.TOP, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the bottom axes\r\n cursor = dataArea.getMaxY()\r\n + this.axisOffset.calculateBottomOutset(dataArea.getHeight());\r\n iterator = axisCollection.getAxesAtBottom().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.BOTTOM, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the left axes\r\n cursor = dataArea.getMinX()\r\n - this.axisOffset.calculateLeftOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtLeft().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.LEFT, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the right axes\r\n cursor = dataArea.getMaxX()\r\n + this.axisOffset.calculateRightOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtRight().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.RIGHT, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n return axisStateMap;\r\n }\r\n\r\n /**\r\n * Draws a representation of the data within the dataArea region, using the\r\n * current renderer.\r\n * <P>\r\n * The <code>info</code> and <code>crosshairState</code> arguments may be\r\n * <code>null</code>.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the region in which the data is to be drawn.\r\n * @param index the dataset index.\r\n * @param info an optional object for collection dimension information.\r\n * @param crosshairState collects crosshair information\r\n * (<code>null</code> permitted).\r\n *\r\n * @return A flag that indicates whether any data was actually rendered.\r\n */\r\n public boolean render(Graphics2D g2, Rectangle2D dataArea, int index,\r\n PlotRenderingInfo info, CrosshairState crosshairState) {\r\n\r\n boolean foundData = false;\r\n XYDataset dataset = getDataset(index);\r\n if (!DatasetUtilities.isEmptyOrNull(dataset)) {\r\n foundData = true;\r\n ValueAxis xAxis = getDomainAxisForDataset(index);\r\n ValueAxis yAxis = getRangeAxisForDataset(index);\r\n if (xAxis == null || yAxis == null) {\r\n return foundData; // can't render anything without axes\r\n }\r\n XYItemRenderer renderer = getRenderer(index);\r\n if (renderer == null) {\r\n renderer = getRenderer();\r\n if (renderer == null) { // no default renderer available\r\n return foundData;\r\n }\r\n }\r\n\r\n XYItemRendererState state = renderer.initialise(g2, dataArea, this,\r\n dataset, info);\r\n int passCount = renderer.getPassCount();\r\n\r\n SeriesRenderingOrder seriesOrder = getSeriesRenderingOrder();\r\n if (seriesOrder == SeriesRenderingOrder.REVERSE) {\r\n //render series in reverse order\r\n for (int pass = 0; pass < passCount; pass++) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = seriesCount - 1; series >= 0; series--) {\r\n int firstItem = 0;\r\n int lastItem = dataset.getItemCount(series) - 1;\r\n if (lastItem == -1) {\r\n continue;\r\n }\r\n if (state.getProcessVisibleItemsOnly()) {\r\n int[] itemBounds = RendererUtilities.findLiveItems(\r\n dataset, series, xAxis.getLowerBound(),\r\n xAxis.getUpperBound());\r\n firstItem = Math.max(itemBounds[0] - 1, 0);\r\n lastItem = Math.min(itemBounds[1] + 1, lastItem);\r\n }\r\n state.startSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n for (int item = firstItem; item <= lastItem; item++) {\r\n renderer.drawItem(g2, state, dataArea, info,\r\n this, xAxis, yAxis, dataset, series, item,\r\n crosshairState, pass);\r\n }\r\n state.endSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n }\r\n }\r\n }\r\n else {\r\n //render series in forward order\r\n for (int pass = 0; pass < passCount; pass++) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n int firstItem = 0;\r\n int lastItem = dataset.getItemCount(series) - 1;\r\n if (state.getProcessVisibleItemsOnly()) {\r\n int[] itemBounds = RendererUtilities.findLiveItems(\r\n dataset, series, xAxis.getLowerBound(),\r\n xAxis.getUpperBound());\r\n firstItem = Math.max(itemBounds[0] - 1, 0);\r\n lastItem = Math.min(itemBounds[1] + 1, lastItem);\r\n }\r\n state.startSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n for (int item = firstItem; item <= lastItem; item++) {\r\n renderer.drawItem(g2, state, dataArea, info,\r\n this, xAxis, yAxis, dataset, series, item,\r\n crosshairState, pass);\r\n }\r\n state.endSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n }\r\n }\r\n }\r\n }\r\n return foundData;\r\n }\r\n\r\n /**\r\n * Returns the domain axis for a dataset.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The axis.\r\n */\r\n public ValueAxis getDomainAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n ValueAxis valueAxis;\r\n List axisIndices = (List) this.datasetToDomainAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n valueAxis = getDomainAxis(axisIndex.intValue());\r\n }\r\n else {\r\n valueAxis = getDomainAxis(0);\r\n }\r\n return valueAxis;\r\n }\r\n\r\n /**\r\n * Returns the range axis for a dataset.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The axis.\r\n */\r\n public ValueAxis getRangeAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n ValueAxis valueAxis;\r\n List axisIndices = (List) this.datasetToRangeAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n valueAxis = getRangeAxis(axisIndex.intValue());\r\n }\r\n else {\r\n valueAxis = getRangeAxis(0);\r\n }\r\n return valueAxis;\r\n }\r\n\r\n /**\r\n * Draws the gridlines for the plot, if they are visible.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #drawRangeGridlines(Graphics2D, Rectangle2D, List)\r\n */\r\n protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n\r\n // no renderer, no gridlines...\r\n if (getRenderer() == null) {\r\n return;\r\n }\r\n\r\n // draw the domain grid lines, if any...\r\n if (isDomainGridlinesVisible() || isDomainMinorGridlinesVisible()) {\r\n Stroke gridStroke = null;\r\n Paint gridPaint = null;\r\n Iterator iterator = ticks.iterator();\r\n boolean paintLine;\r\n while (iterator.hasNext()) {\r\n paintLine = false;\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if ((tick.getTickType() == TickType.MINOR)\r\n && isDomainMinorGridlinesVisible()) {\r\n gridStroke = getDomainMinorGridlineStroke();\r\n gridPaint = getDomainMinorGridlinePaint();\r\n paintLine = true;\r\n } else if ((tick.getTickType() == TickType.MAJOR)\r\n && isDomainGridlinesVisible()) {\r\n gridStroke = getDomainGridlineStroke();\r\n gridPaint = getDomainGridlinePaint();\r\n paintLine = true;\r\n }\r\n XYItemRenderer r = getRenderer();\r\n if ((r instanceof AbstractXYItemRenderer) && paintLine) {\r\n ((AbstractXYItemRenderer) r).drawDomainLine(g2, this,\r\n getDomainAxis(), dataArea, tick.getValue(),\r\n gridPaint, gridStroke);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws the gridlines for the plot's primary range axis, if they are\r\n * visible.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #drawDomainGridlines(Graphics2D, Rectangle2D, List)\r\n */\r\n protected void drawRangeGridlines(Graphics2D g2, Rectangle2D area,\r\n List ticks) {\r\n\r\n // no renderer, no gridlines...\r\n if (getRenderer() == null) {\r\n return;\r\n }\r\n\r\n // draw the range grid lines, if any...\r\n if (isRangeGridlinesVisible() || isRangeMinorGridlinesVisible()) {\r\n Stroke gridStroke = null;\r\n Paint gridPaint = null;\r\n ValueAxis axis = getRangeAxis();\r\n if (axis != null) {\r\n Iterator iterator = ticks.iterator();\r\n boolean paintLine;\r\n while (iterator.hasNext()) {\r\n paintLine = false;\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if ((tick.getTickType() == TickType.MINOR)\r\n && isRangeMinorGridlinesVisible()) {\r\n gridStroke = getRangeMinorGridlineStroke();\r\n gridPaint = getRangeMinorGridlinePaint();\r\n paintLine = true;\r\n } else if ((tick.getTickType() == TickType.MAJOR)\r\n && isRangeGridlinesVisible()) {\r\n gridStroke = getRangeGridlineStroke();\r\n gridPaint = getRangeGridlinePaint();\r\n paintLine = true;\r\n }\r\n if ((tick.getValue() != 0.0\r\n || !isRangeZeroBaselineVisible()) && paintLine) {\r\n getRenderer().drawRangeLine(g2, this, getRangeAxis(),\r\n area, tick.getValue(), gridPaint, gridStroke);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws a base line across the chart at value zero on the domain axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n *\r\n * @see #setDomainZeroBaselineVisible(boolean)\r\n *\r\n * @since 1.0.5\r\n */\r\n protected void drawZeroDomainBaseline(Graphics2D g2, Rectangle2D area) {\r\n if (isDomainZeroBaselineVisible()) {\r\n XYItemRenderer r = getRenderer();\r\n // FIXME: the renderer interface doesn't have the drawDomainLine()\r\n // method, so we have to rely on the renderer being a subclass of\r\n // AbstractXYItemRenderer (which is lame)\r\n if (r instanceof AbstractXYItemRenderer) {\r\n AbstractXYItemRenderer renderer = (AbstractXYItemRenderer) r;\r\n renderer.drawDomainLine(g2, this, getDomainAxis(), area, 0.0,\r\n this.domainZeroBaselinePaint,\r\n this.domainZeroBaselineStroke);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws a base line across the chart at value zero on the range axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n */\r\n protected void drawZeroRangeBaseline(Graphics2D g2, Rectangle2D area) {\r\n if (isRangeZeroBaselineVisible()) {\r\n getRenderer().drawRangeLine(g2, this, getRangeAxis(), area, 0.0,\r\n this.rangeZeroBaselinePaint, this.rangeZeroBaselineStroke);\r\n }\r\n }\r\n\r\n /**\r\n * Draws the annotations for the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param info the chart rendering info.\r\n */\r\n public void drawAnnotations(Graphics2D g2, Rectangle2D dataArea,\r\n PlotRenderingInfo info) {\r\n\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n ValueAxis xAxis = getDomainAxis();\r\n ValueAxis yAxis = getRangeAxis();\r\n annotation.draw(g2, this, dataArea, xAxis, yAxis, 0, info);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the domain markers (if any) for an axis and layer. This method is\r\n * typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the dataset/renderer index.\r\n * @param layer the layer (foreground or background).\r\n */\r\n protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n XYItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n // check that the renderer has a corresponding dataset (it doesn't\r\n // matter if the dataset is null)\r\n if (index >= getDatasetCount()) {\r\n return;\r\n }\r\n Collection markers = getDomainMarkers(index, layer);\r\n ValueAxis axis = getDomainAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker marker = (Marker) iterator.next();\r\n r.drawDomainMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the range markers (if any) for a renderer and layer. This method\r\n * is typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the renderer index.\r\n * @param layer the layer (foreground or background).\r\n */\r\n protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n XYItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n // check that the renderer has a corresponding dataset (it doesn't\r\n // matter if the dataset is null)\r\n if (index >= getDatasetCount()) {\r\n return;\r\n }\r\n Collection markers = getRangeMarkers(index, layer);\r\n ValueAxis axis = getRangeAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker marker = (Marker) iterator.next();\r\n r.drawRangeMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the list of domain markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of domain markers.\r\n *\r\n * @see #getRangeMarkers(Layer)\r\n */\r\n public Collection getDomainMarkers(Layer layer) {\r\n return getDomainMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns the list of range markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of range markers.\r\n *\r\n * @see #getDomainMarkers(Layer)\r\n */\r\n public Collection getRangeMarkers(Layer layer) {\r\n return getRangeMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns a collection of domain markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n *\r\n * @see #getRangeMarkers(int, Layer)\r\n */\r\n public Collection getDomainMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundDomainMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundDomainMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a collection of range markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n *\r\n * @see #getDomainMarkers(int, Layer)\r\n */\r\n public Collection getRangeMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundRangeMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundRangeMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Utility method for drawing a horizontal line across the data area of the\r\n * plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param value the coordinate, where to draw the line.\r\n * @param stroke the stroke to use.\r\n * @param paint the paint to use.\r\n */\r\n protected void drawHorizontalLine(Graphics2D g2, Rectangle2D dataArea,\r\n double value, Stroke stroke,\r\n Paint paint) {\r\n\r\n ValueAxis axis = getRangeAxis();\r\n if (getOrientation() == PlotOrientation.HORIZONTAL) {\r\n axis = getDomainAxis();\r\n }\r\n if (axis.getRange().contains(value)) {\r\n double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT);\r\n Line2D line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws a domain crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param value the crosshair value.\r\n * @param axis the axis against which the value is measured.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @since 1.0.4\r\n */\r\n protected void drawDomainCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, double value, ValueAxis axis,\r\n Stroke stroke, Paint paint) {\r\n\r\n if (!axis.getRange().contains(value)) {\r\n return;\r\n }\r\n Line2D line;\r\n if (orientation == PlotOrientation.VERTICAL) {\r\n double xx = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n } else {\r\n double yy = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n\r\n /**\r\n * Utility method for drawing a vertical line on the data area of the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param value the coordinate, where to draw the line.\r\n * @param stroke the stroke to use.\r\n * @param paint the paint to use.\r\n */\r\n protected void drawVerticalLine(Graphics2D g2, Rectangle2D dataArea,\r\n double value, Stroke stroke, Paint paint) {\r\n\r\n ValueAxis axis = getDomainAxis();\r\n if (getOrientation() == PlotOrientation.HORIZONTAL) {\r\n axis = getRangeAxis();\r\n }\r\n if (axis.getRange().contains(value)) {\r\n double xx = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.BOTTOM);\r\n Line2D line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws a range crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param value the crosshair value.\r\n * @param axis the axis against which the value is measured.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @since 1.0.4\r\n */\r\n protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, double value, ValueAxis axis,\r\n Stroke stroke, Paint paint) {\r\n\r\n if (!axis.getRange().contains(value)) {\r\n return;\r\n }\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n Line2D line;\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n double xx = axis.valueToJava2D(value, dataArea, \r\n RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n } else {\r\n double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the plot by updating the anchor values.\r\n *\r\n * @param x the x-coordinate, where the click occurred, in Java2D space.\r\n * @param y the y-coordinate, where the click occurred, in Java2D space.\r\n * @param info object containing information about the plot dimensions.\r\n */\r\n @Override\r\n public void handleClick(int x, int y, PlotRenderingInfo info) {\r\n\r\n Rectangle2D dataArea = info.getDataArea();\r\n if (dataArea.contains(x, y)) {\r\n // set the anchor value for the horizontal axis...\r\n ValueAxis xaxis = getDomainAxis();\r\n if (xaxis != null) {\r\n double hvalue = xaxis.java2DToValue(x, info.getDataArea(),\r\n getDomainAxisEdge());\r\n setDomainCrosshairValue(hvalue);\r\n }\r\n\r\n // set the anchor value for the vertical axis...\r\n ValueAxis yaxis = getRangeAxis();\r\n if (yaxis != null) {\r\n double vvalue = yaxis.java2DToValue(y, info.getDataArea(),\r\n getRangeAxisEdge());\r\n setRangeCrosshairValue(vvalue);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * A utility method that returns a list of datasets that are mapped to a\r\n * particular axis.\r\n *\r\n * @param axisIndex the axis index (<code>null</code> not permitted).\r\n *\r\n * @return A list of datasets.\r\n */\r\n private List<XYDataset> getDatasetsMappedToDomainAxis(Integer axisIndex) {\r\n ParamChecks.nullNotPermitted(axisIndex, \"axisIndex\");\r\n List<XYDataset> result = new ArrayList<XYDataset>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n int index = entry.getKey();\r\n List<Integer> mappedAxes = this.datasetToDomainAxesMap.get(index);\r\n if (mappedAxes == null) {\r\n if (axisIndex.equals(ZERO)) {\r\n result.add(entry.getValue());\r\n }\r\n } else {\r\n if (mappedAxes.contains(axisIndex)) {\r\n result.add(entry.getValue());\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * A utility method that returns a list of datasets that are mapped to a\r\n * particular axis.\r\n *\r\n * @param axisIndex the axis index (<code>null</code> not permitted).\r\n *\r\n * @return A list of datasets.\r\n */\r\n private List<XYDataset> getDatasetsMappedToRangeAxis(Integer axisIndex) {\r\n ParamChecks.nullNotPermitted(axisIndex, \"axisIndex\");\r\n List<XYDataset> result = new ArrayList<XYDataset>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n int index = entry.getKey();\r\n List<Integer> mappedAxes = this.datasetToRangeAxesMap.get(index);\r\n if (mappedAxes == null) {\r\n if (axisIndex.equals(ZERO)) {\r\n result.add(entry.getValue());\r\n }\r\n } else {\r\n if (mappedAxes.contains(axisIndex)) {\r\n result.add(entry.getValue());\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the index of the given domain axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getRangeAxisIndex(ValueAxis)\r\n */\r\n public int getDomainAxisIndex(ValueAxis axis) {\r\n int result = findDomainAxisIndex(axis);\r\n if (result < 0) {\r\n // try the parent plot\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot p = (XYPlot) parent;\r\n result = p.getDomainAxisIndex(axis);\r\n }\r\n }\r\n return result;\r\n }\r\n \r\n private int findDomainAxisIndex(ValueAxis axis) {\r\n for (Map.Entry<Integer, ValueAxis> entry : this.domainAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the index of the given range axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getDomainAxisIndex(ValueAxis)\r\n */\r\n public int getRangeAxisIndex(ValueAxis axis) {\r\n int result = findRangeAxisIndex(axis);\r\n if (result < 0) {\r\n // try the parent plot\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot p = (XYPlot) parent;\r\n result = p.getRangeAxisIndex(axis);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n private int findRangeAxisIndex(ValueAxis axis) {\r\n for (Map.Entry<Integer, ValueAxis> entry : this.rangeAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the range for the specified axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The range.\r\n */\r\n @Override\r\n public Range getDataRange(ValueAxis axis) {\r\n\r\n Range result = null;\r\n List<XYDataset> mappedDatasets = new ArrayList<XYDataset>();\r\n List<XYAnnotation> includedAnnotations = new ArrayList<XYAnnotation>();\r\n boolean isDomainAxis = true;\r\n\r\n // is it a domain axis?\r\n int domainIndex = getDomainAxisIndex(axis);\r\n if (domainIndex >= 0) {\r\n isDomainAxis = true;\r\n mappedDatasets.addAll(getDatasetsMappedToDomainAxis(domainIndex));\r\n if (domainIndex == 0) {\r\n // grab the plot's annotations\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n if (annotation instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(annotation);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // or is it a range axis?\r\n int rangeIndex = getRangeAxisIndex(axis);\r\n if (rangeIndex >= 0) {\r\n isDomainAxis = false;\r\n mappedDatasets.addAll(getDatasetsMappedToRangeAxis(rangeIndex));\r\n if (rangeIndex == 0) {\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n if (annotation instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(annotation);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // iterate through the datasets that map to the axis and get the union\r\n // of the ranges.\r\n for (XYDataset d : mappedDatasets) {\r\n if (d != null) {\r\n XYItemRenderer r = getRendererForDataset(d);\r\n if (isDomainAxis) {\r\n if (r != null) {\r\n result = Range.combine(result, r.findDomainBounds(d));\r\n }\r\n else {\r\n result = Range.combine(result,\r\n DatasetUtilities.findDomainBounds(d));\r\n }\r\n }\r\n else {\r\n if (r != null) {\r\n result = Range.combine(result, r.findRangeBounds(d));\r\n }\r\n else {\r\n result = Range.combine(result,\r\n DatasetUtilities.findRangeBounds(d));\r\n }\r\n }\r\n // FIXME: the XYItemRenderer interface doesn't specify the\r\n // getAnnotations() method but it should\r\n if (r instanceof AbstractXYItemRenderer) {\r\n AbstractXYItemRenderer rr = (AbstractXYItemRenderer) r;\r\n Collection c = rr.getAnnotations();\r\n Iterator i = c.iterator();\r\n while (i.hasNext()) {\r\n XYAnnotation a = (XYAnnotation) i.next();\r\n if (a instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(a);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n Iterator it = includedAnnotations.iterator();\r\n while (it.hasNext()) {\r\n XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next();\r\n if (xyabi.getIncludeInDataBounds()) {\r\n if (isDomainAxis) {\r\n result = Range.combine(result, xyabi.getXRange());\r\n }\r\n else {\r\n result = Range.combine(result, xyabi.getYRange());\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Receives notification of a change to an {@link Annotation} added to\r\n * this plot.\r\n *\r\n * @param event information about the event (not used here).\r\n *\r\n * @since 1.0.14\r\n */\r\n @Override\r\n public void annotationChanged(AnnotationChangeEvent event) {\r\n if (getParent() != null) {\r\n getParent().annotationChanged(event);\r\n }\r\n else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a change to the plot's dataset.\r\n * <P>\r\n * The axis ranges are updated if necessary.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void datasetChanged(DatasetChangeEvent event) {\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n if (getParent() != null) {\r\n getParent().datasetChanged(event);\r\n }\r\n else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n e.setType(ChartChangeEventType.DATASET_UPDATED);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a renderer change event.\r\n *\r\n * @param event the event.\r\n */\r\n @Override\r\n public void rendererChanged(RendererChangeEvent event) {\r\n // if the event was caused by a change to series visibility, then\r\n // the axis ranges might need updating...\r\n if (event.getSeriesVisibilityChanged()) {\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the domain crosshair is visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setDomainCrosshairVisible(boolean)\r\n */\r\n public boolean isDomainCrosshairVisible() {\r\n return this.domainCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the domain crosshair is visible\r\n * and, if the flag changes, sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isDomainCrosshairVisible()\r\n */\r\n public void setDomainCrosshairVisible(boolean flag) {\r\n if (this.domainCrosshairVisible != flag) {\r\n this.domainCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the crosshair should \"lock-on\"\r\n * to actual data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setDomainCrosshairLockedOnData(boolean)\r\n */\r\n public boolean isDomainCrosshairLockedOnData() {\r\n return this.domainCrosshairLockedOnData;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the domain crosshair should\r\n * \"lock-on\" to actual data values. If the flag value changes, this\r\n * method sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isDomainCrosshairLockedOnData()\r\n */\r\n public void setDomainCrosshairLockedOnData(boolean flag) {\r\n if (this.domainCrosshairLockedOnData != flag) {\r\n this.domainCrosshairLockedOnData = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the domain crosshair value.\r\n *\r\n * @return The value.\r\n *\r\n * @see #setDomainCrosshairValue(double)\r\n */\r\n public double getDomainCrosshairValue() {\r\n return this.domainCrosshairValue;\r\n }\r\n\r\n /**\r\n * Sets the domain crosshair value and sends a {@link PlotChangeEvent} to\r\n * all registered listeners (provided that the domain crosshair is visible).\r\n *\r\n * @param value the value.\r\n *\r\n * @see #getDomainCrosshairValue()\r\n */\r\n public void setDomainCrosshairValue(double value) {\r\n setDomainCrosshairValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the domain crosshair value and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners (provided that the\r\n * domain crosshair is visible).\r\n *\r\n * @param value the new value.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainCrosshairValue()\r\n */\r\n public void setDomainCrosshairValue(double value, boolean notify) {\r\n this.domainCrosshairValue = value;\r\n if (isDomainCrosshairVisible() && notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the {@link Stroke} used to draw the crosshair (if visible).\r\n *\r\n * @return The crosshair stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainCrosshairStroke(Stroke)\r\n * @see #isDomainCrosshairVisible()\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public Stroke getDomainCrosshairStroke() {\r\n return this.domainCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the Stroke used to draw the crosshairs (if visible) and notifies\r\n * registered listeners that the axis has been modified.\r\n *\r\n * @param stroke the new crosshair stroke (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public void setDomainCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainCrosshairStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the domain crosshair paint.\r\n *\r\n * @return The crosshair paint (never <code>null</code>).\r\n *\r\n * @see #setDomainCrosshairPaint(Paint)\r\n * @see #isDomainCrosshairVisible()\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public Paint getDomainCrosshairPaint() {\r\n return this.domainCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the new crosshair paint (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public void setDomainCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the range crosshair is visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairVisible(boolean)\r\n * @see #isDomainCrosshairVisible()\r\n */\r\n public boolean isRangeCrosshairVisible() {\r\n return this.rangeCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair is visible.\r\n * If the flag value changes, this method sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isRangeCrosshairVisible()\r\n */\r\n public void setRangeCrosshairVisible(boolean flag) {\r\n if (this.rangeCrosshairVisible != flag) {\r\n this.rangeCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the crosshair should \"lock-on\"\r\n * to actual data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairLockedOnData(boolean)\r\n */\r\n public boolean isRangeCrosshairLockedOnData() {\r\n return this.rangeCrosshairLockedOnData;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair should\r\n * \"lock-on\" to actual data values. If the flag value changes, this method\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isRangeCrosshairLockedOnData()\r\n */\r\n public void setRangeCrosshairLockedOnData(boolean flag) {\r\n if (this.rangeCrosshairLockedOnData != flag) {\r\n this.rangeCrosshairLockedOnData = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range crosshair value.\r\n *\r\n * @return The value.\r\n *\r\n * @see #setRangeCrosshairValue(double)\r\n */\r\n public double getRangeCrosshairValue() {\r\n return this.rangeCrosshairValue;\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value.\r\n * <P>\r\n * Registered listeners are notified that the plot has been modified, but\r\n * only if the crosshair is visible.\r\n *\r\n * @param value the new value.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value) {\r\n setRangeCrosshairValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value and sends a {@link PlotChangeEvent} to\r\n * all registered listeners, but only if the crosshair is visible.\r\n *\r\n * @param value the new value.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value, boolean notify) {\r\n this.rangeCrosshairValue = value;\r\n if (isRangeCrosshairVisible() && notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the crosshair (if visible).\r\n *\r\n * @return The crosshair stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairStroke(Stroke)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public Stroke getRangeCrosshairStroke() {\r\n return this.rangeCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the new crosshair stroke (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public void setRangeCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeCrosshairStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the range crosshair paint.\r\n *\r\n * @return The crosshair paint (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairPaint(Paint)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public Paint getRangeCrosshairPaint() {\r\n return this.rangeCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to color the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the new crosshair paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public void setRangeCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the fixed domain axis space.\r\n *\r\n * @return The fixed domain axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedDomainAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedDomainAxisSpace() {\r\n return this.fixedDomainAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space) {\r\n setFixedDomainAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n *\r\n * @since 1.0.9\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedDomainAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the fixed range axis space.\r\n *\r\n * @return The fixed range axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedRangeAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedRangeAxisSpace() {\r\n return this.fixedRangeAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space) {\r\n setFixedRangeAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n *\r\n * @since 1.0.9\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedRangeAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if panning is enabled for the domain axes,\r\n * and <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isDomainPannable() {\r\n return this.domainPannable;\r\n }\r\n\r\n /**\r\n * Sets the flag that enables or disables panning of the plot along the\r\n * domain axes.\r\n *\r\n * @param pannable the new flag value.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setDomainPannable(boolean pannable) {\r\n this.domainPannable = pannable;\r\n }\r\n\r\n /**\r\n * Returns {@code true} if panning is enabled for the range axis/axes,\r\n * and {@code false} otherwise. The default value is {@code false}.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isRangePannable() {\r\n return this.rangePannable;\r\n }\r\n\r\n /**\r\n * Sets the flag that enables or disables panning of the plot along\r\n * the range axis/axes.\r\n *\r\n * @param pannable the new flag value.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangePannable(boolean pannable) {\r\n this.rangePannable = pannable;\r\n }\r\n\r\n /**\r\n * Pans the domain axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panDomainAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n if (!isDomainPannable()) {\r\n return;\r\n }\r\n int domainAxisCount = getDomainAxisCount();\r\n for (int i = 0; i < domainAxisCount; i++) {\r\n ValueAxis axis = getDomainAxis(i);\r\n if (axis == null) {\r\n continue;\r\n }\r\n if (axis.isInverted()) {\r\n percent = -percent;\r\n }\r\n axis.pan(percent);\r\n }\r\n }\r\n\r\n /**\r\n * Pans the range axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panRangeAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n if (!isRangePannable()) {\r\n return;\r\n }\r\n int rangeAxisCount = getRangeAxisCount();\r\n for (int i = 0; i < rangeAxisCount; i++) {\r\n ValueAxis axis = getRangeAxis(i);\r\n if (axis == null) {\r\n continue;\r\n }\r\n if (axis.isInverted()) {\r\n percent = -percent;\r\n }\r\n axis.pan(percent);\r\n }\r\n }\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point (in Java2D space).\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo info,\r\n Point2D source) {\r\n // delegate to other method\r\n zoomDomainAxes(factor, info, source, false);\r\n }\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point (in Java2D space).\r\n * @param useAnchor use source point as zoom anchor?\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n\r\n // perform the zoom on each domain axis\r\n for (ValueAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis == null) {\r\n continue;\r\n }\r\n if (useAnchor) {\r\n // get the relevant source coordinate given the plot orientation\r\n double sourceX = source.getX();\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n sourceX = source.getY();\r\n }\r\n double anchorX = xAxis.java2DToValue(sourceX,\r\n info.getDataArea(), getDomainAxisEdge());\r\n xAxis.resizeRange2(factor, anchorX);\r\n } else {\r\n xAxis.resizeRange(factor);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the domain axis/axes. The new lower and upper bounds are\r\n * specified as percentages of the current axis range, where 0 percent is\r\n * the current lower bound and 100 percent is the current upper bound.\r\n *\r\n * @param lowerPercent a percentage that determines the new lower bound\r\n * for the axis (e.g. 0.20 is twenty percent).\r\n * @param upperPercent a percentage that determines the new upper bound\r\n * for the axis (e.g. 0.80 is eighty percent).\r\n * @param info the plot rendering info.\r\n * @param source the source point (ignored).\r\n *\r\n * @see #zoomRangeAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomDomainAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo info, Point2D source) {\r\n for (ValueAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n xAxis.zoomRange(lowerPercent, upperPercent);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo info,\r\n Point2D source) {\r\n // delegate to other method\r\n zoomRangeAxes(factor, info, source, false);\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n * @param useAnchor a flag that controls whether or not the source point\r\n * is used for the zoom anchor.\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n\r\n // perform the zoom on each range axis\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis == null) {\r\n continue;\r\n }\r\n if (useAnchor) {\r\n // get the relevant source coordinate given the plot orientation\r\n double sourceY = source.getY();\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n sourceY = source.getX();\r\n }\r\n double anchorY = yAxis.java2DToValue(sourceY,\r\n info.getDataArea(), getRangeAxisEdge());\r\n yAxis.resizeRange2(factor, anchorY);\r\n } else {\r\n yAxis.resizeRange(factor);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the range axes.\r\n *\r\n * @param lowerPercent the lower bound.\r\n * @param upperPercent the upper bound.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n *\r\n * @see #zoomDomainAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomRangeAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo info, Point2D source) {\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.zoomRange(lowerPercent, upperPercent);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code>, indicating that the domain axis/axes for this\r\n * plot are zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isRangeZoomable()\r\n */\r\n @Override\r\n public boolean isDomainZoomable() {\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code>, indicating that the range axis/axes for this\r\n * plot are zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isDomainZoomable()\r\n */\r\n @Override\r\n public boolean isRangeZoomable() {\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns the number of series in the primary dataset for this plot. If\r\n * the dataset is <code>null</code>, the method returns 0.\r\n *\r\n * @return The series count.\r\n */\r\n public int getSeriesCount() {\r\n int result = 0;\r\n XYDataset dataset = getDataset();\r\n if (dataset != null) {\r\n result = dataset.getSeriesCount();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the fixed legend items, if any.\r\n *\r\n * @return The legend items (possibly <code>null</code>).\r\n *\r\n * @see #setFixedLegendItems(LegendItemCollection)\r\n */\r\n public LegendItemCollection getFixedLegendItems() {\r\n return this.fixedLegendItems;\r\n }\r\n\r\n /**\r\n * Sets the fixed legend items for the plot. Leave this set to\r\n * <code>null</code> if you prefer the legend items to be created\r\n * automatically.\r\n *\r\n * @param items the legend items (<code>null</code> permitted).\r\n *\r\n * @see #getFixedLegendItems()\r\n */\r\n public void setFixedLegendItems(LegendItemCollection items) {\r\n this.fixedLegendItems = items;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the legend items for the plot. Each legend item is generated by\r\n * the plot's renderer, since the renderer is responsible for the visual\r\n * representation of the data.\r\n *\r\n * @return The legend items.\r\n */\r\n @Override\r\n public LegendItemCollection getLegendItems() {\r\n if (this.fixedLegendItems != null) {\r\n return this.fixedLegendItems;\r\n }\r\n LegendItemCollection result = new LegendItemCollection();\r\n for (XYDataset dataset : this.datasets.values()) {\r\n if (dataset == null) {\r\n continue;\r\n }\r\n int datasetIndex = indexOf(dataset);\r\n XYItemRenderer renderer = getRenderer(datasetIndex);\r\n if (renderer == null) {\r\n renderer = getRenderer(0);\r\n }\r\n if (renderer != null) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int i = 0; i < seriesCount; i++) {\r\n if (renderer.isSeriesVisible(i)\r\n && renderer.isSeriesVisibleInLegend(i)) {\r\n LegendItem item = renderer.getLegendItem(\r\n datasetIndex, i);\r\n if (item != null) {\r\n result.add(item);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Tests this plot for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof XYPlot)) {\r\n return false;\r\n }\r\n XYPlot that = (XYPlot) obj;\r\n if (this.weight != that.weight) {\r\n return false;\r\n }\r\n if (this.orientation != that.orientation) {\r\n return false;\r\n }\r\n if (!this.domainAxes.equals(that.domainAxes)) {\r\n return false;\r\n }\r\n if (!this.domainAxisLocations.equals(that.domainAxisLocations)) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairLockedOnData\r\n != that.rangeCrosshairLockedOnData) {\r\n return false;\r\n }\r\n if (this.domainGridlinesVisible != that.domainGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.rangeGridlinesVisible != that.rangeGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.domainMinorGridlinesVisible\r\n != that.domainMinorGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.rangeMinorGridlinesVisible\r\n != that.rangeMinorGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.domainZeroBaselineVisible != that.domainZeroBaselineVisible) {\r\n return false;\r\n }\r\n if (this.rangeZeroBaselineVisible != that.rangeZeroBaselineVisible) {\r\n return false;\r\n }\r\n if (this.domainCrosshairVisible != that.domainCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.domainCrosshairValue != that.domainCrosshairValue) {\r\n return false;\r\n }\r\n if (this.domainCrosshairLockedOnData\r\n != that.domainCrosshairLockedOnData) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairVisible != that.rangeCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairValue != that.rangeCrosshairValue) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.axisOffset, that.axisOffset)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.renderers, that.renderers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeAxes, that.rangeAxes)) {\r\n return false;\r\n }\r\n if (!this.rangeAxisLocations.equals(that.rangeAxisLocations)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToDomainAxesMap,\r\n that.datasetToDomainAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToRangeAxesMap,\r\n that.datasetToRangeAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainGridlineStroke,\r\n that.domainGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainGridlinePaint,\r\n that.domainGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeGridlineStroke,\r\n that.rangeGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeGridlinePaint,\r\n that.rangeGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainMinorGridlineStroke,\r\n that.domainMinorGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainMinorGridlinePaint,\r\n that.domainMinorGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeMinorGridlineStroke,\r\n that.rangeMinorGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeMinorGridlinePaint,\r\n that.rangeMinorGridlinePaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainZeroBaselinePaint,\r\n that.domainZeroBaselinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainZeroBaselineStroke,\r\n that.domainZeroBaselineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeZeroBaselinePaint,\r\n that.rangeZeroBaselinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeZeroBaselineStroke,\r\n that.rangeZeroBaselineStroke)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainCrosshairStroke,\r\n that.domainCrosshairStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainCrosshairPaint,\r\n that.domainCrosshairPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeCrosshairStroke,\r\n that.rangeCrosshairStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeCrosshairPaint,\r\n that.rangeCrosshairPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundDomainMarkers,\r\n that.foregroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundDomainMarkers,\r\n that.backgroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundRangeMarkers,\r\n that.foregroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundRangeMarkers,\r\n that.backgroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundDomainMarkers,\r\n that.foregroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundDomainMarkers,\r\n that.backgroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundRangeMarkers,\r\n that.foregroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundRangeMarkers,\r\n that.backgroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.annotations, that.annotations)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.fixedLegendItems,\r\n that.fixedLegendItems)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainTickBandPaint,\r\n that.domainTickBandPaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeTickBandPaint,\r\n that.rangeTickBandPaint)) {\r\n return false;\r\n }\r\n if (!this.quadrantOrigin.equals(that.quadrantOrigin)) {\r\n return false;\r\n }\r\n for (int i = 0; i < 4; i++) {\r\n if (!PaintUtilities.equal(this.quadrantPaint[i],\r\n that.quadrantPaint[i])) {\r\n return false;\r\n }\r\n }\r\n if (!ObjectUtilities.equal(this.shadowGenerator,\r\n that.shadowGenerator)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a clone of the plot.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException this can occur if some component of\r\n * the plot cannot be cloned.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n XYPlot clone = (XYPlot) super.clone();\r\n clone.domainAxes = CloneUtils.cloneMapValues(this.domainAxes);\r\n for (ValueAxis axis : clone.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n clone.rangeAxes = CloneUtils.cloneMapValues(this.rangeAxes);\r\n for (ValueAxis axis : clone.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n clone.domainAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.domainAxisLocations);\r\n clone.rangeAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.rangeAxisLocations);\r\n\r\n // the datasets are not cloned, but listeners need to be added...\r\n clone.datasets = new HashMap<Integer, XYDataset>(this.datasets);\r\n for (XYDataset dataset : clone.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(clone);\r\n }\r\n }\r\n\r\n clone.datasetToDomainAxesMap = new TreeMap();\r\n clone.datasetToDomainAxesMap.putAll(this.datasetToDomainAxesMap);\r\n clone.datasetToRangeAxesMap = new TreeMap();\r\n clone.datasetToRangeAxesMap.putAll(this.datasetToRangeAxesMap);\r\n\r\n clone.renderers = CloneUtils.cloneMapValues(this.renderers);\r\n for (XYItemRenderer renderer : clone.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.setPlot(clone);\r\n renderer.addChangeListener(clone);\r\n }\r\n }\r\n clone.foregroundDomainMarkers = (Map) ObjectUtilities.clone(\r\n this.foregroundDomainMarkers);\r\n clone.backgroundDomainMarkers = (Map) ObjectUtilities.clone(\r\n this.backgroundDomainMarkers);\r\n clone.foregroundRangeMarkers = (Map) ObjectUtilities.clone(\r\n this.foregroundRangeMarkers);\r\n clone.backgroundRangeMarkers = (Map) ObjectUtilities.clone(\r\n this.backgroundRangeMarkers);\r\n clone.annotations = (List) ObjectUtilities.deepClone(this.annotations);\r\n if (this.fixedDomainAxisSpace != null) {\r\n clone.fixedDomainAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedDomainAxisSpace);\r\n }\r\n if (this.fixedRangeAxisSpace != null) {\r\n clone.fixedRangeAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedRangeAxisSpace);\r\n }\r\n if (this.fixedLegendItems != null) {\r\n clone.fixedLegendItems\r\n = (LegendItemCollection) this.fixedLegendItems.clone();\r\n }\r\n clone.quadrantOrigin = (Point2D) ObjectUtilities.clone(\r\n this.quadrantOrigin);\r\n clone.quadrantPaint = this.quadrantPaint.clone();\r\n return clone;\r\n\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.domainGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.domainGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.domainMinorGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.domainMinorGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeMinorGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeMinorGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeZeroBaselineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeZeroBaselinePaint, stream);\r\n SerialUtilities.writeStroke(this.domainCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.domainCrosshairPaint, stream);\r\n SerialUtilities.writeStroke(this.rangeCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.rangeCrosshairPaint, stream);\r\n SerialUtilities.writePaint(this.domainTickBandPaint, stream);\r\n SerialUtilities.writePaint(this.rangeTickBandPaint, stream);\r\n SerialUtilities.writePoint2D(this.quadrantOrigin, stream);\r\n for (int i = 0; i < 4; i++) {\r\n SerialUtilities.writePaint(this.quadrantPaint[i], stream);\r\n }\r\n SerialUtilities.writeStroke(this.domainZeroBaselineStroke, stream);\r\n SerialUtilities.writePaint(this.domainZeroBaselinePaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n\r\n stream.defaultReadObject();\r\n this.domainGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.domainGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.domainMinorGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.domainMinorGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeMinorGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeMinorGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeZeroBaselineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeZeroBaselinePaint = SerialUtilities.readPaint(stream);\r\n this.domainCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.domainCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.rangeCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.rangeCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.domainTickBandPaint = SerialUtilities.readPaint(stream);\r\n this.rangeTickBandPaint = SerialUtilities.readPaint(stream);\r\n this.quadrantOrigin = SerialUtilities.readPoint2D(stream);\r\n this.quadrantPaint = new Paint[4];\r\n for (int i = 0; i < 4; i++) {\r\n this.quadrantPaint[i] = SerialUtilities.readPaint(stream);\r\n }\r\n\r\n this.domainZeroBaselineStroke = SerialUtilities.readStroke(stream);\r\n this.domainZeroBaselinePaint = SerialUtilities.readPaint(stream);\r\n\r\n // register the plot as a listener with its axes, datasets, and\r\n // renderers...\r\n for (ValueAxis axis : this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n axis.addChangeListener(this);\r\n }\r\n }\r\n for (ValueAxis axis : this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n axis.addChangeListener(this);\r\n }\r\n }\r\n for (XYDataset dataset : this.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n }\r\n for (XYItemRenderer renderer : this.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.addChangeListener(this);\r\n }\r\n }\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "DefaultTableXYDataset", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/xy/DefaultTableXYDataset.java", "snippet": "public class DefaultTableXYDataset extends AbstractIntervalXYDataset\r\n implements TableXYDataset, IntervalXYDataset, DomainInfo,\r\n PublicCloneable {\r\n\r\n /**\r\n * Storage for the data - this list will contain zero, one or many\r\n * XYSeries objects.\r\n */\r\n private List data = null;\r\n\r\n /** Storage for the x values. */\r\n private HashSet xPoints = null;\r\n\r\n /** A flag that controls whether or not events are propogated. */\r\n private boolean propagateEvents = true;\r\n\r\n /** A flag that controls auto pruning. */\r\n private boolean autoPrune = false;\r\n\r\n /** The delegate used to control the interval width. */\r\n private IntervalXYDelegate intervalDelegate;\r\n\r\n /**\r\n * Creates a new empty dataset.\r\n */\r\n public DefaultTableXYDataset() {\r\n this(false);\r\n }\r\n\r\n /**\r\n * Creates a new empty dataset.\r\n *\r\n * @param autoPrune a flag that controls whether or not x-values are\r\n * removed whenever the corresponding y-values are all\r\n * <code>null</code>.\r\n */\r\n public DefaultTableXYDataset(boolean autoPrune) {\r\n this.autoPrune = autoPrune;\r\n this.data = new ArrayList();\r\n this.xPoints = new HashSet();\r\n this.intervalDelegate = new IntervalXYDelegate(this, false);\r\n addChangeListener(this.intervalDelegate);\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not x-values are removed from\r\n * the dataset when the corresponding y-values are all <code>null</code>.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean isAutoPrune() {\r\n return this.autoPrune;\r\n }\r\n\r\n /**\r\n * Adds a series to the collection and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners. The series should be configured to NOT\r\n * allow duplicate x-values.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n */\r\n public void addSeries(XYSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n if (series.getAllowDuplicateXValues()) {\r\n throw new IllegalArgumentException(\r\n \"Cannot accept XYSeries that allow duplicate values. \"\r\n + \"Use XYSeries(seriesName, <sort>, false) constructor.\"\r\n );\r\n }\r\n updateXPoints(series);\r\n this.data.add(series);\r\n series.addChangeListener(this);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Adds any unique x-values from 'series' to the dataset, and also adds any\r\n * x-values that are in the dataset but not in 'series' to the series.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n */\r\n private void updateXPoints(XYSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n HashSet seriesXPoints = new HashSet();\r\n boolean savedState = this.propagateEvents;\r\n this.propagateEvents = false;\r\n for (int itemNo = 0; itemNo < series.getItemCount(); itemNo++) {\r\n Number xValue = series.getX(itemNo);\r\n seriesXPoints.add(xValue);\r\n if (!this.xPoints.contains(xValue)) {\r\n this.xPoints.add(xValue);\r\n int seriesCount = this.data.size();\r\n for (int seriesNo = 0; seriesNo < seriesCount; seriesNo++) {\r\n XYSeries dataSeries = (XYSeries) this.data.get(seriesNo);\r\n if (!dataSeries.equals(series)) {\r\n dataSeries.add(xValue, null);\r\n }\r\n }\r\n }\r\n }\r\n Iterator iterator = this.xPoints.iterator();\r\n while (iterator.hasNext()) {\r\n Number xPoint = (Number) iterator.next();\r\n if (!seriesXPoints.contains(xPoint)) {\r\n series.add(xPoint, null);\r\n }\r\n }\r\n this.propagateEvents = savedState;\r\n }\r\n\r\n /**\r\n * Updates the x-values for all the series in the dataset.\r\n */\r\n public void updateXPoints() {\r\n this.propagateEvents = false;\r\n for (int s = 0; s < this.data.size(); s++) {\r\n updateXPoints((XYSeries) this.data.get(s));\r\n }\r\n if (this.autoPrune) {\r\n prune();\r\n }\r\n this.propagateEvents = true;\r\n }\r\n\r\n /**\r\n * Returns the number of series in the collection.\r\n *\r\n * @return The series count.\r\n */\r\n @Override\r\n public int getSeriesCount() {\r\n return this.data.size();\r\n }\r\n\r\n /**\r\n * Returns the number of x values in the dataset.\r\n *\r\n * @return The number of x values in the dataset.\r\n */\r\n @Override\r\n public int getItemCount() {\r\n if (this.xPoints == null) {\r\n return 0;\r\n }\r\n else {\r\n return this.xPoints.size();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a series.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The series (never <code>null</code>).\r\n */\r\n public XYSeries getSeries(int series) {\r\n if ((series < 0) || (series >= getSeriesCount())) {\r\n throw new IllegalArgumentException(\"Index outside valid range.\");\r\n }\r\n return (XYSeries) this.data.get(series);\r\n }\r\n\r\n /**\r\n * Returns the key for a series.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The key for a series.\r\n */\r\n @Override\r\n public Comparable getSeriesKey(int series) {\r\n // check arguments...delegated\r\n return getSeries(series).getKey();\r\n }\r\n\r\n /**\r\n * Returns the number of items in the specified series.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The number of items in the specified series.\r\n */\r\n @Override\r\n public int getItemCount(int series) {\r\n // check arguments...delegated\r\n return getSeries(series).getItemCount();\r\n }\r\n\r\n /**\r\n * Returns the x-value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The x-value for the specified series and item.\r\n */\r\n @Override\r\n public Number getX(int series, int item) {\r\n XYSeries s = (XYSeries) this.data.get(series);\r\n return s.getX(item);\r\n\r\n }\r\n\r\n /**\r\n * Returns the starting X value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The starting X value.\r\n */\r\n @Override\r\n public Number getStartX(int series, int item) {\r\n return this.intervalDelegate.getStartX(series, item);\r\n }\r\n\r\n /**\r\n * Returns the ending X value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The ending X value.\r\n */\r\n @Override\r\n public Number getEndX(int series, int item) {\r\n return this.intervalDelegate.getEndX(series, item);\r\n }\r\n\r\n /**\r\n * Returns the y-value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param index the index of the item of interest (zero-based).\r\n *\r\n * @return The y-value for the specified series and item (possibly\r\n * <code>null</code>).\r\n */\r\n @Override\r\n public Number getY(int series, int index) {\r\n XYSeries s = (XYSeries) this.data.get(series);\r\n return s.getY(index);\r\n }\r\n\r\n /**\r\n * Returns the starting Y value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The starting Y value.\r\n */\r\n @Override\r\n public Number getStartY(int series, int item) {\r\n return getY(series, item);\r\n }\r\n\r\n /**\r\n * Returns the ending Y value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The ending Y value.\r\n */\r\n @Override\r\n public Number getEndY(int series, int item) {\r\n return getY(series, item);\r\n }\r\n\r\n /**\r\n * Removes all the series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n */\r\n public void removeAllSeries() {\r\n\r\n // Unregister the collection as a change listener to each series in\r\n // the collection.\r\n for (int i = 0; i < this.data.size(); i++) {\r\n XYSeries series = (XYSeries) this.data.get(i);\r\n series.removeChangeListener(this);\r\n }\r\n\r\n // Remove all the series from the collection and notify listeners.\r\n this.data.clear();\r\n this.xPoints.clear();\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes a series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n */\r\n public void removeSeries(XYSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n if (this.data.contains(series)) {\r\n series.removeChangeListener(this);\r\n this.data.remove(series);\r\n if (this.data.isEmpty()) {\r\n this.xPoints.clear();\r\n }\r\n fireDatasetChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Removes a series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series (zero based index).\r\n */\r\n public void removeSeries(int series) {\r\n\r\n // check arguments...\r\n if ((series < 0) || (series > getSeriesCount())) {\r\n throw new IllegalArgumentException(\"Index outside valid range.\");\r\n }\r\n\r\n // fetch the series, remove the change listener, then remove the series.\r\n XYSeries s = (XYSeries) this.data.get(series);\r\n s.removeChangeListener(this);\r\n this.data.remove(series);\r\n if (this.data.isEmpty()) {\r\n this.xPoints.clear();\r\n }\r\n else if (this.autoPrune) {\r\n prune();\r\n }\r\n fireDatasetChanged();\r\n\r\n }\r\n\r\n /**\r\n * Removes the items from all series for a given x value.\r\n *\r\n * @param x the x-value.\r\n */\r\n public void removeAllValuesForX(Number x) {\r\n ParamChecks.nullNotPermitted(x, \"x\");\r\n boolean savedState = this.propagateEvents;\r\n this.propagateEvents = false;\r\n for (int s = 0; s < this.data.size(); s++) {\r\n XYSeries series = (XYSeries) this.data.get(s);\r\n series.remove(x);\r\n }\r\n this.propagateEvents = savedState;\r\n this.xPoints.remove(x);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if all the y-values for the specified x-value\r\n * are <code>null</code> and <code>false</code> otherwise.\r\n *\r\n * @param x the x-value.\r\n *\r\n * @return A boolean.\r\n */\r\n protected boolean canPrune(Number x) {\r\n for (int s = 0; s < this.data.size(); s++) {\r\n XYSeries series = (XYSeries) this.data.get(s);\r\n if (series.getY(series.indexOf(x)) != null) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Removes all x-values for which all the y-values are <code>null</code>.\r\n */\r\n public void prune() {\r\n HashSet hs = (HashSet) this.xPoints.clone();\r\n Iterator iterator = hs.iterator();\r\n while (iterator.hasNext()) {\r\n Number x = (Number) iterator.next();\r\n if (canPrune(x)) {\r\n removeAllValuesForX(x);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * This method receives notification when a series belonging to the dataset\r\n * changes. It responds by updating the x-points for the entire dataset\r\n * and sending a {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param event information about the change.\r\n */\r\n @Override\r\n public void seriesChanged(SeriesChangeEvent event) {\r\n if (this.propagateEvents) {\r\n updateXPoints();\r\n fireDatasetChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Tests this collection for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof DefaultTableXYDataset)) {\r\n return false;\r\n }\r\n DefaultTableXYDataset that = (DefaultTableXYDataset) obj;\r\n if (this.autoPrune != that.autoPrune) {\r\n return false;\r\n }\r\n if (this.propagateEvents != that.propagateEvents) {\r\n return false;\r\n }\r\n if (!this.intervalDelegate.equals(that.intervalDelegate)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.data, that.data)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result;\r\n result = (this.data != null ? this.data.hashCode() : 0);\r\n result = 29 * result\r\n + (this.xPoints != null ? this.xPoints.hashCode() : 0);\r\n result = 29 * result + (this.propagateEvents ? 1 : 0);\r\n result = 29 * result + (this.autoPrune ? 1 : 0);\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns an independent copy of this dataset.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if there is some reason that cloning\r\n * cannot be performed.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n DefaultTableXYDataset clone = (DefaultTableXYDataset) super.clone();\r\n int seriesCount = this.data.size();\r\n clone.data = new java.util.ArrayList(seriesCount);\r\n for (int i = 0; i < seriesCount; i++) {\r\n XYSeries series = (XYSeries) this.data.get(i);\r\n clone.data.add(series.clone());\r\n }\r\n\r\n clone.intervalDelegate = new IntervalXYDelegate(clone);\r\n // need to configure the intervalDelegate to match the original\r\n clone.intervalDelegate.setFixedIntervalWidth(getIntervalWidth());\r\n clone.intervalDelegate.setAutoWidth(isAutoWidth());\r\n clone.intervalDelegate.setIntervalPositionFactor(\r\n getIntervalPositionFactor());\r\n clone.updateXPoints();\r\n return clone;\r\n }\r\n\r\n /**\r\n * Returns the minimum x-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The minimum value.\r\n */\r\n @Override\r\n public double getDomainLowerBound(boolean includeInterval) {\r\n return this.intervalDelegate.getDomainLowerBound(includeInterval);\r\n }\r\n\r\n /**\r\n * Returns the maximum x-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The maximum value.\r\n */\r\n @Override\r\n public double getDomainUpperBound(boolean includeInterval) {\r\n return this.intervalDelegate.getDomainUpperBound(includeInterval);\r\n }\r\n\r\n /**\r\n * Returns the range of the values in this dataset's domain.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The range.\r\n */\r\n @Override\r\n public Range getDomainBounds(boolean includeInterval) {\r\n if (includeInterval) {\r\n return this.intervalDelegate.getDomainBounds(includeInterval);\r\n }\r\n else {\r\n return DatasetUtilities.iterateDomainBounds(this, includeInterval);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the interval position factor.\r\n *\r\n * @return The interval position factor.\r\n */\r\n public double getIntervalPositionFactor() {\r\n return this.intervalDelegate.getIntervalPositionFactor();\r\n }\r\n\r\n /**\r\n * Sets the interval position factor. Must be between 0.0 and 1.0 inclusive.\r\n * If the factor is 0.5, the gap is in the middle of the x values. If it\r\n * is lesser than 0.5, the gap is farther to the left and if greater than\r\n * 0.5 it gets farther to the right.\r\n *\r\n * @param d the new interval position factor.\r\n */\r\n public void setIntervalPositionFactor(double d) {\r\n this.intervalDelegate.setIntervalPositionFactor(d);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * returns the full interval width.\r\n *\r\n * @return The interval width to use.\r\n */\r\n public double getIntervalWidth() {\r\n return this.intervalDelegate.getIntervalWidth();\r\n }\r\n\r\n /**\r\n * Sets the interval width to a fixed value, and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param d the new interval width (must be &gt; 0).\r\n */\r\n public void setIntervalWidth(double d) {\r\n this.intervalDelegate.setFixedIntervalWidth(d);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns whether the interval width is automatically calculated or not.\r\n *\r\n * @return A flag that determines whether or not the interval width is\r\n * automatically calculated.\r\n */\r\n public boolean isAutoWidth() {\r\n return this.intervalDelegate.isAutoWidth();\r\n }\r\n\r\n /**\r\n * Sets the flag that indicates whether the interval width is automatically\r\n * calculated or not.\r\n *\r\n * @param b a boolean.\r\n */\r\n public void setAutoWidth(boolean b) {\r\n this.intervalDelegate.setAutoWidth(b);\r\n fireDatasetChanged();\r\n }\r\n\r\n}\r" }, { "identifier": "XYSeries", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/xy/XYSeries.java", "snippet": "public class XYSeries extends Series implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n static final long serialVersionUID = -5908509288197150436L;\r\n\r\n // In version 0.9.12, in response to several developer requests, I changed\r\n // the 'data' attribute from 'private' to 'protected', so that others can\r\n // make subclasses that work directly with the underlying data structure.\r\n\r\n /** Storage for the data items in the series. */\r\n protected List data;\r\n\r\n /** The maximum number of items for the series. */\r\n private int maximumItemCount = Integer.MAX_VALUE;\r\n\r\n /**\r\n * A flag that controls whether the items are automatically sorted\r\n * (by x-value ascending).\r\n */\r\n private boolean autoSort;\r\n\r\n /** A flag that controls whether or not duplicate x-values are allowed. */\r\n private boolean allowDuplicateXValues;\r\n\r\n /** The lowest x-value in the series, excluding Double.NaN values. */\r\n private double minX;\r\n\r\n /** The highest x-value in the series, excluding Double.NaN values. */\r\n private double maxX;\r\n\r\n /** The lowest y-value in the series, excluding Double.NaN values. */\r\n private double minY;\r\n\r\n /** The highest y-value in the series, excluding Double.NaN values. */\r\n private double maxY;\r\n\r\n /**\r\n * Creates a new empty series. By default, items added to the series will\r\n * be sorted into ascending order by x-value, and duplicate x-values will\r\n * be allowed (these defaults can be modified with another constructor).\r\n *\r\n * @param key the series key (<code>null</code> not permitted).\r\n */\r\n public XYSeries(Comparable key) {\r\n this(key, true, true);\r\n }\r\n\r\n /**\r\n * Constructs a new empty series, with the auto-sort flag set as requested,\r\n * and duplicate values allowed.\r\n *\r\n * @param key the series key (<code>null</code> not permitted).\r\n * @param autoSort a flag that controls whether or not the items in the\r\n * series are sorted.\r\n */\r\n public XYSeries(Comparable key, boolean autoSort) {\r\n this(key, autoSort, true);\r\n }\r\n\r\n /**\r\n * Constructs a new xy-series that contains no data. You can specify\r\n * whether or not duplicate x-values are allowed for the series.\r\n *\r\n * @param key the series key (<code>null</code> not permitted).\r\n * @param autoSort a flag that controls whether or not the items in the\r\n * series are sorted.\r\n * @param allowDuplicateXValues a flag that controls whether duplicate\r\n * x-values are allowed.\r\n */\r\n public XYSeries(Comparable key, boolean autoSort,\r\n boolean allowDuplicateXValues) {\r\n super(key);\r\n this.data = new java.util.ArrayList();\r\n this.autoSort = autoSort;\r\n this.allowDuplicateXValues = allowDuplicateXValues;\r\n this.minX = Double.NaN;\r\n this.maxX = Double.NaN;\r\n this.minY = Double.NaN;\r\n this.maxY = Double.NaN;\r\n }\r\n\r\n /**\r\n * Returns the smallest x-value in the series, ignoring any Double.NaN\r\n * values. This method returns Double.NaN if there is no smallest x-value\r\n * (for example, when the series is empty).\r\n *\r\n * @return The smallest x-value.\r\n *\r\n * @see #getMaxX()\r\n *\r\n * @since 1.0.13\r\n */\r\n public double getMinX() {\r\n return this.minX;\r\n }\r\n\r\n /**\r\n * Returns the largest x-value in the series, ignoring any Double.NaN\r\n * values. This method returns Double.NaN if there is no largest x-value\r\n * (for example, when the series is empty).\r\n *\r\n * @return The largest x-value.\r\n *\r\n * @see #getMinX()\r\n *\r\n * @since 1.0.13\r\n */\r\n public double getMaxX() {\r\n return this.maxX;\r\n }\r\n\r\n /**\r\n * Returns the smallest y-value in the series, ignoring any null and\r\n * Double.NaN values. This method returns Double.NaN if there is no\r\n * smallest y-value (for example, when the series is empty).\r\n *\r\n * @return The smallest y-value.\r\n *\r\n * @see #getMaxY()\r\n *\r\n * @since 1.0.13\r\n */\r\n public double getMinY() {\r\n return this.minY;\r\n }\r\n\r\n /**\r\n * Returns the largest y-value in the series, ignoring any Double.NaN\r\n * values. This method returns Double.NaN if there is no largest y-value\r\n * (for example, when the series is empty).\r\n *\r\n * @return The largest y-value.\r\n *\r\n * @see #getMinY()\r\n *\r\n * @since 1.0.13\r\n */\r\n public double getMaxY() {\r\n return this.maxY;\r\n }\r\n\r\n /**\r\n * Updates the cached values for the minimum and maximum data values.\r\n *\r\n * @param item the item added (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.13\r\n */\r\n private void updateBoundsForAddedItem(XYDataItem item) {\r\n double x = item.getXValue();\r\n this.minX = minIgnoreNaN(this.minX, x);\r\n this.maxX = maxIgnoreNaN(this.maxX, x);\r\n if (item.getY() != null) {\r\n double y = item.getYValue();\r\n this.minY = minIgnoreNaN(this.minY, y);\r\n this.maxY = maxIgnoreNaN(this.maxY, y);\r\n }\r\n }\r\n\r\n /**\r\n * Updates the cached values for the minimum and maximum data values on\r\n * the basis that the specified item has just been removed.\r\n *\r\n * @param item the item added (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.13\r\n */\r\n private void updateBoundsForRemovedItem(XYDataItem item) {\r\n boolean itemContributesToXBounds = false;\r\n boolean itemContributesToYBounds = false;\r\n double x = item.getXValue();\r\n if (!Double.isNaN(x)) {\r\n if (x <= this.minX || x >= this.maxX) {\r\n itemContributesToXBounds = true;\r\n }\r\n }\r\n if (item.getY() != null) {\r\n double y = item.getYValue();\r\n if (!Double.isNaN(y)) {\r\n if (y <= this.minY || y >= this.maxY) {\r\n itemContributesToYBounds = true;\r\n }\r\n }\r\n }\r\n if (itemContributesToYBounds) {\r\n findBoundsByIteration();\r\n }\r\n else if (itemContributesToXBounds) {\r\n if (getAutoSort()) {\r\n this.minX = getX(0).doubleValue();\r\n this.maxX = getX(getItemCount() - 1).doubleValue();\r\n }\r\n else {\r\n findBoundsByIteration();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Finds the bounds of the x and y values for the series, by iterating\r\n * through all the data items.\r\n *\r\n * @since 1.0.13\r\n */\r\n private void findBoundsByIteration() {\r\n this.minX = Double.NaN;\r\n this.maxX = Double.NaN;\r\n this.minY = Double.NaN;\r\n this.maxY = Double.NaN;\r\n Iterator iterator = this.data.iterator();\r\n while (iterator.hasNext()) {\r\n XYDataItem item = (XYDataItem) iterator.next();\r\n updateBoundsForAddedItem(item);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether the items in the series are\r\n * automatically sorted. There is no setter for this flag, it must be\r\n * defined in the series constructor.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean getAutoSort() {\r\n return this.autoSort;\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether duplicate x-values are allowed.\r\n * This flag can only be set in the constructor.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean getAllowDuplicateXValues() {\r\n return this.allowDuplicateXValues;\r\n }\r\n\r\n /**\r\n * Returns the number of items in the series.\r\n *\r\n * @return The item count.\r\n *\r\n * @see #getItems()\r\n */\r\n @Override\r\n public int getItemCount() {\r\n return this.data.size();\r\n }\r\n\r\n /**\r\n * Returns the list of data items for the series (the list contains\r\n * {@link XYDataItem} objects and is unmodifiable).\r\n *\r\n * @return The list of data items.\r\n */\r\n public List getItems() {\r\n return Collections.unmodifiableList(this.data);\r\n }\r\n\r\n /**\r\n * Returns the maximum number of items that will be retained in the series.\r\n * The default value is <code>Integer.MAX_VALUE</code>.\r\n *\r\n * @return The maximum item count.\r\n *\r\n * @see #setMaximumItemCount(int)\r\n */\r\n public int getMaximumItemCount() {\r\n return this.maximumItemCount;\r\n }\r\n\r\n /**\r\n * Sets the maximum number of items that will be retained in the series.\r\n * If you add a new item to the series such that the number of items will\r\n * exceed the maximum item count, then the first element in the series is\r\n * automatically removed, ensuring that the maximum item count is not\r\n * exceeded.\r\n * <p>\r\n * Typically this value is set before the series is populated with data,\r\n * but if it is applied later, it may cause some items to be removed from\r\n * the series (in which case a {@link SeriesChangeEvent} will be sent to\r\n * all registered listeners).\r\n *\r\n * @param maximum the maximum number of items for the series.\r\n */\r\n public void setMaximumItemCount(int maximum) {\r\n this.maximumItemCount = maximum;\r\n int remove = this.data.size() - maximum;\r\n if (remove > 0) {\r\n this.data.subList(0, remove).clear();\r\n findBoundsByIteration();\r\n fireSeriesChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and sends a {@link SeriesChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param item the (x, y) item (<code>null</code> not permitted).\r\n */\r\n public void add(XYDataItem item) {\r\n // argument checking delegated...\r\n add(item, true);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and sends a {@link SeriesChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param x the x value.\r\n * @param y the y value.\r\n */\r\n public void add(double x, double y) {\r\n add(new Double(x), new Double(y), true);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and, if requested, sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param x the x value.\r\n * @param y the y value.\r\n * @param notify a flag that controls whether or not a\r\n * {@link SeriesChangeEvent} is sent to all registered\r\n * listeners.\r\n */\r\n public void add(double x, double y, boolean notify) {\r\n add(new Double(x), new Double(y), notify);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and sends a {@link SeriesChangeEvent} to\r\n * all registered listeners. The unusual pairing of parameter types is to\r\n * make it easier to add <code>null</code> y-values.\r\n *\r\n * @param x the x value.\r\n * @param y the y value (<code>null</code> permitted).\r\n */\r\n public void add(double x, Number y) {\r\n add(new Double(x), y);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and, if requested, sends a\r\n * {@link SeriesChangeEvent} to all registered listeners. The unusual\r\n * pairing of parameter types is to make it easier to add null y-values.\r\n *\r\n * @param x the x value.\r\n * @param y the y value (<code>null</code> permitted).\r\n * @param notify a flag that controls whether or not a\r\n * {@link SeriesChangeEvent} is sent to all registered\r\n * listeners.\r\n */\r\n public void add(double x, Number y, boolean notify) {\r\n add(new Double(x), y, notify);\r\n }\r\n\r\n /**\r\n * Adds a new data item to the series (in the correct position if the\r\n * <code>autoSort</code> flag is set for the series) and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n * <P>\r\n * Throws an exception if the x-value is a duplicate AND the\r\n * allowDuplicateXValues flag is false.\r\n *\r\n * @param x the x-value (<code>null</code> not permitted).\r\n * @param y the y-value (<code>null</code> permitted).\r\n *\r\n * @throws SeriesException if the x-value is a duplicate and the\r\n * <code>allowDuplicateXValues</code> flag is not set for this series.\r\n */\r\n public void add(Number x, Number y) {\r\n // argument checking delegated...\r\n add(x, y, true);\r\n }\r\n\r\n /**\r\n * Adds new data to the series and, if requested, sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n * <P>\r\n * Throws an exception if the x-value is a duplicate AND the\r\n * allowDuplicateXValues flag is false.\r\n *\r\n * @param x the x-value (<code>null</code> not permitted).\r\n * @param y the y-value (<code>null</code> permitted).\r\n * @param notify a flag the controls whether or not a\r\n * {@link SeriesChangeEvent} is sent to all registered\r\n * listeners.\r\n */\r\n public void add(Number x, Number y, boolean notify) {\r\n // delegate argument checking to XYDataItem...\r\n XYDataItem item = new XYDataItem(x, y);\r\n add(item, notify);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and, if requested, sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param item the (x, y) item (<code>null</code> not permitted).\r\n * @param notify a flag that controls whether or not a\r\n * {@link SeriesChangeEvent} is sent to all registered\r\n * listeners.\r\n */\r\n public void add(XYDataItem item, boolean notify) {\r\n ParamChecks.nullNotPermitted(item, \"item\");\r\n item = (XYDataItem) item.clone();\r\n if (this.autoSort) {\r\n int index = Collections.binarySearch(this.data, item);\r\n if (index < 0) {\r\n this.data.add(-index - 1, item);\r\n }\r\n else {\r\n if (this.allowDuplicateXValues) {\r\n // need to make sure we are adding *after* any duplicates\r\n int size = this.data.size();\r\n while (index < size && item.compareTo(\r\n this.data.get(index)) == 0) {\r\n index++;\r\n }\r\n if (index < this.data.size()) {\r\n this.data.add(index, item);\r\n }\r\n else {\r\n this.data.add(item);\r\n }\r\n }\r\n else {\r\n throw new SeriesException(\"X-value already exists.\");\r\n }\r\n }\r\n }\r\n else {\r\n if (!this.allowDuplicateXValues) {\r\n // can't allow duplicate values, so we need to check whether\r\n // there is an item with the given x-value already\r\n int index = indexOf(item.getX());\r\n if (index >= 0) {\r\n throw new SeriesException(\"X-value already exists.\");\r\n }\r\n }\r\n this.data.add(item);\r\n }\r\n updateBoundsForAddedItem(item);\r\n if (getItemCount() > this.maximumItemCount) {\r\n XYDataItem removed = (XYDataItem) this.data.remove(0);\r\n updateBoundsForRemovedItem(removed);\r\n }\r\n if (notify) {\r\n fireSeriesChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Deletes a range of items from the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param start the start index (zero-based).\r\n * @param end the end index (zero-based).\r\n */\r\n public void delete(int start, int end) {\r\n this.data.subList(start, end + 1).clear();\r\n findBoundsByIteration();\r\n fireSeriesChanged();\r\n }\r\n\r\n /**\r\n * Removes the item at the specified index and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param index the index.\r\n *\r\n * @return The item removed.\r\n */\r\n public XYDataItem remove(int index) {\r\n XYDataItem removed = (XYDataItem) this.data.remove(index);\r\n updateBoundsForRemovedItem(removed);\r\n fireSeriesChanged();\r\n return removed;\r\n }\r\n\r\n /**\r\n * Removes an item with the specified x-value and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners. Note that when\r\n * a series permits multiple items with the same x-value, this method\r\n * could remove any one of the items with that x-value.\r\n *\r\n * @param x the x-value.\r\n\r\n * @return The item removed.\r\n */\r\n public XYDataItem remove(Number x) {\r\n return remove(indexOf(x));\r\n }\r\n\r\n /**\r\n * Removes all data items from the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n */\r\n public void clear() {\r\n if (this.data.size() > 0) {\r\n this.data.clear();\r\n this.minX = Double.NaN;\r\n this.maxX = Double.NaN;\r\n this.minY = Double.NaN;\r\n this.maxY = Double.NaN;\r\n fireSeriesChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Return the data item with the specified index.\r\n *\r\n * @param index the index.\r\n *\r\n * @return The data item with the specified index.\r\n */\r\n public XYDataItem getDataItem(int index) {\r\n XYDataItem item = (XYDataItem) this.data.get(index);\r\n return (XYDataItem) item.clone();\r\n }\r\n\r\n /**\r\n * Return the data item with the specified index.\r\n *\r\n * @param index the index.\r\n *\r\n * @return The data item with the specified index.\r\n *\r\n * @since 1.0.14\r\n */\r\n XYDataItem getRawDataItem(int index) {\r\n return (XYDataItem) this.data.get(index);\r\n }\r\n\r\n /**\r\n * Returns the x-value at the specified index.\r\n *\r\n * @param index the index (zero-based).\r\n *\r\n * @return The x-value (never <code>null</code>).\r\n */\r\n public Number getX(int index) {\r\n return getRawDataItem(index).getX();\r\n }\r\n\r\n /**\r\n * Returns the y-value at the specified index.\r\n *\r\n * @param index the index (zero-based).\r\n *\r\n * @return The y-value (possibly <code>null</code>).\r\n */\r\n public Number getY(int index) {\r\n return getRawDataItem(index).getY();\r\n }\r\n\r\n /**\r\n * Updates the value of an item in the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param index the item (zero based index).\r\n * @param y the new value (<code>null</code> permitted).\r\n *\r\n * @deprecated Renamed {@link #updateByIndex(int, Number)} to avoid\r\n * confusion with the {@link #update(Number, Number)} method.\r\n */\r\n public void update(int index, Number y) {\r\n XYDataItem item = getRawDataItem(index);\r\n\r\n // figure out if we need to iterate through all the y-values\r\n boolean iterate = false;\r\n double oldY = item.getYValue();\r\n if (!Double.isNaN(oldY)) {\r\n iterate = oldY <= this.minY || oldY >= this.maxY;\r\n }\r\n item.setY(y);\r\n\r\n if (iterate) {\r\n findBoundsByIteration();\r\n }\r\n else if (y != null) {\r\n double yy = y.doubleValue();\r\n this.minY = minIgnoreNaN(this.minY, yy);\r\n this.maxY = maxIgnoreNaN(this.maxY, yy);\r\n }\r\n fireSeriesChanged();\r\n }\r\n\r\n /**\r\n * A function to find the minimum of two values, but ignoring any\r\n * Double.NaN values.\r\n *\r\n * @param a the first value.\r\n * @param b the second value.\r\n *\r\n * @return The minimum of the two values.\r\n */\r\n private double minIgnoreNaN(double a, double b) {\r\n if (Double.isNaN(a)) {\r\n return b;\r\n }\r\n if (Double.isNaN(b)) {\r\n return a;\r\n }\r\n return Math.min(a, b);\r\n }\r\n\r\n /**\r\n * A function to find the maximum of two values, but ignoring any\r\n * Double.NaN values.\r\n *\r\n * @param a the first value.\r\n * @param b the second value.\r\n *\r\n * @return The maximum of the two values.\r\n */\r\n private double maxIgnoreNaN(double a, double b) {\r\n if (Double.isNaN(a)) {\r\n return b;\r\n }\r\n if (Double.isNaN(b)) {\r\n return a;\r\n }\r\n return Math.max(a, b);\r\n }\r\n\r\n /**\r\n * Updates the value of an item in the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param index the item (zero based index).\r\n * @param y the new value (<code>null</code> permitted).\r\n *\r\n * @since 1.0.1\r\n */\r\n public void updateByIndex(int index, Number y) {\r\n update(index, y);\r\n }\r\n\r\n /**\r\n * Updates an item in the series.\r\n *\r\n * @param x the x-value (<code>null</code> not permitted).\r\n * @param y the y-value (<code>null</code> permitted).\r\n *\r\n * @throws SeriesException if there is no existing item with the specified\r\n * x-value.\r\n */\r\n public void update(Number x, Number y) {\r\n int index = indexOf(x);\r\n if (index < 0) {\r\n throw new SeriesException(\"No observation for x = \" + x);\r\n }\r\n updateByIndex(index, y);\r\n }\r\n\r\n /**\r\n * Adds or updates an item in the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param x the x-value.\r\n * @param y the y-value.\r\n *\r\n * @return The item that was overwritten, if any.\r\n *\r\n * @since 1.0.10\r\n */\r\n public XYDataItem addOrUpdate(double x, double y) {\r\n return addOrUpdate(new Double(x), new Double(y));\r\n }\r\n\r\n /**\r\n * Adds or updates an item in the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param x the x-value (<code>null</code> not permitted).\r\n * @param y the y-value (<code>null</code> permitted).\r\n *\r\n * @return A copy of the overwritten data item, or <code>null</code> if no\r\n * item was overwritten.\r\n */\r\n public XYDataItem addOrUpdate(Number x, Number y) {\r\n // defer argument checking\r\n return addOrUpdate(new XYDataItem(x, y));\r\n }\r\n\r\n /**\r\n * Adds or updates an item in the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param item the data item (<code>null</code> not permitted).\r\n *\r\n * @return A copy of the overwritten data item, or <code>null</code> if no\r\n * item was overwritten.\r\n *\r\n * @since 1.0.14\r\n */\r\n public XYDataItem addOrUpdate(XYDataItem item) {\r\n ParamChecks.nullNotPermitted(item, \"item\");\r\n if (this.allowDuplicateXValues) {\r\n add(item);\r\n return null;\r\n }\r\n\r\n // if we get to here, we know that duplicate X values are not permitted\r\n XYDataItem overwritten = null;\r\n int index = indexOf(item.getX());\r\n if (index >= 0) {\r\n XYDataItem existing = (XYDataItem) this.data.get(index);\r\n overwritten = (XYDataItem) existing.clone();\r\n // figure out if we need to iterate through all the y-values\r\n boolean iterate = false;\r\n double oldY = existing.getYValue();\r\n if (!Double.isNaN(oldY)) {\r\n iterate = oldY <= this.minY || oldY >= this.maxY;\r\n }\r\n existing.setY(item.getY());\r\n\r\n if (iterate) {\r\n findBoundsByIteration();\r\n }\r\n else if (item.getY() != null) {\r\n double yy = item.getY().doubleValue();\r\n this.minY = minIgnoreNaN(this.minY, yy);\r\n this.maxY = maxIgnoreNaN(this.maxY, yy);\r\n }\r\n }\r\n else {\r\n // if the series is sorted, the negative index is a result from\r\n // Collections.binarySearch() and tells us where to insert the\r\n // new item...otherwise it will be just -1 and we should just\r\n // append the value to the list...\r\n item = (XYDataItem) item.clone();\r\n if (this.autoSort) {\r\n this.data.add(-index - 1, item);\r\n }\r\n else {\r\n this.data.add(item);\r\n }\r\n updateBoundsForAddedItem(item);\r\n\r\n // check if this addition will exceed the maximum item count...\r\n if (getItemCount() > this.maximumItemCount) {\r\n XYDataItem removed = (XYDataItem) this.data.remove(0);\r\n updateBoundsForRemovedItem(removed);\r\n }\r\n }\r\n fireSeriesChanged();\r\n return overwritten;\r\n }\r\n\r\n /**\r\n * Returns the index of the item with the specified x-value, or a negative\r\n * index if the series does not contain an item with that x-value. Be\r\n * aware that for an unsorted series, the index is found by iterating\r\n * through all items in the series.\r\n *\r\n * @param x the x-value (<code>null</code> not permitted).\r\n *\r\n * @return The index.\r\n */\r\n public int indexOf(Number x) {\r\n if (this.autoSort) {\r\n return Collections.binarySearch(this.data, new XYDataItem(x, null));\r\n }\r\n else {\r\n for (int i = 0; i < this.data.size(); i++) {\r\n XYDataItem item = (XYDataItem) this.data.get(i);\r\n if (item.getX().equals(x)) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n }\r\n }\r\n\r\n /**\r\n * Returns a new array containing the x and y values from this series.\r\n *\r\n * @return A new array containing the x and y values from this series.\r\n *\r\n * @since 1.0.4\r\n */\r\n public double[][] toArray() {\r\n int itemCount = getItemCount();\r\n double[][] result = new double[2][itemCount];\r\n for (int i = 0; i < itemCount; i++) {\r\n result[0][i] = this.getX(i).doubleValue();\r\n Number y = getY(i);\r\n if (y != null) {\r\n result[1][i] = y.doubleValue();\r\n }\r\n else {\r\n result[1][i] = Double.NaN;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a clone of the series.\r\n *\r\n * @return A clone of the series.\r\n *\r\n * @throws CloneNotSupportedException if there is a cloning problem.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n XYSeries clone = (XYSeries) super.clone();\r\n clone.data = (List) ObjectUtilities.deepClone(this.data);\r\n return clone;\r\n }\r\n\r\n /**\r\n * Creates a new series by copying a subset of the data in this time series.\r\n *\r\n * @param start the index of the first item to copy.\r\n * @param end the index of the last item to copy.\r\n *\r\n * @return A series containing a copy of this series from start until end.\r\n *\r\n * @throws CloneNotSupportedException if there is a cloning problem.\r\n */\r\n public XYSeries createCopy(int start, int end)\r\n throws CloneNotSupportedException {\r\n\r\n XYSeries copy = (XYSeries) super.clone();\r\n copy.data = new java.util.ArrayList();\r\n if (this.data.size() > 0) {\r\n for (int index = start; index <= end; index++) {\r\n XYDataItem item = (XYDataItem) this.data.get(index);\r\n XYDataItem clone = (XYDataItem) item.clone();\r\n try {\r\n copy.add(clone);\r\n }\r\n catch (SeriesException e) {\r\n throw new RuntimeException(\r\n \"Unable to add cloned data item.\", e);\r\n }\r\n }\r\n }\r\n return copy;\r\n\r\n }\r\n\r\n /**\r\n * Tests this series for equality with an arbitrary object.\r\n *\r\n * @param obj the object to test against for equality\r\n * (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof XYSeries)) {\r\n return false;\r\n }\r\n if (!super.equals(obj)) {\r\n return false;\r\n }\r\n XYSeries that = (XYSeries) obj;\r\n if (this.maximumItemCount != that.maximumItemCount) {\r\n return false;\r\n }\r\n if (this.autoSort != that.autoSort) {\r\n return false;\r\n }\r\n if (this.allowDuplicateXValues != that.allowDuplicateXValues) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.data, that.data)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result = super.hashCode();\r\n // it is too slow to look at every data item, so let's just look at\r\n // the first, middle and last items...\r\n int count = getItemCount();\r\n if (count > 0) {\r\n XYDataItem item = getRawDataItem(0);\r\n result = 29 * result + item.hashCode();\r\n }\r\n if (count > 1) {\r\n XYDataItem item = getRawDataItem(count - 1);\r\n result = 29 * result + item.hashCode();\r\n }\r\n if (count > 2) {\r\n XYDataItem item = getRawDataItem(count / 2);\r\n result = 29 * result + item.hashCode();\r\n }\r\n result = 29 * result + this.maximumItemCount;\r\n result = 29 * result + (this.autoSort ? 1 : 0);\r\n result = 29 * result + (this.allowDuplicateXValues ? 1 : 0);\r\n return result;\r\n }\r\n\r\n}\r" }, { "identifier": "XYSeriesCollection", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/xy/XYSeriesCollection.java", "snippet": "public class XYSeriesCollection extends AbstractIntervalXYDataset\r\n implements IntervalXYDataset, DomainInfo, RangeInfo, \r\n VetoableChangeListener, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -7590013825931496766L;\r\n\r\n /** The series that are included in the collection. */\r\n private List data;\r\n\r\n /** The interval delegate (used to calculate the start and end x-values). */\r\n private IntervalXYDelegate intervalDelegate;\r\n\r\n /**\r\n * Constructs an empty dataset.\r\n */\r\n public XYSeriesCollection() {\r\n this(null);\r\n }\r\n\r\n /**\r\n * Constructs a dataset and populates it with a single series.\r\n *\r\n * @param series the series (<code>null</code> ignored).\r\n */\r\n public XYSeriesCollection(XYSeries series) {\r\n this.data = new java.util.ArrayList();\r\n this.intervalDelegate = new IntervalXYDelegate(this, false);\r\n addChangeListener(this.intervalDelegate);\r\n if (series != null) {\r\n this.data.add(series);\r\n series.addChangeListener(this);\r\n series.addVetoableChangeListener(this);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the order of the domain (X) values, if this is known.\r\n *\r\n * @return The domain order.\r\n */\r\n @Override\r\n public DomainOrder getDomainOrder() {\r\n int seriesCount = getSeriesCount();\r\n for (int i = 0; i < seriesCount; i++) {\r\n XYSeries s = getSeries(i);\r\n if (!s.getAutoSort()) {\r\n return DomainOrder.NONE; // we can't be sure of the order\r\n }\r\n }\r\n return DomainOrder.ASCENDING;\r\n }\r\n\r\n /**\r\n * Adds a series to the collection and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n * \r\n * @throws IllegalArgumentException if the key for the series is null or\r\n * not unique within the dataset.\r\n */\r\n public void addSeries(XYSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n if (getSeriesIndex(series.getKey()) >= 0) {\r\n throw new IllegalArgumentException(\r\n \"This dataset already contains a series with the key \" \r\n + series.getKey());\r\n }\r\n this.data.add(series);\r\n series.addChangeListener(this);\r\n series.addVetoableChangeListener(this);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes a series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n */\r\n public void removeSeries(int series) {\r\n if ((series < 0) || (series >= getSeriesCount())) {\r\n throw new IllegalArgumentException(\"Series index out of bounds.\");\r\n }\r\n XYSeries s = (XYSeries) this.data.get(series);\r\n if (s != null) {\r\n removeSeries(s);\r\n }\r\n }\r\n\r\n /**\r\n * Removes a series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n */\r\n public void removeSeries(XYSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n if (this.data.contains(series)) {\r\n series.removeChangeListener(this);\r\n series.removeVetoableChangeListener(this);\r\n this.data.remove(series);\r\n fireDatasetChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Removes all the series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n */\r\n public void removeAllSeries() {\r\n // Unregister the collection as a change listener to each series in\r\n // the collection.\r\n for (int i = 0; i < this.data.size(); i++) {\r\n XYSeries series = (XYSeries) this.data.get(i);\r\n series.removeChangeListener(this);\r\n series.removeVetoableChangeListener(this);\r\n }\r\n\r\n // Remove all the series from the collection and notify listeners.\r\n this.data.clear();\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns the number of series in the collection.\r\n *\r\n * @return The series count.\r\n */\r\n @Override\r\n public int getSeriesCount() {\r\n return this.data.size();\r\n }\r\n\r\n /**\r\n * Returns a list of all the series in the collection.\r\n *\r\n * @return The list (which is unmodifiable).\r\n */\r\n public List getSeries() {\r\n return Collections.unmodifiableList(this.data);\r\n }\r\n\r\n /**\r\n * Returns the index of the specified series, or -1 if that series is not\r\n * present in the dataset.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n *\r\n * @return The series index.\r\n *\r\n * @since 1.0.6\r\n */\r\n public int indexOf(XYSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n return this.data.indexOf(series);\r\n }\r\n\r\n /**\r\n * Returns a series from the collection.\r\n *\r\n * @param series the series index (zero-based).\r\n *\r\n * @return The series.\r\n *\r\n * @throws IllegalArgumentException if <code>series</code> is not in the\r\n * range <code>0</code> to <code>getSeriesCount() - 1</code>.\r\n */\r\n public XYSeries getSeries(int series) {\r\n if ((series < 0) || (series >= getSeriesCount())) {\r\n throw new IllegalArgumentException(\"Series index out of bounds\");\r\n }\r\n return (XYSeries) this.data.get(series);\r\n }\r\n\r\n /**\r\n * Returns a series from the collection.\r\n *\r\n * @param key the key (<code>null</code> not permitted).\r\n *\r\n * @return The series with the specified key.\r\n *\r\n * @throws UnknownKeyException if <code>key</code> is not found in the\r\n * collection.\r\n *\r\n * @since 1.0.9\r\n */\r\n public XYSeries getSeries(Comparable key) {\r\n ParamChecks.nullNotPermitted(key, \"key\");\r\n Iterator iterator = this.data.iterator();\r\n while (iterator.hasNext()) {\r\n XYSeries series = (XYSeries) iterator.next();\r\n if (key.equals(series.getKey())) {\r\n return series;\r\n }\r\n }\r\n throw new UnknownKeyException(\"Key not found: \" + key);\r\n }\r\n\r\n /**\r\n * Returns the key for a series.\r\n *\r\n * @param series the series index (in the range <code>0</code> to\r\n * <code>getSeriesCount() - 1</code>).\r\n *\r\n * @return The key for a series.\r\n *\r\n * @throws IllegalArgumentException if <code>series</code> is not in the\r\n * specified range.\r\n */\r\n @Override\r\n public Comparable getSeriesKey(int series) {\r\n // defer argument checking\r\n return getSeries(series).getKey();\r\n }\r\n\r\n /**\r\n * Returns the index of the series with the specified key, or -1 if no\r\n * series has that key.\r\n * \r\n * @param key the key (<code>null</code> not permitted).\r\n * \r\n * @return The index.\r\n * \r\n * @since 1.0.14\r\n */\r\n public int getSeriesIndex(Comparable key) {\r\n ParamChecks.nullNotPermitted(key, \"key\");\r\n int seriesCount = getSeriesCount();\r\n for (int i = 0; i < seriesCount; i++) {\r\n XYSeries series = (XYSeries) this.data.get(i);\r\n if (key.equals(series.getKey())) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the number of items in the specified series.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The item count.\r\n *\r\n * @throws IllegalArgumentException if <code>series</code> is not in the\r\n * range <code>0</code> to <code>getSeriesCount() - 1</code>.\r\n */\r\n @Override\r\n public int getItemCount(int series) {\r\n // defer argument checking\r\n return getSeries(series).getItemCount();\r\n }\r\n\r\n /**\r\n * Returns the x-value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The value.\r\n */\r\n @Override\r\n public Number getX(int series, int item) {\r\n XYSeries s = (XYSeries) this.data.get(series);\r\n return s.getX(item);\r\n }\r\n\r\n /**\r\n * Returns the starting X value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The starting X value.\r\n */\r\n @Override\r\n public Number getStartX(int series, int item) {\r\n return this.intervalDelegate.getStartX(series, item);\r\n }\r\n\r\n /**\r\n * Returns the ending X value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The ending X value.\r\n */\r\n @Override\r\n public Number getEndX(int series, int item) {\r\n return this.intervalDelegate.getEndX(series, item);\r\n }\r\n\r\n /**\r\n * Returns the y-value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param index the index of the item of interest (zero-based).\r\n *\r\n * @return The value (possibly <code>null</code>).\r\n */\r\n @Override\r\n public Number getY(int series, int index) {\r\n XYSeries s = (XYSeries) this.data.get(series);\r\n return s.getY(index);\r\n }\r\n\r\n /**\r\n * Returns the starting Y value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The starting Y value.\r\n */\r\n @Override\r\n public Number getStartY(int series, int item) {\r\n return getY(series, item);\r\n }\r\n\r\n /**\r\n * Returns the ending Y value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The ending Y value.\r\n */\r\n @Override\r\n public Number getEndY(int series, int item) {\r\n return getY(series, item);\r\n }\r\n\r\n /**\r\n * Tests this collection for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof XYSeriesCollection)) {\r\n return false;\r\n }\r\n XYSeriesCollection that = (XYSeriesCollection) obj;\r\n if (!this.intervalDelegate.equals(that.intervalDelegate)) {\r\n return false;\r\n }\r\n return ObjectUtilities.equal(this.data, that.data);\r\n }\r\n\r\n /**\r\n * Returns a clone of this instance.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if there is a problem.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n XYSeriesCollection clone = (XYSeriesCollection) super.clone();\r\n clone.data = (List) ObjectUtilities.deepClone(this.data);\r\n clone.intervalDelegate\r\n = (IntervalXYDelegate) this.intervalDelegate.clone();\r\n return clone;\r\n }\r\n\r\n /**\r\n * Returns a hash code.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int hash = 5;\r\n hash = HashUtilities.hashCode(hash, this.intervalDelegate);\r\n hash = HashUtilities.hashCode(hash, this.data);\r\n return hash;\r\n }\r\n\r\n /**\r\n * Returns the minimum x-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The minimum value.\r\n */\r\n @Override\r\n public double getDomainLowerBound(boolean includeInterval) {\r\n if (includeInterval) {\r\n return this.intervalDelegate.getDomainLowerBound(includeInterval);\r\n }\r\n double result = Double.NaN;\r\n int seriesCount = getSeriesCount();\r\n for (int s = 0; s < seriesCount; s++) {\r\n XYSeries series = getSeries(s);\r\n double lowX = series.getMinX();\r\n if (Double.isNaN(result)) {\r\n result = lowX;\r\n }\r\n else {\r\n if (!Double.isNaN(lowX)) {\r\n result = Math.min(result, lowX);\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the maximum x-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The maximum value.\r\n */\r\n @Override\r\n public double getDomainUpperBound(boolean includeInterval) {\r\n if (includeInterval) {\r\n return this.intervalDelegate.getDomainUpperBound(includeInterval);\r\n }\r\n else {\r\n double result = Double.NaN;\r\n int seriesCount = getSeriesCount();\r\n for (int s = 0; s < seriesCount; s++) {\r\n XYSeries series = getSeries(s);\r\n double hiX = series.getMaxX();\r\n if (Double.isNaN(result)) {\r\n result = hiX;\r\n }\r\n else {\r\n if (!Double.isNaN(hiX)) {\r\n result = Math.max(result, hiX);\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range of the values in this dataset's domain.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The range (or <code>null</code> if the dataset contains no\r\n * values).\r\n */\r\n @Override\r\n public Range getDomainBounds(boolean includeInterval) {\r\n if (includeInterval) {\r\n return this.intervalDelegate.getDomainBounds(includeInterval);\r\n }\r\n else {\r\n double lower = Double.POSITIVE_INFINITY;\r\n double upper = Double.NEGATIVE_INFINITY;\r\n int seriesCount = getSeriesCount();\r\n for (int s = 0; s < seriesCount; s++) {\r\n XYSeries series = getSeries(s);\r\n double minX = series.getMinX();\r\n if (!Double.isNaN(minX)) {\r\n lower = Math.min(lower, minX);\r\n }\r\n double maxX = series.getMaxX();\r\n if (!Double.isNaN(maxX)) {\r\n upper = Math.max(upper, maxX);\r\n }\r\n }\r\n if (lower > upper) {\r\n return null;\r\n }\r\n else {\r\n return new Range(lower, upper);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the interval width. This is used to calculate the start and end\r\n * x-values, if/when the dataset is used as an {@link IntervalXYDataset}.\r\n *\r\n * @return The interval width.\r\n */\r\n public double getIntervalWidth() {\r\n return this.intervalDelegate.getIntervalWidth();\r\n }\r\n\r\n /**\r\n * Sets the interval width and sends a {@link DatasetChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param width the width (negative values not permitted).\r\n */\r\n public void setIntervalWidth(double width) {\r\n if (width < 0.0) {\r\n throw new IllegalArgumentException(\"Negative 'width' argument.\");\r\n }\r\n this.intervalDelegate.setFixedIntervalWidth(width);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns the interval position factor.\r\n *\r\n * @return The interval position factor.\r\n */\r\n public double getIntervalPositionFactor() {\r\n return this.intervalDelegate.getIntervalPositionFactor();\r\n }\r\n\r\n /**\r\n * Sets the interval position factor. This controls where the x-value is in\r\n * relation to the interval surrounding the x-value (0.0 means the x-value\r\n * will be positioned at the start, 0.5 in the middle, and 1.0 at the end).\r\n *\r\n * @param factor the factor.\r\n */\r\n public void setIntervalPositionFactor(double factor) {\r\n this.intervalDelegate.setIntervalPositionFactor(factor);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns whether the interval width is automatically calculated or not.\r\n *\r\n * @return Whether the width is automatically calculated or not.\r\n */\r\n public boolean isAutoWidth() {\r\n return this.intervalDelegate.isAutoWidth();\r\n }\r\n\r\n /**\r\n * Sets the flag that indicates whether the interval width is automatically\r\n * calculated or not.\r\n *\r\n * @param b a boolean.\r\n */\r\n public void setAutoWidth(boolean b) {\r\n this.intervalDelegate.setAutoWidth(b);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns the range of the values in this dataset's range.\r\n *\r\n * @param includeInterval ignored.\r\n *\r\n * @return The range (or <code>null</code> if the dataset contains no\r\n * values).\r\n */\r\n @Override\r\n public Range getRangeBounds(boolean includeInterval) {\r\n double lower = Double.POSITIVE_INFINITY;\r\n double upper = Double.NEGATIVE_INFINITY;\r\n int seriesCount = getSeriesCount();\r\n for (int s = 0; s < seriesCount; s++) {\r\n XYSeries series = getSeries(s);\r\n double minY = series.getMinY();\r\n if (!Double.isNaN(minY)) {\r\n lower = Math.min(lower, minY);\r\n }\r\n double maxY = series.getMaxY();\r\n if (!Double.isNaN(maxY)) {\r\n upper = Math.max(upper, maxY);\r\n }\r\n }\r\n if (lower > upper) {\r\n return null;\r\n }\r\n else {\r\n return new Range(lower, upper);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the minimum y-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * y-interval is taken into account.\r\n *\r\n * @return The minimum value.\r\n */\r\n @Override\r\n public double getRangeLowerBound(boolean includeInterval) {\r\n double result = Double.NaN;\r\n int seriesCount = getSeriesCount();\r\n for (int s = 0; s < seriesCount; s++) {\r\n XYSeries series = getSeries(s);\r\n double lowY = series.getMinY();\r\n if (Double.isNaN(result)) {\r\n result = lowY;\r\n }\r\n else {\r\n if (!Double.isNaN(lowY)) {\r\n result = Math.min(result, lowY);\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the maximum y-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * y-interval is taken into account.\r\n *\r\n * @return The maximum value.\r\n */\r\n @Override\r\n public double getRangeUpperBound(boolean includeInterval) {\r\n double result = Double.NaN;\r\n int seriesCount = getSeriesCount();\r\n for (int s = 0; s < seriesCount; s++) {\r\n XYSeries series = getSeries(s);\r\n double hiY = series.getMaxY();\r\n if (Double.isNaN(result)) {\r\n result = hiY;\r\n }\r\n else {\r\n if (!Double.isNaN(hiY)) {\r\n result = Math.max(result, hiY);\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Receives notification that the key for one of the series in the \r\n * collection has changed, and vetos it if the key is already present in \r\n * the collection.\r\n * \r\n * @param e the event.\r\n * \r\n * @since 1.0.14\r\n */\r\n @Override\r\n public void vetoableChange(PropertyChangeEvent e)\r\n throws PropertyVetoException {\r\n // if it is not the series name, then we have no interest\r\n if (!\"Key\".equals(e.getPropertyName())) {\r\n return;\r\n }\r\n \r\n // to be defensive, let's check that the source series does in fact\r\n // belong to this collection\r\n Series s = (Series) e.getSource();\r\n if (getSeriesIndex(s.getKey()) == -1) {\r\n throw new IllegalStateException(\"Receiving events from a series \" +\r\n \"that does not belong to this collection.\");\r\n }\r\n // check if the new series name already exists for another series\r\n Comparable key = (Comparable) e.getNewValue();\r\n if (getSeriesIndex(key) >= 0) {\r\n throw new PropertyVetoException(\"Duplicate key2\", e);\r\n }\r\n }\r\n\r\n}\r" } ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import java.awt.Rectangle; import org.jfree.chart.JFreeChart; import org.jfree.chart.LegendItem; import org.jfree.chart.TestUtilities; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.util.PublicCloneable; import org.junit.Test;
94,369
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------ * XYAreaRenderer2Test.java * ------------------------ * (C) Copyright 2005-2013, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 24-May-2005 : Version 1 (DG); * 30-Nov-2006 : Extended testEquals() and testCloning() (DG); * 17-May-2007 : Added testGetLegendItemSeriesIndex() (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.chart.renderer.xy; /** * Tests for the {@link XYAreaRenderer2} class. */ public class XYAreaRenderer2Test { /** * Check that the equals() method distinguishes all fields. */ @Test public void testEquals() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); XYAreaRenderer2 r2 = new XYAreaRenderer2(); assertEquals(r1, r2); r1.setOutline(!r1.isOutline()); assertFalse(r1.equals(r2)); r2.setOutline(r1.isOutline()); assertTrue(r1.equals(r2)); r1.setLegendArea(new Rectangle(1, 2, 3, 4)); assertFalse(r1.equals(r2)); r2.setLegendArea(new Rectangle(1, 2, 3, 4)); assertTrue(r1.equals(r2)); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashcode() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); XYAreaRenderer2 r2 = new XYAreaRenderer2(); assertTrue(r1.equals(r2)); int h1 = r1.hashCode(); int h2 = r2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { XYAreaRenderer2 r1 = new XYAreaRenderer2(); Rectangle rect = new Rectangle(1, 2, 3, 4); r1.setLegendArea(rect); XYAreaRenderer2 r2 = (XYAreaRenderer2) r1.clone(); assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); // check independence rect.setBounds(99, 99, 99, 99); assertFalse(r1.equals(r2)); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); assertTrue(r1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); XYAreaRenderer2 r2 = (XYAreaRenderer2) TestUtilities.serialised(r1); assertEquals(r1, r2); } /** * Draws the chart with a <code>null</code> info object to make sure that * no exceptions are thrown (particularly by code in the renderer). */ @Test public void testDrawWithNullInfo() { try { DefaultTableXYDataset dataset = new DefaultTableXYDataset();
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------ * XYAreaRenderer2Test.java * ------------------------ * (C) Copyright 2005-2013, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 24-May-2005 : Version 1 (DG); * 30-Nov-2006 : Extended testEquals() and testCloning() (DG); * 17-May-2007 : Added testGetLegendItemSeriesIndex() (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.chart.renderer.xy; /** * Tests for the {@link XYAreaRenderer2} class. */ public class XYAreaRenderer2Test { /** * Check that the equals() method distinguishes all fields. */ @Test public void testEquals() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); XYAreaRenderer2 r2 = new XYAreaRenderer2(); assertEquals(r1, r2); r1.setOutline(!r1.isOutline()); assertFalse(r1.equals(r2)); r2.setOutline(r1.isOutline()); assertTrue(r1.equals(r2)); r1.setLegendArea(new Rectangle(1, 2, 3, 4)); assertFalse(r1.equals(r2)); r2.setLegendArea(new Rectangle(1, 2, 3, 4)); assertTrue(r1.equals(r2)); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashcode() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); XYAreaRenderer2 r2 = new XYAreaRenderer2(); assertTrue(r1.equals(r2)); int h1 = r1.hashCode(); int h2 = r2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { XYAreaRenderer2 r1 = new XYAreaRenderer2(); Rectangle rect = new Rectangle(1, 2, 3, 4); r1.setLegendArea(rect); XYAreaRenderer2 r2 = (XYAreaRenderer2) r1.clone(); assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); // check independence rect.setBounds(99, 99, 99, 99); assertFalse(r1.equals(r2)); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); assertTrue(r1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); XYAreaRenderer2 r2 = (XYAreaRenderer2) TestUtilities.serialised(r1); assertEquals(r1, r2); } /** * Draws the chart with a <code>null</code> info object to make sure that * no exceptions are thrown (particularly by code in the renderer). */ @Test public void testDrawWithNullInfo() { try { DefaultTableXYDataset dataset = new DefaultTableXYDataset();
XYSeries s1 = new XYSeries("Series 1", true, false);
6
2023-12-24 12:36:47+00:00
128k
A1anSong/jd_unidbg
unidbg-ios/src/main/java/com/github/unidbg/ios/ARM64SyscallHandler.java
[ { "identifier": "AbstractEmulator", "path": "unidbg-api/src/main/java/com/github/unidbg/AbstractEmulator.java", "snippet": "public abstract class AbstractEmulator<T extends NewFileIO> implements Emulator<T>, MemoryWriteListener {\n\n private static final Log log = LogFactory.getLog(AbstractEmulator.class);\n\n public static final long DEFAULT_TIMEOUT = 0;\n\n protected final Backend backend;\n\n private final int pid;\n\n protected long timeout = DEFAULT_TIMEOUT;\n\n private final RegisterContext registerContext;\n\n private final FileSystem<T> fileSystem;\n protected final SvcMemory svcMemory;\n\n private final Family family;\n\n protected final DateFormat dateFormat = new SimpleDateFormat(\"[HH:mm:ss SSS]\");\n\n public AbstractEmulator(boolean is64Bit, String processName, long svcBase, int svcSize, File rootDir, Family family, Collection<BackendFactory> backendFactories) {\n super();\n this.family = family;\n\n File targetDir = new File(\"target\");\n if (!targetDir.exists()) {\n targetDir = FileUtils.getTempDirectory();\n }\n if (rootDir == null) {\n rootDir = new File(targetDir, FileSystem.DEFAULT_ROOT_FS);\n }\n if (rootDir.isFile()) {\n throw new IllegalArgumentException(\"rootDir must be directory: \" + rootDir);\n }\n if (!rootDir.exists() && !rootDir.mkdirs()) {\n throw new IllegalStateException(\"mkdirs failed: \" + rootDir);\n }\n this.fileSystem = createFileSystem(rootDir);\n this.backend = BackendFactory.createBackend(this, is64Bit, backendFactories);\n this.processName = processName == null ? \"unidbg\" : processName;\n this.registerContext = createRegisterContext(backend);\n\n String name = ManagementFactory.getRuntimeMXBean().getName();\n String pid = name.split(\"@\")[0];\n this.pid = Integer.parseInt(pid) & 0x7fff;\n\n this.svcMemory = new ARMSvcMemory(svcBase, svcSize, this);\n this.threadDispatcher = createThreadDispatcher();\n\n this.backend.onInitialize();\n }\n\n protected ThreadDispatcher createThreadDispatcher() {\n return new UniThreadDispatcher(this);\n }\n\n @Override\n public final int getPageAlign() {\n int pageSize = backend.getPageSize();\n if (pageSize == 0) {\n pageSize = getPageAlignInternal();\n }\n return pageSize;\n }\n\n protected abstract int getPageAlignInternal();\n\n @Override\n public Family getFamily() {\n return family;\n }\n\n public final SvcMemory getSvcMemory() {\n return svcMemory;\n }\n\n @Override\n public final FileSystem<T> getFileSystem() {\n return fileSystem;\n }\n\n protected abstract FileSystem<T> createFileSystem(File rootDir);\n\n @Override\n public boolean is64Bit() {\n return getPointerSize() == 8;\n }\n\n @Override\n public boolean is32Bit() {\n return getPointerSize() == 4;\n }\n\n protected abstract RegisterContext createRegisterContext(Backend backend);\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public <V extends RegisterContext> V getContext() {\n return (V) registerContext;\n }\n\n protected abstract Memory createMemory(UnixSyscallHandler<T> syscallHandler, String[] envs);\n\n protected abstract Dlfcn createDyld(SvcMemory svcMemory);\n\n protected abstract UnixSyscallHandler<T> createSyscallHandler(SvcMemory svcMemory);\n\n protected abstract byte[] assemble(Iterable<String> assembly);\n\n private Debugger debugger;\n\n @Override\n public Debugger attach() {\n return attach(DebuggerType.CONSOLE);\n }\n\n @Override\n public Debugger attach(DebuggerType type) {\n if (debugger != null) {\n return debugger;\n }\n\n switch (type) {\n case GDB_SERVER:\n debugger = new GdbStub(this);\n break;\n case ANDROID_SERVER_V7:\n debugger = new AndroidServer(this, DebugServer.IDA_PROTOCOL_VERSION_V7);\n break;\n case CONSOLE:\n default:\n debugger = createConsoleDebugger();\n break;\n }\n if (debugger == null) {\n throw new UnsupportedOperationException();\n }\n\n this.backend.debugger_add(debugger, 1, 0, this);\n this.timeout = 0;\n return debugger;\n }\n\n protected abstract Debugger createConsoleDebugger();\n\n @Override\n public int getPid() {\n return pid;\n }\n\n @Override\n public final TraceHook traceRead(long begin, long end) {\n return traceRead(begin, end, null);\n }\n\n @Override\n public TraceHook traceRead(long begin, long end, TraceReadListener listener) {\n TraceMemoryHook hook = new TraceMemoryHook(true);\n if (listener != null) {\n hook.traceReadListener = listener;\n }\n backend.hook_add_new((ReadHook) hook, begin, end, this);\n return hook;\n }\n\n @Override\n public final TraceHook traceWrite(long begin, long end) {\n return traceWrite(begin, end, null);\n }\n\n private long traceSystemMemoryWriteBegin;\n private long traceSystemMemoryWriteEnd;\n private boolean traceSystemMemoryWrite;\n private TraceSystemMemoryWriteListener traceSystemMemoryWriteListener;\n\n @Override\n public void setTraceSystemMemoryWrite(long begin, long end, TraceSystemMemoryWriteListener listener) {\n traceSystemMemoryWrite = true;\n traceSystemMemoryWriteBegin = begin;\n traceSystemMemoryWriteEnd = end;\n traceSystemMemoryWriteListener = listener;\n }\n\n @Override\n public void onSystemWrite(long addr, byte[] data) {\n if (!traceSystemMemoryWrite) {\n return;\n }\n long max = Math.max(addr, traceSystemMemoryWriteBegin);\n long min = Math.min(addr + data.length, traceSystemMemoryWriteEnd);\n if (max < min) {\n byte[] buf = new byte[(int) (min - max)];\n System.arraycopy(data, (int) (max - addr), buf, 0, buf.length);\n if (traceSystemMemoryWriteListener != null) {\n traceSystemMemoryWriteListener.onWrite(this, addr, buf);\n } else {\n StringWriter writer = new StringWriter();\n writer.write(\"### System Memory WRITE at 0x\" + Long.toHexString(max) + \"\\n\");\n new Exception().printStackTrace(new PrintWriter(writer));\n Inspector.inspect(buf, writer.toString());\n }\n }\n }\n\n @Override\n public TraceHook traceWrite(long begin, long end, TraceWriteListener listener) {\n TraceMemoryHook hook = new TraceMemoryHook(false);\n if (listener != null) {\n hook.traceWriteListener = listener;\n }\n backend.hook_add_new((WriteHook) hook, begin, end, this);\n return hook;\n }\n\n @Override\n public final TraceHook traceRead() {\n return traceRead(1, 0);\n }\n\n @Override\n public final TraceHook traceWrite() {\n return traceWrite(1, 0);\n }\n\n @Override\n public final TraceHook traceCode() {\n return traceCode(1, 0);\n }\n\n @Override\n public final TraceHook traceCode(long begin, long end) {\n return traceCode(begin, end, null);\n }\n\n @Override\n public TraceHook traceCode(long begin, long end, TraceCodeListener listener) {\n AssemblyCodeDumper hook = new AssemblyCodeDumper(this, begin, end, listener);\n backend.hook_add_new(hook, begin, end, this);\n return hook;\n }\n\n @Override\n public void setTimeout(long timeout) {\n this.timeout = timeout;\n }\n\n private boolean running;\n\n @Override\n public boolean isRunning() {\n return running;\n }\n\n private final ThreadDispatcher threadDispatcher;\n\n @Override\n public ThreadDispatcher getThreadDispatcher() {\n return threadDispatcher;\n }\n\n @Override\n public boolean emulateSignal(int sig) {\n MainTask main = getSyscallHandler().createSignalHandlerTask(this, sig);\n if (main == null) {\n return false;\n } else {\n Memory memory = getMemory();\n long spBackup = memory.getStackPoint();\n try {\n threadDispatcher.runMainForResult(main);\n } finally {\n memory.setStackPoint(spBackup);\n }\n return true;\n }\n }\n\n protected final Number runMainForResult(MainTask task) {\n Memory memory = getMemory();\n long spBackup = memory.getStackPoint();\n try {\n return getThreadDispatcher().runMainForResult(task);\n } finally {\n memory.setStackPoint(spBackup);\n }\n }\n\n /**\n * @return <code>null</code>表示执行未完成,需要线程调度\n */\n public final Number emulate(long begin, long until) throws PopContextException {\n if (running) {\n backend.emu_stop();\n throw new IllegalStateException(\"running\");\n }\n if (is32Bit()) {\n begin &= 0xffffffffL;\n }\n\n final Pointer pointer = UnidbgPointer.pointer(this, begin);\n long start = 0;\n Thread exitHook = null;\n try {\n if (log.isDebugEnabled()) {\n log.debug(\"emulate \" + pointer + \" started sp=\" + getStackPointer());\n }\n start = System.currentTimeMillis();\n running = true;\n if (log.isDebugEnabled()) {\n exitHook = new Thread() {\n @Override\n public void run() {\n backend.emu_stop();\n Debugger debugger = attach();\n if (!debugger.isDebugging()) {\n debugger.debug();\n }\n }\n };\n Runtime.getRuntime().addShutdownHook(exitHook);\n }\n backend.emu_start(begin, until, 0, 0);\n if (is64Bit()) {\n return backend.reg_read(Arm64Const.UC_ARM64_REG_X0);\n } else {\n Number r0 = backend.reg_read(ArmConst.UC_ARM_REG_R0);\n Number r1 = backend.reg_read(ArmConst.UC_ARM_REG_R1);\n return (r0.intValue() & 0xffffffffL) | ((r1.intValue() & 0xffffffffL) << 32);\n }\n } catch (ThreadContextSwitchException e) {\n e.syncReturnValue(this);\n if (log.isTraceEnabled()) {\n e.printStackTrace();\n }\n return null;\n } catch (PopContextException e) {\n throw e;\n } catch (RuntimeException e) {\n return handleEmuException(e, pointer, start);\n } finally {\n if (exitHook != null) {\n Runtime.getRuntime().removeShutdownHook(exitHook);\n }\n running = false;\n\n if (log.isDebugEnabled()) {\n log.debug(\"emulate \" + pointer + \" finished sp=\" + getStackPointer() + \", offset=\" + (System.currentTimeMillis() - start) + \"ms\");\n }\n }\n }\n\n private int handleEmuException(RuntimeException e, Pointer pointer, long start) {\n boolean enterDebug = log.isDebugEnabled();\n if (enterDebug || !log.isWarnEnabled()) {\n e.printStackTrace();\n attach().debug();\n } else {\n String msg = e.getMessage();\n if (msg == null) {\n msg = e.getClass().getName();\n }\n log.warn(\"emulate \" + pointer + \" exception sp=\" + getStackPointer() + \", msg=\" + msg + \", offset=\" + (System.currentTimeMillis() - start) + \"ms\");\n }\n return -1;\n }\n\n public abstract Pointer getStackPointer();\n\n private boolean closed;\n\n @Override\n public synchronized final void close() throws IOException {\n if (closed) {\n throw new IOException(\"Already closed.\");\n }\n\n try {\n IOUtils.close(debugger);\n\n closeInternal();\n\n backend.destroy();\n } finally {\n closed = true;\n }\n }\n\n protected abstract void closeInternal();\n\n @Override\n public Backend getBackend() {\n return backend;\n }\n\n private final String processName;\n\n @Override\n public String getProcessName() {\n return processName == null ? \"unidbg\" : processName;\n }\n\n private final Map<String, Object> context = new HashMap<>();\n\n @Override\n public void set(String key, Object value) {\n context.put(key, value);\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public <V> V get(String key) {\n return (V) context.get(key);\n }\n\n protected abstract boolean isPaddingArgument();\n\n protected void dumpClass(String className) {\n throw new UnsupportedOperationException(\"dumpClass className=\" + className);\n }\n\n protected void searchClass(String keywords) {\n throw new UnsupportedOperationException(\"searchClass keywords=\" + keywords);\n }\n\n protected void dumpGPBProtobufMsg(String className) {\n throw new UnsupportedOperationException(\"dumpGPBProtobufMsg className=\" + className);\n }\n\n @Override\n public final void serialize(DataOutput out) throws IOException {\n out.writeUTF(getClass().getName());\n getMemory().serialize(out);\n getSvcMemory().serialize(out);\n getSyscallHandler().serialize(out);\n getDlfcn().serialize(out);\n }\n\n private static class Context {\n private final long ctx;\n private final int off;\n Context(long ctx, int off) {\n this.ctx = ctx;\n this.off = off;\n }\n void restoreAndFree(Backend backend) {\n backend.context_restore(ctx);\n backend.context_free(ctx);\n }\n }\n\n private final Stack<Context> contextStack = new Stack<>();\n\n @Override\n public void pushContext(int off) {\n long context = backend.context_alloc();\n backend.context_save(context);\n contextStack.push(new Context(context, off));\n }\n\n @Override\n public int popContext() {\n Context ctx = contextStack.pop();\n ctx.restoreAndFree(backend);\n return ctx.off;\n }\n\n}" }, { "identifier": "Emulator", "path": "unidbg-api/src/main/java/com/github/unidbg/Emulator.java", "snippet": "public interface Emulator<T extends NewFileIO> extends Closeable, ArmDisassembler, Serializable {\n\n int getPointerSize();\n\n boolean is64Bit();\n boolean is32Bit();\n\n int getPageAlign();\n\n /**\n * trace memory read\n */\n TraceHook traceRead();\n TraceHook traceRead(long begin, long end);\n TraceHook traceRead(long begin, long end, TraceReadListener listener);\n\n /**\n * trace memory write\n */\n TraceHook traceWrite();\n TraceHook traceWrite(long begin, long end);\n TraceHook traceWrite(long begin, long end, TraceWriteListener listener);\n\n void setTraceSystemMemoryWrite(long begin, long end, TraceSystemMemoryWriteListener listener);\n\n /**\n * trace instruction\n * note: low performance\n */\n TraceHook traceCode();\n TraceHook traceCode(long begin, long end);\n TraceHook traceCode(long begin, long end, TraceCodeListener listener);\n\n Number eFunc(long begin, Number... arguments);\n\n Number eEntry(long begin, long sp);\n\n /**\n * emulate signal handler\n * @param sig signal number\n * @return <code>true</code> means called handler function.\n */\n boolean emulateSignal(int sig);\n\n /**\n * 是否正在运行\n */\n boolean isRunning();\n\n /**\n * show all registers\n */\n void showRegs();\n\n /**\n * show registers\n */\n void showRegs(int... regs);\n\n Module loadLibrary(File libraryFile);\n Module loadLibrary(File libraryFile, boolean forceCallInit);\n\n Memory getMemory();\n\n Backend getBackend();\n\n int getPid();\n\n String getProcessName();\n\n Debugger attach();\n\n Debugger attach(DebuggerType type);\n\n FileSystem<T> getFileSystem();\n\n SvcMemory getSvcMemory();\n\n SyscallHandler<T> getSyscallHandler();\n\n Family getFamily();\n LibraryFile createURLibraryFile(URL url, String libName);\n\n Dlfcn getDlfcn();\n\n /**\n * @param timeout Duration to emulate the code (in microseconds). When this value is 0, we will emulate the code in infinite time, until the code is finished.\n */\n void setTimeout(long timeout);\n\n <V extends RegisterContext> V getContext();\n\n Unwinder getUnwinder();\n\n void pushContext(int off);\n int popContext();\n\n ThreadDispatcher getThreadDispatcher();\n\n long getReturnAddress();\n\n void set(String key, Object value);\n <V> V get(String key);\n\n}" }, { "identifier": "LongJumpException", "path": "unidbg-api/src/main/java/com/github/unidbg/LongJumpException.java", "snippet": "public abstract class LongJumpException extends BackendException {\n}" }, { "identifier": "StopEmulatorException", "path": "unidbg-api/src/main/java/com/github/unidbg/StopEmulatorException.java", "snippet": "public class StopEmulatorException extends BackendException {\n}" }, { "identifier": "Svc", "path": "unidbg-api/src/main/java/com/github/unidbg/Svc.java", "snippet": "public interface Svc {\n\n int PRE_CALLBACK_SYSCALL_NUMBER = 0x8866;\n int POST_CALLBACK_SYSCALL_NUMBER = 0x8888;\n\n UnidbgPointer onRegister(SvcMemory svcMemory, int svcNumber);\n\n long handle(Emulator<?> emulator);\n\n void handlePreCallback(Emulator<?> emulator);\n void handlePostCallback(Emulator<?> emulator);\n\n String getName();\n\n}" }, { "identifier": "ARM", "path": "unidbg-api/src/main/java/com/github/unidbg/arm/ARM.java", "snippet": "public class ARM {\n\n public static boolean isThumb(Backend backend) {\n return Cpsr.getArm(backend).isThumb();\n }\n\n /**\n * 是否为thumb32\n */\n static boolean isThumb32(short ins) {\n return (ins & 0xe000) == 0xe000 && (ins & 0x1800) != 0x0000;\n }\n\n public static void showThumbRegs(Emulator<?> emulator) {\n showRegs(emulator, ARM.THUMB_REGS);\n }\n\n public static void showRegs(Emulator<?> emulator, int[] regs) {\n Backend backend = emulator.getBackend();\n boolean thumb = isThumb(backend);\n if (regs == null || regs.length < 1) {\n regs = ARM.getAllRegisters(thumb);\n }\n StringBuilder builder = new StringBuilder();\n builder.append(\">>>\");\n for (int reg : regs) {\n Number number;\n int value;\n switch (reg) {\n case ArmConst.UC_ARM_REG_CPSR:\n Cpsr cpsr = Cpsr.getArm(backend);\n builder.append(String.format(Locale.US, \" cpsr: N=%d, Z=%d, C=%d, V=%d, T=%d, mode=0b\",\n cpsr.isNegative() ? 1 : 0,\n cpsr.isZero() ? 1 : 0,\n cpsr.hasCarry() ? 1 : 0,\n cpsr.isOverflow() ? 1 : 0,\n cpsr.isThumb() ? 1 : 0)).append(Integer.toBinaryString(cpsr.getMode()));\n break;\n case ArmConst.UC_ARM_REG_R0:\n number = backend.reg_read(reg);\n value = number.intValue();\n builder.append(String.format(Locale.US, \" r0=0x%x\", value));\n if (value < 0) {\n builder.append('(').append(value).append(')');\n }\n break;\n case ArmConst.UC_ARM_REG_R1:\n number = backend.reg_read(reg);\n value = number.intValue();\n builder.append(String.format(Locale.US, \" r1=0x%x\", value));\n break;\n case ArmConst.UC_ARM_REG_R2:\n number = backend.reg_read(reg);\n value = number.intValue();\n builder.append(String.format(Locale.US, \" r2=0x%x\", value));\n break;\n case ArmConst.UC_ARM_REG_R3:\n number = backend.reg_read(reg);\n value = number.intValue();\n builder.append(String.format(Locale.US, \" r3=0x%x\", value));\n break;\n case ArmConst.UC_ARM_REG_R4:\n number = backend.reg_read(reg);\n value = number.intValue();\n builder.append(String.format(Locale.US, \" r4=0x%x\", value));\n break;\n case ArmConst.UC_ARM_REG_R5:\n number = backend.reg_read(reg);\n value = number.intValue();\n builder.append(String.format(Locale.US, \" r5=0x%x\", value));\n break;\n case ArmConst.UC_ARM_REG_R6:\n number = backend.reg_read(reg);\n value = number.intValue();\n builder.append(String.format(Locale.US, \" r6=0x%x\", value));\n break;\n case ArmConst.UC_ARM_REG_R7:\n number = backend.reg_read(reg);\n value = number.intValue();\n builder.append(String.format(Locale.US, \" r7=0x%x\", value));\n break;\n case ArmConst.UC_ARM_REG_R8:\n number = backend.reg_read(reg);\n value = number.intValue();\n builder.append(String.format(Locale.US, \" r8=0x%x\", value));\n break;\n case ArmConst.UC_ARM_REG_R9: // UC_ARM_REG_SB\n number = backend.reg_read(reg);\n value = number.intValue();\n builder.append(String.format(Locale.US, \" sb=0x%x\", value));\n break;\n case ArmConst.UC_ARM_REG_R10: // UC_ARM_REG_SL\n number = backend.reg_read(reg);\n value = number.intValue();\n builder.append(String.format(Locale.US, \" sl=0x%x\", value));\n break;\n case ArmConst.UC_ARM_REG_FP:\n number = backend.reg_read(reg);\n value = number.intValue();\n builder.append(String.format(Locale.US, \" fp=0x%x\", value));\n break;\n case ArmConst.UC_ARM_REG_IP:\n number = backend.reg_read(reg);\n value = number.intValue();\n builder.append(String.format(Locale.US, \" ip=0x%x\", value));\n break;\n case ArmConst.UC_ARM_REG_SP:\n number = backend.reg_read(reg);\n value = number.intValue();\n builder.append(String.format(Locale.US, \"\\n>>> SP=0x%x\", value));\n break;\n case ArmConst.UC_ARM_REG_LR:\n builder.append(String.format(Locale.US, \" LR=%s\", UnidbgPointer.register(emulator, ArmConst.UC_ARM_REG_LR)));\n break;\n case ArmConst.UC_ARM_REG_PC:\n UnidbgPointer pc = UnidbgPointer.register(emulator, ArmConst.UC_ARM_REG_PC);\n builder.append(String.format(Locale.US, \" PC=%s\", pc));\n break;\n case ArmConst.UC_ARM_REG_D0:\n byte[] data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(\"\\n>>>\");\n builder.append(String.format(Locale.US, \" d0=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case ArmConst.UC_ARM_REG_D1:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" d1=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case ArmConst.UC_ARM_REG_D2:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" d2=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case ArmConst.UC_ARM_REG_D3:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" d3=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case ArmConst.UC_ARM_REG_D4:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" d4=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case ArmConst.UC_ARM_REG_D5:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" d5=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case ArmConst.UC_ARM_REG_D6:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" d6=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case ArmConst.UC_ARM_REG_D7:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" d7=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case ArmConst.UC_ARM_REG_D8:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(\"\\n>>>\");\n builder.append(String.format(Locale.US, \" d8=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case ArmConst.UC_ARM_REG_D9:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" d9=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case ArmConst.UC_ARM_REG_D10:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" d10=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case ArmConst.UC_ARM_REG_D11:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" d11=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case ArmConst.UC_ARM_REG_D12:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" d12=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case ArmConst.UC_ARM_REG_D13:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" d13=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case ArmConst.UC_ARM_REG_D14:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" d14=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case ArmConst.UC_ARM_REG_D15:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" d15=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n }\n }\n System.out.println(builder);\n }\n\n public static void showRegs64(Emulator<?> emulator, int[] regs) {\n Backend backend = emulator.getBackend();\n if (regs == null || regs.length < 1) {\n regs = ARM.getAll64Registers();\n }\n StringBuilder builder = new StringBuilder();\n builder.append(\">>>\");\n for (int reg : regs) {\n Number number;\n long value;\n switch (reg) {\n case Arm64Const.UC_ARM64_REG_NZCV:\n Cpsr cpsr = Cpsr.getArm64(backend);\n if (cpsr.isA32()) {\n builder.append(String.format(Locale.US, \" cpsr: N=%d, Z=%d, C=%d, V=%d, T=%d, mode=0b\",\n cpsr.isNegative() ? 1 : 0,\n cpsr.isZero() ? 1 : 0,\n cpsr.hasCarry() ? 1 : 0,\n cpsr.isOverflow() ? 1 : 0,\n cpsr.isThumb() ? 1 : 0)).append(Integer.toBinaryString(cpsr.getMode()));\n } else {\n int el = cpsr.getEL();\n builder.append(String.format(Locale.US, \"\\nnzcv: N=%d, Z=%d, C=%d, V=%d, EL%d, use SP_EL\",\n cpsr.isNegative() ? 1 : 0,\n cpsr.isZero() ? 1 : 0,\n cpsr.hasCarry() ? 1 : 0,\n cpsr.isOverflow() ? 1 : 0,\n el)).append((cpsr.getValue() & 1) == 0 ? 0 : el);\n }\n break;\n case Arm64Const.UC_ARM64_REG_X0:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x0=0x%x\", value));\n if (value < 0) {\n builder.append('(').append(value).append(')');\n } else if((value & 0x7fffffff00000000L) == 0) {\n int iv = (int) value;\n if (iv < 0) {\n builder.append('(').append(iv).append(')');\n }\n }\n break;\n case Arm64Const.UC_ARM64_REG_X1:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x1=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X2:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x2=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X3:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x3=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X4:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x4=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X5:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x5=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X6:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x6=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X7:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x7=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X8:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x8=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X9:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x9=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X10:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x10=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X11:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x11=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X12:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x12=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X13:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x13=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X14:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x14=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X15:\n builder.append(\"\\n>>>\");\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x15=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X16:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x16=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X17:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x17=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X18:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x18=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X19:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x19=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X20:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x20=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X21:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x21=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X22:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x22=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X23:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x23=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X24:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x24=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X25:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x25=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X26:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x26=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X27:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x27=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_X28:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" x28=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_FP:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \" fp=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_SP:\n number = backend.reg_read(reg);\n value = number.longValue();\n builder.append(String.format(Locale.US, \"\\nSP=0x%x\", value));\n break;\n case Arm64Const.UC_ARM64_REG_LR: {\n UnidbgPointer lr = UnidbgPointer.register(emulator, Arm64Const.UC_ARM64_REG_LR);\n builder.append(String.format(Locale.US, \"\\nLR=%s\", lr));\n break;\n }\n case Arm64Const.UC_ARM64_REG_PC:\n UnidbgPointer pc = UnidbgPointer.register(emulator, Arm64Const.UC_ARM64_REG_PC);\n builder.append(String.format(Locale.US, \"\\nPC=%s\", pc));\n break;\n case Arm64Const.UC_ARM64_REG_Q0:\n byte[] data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(\"\\n>>>\");\n builder.append(String.format(Locale.US, \" q0=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q1:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q1=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q2:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q2=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q3:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q3=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q4:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q4=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q5:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q5=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q6:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q6=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q7:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q7=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q8:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q8=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q9:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q9=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q10:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q10=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q11:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q11=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q12:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q12=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q13:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q13=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q14:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q14=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q15:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q15=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q16:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(\"\\n>>>\");\n builder.append(String.format(Locale.US, \" q16=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q17:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q17=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q18:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q18=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q19:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q19=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q20:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q20=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q21:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q21=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q22:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q22=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q23:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q23=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q24:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q24=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q25:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q25=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q26:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q26=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q27:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q27=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q28:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q28=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q29:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q29=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q30:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q30=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n case Arm64Const.UC_ARM64_REG_Q31:\n data = backend.reg_read_vector(reg);\n if (data != null) {\n builder.append(String.format(Locale.US, \" q31=0x%s%s\", newBigInteger(data).toString(16), Utils.decodeVectorRegister(data)));\n }\n break;\n }\n }\n System.out.println(builder);\n }\n\n private static BigInteger newBigInteger(byte[] data) {\n if (data.length != 16) {\n throw new IllegalStateException(\"data.length=\" + data.length);\n }\n byte[] copy = Arrays.copyOf(data, data.length);\n for (int i = 0; i < 8; i++) {\n byte b = copy[i];\n copy[i] = copy[15 - i];\n copy[15 - i] = b;\n }\n byte[] bytes = new byte[copy.length + 1];\n System.arraycopy(copy, 0, bytes, 1, copy.length); // makePositive\n return new BigInteger(bytes);\n }\n\n private static final int[] ARM_ARG_REGS = new int[] {\n ArmConst.UC_ARM_REG_R0,\n ArmConst.UC_ARM_REG_R1,\n ArmConst.UC_ARM_REG_R2,\n ArmConst.UC_ARM_REG_R3\n };\n\n private static final int[] ARM64_ARG_REGS = new int[] {\n Arm64Const.UC_ARM64_REG_X0,\n Arm64Const.UC_ARM64_REG_X1,\n Arm64Const.UC_ARM64_REG_X2,\n Arm64Const.UC_ARM64_REG_X3,\n Arm64Const.UC_ARM64_REG_X4,\n Arm64Const.UC_ARM64_REG_X5,\n Arm64Const.UC_ARM64_REG_X6,\n Arm64Const.UC_ARM64_REG_X7\n };\n\n private static final int[] THUMB_REGS = new int[] {\n ArmConst.UC_ARM_REG_R0,\n ArmConst.UC_ARM_REG_R1,\n ArmConst.UC_ARM_REG_R2,\n ArmConst.UC_ARM_REG_R3,\n ArmConst.UC_ARM_REG_R4,\n ArmConst.UC_ARM_REG_R5,\n ArmConst.UC_ARM_REG_R6,\n ArmConst.UC_ARM_REG_R7,\n ArmConst.UC_ARM_REG_R8,\n ArmConst.UC_ARM_REG_SB,\n ArmConst.UC_ARM_REG_SL,\n\n ArmConst.UC_ARM_REG_FP,\n ArmConst.UC_ARM_REG_IP,\n\n ArmConst.UC_ARM_REG_SP,\n ArmConst.UC_ARM_REG_LR,\n ArmConst.UC_ARM_REG_PC,\n ArmConst.UC_ARM_REG_CPSR,\n\n ArmConst.UC_ARM_REG_D0,\n ArmConst.UC_ARM_REG_D1,\n ArmConst.UC_ARM_REG_D2,\n ArmConst.UC_ARM_REG_D3,\n ArmConst.UC_ARM_REG_D4,\n ArmConst.UC_ARM_REG_D5,\n ArmConst.UC_ARM_REG_D6,\n ArmConst.UC_ARM_REG_D7,\n ArmConst.UC_ARM_REG_D8,\n ArmConst.UC_ARM_REG_D9,\n ArmConst.UC_ARM_REG_D10,\n ArmConst.UC_ARM_REG_D11,\n ArmConst.UC_ARM_REG_D12,\n ArmConst.UC_ARM_REG_D13,\n ArmConst.UC_ARM_REG_D14,\n ArmConst.UC_ARM_REG_D15,\n };\n private static final int[] ARM_REGS = new int[] {\n ArmConst.UC_ARM_REG_R0,\n ArmConst.UC_ARM_REG_R1,\n ArmConst.UC_ARM_REG_R2,\n ArmConst.UC_ARM_REG_R3,\n ArmConst.UC_ARM_REG_R4,\n ArmConst.UC_ARM_REG_R5,\n ArmConst.UC_ARM_REG_R6,\n ArmConst.UC_ARM_REG_R7,\n ArmConst.UC_ARM_REG_R8,\n ArmConst.UC_ARM_REG_R9,\n ArmConst.UC_ARM_REG_R10,\n\n ArmConst.UC_ARM_REG_FP,\n ArmConst.UC_ARM_REG_IP,\n\n ArmConst.UC_ARM_REG_SP,\n ArmConst.UC_ARM_REG_LR,\n ArmConst.UC_ARM_REG_PC,\n ArmConst.UC_ARM_REG_CPSR,\n\n ArmConst.UC_ARM_REG_D0,\n ArmConst.UC_ARM_REG_D1,\n ArmConst.UC_ARM_REG_D2,\n ArmConst.UC_ARM_REG_D3,\n ArmConst.UC_ARM_REG_D4,\n ArmConst.UC_ARM_REG_D5,\n ArmConst.UC_ARM_REG_D6,\n ArmConst.UC_ARM_REG_D7,\n ArmConst.UC_ARM_REG_D8,\n ArmConst.UC_ARM_REG_D9,\n ArmConst.UC_ARM_REG_D10,\n ArmConst.UC_ARM_REG_D11,\n ArmConst.UC_ARM_REG_D12,\n ArmConst.UC_ARM_REG_D13,\n ArmConst.UC_ARM_REG_D14,\n ArmConst.UC_ARM_REG_D15,\n };\n private static final int[] ARM64_REGS = new int[] {\n Arm64Const.UC_ARM64_REG_X0,\n Arm64Const.UC_ARM64_REG_X1,\n Arm64Const.UC_ARM64_REG_X2,\n Arm64Const.UC_ARM64_REG_X3,\n Arm64Const.UC_ARM64_REG_X4,\n Arm64Const.UC_ARM64_REG_X5,\n Arm64Const.UC_ARM64_REG_X6,\n Arm64Const.UC_ARM64_REG_X7,\n Arm64Const.UC_ARM64_REG_X8,\n Arm64Const.UC_ARM64_REG_X9,\n Arm64Const.UC_ARM64_REG_X10,\n Arm64Const.UC_ARM64_REG_X11,\n Arm64Const.UC_ARM64_REG_X12,\n Arm64Const.UC_ARM64_REG_X13,\n Arm64Const.UC_ARM64_REG_X14,\n Arm64Const.UC_ARM64_REG_X15,\n Arm64Const.UC_ARM64_REG_X16,\n Arm64Const.UC_ARM64_REG_X17,\n Arm64Const.UC_ARM64_REG_X18,\n Arm64Const.UC_ARM64_REG_X19,\n Arm64Const.UC_ARM64_REG_X20,\n Arm64Const.UC_ARM64_REG_X21,\n Arm64Const.UC_ARM64_REG_X22,\n Arm64Const.UC_ARM64_REG_X23,\n Arm64Const.UC_ARM64_REG_X24,\n Arm64Const.UC_ARM64_REG_X25,\n Arm64Const.UC_ARM64_REG_X26,\n Arm64Const.UC_ARM64_REG_X27,\n Arm64Const.UC_ARM64_REG_X28,\n\n Arm64Const.UC_ARM64_REG_FP,\n\n Arm64Const.UC_ARM64_REG_Q0,\n Arm64Const.UC_ARM64_REG_Q1,\n Arm64Const.UC_ARM64_REG_Q2,\n Arm64Const.UC_ARM64_REG_Q3,\n Arm64Const.UC_ARM64_REG_Q4,\n Arm64Const.UC_ARM64_REG_Q5,\n Arm64Const.UC_ARM64_REG_Q6,\n Arm64Const.UC_ARM64_REG_Q7,\n Arm64Const.UC_ARM64_REG_Q8,\n Arm64Const.UC_ARM64_REG_Q9,\n Arm64Const.UC_ARM64_REG_Q10,\n Arm64Const.UC_ARM64_REG_Q11,\n Arm64Const.UC_ARM64_REG_Q12,\n Arm64Const.UC_ARM64_REG_Q13,\n Arm64Const.UC_ARM64_REG_Q14,\n Arm64Const.UC_ARM64_REG_Q15,\n\n Arm64Const.UC_ARM64_REG_Q16,\n Arm64Const.UC_ARM64_REG_Q17,\n Arm64Const.UC_ARM64_REG_Q18,\n Arm64Const.UC_ARM64_REG_Q19,\n Arm64Const.UC_ARM64_REG_Q20,\n Arm64Const.UC_ARM64_REG_Q21,\n Arm64Const.UC_ARM64_REG_Q22,\n Arm64Const.UC_ARM64_REG_Q23,\n Arm64Const.UC_ARM64_REG_Q24,\n Arm64Const.UC_ARM64_REG_Q25,\n Arm64Const.UC_ARM64_REG_Q26,\n Arm64Const.UC_ARM64_REG_Q27,\n Arm64Const.UC_ARM64_REG_Q28,\n Arm64Const.UC_ARM64_REG_Q29,\n Arm64Const.UC_ARM64_REG_Q30,\n Arm64Const.UC_ARM64_REG_Q31,\n\n Arm64Const.UC_ARM64_REG_LR,\n Arm64Const.UC_ARM64_REG_SP,\n Arm64Const.UC_ARM64_REG_PC,\n Arm64Const.UC_ARM64_REG_NZCV,\n };\n\n private static int[] getRegArgs(Emulator<?> emulator) {\n return emulator.is32Bit() ? ARM_ARG_REGS : ARM64_ARG_REGS;\n }\n\n public static int[] getAllRegisters(boolean thumb) {\n return thumb ? THUMB_REGS : ARM_REGS;\n }\n\n public static int[] getAll64Registers() {\n return ARM64_REGS;\n }\n\n private static final int ALIGN_SIZE_BASE = 0x10;\n\n public static int alignSize(int size) {\n return (int) alignSize(size, ALIGN_SIZE_BASE);\n }\n\n public static Alignment align(long addr, long size, long alignment) {\n long mask = -alignment;\n long right = addr + size;\n right = (right + alignment - 1) & mask;\n addr &= mask;\n size = right - addr;\n size = (size + alignment - 1) & mask;\n return new Alignment(addr, size);\n }\n\n public static long alignSize(long size, long align) {\n return ((size - 1) / align + 1) * align;\n }\n\n static String assembleDetail(Emulator<?> emulator, Instruction ins, long address, boolean thumb, int maxLengthLibraryName) {\n return assembleDetail(emulator, ins, address, thumb, false, maxLengthLibraryName);\n }\n\n private static void appendMemoryDetails32(Emulator<?> emulator, Instruction ins, capstone.api.arm.OpInfo opInfo, boolean thumb, StringBuilder sb) {\n Memory memory = emulator.getMemory();\n MemType mem = null;\n long addr = -1;\n Operand[] op = opInfo.getOperands();\n\n // ldr rx, [pc, #0xab] or ldr.w rx, [pc, #0xcd] based capstone.setDetail(Capstone.CS_OPT_ON);\n if (op.length == 2 &&\n op[0].getType() == capstone.Arm_const.ARM_OP_REG &&\n op[1].getType() == capstone.Arm_const.ARM_OP_MEM) {\n mem = op[1].getValue().getMem();\n\n if (mem.getIndex() == 0 && mem.getScale() == 1 && mem.getLshift() == 0) {\n UnidbgPointer base = UnidbgPointer.register(emulator, ins.mapToUnicornReg(mem.getBase()));\n long base_value = base == null ? 0L : base.peer;\n addr = base_value + mem.getDisp();\n }\n\n // ldr.w r0, [r2, r0, lsl #2]\n OpShift shift;\n if (mem.getIndex() > 0 && mem.getScale() == 1 && mem.getLshift() == 0 && mem.getDisp() == 0 &&\n (shift = op[1].getShift()) != null) {\n UnidbgPointer base = UnidbgPointer.register(emulator, ins.mapToUnicornReg(mem.getBase()));\n long base_value = base == null ? 0L : base.peer;\n UnidbgPointer index = UnidbgPointer.register(emulator, ins.mapToUnicornReg(mem.getIndex()));\n int index_value = index == null ? 0 : (int) index.peer;\n if (shift.getType() == capstone.Arm_const.ARM_OP_IMM) {\n addr = base_value + ((long) index_value << shift.getValue());\n } else if (shift.getType() == capstone.Arm_const.ARM_OP_INVALID) {\n addr = base_value + index_value;\n }\n }\n }\n\n // ldrb r0, [r1], #1\n if (op.length == 3 &&\n op[0].getType() == capstone.Arm_const.ARM_OP_REG &&\n op[1].getType() == capstone.Arm_const.ARM_OP_MEM &&\n op[2].getType() == capstone.Arm_const.ARM_OP_IMM) {\n mem = op[1].getValue().getMem();\n if (mem.getIndex() == 0 && mem.getScale() == 1 && mem.getLshift() == 0) {\n UnidbgPointer base = UnidbgPointer.register(emulator, ins.mapToUnicornReg(mem.getBase()));\n addr = base == null ? 0L : base.peer;\n }\n }\n if (addr != -1) {\n if (ins.mapToUnicornReg(mem.getBase()) == ArmConst.UC_ARM_REG_PC) {\n addr += (thumb ? 4 : 8);\n }\n int bytesRead = 4;\n if (ins.getMnemonic().startsWith(\"ldrb\") || ins.getMnemonic().startsWith(\"strb\")) {\n bytesRead = 1;\n }\n if (ins.getMnemonic().startsWith(\"ldrh\") || ins.getMnemonic().startsWith(\"strh\")) {\n bytesRead = 2;\n }\n appendAddrValue(sb, addr, memory, emulator.is64Bit(), bytesRead);\n return;\n }\n\n // ldrd r2, r1, [r5, #4]\n if (\"ldrd\".equals(ins.getMnemonic()) && op.length == 3 &&\n op[0].getType() == capstone.Arm_const.ARM_OP_REG &&\n op[1].getType() == capstone.Arm_const.ARM_OP_REG &&\n op[2].getType() == capstone.Arm_const.ARM_OP_MEM) {\n mem = op[2].getValue().getMem();\n if (mem.getIndex() == 0 && mem.getScale() == 1 && mem.getLshift() == 0) {\n int regId = ins.mapToUnicornReg(mem.getBase());\n UnidbgPointer base = UnidbgPointer.register(emulator, regId);\n long base_value = base == null ? 0L : base.peer;\n addr = base_value + mem.getDisp();\n if (regId == ArmConst.UC_ARM_REG_PC) {\n addr += (thumb ? 4 : 8);\n }\n appendAddrValue(sb, addr, memory, emulator.is64Bit(), 4);\n appendAddrValue(sb, addr + emulator.getPointerSize(), memory, emulator.is64Bit(), 4);\n }\n }\n }\n\n private static void appendMemoryDetails64(Emulator<?> emulator, Instruction ins, capstone.api.arm64.OpInfo opInfo, StringBuilder sb) {\n Memory memory = emulator.getMemory();\n capstone.api.arm64.MemType mem;\n long addr = -1;\n int bytesRead = 8;\n capstone.api.arm64.Operand[] op = opInfo.getOperands();\n\n // str w9, [sp, #0xab] based capstone.setDetail(Capstone.CS_OPT_ON);\n if (op.length == 2 &&\n op[0].getType() == capstone.Arm64_const.ARM64_OP_REG &&\n op[1].getType() == capstone.Arm64_const.ARM64_OP_MEM) {\n int regId = ins.mapToUnicornReg(op[0].getValue().getReg());\n if (regId >= Arm64Const.UC_ARM64_REG_W0 && regId <= Arm64Const.UC_ARM64_REG_W30) {\n bytesRead = 4;\n }\n mem = op[1].getValue().getMem();\n\n if (mem.getIndex() == 0) {\n UnidbgPointer base = UnidbgPointer.register(emulator, ins.mapToUnicornReg(mem.getBase()));\n long base_value = base == null ? 0L : base.peer;\n addr = base_value + mem.getDisp();\n }\n }\n\n // ldrb r0, [r1], #1\n if (op.length == 3 &&\n op[0].getType() == capstone.Arm64_const.ARM64_OP_REG &&\n op[1].getType() == capstone.Arm64_const.ARM64_OP_MEM &&\n op[2].getType() == capstone.Arm64_const.ARM64_OP_IMM) {\n int regId = ins.mapToUnicornReg(op[0].getValue().getReg());\n if (regId >= Arm64Const.UC_ARM64_REG_W0 && regId <= Arm64Const.UC_ARM64_REG_W30) {\n bytesRead = 4;\n }\n mem = op[1].getValue().getMem();\n if (mem.getIndex() == 0) {\n UnidbgPointer base = UnidbgPointer.register(emulator, ins.mapToUnicornReg(mem.getBase()));\n addr = base == null ? 0L : base.peer;\n addr += mem.getDisp();\n }\n }\n if (addr != -1) {\n if (ins.getMnemonic().startsWith(\"ldrb\") || ins.getMnemonic().startsWith(\"strb\")) {\n bytesRead = 1;\n }\n if (ins.getMnemonic().startsWith(\"ldrh\") || ins.getMnemonic().startsWith(\"strh\")) {\n bytesRead = 2;\n }\n appendAddrValue(sb, addr, memory, emulator.is64Bit(), bytesRead);\n }\n }\n\n public static void appendHex(StringBuilder builder, long value, int width, char placeholder, boolean reverse) {\n builder.append(\"0x\");\n String hex = Long.toHexString(value);\n appendHex(builder, hex, width, placeholder, reverse);\n }\n\n public static void appendHex(StringBuilder builder, String str, int width, char placeholder, boolean reverse) {\n if (reverse) {\n builder.append(str);\n for (int i = 0; i < width - str.length(); i++) {\n builder.append(placeholder);\n }\n } else {\n for (int i = 0; i < width - str.length(); i++) {\n builder.append(placeholder);\n }\n builder.append(str);\n }\n }\n\n public static String assembleDetail(Emulator<?> emulator, Instruction ins, long address, boolean thumb, boolean current, int maxLengthLibraryName) {\n SvcMemory svcMemory = emulator.getSvcMemory();\n MemRegion region = svcMemory.findRegion(address);\n Memory memory = emulator.getMemory();\n char space = current ? '*' : ' ';\n StringBuilder builder = new StringBuilder();\n Module module = region != null ? null : memory.findModuleByAddress(address);\n if (module != null) {\n builder.append('[');\n appendHex(builder, module.name, maxLengthLibraryName, ' ', true);\n builder.append(space);\n appendHex(builder, address - module.base + (thumb ? 1 : 0), Long.toHexString(memory.getMaxSizeOfLibrary()).length(), '0', false);\n builder.append(']').append(space);\n } else if (address >= svcMemory.getBase()) { // kernel\n builder.append('[');\n if (region == null) {\n appendHex(builder, \"0x\" + Long.toHexString(address), maxLengthLibraryName, ' ', true);\n } else {\n appendHex(builder, region.getName().substring(0, Math.min(maxLengthLibraryName, region.getName().length())), maxLengthLibraryName, ' ', true);\n }\n builder.append(space);\n appendHex(builder, address - svcMemory.getBase() + (thumb ? 1 : 0), Long.toHexString(memory.getMaxSizeOfLibrary()).length(), '0', false);\n builder.append(']').append(space);\n }\n builder.append(\"[\");\n appendHex(builder, Hex.encodeHexString(ins.getBytes()), 8, ' ', true);\n builder.append(\"]\");\n builder.append(space);\n appendHex(builder, ins.getAddress(), 8, '0', false);\n builder.append(\":\").append(space);\n builder.append('\"').append(ins).append('\"');\n\n capstone.api.arm.OpInfo opInfo = null;\n capstone.api.arm64.OpInfo opInfo64 = null;\n if (ins.getOperands() instanceof capstone.api.arm.OpInfo) {\n opInfo = (capstone.api.arm.OpInfo) ins.getOperands();\n }\n if (ins.getOperands() instanceof capstone.api.arm64.OpInfo) {\n opInfo64 = (capstone.api.arm64.OpInfo) ins.getOperands();\n }\n if (current && (ins.getMnemonic().startsWith(\"ldr\") || ins.getMnemonic().startsWith(\"str\")) && opInfo != null) {\n appendMemoryDetails32(emulator, ins, opInfo, thumb, builder);\n }\n if (current && (ins.getMnemonic().startsWith(\"ldr\") || ins.getMnemonic().startsWith(\"str\")) && opInfo64 != null) {\n appendMemoryDetails64(emulator, ins, opInfo64, builder);\n }\n\n return builder.toString();\n }\n\n private static void appendAddrValue(StringBuilder sb, long addr, Memory memory, boolean is64Bit, int bytesRead) {\n long mask = -bytesRead;\n Pointer pointer = memory.pointer(addr & mask);\n sb.append(\" [0x\").append(Long.toHexString(addr)).append(']');\n try {\n if (is64Bit) {\n if (pointer != null) {\n long value;\n switch (bytesRead) {\n case 1:\n value = pointer.getByte(0) & 0xff;\n break;\n case 2:\n value = pointer.getShort(0) & 0xffff;\n break;\n case 4:\n value = pointer.getInt(0);\n break;\n case 8:\n value = pointer.getLong(0);\n break;\n default:\n throw new IllegalStateException(\"bytesRead=\" + bytesRead);\n }\n sb.append(\" => 0x\").append(Long.toHexString(value));\n if (value < 0) {\n sb.append(\" (-0x\").append(Long.toHexString(-value)).append(')');\n } else if((value & 0x7fffffff00000000L) == 0) {\n int iv = (int) value;\n if (iv < 0) {\n sb.append(\" (-0x\").append(Integer.toHexString(-iv)).append(')');\n }\n }\n } else {\n sb.append(\" => null\");\n }\n } else {\n int value;\n switch (bytesRead) {\n case 1:\n value = pointer.getByte(0) & 0xff;\n break;\n case 2:\n value = pointer.getShort(0) & 0xffff;\n break;\n case 4:\n value = pointer.getInt(0);\n break;\n default:\n throw new IllegalStateException(\"bytesRead=\" + bytesRead);\n }\n sb.append(\" => 0x\").append(Long.toHexString(value & 0xffffffffL));\n if (value < 0) {\n sb.append(\" (-0x\").append(Integer.toHexString(-value)).append(\")\");\n }\n }\n } catch (RuntimeException exception) {\n sb.append(\" => \").append(exception.getMessage());\n }\n }\n\n private static final Log log = LogFactory.getLog(ARM.class);\n\n public static void initArgs(Emulator<?> emulator, boolean padding, Number... arguments) {\n Backend backend = emulator.getBackend();\n Memory memory = emulator.getMemory();\n\n int[] regArgs = ARM.getRegArgs(emulator);\n List<Number> argList = new ArrayList<>(arguments.length * 2);\n int regVector = Arm64Const.UC_ARM64_REG_Q0;\n for (Number arg : arguments) {\n if (emulator.is64Bit()) {\n if (arg instanceof Float) {\n ByteBuffer buffer = ByteBuffer.allocate(16);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putFloat((Float) arg);\n emulator.getBackend().reg_write_vector(regVector++, buffer.array());\n continue;\n }\n if (arg instanceof Double) {\n ByteBuffer buffer = ByteBuffer.allocate(16);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putDouble((Double) arg);\n emulator.getBackend().reg_write_vector(regVector++, buffer.array());\n continue;\n }\n argList.add(arg);\n continue;\n }\n if (arg instanceof Long) {\n if (log.isDebugEnabled()) {\n log.debug(\"initLongArgs size=\" + argList.size() + \", length=\" + regArgs.length, new Exception(\"initArgs long=\" + arg));\n }\n if (padding && argList.size() % 2 != 0) {\n argList.add(0);\n }\n ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putLong((Long) arg);\n buffer.flip();\n int v1 = buffer.getInt();\n int v2 = buffer.getInt();\n argList.add(v1);\n argList.add(v2);\n } else if (arg instanceof Double) {\n if (log.isDebugEnabled()) {\n log.debug(\"initDoubleArgs size=\" + argList.size() + \", length=\" + regArgs.length, new Exception(\"initArgs double=\" + arg));\n }\n if (padding && argList.size() % 2 != 0) {\n argList.add(0);\n }\n ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putDouble((Double) arg);\n buffer.flip();\n argList.add(buffer.getInt());\n argList.add(buffer.getInt());\n } else if (arg instanceof Float) {\n if (log.isDebugEnabled()) {\n log.debug(\"initFloatArgs size=\" + argList.size() + \", length=\" + regArgs.length, new Exception(\"initArgs float=\" + arg));\n }\n ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putFloat((Float) arg);\n buffer.flip();\n argList.add(buffer.getInt());\n } else {\n argList.add(arg);\n }\n }\n final Arguments args = new Arguments(memory, argList.toArray(new Number[0]));\n\n List<Number> list = new ArrayList<>();\n if (args.args != null) {\n Collections.addAll(list, args.args);\n }\n int i = 0;\n while (!list.isEmpty() && i < regArgs.length) {\n backend.reg_write(regArgs[i], list.remove(0));\n i++;\n }\n Collections.reverse(list);\n if (list.size() % 2 != 0) { // alignment sp\n memory.allocateStack(emulator.getPointerSize());\n }\n while (!list.isEmpty()) {\n Number number = list.remove(0);\n UnidbgPointer pointer = memory.allocateStack(emulator.getPointerSize());\n assert pointer != null;\n if (emulator.is64Bit()) {\n if ((pointer.peer % 8) != 0) {\n log.warn(\"initArgs pointer=\" + pointer);\n }\n pointer.setLong(0, number.longValue());\n } else {\n if ((pointer.toUIntPeer() % 4) != 0) {\n log.warn(\"initArgs pointer=\" + pointer);\n }\n pointer.setInt(0, number.intValue());\n }\n }\n }\n\n public static UnidbgPointer adjust_ip(UnidbgPointer ip) {\n int adjust = 4;\n\n boolean thumb = (ip.peer & 1) == 1;\n if (thumb) {\n /* Thumb instructions, the currently executing instruction could be\n * 2 or 4 bytes, so adjust appropriately.\n */\n int value = ip.share(-5).getInt(0);\n if ((value & 0xe000f000L) != 0xe000f000L) {\n adjust = 2;\n }\n }\n\n return ip.share(-adjust, 0);\n }\n\n}" }, { "identifier": "ARMEmulator", "path": "unidbg-api/src/main/java/com/github/unidbg/arm/ARMEmulator.java", "snippet": "public interface ARMEmulator<T extends NewFileIO> extends Emulator<T> {\n\n // From http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044f/IHI0044F_aaelf.pdf\n\n /**\n * 用户模式\n */\n int USR_MODE = 0b10000;\n\n /**\n * 管理模式\n */\n int SVC_MODE = 0b10011;\n\n int R_ARM_ABS32 = 2;\n int R_ARM_REL32 = 3;\n int R_ARM_COPY = 20;\n int R_ARM_GLOB_DAT = 21;\n int R_ARM_JUMP_SLOT = 22;\n int R_ARM_RELATIVE = 23;\n int R_ARM_IRELATIVE = 160;\n\n int R_AARCH64_ABS64 = 257;\n int R_AARCH64_ABS32 = 258;\n int R_AARCH64_ABS16 = 259;\n int R_AARCH64_PREL64 = 260;\n int R_AARCH64_PREL32 = 261;\n int R_AARCH64_PREL16 = 262;\n int R_AARCH64_COPY = 1024;\n int R_AARCH64_GLOB_DAT = 1025;\n int R_AARCH64_JUMP_SLOT = 1026;\n int R_AARCH64_RELATIVE = 1027;\n int R_AARCH64_TLS_TPREL64 = 1030;\n int R_AARCH64_TLS_DTPREL32 = 1031;\n int R_AARCH64_IRELATIVE = 1032;\n\n int PAGE_ALIGN = 0x1000; // 4k\n\n int EXCP_UDEF = 1; /* undefined instruction */\n int EXCP_SWI = 2; /* software interrupt */\n int EXCP_BKPT = 7; /* software breakpoint */\n\n}" }, { "identifier": "Arm64Svc", "path": "unidbg-api/src/main/java/com/github/unidbg/arm/Arm64Svc.java", "snippet": "public abstract class Arm64Svc implements Svc {\n\n private static final Log log = LogFactory.getLog(Arm64Svc.class);\n\n public static final int SVC_MAX = 0xffff;\n\n public static int assembleSvc(int svcNumber) {\n if (svcNumber >= 0 && svcNumber < SVC_MAX - 1) {\n return 0xd4000001 | (svcNumber << 5);\n } else {\n throw new IllegalStateException(\"svcNumber=0x\" + Integer.toHexString(svcNumber));\n }\n }\n\n private final String name;\n\n public Arm64Svc() {\n this(null);\n }\n\n public Arm64Svc(String name) {\n this.name = name;\n }\n\n @Override\n public UnidbgPointer onRegister(SvcMemory svcMemory, int svcNumber) {\n if (log.isDebugEnabled()) {\n log.debug(\"onRegister: \" + getClass(), new Exception(\"svcNumber=0x\" + Integer.toHexString(svcNumber)));\n }\n\n String name = getName();\n return register(svcMemory, svcNumber, name == null ? \"Arm64Svc\" : name);\n }\n\n private static UnidbgPointer register(SvcMemory svcMemory, int svcNumber, String name) {\n ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(assembleSvc(svcNumber)); // \"svc #0x\" + Integer.toHexString(svcNumber)\n buffer.putInt(0xd65f03c0); // ret\n\n byte[] code = buffer.array();\n UnidbgPointer pointer = svcMemory.allocate(code.length, name);\n pointer.write(0, code, 0, code.length);\n return pointer;\n }\n\n @Override\n public void handlePostCallback(Emulator<?> emulator) {\n }\n\n @Override\n public void handlePreCallback(Emulator<?> emulator) {\n }\n\n @Override\n public String getName() {\n return name;\n }\n}" }, { "identifier": "Cpsr", "path": "unidbg-api/src/main/java/com/github/unidbg/arm/Cpsr.java", "snippet": "public class Cpsr {\n\n private static boolean hasBit(int value, int offset) {\n return ((value >> offset) & 1) == 1;\n }\n\n private void setBit(int offset) {\n int mask = 1 << offset;\n value |= mask;\n backend.reg_write(regId, value);\n }\n\n private void clearBit(int offset) {\n int mask = ~(1 << offset);\n value &= mask;\n backend.reg_write(regId, value);\n }\n\n public static Cpsr getArm(Backend backend) {\n return new Cpsr(backend, ArmConst.UC_ARM_REG_CPSR);\n }\n\n public static Cpsr getArm64(Backend backend) {\n return new Cpsr(backend, Arm64Const.UC_ARM64_REG_NZCV);\n }\n\n private final Backend backend;\n private final int regId;\n private int value;\n\n private Cpsr(Backend backend, int regId) {\n this.backend = backend;\n this.regId = regId;\n this.value = backend.reg_read(regId).intValue();\n }\n\n public int getValue() {\n return value;\n }\n\n private static final int A32_BIT = 4;\n\n public boolean isA32() {\n return hasBit(value, A32_BIT);\n }\n\n private static final int THUMB_BIT = 5;\n\n public boolean isThumb() {\n return hasBit(value, THUMB_BIT);\n }\n\n private static final int NEGATIVE_BIT = 31;\n\n public boolean isNegative() {\n return hasBit(value, NEGATIVE_BIT);\n }\n\n void setNegative(boolean on) {\n if (on) {\n setBit(NEGATIVE_BIT);\n } else {\n clearBit(NEGATIVE_BIT);\n }\n }\n\n private static final int ZERO_BIT = 30;\n\n public boolean isZero() {\n return hasBit(value, ZERO_BIT);\n }\n\n void setZero(boolean on) {\n if (on) {\n setBit(ZERO_BIT);\n } else {\n clearBit(ZERO_BIT);\n }\n }\n\n private static final int CARRY_BIT = 29;\n\n /**\n * 进位或借位\n */\n public boolean hasCarry() {\n return hasBit(value, CARRY_BIT);\n }\n\n public void setCarry(boolean on) {\n if (on) {\n setBit(CARRY_BIT);\n } else {\n clearBit(CARRY_BIT);\n }\n }\n\n private static final int OVERFLOW_BIT = 28;\n\n public boolean isOverflow() {\n return hasBit(value, OVERFLOW_BIT);\n }\n\n void setOverflow(boolean on) {\n if (on) {\n setBit(OVERFLOW_BIT);\n } else {\n clearBit(OVERFLOW_BIT);\n }\n }\n\n private static final int MODE_MASK = 0x1f;\n\n public int getMode() {\n return value & MODE_MASK;\n }\n\n public int getEL() {\n return (value >> 2) & 3;\n }\n\n public final void switchUserMode() {\n value &= ~MODE_MASK;\n value |= ARMEmulator.USR_MODE;\n backend.reg_write(regId, value);\n }\n\n}" }, { "identifier": "Backend", "path": "unidbg-api/src/main/java/com/github/unidbg/arm/backend/Backend.java", "snippet": "public interface Backend {\n\n void onInitialize();\n\n void switchUserMode();\n void enableVFP();\n\n Number reg_read(int regId)throws BackendException;\n\n byte[] reg_read_vector(int regId) throws BackendException;\n void reg_write_vector(int regId, byte[] vector) throws BackendException;\n\n void reg_write(int regId, Number value) throws BackendException;\n\n byte[] mem_read(long address, long size) throws BackendException;\n\n void mem_write(long address, byte[] bytes) throws BackendException;\n\n void mem_map(long address, long size, int perms) throws BackendException;\n\n void mem_protect(long address, long size, int perms) throws BackendException;\n\n void mem_unmap(long address, long size) throws BackendException;\n\n BreakPoint addBreakPoint(long address, BreakPointCallback callback, boolean thumb);\n boolean removeBreakPoint(long address);\n void setSingleStep(int singleStep);\n void setFastDebug(boolean fastDebug);\n\n void hook_add_new(CodeHook callback, long begin, long end, Object user_data) throws BackendException;\n\n void debugger_add(DebugHook callback, long begin, long end, Object user_data) throws BackendException;\n\n void hook_add_new(ReadHook callback, long begin, long end, Object user_data) throws BackendException;\n\n void hook_add_new(WriteHook callback, long begin, long end, Object user_data) throws BackendException;\n\n void hook_add_new(EventMemHook callback, int type, Object user_data) throws BackendException;\n\n void hook_add_new(InterruptHook callback, Object user_data) throws BackendException;\n\n void hook_add_new(BlockHook callback, long begin, long end, Object user_data) throws BackendException;\n\n void emu_start(long begin, long until, long timeout, long count) throws BackendException;\n\n void emu_stop() throws BackendException;\n\n void destroy() throws BackendException;\n\n void context_restore(long context);\n void context_save(long context);\n long context_alloc();\n void context_free(long context);\n\n int getPageSize();\n\n void registerEmuCountHook(long emu_count);\n\n}" }, { "identifier": "BackendException", "path": "unidbg-api/src/main/java/com/github/unidbg/arm/backend/BackendException.java", "snippet": "public class BackendException extends RuntimeException {\n\n public BackendException() {\n }\n\n public BackendException(String message) {\n super(message);\n }\n\n public BackendException(Throwable cause) {\n super(cause);\n }\n\n public BackendException(String message, Throwable cause) {\n super(message, cause);\n }\n\n}" }, { "identifier": "Arm64RegisterContext", "path": "unidbg-api/src/main/java/com/github/unidbg/arm/context/Arm64RegisterContext.java", "snippet": "public interface Arm64RegisterContext extends RegisterContext {\n\n long getXLong(int index);\n\n int getXInt(int index);\n\n UnidbgPointer getXPointer(int index);\n\n long getFp();\n\n UnidbgPointer getFpPointer();\n\n}" }, { "identifier": "EditableArm64RegisterContext", "path": "unidbg-api/src/main/java/com/github/unidbg/arm/context/EditableArm64RegisterContext.java", "snippet": "public interface EditableArm64RegisterContext extends Arm64RegisterContext {\n\n void setXLong(int index, long value);\n\n void setStackPointer(Pointer sp);\n\n}" }, { "identifier": "RegisterContext", "path": "unidbg-api/src/main/java/com/github/unidbg/arm/context/RegisterContext.java", "snippet": "public interface RegisterContext {\n\n /**\n * @param index 0 based\n */\n int getIntArg(int index);\n\n /**\n * @param index 0 based\n */\n long getLongArg(int index);\n\n /**\n * @param index 0 based\n */\n UnidbgPointer getPointerArg(int index);\n\n long getLR();\n\n UnidbgPointer getLRPointer();\n\n UnidbgPointer getPCPointer();\n\n /**\n * sp\n */\n UnidbgPointer getStackPointer();\n\n int getIntByReg(int regId);\n long getLongByReg(int regId);\n\n}" }, { "identifier": "FileIO", "path": "unidbg-api/src/main/java/com/github/unidbg/file/FileIO.java", "snippet": "public interface FileIO {\n\n int SEEK_SET = 0;\n int SEEK_CUR = 1;\n int SEEK_END = 2;\n\n void close();\n\n int write(byte[] data);\n\n int read(Backend backend, Pointer buffer, int count);\n\n int pread(Backend backend, Pointer buffer, int count, long offset);\n\n int fcntl(Emulator<?> emulator, int cmd, long arg);\n\n int ioctl(Emulator<?> emulator, long request, long argp);\n\n FileIO dup2();\n\n int connect(Pointer addr, int addrlen);\n\n int bind(Pointer addr, int addrlen);\n\n int listen(int backlog);\n\n int setsockopt(int level, int optname, Pointer optval, int optlen);\n\n int sendto(byte[] data, int flags, Pointer dest_addr, int addrlen);\n\n int lseek(int offset, int whence);\n\n int ftruncate(int length);\n\n int getpeername(Pointer addr, Pointer addrlen);\n\n int shutdown(int how);\n\n int getsockopt(int level, int optname, Pointer optval, Pointer optlen);\n\n int getsockname(Pointer addr, Pointer addrlen);\n\n long mmap2(Emulator<?> emulator, long addr, int aligned, int prot, int offset, int length) throws IOException;\n\n int llseek(long offset, Pointer result, int whence);\n\n int recvfrom(Backend backend, Pointer buf, int len, int flags, Pointer src_addr, Pointer addrlen);\n\n String getPath();\n\n boolean isStdIO();\n}" }, { "identifier": "FileResult", "path": "unidbg-api/src/main/java/com/github/unidbg/file/FileResult.java", "snippet": "public class FileResult<T extends NewFileIO> {\n\n private static final int FALLBACK_ERRNO = -1;\n\n public static <T extends NewFileIO> FileResult<T> success(T io) {\n if (io == null) {\n throw new NullPointerException(\"io is null\");\n }\n\n return new FileResult<>(io, 0);\n }\n public static <T extends NewFileIO> FileResult<T> failed(int errno) {\n if (errno == 0) {\n throw new IllegalArgumentException(\"errno=\" + errno);\n }\n\n return new FileResult<>(null, errno);\n }\n public static <T extends NewFileIO> FileResult<T> fallback(T io) {\n if (io == null) {\n throw new NullPointerException(\"io is null\");\n }\n\n return new FileResult<>(io, FALLBACK_ERRNO);\n }\n\n public final T io;\n public final int errno;\n\n public boolean isSuccess() {\n return io != null && errno == 0;\n }\n\n public boolean isFallback() {\n return io != null && errno == FALLBACK_ERRNO;\n }\n\n private FileResult(T io, int errno) {\n this.io = io;\n this.errno = errno;\n }\n\n}" }, { "identifier": "DarwinFileIO", "path": "unidbg-ios/src/main/java/com/github/unidbg/file/ios/DarwinFileIO.java", "snippet": "public interface DarwinFileIO extends NewFileIO {\n\n int F_PREALLOCATE = 42; /* Preallocate storage */\n int F_NOCACHE = 48; /* turn data caching off/on for this fd */\n int F_GETPATH = 50; /* return the full path of the fd */\n int F_SINGLE_WRITER = 76; /* file being written to a by single writer... if throttling enabled, writes */\n\n /*\n * Vnode types. VNON means no type.\n */\n enum vtype\t{ VNON, VREG, VDIR, VBLK, VCHR, VLNK, VSOCK, VFIFO, VBAD, VSTR, VCPLX };\n\n int ATTR_BIT_MAP_COUNT = 5;\n int ATTR_CMN_NAME = 0x00000001;\n int ATTR_CMN_DEVID = 0x00000002;\n int ATTR_CMN_FSID = 0x00000004;\n int ATTR_CMN_OBJTYPE = 0x00000008;\n int ATTR_CMN_OBJID = 0x00000020;\n int ATTR_CMN_CRTIME = 0x00000200;\n int ATTR_CMN_MODTIME = 0x00000400;\n int ATTR_CMN_FNDRINFO = 0x00004000;\n int ATTR_CMN_USERACCESS = 0x00200000; // (used to get the user's access mode to the file).\n int ATTR_CMN_RETURNED_ATTRS = 0x80000000; // It is always the first attribute in the return buffer.\n\n int X_OK = 1;\n int W_OK = 2;\n int R_OK = 4;\n\n int F_SETLK = 8; /* set record locking information */\n int F_SETLKW = 9; /* F_SETLK; wait if blocked */\n int F_GETPROTECTIONCLASS =\t63;\t/* Get the protection class of a file from the EA, returns int */\n int F_SETPROTECTIONCLASS =\t64; /* Set the protection class of a file for the EA, requires int */\n\n int XATTR_NOFOLLOW = 0x0001; /* Don't follow symbolic links */\n int XATTR_CREATE = 0x0002; /* set the value, fail if attr already exists */\n int XATTR_REPLACE = 0x0004; /* set the value, fail if attr does not exist */\n\n int fstat(Emulator<?> emulator, StatStructure stat);\n\n int fstatfs(StatFS statFS);\n\n int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize);\n int setattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize);\n\n int getdirentries64(Pointer buf, int bufSize);\n\n int listxattr(Pointer namebuf, int size, int options);\n int removexattr(String name);\n int setxattr(String name, byte[] data);\n int getxattr(Emulator<?> emulator, String name, Pointer value, int size);\n int chown(int uid, int gid);\n int chmod(int mode);\n int chflags(int flags);\n\n}" }, { "identifier": "IOConstants", "path": "unidbg-ios/src/main/java/com/github/unidbg/file/ios/IOConstants.java", "snippet": "public interface IOConstants {\n\n int O_RDONLY = 0x0000; /* open for reading only */\n int O_WRONLY = 0x0001; /* open for writing only */\n int O_RDWR = 0x0002; /* open for reading and writing */\n int O_NONBLOCK = 0x0004; /* no delay */\n int O_APPEND = 0x0008; /* set append mode */\n int O_CREAT = 0x0200; /* create if nonexistant */\n int O_EXCL = 0x0800; /* error if already exists */\n\n int O_DIRECTORY = 0x100000;\n\n}" }, { "identifier": "ByteArrayFileIO", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/file/ByteArrayFileIO.java", "snippet": "public class ByteArrayFileIO extends BaseDarwinFileIO {\n\n protected final byte[] bytes;\n protected final String path;\n\n public ByteArrayFileIO(int oflags, String path, byte[] bytes) {\n super(oflags);\n this.path = path;\n this.bytes = bytes;\n }\n\n private int pos;\n\n @Override\n public void close() {\n pos = 0;\n }\n\n @Override\n public int write(byte[] data) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public int read(Backend backend, Pointer buffer, int count) {\n if (pos >= bytes.length) {\n return 0;\n }\n\n int remain = bytes.length - pos;\n if (count > remain) {\n count = remain;\n }\n buffer.write(0, bytes, pos, count);\n pos += count;\n return count;\n }\n\n @Override\n public int lseek(int offset, int whence) {\n switch (whence) {\n case SEEK_SET:\n pos = offset;\n return pos;\n case SEEK_CUR:\n pos += offset;\n return pos;\n case SEEK_END:\n pos = bytes.length + offset;\n return pos;\n }\n return super.lseek(offset, whence);\n }\n\n @Override\n protected byte[] getMmapData(long addr, int offset, int length) {\n if (offset == 0 && length == bytes.length) {\n return bytes;\n } else {\n byte[] data = new byte[length];\n System.arraycopy(bytes, offset, data, 0, data.length);\n return data;\n }\n }\n\n @Override\n public int ioctl(Emulator<?> emulator, long request, long argp) {\n return 0;\n }\n\n @Override\n public int fstat(Emulator<?> emulator, StatStructure stat) {\n int blockSize = emulator.getPageAlign();\n stat.st_dev = 1;\n stat.st_mode = (short) (IO.S_IFREG | 0x777);\n stat.setSize(bytes.length);\n stat.setBlockCount(bytes.length / blockSize);\n stat.st_blksize = blockSize;\n stat.st_ino = 7;\n stat.st_uid = 0;\n stat.st_gid = 0;\n stat.setLastModification(System.currentTimeMillis());\n stat.pack();\n return 0;\n }\n\n @Override\n public String toString() {\n return path;\n }\n\n @Override\n public String getPath() {\n return path;\n }\n\n}" }, { "identifier": "DriverFileIO", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/file/DriverFileIO.java", "snippet": "public class DriverFileIO extends BaseDarwinFileIO implements NewFileIO, DarwinFileIO {\n\n public static DriverFileIO create(Emulator<?> emulator, int oflags, String pathname) {\n if (\"/dev/urandom\".equals(pathname) || \"/dev/random\".equals(pathname) || \"/dev/srandom\".equals(pathname)) {\n return new RandomFileIO(emulator, pathname);\n }\n if (\"/dev/null\".equals(pathname)) {\n return new DriverFileIO(emulator, oflags, pathname);\n }\n return null;\n }\n\n private final String path;\n\n @SuppressWarnings(\"unused\")\n DriverFileIO(Emulator<?> emulator, int oflags, String path) {\n super(oflags);\n this.path = path;\n }\n\n @Override\n public void close() {\n }\n\n @Override\n public int write(byte[] data) {\n throw new AbstractMethodError();\n }\n\n @Override\n public int read(Backend backend, Pointer buffer, int count) {\n throw new AbstractMethodError();\n }\n\n @Override\n public int ioctl(Emulator<?> emulator, long request, long argp) {\n return super.ioctl(emulator, request, argp);\n }\n\n @Override\n public int fstat(Emulator<?> emulator, StatStructure stat) {\n return 0;\n }\n\n @Override\n public int fstatfs(StatFS statFS) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public int getdirentries64(Pointer buf, int bufSize) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public String toString() {\n return path;\n }\n}" }, { "identifier": "LocalDarwinUdpSocket", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/file/LocalDarwinUdpSocket.java", "snippet": "public class LocalDarwinUdpSocket extends LocalUdpSocket {\n\n private static final Log log = LogFactory.getLog(LocalDarwinUdpSocket.class);\n\n public LocalDarwinUdpSocket(Emulator<?> emulator) {\n super(emulator);\n }\n\n @Override\n public int connect(Pointer addr, int addrlen) {\n String path = addr.getString(2);\n log.debug(\"connect path=\" + path);\n\n return connect(path);\n }\n\n @Override\n protected int connect(String path) {\n emulator.getMemory().setErrno(UnixEmulator.EPERM);\n return -1;\n }\n\n @Override\n public int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public int getdirentries64(Pointer buf, int bufSize) {\n throw new UnsupportedOperationException();\n }\n}" }, { "identifier": "SocketIO", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/file/SocketIO.java", "snippet": "public abstract class SocketIO extends BaseDarwinFileIO implements DarwinFileIO {\n\n private static final Log log = LogFactory.getLog(SocketIO.class);\n\n public static final short AF_UNSPEC = 0;\n public static final short AF_LOCAL = 1; // AF_UNIX\n public static final short AF_INET = 2;\n public static final short AF_INET6 = 10;\n public static final short AF_ROUTE = 17;\t\t/* Internal Routing Protocol */\n public static final short AF_LINK =\t\t18;\t\t/* Link layer interface */\n\n protected static final int IPV4_ADDR_LEN = 16;\n protected static final int IPV6_ADDR_LEN = 28;\n\n public static final int SOCK_STREAM = 1;\n public static final int SOCK_DGRAM = 2;\n public static final int SOCK_RAW = 3;\n\n private static final int IPPROTO_IP = 0;\n public static final int IPPROTO_ICMP = 1;\n public static final int IPPROTO_TCP = 6;\n\n protected static final int SOL_SOCKET = 1;\n\n private static final int SO_REUSEADDR = 2;\n private static final int SO_ERROR = 4;\n private static final int SO_BROADCAST = 6;\n private static final int SO_RCVBUF = 8;\n private static final int SO_KEEPALIVE = 9;\n private static final int SO_RCVTIMEO = 20;\n private static final int SO_SNDTIMEO = 21;\n protected static final int SO_PEERSEC = 31;\n\n static final int SHUT_RD = 0;\n static final int SHUT_WR = 1;\n static final int SHUT_RDWR = 2;\n\n private static final int TCP_NODELAY = 1;\n private static final int TCP_MAXSEG = 2;\n\n protected SocketIO() {\n super(IOConstants.O_RDWR);\n }\n\n @Override\n public int getsockopt(int level, int optname, Pointer optval, Pointer optlen) {\n try {\n switch (level) {\n case SOL_SOCKET:\n if (optname == SO_ERROR) {\n optlen.setInt(0, 4);\n optval.setInt(0, 0);\n return 0;\n }\n break;\n case IPPROTO_TCP:\n if (optname == TCP_NODELAY) {\n optlen.setInt(0, 4);\n optval.setInt(0, getTcpNoDelay());\n return 0;\n }\n break;\n }\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n return super.getsockopt(level, optname, optval, optlen);\n }\n\n protected abstract int getTcpNoDelay() throws SocketException;\n\n @Override\n public int setsockopt(int level, int optname, Pointer optval, int optlen) {\n try {\n switch (level) {\n case SOL_SOCKET:\n switch (optname) {\n case SO_REUSEADDR:\n if (optlen != 4) {\n throw new IllegalStateException(\"optlen=\" + optlen);\n }\n setReuseAddress(optval.getInt(0));\n return 0;\n case SO_BROADCAST:\n if (optlen != 4) {\n throw new IllegalStateException(\"optlen=\" + optlen);\n }\n optval.getInt(0); // broadcast_pings\n return 0;\n case SO_RCVBUF:\n if (optlen != 4) {\n throw new IllegalStateException(\"optlen=\" + optlen);\n }\n setSocketRecvBuf(optval.getInt(0));\n return 0;\n case SO_KEEPALIVE:\n if (optlen != 4) {\n throw new IllegalStateException(\"optlen=\" + optlen);\n }\n setKeepAlive(optval.getInt(0));\n return 0;\n case SO_RCVTIMEO:\n case SO_SNDTIMEO: {\n return 0;\n }\n }\n break;\n case IPPROTO_TCP:\n switch (optname) {\n case TCP_NODELAY:\n if (optlen != 4) {\n throw new IllegalStateException(\"optlen=\" + optlen);\n }\n setTcpNoDelay(optval.getInt(0));\n return 0;\n case TCP_MAXSEG:\n if (optlen != 4) {\n throw new IllegalStateException(\"optlen=\" + optlen);\n }\n log.debug(\"setsockopt TCP_MAXSEG=\" + optval.getInt(0));\n return 0;\n }\n break;\n case IPPROTO_IP:\n return 0;\n }\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n\n log.warn(\"setsockopt level=\" + level + \", optname=\" + optname + \", optval=\" + optval + \", optlen=\" + optlen);\n return 0;\n }\n\n protected abstract void setTcpNoDelay(int tcpNoDelay) throws SocketException;\n\n protected abstract void setReuseAddress(int reuseAddress) throws SocketException;\n\n protected abstract void setKeepAlive(int keepAlive) throws SocketException;\n\n protected abstract void setSocketRecvBuf(int recvBuf) throws SocketException;\n\n @Override\n public int getsockname(Pointer addr, Pointer addrlen) {\n InetSocketAddress local = getLocalSocketAddress();\n fillAddress(local, addr, addrlen);\n return 0;\n }\n\n protected final void fillAddress(InetSocketAddress socketAddress, Pointer addr, Pointer addrlen) {\n InetAddress address = socketAddress.getAddress();\n SockAddr sockAddr = new SockAddr(addr);\n sockAddr.sin_port = (short) socketAddress.getPort();\n if (address instanceof Inet4Address) {\n sockAddr.sin_family = AF_INET;\n sockAddr.sin_addr = Arrays.copyOf(address.getAddress(), IPV4_ADDR_LEN - 4);\n addrlen.setInt(0, IPV4_ADDR_LEN);\n } else if (address instanceof Inet6Address) {\n sockAddr.sin_family = AF_INET6;\n sockAddr.sin_addr = Arrays.copyOf(address.getAddress(), IPV6_ADDR_LEN - 4);\n addrlen.setInt(0, IPV6_ADDR_LEN);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n\n protected abstract InetSocketAddress getLocalSocketAddress();\n\n @Override\n public int connect(Pointer addr, int addrlen) {\n if (addrlen == IPV4_ADDR_LEN) {\n return connect_ipv4(addr, addrlen);\n } else if(addrlen == IPV6_ADDR_LEN) {\n return connect_ipv6(addr, addrlen);\n } else {\n throw new IllegalStateException(\"addrlen=\" + addrlen);\n }\n }\n\n @Override\n public final int bind(Pointer addr, int addrlen) {\n if (addrlen == IPV4_ADDR_LEN) {\n return bind_ipv4(addr, addrlen);\n } else if(addrlen == IPV6_ADDR_LEN) {\n return bind_ipv6(addr, addrlen);\n } else {\n throw new IllegalStateException(\"addrlen=\" + addrlen);\n }\n }\n\n protected abstract int connect_ipv6(Pointer addr, int addrlen);\n\n protected abstract int connect_ipv4(Pointer addr, int addrlen);\n\n protected int bind_ipv6(Pointer addr, int addrlen) {\n throw new AbstractMethodError(getClass().getName());\n }\n\n protected int bind_ipv4(Pointer addr, int addrlen) {\n throw new AbstractMethodError(getClass().getName());\n }\n\n @Override\n public int recvfrom(Backend backend, Pointer buf, int len, int flags, Pointer src_addr, Pointer addrlen) {\n if (flags == 0x0 && src_addr == null && addrlen == null) {\n return read(backend, buf, len);\n }\n\n return super.recvfrom(backend, buf, len, flags, src_addr, addrlen);\n }\n\n @Override\n public int sendto(byte[] data, int flags, Pointer dest_addr, int addrlen) {\n if (flags == 0x0 && dest_addr == null && addrlen == 0) {\n return write(data);\n }\n\n return super.sendto(data, flags, dest_addr, addrlen);\n }\n\n @Override\n public int fstat(Emulator<?> emulator, StatStructure stat) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public int fstatfs(StatFS statFS) {\n throw new UnsupportedOperationException();\n }\n}" }, { "identifier": "TcpSocket", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/file/TcpSocket.java", "snippet": "public class TcpSocket extends SocketIO implements FileIO {\n\n private static final Log log = LogFactory.getLog(TcpSocket.class);\n\n private final Socket socket;\n private ServerSocket serverSocket;\n\n private final Emulator<?> emulator;\n\n public TcpSocket(Emulator<?> emulator) {\n this(emulator, new Socket());\n }\n\n private TcpSocket(Emulator<?> emulator, Socket socket) {\n this.emulator = emulator;\n this.socket = socket;\n if (emulator.getSyscallHandler().isVerbose()) {\n System.out.printf(\"Tcp opened '%s' from %s%n\", this, emulator.getContext().getLRPointer());\n }\n }\n\n private OutputStream outputStream;\n private InputStream inputStream;\n\n @Override\n public void close() {\n com.alibaba.fastjson.util.IOUtils.close(outputStream);\n com.alibaba.fastjson.util.IOUtils.close(inputStream);\n com.alibaba.fastjson.util.IOUtils.close(socket);\n com.alibaba.fastjson.util.IOUtils.close(serverSocket);\n }\n\n @Override\n public int write(byte[] data) {\n try {\n if (log.isDebugEnabled()) {\n Inspector.inspect(data, \"write hex=\" + Hex.encodeHexString(data));\n }\n outputStream.write(data);\n return data.length;\n } catch (IOException e) {\n log.debug(\"write failed\", e);\n return -1;\n }\n }\n\n private byte[] receiveBuf;\n\n @Override\n public int read(Backend backend, Pointer buffer, int count) {\n try {\n if (receiveBuf == null) {\n receiveBuf = new byte[socket.getReceiveBufferSize()];\n }\n int read = inputStream.read(receiveBuf, 0, Math.min(count, receiveBuf.length));\n if (read <= 0) {\n return read;\n }\n\n byte[] data = Arrays.copyOf(receiveBuf, read);\n buffer.write(0, data, 0, data.length);\n if (log.isDebugEnabled()) {\n Inspector.inspect(data, \"read\");\n }\n return data.length;\n } catch (IOException e) {\n log.debug(\"read failed\", e);\n return -1;\n }\n }\n\n @Override\n public int listen(int backlog) {\n try {\n serverSocket = new ServerSocket();\n com.alibaba.fastjson.util.IOUtils.close(socket);\n serverSocket.bind(socket.getLocalSocketAddress(), backlog);\n if (emulator.getSyscallHandler().isVerbose()) {\n System.out.printf(\"Tcp listen '%s' from %s%n\", this, emulator.getContext().getLRPointer());\n }\n return 0;\n } catch (IOException e) {\n log.debug(\"listen failed\", e);\n emulator.getMemory().setErrno(UnixEmulator.EOPNOTSUPP);\n return -1;\n }\n }\n\n @Override\n protected int bind_ipv4(Pointer addr, int addrlen) {\n int sa_family = addr.getShort(0);\n if (sa_family != AF_INET) {\n throw new AbstractMethodError(\"sa_family=\" + sa_family);\n }\n\n try {\n int port = Short.reverseBytes(addr.getShort(2)) & 0xffff;\n InetSocketAddress address = new InetSocketAddress(InetAddress.getByAddress(addr.getByteArray(4, 4)), port);\n if (log.isDebugEnabled()) {\n byte[] data = addr.getByteArray(0, addrlen);\n Inspector.inspect(data, \"address=\" + address);\n }\n socket.bind(address);\n if (emulator.getSyscallHandler().isVerbose()) {\n System.out.printf(\"Tcp bind '%s' from %s%n\", this, emulator.getContext().getLRPointer());\n }\n return 0;\n } catch (IOException e) {\n log.debug(\"bind ipv4 failed\", e);\n emulator.getMemory().setErrno(UnixEmulator.EADDRINUSE);\n return -1;\n }\n }\n\n @Override\n protected int connect_ipv4(Pointer addr, int addrlen) {\n if (log.isDebugEnabled()) {\n byte[] data = addr.getByteArray(0, addrlen);\n Inspector.inspect(data, \"addr\");\n }\n\n int sa_family = Short.reverseBytes(addr.getShort(0)) & 0xffff;\n if (sa_family != AF_INET) {\n throw new AbstractMethodError(\"sa_family=\" + sa_family);\n }\n\n try {\n int port = Short.reverseBytes(addr.getShort(2)) & 0xffff;\n InetSocketAddress address = new InetSocketAddress(InetAddress.getByAddress(addr.getByteArray(4, 4)), port);\n socket.connect(address);\n outputStream = socket.getOutputStream();\n inputStream = socket.getInputStream();\n if (emulator.getSyscallHandler().isVerbose()) {\n System.out.printf(\"Tcp connected '%s' from %s%n\", this, emulator.getContext().getLRPointer());\n }\n return 0;\n } catch (IOException e) {\n log.debug(\"connect ipv4 failed\", e);\n emulator.getMemory().setErrno(UnixEmulator.ECONNREFUSED);\n return -1;\n }\n }\n\n @Override\n protected int connect_ipv6(Pointer addr, int addrlen) {\n if (log.isDebugEnabled()) {\n byte[] data = addr.getByteArray(0, addrlen);\n Inspector.inspect(data, \"addr\");\n }\n\n int sa_family = addr.getShort(0);\n if (sa_family != AF_INET6) {\n throw new AbstractMethodError(\"sa_family=\" + sa_family);\n }\n\n try {\n int port = Short.reverseBytes(addr.getShort(2)) & 0xffff;\n InetSocketAddress address = new InetSocketAddress(InetAddress.getByAddress(addr.getByteArray(8, 16)), port);\n socket.connect(address);\n outputStream = socket.getOutputStream();\n inputStream = socket.getInputStream();\n if (emulator.getSyscallHandler().isVerbose()) {\n System.out.printf(\"Tcp connected '%s' from %s%n\", this, emulator.getContext().getLRPointer());\n }\n return 0;\n } catch (IOException e) {\n log.debug(\"connect ipv6 failed\", e);\n emulator.getMemory().setErrno(UnixEmulator.ECONNREFUSED);\n return -1;\n }\n }\n\n @Override\n public int getpeername(Pointer addr, Pointer addrlen) {\n InetSocketAddress remote = (InetSocketAddress) socket.getRemoteSocketAddress();\n fillAddress(remote, addr, addrlen);\n return 0;\n }\n\n @Override\n protected InetSocketAddress getLocalSocketAddress() {\n return (InetSocketAddress) socket.getLocalSocketAddress();\n }\n\n @Override\n protected void setKeepAlive(int keepAlive) throws SocketException {\n socket.setKeepAlive(keepAlive != 0);\n }\n\n @Override\n protected void setSocketRecvBuf(int recvBuf) throws SocketException {\n socket.setReceiveBufferSize(recvBuf);\n }\n\n @Override\n protected void setReuseAddress(int reuseAddress) throws SocketException {\n socket.setReuseAddress(reuseAddress != 0);\n }\n\n @Override\n protected void setTcpNoDelay(int tcpNoDelay) throws SocketException {\n socket.setTcpNoDelay(tcpNoDelay != 0);\n }\n\n @Override\n protected int getTcpNoDelay() throws SocketException {\n return socket.getTcpNoDelay() ? 1 : 0;\n }\n\n @Override\n public int shutdown(int how) {\n switch (how) {\n case SHUT_RD:\n case SHUT_WR:\n com.alibaba.fastjson.util.IOUtils.close(outputStream);\n outputStream = null;\n return 0;\n case SHUT_RDWR:\n com.alibaba.fastjson.util.IOUtils.close(outputStream);\n IOUtils.close(inputStream);\n outputStream = null;\n inputStream = null;\n return 0;\n }\n\n return super.shutdown(how);\n }\n\n @Override\n public String toString() {\n return socket.toString();\n }\n\n @Override\n public int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public int getdirentries64(Pointer buf, int bufSize) {\n throw new UnsupportedOperationException();\n }\n}" }, { "identifier": "UdpSocket", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/file/UdpSocket.java", "snippet": "public class UdpSocket extends SocketIO implements FileIO {\n\n private static final Log log = LogFactory.getLog(UdpSocket.class);\n\n private final Emulator<?> emulator;\n private final DatagramSocket datagramSocket;\n\n public UdpSocket(Emulator<?> emulator) {\n this.emulator = emulator;\n try {\n this.datagramSocket = new DatagramSocket();\n } catch (SocketException e) {\n throw new IllegalStateException(e);\n }\n if (emulator.getSyscallHandler().isVerbose()) {\n System.out.printf(\"Udp opened '%s' from %s%n\", this, emulator.getContext().getLRPointer());\n }\n }\n\n @Override\n public String toString() {\n return datagramSocket.toString();\n }\n\n @Override\n public void close() {\n this.datagramSocket.close();\n }\n\n @Override\n protected int connect_ipv6(Pointer addr, int addrlen) {\n if (log.isDebugEnabled()) {\n byte[] data = addr.getByteArray(0, addrlen);\n Inspector.inspect(data, \"addr\");\n }\n\n int sa_family = addr.getShort(0);\n if (sa_family != AF_INET6) {\n throw new AbstractMethodError(\"sa_family=\" + sa_family);\n }\n\n try {\n int port = Short.reverseBytes(addr.getShort(2)) & 0xffff;\n InetSocketAddress address = new InetSocketAddress(InetAddress.getByAddress(addr.getByteArray(4, 16)), port);\n datagramSocket.connect(address);\n return 0;\n } catch (IOException e) {\n log.debug(\"connect ipv6 failed\", e);\n emulator.getMemory().setErrno(UnixEmulator.ECONNREFUSED);\n return -1;\n }\n }\n\n @Override\n protected int connect_ipv4(Pointer addr, int addrlen) {\n if (log.isDebugEnabled()) {\n byte[] data = addr.getByteArray(0, addrlen);\n Inspector.inspect(data, \"addr\");\n }\n\n int sa_family = addr.getShort(0);\n if (sa_family != AF_INET) {\n throw new AbstractMethodError(\"sa_family=\" + sa_family);\n }\n\n try {\n int port = Short.reverseBytes(addr.getShort(2)) & 0xffff;\n InetSocketAddress address = new InetSocketAddress(InetAddress.getByAddress(addr.getByteArray(8, 4)), port);\n datagramSocket.connect(address);\n return 0;\n } catch (IOException e) {\n log.debug(\"connect ipv4 failed\", e);\n emulator.getMemory().setErrno(UnixEmulator.ECONNREFUSED);\n return -1;\n }\n }\n\n @Override\n protected InetSocketAddress getLocalSocketAddress() {\n return (InetSocketAddress) datagramSocket.getLocalSocketAddress();\n }\n\n @Override\n public int write(byte[] data) {\n throw new AbstractMethodError();\n }\n\n @Override\n public int read(Backend backend, Pointer buffer, int count) {\n throw new AbstractMethodError();\n }\n\n @Override\n public FileIO dup2() {\n return new UdpSocket(emulator);\n }\n\n @Override\n public int sendto(byte[] data, int flags, Pointer dest_addr, int addrlen) {\n if (addrlen != 16) {\n throw new IllegalStateException(\"addrlen=\" + addrlen);\n }\n\n if (log.isDebugEnabled()) {\n byte[] addr = dest_addr.getByteArray(0, addrlen);\n Inspector.inspect(addr, \"addr\");\n }\n\n int sa_family = dest_addr.getInt(0);\n if (sa_family != AF_INET) {\n throw new AbstractMethodError(\"sa_family=\" + sa_family);\n }\n\n try {\n InetAddress address = InetAddress.getByAddress(dest_addr.getByteArray(4, 4));\n throw new UnsupportedOperationException(\"address=\" + address);\n } catch (IOException e) {\n log.debug(\"sendto failed\", e);\n emulator.getMemory().setErrno(UnixEmulator.EACCES);\n return -1;\n }\n }\n\n @Override\n protected void setKeepAlive(int keepAlive) {\n throw new AbstractMethodError();\n }\n\n @Override\n protected void setSocketRecvBuf(int recvBuf) {\n throw new AbstractMethodError();\n }\n\n @Override\n protected void setReuseAddress(int reuseAddress) {\n throw new AbstractMethodError();\n }\n\n @Override\n protected void setTcpNoDelay(int tcpNoDelay) {\n throw new AbstractMethodError();\n }\n\n @Override\n protected int getTcpNoDelay() {\n throw new AbstractMethodError();\n }\n\n @Override\n public int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public int getdirentries64(Pointer buf, int bufSize) {\n throw new UnsupportedOperationException();\n }\n}" }, { "identifier": "AttrList", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/AttrList.java", "snippet": "public class AttrList extends UnidbgStructure {\n\n public AttrList(Pointer p) {\n super(p);\n unpack();\n }\n\n public short bitmapcount; /* number of attr. bit sets in list (should be 5) */\n public short reserved; /* (to maintain 4-byte alignment) */\n\n public AttributeSet attributeSet;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"bitmapcount\", \"reserved\", \"attributeSet\");\n }\n\n}" }, { "identifier": "AslServerMessageRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/AslServerMessageRequest.java", "snippet": "public class AslServerMessageRequest extends UnidbgStructure {\n\n public AslServerMessageRequest(Pointer p) {\n super(p);\n }\n\n public int pad;\n public int message;\n public int messageCnt;\n public int flags;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"pad\", \"message\", \"messageCnt\", \"flags\");\n }\n\n}" }, { "identifier": "ClockGetTimeReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/ClockGetTimeReply.java", "snippet": "public class ClockGetTimeReply extends UnidbgStructure {\n\n public NDR_record NDR;\n public int retCode;\n public int tv_sec;\n public int tv_nsec;\n\n public ClockGetTimeReply(Pointer p) {\n super(p);\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"retCode\", \"tv_sec\", \"tv_nsec\");\n }\n\n}" }, { "identifier": "DyldCacheHeader", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/DyldCacheHeader.java", "snippet": "public class DyldCacheHeader extends UnidbgStructure {\n\n public byte[] magic; // e.g. \"dyld_v0 i386\"\n public int mappingOffset; // file offset to first dyld_cache_mapping_info\n public int mappingCount; // number of dyld_cache_mapping_info entries\n public int imagesOffset; // file offset to first dyld_cache_image_info\n public int imagesCount; // number of dyld_cache_image_info entries\n public long dyldBaseAddress; // base address of dyld when cache was built\n public long codeSignatureOffset; // file offset of code signature blob\n public long codeSignatureSize; // size of code signature blob (zero means to end of file)\n public long slideInfoOffset; // file offset of kernel slid info\n public long slideInfoSize; // size of kernel slid info\n public long localSymbolsOffset; // file offset of where local symbols are stored\n public long localSymbolsSize; // size of local symbols information\n public byte[] uuid = new byte[16]; // unique value for each shared cache file\n\n public DyldCacheHeader(Pointer p) {\n super(p);\n\n byte[] magic = \"dyld_v1 arm64e\".getBytes();\n this.magic = Arrays.copyOf(magic, magic.length + 1);\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"magic\", \"mappingOffset\", \"mappingCount\", \"imagesOffset\", \"imagesCount\",\n \"dyldBaseAddress\", \"codeSignatureOffset\", \"codeSignatureSize\", \"slideInfoOffset\", \"slideInfoSize\",\n \"localSymbolsOffset\", \"localSymbolsSize\", \"uuid\");\n }\n}" }, { "identifier": "HostGetClockServiceReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/HostGetClockServiceReply.java", "snippet": "public class HostGetClockServiceReply extends UnidbgStructure {\n\n public HostGetClockServiceReply(Pointer p) {\n super(p);\n }\n\n public MachMsgBody body;\n public MachMsgPortDescriptor clock_server;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"body\", \"clock_server\");\n }\n\n}" }, { "identifier": "HostGetClockServiceRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/HostGetClockServiceRequest.java", "snippet": "public class HostGetClockServiceRequest extends UnidbgStructure {\n\n public HostGetClockServiceRequest(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int clock_id;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"clock_id\");\n }\n\n}" }, { "identifier": "HostInfoReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/HostInfoReply.java", "snippet": "public class HostInfoReply extends UnidbgStructure {\n\n public HostInfoReply(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int retCode;\n public int host_info_outCnt = 8;\n public HostInfo host_info_out;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"retCode\", \"host_info_outCnt\", \"host_info_out\");\n }\n\n}" }, { "identifier": "HostInfoRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/HostInfoRequest.java", "snippet": "public class HostInfoRequest extends UnidbgStructure {\n\n public HostInfoRequest(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int flavor;\n public int host_info_out;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"flavor\", \"host_info_out\");\n }\n}" }, { "identifier": "IOServiceAddNotificationRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/IOServiceAddNotificationRequest.java", "snippet": "public class IOServiceAddNotificationRequest extends UnidbgStructure {\n\n public IOServiceAddNotificationRequest(Pointer p) {\n super(p);\n }\n\n public MachMsgBody body;\n public int name;\n public int v26;\n public int v27;\n public NDR_record NDR;\n public int pad;\n public int size;\n\n public String getMatching() {\n Pointer pointer = getPointer().share(size());\n return new String(pointer.getByteArray(0, size), StandardCharsets.UTF_8).trim();\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"body\", \"name\", \"v26\", \"v27\", \"NDR\", \"pad\", \"size\");\n }\n\n}" }, { "identifier": "IOServiceGetMatchingServiceRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/IOServiceGetMatchingServiceRequest.java", "snippet": "public class IOServiceGetMatchingServiceRequest extends UnidbgStructure {\n\n public IOServiceGetMatchingServiceRequest(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int pad;\n public int size;\n\n public String getMatching() {\n Pointer pointer = getPointer().share(size());\n return new String(pointer.getByteArray(0, size), StandardCharsets.UTF_8).trim();\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"pad\", \"size\");\n }\n\n}" }, { "identifier": "MachMsgHeader", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/MachMsgHeader.java", "snippet": "public class MachMsgHeader extends UnidbgStructure implements DarwinSyscall {\n\n public MachMsgHeader(Pointer p) {\n super(p);\n }\n\n public int msgh_bits;\n public int msgh_size;\n public int msgh_remote_port;\n public int msgh_local_port;\n public int msgh_voucher_port;\n public int msgh_id;\n\n public void setMsgBits(boolean complex) {\n msgh_bits &= 0xff;\n if (complex) {\n msgh_bits |= MACH_MSGH_BITS_COMPLEX;\n }\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"msgh_bits\", \"msgh_size\", \"msgh_remote_port\", \"msgh_local_port\", \"msgh_voucher_port\", \"msgh_id\");\n }\n\n}" }, { "identifier": "MachPortOptions", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/MachPortOptions.java", "snippet": "public class MachPortOptions extends UnidbgStructure {\n\n public MachPortOptions(Pointer p) {\n super(p);\n }\n\n public int flags; /* Flags defining attributes for port */\n public MachPortLimits mpl; /* Message queue limit for port */\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"flags\", \"mpl\");\n }\n\n}" }, { "identifier": "MachPortReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/MachPortReply.java", "snippet": "public class MachPortReply extends UnidbgStructure {\n\n public MachPortReply(Pointer p) {\n super(p);\n }\n\n public MachMsgBody body;\n public MachMsgPortDescriptor port;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"body\", \"port\");\n }\n\n}" }, { "identifier": "MachPortSetAttributesReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/MachPortSetAttributesReply.java", "snippet": "public class MachPortSetAttributesReply extends UnidbgStructure {\n\n public MachPortSetAttributesReply(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int retCode;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"retCode\");\n }\n\n}" }, { "identifier": "MachPortSetAttributesRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/MachPortSetAttributesRequest.java", "snippet": "public class MachPortSetAttributesRequest extends UnidbgStructure {\n\n public MachPortSetAttributesRequest(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int name;\n public int flavor;\n public int count;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"name\", \"flavor\", \"count\");\n }\n\n}" }, { "identifier": "MachPortTypeReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/MachPortTypeReply.java", "snippet": "public class MachPortTypeReply extends UnidbgStructure {\n\n public MachPortTypeReply(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int retCode;\n public int ptype;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"retCode\", \"ptype\");\n }\n\n}" }, { "identifier": "MachPortTypeRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/MachPortTypeRequest.java", "snippet": "public class MachPortTypeRequest extends UnidbgStructure {\n\n public MachPortTypeRequest(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int name;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"name\");\n }\n\n}" }, { "identifier": "MachPortsLookupReply64", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/MachPortsLookupReply64.java", "snippet": "public class MachPortsLookupReply64 extends UnidbgStructure {\n\n public MachPortsLookupReply64(Pointer p) {\n super(p);\n }\n\n public int retCode;\n public int outPortLow;\n public int outPortHigh;\n public int mask;\n public int reserved1;\n public int reserved2;\n public int reserved3;\n public int cnt;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"retCode\", \"outPortLow\", \"outPortHigh\", \"mask\", \"reserved1\", \"reserved2\", \"reserved3\", \"cnt\");\n }\n}" }, { "identifier": "MachTimebaseInfo", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/MachTimebaseInfo.java", "snippet": "public class MachTimebaseInfo extends UnidbgStructure {\n\n public MachTimebaseInfo(Pointer p) {\n super(p);\n }\n\n public int numer;\n public int denom;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"numer\", \"denom\");\n }\n}" }, { "identifier": "NotifyServerCancelReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/NotifyServerCancelReply.java", "snippet": "public class NotifyServerCancelReply extends UnidbgStructure {\n\n public NotifyServerCancelReply(Pointer p) {\n super(p);\n }\n\n public MachMsgBody body;\n public int ret;\n public int code;\n public int status;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"body\", \"ret\", \"code\", \"status\");\n }\n}" }, { "identifier": "NotifyServerCancelRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/NotifyServerCancelRequest.java", "snippet": "public class NotifyServerCancelRequest extends UnidbgStructure {\n\n public NotifyServerCancelRequest(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int clientId;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"clientId\");\n }\n\n}" }, { "identifier": "NotifyServerGetStateReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/NotifyServerGetStateReply.java", "snippet": "public class NotifyServerGetStateReply extends UnidbgStructure {\n\n public NotifyServerGetStateReply(Pointer p) {\n super(p);\n }\n\n public MachMsgBody body;\n public int ret;\n public int code;\n public int version;\n public int pid;\n public int status;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"body\", \"ret\", \"code\", \"version\", \"pid\", \"status\");\n }\n}" }, { "identifier": "NotifyServerGetStateRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/NotifyServerGetStateRequest.java", "snippet": "public class NotifyServerGetStateRequest extends UnidbgStructure {\n\n public NotifyServerGetStateRequest(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int clientId;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"clientId\");\n }\n}" }, { "identifier": "NotifyServerRegisterCheck64Request", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/NotifyServerRegisterCheck64Request.java", "snippet": "public class NotifyServerRegisterCheck64Request extends UnidbgStructure {\n\n public NotifyServerRegisterCheck64Request(Pointer p) {\n super(p);\n }\n\n public int pad1;\n public int nameLow;\n public int nameHigh;\n public int pad2;\n public int namelen;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"pad1\", \"nameLow\", \"nameHigh\", \"pad2\", \"namelen\");\n }\n\n}" }, { "identifier": "NotifyServerRegisterCheckReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/NotifyServerRegisterCheckReply.java", "snippet": "public class NotifyServerRegisterCheckReply extends UnidbgStructure {\n\n public NotifyServerRegisterCheckReply(Pointer p) {\n super(p);\n }\n\n public MachMsgBody body;\n public int ret;\n public int code;\n public int shmsize;\n public int slot;\n public int clientId;\n public int status;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"body\", \"ret\", \"code\", \"shmsize\", \"slot\", \"clientId\", \"status\");\n }\n}" }, { "identifier": "NotifyServerRegisterMachPort64Request", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/NotifyServerRegisterMachPort64Request.java", "snippet": "public class NotifyServerRegisterMachPort64Request extends UnidbgStructure {\n\n public NotifyServerRegisterMachPort64Request(Pointer p) {\n super(p);\n }\n\n public int pad1;\n public int nameLow;\n public int nameHigh;\n public int pad2;\n public int namelen;\n public int flags;\n public int port;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"pad1\", \"nameLow\", \"nameHigh\", \"pad2\", \"namelen\", \"flags\", \"port\");\n }\n\n}" }, { "identifier": "NotifyServerRegisterMachPortReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/NotifyServerRegisterMachPortReply.java", "snippet": "public class NotifyServerRegisterMachPortReply extends UnidbgStructure {\n\n public NotifyServerRegisterMachPortReply(Pointer p) {\n super(p);\n }\n\n public MachMsgBody body;\n public int ret;\n public int code;\n public int clientId;\n public int status;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"body\", \"ret\", \"code\", \"clientId\", \"status\");\n }\n}" }, { "identifier": "NotifyServerRegisterPlain64Request", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/NotifyServerRegisterPlain64Request.java", "snippet": "public class NotifyServerRegisterPlain64Request extends UnidbgStructure {\n\n public NotifyServerRegisterPlain64Request(Pointer p) {\n super(p);\n }\n\n public int pad1;\n public int nameLow;\n public int nameHigh;\n public int pad2;\n public int nameCnt;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"pad1\", \"nameLow\", \"nameHigh\", \"pad2\", \"nameCnt\");\n }\n\n}" }, { "identifier": "NotifyServerRegisterPlainReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/NotifyServerRegisterPlainReply.java", "snippet": "public class NotifyServerRegisterPlainReply extends UnidbgStructure {\n\n public NotifyServerRegisterPlainReply(Pointer p) {\n super(p);\n }\n\n public MachMsgBody body;\n public int ret;\n public int code;\n public int clientId;\n public int status;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"body\", \"ret\", \"code\", \"clientId\", \"status\");\n }\n}" }, { "identifier": "ProcBsdShortInfo", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/ProcBsdShortInfo.java", "snippet": "public class ProcBsdShortInfo extends UnidbgStructure implements DarwinSyscall {\n\n public static final int SRUN = 2; /* Currently runnable. */\n public static final int P_SUGID = 0x00000100; /* Has set privileges since last exec */\n\n public ProcBsdShortInfo(Pointer p) {\n super(p);\n }\n\n public int pbsi_pid; /* process id */\n public int pbsi_ppid; /* process parent id */\n public int pbsi_pgid; /* process perp id */\n public int pbsi_status; /* p_stat value, SZOMB, SRUN, etc */\n public byte[] pbsi_comm = new byte[MAXCOMLEN]; /* upto 16 characters of process name */\n public int pbsi_flags; /* 64bit; emulated etc */\n public int pbsi_uid; /* current uid on process */\n public int pbsi_gid; /* current gid on process */\n public int pbsi_ruid; /* current ruid on process */\n public int pbsi_rgid; /* current tgid on process */\n public int pbsi_svuid; /* current svuid on process */\n public int pbsi_svgid; /* current svgid on process */\n public int pbsi_rfu; /* reserved for future use*/\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"pbsi_pid\", \"pbsi_ppid\", \"pbsi_pgid\", \"pbsi_status\", \"pbsi_comm\", \"pbsi_flags\",\n \"pbsi_uid\", \"pbsi_gid\", \"pbsi_ruid\", \"pbsi_rgid\", \"pbsi_svuid\", \"pbsi_svgid\", \"pbsi_rfu\");\n }\n}" }, { "identifier": "Pthread", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/Pthread.java", "snippet": "public abstract class Pthread extends UnidbgStructure {\n\n public static Pthread create(Emulator<?> emulator, Pointer pointer) {\n Pthread pthread = emulator.is64Bit() ? new Pthread64(pointer) : new Pthread32(pointer);\n pthread.unpack();\n return pthread;\n }\n\n private static final int MAXTHREADNAMESIZE = 64;\n public static final int PTHREAD_CREATE_JOINABLE = 1;\n\n public Pthread(Emulator<?> emulator, byte[] data) {\n super(emulator, data);\n }\n\n public Pthread(Pointer p) {\n super(p);\n }\n\n public byte[] pthread_name = new byte[MAXTHREADNAMESIZE]; // includes NUL\n\n public String getName() {\n return new String(pthread_name, StandardCharsets.UTF_8).trim();\n }\n\n public UnidbgPointer getTSD() {\n return (UnidbgPointer) getPointer().share(fieldOffset(\"self\"));\n }\n\n public Pointer getErrno() {\n return getPointer().share(fieldOffset(\"errno\"));\n }\n\n public abstract void setStack(Pointer stackAddress, long stackSize);\n\n public abstract void setThreadId(int threadId);\n\n public abstract int getThreadId();\n\n public abstract void setSig(long sig);\n\n public abstract void setDetached(int detached);\n\n public abstract void setExitValue(int value);\n\n public abstract void setSelf(Pointer self);\n public abstract void setMachThreadSelf(long machThreadSelf);\n\n public abstract Pointer getErrnoPointer(Emulator<?> emulator);\n\n}" }, { "identifier": "Pthread64", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/Pthread64.java", "snippet": "public class Pthread64 extends Pthread {\n\n public Pthread64(Pointer p) {\n super(p);\n }\n\n @Override\n public void setThreadId(int threadId) {\n this.thread_id = threadId;\n }\n\n @Override\n public int getThreadId() {\n return (int) thread_id;\n }\n\n public long sig; // _PTHREAD_SIG\n public long __cleanup_stack;\n public int childrun;\n public int lock;\n public int detached;\n public int pad0;\n public long thread_id; // 64-bit unique thread id\n public long fun; // thread start routine\n public long arg; // thread start routine argument\n public long exit_value; // thread exit value storage\n public long joiner_notify; // pthread_join notification\n public int max_tsd_key;\n public int cancel_state; // whether the thread can be cancelled\n public int cancel_error;\n public int err_no; // thread-local errno\n public long joiner;\n public SchedParam param;\n public TailqPthread64 plist; // global thread list\n\n public long stackaddr; // base of the stack\n public long stacksize; // size of stack (page multiple and >= PTHREAD_STACK_MIN)\n\n @Override\n public void setStack(Pointer stackAddress, long stackSize) {\n this.stackaddr = UnidbgPointer.nativeValue(stackAddress);\n this.stacksize = stackSize;\n }\n\n public long freeaddr; // stack/thread allocation base address\n public long freesize; // stack/thread allocation size\n public long guardsize; // guard page size in bytes\n\n @Override\n public void setSig(long sig) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void setDetached(int detached) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void setExitValue(int value) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"sig\", \"__cleanup_stack\", \"childrun\", \"lock\", \"detached\", \"pad0\", \"thread_id\", \"fun\", \"arg\",\n \"exit_value\", \"joiner_notify\", \"max_tsd_key\", \"cancel_state\", \"cancel_error\", \"err_no\", \"joiner\",\n \"param\", \"plist\", \"pthread_name\", \"stackaddr\", \"stacksize\", \"freeaddr\", \"freesize\", \"guardsize\",\n \"self\", \"errno\", \"mig_reply\", \"machThreadSelf\");\n }\n\n // thread specific data\n public long self;\n public long errno;\n public long mig_reply;\n public long machThreadSelf;\n\n @Override\n public void setSelf(Pointer self) {\n this.self = UnidbgPointer.nativeValue(self);\n }\n\n @Override\n public void setMachThreadSelf(long machThreadSelf) {\n this.machThreadSelf = machThreadSelf;\n }\n\n @Override\n public Pointer getErrnoPointer(Emulator<?> emulator) {\n return UnidbgPointer.pointer(emulator, errno);\n }\n}" }, { "identifier": "RLimit", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/RLimit.java", "snippet": "public class RLimit extends UnidbgStructure {\n\n public RLimit(Pointer p) {\n super(p);\n }\n\n public long rlim_cur; /* current (soft) limit */\n public long rlim_max; /* maximum value for rlim_cur */\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"rlim_cur\", \"rlim_max\");\n }\n}" }, { "identifier": "RUsage64", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/RUsage64.java", "snippet": "public class RUsage64 extends UnidbgStructure {\n\n public TimeVal64 ru_utime; /* user time used */\n public TimeVal64 ru_stime; /* system time used */\n public long ru_maxrss; /* max resident set size */\n public long ru_ixrss; /* integral shared text memory size */\n public long ru_idrss; /* integral unshared data size */\n public long ru_isrss; /* integral unshared stack size */\n public long ru_minflt; /* page reclaims */\n public long ru_majflt; /* page faults */\n public long ru_nswap; /* swaps */\n public long ru_inblock; /* block input operations */\n public long ru_oublock; /* block output operations */\n public long ru_msgsnd; /* messages sent */\n public long ru_msgrcv; /* messages received */\n public long ru_nsignals; /* signals received */\n public long ru_nvcsw; /* voluntary context switches */\n public long ru_nivcsw; /* involuntary context switches */\n\n public void fillDefault() {\n ru_utime.tv_sec = 1;\n ru_utime.tv_usec = System.nanoTime();\n ru_stime.tv_sec = 2;\n ru_stime.tv_usec = System.nanoTime();\n ru_maxrss = 0;\n ru_ixrss = 0;\n ru_idrss = 0;\n ru_isrss = 0;\n ru_minflt = 0;\n ru_majflt = 0;\n ru_nswap = 0;\n ru_inblock = 0;\n ru_oublock = 0;\n ru_msgsnd = 0;\n ru_msgrcv = 0;\n ru_nsignals = 0;\n ru_nvcsw = 0;\n ru_nivcsw = 0;\n }\n\n public RUsage64(Pointer p) {\n super(p);\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"ru_utime\", \"ru_stime\", \"ru_maxrss\", \"ru_ixrss\", \"ru_idrss\", \"ru_isrss\",\n \"ru_minflt\", \"ru_majflt\", \"ru_nswap\", \"ru_inblock\", \"ru_oublock\",\n \"ru_msgsnd\", \"ru_msgrcv\", \"ru_nsignals\", \"ru_nvcsw\", \"ru_nivcsw\");\n }\n}" }, { "identifier": "SemaphoreCreateReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/SemaphoreCreateReply.java", "snippet": "public class SemaphoreCreateReply extends UnidbgStructure {\n\n public SemaphoreCreateReply(Pointer p) {\n super(p);\n }\n\n public MachMsgBody body;\n public MachMsgPortDescriptor semaphore;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"body\", \"semaphore\");\n }\n\n}" }, { "identifier": "SemaphoreCreateRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/SemaphoreCreateRequest.java", "snippet": "public class SemaphoreCreateRequest extends UnidbgStructure {\n\n public SemaphoreCreateRequest(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int policy;\n public int value;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"policy\", \"value\");\n }\n\n}" }, { "identifier": "Stat64", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/Stat64.java", "snippet": "public class Stat64 extends StatStructure {\n\n public Stat64(Pointer p) {\n super(p);\n unpack();\n }\n\n public TimeSpec64 st_atimespec; /* time of last access */\n public TimeSpec64 st_mtimespec; /* time of last data modification */\n public TimeSpec64 st_ctimespec; /* time of last status change */\n public TimeSpec64 st_birthtimespec; /* time of file creation(birth) */\n\n @Override\n public void setSt_atimespec(long tv_sec, long tv_nsec) {\n st_atimespec.tv_sec = tv_sec;\n st_atimespec.tv_nsec = tv_nsec;\n }\n\n @Override\n public void setSt_mtimespec(long tv_sec, long tv_nsec) {\n st_mtimespec.tv_sec = tv_sec;\n st_mtimespec.tv_nsec = tv_nsec;\n }\n\n @Override\n public void setSt_ctimespec(long tv_sec, long tv_nsec) {\n st_ctimespec.tv_sec = tv_sec;\n st_ctimespec.tv_nsec = tv_nsec;\n }\n\n @Override\n public void setSt_birthtimespec(long tv_sec, long tv_nsec) {\n st_birthtimespec.tv_sec = tv_sec;\n st_birthtimespec.tv_nsec = tv_nsec;\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"st_dev\", \"st_mode\", \"st_nlink\", \"st_ino\", \"st_uid\", \"st_gid\", \"st_rdev\",\n \"st_atimespec\", \"st_mtimespec\", \"st_ctimespec\", \"st_birthtimespec\",\n \"st_size\", \"st_blocks\", \"st_blksize\", \"st_flags\", \"st_gen\");\n }\n\n}" }, { "identifier": "StatFS", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/StatFS.java", "snippet": "public class StatFS extends UnidbgStructure {\n\n private static final int MFSTYPENAMELEN = 16; /* length of fs type name including null */\n private static final int MAXPATHLEN = 1024; /* max bytes in pathname */\n\n public StatFS(byte[] data) {\n super(data);\n }\n\n public StatFS(Pointer p) {\n super(p);\n }\n\n public int f_bsize; /* fundamental file system block size */\n public int f_iosize; /* optimal transfer block size */\n public long f_blocks; /* total data blocks in file system */\n public long f_bfree; /* free blocks in fs */\n public long f_bavail; /* free blocks avail to non-superuser */\n public long f_files; /* total file nodes in file system */\n public long f_ffree; /* free file nodes in fs */\n\n public long f_fsid; /* file system id */\n public int f_owner; /* user that mounted the filesystem */\n public int f_type; /* type of filesystem */\n public int f_flags; /* copy of mount exported flags */\n public int f_fssubtype; /* fs sub-type (flavor) */\n\n public byte[] f_fstypename = new byte[MFSTYPENAMELEN]; /* fs type name */\n public byte[] f_mntonname = new byte[MAXPATHLEN]; /* directory on which mounted */\n public byte[] f_mntfromname = new byte[MAXPATHLEN]; /* mounted filesystem */\n public int[] f_reserved = new int[8]; /* For future use */\n\n public void setFsTypeName(String fsTypeName) {\n if (fsTypeName == null) {\n throw new NullPointerException();\n }\n byte[] data = fsTypeName.getBytes(StandardCharsets.UTF_8);\n if (data.length + 1 >= MFSTYPENAMELEN) {\n throw new IllegalStateException(\"Invalid MFSTYPENAMELEN: \" + MFSTYPENAMELEN);\n }\n f_fstypename = Arrays.copyOf(data, MFSTYPENAMELEN);\n }\n\n public void setMntOnName(String mntOnName) {\n if (mntOnName == null) {\n throw new NullPointerException();\n }\n byte[] data = mntOnName.getBytes(StandardCharsets.UTF_8);\n if (data.length + 1 >= MAXPATHLEN) {\n throw new IllegalStateException(\"Invalid MAXPATHLEN: \" + MAXPATHLEN);\n }\n f_mntonname = Arrays.copyOf(data, MAXPATHLEN);\n }\n\n public void setMntFromName(String mntFromName) {\n if (mntFromName == null) {\n throw new NullPointerException();\n }\n byte[] data = mntFromName.getBytes(StandardCharsets.UTF_8);\n if (data.length + 1 >= MAXPATHLEN) {\n throw new IllegalStateException(\"Invalid MAXPATHLEN: \" + MAXPATHLEN);\n }\n f_mntfromname = Arrays.copyOf(data, MAXPATHLEN);\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"f_bsize\", \"f_iosize\", \"f_blocks\", \"f_bfree\", \"f_bavail\", \"f_files\", \"f_ffree\", \"f_fsid\", \"f_owner\",\n \"f_type\", \"f_flags\", \"f_fssubtype\", \"f_fstypename\", \"f_mntonname\", \"f_mntfromname\", \"f_reserved\");\n }\n\n}" }, { "identifier": "TaskBasicInfoReply64V2", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/TaskBasicInfoReply64V2.java", "snippet": "public class TaskBasicInfoReply64V2 extends UnidbgStructure {\n\n public TaskBasicInfoReply64V2(Pointer p) {\n super(p);\n setAlignType(Structure.ALIGN_NONE);\n }\n\n public NDR_record NDR;\n public int retCode;\n public int task_info_outCnt;\n public TaskBasicInfo64V2 basicInfo;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"retCode\", \"task_info_outCnt\", \"basicInfo\");\n }\n\n}" }, { "identifier": "TaskDyldInfoReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/TaskDyldInfoReply.java", "snippet": "public class TaskDyldInfoReply extends UnidbgStructure {\n\n public TaskDyldInfoReply(Pointer p) {\n super(p);\n setAlignType(Structure.ALIGN_NONE);\n }\n\n public NDR_record NDR;\n public int retCode;\n public int task_info_outCnt;\n public TaskDyldInfo dyldInfo;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"retCode\", \"task_info_outCnt\", \"dyldInfo\");\n }\n\n}" }, { "identifier": "TaskGetExceptionPortsReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/TaskGetExceptionPortsReply.java", "snippet": "public class TaskGetExceptionPortsReply extends UnidbgStructure {\n\n public TaskGetExceptionPortsReply(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int retCode;\n public int[] header = new int[32];\n public int masksCnt;\n public byte[] reserved = new byte[0x100];\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"retCode\", \"header\", \"masksCnt\", \"reserved\");\n }\n\n}" }, { "identifier": "TaskGetExceptionPortsRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/TaskGetExceptionPortsRequest.java", "snippet": "public class TaskGetExceptionPortsRequest extends UnidbgStructure {\n\n public TaskGetExceptionPortsRequest(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int exceptionMask;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"exceptionMask\");\n }\n\n}" }, { "identifier": "TaskGetSpecialPortReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/TaskGetSpecialPortReply.java", "snippet": "public class TaskGetSpecialPortReply extends UnidbgStructure {\n\n public TaskGetSpecialPortReply(Pointer p) {\n super(p);\n }\n\n public MachMsgBody body;\n public MachMsgPortDescriptor port;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"body\", \"port\");\n }\n\n}" }, { "identifier": "TaskGetSpecialPortRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/TaskGetSpecialPortRequest.java", "snippet": "public class TaskGetSpecialPortRequest extends UnidbgStructure {\n\n public TaskGetSpecialPortRequest(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int which;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"which\");\n }\n\n}" }, { "identifier": "TaskInfoRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/TaskInfoRequest.java", "snippet": "public class TaskInfoRequest extends UnidbgStructure {\n\n public static final int TASK_BASIC_INFO_32 = 4; /* basic information */\n public static final int TASK_BASIC_INFO_64 = 5; /* 64-bit capable basic info */\n public static final int TASK_DYLD_INFO = 17;\n\n /* Don't use this, use MACH_TASK_BASIC_INFO instead */\n /* Compatibility for old 32-bit mach_vm_*_t */\n public static final int TASK_BASIC_INFO_64_2 = 18; /* 64-bit capable basic info */\n public static final int TASK_VM_INFO = 22;\n\n public TaskInfoRequest(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int flavor;\n public int task_info_outCnt;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"flavor\", \"task_info_outCnt\");\n }\n}" }, { "identifier": "TaskSetExceptionPortsReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/TaskSetExceptionPortsReply.java", "snippet": "public class TaskSetExceptionPortsReply extends UnidbgStructure {\n\n public TaskSetExceptionPortsReply(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int retCode;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"retCode\");\n }\n\n}" }, { "identifier": "TaskSetExceptionPortsRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/TaskSetExceptionPortsRequest.java", "snippet": "public class TaskSetExceptionPortsRequest extends UnidbgStructure {\n\n public TaskSetExceptionPortsRequest(Pointer p) {\n super(p);\n }\n\n public int action;\n public int newPort;\n public int ret;\n public int mask;\n public NDR_record NDR;\n public int exceptionMask;\n public int behavior;\n public int newFlavor;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"action\", \"newPort\", \"ret\", \"mask\", \"NDR\", \"exceptionMask\", \"behavior\", \"newFlavor\");\n }\n\n}" }, { "identifier": "TaskThreadsReply64", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/TaskThreadsReply64.java", "snippet": "public class TaskThreadsReply64 extends UnidbgStructure {\n\n public TaskThreadsReply64(Pointer p) {\n super(p);\n setAlignType(ALIGN_NONE);\n }\n\n public MachMsgBody body;\n public long act_list; // pointer\n public int mask;\n public long pad1;\n public int pad2;\n public int act_listCnt;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"body\", \"act_list\", \"mask\", \"pad1\", \"pad2\", \"act_listCnt\");\n }\n\n}" }, { "identifier": "TaskVmInfoReply64", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/TaskVmInfoReply64.java", "snippet": "public class TaskVmInfoReply64 extends UnidbgStructure {\n\n public TaskVmInfoReply64(Pointer p) {\n super(p);\n setAlignType(Structure.ALIGN_NONE);\n }\n\n public NDR_record NDR;\n public int retCode;\n public int task_info_outCnt;\n public TaskVmInfo64 vmInfo;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"retCode\", \"task_info_outCnt\", \"vmInfo\");\n }\n\n}" }, { "identifier": "ThreadBasicInfoReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/ThreadBasicInfoReply.java", "snippet": "public class ThreadBasicInfoReply extends UnidbgStructure {\n\n public ThreadBasicInfoReply(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int retCode;\n public int outCnt;\n public ThreadBasicInfo info;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"retCode\", \"outCnt\", \"info\");\n }\n\n}" }, { "identifier": "ThreadInfoRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/ThreadInfoRequest.java", "snippet": "public class ThreadInfoRequest extends UnidbgStructure {\n\n public ThreadInfoRequest(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int flavor;\n public int infoCount; // THREAD_BASIC_INFO_COUNT\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"flavor\", \"infoCount\");\n }\n\n}" }, { "identifier": "ThreadStateReply64", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/ThreadStateReply64.java", "snippet": "public class ThreadStateReply64 extends UnidbgStructure {\n\n public static class ThreadState64 extends UnidbgStructure {\n public ThreadState64(Pointer p) {\n super(p);\n }\n public long[] __x = new long[29]; /* General purpose registers x0-x28 */\n public long __fp; /* Frame pointer x29 */\n public long __lr; /* Link register x30 */\n public long __sp; /* Stack pointer x31 */\n public long __pc; /* Program counter */\n public int __cpsr; /* Current program status register */\n public int __pad; /* Same size for 32-bit or 64-bit clients */\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"__x\", \"__fp\", \"__lr\", \"__sp\", \"__pc\", \"__cpsr\", \"__pad\");\n }\n }\n\n public ThreadStateReply64(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int retCode;\n public int outCnt;\n public ThreadState64 state;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"retCode\", \"outCnt\", \"state\");\n }\n}" }, { "identifier": "ThreadStateRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/ThreadStateRequest.java", "snippet": "public class ThreadStateRequest extends UnidbgStructure {\n\n public static final int ARM_THREAD_STATE = 1;\n public static final int ARM_THREAD_STATE64 = 6;\n\n public static final int ARM_THREAD_STATE_COUNT = 17;\n public static final int ARM_THREAD_STATE64_COUNT = 68;\n\n public ThreadStateRequest(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int flavor;\n public int stateCount; // ARM_THREAD_STATE_COUNT or ARM_THREAD_STATE64_COUNT\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"flavor\", \"stateCount\");\n }\n\n}" }, { "identifier": "VmCopy64Request", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/VmCopy64Request.java", "snippet": "public class VmCopy64Request extends UnidbgStructure {\n\n public VmCopy64Request(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public long source_address;\n public long size;\n public long dest_address;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"source_address\", \"size\", \"dest_address\");\n }\n}" }, { "identifier": "VmCopyReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/VmCopyReply.java", "snippet": "public class VmCopyReply extends UnidbgStructure {\n\n public VmCopyReply(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int retCode;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"retCode\");\n }\n}" }, { "identifier": "VmReadOverwriteReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/VmReadOverwriteReply.java", "snippet": "public class VmReadOverwriteReply extends UnidbgStructure {\n\n public VmReadOverwriteReply(Pointer p) {\n super(p);\n setAlignType(ALIGN_NONE);\n }\n\n public NDR_record NDR;\n public int retCode;\n public long outSize;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"retCode\", \"outSize\");\n }\n}" }, { "identifier": "VmReadOverwriteRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/VmReadOverwriteRequest.java", "snippet": "public class VmReadOverwriteRequest extends UnidbgStructure {\n\n public VmReadOverwriteRequest(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public long address;\n public long size;\n public long data;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"address\", \"size\", \"data\");\n }\n\n}" }, { "identifier": "VmRegion64Reply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/VmRegion64Reply.java", "snippet": "public class VmRegion64Reply extends UnidbgStructure {\n\n public VmRegion64Reply(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int retCode1;\n public int retCode2;\n public int pad1;\n public int pad2;\n public long address;\n public long size;\n public int outCnt;\n public VmRegionBasicInfo64 info;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"retCode1\", \"retCode2\", \"pad1\", \"pad2\", \"address\", \"size\", \"outCnt\", \"info\");\n }\n\n}" }, { "identifier": "VmRegion64Request", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/VmRegion64Request.java", "snippet": "public class VmRegion64Request extends UnidbgStructure {\n\n public static final int VM_REGION_BASIC_INFO_64 = 9;\n public static final int VM_REGION_BASIC_INFO_COUNT_64 = 9;\n\n public NDR_record NDR;\n public long address;\n public int flavor;\n public int infoCount; // VM_REGION_BASIC_INFO_COUNT_64\n\n public VmRegion64Request(Pointer p) {\n super(p);\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"address\", \"flavor\", \"infoCount\");\n }\n\n}" }, { "identifier": "VmRegionRecurse64Reply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/VmRegionRecurse64Reply.java", "snippet": "public class VmRegionRecurse64Reply extends UnidbgStructure {\n\n public VmRegionRecurse64Reply(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public int retCode;\n public int addressLow;\n public int addressHigh;\n public int sizeLow;\n public int sizeHigh;\n public int nestingDepth;\n public int infoCnt = 7;\n public VmRegionSubMapShortInfo64 info;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"retCode\", \"addressLow\", \"addressHigh\", \"sizeLow\", \"sizeHigh\", \"nestingDepth\", \"infoCnt\", \"info\");\n }\n\n}" }, { "identifier": "VmRegionRecurse64Request", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/VmRegionRecurse64Request.java", "snippet": "public class VmRegionRecurse64Request extends UnidbgStructure {\n\n public VmRegionRecurse64Request(Pointer p) {\n super(p);\n }\n\n public NDR_record NDR;\n public long address;\n public int nestingDepth;\n public int infoCnt;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"NDR\", \"address\", \"nestingDepth\", \"infoCnt\");\n }\n\n public long getAddress() {\n return address;\n }\n\n}" }, { "identifier": "VmRemapReply", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/VmRemapReply.java", "snippet": "public class VmRemapReply extends UnidbgStructure {\n\n public VmRemapReply(Pointer p) {\n super(p);\n }\n\n public MachMsgBody body;\n\n public int pad;\n public int retCode;\n public int target_address1;\n public int target_address2;\n public int cur_protection;\n public int max_protection;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"body\", \"pad\", \"retCode\", \"target_address1\", \"target_address2\", \"cur_protection\", \"max_protection\");\n }\n\n}" }, { "identifier": "VmRemapRequest", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/VmRemapRequest.java", "snippet": "public class VmRemapRequest extends UnidbgStructure {\n\n public VmRemapRequest(Pointer p) {\n super(p);\n }\n\n public MachMsgBody body;\n public MachMsgPortDescriptor descriptor;\n public NDR_record NDR;\n\n public long target_address;\n public long size;\n public long mask;\n public int anywhere;\n public int src_address1;\n public int src_address2;\n public int copy;\n public int inheritance;\n\n public long getSourceAddress() {\n return src_address1 | ((long) src_address2 << 32L);\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"body\", \"descriptor\", \"NDR\", \"target_address\", \"size\", \"mask\", \"anywhere\", \"src_address1\", \"src_address2\", \"copy\", \"inheritance\");\n }\n}" }, { "identifier": "IfMsgHeader", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/sysctl/IfMsgHeader.java", "snippet": "public final class IfMsgHeader extends UnidbgStructure {\n\n public IfMsgHeader(Pointer p) {\n super(p);\n }\n\n public short\tifm_msglen;\t/* to skip non-understood messages */\n public byte ifm_version;\t/* future binary compatability */\n public byte ifm_type;\t/* message type */\n public int\t\tifm_addrs;\t/* like rtm_addrs */\n public int\t\tifm_flags;\t/* value of if_flags */\n public short\tifm_index;\t/* index for associated ifp */\n public IfData ifm_data;\t/* statistics and other data about if */\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"ifm_msglen\", \"ifm_version\", \"ifm_type\", \"ifm_addrs\", \"ifm_flags\", \"ifm_index\", \"ifm_data\");\n }\n\n}" }, { "identifier": "KInfoProc64", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/sysctl/KInfoProc64.java", "snippet": "public class KInfoProc64 extends UnidbgStructure {\n\n public KInfoProc64(Pointer p) {\n super(p);\n }\n\n public ExternProc64 kp_proc; /* proc structure */\n public EProc64 kp_eproc;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"kp_proc\", \"kp_eproc\");\n }\n\n}" }, { "identifier": "SockAddrDL", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/sysctl/SockAddrDL.java", "snippet": "public class SockAddrDL extends UnidbgStructure {\n\n public SockAddrDL(Pointer p) {\n super(p);\n }\n\n public byte sdl_len;\t/* Total length of sockaddr */\n public byte sdl_family;\t/* AF_LINK */\n public short sdl_index;\t/* if != 0, system given index for interface */\n public byte sdl_type;\t/* interface type */\n public byte sdl_nlen;\t/* interface name length, no trailing 0 reqd. */\n public byte sdl_alen;\t/* link level address length */\n public byte sdl_slen;\t/* link layer selector length */\n public byte[] sdl_data = new byte[12];\t/* minimum work area, can be larger; contains both if name and ll address */\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"sdl_len\", \"sdl_family\", \"sdl_index\", \"sdl_type\", \"sdl_nlen\", \"sdl_alen\", \"sdl_slen\", \"sdl_data\");\n }\n\n}" }, { "identifier": "TaskDyldInfo", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/sysctl/TaskDyldInfo.java", "snippet": "public class TaskDyldInfo extends UnidbgStructure {\n\n private static final Log log = LogFactory.getLog(TaskDyldInfo.class);\n\n private static final String DYLD_VERSION = \"324.1\";\n\n private static final int TASK_DYLD_ALL_IMAGE_INFO_32 = 0; /* format value */\n private static final int TASK_DYLD_ALL_IMAGE_INFO_64 = 1; /* format value */\n\n public TaskDyldInfo(Pointer p) {\n super(p);\n setAlignType(Structure.ALIGN_NONE);\n }\n\n private static MemoryBlock infoArrayBlock;\n private static Pointer dyldVersion;\n private static MemoryBlock dyldAllImageInfosAddressBlock;\n\n public void allocateAllImage(Emulator<?> emulator) {\n SvcMemory svcMemory = emulator.getSvcMemory();\n MachOLoader loader = (MachOLoader) emulator.getMemory();\n Collection<Module> modules = loader.getLoadedModules();\n for (Iterator<Module> iterator = modules.iterator(); iterator.hasNext(); ) {\n Module module = iterator.next();\n if (module.isVirtual()) {\n iterator.remove();\n }\n }\n if (dyldVersion == null) {\n dyldVersion = svcMemory.writeStackString(DYLD_VERSION);\n }\n if (infoArrayBlock == null) {\n infoArrayBlock = loader.malloc(emulator.getPageAlign(), true);\n }\n if (dyldAllImageInfosAddressBlock == null) {\n dyldAllImageInfosAddressBlock = loader.malloc(emulator.getPageAlign(), true);\n }\n\n if (emulator.getSyscallHandler().isVerbose()) {\n System.out.printf(\"task_info TASK_DYLD_INFO called with %d modules from %s%n\", modules.size(), emulator.getContext().getLRPointer());\n }\n if (log.isTraceEnabled()) {\n emulator.attach().debug();\n }\n\n MachOModule libdyld = (MachOModule) emulator.getMemory().findModule(\"libdyld.dylib\");\n if (emulator.is64Bit()) {\n allocateAllImage64(svcMemory, modules, libdyld);\n } else {\n allocateAllImage32(svcMemory, modules, libdyld);\n }\n }\n\n private void allocateAllImage64(SvcMemory svcMemory, Collection<Module> modules, MachOModule libdyld) {\n int all_image_info_size = UnidbgStructure.calculateSize(DyldAllImageInfos64.class);\n\n this.all_image_info_format = TASK_DYLD_ALL_IMAGE_INFO_64;\n this.all_image_info_size = all_image_info_size;\n UnidbgPointer all_image_info_addr = dyldAllImageInfosAddressBlock.getPointer();\n this.all_image_info_addr = all_image_info_addr.peer;\n\n int size = UnidbgStructure.calculateSize(DyldImageInfo64.class);\n Pointer infoArray = infoArrayBlock.getPointer();\n Pointer pointer = infoArray;\n for (Module module : modules) {\n MachOModule mm = (MachOModule) module;\n DyldImageInfo64 info = new DyldImageInfo64(pointer);\n info.imageLoadAddress = mm.machHeader;\n info.imageFilePath = UnidbgPointer.nativeValue(mm.createPathMemory(svcMemory));\n info.imageFileModDate = 0;\n info.pack();\n pointer = pointer.share(size);\n }\n\n DyldAllImageInfos64 infos = new DyldAllImageInfos64(all_image_info_addr);\n infos.version = 14;\n infos.infoArrayCount = modules.size();\n infos.infoArray = UnidbgPointer.nativeValue(infoArray);\n infos.libSystemInitialized = Constants.YES;\n infos.dyldImageLoadAddress = libdyld == null ? 0x0L : libdyld.machHeader;\n infos.dyldVersion = UnidbgPointer.nativeValue(dyldVersion);\n infos.uuidArrayCount = 0;\n infos.uuidArray = 0L;\n infos.dyldAllImageInfosAddress = UnidbgPointer.nativeValue(all_image_info_addr);\n infos.initialImageCount = modules.size();\n infos.pack();\n }\n\n private void allocateAllImage32(SvcMemory svcMemory, Collection<Module> modules, MachOModule libdyld) {\n int all_image_info_size = UnidbgStructure.calculateSize(DyldAllImageInfos32.class);\n\n this.all_image_info_format = TASK_DYLD_ALL_IMAGE_INFO_32;\n this.all_image_info_size = all_image_info_size;\n UnidbgPointer all_image_info_addr = dyldAllImageInfosAddressBlock.getPointer();\n this.all_image_info_addr = all_image_info_addr.peer;\n\n int size = UnidbgStructure.calculateSize(DyldImageInfo32.class);\n Pointer infoArray = infoArrayBlock.getPointer();\n Pointer pointer = infoArray;\n for (Module module : modules) {\n MachOModule mm = (MachOModule) module;\n DyldImageInfo32 info = new DyldImageInfo32(pointer);\n info.imageLoadAddress = (int) mm.machHeader;\n info.imageFilePath = (int) UnidbgPointer.nativeValue(mm.createPathMemory(svcMemory));\n info.imageFileModDate = 0;\n info.pack();\n pointer = pointer.share(size);\n }\n\n DyldAllImageInfos32 infos = new DyldAllImageInfos32(all_image_info_addr);\n infos.version = 14;\n infos.infoArrayCount = modules.size();\n infos.infoArray = (int) UnidbgPointer.nativeValue(infoArray);\n infos.libSystemInitialized = Constants.YES;\n infos.dyldImageLoadAddress = libdyld == null ? 0x0 : (int) libdyld.machHeader;\n infos.dyldVersion = (int) UnidbgPointer.nativeValue(dyldVersion);\n infos.uuidArrayCount = 0;\n infos.uuidArray = 0;\n infos.dyldAllImageInfosAddress = (int) UnidbgPointer.nativeValue(all_image_info_addr);\n infos.initialImageCount = modules.size();\n infos.pack();\n }\n\n public long all_image_info_addr;\n public long all_image_info_size;\n public int all_image_info_format;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"all_image_info_addr\", \"all_image_info_size\", \"all_image_info_format\");\n }\n}" }, { "identifier": "TaskVmInfo64", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/sysctl/TaskVmInfo64.java", "snippet": "public class TaskVmInfo64 extends UnidbgStructure {\n\n public TaskVmInfo64(Pointer p) {\n super(p);\n }\n\n public TaskVmInfo64(byte[] data) {\n super(data);\n }\n\n public long virtual_size; /* virtual memory size (bytes) */\n public int region_count; /* number of memory regions */\n public int page_size;\n public long resident_size; /* resident memory size (bytes) */\n public long resident_size_peak; /* peak resident size (bytes) */\n\n public long device;\n public long device_peak;\n public long internal;\n public long internal_peak;\n public long external;\n public long external_peak;\n public long reusable;\n public long reusable_peak;\n public long purgeable_volatile_pmap;\n public long purgeable_volatile_resident;\n public long purgeable_volatile_virtual;\n public long compressed;\n public long compressed_peak;\n public long compressed_lifetime;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"virtual_size\", \"region_count\", \"page_size\", \"resident_size\", \"resident_size_peak\",\n \"device\", \"device_peak\", \"internal\", \"internal_peak\", \"external\", \"external_peak\",\n \"reusable\", \"reusable_peak\", \"purgeable_volatile_pmap\", \"purgeable_volatile_resident\",\n \"purgeable_volatile_virtual\", \"compressed\", \"compressed_peak\", \"compressed_lifetime\");\n }\n}" }, { "identifier": "MemoryMap", "path": "unidbg-api/src/main/java/com/github/unidbg/memory/MemoryMap.java", "snippet": "public class MemoryMap implements Serializable {\n\n public final long base;\n public final long size;\n public int prot;\n\n public MemoryMap(long base, long size, int prot) {\n this.base = base;\n this.size = size;\n this.prot = prot;\n }\n\n @Override\n public void serialize(DataOutput out) throws IOException {\n out.writeLong(base);\n out.writeLong(size);\n out.writeInt(prot);\n }\n\n @Override\n public String toString() {\n return \"MemoryMap{\" +\n \"base=0x\" + Long.toHexString(base) +\n \", size=0x\" + Long.toHexString(size) +\n \", prot=\" + prot +\n '}';\n }\n}" }, { "identifier": "SvcMemory", "path": "unidbg-api/src/main/java/com/github/unidbg/memory/SvcMemory.java", "snippet": "public interface SvcMemory extends StackMemory {\n\n UnidbgPointer allocate(int size, String label);\n\n UnidbgPointer allocateSymbolName(String name);\n\n UnidbgPointer registerSvc(Svc svc);\n\n Svc getSvc(int svcNumber);\n\n MemRegion findRegion(long addr);\n\n long getBase();\n int getSize();\n\n}" }, { "identifier": "UnidbgPointer", "path": "unidbg-api/src/main/java/com/github/unidbg/pointer/UnidbgPointer.java", "snippet": "public class UnidbgPointer extends Pointer implements PointerArg {\n\n private static final Log log = LogFactory.getLog(UnidbgPointer.class);\n\n private final Emulator<?> emulator;\n private final Backend backend;\n public final long peer;\n private final int pointerSize;\n\n public static long nativeValue(Pointer ptr) {\n if (ptr == null) {\n return 0L;\n }\n UnidbgPointer up = (UnidbgPointer) ptr;\n return up.emulator.is64Bit() ? up.peer : up.toUIntPeer();\n }\n\n public long toUIntPeer() {\n return peer & 0xffffffffL;\n }\n\n public int toIntPeer() {\n return (int) toUIntPeer();\n }\n\n private final MemoryWriteListener listener;\n\n UnidbgPointer(Emulator<?> emulator, byte[] data) {\n super(0);\n\n this.emulator = emulator;\n this.backend = data == null ? null : new ByteArrayBackend(data);\n this.peer = 0L;\n this.pointerSize = 0;\n this.listener = null;\n }\n\n private UnidbgPointer(Emulator<?> emulator, long peer, int pointerSize) {\n super(0);\n\n this.emulator = emulator;\n this.backend = emulator.getBackend();\n this.peer = peer;\n this.pointerSize = pointerSize;\n\n if (emulator instanceof MemoryWriteListener) {\n listener = (MemoryWriteListener) emulator;\n } else {\n listener = null;\n }\n }\n\n private long size;\n\n public UnidbgPointer setSize(long size) {\n if (size < 0) {\n throw new IllegalArgumentException(\"size=\" + size);\n }\n this.size = size;\n return this;\n }\n\n public long getSize() {\n return size;\n }\n\n public static UnidbgPointer pointer(Emulator<?> emulator, long addr) {\n long peer = emulator.is64Bit() ? addr : addr & 0xffffffffL;\n return peer == 0 ? null : new UnidbgPointer(emulator, peer, emulator.getPointerSize());\n }\n\n public static UnidbgPointer pointer(Emulator<?> emulator, Number number) {\n return pointer(emulator, number.longValue());\n }\n\n public static UnidbgPointer register(Emulator<?> emulator, int reg) {\n return pointer(emulator, emulator.getBackend().reg_read(reg));\n }\n\n @Override\n public long indexOf(long offset, byte value) {\n throw new AbstractMethodError();\n }\n\n @Override\n public void read(long offset, byte[] buf, int index, int length) {\n byte[] data = getByteArray(offset, length);\n System.arraycopy(data, 0, buf, index, length);\n }\n\n @Override\n public void read(long offset, short[] buf, int index, int length) {\n throw new AbstractMethodError();\n }\n\n @Override\n public void read(long offset, char[] buf, int index, int length) {\n throw new AbstractMethodError();\n }\n\n @Override\n public void read(long offset, int[] buf, int index, int length) {\n for (int i = index; i < length; i++) {\n buf[i] = getInt((i - index) * 4L + offset);\n }\n }\n\n @Override\n public void read(long offset, long[] buf, int index, int length) {\n for (int i = index; i < length; i++) {\n buf[i] = getLong((i - index) * 8L + offset);\n }\n }\n\n @Override\n public void read(long offset, float[] buf, int index, int length) {\n \t for (int i = index; i < length; i++) {\n buf[i] = getFloat((i - index) * 4L + offset);\n }\n }\n\n @Override\n public void read(long offset, double[] buf, int index, int length) {\n \t for (int i = index; i < length; i++) {\n buf[i] = getDouble((i - index) * 8L + offset);\n }\n }\n\n @Override\n public void read(long offset, Pointer[] buf, int index, int length) {\n throw new AbstractMethodError();\n }\n\n public void write(byte[] buf) {\n write(0, buf, 0, buf.length);\n }\n\n @Override\n public void write(long offset, byte[] buf, int index, int length) {\n if (size > 0) {\n if (offset < 0) {\n throw new IllegalArgumentException();\n }\n\n if (size - offset < length) {\n throw new InvalidMemoryAccessException();\n }\n }\n\n byte[] data;\n if (index == 0 && buf.length == length) {\n data = buf;\n } else {\n data = new byte[length];\n System.arraycopy(buf, index, data, 0, length);\n }\n long address = peer + offset;\n backend.mem_write(address, data);\n if (listener != null) {\n listener.onSystemWrite(address, data);\n }\n }\n\n @Override\n public void write(long offset, short[] buf, int index, int length) {\n for (int i = index; i < length; i++) {\n setShort((i - index) * 2L + offset, buf[i]);\n }\n }\n\n @Override\n public void write(long offset, char[] buf, int index, int length) {\n throw new AbstractMethodError();\n }\n\n @Override\n public void write(long offset, int[] buf, int index, int length) {\n for (int i = index; i < length; i++) {\n setInt((i - index) * 4L + offset, buf[i]);\n }\n }\n\n @Override\n public void write(long offset, long[] buf, int index, int length) {\n for (int i = index; i < length; i++) {\n setLong((i - index) * 8L + offset, buf[i]);\n }\n }\n\n @Override\n public void write(long offset, float[] buf, int index, int length) {\n for (int i = index; i < length; i++) {\n setFloat((i - index) * 4L + offset, buf[i]);\n }\n }\n\n @Override\n public void write(long offset, double[] buf, int index, int length) {\n for (int i = index; i < length; i++) {\n setDouble((i - index) * 8L + offset, buf[i]);\n }\n }\n\n @Override\n public void write(long offset, Pointer[] buf, int index, int length) {\n throw new AbstractMethodError();\n }\n\n @Override\n public byte getByte(long offset) {\n return getByteArray(offset, 1)[0];\n }\n\n @Override\n public char getChar(long offset) {\n return getByteBuffer(offset, 2).getChar();\n }\n\n @Override\n public short getShort(long offset) {\n return getByteBuffer(offset, 2).getShort();\n }\n\n @Override\n public int getInt(long offset) {\n return getByteBuffer(offset, 4).getInt();\n }\n\n @Override\n public long getLong(long offset) {\n return getByteBuffer(offset, 8).getLong();\n }\n\n @Override\n public NativeLong getNativeLong(long offset) {\n throw new AbstractMethodError();\n }\n\n @Override\n public float getFloat(long offset) {\n return getByteBuffer(offset, 4).getFloat();\n }\n\n @Override\n public double getDouble(long offset) {\n return getByteBuffer(offset, 8).getDouble();\n }\n\n @Override\n public UnidbgPointer getPointer(long offset) {\n return pointer(emulator, pointerSize == 4 ? (Number) getInt(offset) : (Number) getLong(offset));\n }\n\n @Override\n public byte[] getByteArray(long offset, int arraySize) {\n if (size > 0 && offset + arraySize > size) {\n throw new InvalidMemoryAccessException();\n }\n\n if (arraySize < 0 || arraySize >= 0x7ffffff) {\n throw new InvalidMemoryAccessException(\"Invalid array size: \" + arraySize);\n }\n return backend.mem_read(peer + offset, arraySize);\n }\n\n @Override\n public int[] getIntArray(long offset, int arraySize) {\n if (arraySize < 0 || arraySize >= 0x7ffffff) {\n throw new InvalidMemoryAccessException(\"Invalid array size: \" + arraySize);\n }\n\n int[] array = new int[arraySize];\n for (int i = 0; i < arraySize; i++) {\n array[i] = getInt(offset + i * 4);\n }\n return array;\n }\n\n @Override\n public ByteBuffer getByteBuffer(long offset, long length) {\n return ByteBuffer.wrap(getByteArray(offset, (int) length)).order(ByteOrder.LITTLE_ENDIAN);\n }\n\n @Override\n public String getWideString(long offset) {\n throw new AbstractMethodError();\n }\n\n @Override\n public String getString(long offset) {\n return getString(offset, \"UTF-8\");\n }\n\n @Override\n public String getString(long offset, String encoding) {\n long addr = peer + offset;\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream(0x40);\n while (true) {\n byte[] data = backend.mem_read(addr, 0x10);\n int length = data.length;\n for (int i = 0; i < data.length; i++) {\n if (data[i] == 0) {\n length = i;\n break;\n }\n }\n baos.write(data, 0, length);\n addr += length;\n\n if (length < data.length) { // reach zero\n break;\n }\n\n if (baos.size() > 0x40000) { // 256k\n throw new IllegalStateException(\"buffer overflow\");\n }\n\n if (size > 0 && offset + baos.size() > size) {\n throw new InvalidMemoryAccessException();\n }\n }\n\n try {\n String ret = baos.toString(encoding);\n log.debug(\"getString pointer=\" + this + \", size=\" + baos.size() + \", encoding=\" + encoding + \", ret=\" + ret);\n return ret;\n } catch (UnsupportedEncodingException e) {\n throw new IllegalStateException(e);\n }\n }\n\n private ByteBuffer allocateBuffer(int size) {\n return ByteBuffer.allocate(size).order(ByteOrder.LITTLE_ENDIAN);\n }\n\n @Override\n public void setMemory(long offset, long length, byte value) {\n byte[] data = new byte[(int) length];\n Arrays.fill(data, value);\n write(offset, data, 0, data.length);\n }\n\n @Override\n public void setByte(long offset, byte value) {\n write(offset, new byte[] { value }, 0, 1);\n }\n\n @Override\n public void setShort(long offset, short value) {\n write(offset, allocateBuffer(2).putShort(value).array(), 0, 2);\n }\n\n @Override\n public void setChar(long offset, char value) {\n write(offset, allocateBuffer(2).putChar(value).array(), 0, 2);\n }\n\n @Override\n public void setInt(long offset, int value) {\n write(offset, allocateBuffer(4).putInt(value).array(), 0, 4);\n }\n\n @Override\n public void setLong(long offset, long value) {\n write(offset, allocateBuffer(8).putLong(value).array(), 0, 8);\n }\n\n @Override\n public void setNativeLong(long offset, NativeLong value) {\n throw new AbstractMethodError();\n }\n\n @Override\n public void setFloat(long offset, float value) {\n write(offset, allocateBuffer(4).putFloat(value).array(), 0, 4);\n }\n\n @Override\n public void setDouble(long offset, double value) {\n write(offset, allocateBuffer(8).putDouble(value).array(), 0, 8);\n }\n\n @Override\n public void setPointer(long offset, Pointer pointer) {\n long value;\n if (pointer == null) {\n value = 0;\n } else {\n value = ((UnidbgPointer) pointer).peer;\n }\n\n if (pointerSize == 4) {\n setInt(offset, (int) value);\n } else {\n setLong(offset, value);\n }\n }\n\n @Override\n public void setWideString(long offset, String value) {\n throw new AbstractMethodError();\n }\n\n @Override\n public void setString(long offset, WString value) {\n throw new AbstractMethodError();\n }\n\n @Override\n public void setString(long offset, String value) {\n setString(offset, value, \"UTF-8\");\n }\n\n @Override\n public void setString(long offset, String value, String encoding) {\n try {\n byte[] data = value.getBytes(encoding);\n write(offset, Arrays.copyOf(data, data.length + 1), 0, data.length + 1);\n } catch (UnsupportedEncodingException e) {\n throw new IllegalArgumentException(e);\n }\n }\n\n @Override\n public UnidbgPointer share(long offset, long sz) {\n if (offset == 0L && sz == size) {\n return this;\n }\n\n UnidbgPointer pointer = new UnidbgPointer(emulator, peer + offset, pointerSize);\n if (size > 0) {\n if (offset > size) {\n throw new InvalidMemoryAccessException(\"offset=\" + offset + \", size=\" + size + \", peer=0x\" + Long.toHexString(peer));\n }\n\n long newSize = size - offset;\n pointer.setSize(sz > 0 && sz < newSize ? sz : newSize);\n } else {\n pointer.setSize(sz);\n }\n return pointer;\n }\n\n @Override\n public String toString() {\n Memory memory = emulator == null ? null : emulator.getMemory();\n Module module = memory == null ? null : memory.findModuleByAddress(peer);\n MemoryMap memoryMap = null;\n if (memory != null) {\n for (MemoryMap mm : memory.getMemoryMap()) {\n if (peer >= mm.base && peer < mm.base + mm.size) {\n memoryMap = mm;\n break;\n }\n }\n }\n StringBuilder sb = new StringBuilder();\n if (memoryMap == null) {\n sb.append(\"unidbg\");\n } else {\n boolean none = true;\n if ((memoryMap.prot & UnicornConst.UC_PROT_READ) != 0) {\n sb.append('R');\n none = false;\n }\n if ((memoryMap.prot & UnicornConst.UC_PROT_WRITE) != 0) {\n sb.append('W');\n none = false;\n }\n if ((memoryMap.prot & UnicornConst.UC_PROT_EXEC) != 0) {\n sb.append('X');\n none = false;\n }\n if (none) {\n sb.append('N');\n }\n }\n sb.append(\"@0x\");\n sb.append(Long.toHexString(peer));\n if (module != null) {\n sb.append(\"[\").append(module.name).append(\"]0x\").append(Long.toHexString(peer - module.base));\n }\n return sb.toString();\n }\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (o == null) {\n return false;\n }\n return (o instanceof UnidbgPointer) && (((UnidbgPointer)o).peer == peer);\n }\n\n @Override\n public int hashCode() {\n return (int)((peer >>> 32) + (peer & 0xffffffffL));\n }\n\n @Override\n public Pointer getPointer() {\n return this;\n }\n}" }, { "identifier": "UnidbgStructure", "path": "unidbg-api/src/main/java/com/github/unidbg/pointer/UnidbgStructure.java", "snippet": "public abstract class UnidbgStructure extends Structure implements PointerArg {\n\n /** Placeholder pointer to help avoid auto-allocation of memory where a\n * Structure needs a valid pointer but want to avoid actually reading from it.\n */\n private static final Pointer PLACEHOLDER_MEMORY = new UnidbgPointer(null, null) {\n @Override\n public UnidbgPointer share(long offset, long sz) { return this; }\n };\n\n public static int calculateSize(Class<? extends UnidbgStructure> type) {\n try {\n Constructor<? extends UnidbgStructure> constructor = type.getConstructor(Pointer.class);\n return constructor.newInstance(PLACEHOLDER_MEMORY).calculateSize(false);\n } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {\n throw new IllegalStateException(e);\n }\n }\n\n private static class ByteArrayPointer extends UnidbgPointer {\n private final Emulator<?> emulator;\n private final byte[] data;\n public ByteArrayPointer(Emulator<?> emulator, byte[] data) {\n super(emulator, data);\n this.emulator = emulator;\n this.data = data;\n }\n @Override\n public UnidbgPointer share(long offset, long sz) {\n if (offset == 0) {\n return this;\n }\n if (offset > 0 && offset + sz < data.length) {\n if (sz == 0) {\n sz = data.length - offset;\n }\n byte[] tmp = new byte[(int) sz];\n System.arraycopy(data, (int) offset, tmp, 0, (int) sz);\n return new ByteArrayPointer(emulator, tmp);\n }\n throw new UnsupportedOperationException(\"offset=0x\" + Long.toHexString(offset) + \", sz=\" + sz);\n }\n }\n\n protected UnidbgStructure(Emulator<?> emulator, byte[] data) {\n this(new ByteArrayPointer(emulator, data));\n }\n\n protected UnidbgStructure(byte[] data) {\n this(null, data);\n }\n\n protected UnidbgStructure(Pointer p) {\n super(p);\n\n checkPointer(p);\n }\n\n private void checkPointer(Pointer p) {\n if (p == null) {\n throw new NullPointerException(\"p is null\");\n }\n if (!(p instanceof UnidbgPointer) && !isPlaceholderMemory(p)) {\n throw new IllegalArgumentException(\"p is NOT UnidbgPointer\");\n }\n }\n\n @Override\n protected int getNativeSize(Class<?> nativeType, Object value) {\n if (Pointer.class.isAssignableFrom(nativeType)) {\n throw new UnsupportedOperationException();\n }\n\n return super.getNativeSize(nativeType, value);\n }\n\n @Override\n protected int getNativeAlignment(Class<?> type, Object value, boolean isFirstElement) {\n if (Pointer.class.isAssignableFrom(type)) {\n throw new UnsupportedOperationException();\n }\n\n return super.getNativeAlignment(type, value, isFirstElement);\n }\n\n private boolean isPlaceholderMemory(Pointer p) {\n return \"native@0x0\".equals(p.toString());\n }\n\n public void pack() {\n super.write();\n }\n\n public void unpack() {\n super.read();\n }\n\n /**\n * @param debug If true, will include a native memory dump of the\n * Structure's backing memory.\n * @return String representation of this object.\n */\n public String toString(boolean debug) {\n return toString(0, true, debug);\n }\n\n private String format(Class<?> type) {\n String s = type.getName();\n int dot = s.lastIndexOf(\".\");\n return s.substring(dot + 1);\n }\n\n private String toString(int indent, boolean showContents, boolean dumpMemory) {\n ensureAllocated();\n String LS = System.getProperty(\"line.separator\");\n String name = format(getClass()) + \"(\" + getPointer() + \")\";\n if (!(getPointer() instanceof Memory)) {\n name += \" (\" + size() + \" bytes)\";\n }\n StringBuilder prefix = new StringBuilder();\n for (int idx=0;idx < indent;idx++) {\n prefix.append(\" \");\n }\n StringBuilder contents = new StringBuilder(LS);\n if (!showContents) {\n contents = new StringBuilder(\"...}\");\n }\n else for (Iterator<StructField> i = fields().values().iterator(); i.hasNext();) {\n StructField sf = i.next();\n Object value = getFieldValue(sf.field);\n String type = format(sf.type);\n String index = \"\";\n contents.append(prefix);\n if (sf.type.isArray() && value != null) {\n type = format(sf.type.getComponentType());\n index = \"[\" + Array.getLength(value) + \"]\";\n }\n contents.append(String.format(\" %s %s%s@0x%X\", type, sf.name, index, sf.offset));\n if (value instanceof UnidbgStructure) {\n value = ((UnidbgStructure)value).toString(indent + 1, !(value instanceof Structure.ByReference), dumpMemory);\n }\n contents.append(\"=\");\n if (value instanceof Long) {\n contents.append(String.format(\"0x%08X\", value));\n }\n else if (value instanceof Integer) {\n contents.append(String.format(\"0x%04X\", value));\n }\n else if (value instanceof Short) {\n contents.append(String.format(\"0x%02X\", value));\n }\n else if (value instanceof Byte) {\n contents.append(String.format(\"0x%01X\", value));\n }\n else if (value instanceof byte[]) {\n contents.append(Hex.encodeHexString((byte[]) value));\n }\n else {\n contents.append(String.valueOf(value).trim());\n }\n contents.append(LS);\n if (!i.hasNext())\n contents.append(prefix).append(\"}\");\n }\n if (indent == 0 && dumpMemory) {\n final int BYTES_PER_ROW = 4;\n contents.append(LS).append(\"memory dump\").append(LS);\n byte[] buf = getPointer().getByteArray(0, size());\n for (int i=0;i < buf.length;i++) {\n if ((i % BYTES_PER_ROW) == 0) contents.append(\"[\");\n if (buf[i] >=0 && buf[i] < 16)\n contents.append(\"0\");\n contents.append(Integer.toHexString(buf[i] & 0xff));\n if ((i % BYTES_PER_ROW) == BYTES_PER_ROW-1 && i < buf.length-1)\n contents.append(\"]\").append(LS);\n }\n contents.append(\"]\");\n }\n return name + \" {\" + contents;\n }\n\n /** Obtain the value currently in the Java field. Does not read from\n * native memory.\n * @param field field to look up\n * @return current field value (Java-side only)\n */\n private Object getFieldValue(Field field) {\n try {\n return field.get(this);\n }\n catch (Exception e) {\n throw new Error(\"Exception reading field '\" + field.getName() + \"' in \" + getClass(), e);\n }\n }\n\n private static final Field FIELD_STRUCT_FIELDS;\n\n static {\n try {\n FIELD_STRUCT_FIELDS = Structure.class.getDeclaredField(\"structFields\");\n FIELD_STRUCT_FIELDS.setAccessible(true);\n } catch (NoSuchFieldException e) {\n throw new IllegalStateException(e);\n }\n }\n\n /** Return all fields in this structure (ordered). This represents the\n * layout of the structure, and will be shared among Structures of the\n * same class except when the Structure can have a variable size.\n * NOTE: {@link #ensureAllocated()} <em>must</em> be called prior to\n * calling this method.\n * @return {@link Map} of field names to field representations.\n */\n @SuppressWarnings(\"unchecked\")\n private Map<String, StructField> fields() {\n try {\n return (Map<String, StructField>) FIELD_STRUCT_FIELDS.get(this);\n } catch (IllegalAccessException e) {\n throw new IllegalStateException(e);\n }\n }\n}" }, { "identifier": "PopContextException", "path": "unidbg-api/src/main/java/com/github/unidbg/thread/PopContextException.java", "snippet": "public class PopContextException extends LongJumpException {\n}" }, { "identifier": "RunnableTask", "path": "unidbg-api/src/main/java/com/github/unidbg/thread/RunnableTask.java", "snippet": "public interface RunnableTask {\n\n boolean canDispatch();\n\n void saveContext(Emulator<?> emulator);\n\n boolean isContextSaved();\n\n void restoreContext(Emulator<?> emulator);\n\n void destroy(Emulator<?> emulator);\n\n void setWaiter(Emulator<?> emulator, Waiter waiter);\n\n Waiter getWaiter();\n\n void setResult(Emulator<?> emulator, Number ret);\n\n void setDestroyListener(DestroyListener listener);\n\n void popContext(Emulator<?> emulator);\n\n void pushFunction(Emulator<?> emulator, FunctionCall call);\n FunctionCall popFunction(Emulator<?> emulator, long address);\n\n}" }, { "identifier": "ThreadContextSwitchException", "path": "unidbg-api/src/main/java/com/github/unidbg/thread/ThreadContextSwitchException.java", "snippet": "public class ThreadContextSwitchException extends LongJumpException {\n\n private boolean setReturnValue;\n private long returnValue;\n\n public ThreadContextSwitchException setReturnValue(long returnValue) {\n this.setReturnValue = true;\n this.returnValue = returnValue;\n return this;\n }\n\n private boolean setErrno;\n private int errno;\n\n public ThreadContextSwitchException setErrno(int errno) {\n this.setErrno = true;\n this.errno = errno;\n return this;\n }\n\n public void syncReturnValue(Emulator<?> emulator) {\n if (setReturnValue) {\n Backend backend = emulator.getBackend();\n backend.reg_write(emulator.is32Bit() ? ArmConst.UC_ARM_REG_R0 : Arm64Const.UC_ARM64_REG_X0, returnValue);\n }\n if (setErrno) {\n emulator.getMemory().setErrno(errno);\n }\n }\n\n}" }, { "identifier": "UnixEmulator", "path": "unidbg-api/src/main/java/com/github/unidbg/unix/UnixEmulator.java", "snippet": "public interface UnixEmulator {\n\n int EPERM = 1; /* Operation not permitted */\n int ENOENT = 2; /* No such file or directory */\n int ESRCH = 3; /* No such process */\n int EINTR = 4; /* Interrupted system call */\n int EBADF = 9; /* Bad file descriptor */\n int EAGAIN = 11; /* Resource temporarily unavailable */\n int ENOMEM = 12; /* Cannot allocate memory */\n int EACCES = 13; /* Permission denied */\n int EFAULT = 14; /* Bad address */\n int EEXIST = 17; /* File exists */\n int ENOTDIR = 20; /* Not a directory */\n int EINVAL = 22; /* Invalid argument */\n int ENOTTY = 25; /* Inappropriate ioctl for device */\n int ENOSYS = 38; /* Function not implemented */\n int ENOATTR = 93; /* Attribute not found */\n int EOPNOTSUPP = 95; /* Operation not supported on transport endpoint */\n int EAFNOSUPPORT = 97; /* Address family not supported by protocol family */\n int EADDRINUSE = 98; /* Address already in use */\n int ECONNREFUSED = 111; /* Connection refused */\n\n}" }, { "identifier": "TimeSpec", "path": "unidbg-api/src/main/java/com/github/unidbg/unix/struct/TimeSpec.java", "snippet": "public abstract class TimeSpec extends UnidbgStructure {\n\n public static TimeSpec createTimeSpec(Emulator<?> emulator, Pointer ptr) {\n if (ptr == null) {\n return null;\n }\n TimeSpec timeSpec = emulator.is32Bit() ? new TimeSpec32(ptr) : new TimeSpec64(ptr);\n timeSpec.unpack();\n return timeSpec;\n }\n\n public TimeSpec(Pointer p) {\n super(p);\n }\n\n public abstract long getTvSec();\n public abstract long getTvNsec();\n\n public long toMillis() {\n return getTvSec() * 1000L + getTvNsec() / 1000000L;\n }\n\n public void setMillis(long millis) {\n if (millis < 0) {\n millis = 0;\n }\n long tvSec = millis / 1000L;\n long tvNsec = millis % 1000L * 1000000L;\n\n setTv(tvSec, tvNsec);\n }\n\n protected abstract void setTv(long tvSec, long tvNsec);\n\n}" }, { "identifier": "TimeVal64", "path": "unidbg-api/src/main/java/com/github/unidbg/unix/struct/TimeVal64.java", "snippet": "public class TimeVal64 extends UnidbgStructure {\n\n public TimeVal64(Pointer p) {\n super(p);\n }\n\n public long tv_sec;\n public long tv_usec;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"tv_sec\", \"tv_usec\");\n }\n\n}" }, { "identifier": "Inspector", "path": "unidbg-api/src/main/java/com/github/unidbg/utils/Inspector.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class Inspector {\n\n\tpublic static void inspectMapData(String label, byte[] data, int mode) {\n\t\tif (data == null)\n\t\t\treturn;\n\n\t\tStringBuilder buffer = new StringBuilder();\n\t\tbuffer.append(\"\\n>-----------------------------------------------------------------------------<\\n\");\n\n\t\tbuffer.append(new SimpleDateFormat(\"[HH:mm:ss SSS]\").format(new Date()));\n\t\t\n\t\tbuffer.append(label);\n\t\t\n\t\tbuffer.append(\"\\nsize: \").append(data.length).append('\\n');\n\t\t\n\t\tint i = 0;\n\t\tfor(; i < data.length; i++) {\n\t\t\tint di = data[i] & 0xFF;\n\t\t\tif(di != 0) {\n\t\t\t\tString hex = Integer.toString(di, 16).toUpperCase();\n\t\t\t\tif(hex.length() < 2) {\n\t\t\t\t\tbuffer.append('0');\n\t\t\t\t}\n\t\t\t\tbuffer.append(hex);\n\t\t\t} else {\n\t\t\t\tbuffer.append(\" \");\n\t\t\t}\n\t\t\t\n\t\t\tbuffer.append(' ');\n\t\t\t\n\t\t\tif((i + 1) % mode == 0) {\n\t\t\t\t/*buffer.append(\" \");\n\t\t\t\tfor(int k = i - 15; k < i+1; k++) {\n\t\t\t\t\tbuffer.append(toChar(data[k]));\n\t\t\t\t}*/\n\t\t\t\tbuffer.append('\\n');\n\t\t\t}\n\t\t}\n\t\t\n\t\tint redex = mode - i % mode;\n\t\tfor(byte k = 0; k < redex && redex < mode; k++) {\n\t\t\tbuffer.append(\" \");\n\t\t\tbuffer.append(' ');\n\t\t}\n\t\tint count = i % mode;\n\t\tint start = i - count;\n\t\tif(start < i) {\n\t\t\tbuffer.append(\" \");\n\t\t}\n\t\tfor(int k = start; k < i; k++) {\n\t\t\tbuffer.append(toChar(data[k]));\n\t\t}\n\t\t\n\t\tif(redex < mode) {\n\t\t\tbuffer.append('\\n');\n\t\t}\n\t\tbuffer.append(\"^-----------------------------------------------------------------------------^\");\n\t\t\n\t\tSystem.out.println(buffer);\n\t}\n\t\n\tpublic static void available(InputStream dis) throws IOException {\n\t\tif(dis == null) {\n\t\t\tSystem.out.println(\"available=null\");\n\t\t\treturn;\n\t\t}\n\n\t\tint size = dis.available();\n\t\tbyte[] data = new byte[size];\n\t\tif (dis.read(data) != size) {\n\t\t\tthrow new IOException(\"Read available failed.\");\n\t\t}\n\t\tInspector.inspect(data, \"Available\");\n\t}\n\t\n\t/**\n\t * 过滤器\n\t * @return 是否接受该数据\n\t */\n\tpublic boolean accept(byte[] data, String label) {\n\t\treturn true;\n\t}\n\tpublic boolean acceptObject(Object obj) {\n\t\treturn true;\n\t}\n\t\n\tpublic static final int WPE = 16;\n\tpublic static final int MNM = 20;\n\t\n\tpublic static void inspectMapData(String label, short[][] data) {\n\t\tinspectMapData(label, data, -1);\n\t}\n\t\n\tpublic static void inspectMapData(String label, short[][] data, int filter) {\n\t\tStringBuffer buffer = new StringBuffer();\n\t\tbuffer.append(\"\\n>-----------------------------------------------------------------------------<\\n\");\n\n\t\tbuffer.append(new SimpleDateFormat(\"[HH:mm:ss SSS]\").format(new Date()));\n\t\t\n\t\tbuffer.append(data.length);\n\t\tif(data.length > 0) {\n\t\t\tbuffer.append('x').append(data[0].length);\n\t\t}\n\t\tbuffer.append(label).append('\\n');\n\n\t\tfor (short[] dt : data) {\n\t\t\tfor (short ds : dt) {\n\t\t\t\tint di = ds & 0xFFFF;\n\n\t\t\t\tif (di == filter) {\n\t\t\t\t\tbuffer.append(\" \");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tString hex = Integer.toString(di, 16).toUpperCase();\n\t\t\t\tfor (int n = 0; n < 4 - hex.length(); n++) {\n\t\t\t\t\tbuffer.append('0');\n\t\t\t\t}\n\t\t\t\tbuffer.append(hex);\n\t\t\t\tbuffer.append(' ');\n\t\t\t}\n\t\t\tbuffer.append('\\n');\n\t\t}\n\t\t\n\t\tbuffer.append(\"^-----------------------------------------------------------------------------^\");\n\t\tSystem.out.println(buffer);\n\t}\n\t\n\tpublic static void inspect(String label, byte[][] data) {\n\t\tinspect(label, data, -1);\n\t}\n\t\n\tpublic static void inspect(String label, short[] data) {\n\t\tSystem.out.println(inspectString(null, label, data, WPE));\n\t}\n\t\n\tpublic static String inspectString(Date date, String label, short[] data, int mode) {\n\t\tStringBuilder buffer = new StringBuilder();\n\t\tbuffer.append(\"\\n>-----------------------------------------------------------------------------<\\n\");\n\n\t\tif (date == null) {\n\t\t\tdate = new Date();\n\t\t}\n\t\tbuffer.append(new SimpleDateFormat(\"[HH:mm:ss SSS]\").format(date));\n\t\t\n\t\tbuffer.append(label);\n\t\t\n\t\tbuffer.append(\"\\nsize: \");\n\t\tif(data != null) {\n\t\t\tbuffer.append(data.length);\n\t\t} else {\n\t\t\tbuffer.append(\"null\");\n\t\t}\n\t\tbuffer.append('\\n');\n\t\t\n\t\tif(data != null) {\n\t\t\tint i = 0;\n\t\t\tfor(; i < data.length; i++) {\n\t\t\t\tint di = data[i] & 0xFFFF;\n\t\t\t\t\n\t\t\t\tString hex = Integer.toString(di, 16).toUpperCase();\n\t\t\t\tfor(int n = 0; n < 4 - hex.length(); n++) {\n\t\t\t\t\tbuffer.append('0');\n\t\t\t\t}\n\t\t\t\tbuffer.append(hex);\n\t\t\t\tbuffer.append(' ');\n\t\t\t\t\n\t\t\t\tif((i + 1) % mode == 0) {\n\t\t\t\t\tbuffer.append('\\n');\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(i % mode != 0) {\n\t\t\t\tbuffer.append('\\n');\n\t\t\t}\n\t\t}\n\t\t\n\t\tbuffer.append(\"^-----------------------------------------------------------------------------^\");\n\t\t\n\t\treturn buffer.toString();\n\t}\n\t\n\tpublic static void inspect(String label, byte[][] data, int filter) {\n\t\tSystem.out.println(inspectString(label, data, filter));\n\t}\n\t\n\tpublic static void inspect(Date date, String label, byte[] data, int mode) {\n\t\tSystem.out.println(inspectInternal(date, label, data, mode));\n\t}\n\n\tprivate static String inspectInternal(Date date, String label, byte[] data, int mode) {\n\t\tStringBuilder buffer = new StringBuilder();\n\t\tbuffer.append(\"\\n>-----------------------------------------------------------------------------<\\n\");\n\n\t\tif (date == null) {\n\t\t\tdate = new Date();\n\t\t}\n\t\tbuffer.append(new SimpleDateFormat(\"[HH:mm:ss SSS]\").format(date));\n\n\t\tbuffer.append(label);\n\t\tif(data != null) {\n\t\t\tbuffer.append(\", md5=\").append(Hex.encodeHex(DigestUtils.md5(data)));\n\t\t\tif (data.length < 1024) {\n\t\t\t\tbuffer.append(\", hex=\").append(Hex.encodeHex(data));\n\t\t\t}\n\t\t}\n\t\t\n\t\tbuffer.append(\"\\nsize: \");\n\t\tif(data != null) {\n\t\t\tbuffer.append(data.length);\n\t\t} else {\n\t\t\tbuffer.append(\"null\");\n\t\t}\n\t\tbuffer.append('\\n');\n\t\t\n\t\tif(data != null) {\n\t\t\tint i = 0;\n\t\t\tfor(; i < data.length; i++) {\n\t\t\t\tif(i % mode == 0) {\n\t\t\t\t\tString hex = Integer.toHexString(i % 0x10000).toUpperCase();\n\t\t\t\t\tfor(int k = 0, fill = 4 - hex.length(); k < fill; k++) {\n\t\t\t\t\t\tbuffer.append('0');\n\t\t\t\t\t}\n\t\t\t\t\tbuffer.append(hex).append(\": \");\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tint di = data[i] & 0xFF;\n\t\t\t\tString hex = Integer.toString(di, 16).toUpperCase();\n\t\t\t\tif(hex.length() < 2) {\n\t\t\t\t\tbuffer.append('0');\n\t\t\t\t}\n\t\t\t\tbuffer.append(hex);\n\t\t\t\tbuffer.append(' ');\n\t\t\t\t\n\t\t\t\tif((i + 1) % mode == 0) {\n\t\t\t\t\tbuffer.append(\" \");\n\t\t\t\t\tfor(int k = i - 15; k < i+1; k++) {\n\t\t\t\t\t\tbuffer.append(toChar(data[k]));\n\t\t\t\t\t}\n\t\t\t\t\tbuffer.append('\\n');\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tint redex = mode - i % mode;\n\t\t\tfor(byte k = 0; k < redex && redex < mode; k++) {\n\t\t\t\tbuffer.append(\" \");\n\t\t\t\tbuffer.append(' ');\n\t\t\t}\n\t\t\tint count = i % mode;\n\t\t\tint start = i - count;\n\t\t\tif(start < i) {\n\t\t\t\tbuffer.append(\" \");\n\t\t\t}\n\t\t\tfor(int k = start; k < i; k++) {\n\t\t\t\tbuffer.append(toChar(data[k]));\n\t\t\t}\n\t\t\t\n\t\t\tif(redex < mode) {\n\t\t\t\tbuffer.append('\\n');\n\t\t\t}\n\t\t}\n\t\t\n\t\tbuffer.append(\"^-----------------------------------------------------------------------------^\");\n\t\t\n\t\treturn buffer.toString();\n\t}\n\t\n\tpublic static void inspect(String label, byte[] data, int mode) {\n\t\tinspect(null, label, data, mode);\n\t}\n\n\t/**\n\t * 侦察发送的数据\n\t */\n\tpublic static void inspect(byte[] data, boolean send) {\n\t\tinspect(send ? \"发送数据\" : \"接收数据\", data, WPE);\n\t}\n\n\t/**\n\t * 侦察发送的数据\n\t */\n\tpublic static void inspect(int type, byte[] data, boolean send) {\n\t\tString ts = Integer.toHexString(type).toUpperCase();\n\t\tinspect(send ? \"发送数据:0x\" + ts : \"接收数据:0x\" + ts, data, WPE);\n\t}\n\n\t/**\n\t * 侦察发送的数据\n\t */\n\tpublic static void inspect(byte[] data, String label) {\n\t\tinspect(label, data, WPE);\n\t}\n\t\n\tprivate static char toChar(byte in) {\n\t\tif(in == ' ')\n\t\t\treturn ' ';\n\t\t\n\t\tif(in > 0x7E || in < 0x21)\n\t\t\treturn '.';\n\t\telse\n\t\t\treturn (char) in;\n\t}\n\t\n\t/**\n\t * 测试对象类型\n\t */\n\tpublic static void objectType(Object in) {\n\t\tif(in == null) {\n\t\t\tSystem.out.println(\"Object type is null\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tSystem.out.println(\"Object type is \" + in.getClass() + '[' + in + ']');\n\t}\n\t\n\t/**\n\t * 侦测数据类型\n\t * @return 返回null则表示没侦测到\n\t */\n\tprotected Integer detectedType(byte[] data, boolean send) {\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * 查询int值\n\t */\n\tpublic static void inspect(String label, int value) {\n\t\tSystem.out.println(label + \"0x\" + Integer.toHexString(value).toUpperCase());\n\t}\n\t\n\t/**\n\t * 引发错误异常\n\t */\n\tpublic static void throwError() {\n\t\tthrow new Error(\"auxiliary error\");\n\t}\n\t\n\t/**\n\t * 根据值引发错误异常\n\t */\n\tpublic static void throwError(int errorValue, int testValue) {\n\t\tif(testValue != errorValue) {\n\t\t\treturn;\n\t\t}\n\t\tthrow new Error(\"auxiliary error\");\n\t}\n\t\n\tpublic static void where() {\n\t\tThread.dumpStack();\n\t}\n\t\n\tpublic static void where(int testValue, int printValue) {\n\t\tif(testValue != printValue) {\n\t\t\treturn;\n\t\t}\n\n\t\twhere();\n\t}\n\t\n\tprotected static void close(InputStream is) {\n\t\tif(is == null) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\ttry {\n\t\t\tis.close();\n\t\t} catch(Exception ignored) {}\n\t}\n\tprotected static void close(OutputStream os) {\n\t\tif(os == null) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\ttry {\n\t\t\tos.close();\n\t\t} catch(Exception ignored) {}\n\t}\n\t\n\tpublic static String inspectString(String label, byte[][] data) {\n\t\treturn inspectString(label, data, -1);\n\t}\n\t\n\tpublic static String inspectString(String label, short[] data) {\n\t\treturn inspectString(new Date(), label, data);\n\t}\n\t\n\tpublic static String inspectString(Date date, String label, short[] data) {\n\t\treturn inspectString(date, label, data, WPE);\n\t}\n\t\n\tpublic static String inspectString(String label, byte[][] data, int filter) {\n\t\tStringBuilder buffer = new StringBuilder();\n\t\tbuffer.append(\"\\n>-----------------------------------------------------------------------------<\\n\");\n\n\t\tbuffer.append(new SimpleDateFormat(\"[HH:mm:ss SSS]\").format(new Date()));\n\t\t\n\t\tif(data.length > 0) {\n\t\t\tbuffer.append(data[0].length).append('x');\n\t\t}\n\t\tbuffer.append(data.length);\n\t\tbuffer.append(label).append('\\n');\n\n\t\tfor (byte[] dt : data) {\n\t\t\tfor (byte db : dt) {\n\t\t\t\tint di = db & 0xFF;\n\n\t\t\t\tif (di == filter) {\n\t\t\t\t\tbuffer.append(\" \");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tString hex = Integer.toString(di, 16).toUpperCase();\n\t\t\t\tif (hex.length() < 2) {\n\t\t\t\t\tbuffer.append('0');\n\t\t\t\t}\n\t\t\t\tbuffer.append(hex);\n\t\t\t\tbuffer.append(' ');\n\t\t\t}\n\t\t\tbuffer.append('\\n');\n\t\t}\n\t\t\n\t\tbuffer.append(\"^-----------------------------------------------------------------------------^\");\n\t\treturn buffer.toString();\n\t}\n\t\n\tpublic static String inspectString(String label, byte[] data, int mode) {\n\t\treturn inspectString(null, label, data, mode);\n\t}\n\t\n\tpublic static String inspectString(Date date, String label, byte[] data, int mode) {\n\t\treturn inspectInternal(date, label, data, mode);\n\t}\n\n\t/**\n\t * 侦察发送的数据\n\t */\n\tpublic static String inspectString(byte[] data, boolean send) {\n\t\treturn inspectString(send ? \"Sent\" : \"Received\", data, WPE);\n\t}\n\n\t/**\n\t * 侦察发送的数据\n\t */\n\tpublic static String inspectString(int type, byte[] data, boolean send) {\n\t\tString ts = Integer.toHexString(type).toUpperCase();\n\t\treturn inspectString(send ? \"发送数据: 0x\" + ts : \"接收数据: 0x\" + ts, data, WPE);\n\t}\n\n\t/**\n\t * 侦察发送的数据\n\t */\n\tpublic static String inspectString(byte[] data, String label) {\n\t\treturn inspectString(label, data, WPE);\n\t}\n\n}" }, { "identifier": "AF_LINK", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/file/SocketIO.java", "snippet": "public static final short AF_LINK =\t\t18;\t\t/* Link layer interface */" }, { "identifier": "AF_ROUTE", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/file/SocketIO.java", "snippet": "public static final short AF_ROUTE = 17;\t\t/* Internal Routing Protocol */" } ]
import com.github.unidbg.AbstractEmulator; import com.github.unidbg.Emulator; import com.github.unidbg.LongJumpException; import com.github.unidbg.StopEmulatorException; import com.github.unidbg.Svc; import com.github.unidbg.arm.ARM; import com.github.unidbg.arm.ARMEmulator; import com.github.unidbg.arm.Arm64Svc; import com.github.unidbg.arm.Cpsr; import com.github.unidbg.arm.backend.Backend; import com.github.unidbg.arm.backend.BackendException; import com.github.unidbg.arm.context.Arm64RegisterContext; import com.github.unidbg.arm.context.EditableArm64RegisterContext; import com.github.unidbg.arm.context.RegisterContext; import com.github.unidbg.file.FileIO; import com.github.unidbg.file.FileResult; import com.github.unidbg.file.ios.DarwinFileIO; import com.github.unidbg.file.ios.IOConstants; import com.github.unidbg.ios.file.ByteArrayFileIO; import com.github.unidbg.ios.file.DriverFileIO; import com.github.unidbg.ios.file.LocalDarwinUdpSocket; import com.github.unidbg.ios.file.SocketIO; import com.github.unidbg.ios.file.TcpSocket; import com.github.unidbg.ios.file.UdpSocket; import com.github.unidbg.ios.struct.attr.AttrList; import com.github.unidbg.ios.struct.kernel.AslServerMessageRequest; import com.github.unidbg.ios.struct.kernel.ClockGetTimeReply; import com.github.unidbg.ios.struct.kernel.DyldCacheHeader; import com.github.unidbg.ios.struct.kernel.HostGetClockServiceReply; import com.github.unidbg.ios.struct.kernel.HostGetClockServiceRequest; import com.github.unidbg.ios.struct.kernel.HostInfoReply; import com.github.unidbg.ios.struct.kernel.HostInfoRequest; import com.github.unidbg.ios.struct.kernel.IOServiceAddNotificationRequest; import com.github.unidbg.ios.struct.kernel.IOServiceGetMatchingServiceRequest; import com.github.unidbg.ios.struct.kernel.MachMsgHeader; import com.github.unidbg.ios.struct.kernel.MachPortOptions; import com.github.unidbg.ios.struct.kernel.MachPortReply; import com.github.unidbg.ios.struct.kernel.MachPortSetAttributesReply; import com.github.unidbg.ios.struct.kernel.MachPortSetAttributesRequest; import com.github.unidbg.ios.struct.kernel.MachPortTypeReply; import com.github.unidbg.ios.struct.kernel.MachPortTypeRequest; import com.github.unidbg.ios.struct.kernel.MachPortsLookupReply64; import com.github.unidbg.ios.struct.kernel.MachTimebaseInfo; import com.github.unidbg.ios.struct.kernel.NotifyServerCancelReply; import com.github.unidbg.ios.struct.kernel.NotifyServerCancelRequest; import com.github.unidbg.ios.struct.kernel.NotifyServerGetStateReply; import com.github.unidbg.ios.struct.kernel.NotifyServerGetStateRequest; import com.github.unidbg.ios.struct.kernel.NotifyServerRegisterCheck64Request; import com.github.unidbg.ios.struct.kernel.NotifyServerRegisterCheckReply; import com.github.unidbg.ios.struct.kernel.NotifyServerRegisterMachPort64Request; import com.github.unidbg.ios.struct.kernel.NotifyServerRegisterMachPortReply; import com.github.unidbg.ios.struct.kernel.NotifyServerRegisterPlain64Request; import com.github.unidbg.ios.struct.kernel.NotifyServerRegisterPlainReply; import com.github.unidbg.ios.struct.kernel.ProcBsdShortInfo; import com.github.unidbg.ios.struct.kernel.Pthread; import com.github.unidbg.ios.struct.kernel.Pthread64; import com.github.unidbg.ios.struct.kernel.RLimit; import com.github.unidbg.ios.struct.kernel.RUsage64; import com.github.unidbg.ios.struct.kernel.SemaphoreCreateReply; import com.github.unidbg.ios.struct.kernel.SemaphoreCreateRequest; import com.github.unidbg.ios.struct.kernel.Stat64; import com.github.unidbg.ios.struct.kernel.StatFS; import com.github.unidbg.ios.struct.kernel.TaskBasicInfoReply64V2; import com.github.unidbg.ios.struct.kernel.TaskDyldInfoReply; import com.github.unidbg.ios.struct.kernel.TaskGetExceptionPortsReply; import com.github.unidbg.ios.struct.kernel.TaskGetExceptionPortsRequest; import com.github.unidbg.ios.struct.kernel.TaskGetSpecialPortReply; import com.github.unidbg.ios.struct.kernel.TaskGetSpecialPortRequest; import com.github.unidbg.ios.struct.kernel.TaskInfoRequest; import com.github.unidbg.ios.struct.kernel.TaskSetExceptionPortsReply; import com.github.unidbg.ios.struct.kernel.TaskSetExceptionPortsRequest; import com.github.unidbg.ios.struct.kernel.TaskThreadsReply64; import com.github.unidbg.ios.struct.kernel.TaskVmInfoReply64; import com.github.unidbg.ios.struct.kernel.ThreadBasicInfoReply; import com.github.unidbg.ios.struct.kernel.ThreadInfoRequest; import com.github.unidbg.ios.struct.kernel.ThreadStateReply64; import com.github.unidbg.ios.struct.kernel.ThreadStateRequest; import com.github.unidbg.ios.struct.kernel.VmCopy64Request; import com.github.unidbg.ios.struct.kernel.VmCopyReply; import com.github.unidbg.ios.struct.kernel.VmReadOverwriteReply; import com.github.unidbg.ios.struct.kernel.VmReadOverwriteRequest; import com.github.unidbg.ios.struct.kernel.VmRegion64Reply; import com.github.unidbg.ios.struct.kernel.VmRegion64Request; import com.github.unidbg.ios.struct.kernel.VmRegionRecurse64Reply; import com.github.unidbg.ios.struct.kernel.VmRegionRecurse64Request; import com.github.unidbg.ios.struct.kernel.VmRemapReply; import com.github.unidbg.ios.struct.kernel.VmRemapRequest; import com.github.unidbg.ios.struct.sysctl.IfMsgHeader; import com.github.unidbg.ios.struct.sysctl.KInfoProc64; import com.github.unidbg.ios.struct.sysctl.SockAddrDL; import com.github.unidbg.ios.struct.sysctl.TaskDyldInfo; import com.github.unidbg.ios.struct.sysctl.TaskVmInfo64; import com.github.unidbg.memory.MemoryMap; import com.github.unidbg.memory.SvcMemory; import com.github.unidbg.pointer.UnidbgPointer; import com.github.unidbg.pointer.UnidbgStructure; import com.github.unidbg.thread.PopContextException; import com.github.unidbg.thread.RunnableTask; import com.github.unidbg.thread.ThreadContextSwitchException; import com.github.unidbg.unix.UnixEmulator; import com.github.unidbg.unix.struct.TimeSpec; import com.github.unidbg.unix.struct.TimeVal64; import com.github.unidbg.utils.Inspector; import com.sun.jna.Pointer; import org.apache.commons.io.FilenameUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import unicorn.Arm64Const; import unicorn.UnicornConst; import java.net.SocketException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import static com.github.unidbg.file.ios.DarwinFileIO.XATTR_CREATE; import static com.github.unidbg.file.ios.DarwinFileIO.XATTR_REPLACE; import static com.github.unidbg.ios.MachO.MAP_MY_FIXED; import static com.github.unidbg.ios.file.SocketIO.AF_LINK; import static com.github.unidbg.ios.file.SocketIO.AF_ROUTE;
57,649
package com.github.unidbg.ios; public class ARM64SyscallHandler extends DarwinSyscallHandler { private static final Log log = LogFactory.getLog(ARM64SyscallHandler.class); private final SvcMemory svcMemory; protected ARM64SyscallHandler(SvcMemory svcMemory) { super(); this.svcMemory = svcMemory; } @SuppressWarnings("unchecked") @Override public void hook(Backend backend, int intno, int swi, Object user) { Emulator<DarwinFileIO> emulator = (Emulator<DarwinFileIO>) user; UnidbgPointer pc = UnidbgPointer.register(emulator, Arm64Const.UC_ARM64_REG_PC); if (intno == ARMEmulator.EXCP_BKPT) { // brk createBreaker(emulator).brk(pc, pc == null ? swi : (pc.getInt(0) >> 5) & 0xffff); return; } if (intno == ARMEmulator.EXCP_UDEF) { createBreaker(emulator).debug(); return; } if (intno != ARMEmulator.EXCP_SWI) { throw new BackendException("intno=" + intno); } int NR = backend.reg_read(Arm64Const.UC_ARM64_REG_X16).intValue(); String syscall = null; Throwable exception = null; try { if (swi == 0 && NR == Svc.POST_CALLBACK_SYSCALL_NUMBER && backend.reg_read(Arm64Const.UC_ARM64_REG_X8).intValue() == 0) { // postCallback int number = backend.reg_read(Arm64Const.UC_ARM64_REG_X12).intValue(); Svc svc = svcMemory.getSvc(number); if (svc != null) { svc.handlePostCallback(emulator); return; } backend.emu_stop(); throw new IllegalStateException("svc number: " + swi); } if (swi == 0 && NR == Svc.PRE_CALLBACK_SYSCALL_NUMBER && backend.reg_read(Arm64Const.UC_ARM64_REG_X8).intValue() == 0) { // preCallback int number = backend.reg_read(Arm64Const.UC_ARM64_REG_X12).intValue(); Svc svc = svcMemory.getSvc(number); if (svc != null) { svc.handlePreCallback(emulator); return; } backend.emu_stop(); throw new IllegalStateException("svc number: " + swi); } if (swi != DARWIN_SWI_SYSCALL) { if (swi == Arm64Svc.SVC_MAX) { throw new PopContextException(); } if (swi == Arm64Svc.SVC_MAX - 1) { throw new ThreadContextSwitchException(); } Svc svc = svcMemory.getSvc(swi); if (svc != null) { backend.reg_write(Arm64Const.UC_ARM64_REG_X0, svc.handle(emulator)); return; } backend.emu_stop(); throw new BackendException("svc number: " + swi + ", NR=" + NR + ", intno=" + intno); } if (log.isTraceEnabled()) { log.debug("handle syscall NR=" + NR); ARM.showRegs64(emulator, null); }
package com.github.unidbg.ios; public class ARM64SyscallHandler extends DarwinSyscallHandler { private static final Log log = LogFactory.getLog(ARM64SyscallHandler.class); private final SvcMemory svcMemory; protected ARM64SyscallHandler(SvcMemory svcMemory) { super(); this.svcMemory = svcMemory; } @SuppressWarnings("unchecked") @Override public void hook(Backend backend, int intno, int swi, Object user) { Emulator<DarwinFileIO> emulator = (Emulator<DarwinFileIO>) user; UnidbgPointer pc = UnidbgPointer.register(emulator, Arm64Const.UC_ARM64_REG_PC); if (intno == ARMEmulator.EXCP_BKPT) { // brk createBreaker(emulator).brk(pc, pc == null ? swi : (pc.getInt(0) >> 5) & 0xffff); return; } if (intno == ARMEmulator.EXCP_UDEF) { createBreaker(emulator).debug(); return; } if (intno != ARMEmulator.EXCP_SWI) { throw new BackendException("intno=" + intno); } int NR = backend.reg_read(Arm64Const.UC_ARM64_REG_X16).intValue(); String syscall = null; Throwable exception = null; try { if (swi == 0 && NR == Svc.POST_CALLBACK_SYSCALL_NUMBER && backend.reg_read(Arm64Const.UC_ARM64_REG_X8).intValue() == 0) { // postCallback int number = backend.reg_read(Arm64Const.UC_ARM64_REG_X12).intValue(); Svc svc = svcMemory.getSvc(number); if (svc != null) { svc.handlePostCallback(emulator); return; } backend.emu_stop(); throw new IllegalStateException("svc number: " + swi); } if (swi == 0 && NR == Svc.PRE_CALLBACK_SYSCALL_NUMBER && backend.reg_read(Arm64Const.UC_ARM64_REG_X8).intValue() == 0) { // preCallback int number = backend.reg_read(Arm64Const.UC_ARM64_REG_X12).intValue(); Svc svc = svcMemory.getSvc(number); if (svc != null) { svc.handlePreCallback(emulator); return; } backend.emu_stop(); throw new IllegalStateException("svc number: " + swi); } if (swi != DARWIN_SWI_SYSCALL) { if (swi == Arm64Svc.SVC_MAX) { throw new PopContextException(); } if (swi == Arm64Svc.SVC_MAX - 1) { throw new ThreadContextSwitchException(); } Svc svc = svcMemory.getSvc(swi); if (svc != null) { backend.reg_write(Arm64Const.UC_ARM64_REG_X0, svc.handle(emulator)); return; } backend.emu_stop(); throw new BackendException("svc number: " + swi + ", NR=" + NR + ", intno=" + intno); } if (log.isTraceEnabled()) { log.debug("handle syscall NR=" + NR); ARM.showRegs64(emulator, null); }
Cpsr.getArm64(backend).setCarry(false);
8
2023-10-17 06:13:28+00:00
128k
DrMango14/Create-Design-n-Decor
src/main/java/com/mangomilk/design_decor/registry/MmbBlocks.java
[ { "identifier": "DecorBuilderTransformer", "path": "src/main/java/com/mangomilk/design_decor/base/DecorBuilderTransformer.java", "snippet": "public class DecorBuilderTransformer {\n\n public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> connected(\n Supplier<CTSpriteShiftEntry> ct) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get()))\n .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> layeredConnected(\n Supplier<CTSpriteShiftEntry> ct, Supplier<CTSpriteShiftEntry> ct2) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get(), p.models()\n .cubeColumn(c.getName(), ct.get()\n .getOriginalResourceLocation(),\n ct2.get()\n .getOriginalResourceLocation())))\n .onRegister(connectedTextures(() -> new HorizontalCTBehaviour(ct.get(), ct2.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n public static <B extends OrnateGrateBlock> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> ornateconnected(\n Supplier<CTSpriteShiftEntry> ct) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get(), AssetLookup.standardModel(c, p)))\n .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n private static BlockBehaviour.Properties glassProperties(BlockBehaviour.Properties p) {\n return p.isValidSpawn(DecorBuilderTransformer::never)\n .isRedstoneConductor(DecorBuilderTransformer::never)\n .isSuffocating(DecorBuilderTransformer::never)\n .isViewBlocking(DecorBuilderTransformer::never)\n .noOcclusion();\n }\n\n public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(Supplier<ConnectedTextureBehaviour> behaviour) {\n return CreateMMBuilding.REGISTRATE.block(\"tinted_framed_glass\", ConnectedTintedGlassBlock::new)\n .onRegister(connectedTextures(behaviour))\n .addLayer(() -> RenderType::translucent)\n .initialProperties(() -> Blocks.TINTED_GLASS)\n .properties(DecorBuilderTransformer::glassProperties)\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get))\n .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, \"palettes/\", \"tinted_framed_glass\"))\n .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE)\n .lang(\"Tinted Framed Glass\")\n .item()\n .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS)\n .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()),\n p.modLoc(\"block/palettes/tinted_framed_glass\")))\n .build()\n .register();\n }\n\n public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(String type,String name, Supplier<ConnectedTextureBehaviour> behaviour) {\n return CreateMMBuilding.REGISTRATE.block(type + \"_tinted_framed_glass\", ConnectedTintedGlassBlock::new)\n .onRegister(connectedTextures(behaviour))\n .addLayer(() -> RenderType::translucent)\n .initialProperties(() -> Blocks.TINTED_GLASS)\n .properties(DecorBuilderTransformer::glassProperties)\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get))\n .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, \"palettes/\", type + \"_tinted_framed_glass\"))\n .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE)\n .lang(name + \" Tinted Framed Glass\")\n .item()\n .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS)\n .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()),\n p.modLoc(\"block/palettes/\" + type + \"_tinted_framed_glass\")))\n .build()\n .register();\n }\n\n\n\n\n public static BlockEntry<Block> CastelBricks(String id, String lang, MaterialColor color, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Brick Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_bricks\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_bricks\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Brick Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Brick Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_bricks\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Bricks\")\n .register();\n }\n\n public static BlockEntry<Block> CastelBricks(String id, String lang, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Brick Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_bricks\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_bricks\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Brick Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Brick Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_bricks\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Bricks\")\n .register();\n }\n public static BlockEntry<Block> CastelTiles(String id, String lang, MaterialColor color, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Tile Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_tiles\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_tiles\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Tile Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Tile Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_tiles\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Tiles\")\n .register();\n }\n public static BlockEntry<Block> CastelTiles(String id, String lang, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Tile Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_tiles\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_tiles\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Tile Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Tile Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_tiles\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Tiles\")\n .register();\n }\n private static boolean never(BlockState p_235436_0_, BlockGetter p_235436_1_, BlockPos p_235436_2_) {return false;}\n private static Boolean never(BlockState p_235427_0_, BlockGetter p_235427_1_, BlockPos p_235427_2_, EntityType<?> p_235427_3_) {return false;}\n private static String palettesDir() {return \"block/palettes/\";}\n}" }, { "identifier": "MmbSpriteShifts", "path": "src/main/java/com/mangomilk/design_decor/base/MmbSpriteShifts.java", "snippet": "@SuppressWarnings({\"unused\"})\npublic class MmbSpriteShifts {\n public static final Couple<CTSpriteShiftEntry>\n RED_CONTAINER_TOP = vault(\"red\",\"top\"),\n RED_CONTAINER_FRONT = vault(\"red\",\"front\"),\n RED_CONTAINER_SIDE = vault(\"red\",\"side\"),\n RED_CONTAINER_BOTTOM = vault(\"red\",\"bottom\");\n public static final Couple<CTSpriteShiftEntry>\n BLUE_CONTAINER_TOP = vault(\"blue\",\"top\"),\n BLUE_CONTAINER_FRONT = vault(\"blue\",\"front\"),\n BLUE_CONTAINER_SIDE = vault(\"blue\",\"side\"),\n BLUE_CONTAINER_BOTTOM = vault(\"blue\",\"bottom\");\n public static final Couple<CTSpriteShiftEntry>\n GREEN_CONTAINER_TOP = vault(\"green\",\"top\"),\n GREEN_CONTAINER_FRONT = vault(\"green\",\"front\"),\n GREEN_CONTAINER_SIDE = vault(\"green\",\"side\"),\n GREEN_CONTAINER_BOTTOM = vault(\"green\",\"bottom\");\n\n public static final CTSpriteShiftEntry\n ORNATE_GRATE = omni(\"ornate_grate\"),\n INDUSTRIAL_PLATING_BLOCK = omni(\"industrial_plating_block\"),\n INDUSTRIAL_PLATING_BLOCK_SIDE = omni(\"industrial_plating_block_side\"),\n TINTED_FRAMED_GLASS = omni(\"palettes/tinted_framed_glass\"),\n TINTED_HORIZONTAL_FRAMED_GLASS = omni(\"palettes/horizontal_tinted_framed_glass\"),\n TINTED_VERTICAL_FRAMED_GLASS = omni(\"palettes/vertical_tinted_framed_glass\");\n\n private static Couple<CTSpriteShiftEntry> vault(String color,String name) {\n final String prefixed = \"block/\"+color+\"_container/container_\" + name;\n return Couple.createWithContext(\n medium -> CTSpriteShifter.getCT(AllCTTypes.RECTANGLE, CreateMMBuilding.asResource(prefixed + \"_small\"),\n CreateMMBuilding.asResource(medium ? prefixed + \"_medium\" : prefixed + \"_large\")));\n }\n\n private static CTSpriteShiftEntry omni(String name) {\n return getCT(AllCTTypes.OMNIDIRECTIONAL, name);\n }\n\n private static CTSpriteShiftEntry horizontal(String name) {\n return getCT(AllCTTypes.HORIZONTAL, name);\n }\n\n private static CTSpriteShiftEntry vertical(String name) {\n return getCT(AllCTTypes.VERTICAL, name);\n }\n\n\n private static CTSpriteShiftEntry getCT(CTType type, String blockTextureName, String connectedTextureName) {\n return CTSpriteShifter.getCT(type, CreateMMBuilding.asResource(\"block/\" + blockTextureName),\n CreateMMBuilding.asResource(\"block/\" + connectedTextureName + \"_connected\"));\n }\n\n private static CTSpriteShiftEntry getCT(CTType type, String blockTextureName) {\n return getCT(type, blockTextureName, blockTextureName);\n }\n\n public static void init(){}\n\n}" }, { "identifier": "SignBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/SignBlock.java", "snippet": "public class SignBlock extends DirectionalBlock implements IWrenchable {\n\n public static final VoxelShape SHAPE_UP = Block.box(0.0D, 15.0D, 0.0D, 16.0D, 16.0D, 16.0D);\n public static final VoxelShape SHAPE_DOWN = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 1.0D, 16.0D);\n public static final VoxelShape SHAPE_NORTH = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 1.0D);\n public static final VoxelShape SHAPE_WEST = Block.box(0.0D, 0.0D, 0.0D, 1.0D, 16.0D, 16.0D);\n public static final VoxelShape SHAPE_EAST = Block.box(15.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D);\n public static final VoxelShape SHAPE_SOUTH = Block.box(0.0D, 0.0D, 15.0D, 16.0D, 16.0D, 16.0D);\n\n\n\n public static final VoxelShape SHAPE_UP_OUTLINE = Block.box(1.0D, 15.0D, 1.0D, 15.0D, 16.0D, 15.0D);\n public static final VoxelShape SHAPE_DOWN_OUTLINE = Block.box(1.0D, 0.0D, 1.0D, 15.0D, 1.0D, 15.0D);\n\n public static final VoxelShape SHAPE_WEST_OUTLINE = Block.box(0.0D, 1.0D, 1.0D, 1.0D, 15.0D, 15.0D);\n public static final VoxelShape SHAPE_EAST_OUTLINE = Block.box(15.0D, 1.0D, 1.0D, 16.0D, 15.0D, 15.0D);\n public static final VoxelShape SHAPE_SOUTH_OUTLINE = Block.box(1.0D, 1.0D, 15.0D, 15.0D, 15.0D, 16.0D);\n public static final VoxelShape SHAPE_NORTH_OUTLINE = Block.box(1.0D, 1.0D, 0.0D, 15.0D, 15.0D, 1.0D);\n public SignBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP));\n }\n\n public VoxelShape getShape(BlockState p_54561_, BlockGetter p_54562_, BlockPos p_54563_, CollisionContext p_54564_) {\n switch (p_54561_.getValue(FACING)) {\n case NORTH:\n return SHAPE_NORTH_OUTLINE;\n case SOUTH:\n return SHAPE_SOUTH_OUTLINE;\n case EAST:\n return SHAPE_EAST_OUTLINE;\n case WEST:\n return SHAPE_WEST_OUTLINE;\n case UP:\n return SHAPE_UP_OUTLINE;\n case DOWN:\n return SHAPE_DOWN_OUTLINE;\n default:\n return SHAPE_NORTH_OUTLINE;\n }\n }\n\n @Override\n public VoxelShape getBlockSupportShape(BlockState pState, BlockGetter pReader, BlockPos pPos) {\n switch (pState.getValue(FACING)) {\n case NORTH:\n return SHAPE_NORTH;\n case SOUTH:\n return SHAPE_SOUTH;\n case EAST:\n return SHAPE_EAST;\n case WEST:\n return SHAPE_WEST;\n case UP:\n return SHAPE_UP;\n case DOWN:\n return SHAPE_DOWN;\n default:\n return SHAPE_NORTH;\n }\n }\n\n public BlockState updateShape(BlockState p_57503_, Direction p_57504_, BlockState p_57505_, LevelAccessor p_57506_, BlockPos p_57507_, BlockPos p_57508_) {\n return !this.canSurvive(p_57503_, p_57506_, p_57507_) ? Blocks.AIR.defaultBlockState() : super.updateShape(p_57503_, p_57504_, p_57505_, p_57506_, p_57507_, p_57508_);\n }\n\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_55125_) {\n p_55125_.add(FACING);\n }\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_58126_) {\n BlockState blockstate = this.defaultBlockState();\n LevelReader levelreader = p_58126_.getLevel();\n BlockPos blockpos = p_58126_.getClickedPos();\n Direction[] adirection = p_58126_.getNearestLookingDirections();\n\n for(Direction direction : adirection) {\n blockstate = blockstate.setValue(FACING, direction);\n if (blockstate.canSurvive(levelreader, blockpos)) {\n return blockstate;\n }\n\n }\n\n return null;\n }\n public boolean canSurvive(BlockState p_58133_, LevelReader p_58134_, BlockPos p_58135_) {\n Direction direction = p_58133_.getValue(FACING);\n BlockPos blockpos = p_58135_.relative(direction);\n BlockState blockstate = p_58134_.getBlockState(blockpos);\n return !blockstate.isAir();\n }\n}" }, { "identifier": "LargeChain", "path": "src/main/java/com/mangomilk/design_decor/blocks/chain/LargeChain.java", "snippet": "@SuppressWarnings({\"unused\"})\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class LargeChain extends ChainBlock implements SimpleWaterloggedBlock, IWrenchable {\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n protected static final float AABB_MIN = 4;\n protected static final float AABB_MAX = 12;\n\n protected static final VoxelShape Y_AXIS_AABB = Block.box(4, 0, 4, 12, 16, 12);\n protected static final VoxelShape Z_AXIS_AABB = Block.box(4, 4, 0, 12, 12, 16);\n protected static final VoxelShape X_AXIS_AABB = Block.box(0, 4, 4, 16, 12, 12);\n\n public static final int placementHelperId = PlacementHelpers.register(new LargeChain.PlacementHelper());\n\n public LargeChain(Properties p_55926_) {\n super(p_55926_.noCollission().noOcclusion().isSuffocating(LargeChain::never).requiresCorrectToolForDrops().strength(5.0F, 6.0F)\n .sound(new ForgeSoundType(1f, .95f, () -> DecoSoundEvents.LARGE_CHAIN_BREAK.get(),\n () -> DecoSoundEvents.LARGE_CHAIN_STEP.get(), () -> DecoSoundEvents.LARGE_CHAIN_PLACE.get(),\n () -> DecoSoundEvents.LARGE_CHAIN_HIT.get(), () -> DecoSoundEvents.LARGE_CHAIN_FALL.get())));\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE).setValue(AXIS, Direction.Axis.Y));\n }\n\n @Override\n public VoxelShape getShape(BlockState p_51470_, BlockGetter p_51471_, BlockPos p_51472_, CollisionContext p_51473_) {\n switch ((Direction.Axis)p_51470_.getValue(AXIS)) {\n case X:\n default:\n return X_AXIS_AABB;\n case Z:\n return Z_AXIS_AABB;\n case Y:\n return Y_AXIS_AABB;\n }\n }\n\n @Override\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_51454_) {\n FluidState fluidstate = p_51454_.getLevel().getFluidState(p_51454_.getClickedPos());\n boolean flag = fluidstate.getType() == Fluids.WATER;\n return Objects.requireNonNull(super.getStateForPlacement(p_51454_)).setValue(WATERLOGGED, flag);\n }\n\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_51468_) {\n p_51468_.add(WATERLOGGED).add(AXIS);\n }\n\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n\n @Override\n public boolean isPathfindable(BlockState p_51456_, BlockGetter p_51457_, BlockPos p_51458_, PathComputationType p_51459_) {\n return false;\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction.Axis> {\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof LargeChain, state -> state.getValue(AXIS), AXIS);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof LargeChain;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof LargeChain;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectLargeChain(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n if (pPlayer == null)\n return InteractionResult.PASS;\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n public static BlockState pickCorrectLargeChain(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n private static boolean never(BlockState p_235436_0_, BlockGetter p_235436_1_, BlockPos p_235436_2_) {\n return false;\n }\n}" }, { "identifier": "TagDependentLargeChain", "path": "src/main/java/com/mangomilk/design_decor/blocks/chain/TagDependentLargeChain.java", "snippet": "@SuppressWarnings({\"unused\"})\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class TagDependentLargeChain extends ChainBlock implements SimpleWaterloggedBlock, IWrenchable {\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n protected static final float AABB_MIN = 4;\n protected static final float AABB_MAX = 12;\n\n protected static final VoxelShape Y_AXIS_AABB = Block.box(4, 0, 4, 12, 16, 12);\n protected static final VoxelShape Z_AXIS_AABB = Block.box(4, 4, 0, 12, 12, 16);\n protected static final VoxelShape X_AXIS_AABB = Block.box(0, 4, 4, 16, 12, 12);\n\n public static final int placementHelperId = PlacementHelpers.register(new TagDependentLargeChain.PlacementHelper());\n\n private TagKey<Item> tag;\n\n public TagDependentLargeChain(Properties p_55926_, TagKey<Item> itemTagKey) {\n super(p_55926_.noCollission().noOcclusion().isSuffocating(TagDependentLargeChain::never).requiresCorrectToolForDrops().strength(5.0F, 6.0F)\n .sound(new ForgeSoundType(1f, .95f, () -> DecoSoundEvents.LARGE_CHAIN_BREAK.get(),\n () -> DecoSoundEvents.LARGE_CHAIN_STEP.get(), () -> DecoSoundEvents.LARGE_CHAIN_PLACE.get(),\n () -> DecoSoundEvents.LARGE_CHAIN_HIT.get(), () -> DecoSoundEvents.LARGE_CHAIN_FALL.get())));\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE).setValue(AXIS, Direction.Axis.Y));\n this.tag = itemTagKey;\n }\n\n @Override\n public VoxelShape getShape(BlockState p_51470_, BlockGetter p_51471_, BlockPos p_51472_, CollisionContext p_51473_) {\n switch ((Direction.Axis)p_51470_.getValue(AXIS)) {\n case X:\n default:\n return X_AXIS_AABB;\n case Z:\n return Z_AXIS_AABB;\n case Y:\n return Y_AXIS_AABB;\n }\n }\n\n @Override\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_51454_) {\n FluidState fluidstate = p_51454_.getLevel().getFluidState(p_51454_.getClickedPos());\n boolean flag = fluidstate.getType() == Fluids.WATER;\n return Objects.requireNonNull(super.getStateForPlacement(p_51454_)).setValue(WATERLOGGED, flag);\n }\n\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_51468_) {\n p_51468_.add(WATERLOGGED).add(AXIS);\n }\n\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n\n @Override\n public boolean isPathfindable(BlockState p_51456_, BlockGetter p_51457_, BlockPos p_51458_, PathComputationType p_51459_) {\n return false;\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction.Axis> {\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof TagDependentLargeChain, state -> state.getValue(AXIS), AXIS);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof TagDependentLargeChain;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof TagDependentLargeChain;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectLargeChain(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n if (pPlayer == null)\n return InteractionResult.PASS;\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n public static BlockState pickCorrectLargeChain(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n private static boolean never(BlockState p_235436_0_, BlockGetter p_235436_1_, BlockPos p_235436_2_) {\n return false;\n }\n\n\n @Override\n public void fillItemCategory(CreativeModeTab tab, NonNullList<ItemStack> list) {\n if (!shouldHide())\n super.fillItemCategory(tab, list);\n }\n\n public boolean shouldHide() {\n ITagManager<Item> tagManager = ForgeRegistries.ITEMS.tags();\n return !tagManager.isKnownTagName(tag) || tagManager.getTag(tag).isEmpty();\n }\n}" }, { "identifier": "RedContainerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/red/RedContainerBlock.java", "snippet": "public class RedContainerBlock extends Block implements IWrenchable, IBE<RedContainerBlockEntity> {\n\n\tpublic static final Property<Axis> HORIZONTAL_AXIS = BlockStateProperties.HORIZONTAL_AXIS;\n\tpublic static final BooleanProperty LARGE = BooleanProperty.create(\"large\");\n\n\n\tpublic RedContainerBlock(Properties p_i48440_1_) {\n\t\tsuper(p_i48440_1_);\n\t\tregisterDefaultState(defaultBlockState().setValue(LARGE, false));\n\t}\n\n\t@Override\n\tprotected void createBlockStateDefinition(Builder<Block, BlockState> pBuilder) {\n\t\tpBuilder.add(HORIZONTAL_AXIS, LARGE);\n\t\tsuper.createBlockStateDefinition(pBuilder);\n\t}\n\n\t@Override\n\tpublic BlockState getStateForPlacement(BlockPlaceContext pContext) {\n\t\tif (pContext.getPlayer() == null || !pContext.getPlayer()\n\t\t\t.isSteppingCarefully()) {\n\t\t\tBlockState placedOn = pContext.getLevel()\n\t\t\t\t.getBlockState(pContext.getClickedPos()\n\t\t\t\t\t.relative(pContext.getClickedFace()\n\t\t\t\t\t\t.getOpposite()));\n\t\t\tAxis preferredAxis = getContainerBlockAxis(placedOn);\n\t\t\tif (preferredAxis != null)\n\t\t\t\treturn this.defaultBlockState()\n\t\t\t\t\t.setValue(HORIZONTAL_AXIS, preferredAxis);\n\t\t}\n\t\treturn this.defaultBlockState()\n\t\t\t.setValue(HORIZONTAL_AXIS, pContext.getHorizontalDirection()\n\t\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic void onPlace(BlockState pState, Level pLevel, BlockPos pPos, BlockState pOldState, boolean pIsMoving) {\n\t\tif (pOldState.getBlock() == pState.getBlock())\n\t\t\treturn;\n\t\tif (pIsMoving)\n\t\t\treturn;\n\t\twithBlockEntityDo(pLevel, pPos, RedContainerBlockEntity::updateConnectivity);\n\t}\n\n\t@Override\n\tpublic InteractionResult onWrenched(BlockState state, UseOnContext context) {\n\t\tif (context.getClickedFace()\n\t\t\t.getAxis()\n\t\t\t.isVertical()) {\n\t\t\tBlockEntity be = context.getLevel()\n\t\t\t\t.getBlockEntity(context.getClickedPos());\n\t\t\tif (be instanceof RedContainerBlockEntity) {\n\t\t\t\tRedContainerBlockEntity container = (RedContainerBlockEntity) be;\n\t\t\t\tConnectivityHandler.splitMulti(container);\n\t\t\t\tcontainer.removeController(true);\n\t\t\t}\n\t\t\tstate = state.setValue(LARGE, false);\n\t\t}\n\t\tInteractionResult onWrenched = IWrenchable.super.onWrenched(state, context);\n\t\treturn onWrenched;\n\t}\n\n\t@Override\n\tpublic void onRemove(BlockState state, Level world, BlockPos pos, BlockState newState, boolean pIsMoving) {\n\t\tif (state.hasBlockEntity() && (state.getBlock() != newState.getBlock() || !newState.hasBlockEntity())) {\n\t\t\tBlockEntity be = world.getBlockEntity(pos);\n\t\t\tif (!(be instanceof RedContainerBlockEntity))\n\t\t\t\treturn;\n\t\t\tRedContainerBlockEntity containerBE = (RedContainerBlockEntity) be;\n\t\t\tItemHelper.dropContents(world, pos, containerBE.inventory);\n\t\t\tworld.removeBlockEntity(pos);\n\t\t\tConnectivityHandler.splitMulti(containerBE);\n\t\t}\n\t}\n\n\tpublic static boolean isContainer(BlockState state) {\n\n\n\t\treturn MmbBlocks.RED_CONTAINER.has(state);\n\t}\n\n\t@Nullable\n\tpublic static Axis getContainerBlockAxis(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn null;\n\t\treturn state.getValue(HORIZONTAL_AXIS);\n\t}\n\n\tpublic static boolean isLarge(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn false;\n\t\treturn state.getValue(LARGE);\n\t}\n\n\t@Override\n\tpublic BlockState rotate(BlockState state, Rotation rot) {\n\t\tAxis axis = state.getValue(HORIZONTAL_AXIS);\n\t\treturn state.setValue(HORIZONTAL_AXIS, rot.rotate(Direction.fromAxisAndDirection(axis, AxisDirection.POSITIVE))\n\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic BlockState mirror(BlockState state, Mirror mirrorIn) {\n\t\treturn state;\n\t}\n\n\n\tpublic static final SoundType SILENCED_METAL =\n\t\tnew ForgeSoundType(0.1F, 1.5F, () -> SoundEvents.NETHERITE_BLOCK_BREAK, () -> SoundEvents.NETHERITE_BLOCK_STEP,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_PLACE, () -> SoundEvents.NETHERITE_BLOCK_HIT,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_FALL);\n\n\t@Override\n\tpublic SoundType getSoundType(BlockState state, LevelReader world, BlockPos pos, Entity entity) {\n\t\tSoundType soundType = super.getSoundType(state, world, pos, entity);\n\t\tif (entity != null && entity.getPersistentData()\n\t\t\t.contains(\"SilenceVaultSound\"))\n\t\t\treturn SILENCED_METAL;\n\t\treturn soundType;\n\t}\n\n\t@Override\n\tpublic boolean hasAnalogOutputSignal(BlockState p_149740_1_) {\n\t\treturn true;\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"removal\")\n\tpublic int getAnalogOutputSignal(BlockState pState, Level pLevel, BlockPos pPos) {\n\t\treturn getBlockEntityOptional(pLevel, pPos)\n\t\t\t.map(vte -> vte.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY))\n\t\t\t.map(lo -> lo.map(ItemHelper::calcRedstoneFromInventory)\n\t\t\t\t.orElse(0))\n\t\t\t.orElse(0);\n\t}\n\n\t@Override\n\tpublic BlockEntityType<? extends RedContainerBlockEntity> getBlockEntityType() {\n\t\treturn MmbBlockEntities.RED_CONTAINER.get();\n\t}\n\n\t@Override\n\tpublic Class<RedContainerBlockEntity> getBlockEntityClass() {\n\t\treturn RedContainerBlockEntity.class;\n\t}\n\n\n\n\n\n\n}" }, { "identifier": "RedContainerCTBehaviour", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/red/RedContainerCTBehaviour.java", "snippet": "public class RedContainerCTBehaviour extends ConnectedTextureBehaviour.Base {\n\n\t@Override\n\tpublic CTSpriteShiftEntry getShift(BlockState state, Direction direction, @Nullable TextureAtlasSprite sprite) {\n\t\tAxis containerBlockAxis = RedContainerBlock.getContainerBlockAxis(state);\n\t\tboolean small = !RedContainerBlock.isLarge(state);\n\t\tif (containerBlockAxis == null)\n\t\t\treturn null;\n\n\t\tif (direction.getAxis() == containerBlockAxis)\n\t\t\treturn MmbSpriteShifts.RED_CONTAINER_FRONT.get(small);\n\t\tif (direction == Direction.UP)\n\t\t\treturn MmbSpriteShifts.RED_CONTAINER_TOP.get(small);\n\t\tif (direction == Direction.DOWN)\n\t\t\treturn MmbSpriteShifts.RED_CONTAINER_BOTTOM.get(small);\n\n\t\treturn MmbSpriteShifts.RED_CONTAINER_SIDE.get(small);\n\t}\n\n\t@Override\n\tprotected Direction getUpDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = RedContainerBlock.getContainerBlockAxis(state);\n\t\tboolean alongX = containerBlockAxis == Axis.X;\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && alongX)\n\t\t\treturn super.getUpDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getUpDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(containerBlockAxis, alongX ? AxisDirection.POSITIVE : AxisDirection.NEGATIVE);\n\t}\n\n\t@Override\n\tprotected Direction getRightDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = RedContainerBlock.getContainerBlockAxis(state);\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && containerBlockAxis == Axis.X)\n\t\t\treturn super.getRightDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getRightDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(Axis.Y, face.getAxisDirection());\n\t}\n\n\tpublic boolean buildContextForOccludedDirections() {\n\t\treturn super.buildContextForOccludedDirections();\n\t}\n\n\t@Override\n\tpublic boolean connectsTo(BlockState state, BlockState other, BlockAndTintGetter reader, BlockPos pos,\n\t\tBlockPos otherPos, Direction face) {\n\t\treturn state == other && ConnectivityHandler.isConnected(reader, pos, otherPos); //ItemVaultConnectivityHandler.isConnected(reader, pos, otherPos);\n\t}\n\n}" }, { "identifier": "RedContainerItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/red/RedContainerItem.java", "snippet": "public class RedContainerItem extends BlockItem {\n\n\tpublic RedContainerItem(Block p_i48527_1_, Properties p_i48527_2_) {\n\t\tsuper(p_i48527_1_, p_i48527_2_);\n\t}\n\n\t@Override\n\tpublic InteractionResult place(BlockPlaceContext ctx) {\n\t\tInteractionResult initialResult = super.place(ctx);\n\t\tif (!initialResult.consumesAction())\n\t\t\treturn initialResult;\n\t\ttryMultiPlace(ctx);\n\t\treturn initialResult;\n\t}\n\n\t@Override\n\tprotected boolean updateCustomBlockEntityTag(BlockPos p_195943_1_, Level p_195943_2_, Player p_195943_3_,\n\t\tItemStack p_195943_4_, BlockState p_195943_5_) {\n\t\tMinecraftServer minecraftserver = p_195943_2_.getServer();\n\t\tif (minecraftserver == null)\n\t\t\treturn false;\n\t\tCompoundTag nbt = p_195943_4_.getTagElement(\"BlockEntityTag\");\n\t\tif (nbt != null) {\n\t\t\tnbt.remove(\"Length\");\n\t\t\tnbt.remove(\"Size\");\n\t\t\tnbt.remove(\"Controller\");\n\t\t\tnbt.remove(\"LastKnownPos\");\n\t\t}\n\t\treturn super.updateCustomBlockEntityTag(p_195943_1_, p_195943_2_, p_195943_3_, p_195943_4_, p_195943_5_);\n\t}\n\n\tpublic void tryMultiPlace(BlockPlaceContext ctx) {\n\t\tPlayer player = ctx.getPlayer();\n\t\tif (player == null)\n\t\t\treturn;\n\t\tif (player.isSteppingCarefully())\n\t\t\treturn;\n\t\tDirection face = ctx.getClickedFace();\n\t\tItemStack stack = ctx.getItemInHand();\n\t\tLevel world = ctx.getLevel();\n\t\tBlockPos pos = ctx.getClickedPos();\n\t\tBlockPos placedOnPos = pos.relative(face.getOpposite());\n\t\tBlockState placedOnState = world.getBlockState(placedOnPos);\n\n\t\tif (!RedContainerBlock.isContainer(placedOnState))\n\t\t\treturn;\n\t\tRedContainerBlockEntity tankAt = ConnectivityHandler.partAt(MmbBlockEntities.RED_CONTAINER.get(), world, placedOnPos);\n\t\tif (tankAt == null)\n\t\t\treturn;\n\t\tRedContainerBlockEntity controllerBE = tankAt.getControllerBE();\n\t\tif (controllerBE == null)\n\t\t\treturn;\n\n\t\tint width = controllerBE.radius;\n\t\tif (width == 1)\n\t\t\treturn;\n\n\t\tint tanksToPlace = 0;\n\t\tAxis vaultBlockAxis = RedContainerBlock.getContainerBlockAxis(placedOnState);\n\t\tif (vaultBlockAxis == null)\n\t\t\treturn;\n\t\tif (face.getAxis() != vaultBlockAxis)\n\t\t\treturn;\n\n\t\tDirection vaultFacing = Direction.fromAxisAndDirection(vaultBlockAxis, AxisDirection.POSITIVE);\n\t\tBlockPos startPos = face == vaultFacing.getOpposite() ? controllerBE.getBlockPos()\n\t\t\t.relative(vaultFacing.getOpposite())\n\t\t\t: controllerBE.getBlockPos()\n\t\t\t\t.relative(vaultFacing, controllerBE.length);\n\n\t\tif (VecHelper.getCoordinate(startPos, vaultBlockAxis) != VecHelper.getCoordinate(pos, vaultBlockAxis))\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\t\t\t\tif (RedContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!blockState.getMaterial()\n\t\t\t\t\t.isReplaceable())\n\t\t\t\t\treturn;\n\t\t\t\ttanksToPlace++;\n\t\t\t}\n\t\t}\n\n\t\tif (!player.isCreative() && stack.getCount() < tanksToPlace)\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\n\n\t\t\t\tif (RedContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\n\n\t\t\t\tBlockPlaceContext context = BlockPlaceContext.at(ctx, offsetPos, face);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.putBoolean(\"SilenceVaultSound\", true);\n\t\t\t\tsuper.place(context);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.remove(\"SilenceVaultSound\");\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "BlueContainerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/blue/BlueContainerBlock.java", "snippet": "public class BlueContainerBlock extends Block implements IWrenchable, IBE<BlueContainerBlockEntity> {\n\n\tpublic static final Property<Axis> HORIZONTAL_AXIS = BlockStateProperties.HORIZONTAL_AXIS;\n\tpublic static final BooleanProperty LARGE = BooleanProperty.create(\"large\");\n\n\n\tpublic BlueContainerBlock(Properties p_i48440_1_) {\n\t\tsuper(p_i48440_1_);\n\t\tregisterDefaultState(defaultBlockState().setValue(LARGE, false));\n\t}\n\n\t@Override\n\tprotected void createBlockStateDefinition(Builder<Block, BlockState> pBuilder) {\n\t\tpBuilder.add(HORIZONTAL_AXIS, LARGE);\n\t\tsuper.createBlockStateDefinition(pBuilder);\n\t}\n\n\t@Override\n\tpublic BlockState getStateForPlacement(BlockPlaceContext pContext) {\n\t\tif (pContext.getPlayer() == null || !pContext.getPlayer()\n\t\t\t.isSteppingCarefully()) {\n\t\t\tBlockState placedOn = pContext.getLevel()\n\t\t\t\t.getBlockState(pContext.getClickedPos()\n\t\t\t\t\t.relative(pContext.getClickedFace()\n\t\t\t\t\t\t.getOpposite()));\n\t\t\tAxis preferredAxis = getContainerBlockAxis(placedOn);\n\t\t\tif (preferredAxis != null)\n\t\t\t\treturn this.defaultBlockState()\n\t\t\t\t\t.setValue(HORIZONTAL_AXIS, preferredAxis);\n\t\t}\n\t\treturn this.defaultBlockState()\n\t\t\t.setValue(HORIZONTAL_AXIS, pContext.getHorizontalDirection()\n\t\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic void onPlace(BlockState pState, Level pLevel, BlockPos pPos, BlockState pOldState, boolean pIsMoving) {\n\t\tif (pOldState.getBlock() == pState.getBlock())\n\t\t\treturn;\n\t\tif (pIsMoving)\n\t\t\treturn;\n\t\twithBlockEntityDo(pLevel, pPos, BlueContainerBlockEntity::updateConnectivity);\n\t}\n\n\t@Override\n\tpublic InteractionResult onWrenched(BlockState state, UseOnContext context) {\n\t\tif (context.getClickedFace()\n\t\t\t.getAxis()\n\t\t\t.isVertical()) {\n\t\t\tBlockEntity be = context.getLevel()\n\t\t\t\t.getBlockEntity(context.getClickedPos());\n\t\t\tif (be instanceof BlueContainerBlockEntity) {\n\t\t\t\tBlueContainerBlockEntity container = (BlueContainerBlockEntity) be;\n\t\t\t\tConnectivityHandler.splitMulti(container);\n\t\t\t\tcontainer.removeController(true);\n\t\t\t}\n\t\t\tstate = state.setValue(LARGE, false);\n\t\t}\n\t\tInteractionResult onWrenched = IWrenchable.super.onWrenched(state, context);\n\t\treturn onWrenched;\n\t}\n\n\t@Override\n\tpublic void onRemove(BlockState state, Level world, BlockPos pos, BlockState newState, boolean pIsMoving) {\n\t\tif (state.hasBlockEntity() && (state.getBlock() != newState.getBlock() || !newState.hasBlockEntity())) {\n\t\t\tBlockEntity be = world.getBlockEntity(pos);\n\t\t\tif (!(be instanceof BlueContainerBlockEntity))\n\t\t\t\treturn;\n\t\t\tBlueContainerBlockEntity containerBE = (BlueContainerBlockEntity) be;\n\t\t\tItemHelper.dropContents(world, pos, containerBE.inventory);\n\t\t\tworld.removeBlockEntity(pos);\n\t\t\tConnectivityHandler.splitMulti(containerBE);\n\t\t}\n\t}\n\n\tpublic static boolean isContainer(BlockState state) {\n\n\n\t\treturn MmbBlocks.BLUE_CONTAINER.has(state);\n\t}\n\n\t@Nullable\n\tpublic static Axis getContainerBlockAxis(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn null;\n\t\treturn state.getValue(HORIZONTAL_AXIS);\n\t}\n\n\tpublic static boolean isLarge(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn false;\n\t\treturn state.getValue(LARGE);\n\t}\n\n\t@Override\n\tpublic BlockState rotate(BlockState state, Rotation rot) {\n\t\tAxis axis = state.getValue(HORIZONTAL_AXIS);\n\t\treturn state.setValue(HORIZONTAL_AXIS, rot.rotate(Direction.fromAxisAndDirection(axis, AxisDirection.POSITIVE))\n\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic BlockState mirror(BlockState state, Mirror mirrorIn) {\n\t\treturn state;\n\t}\n\n\n\tpublic static final SoundType SILENCED_METAL =\n\t\tnew ForgeSoundType(0.1F, 1.5F, () -> SoundEvents.NETHERITE_BLOCK_BREAK, () -> SoundEvents.NETHERITE_BLOCK_STEP,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_PLACE, () -> SoundEvents.NETHERITE_BLOCK_HIT,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_FALL);\n\n\t@Override\n\tpublic SoundType getSoundType(BlockState state, LevelReader world, BlockPos pos, Entity entity) {\n\t\tSoundType soundType = super.getSoundType(state, world, pos, entity);\n\t\tif (entity != null && entity.getPersistentData()\n\t\t\t.contains(\"SilenceVaultSound\"))\n\t\t\treturn SILENCED_METAL;\n\t\treturn soundType;\n\t}\n\n\t@Override\n\tpublic boolean hasAnalogOutputSignal(BlockState p_149740_1_) {\n\t\treturn true;\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"removal\")\n\tpublic int getAnalogOutputSignal(BlockState pState, Level pLevel, BlockPos pPos) {\n\t\treturn getBlockEntityOptional(pLevel, pPos)\n\t\t\t.map(vte -> vte.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY))\n\t\t\t.map(lo -> lo.map(ItemHelper::calcRedstoneFromInventory)\n\t\t\t\t.orElse(0))\n\t\t\t.orElse(0);\n\t}\n\n\t@Override\n\tpublic BlockEntityType<? extends BlueContainerBlockEntity> getBlockEntityType() {\n\t\treturn MmbBlockEntities.BLUE_CONTAINER.get();\n\t}\n\n\t@Override\n\tpublic Class<BlueContainerBlockEntity> getBlockEntityClass() {\n\t\treturn BlueContainerBlockEntity.class;\n\t}\n\n\n\n\n\n\n}" }, { "identifier": "BlueContainerCTBehaviour", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/blue/BlueContainerCTBehaviour.java", "snippet": "public class BlueContainerCTBehaviour extends ConnectedTextureBehaviour.Base {\n\n\t@Override\n\tpublic CTSpriteShiftEntry getShift(BlockState state, Direction direction, @Nullable TextureAtlasSprite sprite) {\n\t\tAxis containerBlockAxis = BlueContainerBlock.getContainerBlockAxis(state);\n\t\tboolean small = !BlueContainerBlock.isLarge(state);\n\t\tif (containerBlockAxis == null)\n\t\t\treturn null;\n\n\t\tif (direction.getAxis() == containerBlockAxis)\n\t\t\treturn MmbSpriteShifts.BLUE_CONTAINER_FRONT.get(small);\n\t\tif (direction == Direction.UP)\n\t\t\treturn MmbSpriteShifts.BLUE_CONTAINER_TOP.get(small);\n\t\tif (direction == Direction.DOWN)\n\t\t\treturn MmbSpriteShifts.BLUE_CONTAINER_BOTTOM.get(small);\n\n\t\treturn MmbSpriteShifts.BLUE_CONTAINER_SIDE.get(small);\n\t}\n\n\t@Override\n\tprotected Direction getUpDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = BlueContainerBlock.getContainerBlockAxis(state);\n\t\tboolean alongX = containerBlockAxis == Axis.X;\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && alongX)\n\t\t\treturn super.getUpDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getUpDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(containerBlockAxis, alongX ? AxisDirection.POSITIVE : AxisDirection.NEGATIVE);\n\t}\n\n\t@Override\n\tprotected Direction getRightDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = BlueContainerBlock.getContainerBlockAxis(state);\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && containerBlockAxis == Axis.X)\n\t\t\treturn super.getRightDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getRightDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(Axis.Y, face.getAxisDirection());\n\t}\n\n\tpublic boolean buildContextForOccludedDirections() {\n\t\treturn super.buildContextForOccludedDirections();\n\t}\n\n\t@Override\n\tpublic boolean connectsTo(BlockState state, BlockState other, BlockAndTintGetter reader, BlockPos pos,\n\t\tBlockPos otherPos, Direction face) {\n\t\treturn state == other && ConnectivityHandler.isConnected(reader, pos, otherPos); //ItemVaultConnectivityHandler.isConnected(reader, pos, otherPos);\n\t}\n\n}" }, { "identifier": "BlueContainerItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/blue/BlueContainerItem.java", "snippet": "public class BlueContainerItem extends BlockItem {\n\n\tpublic BlueContainerItem(Block p_i48527_1_, Properties p_i48527_2_) {\n\t\tsuper(p_i48527_1_, p_i48527_2_);\n\t}\n\n\t@Override\n\tpublic InteractionResult place(BlockPlaceContext ctx) {\n\t\tInteractionResult initialResult = super.place(ctx);\n\t\tif (!initialResult.consumesAction())\n\t\t\treturn initialResult;\n\t\ttryMultiPlace(ctx);\n\t\treturn initialResult;\n\t}\n\n\t@Override\n\tprotected boolean updateCustomBlockEntityTag(BlockPos p_195943_1_, Level p_195943_2_, Player p_195943_3_,\n\t\tItemStack p_195943_4_, BlockState p_195943_5_) {\n\t\tMinecraftServer minecraftserver = p_195943_2_.getServer();\n\t\tif (minecraftserver == null)\n\t\t\treturn false;\n\t\tCompoundTag nbt = p_195943_4_.getTagElement(\"BlockEntityTag\");\n\t\tif (nbt != null) {\n\t\t\tnbt.remove(\"Length\");\n\t\t\tnbt.remove(\"Size\");\n\t\t\tnbt.remove(\"Controller\");\n\t\t\tnbt.remove(\"LastKnownPos\");\n\t\t}\n\t\treturn super.updateCustomBlockEntityTag(p_195943_1_, p_195943_2_, p_195943_3_, p_195943_4_, p_195943_5_);\n\t}\n\n\tpublic void tryMultiPlace(BlockPlaceContext ctx) {\n\t\tPlayer player = ctx.getPlayer();\n\t\tif (player == null)\n\t\t\treturn;\n\t\tif (player.isSteppingCarefully())\n\t\t\treturn;\n\t\tDirection face = ctx.getClickedFace();\n\t\tItemStack stack = ctx.getItemInHand();\n\t\tLevel world = ctx.getLevel();\n\t\tBlockPos pos = ctx.getClickedPos();\n\t\tBlockPos placedOnPos = pos.relative(face.getOpposite());\n\t\tBlockState placedOnState = world.getBlockState(placedOnPos);\n\n\t\tif (!BlueContainerBlock.isContainer(placedOnState))\n\t\t\treturn;\n\t\tBlueContainerBlockEntity tankAt = ConnectivityHandler.partAt(MmbBlockEntities.BLUE_CONTAINER.get(), world, placedOnPos);\n\t\tif (tankAt == null)\n\t\t\treturn;\n\t\tBlueContainerBlockEntity controllerBE = tankAt.getControllerBE();\n\t\tif (controllerBE == null)\n\t\t\treturn;\n\n\t\tint width = controllerBE.radius;\n\t\tif (width == 1)\n\t\t\treturn;\n\n\t\tint tanksToPlace = 0;\n\t\tAxis vaultBlockAxis = BlueContainerBlock.getContainerBlockAxis(placedOnState);\n\t\tif (vaultBlockAxis == null)\n\t\t\treturn;\n\t\tif (face.getAxis() != vaultBlockAxis)\n\t\t\treturn;\n\n\t\tDirection vaultFacing = Direction.fromAxisAndDirection(vaultBlockAxis, AxisDirection.POSITIVE);\n\t\tBlockPos startPos = face == vaultFacing.getOpposite() ? controllerBE.getBlockPos()\n\t\t\t.relative(vaultFacing.getOpposite())\n\t\t\t: controllerBE.getBlockPos()\n\t\t\t\t.relative(vaultFacing, controllerBE.length);\n\n\t\tif (VecHelper.getCoordinate(startPos, vaultBlockAxis) != VecHelper.getCoordinate(pos, vaultBlockAxis))\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\t\t\t\tif (BlueContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!blockState.getMaterial()\n\t\t\t\t\t.isReplaceable())\n\t\t\t\t\treturn;\n\t\t\t\ttanksToPlace++;\n\t\t\t}\n\t\t}\n\n\t\tif (!player.isCreative() && stack.getCount() < tanksToPlace)\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\n\n\t\t\t\tif (BlueContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\n\n\t\t\t\tBlockPlaceContext context = BlockPlaceContext.at(ctx, offsetPos, face);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.putBoolean(\"SilenceVaultSound\", true);\n\t\t\t\tsuper.place(context);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.remove(\"SilenceVaultSound\");\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "GreenContainerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/green/GreenContainerBlock.java", "snippet": "public class GreenContainerBlock extends Block implements IWrenchable, IBE<GreenContainerBlockEntity> {\n\n\tpublic static final Property<Axis> HORIZONTAL_AXIS = BlockStateProperties.HORIZONTAL_AXIS;\n\tpublic static final BooleanProperty LARGE = BooleanProperty.create(\"large\");\n\n\n\tpublic GreenContainerBlock(Properties p_i48440_1_) {\n\t\tsuper(p_i48440_1_);\n\t\tregisterDefaultState(defaultBlockState().setValue(LARGE, false));\n\t}\n\n\t@Override\n\tprotected void createBlockStateDefinition(Builder<Block, BlockState> pBuilder) {\n\t\tpBuilder.add(HORIZONTAL_AXIS, LARGE);\n\t\tsuper.createBlockStateDefinition(pBuilder);\n\t}\n\n\t@Override\n\tpublic BlockState getStateForPlacement(BlockPlaceContext pContext) {\n\t\tif (pContext.getPlayer() == null || !pContext.getPlayer()\n\t\t\t.isSteppingCarefully()) {\n\t\t\tBlockState placedOn = pContext.getLevel()\n\t\t\t\t.getBlockState(pContext.getClickedPos()\n\t\t\t\t\t.relative(pContext.getClickedFace()\n\t\t\t\t\t\t.getOpposite()));\n\t\t\tAxis preferredAxis = getContainerBlockAxis(placedOn);\n\t\t\tif (preferredAxis != null)\n\t\t\t\treturn this.defaultBlockState()\n\t\t\t\t\t.setValue(HORIZONTAL_AXIS, preferredAxis);\n\t\t}\n\t\treturn this.defaultBlockState()\n\t\t\t.setValue(HORIZONTAL_AXIS, pContext.getHorizontalDirection()\n\t\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic void onPlace(BlockState pState, Level pLevel, BlockPos pPos, BlockState pOldState, boolean pIsMoving) {\n\t\tif (pOldState.getBlock() == pState.getBlock())\n\t\t\treturn;\n\t\tif (pIsMoving)\n\t\t\treturn;\n\t\twithBlockEntityDo(pLevel, pPos, GreenContainerBlockEntity::updateConnectivity);\n\t}\n\n\t@Override\n\tpublic InteractionResult onWrenched(BlockState state, UseOnContext context) {\n\t\tif (context.getClickedFace()\n\t\t\t.getAxis()\n\t\t\t.isVertical()) {\n\t\t\tBlockEntity be = context.getLevel()\n\t\t\t\t.getBlockEntity(context.getClickedPos());\n\t\t\tif (be instanceof GreenContainerBlockEntity) {\n\t\t\t\tGreenContainerBlockEntity container = (GreenContainerBlockEntity) be;\n\t\t\t\tConnectivityHandler.splitMulti(container);\n\t\t\t\tcontainer.removeController(true);\n\t\t\t}\n\t\t\tstate = state.setValue(LARGE, false);\n\t\t}\n\t\tInteractionResult onWrenched = IWrenchable.super.onWrenched(state, context);\n\t\treturn onWrenched;\n\t}\n\n\t@Override\n\tpublic void onRemove(BlockState state, Level world, BlockPos pos, BlockState newState, boolean pIsMoving) {\n\t\tif (state.hasBlockEntity() && (state.getBlock() != newState.getBlock() || !newState.hasBlockEntity())) {\n\t\t\tBlockEntity be = world.getBlockEntity(pos);\n\t\t\tif (!(be instanceof GreenContainerBlockEntity))\n\t\t\t\treturn;\n\t\t\tGreenContainerBlockEntity containerBE = (GreenContainerBlockEntity) be;\n\t\t\tItemHelper.dropContents(world, pos, containerBE.inventory);\n\t\t\tworld.removeBlockEntity(pos);\n\t\t\tConnectivityHandler.splitMulti(containerBE);\n\t\t}\n\t}\n\n\tpublic static boolean isContainer(BlockState state) {\n\n\n\t\treturn MmbBlocks.GREEN_CONTAINER.has(state);\n\t}\n\n\t@Nullable\n\tpublic static Axis getContainerBlockAxis(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn null;\n\t\treturn state.getValue(HORIZONTAL_AXIS);\n\t}\n\n\tpublic static boolean isLarge(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn false;\n\t\treturn state.getValue(LARGE);\n\t}\n\n\t@Override\n\tpublic BlockState rotate(BlockState state, Rotation rot) {\n\t\tAxis axis = state.getValue(HORIZONTAL_AXIS);\n\t\treturn state.setValue(HORIZONTAL_AXIS, rot.rotate(Direction.fromAxisAndDirection(axis, AxisDirection.POSITIVE))\n\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic BlockState mirror(BlockState state, Mirror mirrorIn) {\n\t\treturn state;\n\t}\n\n\n\tpublic static final SoundType SILENCED_METAL =\n\t\tnew ForgeSoundType(0.1F, 1.5F, () -> SoundEvents.NETHERITE_BLOCK_BREAK, () -> SoundEvents.NETHERITE_BLOCK_STEP,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_PLACE, () -> SoundEvents.NETHERITE_BLOCK_HIT,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_FALL);\n\n\t@Override\n\tpublic SoundType getSoundType(BlockState state, LevelReader world, BlockPos pos, Entity entity) {\n\t\tSoundType soundType = super.getSoundType(state, world, pos, entity);\n\t\tif (entity != null && entity.getPersistentData()\n\t\t\t.contains(\"SilenceVaultSound\"))\n\t\t\treturn SILENCED_METAL;\n\t\treturn soundType;\n\t}\n\n\t@Override\n\tpublic boolean hasAnalogOutputSignal(BlockState p_149740_1_) {\n\t\treturn true;\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"removal\")\n\tpublic int getAnalogOutputSignal(BlockState pState, Level pLevel, BlockPos pPos) {\n\t\treturn getBlockEntityOptional(pLevel, pPos)\n\t\t\t.map(vte -> vte.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY))\n\t\t\t.map(lo -> lo.map(ItemHelper::calcRedstoneFromInventory)\n\t\t\t\t.orElse(0))\n\t\t\t.orElse(0);\n\t}\n\n\t@Override\n\tpublic BlockEntityType<? extends GreenContainerBlockEntity> getBlockEntityType() {\n\t\treturn MmbBlockEntities.GREEN_CONTAINER.get();\n\t}\n\n\t@Override\n\tpublic Class<GreenContainerBlockEntity> getBlockEntityClass() {\n\t\treturn GreenContainerBlockEntity.class;\n\t}\n\n\n\n\n\n\n}" }, { "identifier": "GreenContainerCTBehaviour", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/green/GreenContainerCTBehaviour.java", "snippet": "public class GreenContainerCTBehaviour extends ConnectedTextureBehaviour.Base {\n\n\t@Override\n\tpublic CTSpriteShiftEntry getShift(BlockState state, Direction direction, @Nullable TextureAtlasSprite sprite) {\n\t\tAxis containerBlockAxis = GreenContainerBlock.getContainerBlockAxis(state);\n\t\tboolean small = !GreenContainerBlock.isLarge(state);\n\t\tif (containerBlockAxis == null)\n\t\t\treturn null;\n\n\t\tif (direction.getAxis() == containerBlockAxis)\n\t\t\treturn MmbSpriteShifts.GREEN_CONTAINER_FRONT.get(small);\n\t\tif (direction == Direction.UP)\n\t\t\treturn MmbSpriteShifts.GREEN_CONTAINER_TOP.get(small);\n\t\tif (direction == Direction.DOWN)\n\t\t\treturn MmbSpriteShifts.GREEN_CONTAINER_BOTTOM.get(small);\n\n\t\treturn MmbSpriteShifts.GREEN_CONTAINER_SIDE.get(small);\n\t}\n\n\t@Override\n\tprotected Direction getUpDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = GreenContainerBlock.getContainerBlockAxis(state);\n\t\tboolean alongX = containerBlockAxis == Axis.X;\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && alongX)\n\t\t\treturn super.getUpDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getUpDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(containerBlockAxis, alongX ? AxisDirection.POSITIVE : AxisDirection.NEGATIVE);\n\t}\n\n\t@Override\n\tprotected Direction getRightDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = GreenContainerBlock.getContainerBlockAxis(state);\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && containerBlockAxis == Axis.X)\n\t\t\treturn super.getRightDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getRightDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(Axis.Y, face.getAxisDirection());\n\t}\n\n\tpublic boolean buildContextForOccludedDirections() {\n\t\treturn super.buildContextForOccludedDirections();\n\t}\n\n\t@Override\n\tpublic boolean connectsTo(BlockState state, BlockState other, BlockAndTintGetter reader, BlockPos pos,\n\t\tBlockPos otherPos, Direction face) {\n\t\treturn state == other && ConnectivityHandler.isConnected(reader, pos, otherPos); //ItemVaultConnectivityHandler.isConnected(reader, pos, otherPos);\n\t}\n\n}" }, { "identifier": "GreenContainerItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/green/GreenContainerItem.java", "snippet": "public class GreenContainerItem extends BlockItem {\n\n\tpublic GreenContainerItem(Block p_i48527_1_, Properties p_i48527_2_) {\n\t\tsuper(p_i48527_1_, p_i48527_2_);\n\t}\n\n\t@Override\n\tpublic InteractionResult place(BlockPlaceContext ctx) {\n\t\tInteractionResult initialResult = super.place(ctx);\n\t\tif (!initialResult.consumesAction())\n\t\t\treturn initialResult;\n\t\ttryMultiPlace(ctx);\n\t\treturn initialResult;\n\t}\n\n\t@Override\n\tprotected boolean updateCustomBlockEntityTag(BlockPos p_195943_1_, Level p_195943_2_, Player p_195943_3_,\n\t\tItemStack p_195943_4_, BlockState p_195943_5_) {\n\t\tMinecraftServer minecraftserver = p_195943_2_.getServer();\n\t\tif (minecraftserver == null)\n\t\t\treturn false;\n\t\tCompoundTag nbt = p_195943_4_.getTagElement(\"BlockEntityTag\");\n\t\tif (nbt != null) {\n\t\t\tnbt.remove(\"Length\");\n\t\t\tnbt.remove(\"Size\");\n\t\t\tnbt.remove(\"Controller\");\n\t\t\tnbt.remove(\"LastKnownPos\");\n\t\t}\n\t\treturn super.updateCustomBlockEntityTag(p_195943_1_, p_195943_2_, p_195943_3_, p_195943_4_, p_195943_5_);\n\t}\n\n\tpublic void tryMultiPlace(BlockPlaceContext ctx) {\n\t\tPlayer player = ctx.getPlayer();\n\t\tif (player == null)\n\t\t\treturn;\n\t\tif (player.isSteppingCarefully())\n\t\t\treturn;\n\t\tDirection face = ctx.getClickedFace();\n\t\tItemStack stack = ctx.getItemInHand();\n\t\tLevel world = ctx.getLevel();\n\t\tBlockPos pos = ctx.getClickedPos();\n\t\tBlockPos placedOnPos = pos.relative(face.getOpposite());\n\t\tBlockState placedOnState = world.getBlockState(placedOnPos);\n\n\t\tif (!GreenContainerBlock.isContainer(placedOnState))\n\t\t\treturn;\n\t\tGreenContainerBlockEntity tankAt = ConnectivityHandler.partAt(MmbBlockEntities.GREEN_CONTAINER.get(), world, placedOnPos);\n\t\tif (tankAt == null)\n\t\t\treturn;\n\t\tGreenContainerBlockEntity controllerBE = tankAt.getControllerBE();\n\t\tif (controllerBE == null)\n\t\t\treturn;\n\n\t\tint width = controllerBE.radius;\n\t\tif (width == 1)\n\t\t\treturn;\n\n\t\tint tanksToPlace = 0;\n\t\tAxis vaultBlockAxis = GreenContainerBlock.getContainerBlockAxis(placedOnState);\n\t\tif (vaultBlockAxis == null)\n\t\t\treturn;\n\t\tif (face.getAxis() != vaultBlockAxis)\n\t\t\treturn;\n\n\t\tDirection vaultFacing = Direction.fromAxisAndDirection(vaultBlockAxis, AxisDirection.POSITIVE);\n\t\tBlockPos startPos = face == vaultFacing.getOpposite() ? controllerBE.getBlockPos()\n\t\t\t.relative(vaultFacing.getOpposite())\n\t\t\t: controllerBE.getBlockPos()\n\t\t\t\t.relative(vaultFacing, controllerBE.length);\n\n\t\tif (VecHelper.getCoordinate(startPos, vaultBlockAxis) != VecHelper.getCoordinate(pos, vaultBlockAxis))\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\t\t\t\tif (GreenContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!blockState.getMaterial()\n\t\t\t\t\t.isReplaceable())\n\t\t\t\t\treturn;\n\t\t\t\ttanksToPlace++;\n\t\t\t}\n\t\t}\n\n\t\tif (!player.isCreative() && stack.getCount() < tanksToPlace)\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\n\n\t\t\t\tif (GreenContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\n\n\t\t\t\tBlockPlaceContext context = BlockPlaceContext.at(ctx, offsetPos, face);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.putBoolean(\"SilenceVaultSound\", true);\n\t\t\t\tsuper.place(context);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.remove(\"SilenceVaultSound\");\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "MmbCrushingWheelBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/crushing_wheels/MmbCrushingWheelBlock.java", "snippet": "public class MmbCrushingWheelBlock extends CrushingWheelBlock {\n\n\tpublic MmbCrushingWheelBlock(Properties properties) {\n\t\tsuper(properties);\n\t}\n\n\n\t@Override\n\tpublic void onRemove(BlockState state, Level worldIn, BlockPos pos, BlockState newState, boolean isMoving) {\n\t\tfor (Direction d : Iterate.directions) {\n\t\t\tif (d.getAxis() == state.getValue(AXIS))\n\t\t\t\tcontinue;\n\t\t\tif (MmbBlocks.MMB_CRUSHING_WHEEL_CONTROLLER.has(worldIn.getBlockState(pos.relative(d))))\n\t\t\t\tworldIn.removeBlock(pos.relative(d), isMoving);\n\t\t\tif (AllBlocks.CRUSHING_WHEEL_CONTROLLER.has(worldIn.getBlockState(pos.relative(d))))\n\t\t\t\tworldIn.removeBlock(pos.relative(d), isMoving);\n\t\t}\n\n\t\tsuper.onRemove(state, worldIn, pos, newState, isMoving);\n\t}\n\n\n\tpublic void updateControllers(BlockState state, Level world, BlockPos pos, Direction side) {\n\t\tif (side.getAxis() == state.getValue(AXIS))\n\t\t\treturn;\n\t\tif (world == null)\n\t\t\treturn;\n\n\t\tBlockPos controllerPos = pos.relative(side);\n\t\tBlockPos otherWheelPos = pos.relative(side, 2);\n\n\t\tboolean controllerExists =\n\t\t\t\tMmbBlocks.MMB_CRUSHING_WHEEL_CONTROLLER.has(world.getBlockState(controllerPos));\n\t\tboolean controllerIsValid = controllerExists && world.getBlockState(controllerPos)\n\t\t\t\t.getValue(VALID);\n\t\tDirection controllerOldDirection = controllerExists ? world.getBlockState(controllerPos)\n\t\t\t\t.getValue(CrushingWheelControllerBlock.FACING) : null;\n\n\t\tboolean controllerShouldExist = false;\n\t\tboolean controllerShouldBeValid = false;\n\t\tDirection controllerNewDirection = Direction.DOWN;\n\n\t\tBlockState otherState = world.getBlockState(otherWheelPos);\n\t\tif (\n\t\t\t\tAllBlocks.CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.GRANITE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.DIORITE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.LIMESTONE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.OCHRUM_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.SCORCHIA_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.SCORIA_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.TUFF_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.VERIDIUM_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.DRIPSTONE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.DEEPSLATE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.CRIMSITE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.CALCITE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.ASURINE_CRUSHING_WHEEL.has(otherState)\n\n\t\t) {\n\t\t\tcontrollerShouldExist = true;\n\n\t\t\tCrushingWheelBlockEntity be = getBlockEntity(world, pos);\n\t\t\tCrushingWheelBlockEntity otherBE = getBlockEntity(world, otherWheelPos);\n\n\t\t\tif (be != null && otherBE != null && (be.getSpeed() > 0) != (otherBE.getSpeed() > 0)\n\t\t\t\t\t&& be.getSpeed() != 0) {\n\t\t\t\tAxis wheelAxis = state.getValue(AXIS);\n\t\t\t\tAxis sideAxis = side.getAxis();\n\t\t\t\tint controllerADO = Math.round(Math.signum(be.getSpeed())) * side.getAxisDirection()\n\t\t\t\t\t\t.getStep();\n\t\t\t\tVec3 controllerDirVec = new Vec3(wheelAxis == Axis.X ? 1 : 0, wheelAxis == Axis.Y ? 1 : 0,\n\t\t\t\t\t\twheelAxis == Axis.Z ? 1 : 0).cross(\n\t\t\t\t\t\tnew Vec3(sideAxis == Axis.X ? 1 : 0, sideAxis == Axis.Y ? 1 : 0, sideAxis == Axis.Z ? 1 : 0));\n\n\t\t\t\tcontrollerNewDirection = Direction.getNearest(controllerDirVec.x * controllerADO,\n\t\t\t\t\t\tcontrollerDirVec.y * controllerADO, controllerDirVec.z * controllerADO);\n\n\t\t\t\tcontrollerShouldBeValid = true;\n\t\t\t}\n\t\t\tif (otherState.getValue(AXIS) != state.getValue(AXIS))\n\t\t\t\tcontrollerShouldExist = false;\n\t\t}\n\n\t\tif (!controllerShouldExist) {\n\t\t\tif (controllerExists)\n\t\t\t\tworld.setBlockAndUpdate(controllerPos, Blocks.AIR.defaultBlockState());\n\t\t\treturn;\n\t\t}\n\n\t\tif (!controllerExists) {\n\t\t\tif (!world.getBlockState(controllerPos)\n\t\t\t\t\t.getMaterial()\n\t\t\t\t\t.isReplaceable())\n\t\t\t\treturn;\n\t\t\tworld.setBlockAndUpdate(controllerPos, MmbBlocks.MMB_CRUSHING_WHEEL_CONTROLLER.getDefaultState()\n\t\t\t\t\t.setValue(VALID, controllerShouldBeValid)\n\t\t\t\t\t.setValue(CrushingWheelControllerBlock.FACING, controllerNewDirection));\n\t\t} else if (controllerIsValid != controllerShouldBeValid || controllerOldDirection != controllerNewDirection) {\n\t\t\tworld.setBlockAndUpdate(controllerPos, world.getBlockState(controllerPos)\n\t\t\t\t\t.setValue(VALID, controllerShouldBeValid)\n\t\t\t\t\t.setValue(CrushingWheelControllerBlock.FACING, controllerNewDirection));\n\t\t}\n\n\t\t( MmbBlocks.MMB_CRUSHING_WHEEL_CONTROLLER.get())\n\t\t\t\t.updateSpeed(world.getBlockState(controllerPos), world, controllerPos);\n\n\t}\n\n\n\t@Override\n\tpublic boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) {\n\t\tfor (Direction direction : Iterate.directions) {\n\t\t\tBlockPos neighbourPos = pos.relative(direction);\n\t\t\tBlockState neighbourState = worldIn.getBlockState(neighbourPos);\n\t\t\tAxis stateAxis = state.getValue(AXIS);\n\t\t\tif (MmbBlocks.MMB_CRUSHING_WHEEL_CONTROLLER.has(neighbourState) && direction.getAxis() != stateAxis)\n\t\t\t\treturn false;\n\t\t\tif (AllBlocks.CRUSHING_WHEEL_CONTROLLER.has(neighbourState) && direction.getAxis() != stateAxis)\n\t\t\t\treturn false;\n\t\t\tif (!(worldIn.getBlockState(neighbourPos).getBlock() instanceof CrushingWheelBlock))\n\t\t\t\tcontinue;\n\t\t\tif (neighbourState.getValue(AXIS) != stateAxis || stateAxis != direction.getAxis())\n\t\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic Class<CrushingWheelBlockEntity> getBlockEntityClass() {\n\t\treturn CrushingWheelBlockEntity.class;\n\t}\n\t\n\t@Override\n\tpublic BlockEntityType<? extends CrushingWheelBlockEntity> getBlockEntityType() {\n\t\treturn MmbBlockEntities.MMB_CRUSHING_WHEEL.get();\n\t}\n\n}" }, { "identifier": "MmbCrushingWheelControllerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/crushing_wheels/MmbCrushingWheelControllerBlock.java", "snippet": "public class MmbCrushingWheelControllerBlock extends CrushingWheelControllerBlock {\n\n\tpublic MmbCrushingWheelControllerBlock(Properties p_i48440_1_) {\n\t\tsuper(p_i48440_1_);\n\t}\n\n\n\t@Override\n\tpublic boolean canBeReplaced(BlockState state, BlockPlaceContext useContext) {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean addRunningEffects(BlockState state, Level world, BlockPos pos, Entity entity) {\n\t\treturn true;\n\t}\n\n\t@Override\n\tprotected void createBlockStateDefinition(Builder<Block, BlockState> builder) {\n\t\tsuper.createBlockStateDefinition(builder);\n\t}\n\n\tpublic void entityInside(BlockState state, Level worldIn, BlockPos pos, Entity entityIn) {\n\t\tif (!state.getValue(VALID))\n\t\t\treturn;\n\n\t\tDirection facing = state.getValue(FACING);\n\t\tAxis axis = facing.getAxis();\n\n\t\tcheckEntityForProcessing(worldIn, pos, entityIn);\n\n\t\twithBlockEntityDo(worldIn, pos, be -> {\n\t\t\tif (be.processingEntity == entityIn)\n\n\t\t\t\tentityIn.makeStuckInBlock(state, new Vec3(axis == Axis.X ? (double) 0.05F : 0.25D,\n\t\t\t\t\taxis == Axis.Y ? (double) 0.05F : 0.25D, axis == Axis.Z ? (double) 0.05F : 0.25D));\n\t\t});\n\t}\n\n\tpublic void checkEntityForProcessing(Level worldIn, BlockPos pos, Entity entityIn) {\n\t\tCrushingWheelControllerBlockEntity be = getBlockEntity(worldIn, pos);\n\t\tif (be == null)\n\t\t\treturn;\n\t\tif (be.crushingspeed == 0)\n\t\t\treturn;\n//\t\tif (entityIn instanceof ItemEntity)\n//\t\t\t((ItemEntity) entityIn).setPickUpDelay(10);\n\t\tCompoundTag data = entityIn.getPersistentData();\n\t\tif (data.contains(\"BypassCrushingWheel\")) {\n\t\t\tif (pos.equals(NbtUtils.readBlockPos(data.getCompound(\"BypassCrushingWheel\"))))\n\t\t\t\treturn;\n\t\t}\n\t\tif (be.isOccupied())\n\t\t\treturn;\n\t\tboolean isPlayer = entityIn instanceof Player;\n\t\tif (isPlayer && ((Player) entityIn).isCreative())\n\t\t\treturn;\n\t\tif (isPlayer && entityIn.level.getDifficulty() == Difficulty.PEACEFUL)\n\t\t\treturn;\n\n\t\tbe.startCrushing(entityIn);\n\t}\n\n\t@Override\n\tpublic void updateEntityAfterFallOn(BlockGetter worldIn, Entity entityIn) {\n\t\tsuper.updateEntityAfterFallOn(worldIn, entityIn);\n\t\t// Moved to onEntityCollision to allow for omnidirectional input\n\t}\n\n\t@Override\n\tpublic void animateTick(BlockState stateIn, Level worldIn, BlockPos pos, RandomSource rand) {\n\t\tif (!stateIn.getValue(VALID))\n\t\t\treturn;\n\t\tif (rand.nextInt(1) != 0)\n\t\t\treturn;\n\t\tdouble d0 = (double) ((float) pos.getX() + rand.nextFloat());\n\t\tdouble d1 = (double) ((float) pos.getY() + rand.nextFloat());\n\t\tdouble d2 = (double) ((float) pos.getZ() + rand.nextFloat());\n\t\tworldIn.addParticle(ParticleTypes.CRIT, d0, d1, d2, 0.0D, 0.0D, 0.0D);\n\t}\n\n\t@Override\n\tpublic BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn,\n\t\tBlockPos currentPos, BlockPos facingPos) {\n\t\tupdateSpeed(stateIn, worldIn, currentPos);\n\t\treturn stateIn;\n\t}\n\n\tpublic void updateSpeed(BlockState state, LevelAccessor world, BlockPos pos) {\n\t\twithBlockEntityDo(world, pos, be -> {\n\t\t\tif (!state.getValue(VALID)) {\n\t\t\t\tif (be.crushingspeed != 0) {\n\t\t\t\t\tbe.crushingspeed = 0;\n\t\t\t\t\tbe.sendData();\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (Direction d : Iterate.directions) {\n\t\t\t\tBlockState neighbour = world.getBlockState(pos.relative(d));\n\t\t\t\tif (\n\t\t\t\t\t\t!MmbBlocks.GRANITE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t\t\t!MmbBlocks.DIORITE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t\t\t\t\t!AllBlocks.CRUSHING_WHEEL.has(neighbour)&&\n\n\t\t\t\t\t\t\t\t!MmbBlocks.LIMESTONE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.OCHRUM_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.SCORCHIA_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.SCORIA_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.TUFF_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.VERIDIUM_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.DRIPSTONE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.DEEPSLATE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.CRIMSITE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.CALCITE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.ASURINE_CRUSHING_WHEEL.has(neighbour))\n\t\t\t\t\tcontinue;\n\t\t\t\tif (neighbour.getValue(BlockStateProperties.AXIS) == d.getAxis())\n\t\t\t\t\tcontinue;\n\t\t\t\tBlockEntity adjBE = world.getBlockEntity(pos.relative(d));\n\t\t\t\tif (!(adjBE instanceof CrushingWheelBlockEntity cwbe))\n\t\t\t\t\tcontinue;\n\t\t\t\tbe.crushingspeed = Math.abs(cwbe.getSpeed() / 50f);\n\t\t\t\tbe.sendData();\n\n\t\t\t\tcwbe.award(AllAdvancements.CRUSHING_WHEEL);\n\t\t\t\tif (cwbe.getSpeed() > 255)\n\t\t\t\t\tcwbe.award(AllAdvancements.CRUSHER_MAXED);\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tpublic VoxelShape getCollisionShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) {\n\t\tVoxelShape standardShape = AllShapes.CRUSHING_WHEEL_CONTROLLER_COLLISION.get(state.getValue(FACING));\n\n\t\tif (!state.getValue(VALID))\n\t\t\treturn standardShape;\n\t\tif (!(context instanceof EntityCollisionContext))\n\t\t\treturn standardShape;\n\t\tEntity entity = ((EntityCollisionContext) context).getEntity();\n\t\tif (entity == null)\n\t\t\treturn standardShape;\n\n\t\tCompoundTag data = entity.getPersistentData();\n\t\tif (data.contains(\"BypassCrushingWheel\"))\n\t\t\tif (pos.equals(NbtUtils.readBlockPos(data.getCompound(\"BypassCrushingWheel\"))))\n\t\t\t\tif (state.getValue(FACING) != Direction.UP) // Allow output items to land on top of the block rather\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// than falling back through.\n\t\t\t\t\treturn Shapes.empty();\n\n\t\tCrushingWheelControllerBlockEntity be = getBlockEntity(worldIn, pos);\n\t\tif (be != null && be.processingEntity == entity)\n\t\t\treturn Shapes.empty();\n\n\t\treturn standardShape;\n\t}\n\n\t@Override\n\tpublic void onRemove(BlockState state, Level worldIn, BlockPos pos, BlockState newState, boolean isMoving) {\n\t\tif (!state.hasBlockEntity() || state.getBlock() == newState.getBlock())\n\t\t\treturn;\n\n\t\twithBlockEntityDo(worldIn, pos, be -> ItemHelper.dropContents(worldIn, pos, be.inventory));\n\t\tworldIn.removeBlockEntity(pos);\n\t}\n\n\t@Override\n\tpublic Class<CrushingWheelControllerBlockEntity> getBlockEntityClass() {\n\t\treturn CrushingWheelControllerBlockEntity.class;\n\t}\n\n\t@Override\n\tpublic BlockEntityType<? extends CrushingWheelControllerBlockEntity> getBlockEntityType() {\n\t\treturn MmbBlockEntities.MMB_CRUSHING_WHEEL_CONTROLLER.get();\n\t}\n\n\t@Override\n\tpublic boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) {\n\t\treturn false;\n\t}\n\n}" }, { "identifier": "DiagonalGirderBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/diagonal_girder/DiagonalGirderBlock.java", "snippet": "@SuppressWarnings({\"unused\",\"deprecation\"})\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class DiagonalGirderBlock extends DirectionalBlock implements SimpleWaterloggedBlock, IWrenchable {\n\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n public static final BooleanProperty FACING_UP = BooleanProperty.create(\"facing_up\");\n public DiagonalGirderBlock(Properties p_54120_) {\n super(p_54120_);\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE).setValue(FACING, Direction.NORTH).setValue(FACING_UP, false));\n }\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_55125_) {\n p_55125_.add(WATERLOGGED,FACING, FACING_UP);\n }\n\n public static final VoxelShape SHAPE_EAST = eShape();\n public static final VoxelShape SHAPE_WEST = wShape();\n public static final VoxelShape SHAPE_NORTH = nShape();\n public static final VoxelShape SHAPE_SOUTH = sShape();\n\n public static final VoxelShape SHAPE_UP_EAST = ueShape();\n public static final VoxelShape SHAPE_UP_WEST = uwShape();\n public static final VoxelShape SHAPE_UP_NORTH = unShape();\n public static final VoxelShape SHAPE_UP_SOUTH = usShape();\n\n public static VoxelShape nShape(){\n return Shapes.or(\n Block.box(3, 3, 0, 13, 13, 5),\n Block.box(3, 0, 3, 13, 5, 13),\n Block.box(4, 5, 5, 12, 12, 12)\n );\n }\n public static VoxelShape eShape(){\n return Shapes.or(\n Block.box(11, 3, 3, 16, 13, 13),\n Block.box(3, 0, 3, 13, 5, 13),\n Block.box(4, 5, 4, 11, 12, 12)\n );\n }\n\n public static VoxelShape sShape(){\n return Shapes.or(\n Block.box(3, 3, 11, 13, 13, 16),\n Block.box(3, 0, 3, 13, 5, 13),\n Block.box(4, 5, 4, 12, 12, 11)\n );\n }\n\n public static VoxelShape wShape(){\n return Shapes.or(\n Block.box(0, 3, 3, 5, 13, 13),\n Block.box(3, 0, 3, 13, 5, 13),\n Block.box(5, 5, 4, 12, 12, 12)\n );\n }\n\n public static VoxelShape unShape(){\n return Shapes.or(\n Block.box(3, 3, 0, 13, 13, 5),\n Block.box(3, 11, 3, 13, 16, 13),\n Block.box(4, 4, 5, 12, 11, 12)\n );\n }\n public static VoxelShape ueShape(){\n return Shapes.or(\n Block.box(11, 3, 3, 16, 13, 13),\n Block.box(3, 11, 3, 13, 16, 13),\n Block.box(4, 4, 4, 11, 11, 12)\n );\n }\n\n public static VoxelShape usShape(){\n return Shapes.or(\n Block.box(3, 3, 11, 13, 13, 16),\n Block.box(3, 11, 3, 13, 16, 13),\n Block.box(4, 4, 4, 12, 11, 11)\n );\n }\n\n public static VoxelShape uwShape(){\n return Shapes.or(\n Block.box(0, 3, 3, 5, 13, 13),\n Block.box(3, 11, 3, 13, 16, 13),\n Block.box(5, 4, 4, 12, 11, 12)\n );\n }\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n public VoxelShape getShape(BlockState p_54561_, BlockGetter p_54562_, BlockPos p_54563_, CollisionContext p_54564_) {\n if (!p_54561_.getValue(FACING_UP)) {\n return switch (p_54561_.getValue(FACING)) {\n case NORTH, UP, DOWN -> SHAPE_NORTH;\n case SOUTH -> SHAPE_SOUTH;\n case EAST -> SHAPE_EAST;\n case WEST -> SHAPE_WEST;\n };\n }\n if (p_54561_.getValue(FACING_UP)) {\n return switch (p_54561_.getValue(FACING)) {\n case NORTH, UP, DOWN -> SHAPE_UP_NORTH;\n case SOUTH -> SHAPE_UP_SOUTH;\n case EAST -> SHAPE_UP_EAST;\n case WEST -> SHAPE_UP_WEST;\n };\n }\n return SHAPE_NORTH;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n InteractionResult onWrenched = IWrenchable.super.onWrenched(state, context);\n if (!onWrenched.consumesAction())\n return onWrenched;\n\n context.getLevel().setBlock(context.getClickedPos(),state.setValue(FACING_UP,!state.getValue(FACING_UP)),2);\n\n playRotateSound(context.getLevel(), context.getClickedPos());\n return onWrenched;\n }\n\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n FluidState fluidstate = context.getLevel().getFluidState(context.getClickedPos());\n boolean flag = fluidstate.getType() == Fluids.WATER;\n Direction facing = Objects.requireNonNull(context.getPlayer()).getDirection();\n Direction clickedFace = context.getClickedFace();\n\n if (context.getPlayer() != null && context.getPlayer().isShiftKeyDown()) {\n if (clickedFace == Direction.DOWN)\n return defaultBlockState().setValue(FACING, facing.getOpposite()).setValue(FACING_UP,true).setValue(WATERLOGGED, flag);\n else\n return defaultBlockState().setValue(FACING, facing.getOpposite()).setValue(FACING_UP,false).setValue(WATERLOGGED, flag);\n }\n if (clickedFace == Direction.DOWN)\n return defaultBlockState().setValue(FACING, facing).setValue(FACING_UP,true).setValue(WATERLOGGED, flag);\n\n\n return defaultBlockState().setValue(FACING, facing).setValue(FACING_UP,false).setValue(WATERLOGGED, flag);\n }\n}" }, { "identifier": "DiagonalGirderGenerator", "path": "src/main/java/com/mangomilk/design_decor/blocks/diagonal_girder/DiagonalGirderGenerator.java", "snippet": "public class DiagonalGirderGenerator extends SpecialBlockStateGen {\n\n @Override\n protected int getXRotation(BlockState state) {\n return 0;\n }\n\n @Override\n protected int getYRotation(BlockState state) {\n return switch (state.getValue(DiagonalGirderBlock.FACING)) {\n case NORTH -> 270;\n case SOUTH -> 90;\n case WEST -> 180;\n case EAST -> 0;\n case DOWN -> 0;\n case UP -> 0;\n };\n }\n\n @Override\n public <T extends Block> ModelFile getModel(DataGenContext<Block, T> ctx, RegistrateBlockstateProvider prov,\n BlockState state) {\n // return AssetLookup.forPowered(ctx, prov)\n // .apply(state);\n\n return state.getValue(DiagonalGirderBlock.FACING_UP) ? partialBaseModel(ctx, prov, \"up\")\n : partialBaseModel(ctx, prov);\n }\n\n}" }, { "identifier": "FloodlightBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/floodlight/FloodlightBlock.java", "snippet": "@SuppressWarnings({\"unused\",\"deprecation\"})\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class FloodlightBlock extends DirectionalBlock implements SimpleWaterloggedBlock, IWrenchable {\n\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n public static final BooleanProperty TURNED_ON = BooleanProperty.create(\"turned_on\");\n public static final BooleanProperty WRENCHED = BooleanProperty.create(\"wrenched\");\n\n public static final VoxelShape SHAPE_DOWN = Block.box(3.0D, 8.0D, 3.0D, 13.0D, 16.0D, 13.0D);\n public static final VoxelShape SHAPE_UP = Block.box(3.0D, 0.0D, 3.0D, 13.0D, 8.0D, 13.0D);\n\n public static final VoxelShape SHAPE_EAST = Block.box(0.0D, 3.0D, 3.0D, 8.0D, 13.0D, 13.0D);\n public static final VoxelShape SHAPE_WEST = Block.box(8.0D, 3.0D, 3.0D, 16.0D, 13.0D, 13.0D);\n public static final VoxelShape SHAPE_NORTH = Block.box(3.0D, 3.0D, 8.0D, 13.0D, 13.0D, 16.0D);\n public static final VoxelShape SHAPE_SOUTH = Block.box(3.0D, 3.0D, 0.0D, 13.0D, 13.0D, 8.0D);\n public FloodlightBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE).setValue(FACING, Direction.UP).setValue(TURNED_ON, false).setValue(WRENCHED, false));\n }\n\n public VoxelShape getShape(BlockState p_54561_, BlockGetter p_54562_, BlockPos p_54563_, CollisionContext p_54564_) {\n return switch (p_54561_.getValue(FACING)) {\n case NORTH -> SHAPE_NORTH;\n case SOUTH -> SHAPE_SOUTH;\n case EAST -> SHAPE_EAST;\n case WEST -> SHAPE_WEST;\n case UP -> SHAPE_UP;\n case DOWN -> SHAPE_DOWN;\n default -> SHAPE_NORTH;\n };\n }\n\n @Override\n public void neighborChanged(BlockState pState, Level pLevel, BlockPos pPos, Block pBlock, BlockPos pFromPos,\n boolean pIsMoving) {\n if (pLevel.isClientSide)\n return;\n boolean beenWrenched = pState.getValue(WRENCHED);\n\n if (!beenWrenched && pLevel.hasNeighborSignal(pPos)) {\n pLevel.setBlock(pPos,pState.setValue(TURNED_ON,!pState.getValue(TURNED_ON)), 2);\n }\n }\n\n public void tick(BlockState p_221937_, ServerLevel p_221938_, BlockPos p_221939_, RandomSource p_221940_) {\n if (p_221937_.getValue(TURNED_ON) && p_221938_.hasNeighborSignal(p_221939_) != p_221937_.getValue(WRENCHED)) {\n p_221938_.setBlock(p_221939_, p_221937_.setValue(TURNED_ON, false), 2);\n }\n }\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n InteractionResult onWrenched = IWrenchable.super.onWrenched(state, context);\n if (!onWrenched.consumesAction())\n return onWrenched;\n boolean isOn = state.getValue(TURNED_ON);\n\n context.getLevel().setBlock(context.getClickedPos(),state.setValue(TURNED_ON,!state.getValue(TURNED_ON)).setValue(WRENCHED,!state.getValue(WRENCHED)),2);\n\n playRotateSound(context.getLevel(), context.getClickedPos());\n\n if (!isOn) {\n context.getLevel().playLocalSound(context.getClickedPos().getX(), context.getClickedPos().getY(), context.getClickedPos().getZ(),\n DecoSoundEvents.FLOODLIGHT_ON.get(), SoundSource.BLOCKS, 0.25F, Create.RANDOM.nextFloat() * 0.2F + 1.6F, false);\n }\n if (isOn) {\n context.getLevel().playLocalSound(context.getClickedPos().getX(), context.getClickedPos().getY(), context.getClickedPos().getZ(),\n DecoSoundEvents.FLOODLIGHT_OFF.get(), SoundSource.BLOCKS, 0.25F, Create.RANDOM.nextFloat() * 0.2F + 0.8F, false);\n }\n return onWrenched;\n }\n\n\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n\n @Override\n public boolean isPathfindable(BlockState p_51456_, BlockGetter p_51457_, BlockPos p_51458_, PathComputationType p_51459_) {\n return false;\n }\n\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_55125_) {\n p_55125_.add(WATERLOGGED,FACING,TURNED_ON,WRENCHED);\n }\n\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_58126_) {\n FluidState fluidstate = p_58126_.getLevel().getFluidState(p_58126_.getClickedPos());\n boolean flag = fluidstate.getType() == Fluids.WATER;\n\n BlockState blockstate = this.defaultBlockState();\n LevelReader levelreader = p_58126_.getLevel();\n BlockPos blockpos = p_58126_.getClickedPos();\n Direction[] adirection = p_58126_.getNearestLookingDirections();\n\n for(Direction direction : adirection) {\n Direction direction1 = direction.getOpposite();\n blockstate = blockstate.setValue(FACING, direction1).setValue(WATERLOGGED, flag);\n return blockstate;\n }\n\n return Objects.requireNonNull(super.getStateForPlacement(p_58126_)).setValue(WATERLOGGED, flag);\n }\n\n\n public void FloodlightSoundOff(Level p_49713_, BlockPos p_49714_, @Nullable Direction p_49715_) {\n this.FloodlightSoundOff((Entity) null, p_49713_, p_49714_, p_49715_);\n }\n\n public boolean FloodlightSoundOff(@Nullable Entity p_152189_, Level p_152190_, BlockPos p_152191_, @Nullable Direction p_152192_) {\n BlockEntity blockentity = p_152190_.getBlockEntity(p_152191_);\n if (!p_152190_.isClientSide) {\n\n p_152190_.playSound((Player)null, p_152191_, DecoSoundEvents.FLOODLIGHT_OFF.get(), SoundSource.BLOCKS, 0.25F, Create.RANDOM.nextFloat() * 0.2F + 0.8F);\n p_152190_.gameEvent(p_152189_, GameEvent.BLOCK_CHANGE, p_152191_);\n return true;\n } else {\n return false;\n }\n }\n\n public void FloodlightSoundOn(Level p_49713_, BlockPos p_49714_, @Nullable Direction p_49715_) {\n this.FloodlightSoundOn((Entity) null, p_49713_, p_49714_, p_49715_);\n }\n\n public boolean FloodlightSoundOn(@Nullable Entity p_152189_, Level p_152190_, BlockPos p_152191_, @Nullable Direction p_152192_) {\n BlockEntity blockentity = p_152190_.getBlockEntity(p_152191_);\n if (!p_152190_.isClientSide) {\n\n p_152190_.playSound((Player)null, p_152191_, DecoSoundEvents.FLOODLIGHT_ON.get(), SoundSource.BLOCKS, 0.25F, Create.RANDOM.nextFloat() * 0.2F + 1.6F);\n p_152190_.gameEvent(p_152189_, GameEvent.BLOCK_CHANGE, p_152191_);\n return true;\n } else {\n return false;\n }\n }\n}" }, { "identifier": "FloodlightGenerator", "path": "src/main/java/com/mangomilk/design_decor/blocks/floodlight/FloodlightGenerator.java", "snippet": "public class FloodlightGenerator extends SpecialBlockStateGen {\n public FloodlightGenerator() {\n }\n\n protected int getXRotation(BlockState state) {\n short value;\n switch ((Direction)state.getValue(FloodlightBlock.FACING)) {\n case NORTH:\n value = 0;\n break;\n case SOUTH:\n value = 0;\n break;\n case WEST:\n value = 0;\n break;\n case EAST:\n value = 0;\n break;\n case DOWN:\n value = 90;\n break;\n case UP:\n value = 270;\n break;\n default:\n throw new IncompatibleClassChangeError();\n }\n\n return value;\n }\n\n protected int getYRotation(BlockState state) {\n short value;\n switch ((Direction)state.getValue(FloodlightBlock.FACING)) {\n case NORTH:\n value = 0;\n break;\n case SOUTH:\n value = 180;\n break;\n case WEST:\n value = 270;\n break;\n case EAST:\n value = 90;\n break;\n case DOWN:\n value = 0;\n break;\n case UP:\n value = 0;\n break;\n default:\n throw new IncompatibleClassChangeError();\n }\n\n return value;\n }\n\n public <T extends Block> ModelFile getModel(DataGenContext<Block, T> ctx, RegistrateBlockstateProvider prov, BlockState state) {\n return (Boolean)state.getValue(FloodlightBlock.TURNED_ON) ? AssetLookup.partialBaseModel(ctx, prov, new String[]{\"on\"}) : AssetLookup.partialBaseModel(ctx, prov, new String[0]);\n }\n}" }, { "identifier": "GasTankBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/gas_tank/GasTankBlock.java", "snippet": "public class GasTankBlock extends Block implements SimpleWaterloggedBlock, IWrenchable, IBE<GasTankBlockEntity> {\n\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n\n public GasTankBlock(Properties p_49795_) {\n super(p_49795_);\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE));\n }\n\n public VoxelShape getShape(BlockState p_54561_, BlockGetter p_54562_, BlockPos p_54563_, CollisionContext p_54564_) {\n return Block.box(1, 0, 1, 15, 16, 15);\n }\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_55125_) {\n p_55125_.add(WATERLOGGED);\n }\n @Override\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_152019_) {\n LevelAccessor levelaccessor = p_152019_.getLevel();\n BlockPos blockpos = p_152019_.getClickedPos();\n return this.defaultBlockState().setValue(WATERLOGGED, levelaccessor.getFluidState(blockpos).getType() == Fluids.WATER);\n }\n\n @Override\n public Class<GasTankBlockEntity> getBlockEntityClass() {\n return GasTankBlockEntity.class;\n }\n\n @Override\n public BlockEntityType<? extends GasTankBlockEntity> getBlockEntityType() {\n return MmbBlockEntities.GAS_TANK.get();\n }\n}" }, { "identifier": "ConnectedTintedGlassBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/glass/ConnectedTintedGlassBlock.java", "snippet": "public class ConnectedTintedGlassBlock extends TintedGlassBlock {\n public ConnectedTintedGlassBlock(Properties p_154822_) {\n super(p_154822_);\n }\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public boolean skipRendering(BlockState state, BlockState adjacentBlockState, Direction side) {\n return adjacentBlockState.getBlock() instanceof ConnectedTintedGlassBlock || super.skipRendering(state, adjacentBlockState, side);\n }\n\n @Override\n public boolean shouldDisplayFluidOverlay(BlockState state, BlockAndTintGetter world, BlockPos pos, FluidState fluidState) {\n return true;\n }\n}" }, { "identifier": "IndustrialGearBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/industrial_gear/IndustrialGearBlock.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class IndustrialGearBlock extends ShaftBlock implements ICogWheel, EncasableBlock {\n boolean isLarge;\n\n VoxelShape largeY = Shapes.join(Block.box(-2, 2, -2, 18, 14, 18),\n Block.box(5, 0, 5, 11, 16, 11), BooleanOp.OR);\n VoxelShape smallY = Shapes.join(Block.box(1, 2, 1, 15, 14, 15),\n Block.box(5, 0, 5, 11, 16, 11), BooleanOp.OR);\n\n VoxelShape largeX = Shapes.join(Block.box(2, -2, -2, 14, 18, 18),\n Block.box(0, 5, 5, 16, 11, 11), BooleanOp.OR);\n VoxelShape smallX = Shapes.join(Block.box(2, 1, 1, 14, 15, 15),\n Block.box(0, 5, 5, 16, 11, 11), BooleanOp.OR);\n\n VoxelShape largeZ = Shapes.join(Block.box(-2, -2, 2, 18, 18, 14),\n Block.box(5, 5, 0, 11, 11, 16), BooleanOp.OR);\n VoxelShape smallZ = Shapes.join(Block.box(1, 1, 2, 15, 15, 14),\n Block.box(5, 5, 0, 11, 11, 16), BooleanOp.OR);\n\n protected IndustrialGearBlock(boolean large, Properties properties) {\n super(properties);\n isLarge = large;\n }\n\n public static IndustrialGearBlock small(Properties properties) {\n return new IndustrialGearBlock(false, properties);\n }\n\n public static IndustrialGearBlock large(Properties properties) {\n return new IndustrialGearBlock(true, properties);\n }\n\n @Override\n public boolean isLargeCog() {\n return isLarge;\n }\n\n @Override\n public boolean isSmallCog() {\n return !isLarge;\n }\n\n @Override\n public void fillItemCategory(CreativeModeTab pTab, NonNullList<ItemStack> pItems) {\n super.fillItemCategory(pTab, pItems);\n MmbBlocks.LARGE_COGWHEEL.is(this);\n }\n\n @Override\n public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) {\n if (state.getValue(AXIS) == Direction.Axis.X) {\n return (isLarge ? largeX : smallX);\n }\n if (state.getValue(AXIS) == Direction.Axis.Z) {\n return (isLarge ? largeZ : smallZ);\n }\n state.getValue(AXIS);\n return (isLarge ? largeY : smallY);\n }\n\n @Override\n public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) {\n return isValidCogwheelPosition(ICogWheel.isLargeCog(state), worldIn, pos, state.getValue(AXIS));\n }\n\n @Override\n public void setPlacedBy(Level worldIn, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {\n super.setPlacedBy(worldIn, pos, state, placer, stack);\n if (placer instanceof Player player)\n triggerShiftingGearsAdvancement(worldIn, pos, state, player);\n }\n\n protected void triggerShiftingGearsAdvancement(Level world, BlockPos pos, BlockState state, Player player) {\n if (world.isClientSide || player == null)\n return;\n\n Direction.Axis axis = state.getValue(IndustrialGearBlock.AXIS);\n for (Direction.Axis perpendicular1 : Iterate.axes) {\n if (perpendicular1 == axis)\n continue;\n\n Direction d1 = Direction.get(Direction.AxisDirection.POSITIVE, perpendicular1);\n for (Direction.Axis perpendicular2 : Iterate.axes) {\n if (perpendicular1 == perpendicular2)\n continue;\n if (axis == perpendicular2)\n continue;\n\n Direction d2 = Direction.get(Direction.AxisDirection.POSITIVE, perpendicular2);\n for (int offset1 : Iterate.positiveAndNegative) {\n for (int offset2 : Iterate.positiveAndNegative) {\n BlockPos connectedPos = pos.relative(d1, offset1)\n .relative(d2, offset2);\n BlockState blockState = world.getBlockState(connectedPos);\n if (!(blockState.getBlock() instanceof IndustrialGearBlock))\n continue;\n if (blockState.getValue(IndustrialGearBlock.AXIS) != axis)\n continue;\n if (ICogWheel.isLargeCog(blockState) == isLarge)\n continue;\n\n AllAdvancements.COGS.awardTo(player);\n }\n }\n }\n }\n }\n\n @Override\n public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand,\n BlockHitResult ray) {\n if (player.isShiftKeyDown() || !player.mayBuild())\n return InteractionResult.PASS;\n\n ItemStack heldItem = player.getItemInHand(hand);\n InteractionResult result = tryEncase(state, world, pos, heldItem, player, hand, ray);\n if (result.consumesAction())\n return result;\n\n return InteractionResult.PASS;\n }\n\n public static boolean isValidCogwheelPosition(boolean large, LevelReader worldIn, BlockPos pos, Direction.Axis cogAxis) {\n for (Direction facing : Iterate.directions) {\n if (facing.getAxis() == cogAxis)\n continue;\n\n BlockPos offsetPos = pos.relative(facing);\n BlockState blockState = worldIn.getBlockState(offsetPos);\n if (blockState.hasProperty(AXIS) && facing.getAxis() == blockState.getValue(AXIS))\n continue;\n\n if (ICogWheel.isLargeCog(blockState) || large && ICogWheel.isSmallCog(blockState))\n return false;\n }\n return true;\n }\n\n protected Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n if (context.getPlayer() != null && context.getPlayer()\n .isShiftKeyDown())\n return context.getClickedFace()\n .getAxis();\n\n Level world = context.getLevel();\n BlockState stateBelow = world.getBlockState(context.getClickedPos()\n .below());\n\n BlockPos placedOnPos = context.getClickedPos()\n .relative(context.getClickedFace()\n .getOpposite());\n BlockState placedAgainst = world.getBlockState(placedOnPos);\n\n Block block = placedAgainst.getBlock();\n if (ICogWheel.isSmallCog(placedAgainst))\n return ((IRotate) block).getRotationAxis(placedAgainst);\n\n Direction.Axis preferredAxis = getPreferredAxis(context);\n return preferredAxis != null ? preferredAxis\n : context.getClickedFace()\n .getAxis();\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n boolean shouldWaterlog = context.getLevel()\n .getFluidState(context.getClickedPos())\n .getType() == Fluids.WATER;\n return this.defaultBlockState()\n .setValue(AXIS, getAxisForPlacement(context))\n .setValue(BlockStateProperties.WATERLOGGED, shouldWaterlog);\n }\n\n @Override\n public float getParticleTargetRadius() {\n return isLargeCog() ? 1.125f : .65f;\n }\n\n @Override\n public float getParticleInitialRadius() {\n return isLargeCog() ? 1f : .75f;\n }\n\n @Override\n public boolean isDedicatedCogWheel() {\n return true;\n }\n\n}" }, { "identifier": "IndustrialGearBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/industrial_gear/IndustrialGearBlockItem.java", "snippet": "public class IndustrialGearBlockItem extends BlockItem {\n\n boolean large;\n\n private final int placementHelperId;\n private final int integratedCogHelperId;\n\n public IndustrialGearBlockItem(IndustrialGearBlock block, Properties builder) {\n super(block, builder);\n large = block.isLarge;\n\n placementHelperId = PlacementHelpers.register(large ? new IndustrialGearBlockItem.LargeCogHelper() : new IndustrialGearBlockItem.SmallCogHelper());\n integratedCogHelperId =\n PlacementHelpers.register(large ? new IndustrialGearBlockItem.IntegratedLargeCogHelper() : new IndustrialGearBlockItem.IntegratedSmallCogHelper());\n }\n\n @Override\n public InteractionResult onItemUseFirst(ItemStack stack, UseOnContext context) {\n Level world = context.getLevel();\n BlockPos pos = context.getClickedPos();\n BlockState state = world.getBlockState(pos);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n Player player = context.getPlayer();\n BlockHitResult ray = new BlockHitResult(context.getClickLocation(), context.getClickedFace(), pos, true);\n if (helper.matchesState(state) && player != null && !player.isShiftKeyDown()) {\n return helper.getOffset(player, world, state, pos, ray)\n .placeInWorld(world, this, player, context.getHand(), ray);\n }\n\n if (integratedCogHelperId != -1) {\n helper = PlacementHelpers.get(integratedCogHelperId);\n\n if (helper.matchesState(state) && player != null && !player.isShiftKeyDown()) {\n return helper.getOffset(player, world, state, pos, ray)\n .placeInWorld(world, this, player, context.getHand(), ray);\n }\n }\n\n return super.onItemUseFirst(stack, context);\n }\n\n @MethodsReturnNonnullByDefault\n private static class SmallCogHelper extends IndustrialGearBlockItem.DiagonalCogHelper {\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return ((Predicate<ItemStack>) ICogWheel::isSmallCogItem).and(ICogWheel::isDedicatedCogItem);\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n if (hitOnShaft(state, ray))\n return PlacementOffset.fail();\n\n if (!ICogWheel.isLargeCog(state)) {\n Direction.Axis axis = ((IRotate) state.getBlock()).getRotationAxis(state);\n List<Direction> directions = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), axis);\n\n for (Direction dir : directions) {\n BlockPos newPos = pos.relative(dir);\n\n if (!IndustrialGearBlock.isValidCogwheelPosition(false, world, newPos, axis))\n continue;\n\n if (!world.getBlockState(newPos)\n .getMaterial()\n .isReplaceable())\n continue;\n\n return PlacementOffset.success(newPos, s -> s.setValue(AXIS, axis));\n\n }\n\n return PlacementOffset.fail();\n }\n\n return super.getOffset(player, world, state, pos, ray);\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class LargeCogHelper extends IndustrialGearBlockItem.DiagonalCogHelper {\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return ((Predicate<ItemStack>) ICogWheel::isLargeCogItem).and(ICogWheel::isDedicatedCogItem);\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n if (hitOnShaft(state, ray))\n return PlacementOffset.fail();\n\n if (ICogWheel.isLargeCog(state)) {\n Direction.Axis axis = ((IRotate) state.getBlock()).getRotationAxis(state);\n Direction side = IPlacementHelper.orderedByDistanceOnlyAxis(pos, ray.getLocation(), axis)\n .get(0);\n List<Direction> directions = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), axis);\n for (Direction dir : directions) {\n BlockPos newPos = pos.relative(dir)\n .relative(side);\n\n if (!IndustrialGearBlock.isValidCogwheelPosition(true, world, newPos, dir.getAxis()))\n continue;\n\n if (!world.getBlockState(newPos)\n .getMaterial()\n .isReplaceable())\n continue;\n\n return PlacementOffset.success(newPos, s -> s.setValue(AXIS, dir.getAxis()));\n }\n\n return PlacementOffset.fail();\n }\n\n return super.getOffset(player, world, state, pos, ray);\n }\n }\n\n @MethodsReturnNonnullByDefault\n public abstract static class DiagonalCogHelper implements IPlacementHelper {\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> ICogWheel.isSmallCog(s) || ICogWheel.isLargeCog(s);\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n // diagonal gears of different size\n Direction.Axis axis = ((IRotate) state.getBlock()).getRotationAxis(state);\n Direction closest = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), axis)\n .get(0);\n List<Direction> directions = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), axis,\n d -> d.getAxis() != closest.getAxis());\n\n for (Direction dir : directions) {\n BlockPos newPos = pos.relative(dir)\n .relative(closest);\n if (!world.getBlockState(newPos)\n .getMaterial()\n .isReplaceable())\n continue;\n\n if (!IndustrialGearBlock.isValidCogwheelPosition(ICogWheel.isLargeCog(state), world, newPos, axis))\n continue;\n\n return PlacementOffset.success(newPos, s -> s.setValue(AXIS, axis));\n }\n\n return PlacementOffset.fail();\n }\n\n protected boolean hitOnShaft(BlockState state, BlockHitResult ray) {\n return AllShapes.SIX_VOXEL_POLE.get(((IRotate) state.getBlock()).getRotationAxis(state))\n .bounds()\n .inflate(0.001)\n .contains(ray.getLocation()\n .subtract(ray.getLocation()\n .align(Iterate.axisSet)));\n }\n }\n\n @MethodsReturnNonnullByDefault\n public static class IntegratedLargeCogHelper implements IPlacementHelper {\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return ((Predicate<ItemStack>) ICogWheel::isLargeCogItem).and(ICogWheel::isDedicatedCogItem);\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> !ICogWheel.isDedicatedCogWheel(s.getBlock()) && ICogWheel.isSmallCog(s);\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n Direction face = ray.getDirection();\n Direction.Axis newAxis;\n\n if (state.hasProperty(HorizontalKineticBlock.HORIZONTAL_FACING))\n newAxis = state.getValue(HorizontalKineticBlock.HORIZONTAL_FACING)\n .getAxis();\n else if (state.hasProperty(DirectionalKineticBlock.FACING))\n newAxis = state.getValue(DirectionalKineticBlock.FACING)\n .getAxis();\n else if (state.hasProperty(RotatedPillarKineticBlock.AXIS))\n newAxis = state.getValue(RotatedPillarKineticBlock.AXIS);\n else\n newAxis = Direction.Axis.Y;\n\n if (face.getAxis() == newAxis)\n return PlacementOffset.fail();\n\n List<Direction> directions =\n IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), face.getAxis(), newAxis);\n\n for (Direction d : directions) {\n BlockPos newPos = pos.relative(face)\n .relative(d);\n\n if (!world.getBlockState(newPos)\n .getMaterial()\n .isReplaceable())\n continue;\n\n if (!IndustrialGearBlock.isValidCogwheelPosition(false, world, newPos, newAxis))\n return PlacementOffset.fail();\n\n return PlacementOffset.success(newPos, s -> s.setValue(IndustrialGearBlock.AXIS, newAxis));\n }\n\n return PlacementOffset.fail();\n }\n\n }\n\n @MethodsReturnNonnullByDefault\n public static class IntegratedSmallCogHelper implements IPlacementHelper {\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return ((Predicate<ItemStack>) ICogWheel::isSmallCogItem).and(ICogWheel::isDedicatedCogItem);\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> !ICogWheel.isDedicatedCogWheel(s.getBlock()) && ICogWheel.isSmallCog(s);\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n Direction face = ray.getDirection();\n Direction.Axis newAxis;\n\n if (state.hasProperty(HorizontalKineticBlock.HORIZONTAL_FACING))\n newAxis = state.getValue(HorizontalKineticBlock.HORIZONTAL_FACING)\n .getAxis();\n else if (state.hasProperty(DirectionalKineticBlock.FACING))\n newAxis = state.getValue(DirectionalKineticBlock.FACING)\n .getAxis();\n else if (state.hasProperty(RotatedPillarKineticBlock.AXIS))\n newAxis = state.getValue(RotatedPillarKineticBlock.AXIS);\n else\n newAxis = Direction.Axis.Y;\n\n if (face.getAxis() == newAxis)\n return PlacementOffset.fail();\n\n List<Direction> directions = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), newAxis);\n\n for (Direction d : directions) {\n BlockPos newPos = pos.relative(d);\n\n if (!world.getBlockState(newPos)\n .getMaterial()\n .isReplaceable())\n continue;\n\n if (!IndustrialGearBlock.isValidCogwheelPosition(false, world, newPos, newAxis))\n return PlacementOffset.fail();\n\n return PlacementOffset.success()\n .at(newPos)\n .withTransform(s -> s.setValue(IndustrialGearBlock.AXIS, newAxis));\n }\n\n return PlacementOffset.fail();\n }\n\n }\n}" }, { "identifier": "AluminumBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/aluminum/AluminumBoilerStructure.java", "snippet": "public class AluminumBoilerStructure extends DirectionalBlock implements IWrenchable {\n public AluminumBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_ALUMINUM_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_ALUMINUM_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_ALUMINUM_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.ALUMINUM_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof AluminumLargeBoilerBlock\n && targetedState.getValue(AluminumLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n AluminumBoilerStructure waterWheelStructuralBlock = MmbBlocks.ALUMINUM_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(AluminumBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n AluminumBoilerStructure waterWheelStructuralBlock = MmbBlocks.ALUMINUM_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(AluminumBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "AluminumLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/aluminum/AluminumLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class AluminumLargeBoilerBlock extends TagDependentDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public AluminumLargeBoilerBlock(Properties properties, TagKey<Item> itemTagKey) {\n super(properties, itemTagKey);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.ALUMINUM_BOILER_STRUCTURAL.getDefaultState()\n .setValue(AluminumBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof AluminumLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof AluminumLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof AluminumLargeBoilerBlock || s.getBlock() instanceof AluminumLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n}" }, { "identifier": "AluminumLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/aluminum/AluminumLargeBoilerBlockItem.java", "snippet": "public class AluminumLargeBoilerBlockItem extends BlockItem {\n public AluminumLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((AluminumLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((AluminumLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "AndesiteBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/andesite/AndesiteBoilerStructure.java", "snippet": "public class AndesiteBoilerStructure extends DirectionalBlock implements IWrenchable {\n public AndesiteBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_ANDESITE_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_ANDESITE_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_ANDESITE_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.ANDESITE_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof AndesiteLargeBoilerBlock\n && targetedState.getValue(AndesiteLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n AndesiteBoilerStructure waterWheelStructuralBlock = MmbBlocks.ANDESITE_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(AndesiteBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n AndesiteBoilerStructure waterWheelStructuralBlock = MmbBlocks.ANDESITE_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(AndesiteBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "AndesiteLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/andesite/AndesiteLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class AndesiteLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public AndesiteLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.ANDESITE_BOILER_STRUCTURAL.getDefaultState()\n .setValue(AndesiteBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof AndesiteLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof AndesiteLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof AndesiteLargeBoilerBlock || s.getBlock() instanceof AndesiteLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "AndesiteLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/andesite/AndesiteLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class AndesiteLargeBoilerBlockItem extends BlockItem {\n\n public AndesiteLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((AndesiteLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((AndesiteLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "BrassBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/brass/BrassBoilerStructure.java", "snippet": "public class BrassBoilerStructure extends DirectionalBlock implements IWrenchable {\n public BrassBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_BRASS_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_BRASS_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_BRASS_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.BRASS_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof BrassLargeBoilerBlock\n && targetedState.getValue(BrassLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new BrassBoilerStructure.RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n BrassBoilerStructure waterWheelStructuralBlock = MmbBlocks.BRASS_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(BrassBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n BrassBoilerStructure waterWheelStructuralBlock = MmbBlocks.BRASS_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(BrassBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "BrassLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/brass/BrassLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class BrassLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public BrassLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.BRASS_BOILER_STRUCTURAL.getDefaultState()\n .setValue(BrassBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof BrassLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof BrassLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof BrassLargeBoilerBlock || s.getBlock() instanceof BrassLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "BrassLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/brass/BrassLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class BrassLargeBoilerBlockItem extends BlockItem {\n\n public BrassLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((BrassLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((BrassLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n\n}" }, { "identifier": "CapitalismBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/capitalism/CapitalismBoilerStructure.java", "snippet": "public class CapitalismBoilerStructure extends DirectionalBlock implements IWrenchable {\n public CapitalismBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_CAPITALISM_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_CAPITALISM_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_CAPITALISM_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.CAPITALISM_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof CapitalismLargeBoilerBlock\n && targetedState.getValue(CapitalismLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new CapitalismBoilerStructure.RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n CapitalismBoilerStructure waterWheelStructuralBlock = MmbBlocks.CAPITALISM_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(CapitalismBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n CapitalismBoilerStructure waterWheelStructuralBlock = MmbBlocks.CAPITALISM_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(CapitalismBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "CapitalismLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/capitalism/CapitalismLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CapitalismLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public CapitalismLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.CAPITALISM_BOILER_STRUCTURAL.getDefaultState()\n .setValue(CapitalismBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof CapitalismLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof CapitalismLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof CapitalismLargeBoilerBlock || s.getBlock() instanceof CapitalismLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "CapitalismLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/capitalism/CapitalismLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CapitalismLargeBoilerBlockItem extends BlockItem {\n\n public CapitalismLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((CapitalismLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((CapitalismLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "CastIronBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/cast_iron/CastIronBoilerStructure.java", "snippet": "public class CastIronBoilerStructure extends DirectionalBlock implements IWrenchable {\n public CastIronBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_CAST_IRON_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_CAST_IRON_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_CAST_IRON_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.CAST_IRON_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof CastIronLargeBoilerBlock\n && targetedState.getValue(CastIronLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new CastIronBoilerStructure.RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n CastIronBoilerStructure waterWheelStructuralBlock = MmbBlocks.CAST_IRON_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(CastIronBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n CastIronBoilerStructure waterWheelStructuralBlock = MmbBlocks.CAST_IRON_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(CastIronBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "CastIronLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/cast_iron/CastIronLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CastIronLargeBoilerBlock extends TagDependentDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public CastIronLargeBoilerBlock(Properties properties, TagKey<Item> itemTagKey) {\n super(properties, itemTagKey);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.CAST_IRON_BOILER_STRUCTURAL.getDefaultState()\n .setValue(CastIronBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof CastIronLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof CastIronLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof CastIronLargeBoilerBlock || s.getBlock() instanceof CastIronLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "CastIronLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/cast_iron/CastIronLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CastIronLargeBoilerBlockItem extends BlockItem {\n\n public CastIronLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((CastIronLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((CastIronLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n\n}" }, { "identifier": "CopperBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/copper/CopperBoilerStructure.java", "snippet": "public class CopperBoilerStructure extends DirectionalBlock implements IWrenchable {\n public CopperBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_COPPER_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_COPPER_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_COPPER_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.COPPER_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof CopperLargeBoilerBlock\n && targetedState.getValue(CopperLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n CopperBoilerStructure waterWheelStructuralBlock = MmbBlocks.COPPER_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(CopperBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n CopperBoilerStructure waterWheelStructuralBlock = MmbBlocks.COPPER_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(CopperBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "CopperLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/copper/CopperLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CopperLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public CopperLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.COPPER_BOILER_STRUCTURAL.getDefaultState()\n .setValue(CopperBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof CopperLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof CopperLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof CopperLargeBoilerBlock || s.getBlock() instanceof CopperLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "CopperLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/copper/CopperLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CopperLargeBoilerBlockItem extends BlockItem {\n\n public CopperLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((CopperLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((CopperLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "GoldBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/gold/GoldBoilerStructure.java", "snippet": "public class GoldBoilerStructure extends DirectionalBlock implements IWrenchable {\n public GoldBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_GOLD_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_GOLD_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_GOLD_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.GOLD_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof GoldLargeBoilerBlock\n && targetedState.getValue(GoldLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n GoldBoilerStructure waterWheelStructuralBlock = MmbBlocks.GOLD_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(GoldBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n GoldBoilerStructure waterWheelStructuralBlock = MmbBlocks.GOLD_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(GoldBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "GoldLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/gold/GoldLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class GoldLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public GoldLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.GOLD_BOILER_STRUCTURAL.getDefaultState()\n .setValue(GoldBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof GoldLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof GoldLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof GoldLargeBoilerBlock || s.getBlock() instanceof GoldLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "GoldLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/gold/GoldLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class GoldLargeBoilerBlockItem extends BlockItem {\n\n public GoldLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((GoldLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((GoldLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "IndustrialIronBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/industrial_iron/IndustrialIronBoilerStructure.java", "snippet": "public class IndustrialIronBoilerStructure extends DirectionalBlock implements IWrenchable {\n public IndustrialIronBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_INDUSTRIAL_IRON_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_INDUSTRIAL_IRON_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_INDUSTRIAL_IRON_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.INDUSTRIAL_IRON_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof IndustrialIronLargeBoilerBlock\n && targetedState.getValue(IndustrialIronLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n IndustrialIronBoilerStructure waterWheelStructuralBlock = MmbBlocks.INDUSTRIAL_IRON_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(IndustrialIronBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n IndustrialIronBoilerStructure waterWheelStructuralBlock = MmbBlocks.INDUSTRIAL_IRON_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(IndustrialIronBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "IndustrialIronLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/industrial_iron/IndustrialIronLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class IndustrialIronLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public IndustrialIronLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.INDUSTRIAL_IRON_BOILER_STRUCTURAL.getDefaultState()\n .setValue(IndustrialIronBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof IndustrialIronLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof IndustrialIronLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof IndustrialIronLargeBoilerBlock || s.getBlock() instanceof IndustrialIronLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "IndustrialIronLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/industrial_iron/IndustrialIronLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class IndustrialIronLargeBoilerBlockItem extends BlockItem {\n\n public IndustrialIronLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((IndustrialIronLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((IndustrialIronLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "ZincBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/zinc/ZincBoilerStructure.java", "snippet": "public class ZincBoilerStructure extends DirectionalBlock implements IWrenchable {\n public ZincBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_ZINC_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_ZINC_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_ZINC_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.ZINC_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof ZincLargeBoilerBlock\n && targetedState.getValue(ZincLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n ZincBoilerStructure waterWheelStructuralBlock = MmbBlocks.ZINC_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(ZincBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n ZincBoilerStructure waterWheelStructuralBlock = MmbBlocks.ZINC_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(ZincBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "ZincLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/zinc/ZincLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class ZincLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public ZincLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.ZINC_BOILER_STRUCTURAL.getDefaultState()\n .setValue(ZincBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof ZincLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof ZincLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof ZincLargeBoilerBlock || s.getBlock() instanceof ZincLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "ZincLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/zinc/ZincLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class ZincLargeBoilerBlockItem extends BlockItem {\n\n public ZincLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((ZincLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((ZincLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n\n\n}" }, { "identifier": "REGISTRATE", "path": "src/main/java/com/mangomilk/design_decor/CreateMMBuilding.java", "snippet": "public static final CreateRegistrate REGISTRATE = CreateRegistrate.create(CreateMMBuilding.MOD_ID).creativeModeTab(()-> MmbCreativeModeTab.BUILDING);" }, { "identifier": "DecorBuilderTransformer", "path": "src/main/java/com/mangomilk/design_decor/base/DecorBuilderTransformer.java", "snippet": "public class DecorBuilderTransformer {\n\n public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> connected(\n Supplier<CTSpriteShiftEntry> ct) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get()))\n .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> layeredConnected(\n Supplier<CTSpriteShiftEntry> ct, Supplier<CTSpriteShiftEntry> ct2) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get(), p.models()\n .cubeColumn(c.getName(), ct.get()\n .getOriginalResourceLocation(),\n ct2.get()\n .getOriginalResourceLocation())))\n .onRegister(connectedTextures(() -> new HorizontalCTBehaviour(ct.get(), ct2.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n public static <B extends OrnateGrateBlock> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> ornateconnected(\n Supplier<CTSpriteShiftEntry> ct) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get(), AssetLookup.standardModel(c, p)))\n .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n private static BlockBehaviour.Properties glassProperties(BlockBehaviour.Properties p) {\n return p.isValidSpawn(DecorBuilderTransformer::never)\n .isRedstoneConductor(DecorBuilderTransformer::never)\n .isSuffocating(DecorBuilderTransformer::never)\n .isViewBlocking(DecorBuilderTransformer::never)\n .noOcclusion();\n }\n\n public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(Supplier<ConnectedTextureBehaviour> behaviour) {\n return CreateMMBuilding.REGISTRATE.block(\"tinted_framed_glass\", ConnectedTintedGlassBlock::new)\n .onRegister(connectedTextures(behaviour))\n .addLayer(() -> RenderType::translucent)\n .initialProperties(() -> Blocks.TINTED_GLASS)\n .properties(DecorBuilderTransformer::glassProperties)\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get))\n .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, \"palettes/\", \"tinted_framed_glass\"))\n .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE)\n .lang(\"Tinted Framed Glass\")\n .item()\n .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS)\n .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()),\n p.modLoc(\"block/palettes/tinted_framed_glass\")))\n .build()\n .register();\n }\n\n public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(String type,String name, Supplier<ConnectedTextureBehaviour> behaviour) {\n return CreateMMBuilding.REGISTRATE.block(type + \"_tinted_framed_glass\", ConnectedTintedGlassBlock::new)\n .onRegister(connectedTextures(behaviour))\n .addLayer(() -> RenderType::translucent)\n .initialProperties(() -> Blocks.TINTED_GLASS)\n .properties(DecorBuilderTransformer::glassProperties)\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get))\n .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, \"palettes/\", type + \"_tinted_framed_glass\"))\n .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE)\n .lang(name + \" Tinted Framed Glass\")\n .item()\n .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS)\n .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()),\n p.modLoc(\"block/palettes/\" + type + \"_tinted_framed_glass\")))\n .build()\n .register();\n }\n\n\n\n\n public static BlockEntry<Block> CastelBricks(String id, String lang, MaterialColor color, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Brick Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_bricks\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_bricks\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Brick Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Brick Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_bricks\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Bricks\")\n .register();\n }\n\n public static BlockEntry<Block> CastelBricks(String id, String lang, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Brick Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_bricks\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_bricks\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Brick Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Brick Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_bricks\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Bricks\")\n .register();\n }\n public static BlockEntry<Block> CastelTiles(String id, String lang, MaterialColor color, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Tile Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_tiles\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_tiles\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Tile Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Tile Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_tiles\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Tiles\")\n .register();\n }\n public static BlockEntry<Block> CastelTiles(String id, String lang, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Tile Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_tiles\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_tiles\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Tile Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Tile Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_tiles\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Tiles\")\n .register();\n }\n private static boolean never(BlockState p_235436_0_, BlockGetter p_235436_1_, BlockPos p_235436_2_) {return false;}\n private static Boolean never(BlockState p_235427_0_, BlockGetter p_235427_1_, BlockPos p_235427_2_, EntityType<?> p_235427_3_) {return false;}\n private static String palettesDir() {return \"block/palettes/\";}\n}" } ]
import com.mangomilk.design_decor.base.DecorBuilderTransformer; import com.mangomilk.design_decor.base.MmbSpriteShifts; import com.mangomilk.design_decor.blocks.*; import com.mangomilk.design_decor.blocks.SignBlock; import com.mangomilk.design_decor.blocks.chain.LargeChain; import com.mangomilk.design_decor.blocks.chain.TagDependentLargeChain; import com.mangomilk.design_decor.blocks.containers.red.RedContainerBlock; import com.mangomilk.design_decor.blocks.containers.red.RedContainerCTBehaviour; import com.mangomilk.design_decor.blocks.containers.red.RedContainerItem; import com.mangomilk.design_decor.blocks.containers.blue.BlueContainerBlock; import com.mangomilk.design_decor.blocks.containers.blue.BlueContainerCTBehaviour; import com.mangomilk.design_decor.blocks.containers.blue.BlueContainerItem; import com.mangomilk.design_decor.blocks.containers.green.GreenContainerBlock; import com.mangomilk.design_decor.blocks.containers.green.GreenContainerCTBehaviour; import com.mangomilk.design_decor.blocks.containers.green.GreenContainerItem; import com.mangomilk.design_decor.blocks.crushing_wheels.MmbCrushingWheelBlock; import com.mangomilk.design_decor.blocks.crushing_wheels.MmbCrushingWheelControllerBlock; import com.mangomilk.design_decor.blocks.diagonal_girder.DiagonalGirderBlock; import com.mangomilk.design_decor.blocks.diagonal_girder.DiagonalGirderGenerator; import com.mangomilk.design_decor.blocks.floodlight.FloodlightBlock; import com.mangomilk.design_decor.blocks.floodlight.FloodlightGenerator; import com.mangomilk.design_decor.blocks.gas_tank.GasTankBlock; import com.mangomilk.design_decor.blocks.glass.ConnectedTintedGlassBlock; import com.mangomilk.design_decor.blocks.industrial_gear.IndustrialGearBlock; import com.mangomilk.design_decor.blocks.industrial_gear.IndustrialGearBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.aluminum.AluminumBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.aluminum.AluminumLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.aluminum.AluminumLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.andesite.AndesiteBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.andesite.AndesiteLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.andesite.AndesiteLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.brass.BrassBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.brass.BrassLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.brass.BrassLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.capitalism.CapitalismBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.capitalism.CapitalismLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.capitalism.CapitalismLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.cast_iron.CastIronBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.cast_iron.CastIronLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.cast_iron.CastIronLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.copper.CopperBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.copper.CopperLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.copper.CopperLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.gold.GoldBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.gold.GoldLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.gold.GoldLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.industrial_iron.IndustrialIronBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.industrial_iron.IndustrialIronLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.industrial_iron.IndustrialIronLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.zinc.ZincBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.zinc.ZincLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.zinc.ZincLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.millstone.block.*; import com.simibubi.create.AllTags; import com.simibubi.create.content.kinetics.BlockStressDefaults; import com.simibubi.create.content.kinetics.simpleRelays.BracketedKineticBlockModel; import com.simibubi.create.foundation.block.connected.HorizontalCTBehaviour; import com.simibubi.create.foundation.block.connected.SimpleCTBehaviour; import com.simibubi.create.foundation.data.AssetLookup; import com.simibubi.create.foundation.data.BlockStateGen; import com.simibubi.create.foundation.data.CreateRegistrate; import com.simibubi.create.foundation.data.SharedProperties; import com.tterrag.registrate.util.entry.BlockEntry; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.client.renderer.RenderType; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.MaterialColor; import net.minecraftforge.client.model.generators.ConfiguredModel; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.IForgeRegistry; import javax.annotation.ParametersAreNonnullByDefault; import java.util.Collections; import static com.mangomilk.design_decor.CreateMMBuilding.REGISTRATE; import static com.mangomilk.design_decor.base.DecorBuilderTransformer.*; import static com.simibubi.create.foundation.data.CreateRegistrate.connectedTextures; import static com.simibubi.create.foundation.data.ModelGen.customItemModel; import static com.simibubi.create.foundation.data.TagGen.axeOrPickaxe; import static com.simibubi.create.foundation.data.TagGen.pickaxeOnly;
74,902
.forAllStatesExcept(BlockStateGen.mapToAir(p), CastIronBoilerStructure.FACING)) .lang("Large Cast Iron Boiler") .register(); public static final BlockEntry<BoilerBlock> CAPITALISM_BOILER = REGISTRATE.block("capitalism_boiler", BoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Capitalism Boiler") .register(); public static final BlockEntry<CapitalismLargeBoilerBlock> LARGE_CAPITALISM_BOILER = REGISTRATE.block("capitalism_boiler_large", CapitalismLargeBoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(CapitalismLargeBoilerBlockItem::new) .build() .lang("Large Capitalism Boiler") .register(); public static final BlockEntry<CapitalismBoilerStructure> CAPITALISM_BOILER_STRUCTURAL = REGISTRATE.block("capitalism_boiler_structure", CapitalismBoilerStructure::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStatesExcept(BlockStateGen.mapToAir(p), CapitalismBoilerStructure.FACING)) .lang("Large Capitalism Boiler") .register(); //GAS TANK public static final BlockEntry<GasTankBlock> GAS_TANK = REGISTRATE.block("gas_tank", GasTankBlock::new) .initialProperties(SharedProperties::softMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.sound(SoundType.COPPER)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate((c, p) -> p.simpleBlock(c.getEntry(), AssetLookup.partialBaseModel(c, p))) .item() .build() .lang("Compact Iron Fluid Tank") .register(); public static final BlockEntry<GasTankBlock> COPPER_GAS_TANK = REGISTRATE.block("copper_gas_tank", GasTankBlock::new) .initialProperties(SharedProperties::softMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.sound(SoundType.COPPER)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate((c, p) -> p.simpleBlock(c.getEntry(), AssetLookup.partialBaseModel(c, p))) .item() .build() .lang("Compact Fluid Tank") .register(); //CONTAINERS public static final BlockEntry<RedContainerBlock> RED_CONTAINER = REGISTRATE.block("red_container", RedContainerBlock::new) .initialProperties(SharedProperties::softMetal) .properties(p -> p.color(MaterialColor.TERRACOTTA_RED)) .properties(p -> p.sound(SoundType.NETHERITE_BLOCK) .explosionResistance(1200)) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStates(s -> ConfiguredModel.builder() .modelFile(AssetLookup.standardModel(c, p)) .rotationY(s.getValue(RedContainerBlock.HORIZONTAL_AXIS) == Direction.Axis.X ? 90 : 0) .build())) .onRegister(connectedTextures(RedContainerCTBehaviour::new)) .item(RedContainerItem::new) .build() .lang("Red Container") .register(); public static final BlockEntry<BlueContainerBlock> BLUE_CONTAINER = REGISTRATE.block("blue_container",BlueContainerBlock::new) .initialProperties(SharedProperties::softMetal) .properties(p -> p.color(MaterialColor.COLOR_BLUE)) .properties(p -> p.sound(SoundType.NETHERITE_BLOCK) .explosionResistance(1200)) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStates(s -> ConfiguredModel.builder() .modelFile(AssetLookup.standardModel(c, p)) .rotationY(s.getValue(RedContainerBlock.HORIZONTAL_AXIS) == Direction.Axis.X ? 90 : 0) .build())) .onRegister(connectedTextures(BlueContainerCTBehaviour::new)) .item(BlueContainerItem::new) .build() .lang("Blue Container") .register(); public static final BlockEntry<GreenContainerBlock> GREEN_CONTAINER = REGISTRATE.block("green_container",GreenContainerBlock::new) .initialProperties(SharedProperties::softMetal) .properties(p -> p.color(MaterialColor.COLOR_GREEN)) .properties(p -> p.sound(SoundType.NETHERITE_BLOCK) .explosionResistance(1200)) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStates(s -> ConfiguredModel.builder() .modelFile(AssetLookup.standardModel(c, p)) .rotationY(s.getValue(RedContainerBlock.HORIZONTAL_AXIS) == Direction.Axis.X ? 90 : 0) .build())) .onRegister(connectedTextures(GreenContainerCTBehaviour::new)) .item(GreenContainerItem::new) .build() .lang("Green Container") .register(); //SIGNS
package com.mangomilk.design_decor.registry; @SuppressWarnings({"unused", "removal"}) @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class MmbBlocks { //LAMPS public static final BlockEntry<LampBlock> BRASS_LAMP = REGISTRATE.block("brass_lamp", LampBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p->p.lightLevel(s -> 15)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(false)) .item() .build() .lang("Brass Lamp") .register(); public static final BlockEntry<LampBlock> COPPER_LAMP = REGISTRATE.block("copper_lamp", LampBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p->p.lightLevel(s -> 15)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(false)) .item() .build() .lang("Copper Lamp") .register(); public static final BlockEntry<LampBlock> ZINC_LAMP = REGISTRATE.block("zinc_lamp", LampBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p->p.lightLevel(s -> 15)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(false)) .item() .build() .lang("Zinc Lamp") .register(); public static final BlockEntry<Block> BRASS_LIGHT = REGISTRATE.block("brass_light", Block::new) .properties(p -> p.color(MaterialColor.GOLD)) .properties(p->p.lightLevel(s -> 15)) .initialProperties(SharedProperties::copperMetal) .transform(pickaxeOnly()) .item() .build() .lang("Brass Light") .register(); public static final BlockEntry<Block> COPPER_LIGHT = REGISTRATE.block("copper_light", Block::new) .properties(p -> p.color(MaterialColor.GOLD)) .properties(p->p.lightLevel(s -> 15)) .initialProperties(SharedProperties::copperMetal) .transform(pickaxeOnly()) .item() .build() .lang("Copper Light") .register(); public static final BlockEntry<Block> ZINC_LIGHT = REGISTRATE.block("zinc_light", Block::new) .properties(p -> p.color(MaterialColor.GOLD)) .properties(p->p.lightLevel(s -> 15)) .initialProperties(SharedProperties::copperMetal) .transform(pickaxeOnly()) .item() .build() .lang("Zinc Light") .register(); //FLOODLIGHTS public static final BlockEntry<FloodlightBlock> BRASS_FLOODLIGHT = REGISTRATE.block("brass_floodlight", FloodlightBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(p -> p.color(MaterialColor.TERRACOTTA_YELLOW)) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.lightLevel(s -> s.getValue(FloodlightBlock.TURNED_ON) ? 15 : 0)) .addLayer(() -> RenderType::cutout) .blockstate(new FloodlightGenerator()::generate) .transform(axeOrPickaxe()) .lang("Brass Floodlight") .item() .transform(customItemModel("_", "block")) .register(); public static final BlockEntry<FloodlightBlock> ANDESITE_FLOODLIGHT = REGISTRATE.block("andesite_floodlight", FloodlightBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(p -> p.color(MaterialColor.STONE)) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.lightLevel(s -> s.getValue(FloodlightBlock.WATERLOGGED) == s.getValue(FloodlightBlock.TURNED_ON) ? 0 : !s.getValue(FloodlightBlock.WATERLOGGED) ? 12 : 8 )) .addLayer(() -> RenderType::cutout) .blockstate(new FloodlightGenerator()::generate) .transform(axeOrPickaxe()) .lang("Andesite Floodlight") .item() .transform(customItemModel("_", "block")) .register(); public static final BlockEntry<FloodlightBlock> COPPER_FLOODLIGHT = REGISTRATE.block("copper_floodlight", FloodlightBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(p -> p.color(MaterialColor.STONE)) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.lightLevel(s -> s.getValue(FloodlightBlock.WATERLOGGED) == s.getValue(FloodlightBlock.TURNED_ON) ? 12 : 0 )) .properties(p -> p.lightLevel(s -> !s.getValue(FloodlightBlock.WATERLOGGED) == s.getValue(FloodlightBlock.TURNED_ON) ? 6 : 0 )) .addLayer(() -> RenderType::cutout) .blockstate(new FloodlightGenerator()::generate) .transform(axeOrPickaxe()) .lang("Copper Floodlight") .item() .transform(customItemModel("_", "block")) .register(); //COGWHEELS public static final BlockEntry<IndustrialGearBlock> COGWHEEL = REGISTRATE.block("industrial_gear", IndustrialGearBlock::small) .initialProperties(SharedProperties::softMetal) .properties(p -> p.color(MaterialColor.COLOR_GRAY)) .properties(p -> p.sound(SoundType.NETHERITE_BLOCK)) .properties(BlockBehaviour.Properties::requiresCorrectToolForDrops) .transform(pickaxeOnly()) .transform(BlockStressDefaults.setNoImpact()) .blockstate(BlockStateGen.axisBlockProvider(false)) .onRegister(CreateRegistrate.blockModel(() -> BracketedKineticBlockModel::new)) .item(IndustrialGearBlockItem::new) .build() .lang("Industrial Gear") .register(); public static final BlockEntry<IndustrialGearBlock> LARGE_COGWHEEL = REGISTRATE.block("industrial_gear_large", IndustrialGearBlock::large) .initialProperties(SharedProperties::softMetal) .properties(p -> p.color(MaterialColor.COLOR_GRAY)) .properties(p -> p.sound(SoundType.NETHERITE_BLOCK)) .properties(BlockBehaviour.Properties::requiresCorrectToolForDrops) .transform(pickaxeOnly()) .transform(BlockStressDefaults.setNoImpact()) .blockstate(BlockStateGen.axisBlockProvider(false)) .onRegister(CreateRegistrate.blockModel(() -> BracketedKineticBlockModel::new)) .item(IndustrialGearBlockItem::new) .build() .lang("Large Industrial Gear") .register(); //BOILERS public static final BlockEntry<BoilerBlock> BRASS_BOILER = REGISTRATE.block("brass_boiler", BoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Brass Boiler") .register(); public static final BlockEntry<BrassLargeBoilerBlock> LARGE_BRASS_BOILER = REGISTRATE.block("brass_boiler_large", BrassLargeBoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .properties(p -> p.isViewBlocking(MmbBlocks::never)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(BrassLargeBoilerBlockItem::new) .build() .lang("Large Brass Boiler") .register(); public static final BlockEntry<BrassBoilerStructure> BRASS_BOILER_STRUCTURAL = REGISTRATE.block("brass_boiler_structure", BrassBoilerStructure::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStatesExcept(BlockStateGen.mapToAir(p), BrassBoilerStructure.FACING)) .lang("Large Brass Boiler") .register(); public static final BlockEntry<TagBoilerBlock> ALUMINUM_BOILER = REGISTRATE.block("aluminium_boiler", p -> new TagBoilerBlock(p, AllTags.forgeItemTag("ingots/aluminium"))) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Aluminium Boiler") .register(); public static final BlockEntry<TagBoilerBlock> ALUMINUM_BOILER_SPECIAL = REGISTRATE.block("aluminium_boiler_special", p -> new TagBoilerBlock(p, AllTags.forgeItemTag("ingots/aluminium"))) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Aluminium Boiler") .register(); public static final BlockEntry<AluminumLargeBoilerBlock> LARGE_ALUMINUM_BOILER = REGISTRATE.block("aluminium_boiler_large", p -> new AluminumLargeBoilerBlock(p, AllTags.forgeItemTag("ingots/aluminium"))) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(AluminumLargeBoilerBlockItem::new) .build() .lang("Large Aluminium Boiler") .register(); public static final BlockEntry<AluminumBoilerStructure> ALUMINUM_BOILER_STRUCTURAL = REGISTRATE.block("aluminium_boiler_structure", AluminumBoilerStructure::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStatesExcept(BlockStateGen.mapToAir(p), AluminumBoilerStructure.FACING)) .lang("Large Aluminium Boiler") .register(); public static final BlockEntry<BoilerBlock> GOLD_BOILER = REGISTRATE.block("gold_boiler", BoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Gold Boiler") .register(); public static final BlockEntry<GoldLargeBoilerBlock> LARGE_GOLD_BOILER = REGISTRATE.block("gold_boiler_large", GoldLargeBoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(GoldLargeBoilerBlockItem::new) .build() .lang("Large Gold Boiler") .register(); public static final BlockEntry<GoldBoilerStructure> GOLD_BOILER_STRUCTURAL = REGISTRATE.block("gold_boiler_structure", GoldBoilerStructure::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStatesExcept(BlockStateGen.mapToAir(p), GoldBoilerStructure.FACING)) .lang("Large Gold Boiler") .register(); public static final BlockEntry<BoilerBlock> COPPER_BOILER = REGISTRATE.block("copper_boiler", BoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Copper Boiler") .register(); public static final BlockEntry<CopperLargeBoilerBlock> LARGE_COPPER_BOILER = REGISTRATE.block("copper_boiler_large", CopperLargeBoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(CopperLargeBoilerBlockItem::new) .build() .lang("Large Copper Boiler") .register(); public static final BlockEntry<CopperBoilerStructure> COPPER_BOILER_STRUCTURAL = REGISTRATE.block("copper_boiler_structure", CopperBoilerStructure::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStatesExcept(BlockStateGen.mapToAir(p), CopperBoilerStructure.FACING)) .lang("Large Copper Boiler") .register(); public static final BlockEntry<BoilerBlock> ZINC_BOILER = REGISTRATE.block("zinc_boiler", BoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Zinc Boiler") .register(); public static final BlockEntry<ZincLargeBoilerBlock> LARGE_ZINC_BOILER = REGISTRATE.block("zinc_boiler_large", ZincLargeBoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(ZincLargeBoilerBlockItem::new) .build() .lang("Large Zinc Boiler") .register(); public static final BlockEntry<ZincBoilerStructure> ZINC_BOILER_STRUCTURAL = REGISTRATE.block("zinc_boiler_structure", ZincBoilerStructure::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStatesExcept(BlockStateGen.mapToAir(p), ZincBoilerStructure.FACING)) .lang("Large Zinc Boiler") .register(); public static final BlockEntry<BoilerBlock> INDUSTRIAL_IRON_BOILER = REGISTRATE.block("industrial_iron_boiler", BoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Industrial Iron Boiler") .register(); public static final BlockEntry<IndustrialIronLargeBoilerBlock> LARGE_INDUSTRIAL_IRON_BOILER = REGISTRATE.block("industrial_iron_boiler_large", IndustrialIronLargeBoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(IndustrialIronLargeBoilerBlockItem::new) .build() .lang("Large Industrial Iron Boiler") .register(); public static final BlockEntry<IndustrialIronBoilerStructure> INDUSTRIAL_IRON_BOILER_STRUCTURAL = REGISTRATE.block("industrial_iron_boiler_structure", IndustrialIronBoilerStructure::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStatesExcept(BlockStateGen.mapToAir(p), IndustrialIronBoilerStructure.FACING)) .lang("Large Industrial Iron Boiler") .register(); public static final BlockEntry<BoilerBlock> ANDESITE_BOILER = REGISTRATE.block("andesite_boiler", BoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Andesite Boiler") .register(); public static final BlockEntry<AndesiteLargeBoilerBlock> LARGE_ANDESITE_BOILER = REGISTRATE.block("andesite_boiler_large", AndesiteLargeBoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(AndesiteLargeBoilerBlockItem::new) .build() .lang("Large Andesite Boiler") .register(); public static final BlockEntry<AndesiteBoilerStructure> ANDESITE_BOILER_STRUCTURAL = REGISTRATE.block("andesite_boiler_structure", AndesiteBoilerStructure::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStatesExcept(BlockStateGen.mapToAir(p), AndesiteBoilerStructure.FACING)) .lang("Large Andesite Boiler") .register(); public static final BlockEntry<TagBoilerBlock> CAST_IRON_BOILER = REGISTRATE.block("cast_iron_boiler", p -> new TagBoilerBlock(p, AllTags.forgeItemTag("ingots/cast_iron"))) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Cast Iron Boiler") .register(); public static final BlockEntry<CastIronLargeBoilerBlock> LARGE_CAST_IRON_BOILER = REGISTRATE.block("cast_iron_boiler_large", p -> new CastIronLargeBoilerBlock(p, AllTags.forgeItemTag("ingots/cast_iron"))) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(CastIronLargeBoilerBlockItem::new) .build() .lang("Large Cast Iron Boiler") .register(); public static final BlockEntry<CastIronBoilerStructure> CAST_IRON_BOILER_STRUCTURAL = REGISTRATE.block("cast_iron_boiler_structure", CastIronBoilerStructure::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStatesExcept(BlockStateGen.mapToAir(p), CastIronBoilerStructure.FACING)) .lang("Large Cast Iron Boiler") .register(); public static final BlockEntry<BoilerBlock> CAPITALISM_BOILER = REGISTRATE.block("capitalism_boiler", BoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Capitalism Boiler") .register(); public static final BlockEntry<CapitalismLargeBoilerBlock> LARGE_CAPITALISM_BOILER = REGISTRATE.block("capitalism_boiler_large", CapitalismLargeBoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(CapitalismLargeBoilerBlockItem::new) .build() .lang("Large Capitalism Boiler") .register(); public static final BlockEntry<CapitalismBoilerStructure> CAPITALISM_BOILER_STRUCTURAL = REGISTRATE.block("capitalism_boiler_structure", CapitalismBoilerStructure::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStatesExcept(BlockStateGen.mapToAir(p), CapitalismBoilerStructure.FACING)) .lang("Large Capitalism Boiler") .register(); //GAS TANK public static final BlockEntry<GasTankBlock> GAS_TANK = REGISTRATE.block("gas_tank", GasTankBlock::new) .initialProperties(SharedProperties::softMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.sound(SoundType.COPPER)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate((c, p) -> p.simpleBlock(c.getEntry(), AssetLookup.partialBaseModel(c, p))) .item() .build() .lang("Compact Iron Fluid Tank") .register(); public static final BlockEntry<GasTankBlock> COPPER_GAS_TANK = REGISTRATE.block("copper_gas_tank", GasTankBlock::new) .initialProperties(SharedProperties::softMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.sound(SoundType.COPPER)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate((c, p) -> p.simpleBlock(c.getEntry(), AssetLookup.partialBaseModel(c, p))) .item() .build() .lang("Compact Fluid Tank") .register(); //CONTAINERS public static final BlockEntry<RedContainerBlock> RED_CONTAINER = REGISTRATE.block("red_container", RedContainerBlock::new) .initialProperties(SharedProperties::softMetal) .properties(p -> p.color(MaterialColor.TERRACOTTA_RED)) .properties(p -> p.sound(SoundType.NETHERITE_BLOCK) .explosionResistance(1200)) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStates(s -> ConfiguredModel.builder() .modelFile(AssetLookup.standardModel(c, p)) .rotationY(s.getValue(RedContainerBlock.HORIZONTAL_AXIS) == Direction.Axis.X ? 90 : 0) .build())) .onRegister(connectedTextures(RedContainerCTBehaviour::new)) .item(RedContainerItem::new) .build() .lang("Red Container") .register(); public static final BlockEntry<BlueContainerBlock> BLUE_CONTAINER = REGISTRATE.block("blue_container",BlueContainerBlock::new) .initialProperties(SharedProperties::softMetal) .properties(p -> p.color(MaterialColor.COLOR_BLUE)) .properties(p -> p.sound(SoundType.NETHERITE_BLOCK) .explosionResistance(1200)) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStates(s -> ConfiguredModel.builder() .modelFile(AssetLookup.standardModel(c, p)) .rotationY(s.getValue(RedContainerBlock.HORIZONTAL_AXIS) == Direction.Axis.X ? 90 : 0) .build())) .onRegister(connectedTextures(BlueContainerCTBehaviour::new)) .item(BlueContainerItem::new) .build() .lang("Blue Container") .register(); public static final BlockEntry<GreenContainerBlock> GREEN_CONTAINER = REGISTRATE.block("green_container",GreenContainerBlock::new) .initialProperties(SharedProperties::softMetal) .properties(p -> p.color(MaterialColor.COLOR_GREEN)) .properties(p -> p.sound(SoundType.NETHERITE_BLOCK) .explosionResistance(1200)) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStates(s -> ConfiguredModel.builder() .modelFile(AssetLookup.standardModel(c, p)) .rotationY(s.getValue(RedContainerBlock.HORIZONTAL_AXIS) == Direction.Axis.X ? 90 : 0) .build())) .onRegister(connectedTextures(GreenContainerCTBehaviour::new)) .item(GreenContainerItem::new) .build() .lang("Green Container") .register(); //SIGNS
public static final BlockEntry<SignBlock> MOYAI_SIGN = REGISTRATE.block("moyai_sign", SignBlock::new)
2
2023-10-14 21:51:49+00:00
128k
Hoto-Mocha/Re-ARranged-Pixel-Dungeon
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/weapon/melee/Rapier.java
[ { "identifier": "Assets", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/Assets.java", "snippet": "public class Assets {\n\n\tpublic static class Effects {\n\t\tpublic static final String EFFECTS = \"effects/effects.png\";\n\t\tpublic static final String FIREBALL = \"effects/fireball.png\";\n\t\tpublic static final String SPECKS = \"effects/specks.png\";\n\t\tpublic static final String SPELL_ICONS = \"effects/spell_icons.png\";\n\t}\n\n\tpublic static class Environment {\n\t\tpublic static final String TERRAIN_FEATURES = \"environment/terrain_features.png\";\n\n\t\tpublic static final String VISUAL_GRID = \"environment/visual_grid.png\";\n\t\tpublic static final String WALL_BLOCKING= \"environment/wall_blocking.png\";\n\n\t\tpublic static final String TILES_SEWERS = \"environment/tiles_sewers.png\";\n\t\tpublic static final String TILES_PRISON = \"environment/tiles_prison.png\";\n\t\tpublic static final String TILES_CAVES = \"environment/tiles_caves.png\";\n\t\tpublic static final String TILES_CITY = \"environment/tiles_city.png\";\n\t\tpublic static final String TILES_HALLS = \"environment/tiles_halls.png\";\n\t\tpublic static final String TILES_TEMPLE = \"environment/tiles_temple.png\";\n\t\tpublic static final String TILES_LABS\t= \"environment/tiles_labs.png\";\n\n\t\tpublic static final String WATER_SEWERS = \"environment/water0.png\";\n\t\tpublic static final String WATER_PRISON = \"environment/water1.png\";\n\t\tpublic static final String WATER_CAVES = \"environment/water2.png\";\n\t\tpublic static final String WATER_CITY = \"environment/water3.png\";\n\t\tpublic static final String WATER_HALLS = \"environment/water4.png\";\n\t\tpublic static final String WATER_TEMPLE = \"environment/water0_temple.png\";\n\t\tpublic static final String WATER_LABS\t= \"environment/water5.png\";\n\n\t\tpublic static final String WEAK_FLOOR = \"environment/custom_tiles/weak_floor.png\";\n\t\tpublic static final String SEWER_BOSS = \"environment/custom_tiles/sewer_boss.png\";\n\t\tpublic static final String PRISON_QUEST = \"environment/custom_tiles/prison_quest.png\";\n\t\tpublic static final String PRISON_EXIT = \"environment/custom_tiles/prison_exit.png\";\n\t\tpublic static final String CAVES_QUEST = \"environment/custom_tiles/caves_quest.png\";\n\t\tpublic static final String CAVES_BOSS = \"environment/custom_tiles/caves_boss.png\";\n\t\tpublic static final String CITY_BOSS = \"environment/custom_tiles/city_boss.png\";\n\t\tpublic static final String HALLS_SP = \"environment/custom_tiles/halls_special.png\";\n\t\tpublic static final String TEMPLE_SP = \"environment/custom_tiles/temple_special.png\";\n\t}\n\t\n\t//TODO include other font assets here? Some are platform specific though...\n\tpublic static class Fonts {\n\t\tpublic static final String PIXELFONT= \"fonts/pixel_font.png\";\n\t}\n\n\tpublic static class Interfaces {\n\t\tpublic static final String ARCS_BG = \"interfaces/arcs1.png\";\n\t\tpublic static final String ARCS_FG = \"interfaces/arcs2.png\";\n\n\t\tpublic static final String BANNERS = \"interfaces/banners.png\";\n\t\tpublic static final String BADGES = \"interfaces/badges.png\";\n\t\tpublic static final String LOCKED = \"interfaces/locked_badge.png\";\n\n\t\tpublic static final String CHROME = \"interfaces/chrome.png\";\n\t\tpublic static final String ICONS = \"interfaces/icons.png\";\n\t\tpublic static final String STATUS = \"interfaces/status_pane.png\";\n\t\tpublic static final String MENU = \"interfaces/menu_pane.png\";\n\t\tpublic static final String MENU_BTN = \"interfaces/menu_button.png\";\n\t\tpublic static final String TOOLBAR = \"interfaces/toolbar.png\";\n\t\tpublic static final String SHADOW = \"interfaces/shadow.png\";\n\t\tpublic static final String BOSSHP = \"interfaces/boss_hp.png\";\n\n\t\tpublic static final String SURFACE = \"interfaces/surface.png\";\n\n\t\tpublic static final String LOADING_SEWERS = \"interfaces/loading_sewers.png\";\n\t\tpublic static final String LOADING_PRISON = \"interfaces/loading_prison.png\";\n\t\tpublic static final String LOADING_CAVES = \"interfaces/loading_caves.png\";\n\t\tpublic static final String LOADING_CITY = \"interfaces/loading_city.png\";\n\t\tpublic static final String LOADING_HALLS = \"interfaces/loading_halls.png\";\n\n\t\tpublic static final String BUFFS_SMALL = \"interfaces/buffs.png\";\n\t\tpublic static final String BUFFS_LARGE = \"interfaces/large_buffs.png\";\n\n\t\tpublic static final String TALENT_ICONS = \"interfaces/talent_icons.png\";\n\t\tpublic static final String TALENT_BUTTON = \"interfaces/talent_button.png\";\n\n\t\tpublic static final String HERO_ICONS = \"interfaces/hero_icons.png\";\n\n\t\tpublic static final String RADIAL_MENU = \"interfaces/radial_menu.png\";\n\t}\n\n\t//these points to resource bundles, not raw asset files\n\tpublic static class Messages {\n\t\tpublic static final String ACTORS = \"messages/actors/actors\";\n\t\tpublic static final String ITEMS = \"messages/items/items\";\n\t\tpublic static final String JOURNAL = \"messages/journal/journal\";\n\t\tpublic static final String LEVELS = \"messages/levels/levels\";\n\t\tpublic static final String MISC = \"messages/misc/misc\";\n\t\tpublic static final String PLANTS = \"messages/plants/plants\";\n\t\tpublic static final String SCENES = \"messages/scenes/scenes\";\n\t\tpublic static final String UI = \"messages/ui/ui\";\n\t\tpublic static final String WINDOWS = \"messages/windows/windows\";\n\t}\n\n\tpublic static class Music {\n\t\tpublic static final String THEME_1 = \"music/theme_1.ogg\";\n\t\tpublic static final String THEME_2 = \"music/theme_2.ogg\";\n\t\tpublic static final String THEME_FINALE = \"music/theme_finale.ogg\";\n\n\t\tpublic static final String SEWERS_1 = \"music/sewers_1.ogg\";\n\t\tpublic static final String SEWERS_2 = \"music/sewers_2.ogg\";\n\t\tpublic static final String SEWERS_3 = \"music/sewers_3.ogg\";\n\t\tpublic static final String SEWERS_TENSE = \"music/sewers_tense.ogg\";\n\t\tpublic static final String SEWERS_BOSS = \"music/sewers_boss.ogg\";\n\n\t\tpublic static final String PRISON_1 = \"music/prison_1.ogg\";\n\t\tpublic static final String PRISON_2 = \"music/prison_2.ogg\";\n\t\tpublic static final String PRISON_3 = \"music/prison_3.ogg\";\n\t\tpublic static final String PRISON_TENSE = \"music/prison_tense.ogg\";\n\t\tpublic static final String PRISON_BOSS = \"music/prison_boss.ogg\";\n\n\t\tpublic static final String CAVES_1 = \"music/caves_1.ogg\";\n\t\tpublic static final String CAVES_2 = \"music/caves_2.ogg\";\n\t\tpublic static final String CAVES_3 = \"music/caves_3.ogg\";\n\t\tpublic static final String CAVES_TENSE = \"music/caves_tense.ogg\";\n\t\tpublic static final String CAVES_BOSS = \"music/caves_boss.ogg\";\n\t\tpublic static final String CAVES_BOSS_FINALE = \"music/caves_boss_finale.ogg\";\n\n\t\tpublic static final String CITY_1 = \"music/city_1.ogg\";\n\t\tpublic static final String CITY_2 = \"music/city_2.ogg\";\n\t\tpublic static final String CITY_3 = \"music/city_3.ogg\";\n\t\tpublic static final String CITY_TENSE = \"music/city_tense.ogg\";\n\t\tpublic static final String CITY_BOSS = \"music/city_boss.ogg\";\n\t\tpublic static final String CITY_BOSS_FINALE = \"music/city_boss_finale.ogg\";\n\n\t\tpublic static final String HALLS_1 = \"music/halls_1.ogg\";\n\t\tpublic static final String HALLS_2 = \"music/halls_2.ogg\";\n\t\tpublic static final String HALLS_3 = \"music/halls_3.ogg\";\n\t\tpublic static final String HALLS_TENSE = \"music/halls_tense.ogg\";\n\t\tpublic static final String HALLS_BOSS = \"music/halls_boss.ogg\";\n\t\tpublic static final String HALLS_BOSS_FINALE = \"music/halls_boss_finale.ogg\";\n\t}\n\n\tpublic static class Sounds {\n\t\tpublic static final String CLICK = \"sounds/click.mp3\";\n\t\tpublic static final String BADGE = \"sounds/badge.mp3\";\n\t\tpublic static final String GOLD = \"sounds/gold.mp3\";\n\n\t\tpublic static final String OPEN = \"sounds/door_open.mp3\";\n\t\tpublic static final String UNLOCK = \"sounds/unlock.mp3\";\n\t\tpublic static final String ITEM = \"sounds/item.mp3\";\n\t\tpublic static final String DEWDROP = \"sounds/dewdrop.mp3\";\n\t\tpublic static final String STEP = \"sounds/step.mp3\";\n\t\tpublic static final String WATER = \"sounds/water.mp3\";\n\t\tpublic static final String GRASS = \"sounds/grass.mp3\";\n\t\tpublic static final String TRAMPLE = \"sounds/trample.mp3\";\n\t\tpublic static final String STURDY = \"sounds/sturdy.mp3\";\n\n\t\tpublic static final String HIT = \"sounds/hit.mp3\";\n\t\tpublic static final String MISS = \"sounds/miss.mp3\";\n\t\tpublic static final String HIT_SLASH = \"sounds/hit_slash.mp3\";\n\t\tpublic static final String HIT_STAB = \"sounds/hit_stab.mp3\";\n\t\tpublic static final String HIT_CRUSH = \"sounds/hit_crush.mp3\";\n\t\tpublic static final String HIT_MAGIC = \"sounds/hit_magic.mp3\";\n\t\tpublic static final String HIT_STRONG = \"sounds/hit_strong.mp3\";\n\t\tpublic static final String HIT_PARRY = \"sounds/hit_parry.mp3\";\n\t\tpublic static final String HIT_ARROW = \"sounds/hit_arrow.mp3\";\n\t\tpublic static final String ATK_SPIRITBOW = \"sounds/atk_spiritbow.mp3\";\n\t\tpublic static final String ATK_CROSSBOW = \"sounds/atk_crossbow.mp3\";\n\t\tpublic static final String HEALTH_WARN = \"sounds/health_warn.mp3\";\n\t\tpublic static final String HEALTH_CRITICAL = \"sounds/health_critical.mp3\";\n\n\t\tpublic static final String DESCEND = \"sounds/descend.mp3\";\n\t\tpublic static final String EAT = \"sounds/eat.mp3\";\n\t\tpublic static final String READ = \"sounds/read.mp3\";\n\t\tpublic static final String LULLABY = \"sounds/lullaby.mp3\";\n\t\tpublic static final String DRINK = \"sounds/drink.mp3\";\n\t\tpublic static final String SHATTER = \"sounds/shatter.mp3\";\n\t\tpublic static final String ZAP = \"sounds/zap.mp3\";\n\t\tpublic static final String LIGHTNING= \"sounds/lightning.mp3\";\n\t\tpublic static final String LEVELUP = \"sounds/levelup.mp3\";\n\t\tpublic static final String DEATH = \"sounds/death.mp3\";\n\t\tpublic static final String CHALLENGE= \"sounds/challenge.mp3\";\n\t\tpublic static final String CURSED = \"sounds/cursed.mp3\";\n\t\tpublic static final String TRAP = \"sounds/trap.mp3\";\n\t\tpublic static final String EVOKE = \"sounds/evoke.mp3\";\n\t\tpublic static final String TOMB = \"sounds/tomb.mp3\";\n\t\tpublic static final String ALERT = \"sounds/alert.mp3\";\n\t\tpublic static final String MELD = \"sounds/meld.mp3\";\n\t\tpublic static final String BOSS = \"sounds/boss.mp3\";\n\t\tpublic static final String BLAST = \"sounds/blast.mp3\";\n\t\tpublic static final String PLANT = \"sounds/plant.mp3\";\n\t\tpublic static final String RAY = \"sounds/ray.mp3\";\n\t\tpublic static final String BEACON = \"sounds/beacon.mp3\";\n\t\tpublic static final String TELEPORT = \"sounds/teleport.mp3\";\n\t\tpublic static final String CHARMS = \"sounds/charms.mp3\";\n\t\tpublic static final String MASTERY = \"sounds/mastery.mp3\";\n\t\tpublic static final String PUFF = \"sounds/puff.mp3\";\n\t\tpublic static final String ROCKS = \"sounds/rocks.mp3\";\n\t\tpublic static final String BURNING = \"sounds/burning.mp3\";\n\t\tpublic static final String FALLING = \"sounds/falling.mp3\";\n\t\tpublic static final String GHOST = \"sounds/ghost.mp3\";\n\t\tpublic static final String SECRET = \"sounds/secret.mp3\";\n\t\tpublic static final String BONES = \"sounds/bones.mp3\";\n\t\tpublic static final String BEE = \"sounds/bee.mp3\";\n\t\tpublic static final String DEGRADE = \"sounds/degrade.mp3\";\n\t\tpublic static final String MIMIC = \"sounds/mimic.mp3\";\n\t\tpublic static final String DEBUFF = \"sounds/debuff.mp3\";\n\t\tpublic static final String CHARGEUP = \"sounds/chargeup.mp3\";\n\t\tpublic static final String GAS = \"sounds/gas.mp3\";\n\t\tpublic static final String CHAINS = \"sounds/chains.mp3\";\n\t\tpublic static final String SCAN = \"sounds/scan.mp3\";\n\t\tpublic static final String SHEEP = \"sounds/sheep.mp3\";\n\t\tpublic static final String MINE = \"sounds/mine.mp3\";\n\n\t\tpublic static final String[] all = new String[]{\n\t\t\t\tCLICK, BADGE, GOLD,\n\n\t\t\t\tOPEN, UNLOCK, ITEM, DEWDROP, STEP, WATER, GRASS, TRAMPLE, STURDY,\n\n\t\t\t\tHIT, MISS, HIT_SLASH, HIT_STAB, HIT_CRUSH, HIT_MAGIC, HIT_STRONG, HIT_PARRY,\n\t\t\t\tHIT_ARROW, ATK_SPIRITBOW, ATK_CROSSBOW, HEALTH_WARN, HEALTH_CRITICAL,\n\n\t\t\t\tDESCEND, EAT, READ, LULLABY, DRINK, SHATTER, ZAP, LIGHTNING, LEVELUP, DEATH,\n\t\t\t\tCHALLENGE, CURSED, TRAP, EVOKE, TOMB, ALERT, MELD, BOSS, BLAST, PLANT, RAY, BEACON,\n\t\t\t\tTELEPORT, CHARMS, MASTERY, PUFF, ROCKS, BURNING, FALLING, GHOST, SECRET, BONES,\n\t\t\t\tBEE, DEGRADE, MIMIC, DEBUFF, CHARGEUP, GAS, CHAINS, SCAN, SHEEP, MINE\n\t\t};\n\t}\n\n\tpublic static class Splashes {\n\t\tpublic static final String WARRIOR = \"splashes/warrior.jpg\";\n\t\tpublic static final String MAGE = \"splashes/mage.jpg\";\n\t\tpublic static final String ROGUE = \"splashes/rogue.jpg\";\n\t\tpublic static final String HUNTRESS = \"splashes/huntress.jpg\";\n\t\tpublic static final String DUELIST = \"splashes/duelist.jpg\";\n\t\tpublic static final String GUNNER\t= \"splashes/gunner.jpg\";\n\t\tpublic static final String SAMURAI = \"splashes/samurai.jpg\";\n\t\tpublic static final String PLANTER\t= \"splashes/planter.jpg\";\n\t\tpublic static final String KNIGHT\t= \"splashes/knight.jpg\";\n\t\tpublic static final String NURSE\t= \"splashes/nurse.jpg\";\n\t}\n\n\tpublic static class Sprites {\n\t\tpublic static final String ITEMS = \"sprites/items.png\";\n\t\tpublic static final String ITEM_ICONS = \"sprites/item_icons.png\";\n\n\t\tpublic static final String WARRIOR = \"sprites/warrior.png\";\n\t\tpublic static final String MAGE = \"sprites/mage.png\";\n\t\tpublic static final String ROGUE = \"sprites/rogue.png\";\n\t\tpublic static final String HUNTRESS = \"sprites/huntress.png\";\n\t\tpublic static final String DUELIST = \"sprites/duelist.png\";\n\t\tpublic static final String GUNNER\t= \"sprites/gunner.png\";\n\t\tpublic static final String SAMURAI\t= \"sprites/samurai.png\";\n\t\tpublic static final String PLANTER\t= \"sprites/planter.png\";\n\t\tpublic static final String KNIGHT\t= \"sprites/knight.png\";\n\t\tpublic static final String NURSE\t= \"sprites/nurse.png\";\n\t\tpublic static final String AVATARS = \"sprites/avatars.png\";\n\t\tpublic static final String PET = \"sprites/pet.png\";\n\t\tpublic static final String AMULET = \"sprites/amulet.png\";\n\n\t\tpublic static final String RAT = \"sprites/rat.png\";\n\t\tpublic static final String BRUTE = \"sprites/brute.png\";\n\t\tpublic static final String SPINNER = \"sprites/spinner.png\";\n\t\tpublic static final String DM300 = \"sprites/dm300.png\";\n\t\tpublic static final String WRAITH = \"sprites/wraith.png\";\n\t\tpublic static final String UNDEAD = \"sprites/undead.png\";\n\t\tpublic static final String KING = \"sprites/king.png\";\n\t\tpublic static final String PIRANHA = \"sprites/piranha.png\";\n\t\tpublic static final String EYE = \"sprites/eye.png\";\n\t\tpublic static final String GNOLL = \"sprites/gnoll.png\";\n\t\tpublic static final String CRAB = \"sprites/crab.png\";\n\t\tpublic static final String GOO = \"sprites/goo.png\";\n\t\tpublic static final String SWARM = \"sprites/swarm.png\";\n\t\tpublic static final String SKELETON = \"sprites/skeleton.png\";\n\t\tpublic static final String SHAMAN = \"sprites/shaman.png\";\n\t\tpublic static final String THIEF = \"sprites/thief.png\";\n\t\tpublic static final String TENGU = \"sprites/tengu.png\";\n\t\tpublic static final String SHEEP = \"sprites/sheep.png\";\n\t\tpublic static final String KEEPER = \"sprites/shopkeeper.png\";\n\t\tpublic static final String BAT = \"sprites/bat.png\";\n\t\tpublic static final String ELEMENTAL= \"sprites/elemental.png\";\n\t\tpublic static final String MONK = \"sprites/monk.png\";\n\t\tpublic static final String WARLOCK = \"sprites/warlock.png\";\n\t\tpublic static final String GOLEM = \"sprites/golem.png\";\n\t\tpublic static final String STATUE = \"sprites/statue.png\";\n\t\tpublic static final String SUCCUBUS = \"sprites/succubus.png\";\n\t\tpublic static final String SCORPIO = \"sprites/scorpio.png\";\n\t\tpublic static final String FISTS = \"sprites/yog_fists.png\";\n\t\tpublic static final String YOG = \"sprites/yog.png\";\n\t\tpublic static final String LARVA = \"sprites/larva.png\";\n\t\tpublic static final String GHOST = \"sprites/ghost.png\";\n\t\tpublic static final String MAKER = \"sprites/wandmaker.png\";\n\t\tpublic static final String TROLL = \"sprites/blacksmith.png\";\n\t\tpublic static final String IMP = \"sprites/demon.png\";\n\t\tpublic static final String RATKING = \"sprites/ratking.png\";\n\t\tpublic static final String BEE = \"sprites/bee.png\";\n\t\tpublic static final String MIMIC = \"sprites/mimic.png\";\n\t\tpublic static final String ROT_LASH = \"sprites/rot_lasher.png\";\n\t\tpublic static final String ROT_HEART= \"sprites/rot_heart.png\";\n\t\tpublic static final String GUARD = \"sprites/guard.png\";\n\t\tpublic static final String WARDS = \"sprites/wards.png\";\n\t\tpublic static final String GUARDIAN = \"sprites/guardian.png\";\n\t\tpublic static final String SLIME = \"sprites/slime.png\";\n\t\tpublic static final String SNAKE = \"sprites/snake.png\";\n\t\tpublic static final String NECRO = \"sprites/necromancer.png\";\n\t\tpublic static final String GHOUL = \"sprites/ghoul.png\";\n\t\tpublic static final String RIPPER = \"sprites/ripper.png\";\n\t\tpublic static final String SPAWNER = \"sprites/spawner.png\";\n\t\tpublic static final String DM100 = \"sprites/dm100.png\";\n\t\tpublic static final String PYLON = \"sprites/pylon.png\";\n\t\tpublic static final String DM200 = \"sprites/dm200.png\";\n\t\tpublic static final String LOTUS = \"sprites/lotus.png\";\n\t\tpublic static final String NINJA_LOG= \"sprites/ninja_log.png\";\n\t\tpublic static final String SPIRIT_HAWK= \"sprites/spirit_hawk.png\";\n\t\tpublic static final String RED_SENTRY= \"sprites/red_sentry.png\";\n\t\tpublic static final String NEW_SENTRY= \"sprites/new_sentry.png\";\n\t\tpublic static final String CRYSTAL_WISP= \"sprites/crystal_wisp.png\";\n\t\tpublic static final String CRYSTAL_GUARDIAN= \"sprites/crystal_guardian.png\";\n\t\tpublic static final String CRYSTAL_SPIRE= \"sprites/crystal_spire.png\";\n\t\tpublic static final String GNOLL_GUARD= \"sprites/gnoll_guard.png\";\n\n\t\tpublic static final String SOLDIER= \"sprites/soldier.png\";\n\t\tpublic static final String RESEARCHER= \"sprites/researcher.png\";\n\t\tpublic static final String TANK= \"sprites/tank.png\";\n\t\tpublic static final String SUPRESSION= \"sprites/supression.png\";\n\t\tpublic static final String MEDIC= \"sprites/medic.png\";\n\t\tpublic static final String REBEL= \"sprites/rebel.png\";\n\t}\n}" }, { "identifier": "Dungeon", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/Dungeon.java", "snippet": "public class Dungeon {\n\n\t//enum of items which have limited spawns, records how many have spawned\n\t//could all be their own separate numbers, but this allows iterating, much nicer for bundling/initializing.\n\tpublic static enum LimitedDrops {\n\t\t//limited world drops\n\t\tSTRENGTH_POTIONS,\n\t\tUPGRADE_SCROLLS,\n\t\tARCANE_STYLI,\n\n\t\t//Health potion sources\n\t\t//enemies\n\t\tSWARM_HP,\n\t\tNECRO_HP,\n\t\tBAT_HP,\n\t\tWARLOCK_HP,\n\t\t//Demon spawners are already limited in their spawnrate, no need to limit their health drops\n\t\t//alchemy\n\t\tCOOKING_HP,\n\t\tBLANDFRUIT_SEED,\n\n\t\t//Other limited enemy drops\n\t\tSLIME_WEP,\n\t\tSKELE_WEP,\n\t\tTHEIF_MISC,\n\t\tGUARD_ARM,\n\t\tSHAMAN_WAND,\n\t\tDM200_EQUIP,\n\t\tGOLEM_EQUIP,\n\t\tSOLDIER_WEP,\n\t\tMEDIC_HP,\n\n\t\t//containers\n\t\tVELVET_POUCH,\n\t\tSCROLL_HOLDER,\n\t\tPOTION_BANDOLIER,\n\t\tMAGICAL_HOLSTER,\n\n\t\t//lore documents\n\t\tLORE_SEWERS,\n\t\tLORE_PRISON,\n\t\tLORE_CAVES,\n\t\tLORE_CITY,\n\t\tLORE_HALLS,\n\t\tLORE_LABS;\n\n\t\tpublic int count = 0;\n\n\t\t//for items which can only be dropped once, should directly access count otherwise.\n\t\tpublic boolean dropped(){\n\t\t\treturn count != 0;\n\t\t}\n\t\tpublic void drop(){\n\t\t\tcount = 1;\n\t\t}\n\n\t\tpublic static void reset(){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tlim.count = 0;\n\t\t\t}\n\t\t}\n\n\t\tpublic static void store( Bundle bundle ){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tbundle.put(lim.name(), lim.count);\n\t\t\t}\n\t\t}\n\n\t\tpublic static void restore( Bundle bundle ){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tif (bundle.contains(lim.name())){\n\t\t\t\t\tlim.count = bundle.getInt(lim.name());\n\t\t\t\t} else {\n\t\t\t\t\tlim.count = 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\n\t\t\t//pre-v2.2.0 saves\n\t\t\tif (Dungeon.version < 750\n\t\t\t\t\t&& Dungeon.isChallenged(Challenges.NO_SCROLLS)\n\t\t\t\t\t&& UPGRADE_SCROLLS.count > 0){\n\t\t\t\t//we now count SOU fully, and just don't drop every 2nd one\n\t\t\t\tUPGRADE_SCROLLS.count += UPGRADE_SCROLLS.count-1;\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic static int challenges;\n\tpublic static int mobsToChampion;\n\n\tpublic static Hero hero;\n\tpublic static Level level;\n\n\tpublic static QuickSlot quickslot = new QuickSlot();\n\t\n\tpublic static int depth;\n\t//determines path the hero is on. Current uses:\n\t// 0 is the default path\n\t// 1 is for quest sub-floors\n\tpublic static int branch;\n\n\t//keeps track of what levels the game should try to load instead of creating fresh\n\tpublic static ArrayList<Integer> generatedLevels = new ArrayList<>();\n\n\tpublic static int gold;\n\tpublic static int energy;\n\tpublic static int bullet;\n\n\tpublic static HashSet<Integer> chapters;\n\n\tpublic static SparseArray<ArrayList<Item>> droppedItems;\n\n\t//first variable is only assigned when game is started, second is updated every time game is saved\n\tpublic static int initialVersion;\n\tpublic static int version;\n\n\tpublic static boolean daily;\n\tpublic static boolean dailyReplay;\n\tpublic static String customSeedText = \"\";\n\tpublic static long seed;\n\t\n\tpublic static void init() {\n\n\t\tinitialVersion = version = Game.versionCode;\n\t\tchallenges = SPDSettings.challenges();\n\t\tmobsToChampion = -1;\n\n\t\tif (daily) {\n\t\t\t//Ensures that daily seeds are not in the range of user-enterable seeds\n\t\t\tseed = SPDSettings.lastDaily() + DungeonSeed.TOTAL_SEEDS;\n\t\t\tDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ROOT);\n\t\t\tformat.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\t\t\tcustomSeedText = format.format(new Date(SPDSettings.lastDaily()));\n\t\t} else if (!SPDSettings.customSeed().isEmpty()){\n\t\t\tcustomSeedText = SPDSettings.customSeed();\n\t\t\tseed = DungeonSeed.convertFromText(customSeedText);\n\t\t} else {\n\t\t\tcustomSeedText = \"\";\n\t\t\tseed = DungeonSeed.randomSeed();\n\t\t}\n\n\t\tActor.clear();\n\t\tActor.resetNextID();\n\n\t\t//offset seed slightly to avoid output patterns\n\t\tRandom.pushGenerator( seed+1 );\n\n\t\t\tScroll.initLabels();\n\t\t\tPotion.initColors();\n\t\t\tRing.initGems();\n\n\t\t\tSpecialRoom.initForRun();\n\t\t\tSecretRoom.initForRun();\n\n\t\t\tGenerator.fullReset();\n\n\t\tRandom.resetGenerators();\n\t\t\n\t\tStatistics.reset();\n\t\tNotes.reset();\n\n\t\tquickslot.reset();\n\t\tQuickSlotButton.reset();\n\t\tToolbar.swappedQuickslots = false;\n\t\t\n\t\tdepth = 1;\n\t\tbranch = 0;\n\t\tgeneratedLevels.clear();\n\n\t\tgold = 0;\n\t\tenergy = 0;\n\t\tbullet = 0;\n\n\t\tdroppedItems = new SparseArray<>();\n\n\t\tLimitedDrops.reset();\n\t\t\n\t\tchapters = new HashSet<>();\n\t\t\n\t\tGhost.Quest.reset();\n\t\tWandmaker.Quest.reset();\n\t\tBlacksmith.Quest.reset();\n\t\tImp.Quest.reset();\n\n\t\thero = new Hero();\n\t\thero.live();\n\t\t\n\t\tBadges.reset();\n\t\t\n\t\tGamesInProgress.selectedClass.initHero( hero );\n\t}\n\n\tpublic static boolean isChallenged( int mask ) {\n\t\treturn (challenges & mask) != 0;\n\t}\n\n\tpublic static boolean levelHasBeenGenerated(int depth, int branch){\n\t\treturn generatedLevels.contains(depth + 1000*branch);\n\t}\n\t\n\tpublic static Level newLevel() {\n\t\t\n\t\tDungeon.level = null;\n\t\tActor.clear();\n\t\t\n\t\tLevel level;\n\t\tif (branch == 0) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 1:\n\t\t\t\tcase 2:\n\t\t\t\tcase 3:\n\t\t\t\tcase 4:\n\t\t\t\t\tlevel = new SewerLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\tlevel = new SewerBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 6:\n\t\t\t\tcase 7:\n\t\t\t\tcase 8:\n\t\t\t\tcase 9:\n\t\t\t\t\tlevel = new PrisonLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 10:\n\t\t\t\t\tlevel = new PrisonBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 11:\n\t\t\t\tcase 12:\n\t\t\t\tcase 13:\n\t\t\t\tcase 14:\n\t\t\t\t\tlevel = new CavesLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 15:\n\t\t\t\t\tlevel = new CavesBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 16:\n\t\t\t\tcase 17:\n\t\t\t\tcase 18:\n\t\t\t\tcase 19:\n\t\t\t\t\tlevel = new CityLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tlevel = new CityBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 21:\n\t\t\t\tcase 22:\n\t\t\t\tcase 23:\n\t\t\t\tcase 24:\n\t\t\t\t\tlevel = new HallsLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 25:\n\t\t\t\t\tlevel = new HallsBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 26:\n\t\t\t\tcase 27:\n\t\t\t\tcase 28:\n\t\t\t\tcase 29:\n\t\t\t\t\tlevel = new LabsLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 30:\n\t\t\t\t\tlevel = new LabsBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 31:\n\t\t\t\t\tlevel = new NewLastLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else if (branch == 1) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 11:\n\t\t\t\tcase 12:\n\t\t\t\tcase 13:\n\t\t\t\tcase 14:\n\t\t\t\t\tlevel = new MiningLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else if (branch == 2) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 16:\n\t\t\t\tcase 17:\n\t\t\t\tcase 18:\n\t\t\t\tcase 19:\n\t\t\t\t\tlevel = new TempleLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tlevel = new TempleLastLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else {\n\t\t\tlevel = new DeadEndLevel();\n\t\t}\n\n\t\t//dead end levels get cleared, don't count as generated\n\t\tif (!(level instanceof DeadEndLevel)){\n\t\t\t//this assumes that we will never have a depth value outside the range 0 to 999\n\t\t\t// or -500 to 499, etc.\n\t\t\tif (!generatedLevels.contains(depth + 1000*branch)) {\n\t\t\t\tgeneratedLevels.add(depth + 1000 * branch);\n\t\t\t}\n\n\t\t\tif (depth > Statistics.deepestFloor && branch == 0) {\n\t\t\t\tStatistics.deepestFloor = depth;\n\n\t\t\t\tif (Statistics.qualifiedForNoKilling) {\n\t\t\t\t\tStatistics.completedWithNoKilling = true;\n\t\t\t\t} else {\n\t\t\t\t\tStatistics.completedWithNoKilling = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tlevel.create();\n\t\t\n\t\tif (branch == 0) Statistics.qualifiedForNoKilling = !bossLevel();\n\t\tStatistics.qualifiedForBossChallengeBadge = false;\n\t\t\n\t\treturn level;\n\t}\n\t\n\tpublic static void resetLevel() {\n\t\t\n\t\tActor.clear();\n\t\t\n\t\tlevel.reset();\n\t\tswitchLevel( level, level.entrance() );\n\t}\n\n\tpublic static long seedCurDepth(){\n\t\treturn seedForDepth(depth, branch);\n\t}\n\n\tpublic static long seedForDepth(int depth, int branch){\n\t\tint lookAhead = depth;\n\t\tlookAhead += 30*branch; //Assumes depth is always 1-30, and branch is always 0 or higher\n\n\t\tRandom.pushGenerator( seed );\n\n\t\t\tfor (int i = 0; i < lookAhead; i ++) {\n\t\t\t\tRandom.Long(); //we don't care about these values, just need to go through them\n\t\t\t}\n\t\t\tlong result = Random.Long();\n\n\t\tRandom.popGenerator();\n\t\treturn result;\n\t}\n\t\n\tpublic static boolean shopOnLevel() {\n\t\treturn (depth == 6 || depth == 11 || depth == 16 || depth == 26) && branch == 0;\n\t}\n\t\n\tpublic static boolean bossLevel() {\n\t\treturn bossLevel( depth );\n\t}\n\t\n\tpublic static boolean bossLevel( int depth ) {\n\t\treturn depth == 5 || depth == 10 || depth == 15 || depth == 20 || depth == 25|| depth == 30;\n\t}\n\n\t//value used for scaling of damage values and other effects.\n\t//is usually the dungeon depth, but can be set to 26 when ascending\n\tpublic static int scalingDepth(){\n\t\tif (Dungeon.hero != null && Dungeon.hero.buff(AscensionChallenge.class) != null){\n\t\t\treturn 31;\n\t\t} else {\n\t\t\treturn depth;\n\t\t}\n\t}\n\n\tpublic static boolean interfloorTeleportAllowed(){\n\t\tif (Dungeon.level.locked\n\t\t\t\t|| (Dungeon.hero != null && Dungeon.hero.belongings.getItem(Amulet.class) != null)\n\t\t\t\t|| (Dungeon.hero != null && Dungeon.hero.buff(OldAmulet.TempleCurse.class) != null)){\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\n\tpublic static void switchLevel( final Level level, int pos ) {\n\n\t\t//Position of -2 specifically means trying to place the hero the exit\n\t\tif (pos == -2){\n\t\t\tLevelTransition t = level.getTransition(LevelTransition.Type.REGULAR_EXIT);\n\t\t\tif (t != null) pos = t.cell();\n\t\t}\n\n\t\t//Place hero at the entrance if they are out of the map (often used for pox = -1)\n\t\t// or if they are in solid terrain (except in the mining level, where that happens normally)\n\t\tif (pos < 0 || pos >= level.length()\n\t\t\t\t|| (!(level instanceof MiningLevel) && !level.passable[pos] && !level.avoid[pos])){\n\t\t\tpos = level.getTransition(null).cell();\n\t\t}\n\t\t\n\t\tPathFinder.setMapSize(level.width(), level.height());\n\t\t\n\t\tDungeon.level = level;\n\t\thero.pos = pos;\n\n\t\tif (hero.buff(AscensionChallenge.class) != null){\n\t\t\thero.buff(AscensionChallenge.class).onLevelSwitch();\n\t\t}\n\n\t\tif (hero.buff(OldAmulet.TempleCurse.class) != null){\n\t\t\thero.buff(OldAmulet.TempleCurse.class).onLevelSwitch();\n\t\t}\n\n\t\tMob.restoreAllies( level, pos );\n\n\t\tActor.init();\n\n\t\tlevel.addRespawner();\n\t\t\n\t\tfor(Mob m : level.mobs){\n\t\t\tif (m.pos == hero.pos && !Char.hasProp(m, Char.Property.IMMOVABLE)){\n\t\t\t\t//displace mob\n\t\t\t\tfor(int i : PathFinder.NEIGHBOURS8){\n\t\t\t\t\tif (Actor.findChar(m.pos+i) == null && level.passable[m.pos + i]){\n\t\t\t\t\t\tm.pos += i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tLight light = hero.buff( Light.class );\n\t\thero.viewDistance = light == null ? level.viewDistance : Math.max( Light.DISTANCE, level.viewDistance );\n\t\t\n\t\thero.curAction = hero.lastAction = null;\n\n\t\tobserve();\n\t\ttry {\n\t\t\tsaveAll();\n\t\t} catch (IOException e) {\n\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t\t/*This only catches IO errors. Yes, this means things can go wrong, and they can go wrong catastrophically.\n\t\t\tBut when they do the user will get a nice 'report this issue' dialogue, and I can fix the bug.*/\n\t\t}\n\t}\n\n\tpublic static void dropToChasm( Item item ) {\n\t\tint depth = Dungeon.depth + 1;\n\t\tArrayList<Item> dropped = Dungeon.droppedItems.get( depth );\n\t\tif (dropped == null) {\n\t\t\tDungeon.droppedItems.put( depth, dropped = new ArrayList<>() );\n\t\t}\n\t\tdropped.add( item );\n\t}\n\n\tpublic static boolean posNeeded() {\n\t\t//2 POS each floor set\n\t\tint posLeftThisSet = 2 - (LimitedDrops.STRENGTH_POTIONS.count - (depth / 5) * 2);\n\t\tif (posLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\n\t\t//pos drops every two floors, (numbers 1-2, and 3-4) with a 50% chance for the earlier one each time.\n\t\tint targetPOSLeft = 2 - floorThisSet/2;\n\t\tif (floorThisSet % 2 == 1 && Random.Int(2) == 0) targetPOSLeft --;\n\n\t\tif (targetPOSLeft < posLeftThisSet) return true;\n\t\telse return false;\n\n\t}\n\t\n\tpublic static boolean souNeeded() {\n\t\tint souLeftThisSet;\n\t\t//3 SOU each floor set\n\t\tsouLeftThisSet = 3 - (LimitedDrops.UPGRADE_SCROLLS.count - (depth / 5) * 3);\n\t\tif (souLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\t\t//chance is floors left / scrolls left\n\t\treturn Random.Int(5 - floorThisSet) < souLeftThisSet;\n\t}\n\t\n\tpublic static boolean asNeeded() {\n\t\t//1 AS each floor set\n\t\tint asLeftThisSet = 1 - (LimitedDrops.ARCANE_STYLI.count - (depth / 5));\n\t\tif (asLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\t\t//chance is floors left / scrolls left\n\t\treturn Random.Int(5 - floorThisSet) < asLeftThisSet;\n\t}\n\n\tprivate static final String INIT_VER\t= \"init_ver\";\n\tprivate static final String VERSION\t\t= \"version\";\n\tprivate static final String SEED\t\t= \"seed\";\n\tprivate static final String CUSTOM_SEED\t= \"custom_seed\";\n\tprivate static final String DAILY\t = \"daily\";\n\tprivate static final String DAILY_REPLAY= \"daily_replay\";\n\tprivate static final String CHALLENGES\t= \"challenges\";\n\tprivate static final String MOBS_TO_CHAMPION\t= \"mobs_to_champion\";\n\tprivate static final String HERO\t\t= \"hero\";\n\tprivate static final String DEPTH\t\t= \"depth\";\n\tprivate static final String BRANCH\t\t= \"branch\";\n\tprivate static final String GENERATED_LEVELS = \"generated_levels\";\n\tprivate static final String GOLD\t\t= \"gold\";\n\tprivate static final String ENERGY\t\t= \"energy\";\n\tprivate static final String BULLET\t\t= \"bullet\";\n\tprivate static final String DROPPED = \"dropped%d\";\n\tprivate static final String PORTED = \"ported%d\";\n\tprivate static final String LEVEL\t\t= \"level\";\n\tprivate static final String LIMDROPS = \"limited_drops\";\n\tprivate static final String CHAPTERS\t= \"chapters\";\n\tprivate static final String QUESTS\t\t= \"quests\";\n\tprivate static final String BADGES\t\t= \"badges\";\n\n\tpublic static void saveGame( int save ) {\n\t\ttry {\n\t\t\tBundle bundle = new Bundle();\n\n\t\t\tbundle.put( INIT_VER, initialVersion );\n\t\t\tbundle.put( VERSION, version = Game.versionCode );\n\t\t\tbundle.put( SEED, seed );\n\t\t\tbundle.put( CUSTOM_SEED, customSeedText );\n\t\t\tbundle.put( DAILY, daily );\n\t\t\tbundle.put( DAILY_REPLAY, dailyReplay );\n\t\t\tbundle.put( CHALLENGES, challenges );\n\t\t\tbundle.put( MOBS_TO_CHAMPION, mobsToChampion );\n\t\t\tbundle.put( HERO, hero );\n\t\t\tbundle.put( DEPTH, depth );\n\t\t\tbundle.put( BRANCH, branch );\n\n\t\t\tbundle.put( GOLD, gold );\n\t\t\tbundle.put( ENERGY, energy );\n\t\t\tbundle.put( BULLET, bullet );\n\n\t\t\tfor (int d : droppedItems.keyArray()) {\n\t\t\t\tbundle.put(Messages.format(DROPPED, d), droppedItems.get(d));\n\t\t\t}\n\n\t\t\tquickslot.storePlaceholders( bundle );\n\n\t\t\tBundle limDrops = new Bundle();\n\t\t\tLimitedDrops.store( limDrops );\n\t\t\tbundle.put ( LIMDROPS, limDrops );\n\t\t\t\n\t\t\tint count = 0;\n\t\t\tint ids[] = new int[chapters.size()];\n\t\t\tfor (Integer id : chapters) {\n\t\t\t\tids[count++] = id;\n\t\t\t}\n\t\t\tbundle.put( CHAPTERS, ids );\n\t\t\t\n\t\t\tBundle quests = new Bundle();\n\t\t\tGhost\t\t.Quest.storeInBundle( quests );\n\t\t\tWandmaker\t.Quest.storeInBundle( quests );\n\t\t\tBlacksmith\t.Quest.storeInBundle( quests );\n\t\t\tImp\t\t\t.Quest.storeInBundle( quests );\n\t\t\tbundle.put( QUESTS, quests );\n\t\t\t\n\t\t\tSpecialRoom.storeRoomsInBundle( bundle );\n\t\t\tSecretRoom.storeRoomsInBundle( bundle );\n\t\t\t\n\t\t\tStatistics.storeInBundle( bundle );\n\t\t\tNotes.storeInBundle( bundle );\n\t\t\tGenerator.storeInBundle( bundle );\n\n\t\t\tint[] bundleArr = new int[generatedLevels.size()];\n\t\t\tfor (int i = 0; i < generatedLevels.size(); i++){\n\t\t\t\tbundleArr[i] = generatedLevels.get(i);\n\t\t\t}\n\t\t\tbundle.put( GENERATED_LEVELS, bundleArr);\n\t\t\t\n\t\t\tScroll.save( bundle );\n\t\t\tPotion.save( bundle );\n\t\t\tRing.save( bundle );\n\n\t\t\tActor.storeNextID( bundle );\n\t\t\t\n\t\t\tBundle badges = new Bundle();\n\t\t\tBadges.saveLocal( badges );\n\t\t\tbundle.put( BADGES, badges );\n\t\t\t\n\t\t\tFileUtils.bundleToFile( GamesInProgress.gameFile(save), bundle);\n\t\t\t\n\t\t} catch (IOException e) {\n\t\t\tGamesInProgress.setUnknown( save );\n\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t}\n\t}\n\t\n\tpublic static void saveLevel( int save ) throws IOException {\n\t\tBundle bundle = new Bundle();\n\t\tbundle.put( LEVEL, level );\n\t\t\n\t\tFileUtils.bundleToFile(GamesInProgress.depthFile( save, depth, branch ), bundle);\n\t}\n\t\n\tpublic static void saveAll() throws IOException {\n\t\tif (hero != null && (hero.isAlive() || WndResurrect.instance != null)) {\n\t\t\t\n\t\t\tActor.fixTime();\n\t\t\tupdateLevelExplored();\n\t\t\tsaveGame( GamesInProgress.curSlot );\n\t\t\tsaveLevel( GamesInProgress.curSlot );\n\n\t\t\tGamesInProgress.set( GamesInProgress.curSlot );\n\n\t\t}\n\t}\n\t\n\tpublic static void loadGame( int save ) throws IOException {\n\t\tloadGame( save, true );\n\t}\n\t\n\tpublic static void loadGame( int save, boolean fullLoad ) throws IOException {\n\t\t\n\t\tBundle bundle = FileUtils.bundleFromFile( GamesInProgress.gameFile( save ) );\n\n\t\t//pre-1.3.0 saves\n\t\tif (bundle.contains(INIT_VER)){\n\t\t\tinitialVersion = bundle.getInt( INIT_VER );\n\t\t} else {\n\t\t\tinitialVersion = bundle.getInt( VERSION );\n\t\t}\n\n\t\tversion = bundle.getInt( VERSION );\n\n\t\tseed = bundle.contains( SEED ) ? bundle.getLong( SEED ) : DungeonSeed.randomSeed();\n\t\tcustomSeedText = bundle.getString( CUSTOM_SEED );\n\t\tdaily = bundle.getBoolean( DAILY );\n\t\tdailyReplay = bundle.getBoolean( DAILY_REPLAY );\n\n\t\tActor.clear();\n\t\tActor.restoreNextID( bundle );\n\n\t\tquickslot.reset();\n\t\tQuickSlotButton.reset();\n\t\tToolbar.swappedQuickslots = false;\n\n\t\tDungeon.challenges = bundle.getInt( CHALLENGES );\n\t\tDungeon.mobsToChampion = bundle.getInt( MOBS_TO_CHAMPION );\n\t\t\n\t\tDungeon.level = null;\n\t\tDungeon.depth = -1;\n\t\t\n\t\tScroll.restore( bundle );\n\t\tPotion.restore( bundle );\n\t\tRing.restore( bundle );\n\n\t\tquickslot.restorePlaceholders( bundle );\n\t\t\n\t\tif (fullLoad) {\n\t\t\t\n\t\t\tLimitedDrops.restore( bundle.getBundle(LIMDROPS) );\n\n\t\t\tchapters = new HashSet<>();\n\t\t\tint ids[] = bundle.getIntArray( CHAPTERS );\n\t\t\tif (ids != null) {\n\t\t\t\tfor (int id : ids) {\n\t\t\t\t\tchapters.add( id );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tBundle quests = bundle.getBundle( QUESTS );\n\t\t\tif (!quests.isNull()) {\n\t\t\t\tGhost.Quest.restoreFromBundle( quests );\n\t\t\t\tWandmaker.Quest.restoreFromBundle( quests );\n\t\t\t\tBlacksmith.Quest.restoreFromBundle( quests );\n\t\t\t\tImp.Quest.restoreFromBundle( quests );\n\t\t\t} else {\n\t\t\t\tGhost.Quest.reset();\n\t\t\t\tWandmaker.Quest.reset();\n\t\t\t\tBlacksmith.Quest.reset();\n\t\t\t\tImp.Quest.reset();\n\t\t\t}\n\t\t\t\n\t\t\tSpecialRoom.restoreRoomsFromBundle(bundle);\n\t\t\tSecretRoom.restoreRoomsFromBundle(bundle);\n\t\t}\n\t\t\n\t\tBundle badges = bundle.getBundle(BADGES);\n\t\tif (!badges.isNull()) {\n\t\t\tBadges.loadLocal( badges );\n\t\t} else {\n\t\t\tBadges.reset();\n\t\t}\n\t\t\n\t\tNotes.restoreFromBundle( bundle );\n\t\t\n\t\thero = null;\n\t\thero = (Hero)bundle.get( HERO );\n\t\t\n\t\tdepth = bundle.getInt( DEPTH );\n\t\tbranch = bundle.getInt( BRANCH );\n\n\t\tgold = bundle.getInt( GOLD );\n\t\tenergy = bundle.getInt( ENERGY );\n\t\tbullet = bundle.getInt( BULLET );\n\n\t\tStatistics.restoreFromBundle( bundle );\n\t\tGenerator.restoreFromBundle( bundle );\n\n\t\tgeneratedLevels.clear();\n\t\tif (bundle.contains(GENERATED_LEVELS)){\n\t\t\tfor (int i : bundle.getIntArray(GENERATED_LEVELS)){\n\t\t\t\tgeneratedLevels.add(i);\n\t\t\t}\n\t\t//pre-v2.1.1 saves\n\t\t} else {\n\t\t\tfor (int i = 1; i <= Statistics.deepestFloor; i++){\n\t\t\t\tgeneratedLevels.add(i);\n\t\t\t}\n\t\t}\n\n\t\tdroppedItems = new SparseArray<>();\n\t\tfor (int i=1; i <= 31; i++) {\n\t\t\t\n\t\t\t//dropped items\n\t\t\tArrayList<Item> items = new ArrayList<>();\n\t\t\tif (bundle.contains(Messages.format( DROPPED, i )))\n\t\t\t\tfor (Bundlable b : bundle.getCollection( Messages.format( DROPPED, i ) ) ) {\n\t\t\t\t\titems.add( (Item)b );\n\t\t\t\t}\n\t\t\tif (!items.isEmpty()) {\n\t\t\t\tdroppedItems.put( i, items );\n\t\t\t}\n\n\t\t}\n\t}\n\t\n\tpublic static Level loadLevel( int save ) throws IOException {\n\t\t\n\t\tDungeon.level = null;\n\t\tActor.clear();\n\n\t\tBundle bundle = FileUtils.bundleFromFile( GamesInProgress.depthFile( save, depth, branch ));\n\n\t\tLevel level = (Level)bundle.get( LEVEL );\n\n\t\tif (level == null){\n\t\t\tthrow new IOException();\n\t\t} else {\n\t\t\treturn level;\n\t\t}\n\t}\n\t\n\tpublic static void deleteGame( int save, boolean deleteLevels ) {\n\n\t\tif (deleteLevels) {\n\t\t\tString folder = GamesInProgress.gameFolder(save);\n\t\t\tfor (String file : FileUtils.filesInDir(folder)){\n\t\t\t\tif (file.contains(\"depth\")){\n\t\t\t\t\tFileUtils.deleteFile(folder + \"/\" + file);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tFileUtils.overwriteFile(GamesInProgress.gameFile(save), 1);\n\t\t\n\t\tGamesInProgress.delete( save );\n\t}\n\t\n\tpublic static void preview( GamesInProgress.Info info, Bundle bundle ) {\n\t\tinfo.depth = bundle.getInt( DEPTH );\n\t\tinfo.version = bundle.getInt( VERSION );\n\t\tinfo.challenges = bundle.getInt( CHALLENGES );\n\t\tinfo.seed = bundle.getLong( SEED );\n\t\tinfo.customSeed = bundle.getString( CUSTOM_SEED );\n\t\tinfo.daily = bundle.getBoolean( DAILY );\n\t\tinfo.dailyReplay = bundle.getBoolean( DAILY_REPLAY );\n\n\t\tHero.preview( info, bundle.getBundle( HERO ) );\n\t\tStatistics.preview( info, bundle );\n\t}\n\t\n\tpublic static void fail( Object cause ) {\n\t\tif (WndResurrect.instance == null) {\n\t\t\tupdateLevelExplored();\n\t\t\tStatistics.gameWon = false;\n\t\t\tRankings.INSTANCE.submit( false, cause );\n\t\t}\n\t}\n\t\n\tpublic static void win( Object cause ) {\n\n\t\tupdateLevelExplored();\n\t\tStatistics.gameWon = true;\n\n\t\thero.belongings.identify();\n\n\t\tRankings.INSTANCE.submit( true, cause );\n\t}\n\n\tpublic static void updateLevelExplored(){\n\t\tif (branch == 0 && level instanceof RegularLevel && !Dungeon.bossLevel()){\n\t\t\tStatistics.floorsExplored.put( depth, level.isLevelExplored(depth));\n\t\t}\n\t}\n\n\t//default to recomputing based on max hero vision, in case vision just shrank/grew\n\tpublic static void observe(){\n\t\tint dist = Math.max(Dungeon.hero.viewDistance, 8);\n\t\tdist *= 1f + 0.25f*Dungeon.hero.pointsInTalent(Talent.FARSIGHT);\n\t\tdist *= 1f + 0.25f*Dungeon.hero.pointsInTalent(Talent.TELESCOPE);\n\n\t\tif (Dungeon.hero.buff(MagicalSight.class) != null){\n\t\t\tdist = Math.max( dist, MagicalSight.DISTANCE );\n\t\t}\n\n\t\tobserve( dist+1 );\n\t}\n\t\n\tpublic static void observe( int dist ) {\n\n\t\tif (level == null) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlevel.updateFieldOfView(hero, level.heroFOV);\n\n\t\tint x = hero.pos % level.width();\n\t\tint y = hero.pos / level.width();\n\t\n\t\t//left, right, top, bottom\n\t\tint l = Math.max( 0, x - dist );\n\t\tint r = Math.min( x + dist, level.width() - 1 );\n\t\tint t = Math.max( 0, y - dist );\n\t\tint b = Math.min( y + dist, level.height() - 1 );\n\t\n\t\tint width = r - l + 1;\n\t\tint height = b - t + 1;\n\t\t\n\t\tint pos = l + t * level.width();\n\t\n\t\tfor (int i = t; i <= b; i++) {\n\t\t\tBArray.or( level.visited, level.heroFOV, pos, width, level.visited );\n\t\t\tpos+=level.width();\n\t\t}\n\t\n\t\tGameScene.updateFog(l, t, width, height);\n\n\t\tif (hero.buff(MindVision.class) != null){\n\t\t\tfor (Mob m : level.mobs.toArray(new Mob[0])){\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1 - level.width(), 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1, 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1 + level.width(), 3, level.visited );\n\t\t\t\t//updates adjacent cells too\n\t\t\t\tGameScene.updateFog(m.pos, 2);\n\t\t\t}\n\t\t}\n\n\t\tif (hero.buff(Awareness.class) != null){\n\t\t\tfor (Heap h : level.heaps.valueList()){\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 - level.width(), 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1, 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 + level.width(), 3, level.visited );\n\t\t\t\tGameScene.updateFog(h.pos, 2);\n\t\t\t}\n\t\t}\n\n\t\tfor (TalismanOfForesight.CharAwareness c : hero.buffs(TalismanOfForesight.CharAwareness.class)){\n\t\t\tChar ch = (Char) Actor.findById(c.charID);\n\t\t\tif (ch == null || !ch.isAlive()) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(ch.pos, 2);\n\t\t}\n\n\t\tfor (TalismanOfForesight.HeapAwareness h : hero.buffs(TalismanOfForesight.HeapAwareness.class)){\n\t\t\tif (Dungeon.depth != h.depth || Dungeon.branch != h.branch) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(h.pos, 2);\n\t\t}\n\n\t\tfor (RevealedArea a : hero.buffs(RevealedArea.class)){\n\t\t\tif (Dungeon.depth != a.depth || Dungeon.branch != a.branch) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(a.pos, 2);\n\t\t}\n\n\t\tfor (Char ch : Actor.chars()){\n\t\t\tif (ch instanceof WandOfWarding.Ward\n\t\t\t\t\t|| ch instanceof WandOfRegrowth.Lotus\n\t\t\t\t\t|| ch instanceof SpiritHawk.HawkAlly){\n\t\t\t\tx = ch.pos % level.width();\n\t\t\t\ty = ch.pos / level.width();\n\n\t\t\t\t//left, right, top, bottom\n\t\t\t\tdist = ch.viewDistance+1;\n\t\t\t\tl = Math.max( 0, x - dist );\n\t\t\t\tr = Math.min( x + dist, level.width() - 1 );\n\t\t\t\tt = Math.max( 0, y - dist );\n\t\t\t\tb = Math.min( y + dist, level.height() - 1 );\n\n\t\t\t\twidth = r - l + 1;\n\t\t\t\theight = b - t + 1;\n\n\t\t\t\tpos = l + t * level.width();\n\n\t\t\t\tfor (int i = t; i <= b; i++) {\n\t\t\t\t\tBArray.or( level.visited, level.heroFOV, pos, width, level.visited );\n\t\t\t\t\tpos+=level.width();\n\t\t\t\t}\n\t\t\t\tGameScene.updateFog(ch.pos, dist);\n\t\t\t}\n\t\t}\n\n\t\tGameScene.afterObserve();\n\t}\n\n\t//we store this to avoid having to re-allocate the array with each pathfind\n\tprivate static boolean[] passable;\n\n\tprivate static void setupPassable(){\n\t\tif (passable == null || passable.length != Dungeon.level.length())\n\t\t\tpassable = new boolean[Dungeon.level.length()];\n\t\telse\n\t\t\tBArray.setFalse(passable);\n\t}\n\n\tpublic static boolean[] findPassable(Char ch, boolean[] pass, boolean[] vis, boolean chars){\n\t\treturn findPassable(ch, pass, vis, chars, chars);\n\t}\n\n\tpublic static boolean[] findPassable(Char ch, boolean[] pass, boolean[] vis, boolean chars, boolean considerLarge){\n\t\tsetupPassable();\n\t\tif (ch.flying || ch.buff( Amok.class ) != null) {\n\t\t\tBArray.or( pass, Dungeon.level.avoid, passable );\n\t\t} else {\n\t\t\tSystem.arraycopy( pass, 0, passable, 0, Dungeon.level.length() );\n\t\t}\n\n\t\tif (considerLarge && Char.hasProp(ch, Char.Property.LARGE)){\n\t\t\tBArray.and( passable, Dungeon.level.openSpace, passable );\n\t\t}\n\n\t\tch.modifyPassable(passable);\n\n\t\tif (chars) {\n\t\t\tfor (Char c : Actor.chars()) {\n\t\t\t\tif (vis[c.pos]) {\n\t\t\t\t\tpassable[c.pos] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn passable;\n\t}\n\n\tpublic static PathFinder.Path findPath(Char ch, int to, boolean[] pass, boolean[] vis, boolean chars) {\n\n\t\treturn PathFinder.find( ch.pos, to, findPassable(ch, pass, vis, chars) );\n\n\t}\n\t\n\tpublic static int findStep(Char ch, int to, boolean[] pass, boolean[] visible, boolean chars ) {\n\n\t\tif (Dungeon.level.adjacent( ch.pos, to )) {\n\t\t\treturn Actor.findChar( to ) == null && pass[to] ? to : -1;\n\t\t}\n\n\t\treturn PathFinder.getStep( ch.pos, to, findPassable(ch, pass, visible, chars) );\n\n\t}\n\t\n\tpublic static int flee( Char ch, int from, boolean[] pass, boolean[] visible, boolean chars ) {\n\t\tboolean[] passable = findPassable(ch, pass, visible, false, true);\n\t\tpassable[ch.pos] = true;\n\n\t\t//only consider other chars impassable if our retreat step may collide with them\n\t\tif (chars) {\n\t\t\tfor (Char c : Actor.chars()) {\n\t\t\t\tif (c.pos == from || Dungeon.level.adjacent(c.pos, ch.pos)) {\n\t\t\t\t\tpassable[c.pos] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//chars affected by terror have a shorter lookahead and can't approach the fear source\n\t\tboolean canApproachFromPos = ch.buff(Terror.class) == null && ch.buff(Dread.class) == null;\n\t\treturn PathFinder.getStepBack( ch.pos, from, canApproachFromPos ? 8 : 4, passable, canApproachFromPos );\n\t\t\n\t}\n\n}" }, { "identifier": "Actor", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/Actor.java", "snippet": "public abstract class Actor implements Bundlable {\n\t\n\tpublic static final float TICK\t= 1f;\n\n\tprivate float time;\n\n\tprivate int id = 0;\n\n\t//default priority values for general actor categories\n\t//note that some specific actors pick more specific values\n\t//e.g. a buff acting after all normal buffs might have priority BUFF_PRIO + 1\n\tprotected static final int VFX_PRIO = 100; //visual effects take priority\n\tprotected static final int HERO_PRIO = 0; //positive is before hero, negative after\n\tprotected static final int BLOB_PRIO = -10; //blobs act after hero, before mobs\n\tprotected static final int MOB_PRIO = -20; //mobs act between buffs and blobs\n\tprotected static final int BUFF_PRIO = -30; //buffs act last in a turn\n\tprivate static final int DEFAULT = -100; //if no priority is given, act after all else\n\n\t//used to determine what order actors act in if their time is equal. Higher values act earlier.\n\tprotected int actPriority = DEFAULT;\n\n\tprotected abstract boolean act();\n\n\t//Always spends exactly the specified amount of time, regardless of time-influencing factors\n\tprotected void spendConstant( float time ){\n\t\tthis.time += time;\n\t\t//if time is very close to a whole number, round to a whole number to fix errors\n\t\tfloat ex = Math.abs(this.time % 1f);\n\t\tif (ex < .001f){\n\t\t\tthis.time = Math.round(this.time);\n\t\t}\n\t}\n\n\t//sends time, but the amount can be influenced\n\tprotected void spend( float time ) {\n\t\tspendConstant( time );\n\t}\n\n\tpublic void spendToWhole(){\n\t\ttime = (float)Math.ceil(time);\n\t}\n\t\n\tprotected void postpone( float time ) {\n\t\tif (this.time < now + time) {\n\t\t\tthis.time = now + time;\n\t\t\t//if time is very close to a whole number, round to a whole number to fix errors\n\t\t\tfloat ex = Math.abs(this.time % 1f);\n\t\t\tif (ex < .001f){\n\t\t\t\tthis.time = Math.round(this.time);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic float cooldown() {\n\t\treturn time - now;\n\t}\n\n\tpublic void clearTime() {\n\t\ttime = 0;\n\t}\n\n\tpublic void timeToNow() {\n\t\ttime = now;\n\t}\n\t\n\tprotected void diactivate() {\n\t\ttime = Float.MAX_VALUE;\n\t}\n\t\n\tprotected void onAdd() {}\n\t\n\tprotected void onRemove() {}\n\n\tprivate static final String TIME = \"time\";\n\tprivate static final String ID = \"id\";\n\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tbundle.put( TIME, time );\n\t\tbundle.put( ID, id );\n\t}\n\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\ttime = bundle.getFloat( TIME );\n\t\tint incomingID = bundle.getInt( ID );\n\t\tif (Actor.findById(incomingID) == null){\n\t\t\tid = incomingID;\n\t\t} else {\n\t\t\tid = nextID++;\n\t\t}\n\t}\n\n\tpublic int id() {\n\t\tif (id > 0) {\n\t\t\treturn id;\n\t\t} else {\n\t\t\treturn (id = nextID++);\n\t\t}\n\t}\n\n\t// **********************\n\t// *** Static members ***\n\t// **********************\n\t\n\tprivate static HashSet<Actor> all = new HashSet<>();\n\tprivate static HashSet<Char> chars = new HashSet<>();\n\tprivate static volatile Actor current;\n\n\tprivate static SparseArray<Actor> ids = new SparseArray<>();\n\tprivate static int nextID = 1;\n\n\tprivate static float now = 0;\n\t\n\tpublic static float now(){\n\t\treturn now;\n\t}\n\t\n\tpublic static synchronized void clear() {\n\t\t\n\t\tnow = 0;\n\n\t\tall.clear();\n\t\tchars.clear();\n\n\t\tids.clear();\n\t}\n\n\tpublic static synchronized void fixTime() {\n\t\t\n\t\tif (all.isEmpty()) return;\n\t\t\n\t\tfloat min = Float.MAX_VALUE;\n\t\tfor (Actor a : all) {\n\t\t\tif (a.time < min) {\n\t\t\t\tmin = a.time;\n\t\t\t}\n\t\t}\n\n\t\t//Only pull everything back by whole numbers\n\t\t//So that turns always align with a whole number\n\t\tmin = (int)min;\n\t\tfor (Actor a : all) {\n\t\t\ta.time -= min;\n\t\t}\n\n\t\tif (Dungeon.hero != null && all.contains( Dungeon.hero )) {\n\t\t\tStatistics.duration += min;\n\t\t}\n\t\tnow -= min;\n\t}\n\t\n\tpublic static void init() {\n\t\t\n\t\tadd( Dungeon.hero );\n\t\t\n\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\tadd( mob );\n\t\t}\n\n\t\t//mobs need to remember their targets after every actor is added\n\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\tmob.restoreEnemy();\n\t\t}\n\t\t\n\t\tfor (Blob blob : Dungeon.level.blobs.values()) {\n\t\t\tadd( blob );\n\t\t}\n\t\t\n\t\tcurrent = null;\n\t}\n\n\tprivate static final String NEXTID = \"nextid\";\n\n\tpublic static void storeNextID( Bundle bundle){\n\t\tbundle.put( NEXTID, nextID );\n\t}\n\n\tpublic static void restoreNextID( Bundle bundle){\n\t\tnextID = bundle.getInt( NEXTID );\n\t}\n\n\tpublic static void resetNextID(){\n\t\tnextID = 1;\n\t}\n\n\t/*protected*/public void next() {\n\t\tif (current == this) {\n\t\t\tcurrent = null;\n\t\t}\n\t}\n\n\tpublic static boolean processing(){\n\t\treturn current != null;\n\t}\n\n\tpublic static int curActorPriority() {\n\t\treturn current != null ? current.actPriority : DEFAULT;\n\t}\n\t\n\tpublic static boolean keepActorThreadAlive = true;\n\t\n\tpublic static void process() {\n\t\t\n\t\tboolean doNext;\n\t\tboolean interrupted = false;\n\n\t\tdo {\n\t\t\t\n\t\t\tcurrent = null;\n\t\t\tif (!interrupted) {\n\t\t\t\tfloat earliest = Float.MAX_VALUE;\n\n\t\t\t\tfor (Actor actor : all) {\n\t\t\t\t\t\n\t\t\t\t\t//some actors will always go before others if time is equal.\n\t\t\t\t\tif (actor.time < earliest ||\n\t\t\t\t\t\t\tactor.time == earliest && (current == null || actor.actPriority > current.actPriority)) {\n\t\t\t\t\t\tearliest = actor.time;\n\t\t\t\t\t\tcurrent = actor;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (current != null) {\n\n\t\t\t\tnow = current.time;\n\t\t\t\tActor acting = current;\n\n\t\t\t\tif (acting instanceof Char && ((Char) acting).sprite != null) {\n\t\t\t\t\t// If it's character's turn to act, but its sprite\n\t\t\t\t\t// is moving, wait till the movement is over\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsynchronized (((Char)acting).sprite) {\n\t\t\t\t\t\t\tif (((Char)acting).sprite.isMoving) {\n\t\t\t\t\t\t\t\t((Char) acting).sprite.wait();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\tinterrupted = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tinterrupted = interrupted || Thread.interrupted();\n\t\t\t\t\n\t\t\t\tif (interrupted){\n\t\t\t\t\tdoNext = false;\n\t\t\t\t\tcurrent = null;\n\t\t\t\t} else {\n\t\t\t\t\tdoNext = acting.act();\n\t\t\t\t\tif (doNext && (Dungeon.hero == null || !Dungeon.hero.isAlive())) {\n\t\t\t\t\t\tdoNext = false;\n\t\t\t\t\t\tcurrent = null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdoNext = false;\n\t\t\t}\n\n\t\t\tif (!doNext){\n\t\t\t\tsynchronized (Thread.currentThread()) {\n\t\t\t\t\t\n\t\t\t\t\tinterrupted = interrupted || Thread.interrupted();\n\t\t\t\t\t\n\t\t\t\t\tif (interrupted){\n\t\t\t\t\t\tcurrent = null;\n\t\t\t\t\t\tinterrupted = false;\n\t\t\t\t\t}\n\n\t\t\t\t\t//signals to the gamescene that actor processing is finished for now\n\t\t\t\t\tThread.currentThread().notify();\n\t\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\tThread.currentThread().wait();\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\tinterrupted = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t} while (keepActorThreadAlive);\n\t}\n\t\n\tpublic static void add( Actor actor ) {\n\t\tadd( actor, now );\n\t}\n\t\n\tpublic static void addDelayed( Actor actor, float delay ) {\n\t\tadd( actor, now + Math.max(delay, 0) );\n\t}\n\t\n\tprivate static synchronized void add( Actor actor, float time ) {\n\t\t\n\t\tif (all.contains( actor )) {\n\t\t\treturn;\n\t\t}\n\n\t\tids.put( actor.id(), actor );\n\n\t\tall.add( actor );\n\t\tactor.time += time;\n\t\tactor.onAdd();\n\t\t\n\t\tif (actor instanceof Char) {\n\t\t\tChar ch = (Char)actor;\n\t\t\tchars.add( ch );\n\t\t\tfor (Buff buff : ch.buffs()) {\n\t\t\t\tadd(buff);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static synchronized void remove( Actor actor ) {\n\t\t\n\t\tif (actor != null) {\n\t\t\tall.remove( actor );\n\t\t\tchars.remove( actor );\n\t\t\tactor.onRemove();\n\n\t\t\tif (actor.id > 0) {\n\t\t\t\tids.remove( actor.id );\n\t\t\t}\n\t\t}\n\t}\n\n\t//'freezes' a character in time for a specified amount of time\n\t//USE CAREFULLY! Manipulating time like this is useful for some gameplay effects but is tricky\n\tpublic static void delayChar( Char ch, float time ){\n\t\tch.spendConstant(time);\n\t\tfor (Buff b : ch.buffs()){\n\t\t\tb.spendConstant(time);\n\t\t}\n\t}\n\t\n\tpublic static synchronized Char findChar( int pos ) {\n\t\tfor (Char ch : chars){\n\t\t\tif (ch.pos == pos)\n\t\t\t\treturn ch;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static synchronized Actor findById( int id ) {\n\t\treturn ids.get( id );\n\t}\n\n\tpublic static synchronized HashSet<Actor> all() {\n\t\treturn new HashSet<>(all);\n\t}\n\n\tpublic static synchronized HashSet<Char> chars() { return new HashSet<>(chars); }\n}" }, { "identifier": "Char", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/Char.java", "snippet": "public abstract class Char extends Actor {\n\t\n\tpublic int pos = 0;\n\t\n\tpublic CharSprite sprite;\n\t\n\tpublic int HT;\n\tpublic int HP;\n\t\n\tprotected float baseSpeed\t= 1;\n\tprotected PathFinder.Path path;\n\n\tpublic int paralysed\t = 0;\n\tpublic boolean rooted\t\t= false;\n\tpublic boolean flying\t\t= false;\n\tpublic int invisible\t\t= 0;\n\t\n\t//these are relative to the hero\n\tpublic enum Alignment{\n\t\tENEMY,\n\t\tNEUTRAL,\n\t\tALLY\n\t}\n\tpublic Alignment alignment;\n\t\n\tpublic int viewDistance\t= 8;\n\t\n\tpublic boolean[] fieldOfView = null;\n\t\n\tprivate LinkedHashSet<Buff> buffs = new LinkedHashSet<>();\n\t\n\t@Override\n\tprotected boolean act() {\n\t\tif (fieldOfView == null || fieldOfView.length != Dungeon.level.length()){\n\t\t\tfieldOfView = new boolean[Dungeon.level.length()];\n\t\t}\n\t\tDungeon.level.updateFieldOfView( this, fieldOfView );\n\n\t\t//throw any items that are on top of an immovable char\n\t\tif (properties().contains(Property.IMMOVABLE)){\n\t\t\tthrowItems();\n\t\t}\n\t\treturn false;\n\t}\n\n\tprotected void throwItems(){\n\t\tHeap heap = Dungeon.level.heaps.get( pos );\n\t\tif (heap != null && heap.type == Heap.Type.HEAP\n\t\t\t\t&& !(heap.peek() instanceof Tengu.BombAbility.BombItem)\n\t\t\t\t&& !(heap.peek() instanceof Tengu.ShockerAbility.ShockerItem)) {\n\t\t\tArrayList<Integer> candidates = new ArrayList<>();\n\t\t\tfor (int n : PathFinder.NEIGHBOURS8){\n\t\t\t\tif (Dungeon.level.passable[pos+n]){\n\t\t\t\t\tcandidates.add(pos+n);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!candidates.isEmpty()){\n\t\t\t\tDungeon.level.drop( heap.pickUp(), Random.element(candidates) ).sprite.drop( pos );\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic String name(){\n\t\treturn Messages.get(this, \"name\");\n\t}\n\n\tpublic boolean canInteract(Char c){\n\t\tif (Dungeon.level.adjacent( pos, c.pos )){\n\t\t\treturn true;\n\t\t} else if (c instanceof Hero\n\t\t\t\t&& alignment == Alignment.ALLY\n\t\t\t\t&& Dungeon.level.distance(pos, c.pos) <= 2*Dungeon.hero.pointsInTalent(Talent.ALLY_WARP)){\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t//swaps places by default\n\tpublic boolean interact(Char c){\n\n\t\t//don't allow char to swap onto hazard unless they're flying\n\t\t//you can swap onto a hazard though, as you're not the one instigating the swap\n\t\tif (!Dungeon.level.passable[pos] && !c.flying){\n\t\t\treturn true;\n\t\t}\n\n\t\t//can't swap into a space without room\n\t\tif (properties().contains(Property.LARGE) && !Dungeon.level.openSpace[c.pos]\n\t\t\t|| c.properties().contains(Property.LARGE) && !Dungeon.level.openSpace[pos]){\n\t\t\treturn true;\n\t\t}\n\n\t\t//we do a little raw position shuffling here so that the characters are never\n\t\t// on the same cell when logic such as occupyCell() is triggered\n\t\tint oldPos = pos;\n\t\tint newPos = c.pos;\n\n\t\t//warp instantly with allies in this case\n\t\tif (c == Dungeon.hero && Dungeon.hero.hasTalent(Talent.ALLY_WARP)){\n\t\t\tPathFinder.buildDistanceMap(c.pos, BArray.or(Dungeon.level.passable, Dungeon.level.avoid, null));\n\t\t\tif (PathFinder.distance[pos] == Integer.MAX_VALUE){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tpos = newPos;\n\t\t\tc.pos = oldPos;\n\t\t\tScrollOfTeleportation.appear(this, newPos);\n\t\t\tScrollOfTeleportation.appear(c, oldPos);\n\t\t\tDungeon.observe();\n\t\t\tGameScene.updateFog();\n\t\t\treturn true;\n\t\t}\n\n\t\t//can't swap places if one char has restricted movement\n\t\tif (rooted || c.rooted || buff(Vertigo.class) != null || c.buff(Vertigo.class) != null){\n\t\t\treturn true;\n\t\t}\n\n\t\tc.pos = oldPos;\n\t\tmoveSprite( oldPos, newPos );\n\t\tmove( newPos );\n\n\t\tc.pos = newPos;\n\t\tc.sprite.move( newPos, oldPos );\n\t\tc.move( oldPos );\n\t\t\n\t\tc.spend( 1 / c.speed() );\n\n\t\tif (c == Dungeon.hero){\n\t\t\tif (Dungeon.hero.subClass == HeroSubClass.FREERUNNER){\n\t\t\t\tBuff.affect(Dungeon.hero, Momentum.class).gainStack();\n\t\t\t}\n\n\t\t\tDungeon.hero.busy();\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t\n\tprotected boolean moveSprite( int from, int to ) {\n\t\t\n\t\tif (sprite.isVisible() && sprite.parent != null && (Dungeon.level.heroFOV[from] || Dungeon.level.heroFOV[to])) {\n\t\t\tsprite.move( from, to );\n\t\t\treturn true;\n\t\t} else {\n\t\t\tsprite.turnTo(from, to);\n\t\t\tsprite.place( to );\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic void hitSound( float pitch ){\n\t\tSample.INSTANCE.play(Assets.Sounds.HIT, 1, pitch);\n\t}\n\n\tpublic boolean blockSound( float pitch ) {\n\t\treturn false;\n\t}\n\t\n\tprotected static final String POS = \"pos\";\n\tprotected static final String TAG_HP = \"HP\";\n\tprotected static final String TAG_HT = \"HT\";\n\tprotected static final String TAG_SHLD = \"SHLD\";\n\tprotected static final String BUFFS\t = \"buffs\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.storeInBundle( bundle );\n\t\t\n\t\tbundle.put( POS, pos );\n\t\tbundle.put( TAG_HP, HP );\n\t\tbundle.put( TAG_HT, HT );\n\t\tbundle.put( BUFFS, buffs );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.restoreFromBundle( bundle );\n\t\t\n\t\tpos = bundle.getInt( POS );\n\t\tHP = bundle.getInt( TAG_HP );\n\t\tHT = bundle.getInt( TAG_HT );\n\t\t\n\t\tfor (Bundlable b : bundle.getCollection( BUFFS )) {\n\t\t\tif (b != null) {\n\t\t\t\t((Buff)b).attachTo( this );\n\t\t\t}\n\t\t}\n\t}\n\n\tfinal public boolean attack( Char enemy ){\n\t\treturn attack(enemy, 1f, 0f, 1f);\n\t}\n\t\n\tpublic boolean attack( Char enemy, float dmgMulti, float dmgBonus, float accMulti ) {\n\n\t\tif (enemy == null) return false;\n\t\t\n\t\tboolean visibleFight = Dungeon.level.heroFOV[pos] || Dungeon.level.heroFOV[enemy.pos];\n\n\t\tif (enemy.isInvulnerable(getClass())) {\n\n\t\t\tif (visibleFight) {\n\t\t\t\tenemy.sprite.showStatus( CharSprite.POSITIVE, Messages.get(this, \"invulnerable\") );\n\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1f, Random.Float(0.96f, 1.05f));\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (hit( this, enemy, accMulti, false )) {\n\t\t\t\n\t\t\tint dr = Math.round(enemy.drRoll() * AscensionChallenge.statModifier(enemy));\n\t\t\t\n\t\t\tif (this instanceof Hero){\n\t\t\t\tHero h = (Hero)this;\n\t\t\t\tif (h.belongings.attackingWeapon() instanceof MissileWeapon\n\t\t\t\t\t\t&& h.subClass == HeroSubClass.SNIPER\n\t\t\t\t\t\t&& !Dungeon.level.adjacent(h.pos, enemy.pos)){\n\t\t\t\t\tdr = 0;\n\t\t\t\t}\n\n\t\t\t\tif (h.belongings.attackingWeapon() instanceof Gun.Bullet) {\n\t\t\t\t\tdr *= ((Gun.Bullet) h.belongings.attackingWeapon()).whatBullet().armorFactor();\n\t\t\t\t}\n\n\t\t\t\tif (h.buff(MonkEnergy.MonkAbility.UnarmedAbilityTracker.class) != null){\n\t\t\t\t\tdr = 0;\n\t\t\t\t} else if (h.subClass == HeroSubClass.MONK) {\n\t\t\t\t\t//3 turns with standard attack delay\n\t\t\t\t\tBuff.prolong(h, MonkEnergy.MonkAbility.JustHitTracker.class, 4f);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//we use a float here briefly so that we don't have to constantly round while\n\t\t\t// potentially applying various multiplier effects\n\t\t\tfloat dmg;\n\t\t\tPreparation prep = buff(Preparation.class);\n\t\t\tif (prep != null){\n\t\t\t\tdmg = prep.damageRoll(this);\n\t\t\t\tif (this == Dungeon.hero && Dungeon.hero.hasTalent(Talent.BOUNTY_HUNTER)) {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.BountyHunterTracker.class, 0.0f);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdmg = damageRoll();\n\t\t\t}\n\n\t\t\tdmg = Math.round(dmg*dmgMulti);\n\n\t\t\tBerserk berserk = buff(Berserk.class);\n\t\t\tif (berserk != null) dmg = berserk.damageFactor(dmg);\n\n\t\t\tif (buff( Fury.class ) != null) {\n\t\t\t\tdmg *= 1.5f;\n\t\t\t}\n\n\t\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\t\tdmg *= buff.meleeDamageFactor();\n\t\t\t}\n\n\t\t\tdmg *= AscensionChallenge.statModifier(this);\n\n\t\t\t//flat damage bonus is applied after positive multipliers, but before negative ones\n\t\t\tdmg += dmgBonus;\n\n\t\t\t//friendly endure\n\t\t\tEndure.EndureTracker endure = buff(Endure.EndureTracker.class);\n\t\t\tif (endure != null) dmg = endure.damageFactor(dmg);\n\n\t\t\t//enemy endure\n\t\t\tendure = enemy.buff(Endure.EndureTracker.class);\n\t\t\tif (endure != null){\n\t\t\t\tdmg = endure.adjustDamageTaken(dmg);\n\t\t\t}\n\n\t\t\tif (enemy.buff(ScrollOfChallenge.ChallengeArena.class) != null){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\n\t\t\tif (enemy.buff(MonkEnergy.MonkAbility.Meditate.MeditateResistance.class) != null){\n\t\t\t\tdmg *= 0.2f;\n\t\t\t}\n\n\t\t\tif ( buff(Weakness.class) != null ){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\n\t\t\tif ( buff(SoulMark.class) != null && hero.hasTalent(Talent.MARK_OF_WEAKNESS)) {\n\t\t\t\tif (this.alignment != Alignment.ALLY) {\n\t\t\t\t\tdmg *= Math.pow(0.9f, hero.pointsInTalent(Talent.MARK_OF_WEAKNESS));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tint effectiveDamage = enemy.defenseProc( this, Math.round(dmg) );\n\t\t\t//do not trigger on-hit logic if defenseProc returned a negative value\n\t\t\tif (effectiveDamage >= 0) {\n\t\t\t\teffectiveDamage = Math.max(effectiveDamage - dr, 0);\n\n\t\t\t\tif (enemy.buff(Viscosity.ViscosityTracker.class) != null) {\n\t\t\t\t\teffectiveDamage = enemy.buff(Viscosity.ViscosityTracker.class).deferDamage(effectiveDamage);\n\t\t\t\t\tenemy.buff(Viscosity.ViscosityTracker.class).detach();\n\t\t\t\t}\n\n\t\t\t\t//vulnerable specifically applies after armor reductions\n\t\t\t\tif (enemy.buff(Vulnerable.class) != null) {\n\t\t\t\t\teffectiveDamage *= 1.33f;\n\t\t\t\t}\n\n\t\t\t\teffectiveDamage = attackProc(enemy, effectiveDamage);\n\t\t\t}\n\t\t\tif (visibleFight) {\n\t\t\t\tif (effectiveDamage > 0 || !enemy.blockSound(Random.Float(0.96f, 1.05f))) {\n\t\t\t\t\thitSound(Random.Float(0.87f, 1.15f));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If the enemy is already dead, interrupt the attack.\n\t\t\t// This matters as defence procs can sometimes inflict self-damage, such as armor glyphs.\n\t\t\tif (!enemy.isAlive()){\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tenemy.damage( effectiveDamage, this );\n\n\t\t\tif (buff(FireImbue.class) != null) buff(FireImbue.class).proc(enemy);\n\t\t\tif (buff(FrostImbue.class) != null) buff(FrostImbue.class).proc(enemy);\n\t\t\tif (buff(ThunderImbue.class) != null) buff(ThunderImbue.class).proc(enemy, (int)dmg);\n\n\t\t\tif (enemy.isAlive() && enemy.alignment != alignment && prep != null && prep.canKO(enemy)){\n\t\t\t\tenemy.HP = 0;\n\t\t\t\tif (!enemy.isAlive()) {\n\t\t\t\t\tenemy.die(this);\n\t\t\t\t} else {\n\t\t\t\t\t//helps with triggering any on-damage effects that need to activate\n\t\t\t\t\tenemy.damage(-1, this);\n\t\t\t\t\tDeathMark.processFearTheReaper(enemy);\n\t\t\t\t}\n\t\t\t\tif (enemy.sprite != null) {\n\t\t\t\t\tenemy.sprite.showStatus(CharSprite.NEGATIVE, Messages.get(Preparation.class, \"assassinated\"));\n\t\t\t\t}\n\t\t\t\tif (Random.Float() < hero.pointsInTalent(Talent.ENERGY_DRAW)/3f) {\n\t\t\t\t\tCloakOfShadows cloak = hero.belongings.getItem(CloakOfShadows.class);\n\t\t\t\t\tif (cloak != null) {\n\t\t\t\t\t\tcloak.overCharge(1);\n\t\t\t\t\t\tScrollOfRecharging.charge(Dungeon.hero);\n\t\t\t\t\t\tSpellSprite.show(hero, SpellSprite.CHARGE);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tTalent.CombinedLethalityTriggerTracker combinedLethality = buff(Talent.CombinedLethalityTriggerTracker.class);\n\t\t\tif (combinedLethality != null){\n\t\t\t\tif ( enemy.isAlive() && enemy.alignment != alignment && !Char.hasProp(enemy, Property.BOSS)\n\t\t\t\t\t\t&& !Char.hasProp(enemy, Property.MINIBOSS) && this instanceof Hero &&\n\t\t\t\t\t\t(enemy.HP/(float)enemy.HT) <= 0.4f*((Hero)this).pointsInTalent(Talent.COMBINED_LETHALITY)/3f) {\n\t\t\t\t\tenemy.HP = 0;\n\t\t\t\t\tif (!enemy.isAlive()) {\n\t\t\t\t\t\tenemy.die(this);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//helps with triggering any on-damage effects that need to activate\n\t\t\t\t\t\tenemy.damage(-1, this);\n\t\t\t\t\t\tDeathMark.processFearTheReaper(enemy);\n\t\t\t\t\t}\n\t\t\t\t\tif (enemy.sprite != null) {\n\t\t\t\t\t\tenemy.sprite.showStatus(CharSprite.NEGATIVE, Messages.get(Talent.CombinedLethalityTriggerTracker.class, \"executed\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcombinedLethality.detach();\n\t\t\t}\n\n\t\t\tif (enemy.sprite != null) {\n\t\t\t\tenemy.sprite.bloodBurstA(sprite.center(), effectiveDamage);\n\t\t\t\tenemy.sprite.flash();\n\t\t\t}\n\n\t\t\tif (!enemy.isAlive() && visibleFight) {\n\t\t\t\tif (enemy == Dungeon.hero) {\n\t\t\t\t\t\n\t\t\t\t\tif (this == Dungeon.hero) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this instanceof WandOfLivingEarth.EarthGuardian\n\t\t\t\t\t\t\t|| this instanceof MirrorImage || this instanceof PrismaticImage){\n\t\t\t\t\t\tBadges.validateDeathFromFriendlyMagic();\n\t\t\t\t\t}\n\t\t\t\t\tDungeon.fail( this );\n\t\t\t\t\tGLog.n( Messages.capitalize(Messages.get(Char.class, \"kill\", name())) );\n\t\t\t\t\t\n\t\t\t\t} else if (this == Dungeon.hero) {\n\t\t\t\t\tGLog.i( Messages.capitalize(Messages.get(Char.class, \"defeat\", enemy.name())) );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t\t\n\t\t} else {\n\n\t\t\tif (enemy instanceof Hero) {\n\t\t\t\tif (hero.pointsInTalent(Talent.SWIFT_MOVEMENT) == 3) {\n\t\t\t\t\tBuff.prolong(hero, Invisibility.class, 1.0001f);\n\t\t\t\t}\n\t\t\t\tif (Random.Int(5) < hero.pointsInTalent(Talent.COUNTER_ATTACK)) {\n\t\t\t\t\tBuff.affect(hero, Talent.CounterAttackTracker.class);\n\t\t\t\t}\n\t\t\t\tif (hero.hasTalent(Talent.QUICK_PREP)) {\n\t\t\t\t\tMomentum momentum = hero.buff(Momentum.class);\n\t\t\t\t\tif (momentum != null) {\n\t\t\t\t\t\tmomentum.quickPrep(hero.pointsInTalent(Talent.QUICK_PREP));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tenemy.sprite.showStatus( CharSprite.NEUTRAL, enemy.defenseVerb() );\n\t\t\tif (visibleFight) {\n\t\t\t\t//TODO enemy.defenseSound? currently miss plays for monks/crab even when they parry\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.MISS);\n\t\t\t}\n\t\t\t\n\t\t\treturn false;\n\t\t\t\n\t\t}\n\t}\n\n\tpublic static int INFINITE_ACCURACY = 1_000_000;\n\tpublic static int INFINITE_EVASION = 1_000_000;\n\n\tfinal public static boolean hit( Char attacker, Char defender, boolean magic ) {\n\t\treturn hit(attacker, defender, magic ? 2f : 1f, magic);\n\t}\n\n\tpublic static boolean hit( Char attacker, Char defender, float accMulti, boolean magic ) {\n\t\tfloat acuStat = attacker.attackSkill( defender );\n\t\tfloat defStat = defender.defenseSkill( attacker );\n\n\t\tif (defender instanceof Hero && ((Hero) defender).damageInterrupt){\n\t\t\t((Hero) defender).interrupt();\n\t\t}\n\n\t\t//invisible chars always hit (for the hero this is surprise attacking)\n\t\tif (attacker.invisible > 0 && attacker.canSurpriseAttack()){\n\t\t\tacuStat = INFINITE_ACCURACY;\n\t\t}\n\n\t\tif (defender.buff(MonkEnergy.MonkAbility.Focus.FocusBuff.class) != null && !magic){\n\t\t\tdefStat = INFINITE_EVASION;\n\t\t\tdefender.buff(MonkEnergy.MonkAbility.Focus.FocusBuff.class).detach();\n\t\t\tBuff.affect(defender, MonkEnergy.MonkAbility.Focus.FocusActivation.class, 0);\n\t\t}\n\n\t\t//if accuracy or evasion are large enough, treat them as infinite.\n\t\t//note that infinite evasion beats infinite accuracy\n\t\tif (defStat >= INFINITE_EVASION){\n\t\t\treturn false;\n\t\t} else if (acuStat >= INFINITE_ACCURACY){\n\t\t\treturn true;\n\t\t}\n\n\t\tfloat acuRoll = Random.Float( acuStat );\n\t\tif (attacker.buff(Bless.class) != null) acuRoll *= 1.25f;\n\t\tif (attacker.buff( Hex.class) != null) acuRoll *= 0.8f;\n\t\tif (attacker.buff( Daze.class) != null) acuRoll *= 0.5f;\n\t\tfor (ChampionEnemy buff : attacker.buffs(ChampionEnemy.class)){\n\t\t\tacuRoll *= buff.evasionAndAccuracyFactor();\n\t\t}\n\t\tacuRoll *= AscensionChallenge.statModifier(attacker);\n\t\t\n\t\tfloat defRoll = Random.Float( defStat );\n\t\tif (defender.buff(Bless.class) != null) defRoll *= 1.25f;\n\t\tif (defender.buff( Hex.class) != null) defRoll *= 0.8f;\n\t\tif (defender.buff( Daze.class) != null) defRoll *= 0.5f;\n\t\tfor (ChampionEnemy buff : defender.buffs(ChampionEnemy.class)){\n\t\t\tdefRoll *= buff.evasionAndAccuracyFactor();\n\t\t}\n\t\tdefRoll *= AscensionChallenge.statModifier(defender);\n\t\t\n\t\treturn (acuRoll * accMulti) >= defRoll;\n\t}\n\t\n\tpublic int attackSkill( Char target ) {\n\t\treturn 0;\n\t}\n\t\n\tpublic int defenseSkill( Char enemy ) {\n\t\treturn 0;\n\t}\n\t\n\tpublic String defenseVerb() {\n\t\treturn Messages.get(this, \"def_verb\");\n\t}\n\t\n\tpublic int drRoll() {\n\t\tint dr = 0;\n\n\t\tdr += Random.NormalIntRange( 0 , Barkskin.currentLevel(this) );\n\n\t\treturn dr;\n\t}\n\t\n\tpublic int damageRoll() {\n\t\treturn 1;\n\t}\n\t\n\t//TODO it would be nice to have a pre-armor and post-armor proc.\n\t// atm attack is always post-armor and defence is already pre-armor\n\t\n\tpublic int attackProc( Char enemy, int damage ) {\n\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\tbuff.onAttackProc( enemy );\n\t\t}\n\t\treturn damage;\n\t}\n\t\n\tpublic int defenseProc( Char enemy, int damage ) {\n\n\t\tEarthroot.Armor armor = buff( Earthroot.Armor.class );\n\t\tif (armor != null) {\n\t\t\tdamage = armor.absorb( damage );\n\t\t}\n\n\t\treturn damage;\n\t}\n\t\n\tpublic float speed() {\n\t\tfloat speed = baseSpeed;\n\t\tif ( buff( Cripple.class ) != null ) speed /= 2f;\n\t\tif ( buff( Stamina.class ) != null) speed *= 1.5f;\n\t\tif ( buff( Adrenaline.class ) != null) speed *= 2f;\n\t\tif ( buff( Haste.class ) != null) speed *= 3f;\n\t\tif ( buff( Dread.class ) != null) speed *= 2f;\n\t\treturn speed;\n\t}\n\n\t//currently only used by invisible chars, or by the hero\n\tpublic boolean canSurpriseAttack(){\n\t\treturn true;\n\t}\n\t\n\t//used so that buffs(Shieldbuff.class) isn't called every time unnecessarily\n\tprivate int cachedShield = 0;\n\tpublic boolean needsShieldUpdate = true;\n\t\n\tpublic int shielding(){\n\t\tif (!needsShieldUpdate){\n\t\t\treturn cachedShield;\n\t\t}\n\t\t\n\t\tcachedShield = 0;\n\t\tfor (ShieldBuff s : buffs(ShieldBuff.class)){\n\t\t\tcachedShield += s.shielding();\n\t\t}\n\t\tneedsShieldUpdate = false;\n\t\treturn cachedShield;\n\t}\n\t\n\tpublic void damage( int dmg, Object src ) {\n\t\t\n\t\tif (!isAlive() || dmg < 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tif(isInvulnerable(src.getClass())){\n\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.get(this, \"invulnerable\"));\n\t\t\treturn;\n\t\t}\n\n\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\tdmg = (int) Math.ceil(dmg * buff.damageTakenFactor());\n\t\t}\n\n\t\tif (!(src instanceof LifeLink) && buff(LifeLink.class) != null){\n\t\t\tHashSet<LifeLink> links = buffs(LifeLink.class);\n\t\t\tfor (LifeLink link : links.toArray(new LifeLink[0])){\n\t\t\t\tif (Actor.findById(link.object) == null){\n\t\t\t\t\tlinks.remove(link);\n\t\t\t\t\tlink.detach();\n\t\t\t\t}\n\t\t\t}\n\t\t\tdmg = (int)Math.ceil(dmg / (float)(links.size()+1));\n\t\t\tfor (LifeLink link : links){\n\t\t\t\tChar ch = (Char)Actor.findById(link.object);\n\t\t\t\tif (ch != null) {\n\t\t\t\t\tch.damage(dmg, link);\n\t\t\t\t\tif (!ch.isAlive()) {\n\t\t\t\t\t\tlink.detach();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tTerror t = buff(Terror.class);\n\t\tif (t != null){\n\t\t\tt.recover();\n\t\t}\n\t\tDread d = buff(Dread.class);\n\t\tif (d != null){\n\t\t\td.recover();\n\t\t}\n\t\tCharm c = buff(Charm.class);\n\t\tif (c != null){\n\t\t\tc.recover(src);\n\t\t}\n\t\tif (this.buff(Frost.class) != null){\n\t\t\tBuff.detach( this, Frost.class );\n\t\t}\n\t\tif (this.buff(MagicalSleep.class) != null){\n\t\t\tBuff.detach(this, MagicalSleep.class);\n\t\t}\n\t\tif (this.buff(Doom.class) != null && !isImmune(Doom.class)){\n\t\t\tdmg *= 1.67f;\n\t\t}\n\t\tif (alignment != Alignment.ALLY && this.buff(DeathMark.DeathMarkTracker.class) != null){\n\t\t\tdmg *= 1.25f;\n\t\t}\n\t\t\n\t\tClass<?> srcClass = src.getClass();\n\t\tif (isImmune( srcClass )) {\n\t\t\tdmg = 0;\n\t\t} else {\n\t\t\tdmg = Math.round( dmg * resist( srcClass ));\n\t\t}\n\t\t\n\t\t//TODO improve this when I have proper damage source logic\n\t\tif (AntiMagic.RESISTS.contains(src.getClass()) && buff(ArcaneArmor.class) != null){\n\t\t\tdmg -= Random.NormalIntRange(0, buff(ArcaneArmor.class).level());\n\t\t\tif (dmg < 0) dmg = 0;\n\t\t}\n\n\t\tif (buff(Sickle.HarvestBleedTracker.class) != null){\n\t\t\tif (isImmune(Bleeding.class)){\n\t\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.titleCase(Messages.get(this, \"immune\")));\n\t\t\t\tbuff(Sickle.HarvestBleedTracker.class).detach();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tBleeding b = buff(Bleeding.class);\n\t\t\tif (b == null){\n\t\t\t\tb = new Bleeding();\n\t\t\t}\n\t\t\tb.announced = false;\n\t\t\tb.set(dmg*buff(Sickle.HarvestBleedTracker.class).bleedFactor, Sickle.HarvestBleedTracker.class);\n\t\t\tb.attachTo(this);\n\t\t\tsprite.showStatus(CharSprite.WARNING, Messages.titleCase(b.name()) + \" \" + (int)b.level());\n\t\t\tbuff(Sickle.HarvestBleedTracker.class).detach();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (buff( Paralysis.class ) != null) {\n\t\t\tbuff( Paralysis.class ).processDamage(dmg);\n\t\t}\n\n\t\tint shielded = dmg;\n\t\t//FIXME: when I add proper damage properties, should add an IGNORES_SHIELDS property to use here.\n\t\tif (!(src instanceof Hunger)){\n\t\t\tfor (ShieldBuff s : buffs(ShieldBuff.class)){\n\t\t\t\tdmg = s.absorbDamage(dmg);\n\t\t\t\tif (dmg == 0) break;\n\t\t\t}\n\t\t}\n\t\tshielded -= dmg;\n\t\tHP -= dmg;\n\n\t\tif (HP > 0 && buff(Grim.GrimTracker.class) != null){\n\n\t\t\tfloat finalChance = buff(Grim.GrimTracker.class).maxChance;\n\t\t\tfinalChance *= (float)Math.pow( ((HT - HP) / (float)HT), 2);\n\n\t\t\tif (Random.Float() < finalChance) {\n\t\t\t\tint extraDmg = Math.round(HP*resist(Grim.class));\n\t\t\t\tdmg += extraDmg;\n\t\t\t\tHP -= extraDmg;\n\n\t\t\t\tsprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\tif (!isAlive() && buff(Grim.GrimTracker.class).qualifiesForBadge){\n\t\t\t\t\tBadges.validateGrimWeapon();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (HP < 0 && src instanceof Char && alignment == Alignment.ENEMY){\n\t\t\tif (((Char) src).buff(Kinetic.KineticTracker.class) != null){\n\t\t\t\tint dmgToAdd = -HP;\n\t\t\t\tdmgToAdd -= ((Char) src).buff(Kinetic.KineticTracker.class).conservedDamage;\n\t\t\t\tdmgToAdd = Math.round(dmgToAdd * Weapon.Enchantment.genericProcChanceMultiplier((Char) src));\n\t\t\t\tif (dmgToAdd > 0) {\n\t\t\t\t\tBuff.affect((Char) src, Kinetic.ConservedDamage.class).setBonus(dmgToAdd);\n\t\t\t\t}\n\t\t\t\t((Char) src).buff(Kinetic.KineticTracker.class).detach();\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (sprite != null) {\n\t\t\tsprite.showStatus(HP > HT / 2 ?\n\t\t\t\t\t\t\tCharSprite.WARNING :\n\t\t\t\t\t\t\tCharSprite.NEGATIVE,\n\t\t\t\t\tInteger.toString(dmg + shielded));\n\t\t}\n\n\t\tif (HP < 0) HP = 0;\n\n\t\tif (!isAlive()) {\n\t\t\tdie( src );\n\t\t} else if (HP == 0 && buff(DeathMark.DeathMarkTracker.class) != null){\n\t\t\tDeathMark.processFearTheReaper(this);\n\t\t}\n\t}\n\t\n\tpublic void destroy() {\n\t\tHP = 0;\n\t\tActor.remove( this );\n\n\t\tfor (Char ch : Actor.chars().toArray(new Char[0])){\n\t\t\tif (ch.buff(Charm.class) != null && ch.buff(Charm.class).object == id()){\n\t\t\t\tch.buff(Charm.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Dread.class) != null && ch.buff(Dread.class).object == id()){\n\t\t\t\tch.buff(Dread.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Terror.class) != null && ch.buff(Terror.class).object == id()){\n\t\t\t\tch.buff(Terror.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(SnipersMark.class) != null && ch.buff(SnipersMark.class).object == id()){\n\t\t\t\tch.buff(SnipersMark.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Talent.FollowupStrikeTracker.class) != null\n\t\t\t\t\t&& ch.buff(Talent.FollowupStrikeTracker.class).object == id()){\n\t\t\t\tch.buff(Talent.FollowupStrikeTracker.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Talent.DeadlyFollowupTracker.class) != null\n\t\t\t\t\t&& ch.buff(Talent.DeadlyFollowupTracker.class).object == id()){\n\t\t\t\tch.buff(Talent.DeadlyFollowupTracker.class).detach();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void die( Object src ) {\n\t\tdestroy();\n\t\tif (src != Chasm.class) sprite.die();\n\t}\n\n\t//we cache this info to prevent having to call buff(...) in isAlive.\n\t//This is relevant because we call isAlive during drawing, which has both performance\n\t//and thread coordination implications\n\tpublic boolean deathMarked = false;\n\t\n\tpublic boolean isAlive() {\n\t\treturn HP > 0 || deathMarked;\n\t}\n\n\tpublic boolean isActive() {\n\t\treturn isAlive();\n\t}\n\n\t@Override\n\tprotected void spendConstant(float time) {\n\t\tTimekeepersHourglass.timeFreeze freeze = buff(TimekeepersHourglass.timeFreeze.class);\n\t\tif (freeze != null) {\n\t\t\tfreeze.processTime(time);\n\t\t\treturn;\n\t\t}\n\n\t\tSwiftthistle.TimeBubble bubble = buff(Swiftthistle.TimeBubble.class);\n\t\tif (bubble != null){\n\t\t\tbubble.processTime(time);\n\t\t\treturn;\n\t\t}\n\n\t\tsuper.spendConstant(time);\n\t}\n\n\t@Override\n\tprotected void spend( float time ) {\n\n\t\tfloat timeScale = 1f;\n\t\tif (buff( Slow.class ) != null) {\n\t\t\ttimeScale *= 0.5f;\n\t\t\t//slowed and chilled do not stack\n\t\t} else if (buff( Chill.class ) != null) {\n\t\t\ttimeScale *= buff( Chill.class ).speedFactor();\n\t\t}\n\t\tif (buff( Speed.class ) != null) {\n\t\t\ttimeScale *= 2.0f;\n\t\t}\n\t\t\n\t\tsuper.spend( time / timeScale );\n\t}\n\t\n\tpublic synchronized LinkedHashSet<Buff> buffs() {\n\t\treturn new LinkedHashSet<>(buffs);\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\t//returns all buffs assignable from the given buff class\n\tpublic synchronized <T extends Buff> HashSet<T> buffs( Class<T> c ) {\n\t\tHashSet<T> filtered = new HashSet<>();\n\t\tfor (Buff b : buffs) {\n\t\t\tif (c.isInstance( b )) {\n\t\t\t\tfiltered.add( (T)b );\n\t\t\t}\n\t\t}\n\t\treturn filtered;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t//returns an instance of the specific buff class, if it exists. Not just assignable\n\tpublic synchronized <T extends Buff> T buff( Class<T> c ) {\n\t\tfor (Buff b : buffs) {\n\t\t\tif (b.getClass() == c) {\n\t\t\t\treturn (T)b;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic synchronized boolean isCharmedBy( Char ch ) {\n\t\tint chID = ch.id();\n\t\tfor (Buff b : buffs) {\n\t\t\tif (b instanceof Charm && ((Charm)b).object == chID) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic synchronized boolean add( Buff buff ) {\n\n\t\tif (buff(PotionOfCleansing.Cleanse.class) != null) { //cleansing buff\n\t\t\tif (buff.type == Buff.buffType.NEGATIVE\n\t\t\t\t\t&& !(buff instanceof AllyBuff)\n\t\t\t\t\t&& !(buff instanceof LostInventory)){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tif (sprite != null && buff(Challenge.SpectatorFreeze.class) != null){\n\t\t\treturn false; //can't add buffs while frozen and game is loaded\n\t\t}\n\n\t\tbuffs.add( buff );\n\t\tif (Actor.chars().contains(this)) Actor.add( buff );\n\n\t\tif (sprite != null && buff.announced) {\n\t\t\tswitch (buff.type) {\n\t\t\t\tcase POSITIVE:\n\t\t\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NEGATIVE:\n\t\t\t\t\tsprite.showStatus(CharSprite.NEGATIVE, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NEUTRAL:\n\t\t\t\tdefault:\n\t\t\t\t\tsprite.showStatus(CharSprite.NEUTRAL, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\n\t}\n\t\n\tpublic synchronized boolean remove( Buff buff ) {\n\t\t\n\t\tbuffs.remove( buff );\n\t\tActor.remove( buff );\n\n\t\treturn true;\n\t}\n\t\n\tpublic synchronized void remove( Class<? extends Buff> buffClass ) {\n\t\tfor (Buff buff : buffs( buffClass )) {\n\t\t\tremove( buff );\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected synchronized void onRemove() {\n\t\tfor (Buff buff : buffs.toArray(new Buff[buffs.size()])) {\n\t\t\tbuff.detach();\n\t\t}\n\t}\n\t\n\tpublic synchronized void updateSpriteState() {\n\t\tfor (Buff buff:buffs) {\n\t\t\tbuff.fx( true );\n\t\t}\n\t}\n\t\n\tpublic float stealth() {\n\t\treturn 0;\n\t}\n\n\tpublic final void move( int step ) {\n\t\tmove( step, true );\n\t}\n\n\t//travelling may be false when a character is moving instantaneously, such as via teleportation\n\tpublic void move( int step, boolean travelling ) {\n\n\t\tif (travelling && Dungeon.level.adjacent( step, pos ) && buff( Vertigo.class ) != null) {\n\t\t\tsprite.interruptMotion();\n\t\t\tint newPos = pos + PathFinder.NEIGHBOURS8[Random.Int( 8 )];\n\t\t\tif (!(Dungeon.level.passable[newPos] || Dungeon.level.avoid[newPos])\n\t\t\t\t\t|| (properties().contains(Property.LARGE) && !Dungeon.level.openSpace[newPos])\n\t\t\t\t\t|| Actor.findChar( newPos ) != null)\n\t\t\t\treturn;\n\t\t\telse {\n\t\t\t\tsprite.move(pos, newPos);\n\t\t\t\tstep = newPos;\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.level.map[pos] == Terrain.OPEN_DOOR) {\n\t\t\tDoor.leave( pos );\n\t\t}\n\n\t\tpos = step;\n\t\t\n\t\tif (this != Dungeon.hero) {\n\t\t\tsprite.visible = Dungeon.level.heroFOV[pos];\n\t\t}\n\t\t\n\t\tDungeon.level.occupyCell(this );\n\t}\n\t\n\tpublic int distance( Char other ) {\n\t\treturn Dungeon.level.distance( pos, other.pos );\n\t}\n\n\tpublic boolean[] modifyPassable( boolean[] passable){\n\t\t//do nothing by default, but some chars can pass over terrain that others can't\n\t\treturn passable;\n\t}\n\t\n\tpublic void onMotionComplete() {\n\t\t//Does nothing by default\n\t\t//The main actor thread already accounts for motion,\n\t\t// so calling next() here isn't necessary (see Actor.process)\n\t}\n\t\n\tpublic void onAttackComplete() {\n\t\tnext();\n\t}\n\t\n\tpublic void onOperateComplete() {\n\t\tnext();\n\t}\n\t\n\tprotected final HashSet<Class> resistances = new HashSet<>();\n\t\n\t//returns percent effectiveness after resistances\n\t//TODO currently resistances reduce effectiveness by a static 50%, and do not stack.\n\tpublic float resist( Class effect ){\n\t\tHashSet<Class> resists = new HashSet<>(resistances);\n\t\tfor (Property p : properties()){\n\t\t\tresists.addAll(p.resistances());\n\t\t}\n\t\tfor (Buff b : buffs()){\n\t\t\tresists.addAll(b.resistances());\n\t\t}\n\t\t\n\t\tfloat result = 1f;\n\t\tfor (Class c : resists){\n\t\t\tif (c.isAssignableFrom(effect)){\n\t\t\t\tresult *= 0.5f;\n\t\t\t}\n\t\t}\n\t\treturn result * RingOfElements.resist(this, effect);\n\t}\n\t\n\tprotected final HashSet<Class> immunities = new HashSet<>();\n\t\n\tpublic boolean isImmune(Class effect ){\n\t\tHashSet<Class> immunes = new HashSet<>(immunities);\n\t\tfor (Property p : properties()){\n\t\t\timmunes.addAll(p.immunities());\n\t\t}\n\t\tfor (Buff b : buffs()){\n\t\t\timmunes.addAll(b.immunities());\n\t\t}\n\t\t\n\t\tfor (Class c : immunes){\n\t\t\tif (c.isAssignableFrom(effect)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t//similar to isImmune, but only factors in damage.\n\t//Is used in AI decision-making\n\tpublic boolean isInvulnerable( Class effect ){\n\t\treturn buff(Challenge.SpectatorFreeze.class) != null;\n\t}\n\n\tprotected HashSet<Property> properties = new HashSet<>();\n\n\tpublic HashSet<Property> properties() {\n\t\tHashSet<Property> props = new HashSet<>(properties);\n\t\t//TODO any more of these and we should make it a property of the buff, like with resistances/immunities\n\t\tif (buff(ChampionEnemy.Giant.class) != null) {\n\t\t\tprops.add(Property.LARGE);\n\t\t}\n\t\treturn props;\n\t}\n\n\tpublic enum Property{\n\t\tBOSS ( new HashSet<Class>( Arrays.asList(Grim.class, GrimTrap.class, ScrollOfRetribution.class, ScrollOfPsionicBlast.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(AllyBuff.class, Dread.class) )),\n\t\tMINIBOSS ( new HashSet<Class>(),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(AllyBuff.class, Dread.class) )),\n\t\tBOSS_MINION,\n\t\tUNDEAD,\n\t\tDEMONIC,\n\t\tINORGANIC ( new HashSet<Class>(),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Bleeding.class, ToxicGas.class, Poison.class) )),\n\t\tFIERY ( new HashSet<Class>( Arrays.asList(WandOfFireblast.class, Elemental.FireElemental.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Burning.class, Blazing.class))),\n\t\tICY ( new HashSet<Class>( Arrays.asList(WandOfFrost.class, Elemental.FrostElemental.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Frost.class, Chill.class))),\n\t\tACIDIC ( new HashSet<Class>( Arrays.asList(Corrosion.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Ooze.class))),\n\t\tELECTRIC ( new HashSet<Class>( Arrays.asList(WandOfLightning.class, Shocking.class, Potential.class, Electricity.class, ShockingDart.class, Elemental.ShockElemental.class )),\n\t\t\t\tnew HashSet<Class>()),\n\t\tLARGE,\n\t\tIMMOVABLE;\n\t\t\n\t\tprivate HashSet<Class> resistances;\n\t\tprivate HashSet<Class> immunities;\n\t\t\n\t\tProperty(){\n\t\t\tthis(new HashSet<Class>(), new HashSet<Class>());\n\t\t}\n\t\t\n\t\tProperty( HashSet<Class> resistances, HashSet<Class> immunities){\n\t\t\tthis.resistances = resistances;\n\t\t\tthis.immunities = immunities;\n\t\t}\n\t\t\n\t\tpublic HashSet<Class> resistances(){\n\t\t\treturn new HashSet<>(resistances);\n\t\t}\n\t\t\n\t\tpublic HashSet<Class> immunities(){\n\t\t\treturn new HashSet<>(immunities);\n\t\t}\n\n\t}\n\n\tpublic static boolean hasProp( Char ch, Property p){\n\t\treturn (ch != null && ch.properties().contains(p));\n\t}\n\n\tpublic void heal(int amount) {\n\t\tamount = Math.min( amount, this.HT - this.HP );\n\t\tif (amount > 0 && this.isAlive()) {\n\t\t\tthis.HP += amount;\n\t\t\tthis.sprite.emitter().start( Speck.factory( Speck.HEALING ), 0.4f, 1 );\n\t\t\tthis.sprite.showStatus( CharSprite.POSITIVE, Integer.toString( amount ) );\n\t\t}\n\t}\n}" }, { "identifier": "Invisibility", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Invisibility.java", "snippet": "public class Invisibility extends FlavourBuff {\n\n\tpublic static final float DURATION\t= 20f;\n\n\t{\n\t\ttype = buffType.POSITIVE;\n\t\tannounced = true;\n\t}\n\t\n\t@Override\n\tpublic boolean attachTo( Char target ) {\n\t\tif (super.attachTo( target )) {\n\t\t\ttarget.invisible++;\n\t\t\tif (target instanceof Hero && ((Hero) target).subClass == HeroSubClass.ASSASSIN){\n\t\t\t\tBuff.affect(target, Preparation.class);\n\t\t\t}\n\t\t\tif (target instanceof Hero && ((Hero) target).hasTalent(Talent.PROTECTIVE_SHADOWS)){\n\t\t\t\tBuff.affect(target, Talent.ProtectiveShadowsTracker.class);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void detach() {\n\t\tif (target.invisible > 0)\n\t\t\ttarget.invisible--;\n\t\tsuper.detach();\n\t}\n\t\n\t@Override\n\tpublic int icon() {\n\t\treturn BuffIndicator.INVISIBLE;\n\t}\n\n\t@Override\n\tpublic float iconFadePercent() {\n\t\treturn Math.max(0, (DURATION - visualcooldown()) / DURATION);\n\t}\n\n\t@Override\n\tpublic void fx(boolean on) {\n\t\tif (on) target.sprite.add( CharSprite.State.INVISIBLE );\n\t\telse if (target.invisible == 0) target.sprite.remove( CharSprite.State.INVISIBLE );\n\t}\n\n\tpublic static void dispel() {\n\t\tif (Dungeon.hero == null) return;\n\n\t\tdispel(Dungeon.hero);\n\t}\n\n\tpublic static void dispel(Char ch){\n\n\t\tfor ( Buff invis : ch.buffs( Invisibility.class )){\n\t\t\tinvis.detach();\n\t\t}\n\t\tCloakOfShadows.cloakStealth cloakBuff = ch.buff( CloakOfShadows.cloakStealth.class );\n\t\tif (cloakBuff != null) {\n\t\t\tcloakBuff.dispel();\n\t\t}\n\n\t\t//these aren't forms of invisibility, but do dispel at the same time as it.\n\t\tTimekeepersHourglass.timeFreeze timeFreeze = ch.buff( TimekeepersHourglass.timeFreeze.class );\n\t\tif (timeFreeze != null) {\n\t\t\ttimeFreeze.detach();\n\t\t}\n\n\t\tPreparation prep = ch.buff( Preparation.class );\n\t\tif (prep != null){\n\t\t\tprep.detach();\n\t\t}\n\n\t\tSwiftthistle.TimeBubble bubble = ch.buff( Swiftthistle.TimeBubble.class );\n\t\tif (bubble != null){\n\t\t\tbubble.detach();\n\t\t}\n\t}\n}" }, { "identifier": "Hero", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/hero/Hero.java", "snippet": "public class Hero extends Char {\n\n\t{\n\t\tactPriority = HERO_PRIO;\n\t\t\n\t\talignment = Alignment.ALLY;\n\t}\n\t\n\tpublic static final int MAX_LEVEL = 30;\n\n\tpublic static final int STARTING_STR = 10;\n\t\n\tprivate static final float TIME_TO_REST\t\t = 1f;\n\tprivate static final float TIME_TO_SEARCH\t = 2f;\n\tprivate static final float HUNGER_FOR_SEARCH\t= 6f;\n\t\n\tpublic HeroClass heroClass = HeroClass.ROGUE;\n\tpublic HeroSubClass subClass = HeroSubClass.NONE;\n\tpublic ArmorAbility armorAbility = null;\n\tpublic ArrayList<LinkedHashMap<Talent, Integer>> talents = new ArrayList<>();\n\tpublic LinkedHashMap<Talent, Talent> metamorphedTalents = new LinkedHashMap<>();\n\t\n\tprivate int attackSkill = 10;\n\tprivate int defenseSkill = 5;\n\n\tpublic boolean ready = false;\n\tpublic boolean damageInterrupt = true;\n\tpublic HeroAction curAction = null;\n\tpublic HeroAction lastAction = null;\n\n\tprivate Char enemy;\n\t\n\tpublic boolean resting = false;\n\t\n\tpublic Belongings belongings;\n\t\n\tpublic int STR;\n\t\n\tpublic float awareness;\n\t\n\tpublic int lvl = 1;\n\tpublic int exp = 0;\n\t\n\tpublic int HTBoost = 0;\n\t\n\tprivate ArrayList<Mob> visibleEnemies;\n\n\t//This list is maintained so that some logic checks can be skipped\n\t// for enemies we know we aren't seeing normally, resulting in better performance\n\tpublic ArrayList<Mob> mindVisionEnemies = new ArrayList<>();\n\n\tpublic Hero() {\n\t\tsuper();\n\n\t\tHP = HT = (Dungeon.isChallenged(Challenges.SUPERMAN)) ? 10 : 20;\n\t\tSTR = STARTING_STR;\n\t\t\n\t\tbelongings = new Belongings( this );\n\t\t\n\t\tvisibleEnemies = new ArrayList<>();\n\t}\n\t\n\tpublic void updateHT( boolean boostHP ){\n\t\tint curHT = HT;\n\n\t\tHT = (Dungeon.isChallenged(Challenges.SUPERMAN)) ? 10 : 20 + 5 * (lvl-1) + HTBoost;\n\t\tif (this.hasTalent(Talent.MAX_HEALTH)) {\n\t\t\tHT += 5*this.pointsInTalent(Talent.MAX_HEALTH);\n\t\t}\n\t\tfloat multiplier = RingOfMight.HTMultiplier(this);\n\t\tHT = Math.round(multiplier * HT);\n\t\t\n\t\tif (buff(ElixirOfMight.HTBoost.class) != null){\n\t\t\tHT += buff(ElixirOfMight.HTBoost.class).boost();\n\t\t}\n\n\t\tif (buff(ElixirOfTalent.ElixirOfTalentHTBoost.class) != null){\n\t\t\tHT += buff(ElixirOfTalent.ElixirOfTalentHTBoost.class).boost();\n\t\t}\n\t\t\n\t\tif (boostHP){\n\t\t\tHP += Math.max(HT - curHT, 0);\n\t\t}\n\t\tHP = Math.min(HP, HT);\n\t}\n\n\tpublic int STR() {\n\t\tint strBonus = 0;\n\n\t\tstrBonus += RingOfMight.strengthBonus( this );\n\t\t\n\t\tAdrenalineSurge buff = buff(AdrenalineSurge.class);\n\t\tif (buff != null){\n\t\t\tstrBonus += buff.boost();\n\t\t}\n\n\t\tif (hasTalent(Talent.STRONGMAN)){\n\t\t\tstrBonus += (int)Math.floor(STR * (0.03f + 0.05f*pointsInTalent(Talent.STRONGMAN)));\n\t\t}\n\n\t\treturn STR + strBonus;\n\t}\n\n\tpublic void onSTRGained() {\n\n\t}\n\n\tpublic void onSTRLost() {\n\n\t}\n\n\tprivate static final String CLASS = \"class\";\n\tprivate static final String SUBCLASS = \"subClass\";\n\tprivate static final String ABILITY = \"armorAbility\";\n\n\tprivate static final String ATTACK\t\t= \"attackSkill\";\n\tprivate static final String DEFENSE\t\t= \"defenseSkill\";\n\tprivate static final String STRENGTH\t= \"STR\";\n\tprivate static final String LEVEL\t\t= \"lvl\";\n\tprivate static final String EXPERIENCE\t= \"exp\";\n\tprivate static final String HTBOOST = \"htboost\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\n\t\tsuper.storeInBundle( bundle );\n\n\t\tbundle.put( CLASS, heroClass );\n\t\tbundle.put( SUBCLASS, subClass );\n\t\tbundle.put( ABILITY, armorAbility );\n\t\tTalent.storeTalentsInBundle( bundle, this );\n\t\t\n\t\tbundle.put( ATTACK, attackSkill );\n\t\tbundle.put( DEFENSE, defenseSkill );\n\t\t\n\t\tbundle.put( STRENGTH, STR );\n\t\t\n\t\tbundle.put( LEVEL, lvl );\n\t\tbundle.put( EXPERIENCE, exp );\n\t\t\n\t\tbundle.put( HTBOOST, HTBoost );\n\n\t\tbelongings.storeInBundle( bundle );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\n\t\tlvl = bundle.getInt( LEVEL );\n\t\texp = bundle.getInt( EXPERIENCE );\n\n\t\tHTBoost = bundle.getInt(HTBOOST);\n\n\t\tsuper.restoreFromBundle( bundle );\n\n\t\theroClass = bundle.getEnum( CLASS, HeroClass.class );\n\t\tsubClass = bundle.getEnum( SUBCLASS, HeroSubClass.class );\n\t\tarmorAbility = (ArmorAbility)bundle.get( ABILITY );\n\t\tTalent.restoreTalentsFromBundle( bundle, this );\n\t\t\n\t\tattackSkill = bundle.getInt( ATTACK );\n\t\tdefenseSkill = bundle.getInt( DEFENSE );\n\t\t\n\t\tSTR = bundle.getInt( STRENGTH );\n\n\t\tbelongings.restoreFromBundle( bundle );\n\t}\n\t\n\tpublic static void preview( GamesInProgress.Info info, Bundle bundle ) {\n\t\tinfo.level = bundle.getInt( LEVEL );\n\t\tinfo.str = bundle.getInt( STRENGTH );\n\t\tinfo.exp = bundle.getInt( EXPERIENCE );\n\t\tinfo.hp = bundle.getInt( Char.TAG_HP );\n\t\tinfo.ht = bundle.getInt( Char.TAG_HT );\n\t\tinfo.shld = bundle.getInt( Char.TAG_SHLD );\n\t\tinfo.heroClass = bundle.getEnum( CLASS, HeroClass.class );\n\t\tinfo.subClass = bundle.getEnum( SUBCLASS, HeroSubClass.class );\n\t\tBelongings.preview( info, bundle );\n\t}\n\n\tpublic boolean hasTalent( Talent talent ){\n\t\treturn pointsInTalent(talent) > 0;\n\t}\n\n\tpublic int pointsInTalent( Talent talent ){\n\t\tfor (LinkedHashMap<Talent, Integer> tier : talents){\n\t\t\tfor (Talent f : tier.keySet()){\n\t\t\t\tif (f == talent) return tier.get(f);\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\n\tpublic void upgradeTalent( Talent talent ){\n\t\tfor (LinkedHashMap<Talent, Integer> tier : talents){\n\t\t\tfor (Talent f : tier.keySet()){\n\t\t\t\tif (f == talent) tier.put(talent, tier.get(talent)+1);\n\t\t\t}\n\t\t}\n\t\tTalent.onTalentUpgraded(this, talent);\n\t}\n\n\tpublic int talentPointsSpent(int tier){\n\t\tint total = 0;\n\t\tfor (int i : talents.get(tier-1).values()){\n\t\t\ttotal += i;\n\t\t}\n\t\treturn total;\n\t}\n\n\tpublic int talentPointsAvailable(int tier){\n\t\tif (lvl < (Talent.tierLevelThresholds[tier] - 1)\n\t\t\t|| (tier == 3 && subClass == HeroSubClass.NONE)\n\t\t\t|| (tier == 4 && armorAbility == null)) {\n\t\t\treturn 0;\n\t\t} else if (lvl >= Talent.tierLevelThresholds[tier+1]){\n\t\t\treturn Talent.tierLevelThresholds[tier+1] - Talent.tierLevelThresholds[tier] - talentPointsSpent(tier) + bonusTalentPoints(tier);\n\t\t} else {\n\t\t\treturn 1 + lvl - Talent.tierLevelThresholds[tier] - talentPointsSpent(tier) + bonusTalentPoints(tier);\n\t\t}\n\t}\n\n\tpublic int bonusTalentPoints(int tier){\n\t\tint bonusPoints = 0;\n\t\tif (lvl < (Talent.tierLevelThresholds[tier]-1)\n\t\t\t\t|| (tier == 3 && subClass == HeroSubClass.NONE)\n\t\t\t\t|| (tier == 4 && armorAbility == null)) {\n\t\t\treturn 0;\n\t\t} else if (buff(PotionOfDivineInspiration.DivineInspirationTracker.class) != null\n\t\t\t\t\t&& buff(PotionOfDivineInspiration.DivineInspirationTracker.class).isBoosted(tier)) {\n\t\t\tbonusPoints += 2;\n\t\t}\n\t\tif (tier == 3 && buff(ElixirOfTalent.BonusTalentTracker.class) != null) {\n\t\t\tbonusPoints += 4;\n\t\t}\n\t\treturn bonusPoints;\n\t}\n\t\n\tpublic String className() {\n\t\treturn subClass == null || subClass == HeroSubClass.NONE ? heroClass.title() : subClass.title();\n\t}\n\n\t@Override\n\tpublic String name(){\n\t\treturn className();\n\t}\n\n\t@Override\n\tpublic void hitSound(float pitch) {\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\tbelongings.attackingWeapon().hitSound(pitch);\n\t\t} else if (RingOfForce.getBuffedBonus(this, RingOfForce.Force.class) > 0) {\n\t\t\t//pitch deepens by 2.5% (additive) per point of strength, down to 75%\n\t\t\tsuper.hitSound( pitch * GameMath.gate( 0.75f, 1.25f - 0.025f*STR(), 1f) );\n\t\t} else {\n\t\t\tsuper.hitSound(pitch * 1.1f);\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean blockSound(float pitch) {\n\t\tif ( belongings.weapon() != null && belongings.weapon().defenseFactor(this) >= 4 ){\n\t\t\tSample.INSTANCE.play( Assets.Sounds.HIT_PARRY, 1, pitch);\n\t\t\treturn true;\n\t\t}\n\t\treturn super.blockSound(pitch);\n\t}\n\n\tpublic void live() {\n\t\tfor (Buff b : buffs()){\n\t\t\tif (!b.revivePersists) b.detach();\n\t\t}\n\t\tBuff.affect( this, Regeneration.class );\n\t\tBuff.affect( this, Hunger.class );\n\t}\n\t\n\tpublic int tier() {\n\t\tArmor armor = belongings.armor();\n\t\tif (armor instanceof ClassArmor){\n\t\t\treturn 6;\n\t\t} else if (armor != null){\n\t\t\treturn armor.tier;\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tpublic boolean shoot( Char enemy, MissileWeapon wep ) {\n\n\t\tthis.enemy = enemy;\n\t\tboolean wasEnemy = enemy.alignment == Alignment.ENEMY\n\t\t\t\t|| (enemy instanceof Mimic && enemy.alignment == Alignment.NEUTRAL);\n\n\t\t//temporarily set the hero's weapon to the missile weapon being used\n\t\t//TODO improve this!\n\t\tbelongings.thrownWeapon = wep;\n\t\tboolean hit = attack( enemy );\n\t\tInvisibility.dispel();\n\t\tbelongings.thrownWeapon = null;\n\n\t\tif (hit && subClass == HeroSubClass.GLADIATOR && wasEnemy){\n\t\t\tBuff.affect( this, Combo.class ).hit( enemy );\n\t\t}\n\n\t\tif (hit && heroClass == HeroClass.DUELIST && wasEnemy){\n\t\t\tBuff.affect( this, Sai.ComboStrikeTracker.class).addHit();\n\t\t}\n\n\t\treturn hit;\n\t}\n\t\n\t@Override\n\tpublic int attackSkill( Char target ) {\n\t\tKindOfWeapon wep = belongings.attackingWeapon();\n\t\t\n\t\tfloat accuracy = 1;\n\t\taccuracy *= RingOfAccuracy.accuracyMultiplier( this );\n\n\t\tif (Dungeon.isChallenged(Challenges.SUPERMAN)) {\n\t\t\taccuracy *= 2;\n\t\t}\n\t\t\n\t\tif (wep instanceof MissileWeapon && !(wep instanceof Gun.Bullet)){ //총탄을 제외한 투척 무기의 정확성\n\t\t\tif (Dungeon.level.adjacent( pos, target.pos )) {\n\t\t\t\taccuracy *= (0.5f + 0.2f*pointsInTalent(Talent.POINT_BLANK));\n\t\t\t} else {\n\t\t\t\taccuracy *= 1.5f;\n\t\t\t}\n\t\t}\n\n\t\tif (wep instanceof Gun.Bullet) {\t//총탄의 정확성\n\t\t\tif (Dungeon.level.adjacent( pos, target.pos )) {\n\t\t\t\tif (wep instanceof SG.SGBullet) {\n\t\t\t\t\taccuracy *= 10f; //산탄총은 기본적으로 0.2배의 명중률 보정이 있으며, 이를 10배함으로써 2배의 명중률을 가짐\n\t\t\t\t} else {\n\t\t\t\t\taccuracy *= (0.5f + 0.2f*pointsInTalent(Talent.POINT_BLANK));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hero.hasTalent(Talent.INEVITABLE_DEATH) && hero.buff(RouletteOfDeath.class) != null && hero.buff(RouletteOfDeath.class).timeToDeath()) {\n\t\t\t\taccuracy *= 1 + hero.pointsInTalent(Talent.INEVITABLE_DEATH);\n\t\t\t}\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.GUNSLINGER && hero.justMoved && wep instanceof MissileWeapon) {\n\t\t\taccuracy *= 0.25f*(1+0.5f*hero.pointsInTalent(Talent.MOVING_SHOT));\n\t\t}\n\n\t\tif (buff(Scimitar.SwordDance.class) != null){\n\t\t\taccuracy *= 1.25f;\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.ACC_ENHANCE)) {\n\t\t\taccuracy *= 1 + 0.05f * hero.pointsInTalent(Talent.ACC_ENHANCE);\n\t\t}\n\n\t\tif (hero.buff(LargeSword.LargeSwordBuff.class) != null) {\n\t\t\taccuracy *= hero.buff(LargeSword.LargeSwordBuff.class).getAccuracyFactor();\n\t\t}\n\n\t\tif (hero.buff(UnholyBible.Demon.class) != null) {\n\t\t\taccuracy = INFINITE_ACCURACY;\n\t\t}\n\n\t\tif (hero.buff(MeleeWeapon.DashAttack.class) != null) {\n\t\t\taccuracy = INFINITE_ACCURACY;\n\t\t}\n\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\treturn (int)(attackSkill * accuracy * wep.accuracyFactor( this, target ));\n\t\t} else {\n\t\t\treturn (int)(attackSkill * accuracy);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic int defenseSkill( Char enemy ) {\n\n\t\tif (buff(Combo.ParryTracker.class) != null){\n\t\t\tif (canAttack(enemy) && !isCharmedBy(enemy)){\n\t\t\t\tBuff.affect(this, Combo.RiposteTracker.class).enemy = enemy;\n\t\t\t}\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\n\t\tif (buff(RoundShield.GuardTracker.class) != null){\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\n\t\tif (buff(Talent.ParryTracker.class) != null){\n\t\t\tif (canAttack(enemy) && !isCharmedBy(enemy)){\n\t\t\t\tBuff.affect(this, Talent.RiposteTracker.class).enemy = enemy;\n\t\t\t}\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\n\t\tif (buff(Nunchaku.ParryTracker.class) != null){\n\t\t\tif (canAttack(enemy) && !isCharmedBy(enemy)){\n\t\t\t\tBuff.affect(this, Nunchaku.RiposteTracker.class).enemy = enemy;\n\t\t\t}\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\t\t\n\t\tfloat evasion = defenseSkill;\n\t\t\n\t\tevasion *= RingOfEvasion.evasionMultiplier( this );\n\n\t\tif (hero.hasTalent(Talent.SWIFT_MOVEMENT)) {\n\t\t\tevasion += hero.STR()-10;\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.SUPERMAN)) {\n\t\t\tevasion *= 3;\n\t\t}\n\n\t\tif (buff(Talent.RestoredAgilityTracker.class) != null){\n\t\t\tif (pointsInTalent(Talent.LIQUID_AGILITY) == 1){\n\t\t\t\tevasion *= 4f;\n\t\t\t} else if (pointsInTalent(Talent.LIQUID_AGILITY) == 2){\n\t\t\t\treturn INFINITE_EVASION;\n\t\t\t}\n\t\t}\n\n\t\tif (buff(Quarterstaff.DefensiveStance.class) != null){\n\t\t\tevasion *= 3;\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.EVA_ENHANCE)) {\n\t\t\tevasion *= 1 + 0.05f * hero.pointsInTalent(Talent.EVA_ENHANCE);\n\t\t}\n\n\t\tif (hero.buff(UnholyBible.Demon.class) != null) {\n\t\t\tevasion /= 2;\n\t\t}\n\t\t\n\t\tif (paralysed > 0) {\n\t\t\tevasion /= 2;\n\t\t}\n\n\t\tif (belongings.armor() != null) {\n\t\t\tevasion = belongings.armor().evasionFactor(this, evasion);\n\t\t}\n\n\t\treturn Math.round(evasion);\n\t}\n\n\t@Override\n\tpublic String defenseVerb() {\n\t\tCombo.ParryTracker parry = buff(Combo.ParryTracker.class);\n\t\tif (parry != null){\n\t\t\tparry.parried = true;\n\t\t\tif (buff(Combo.class).getComboCount() < 9 || pointsInTalent(Talent.ENHANCED_COMBO) < 2){\n\t\t\t\tparry.detach();\n\t\t\t}\n\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t}\n\n\t\tif (buff(RoundShield.GuardTracker.class) != null){\n\t\t\tbuff(RoundShield.GuardTracker.class).detach();\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1, Random.Float(0.96f, 1.05f));\n\t\t\treturn Messages.get(RoundShield.GuardTracker.class, \"guarded\");\n\t\t}\n\n\t\tif (buff(MonkEnergy.MonkAbility.Focus.FocusActivation.class) != null){\n\t\t\tbuff(MonkEnergy.MonkAbility.Focus.FocusActivation.class).detach();\n\t\t\tif (sprite != null && sprite.visible) {\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1, Random.Float(0.96f, 1.05f));\n\t\t\t}\n\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t}\n\n\t\tTalent.ParryTracker parryTracker = buff(Talent.ParryTracker.class);\n\t\tif (hasTalent(Talent.PARRY)) {\n\t\t\tif (parryTracker != null) {\n\t\t\t\tparryTracker.detach();\n\t\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t\t}\n\t\t}\n\n\t\tNunchaku.ParryTracker nunchakuParry = buff(Nunchaku.ParryTracker.class);\n\t\tif (nunchakuParry != null){\n\t\t\tnunchakuParry.parried = true;\n\t\t\tif (sprite != null && sprite.visible) {\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1, Random.Float(0.96f, 1.05f));\n\t\t\t}\n\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t}\n\n\t\tRouletteOfDeath roulette = buff(RouletteOfDeath.class);\n\t\tif (hasTalent(Talent.HONORABLE_SHOT) && roulette != null && roulette.overHalf()) {\n\t\t\tBuff.prolong(hero, Talent.HonorableShotTracker.class, 1f);\n\t\t}\n\n\t\treturn super.defenseVerb();\n\t}\n\n\t@Override\n\tpublic int drRoll() {\n\t\tint dr = super.drRoll();\n\n\t\tif (belongings.armor() != null) {\n\t\t\tint armDr = Random.NormalIntRange( belongings.armor().DRMin(), belongings.armor().DRMax());\n\t\t\tif (STR() < belongings.armor().STRReq()){\n\t\t\t\tarmDr -= 2*(belongings.armor().STRReq() - STR());\n\t\t\t}\n\t\t\tif (armDr > 0) dr += armDr;\n\t\t}\n\t\tif (belongings.weapon() != null && !RingOfForce.fightingUnarmed(this)) {\n\t\t\tint wepDr = Random.NormalIntRange( 0 , belongings.weapon().defenseFactor( this ) );\n\t\t\tif (STR() < ((Weapon)belongings.weapon()).STRReq()){\n\t\t\t\twepDr -= 2*(((Weapon)belongings.weapon()).STRReq() - STR());\n\t\t\t}\n\t\t\tif (wepDr > 0) dr += wepDr;\n\t\t}\n\n\t\tif (buff(HoldFast.class) != null){\n\t\t\tdr += buff(HoldFast.class).armorBonus();\n\t\t}\n\n\t\tReinforcedArmor.ReinforcedArmorTracker rearmor = hero.buff(ReinforcedArmor.ReinforcedArmorTracker.class);\n\t\tif (rearmor != null) dr += rearmor.blockingRoll();\n\t\t\n\t\treturn dr;\n\t}\n\t\n\t@Override\n\tpublic int damageRoll() {\n\t\tKindOfWeapon wep = belongings.attackingWeapon();\n\t\tint dmg;\n\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\tdmg = wep.damageRoll( this );\n\n\t\t\tif (!(wep instanceof MissileWeapon)) dmg += RingOfForce.armedDamageBonus(this);\n\t\t} else {\n\t\t\tdmg = RingOfForce.damageRoll(this);\n\t\t\tif (RingOfForce.unarmedGetsWeaponAugment(this)){\n\t\t\t\tdmg = ((Weapon)belongings.attackingWeapon()).augment.damageFactor(dmg);\n\t\t\t}\n\t\t}\n\n\t\tPhysicalEmpower emp = buff(PhysicalEmpower.class);\n\t\tif (emp != null){\n\t\t\tdmg += emp.dmgBoost;\n\t\t\temp.left--;\n\t\t\tif (emp.left <= 0) {\n\t\t\t\temp.detach();\n\t\t\t}\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG, 0.75f, 1.2f);\n\t\t}\n\n\t\tif (heroClass != HeroClass.DUELIST\n\t\t\t\t&& hasTalent(Talent.WEAPON_RECHARGING)\n\t\t\t\t&& (buff(Recharging.class) != null || buff(ArtifactRecharge.class) != null)){\n\t\t\tdmg = Math.round(dmg * 1.025f + (.025f*pointsInTalent(Talent.WEAPON_RECHARGING)));\n\t\t}\n\n\t\tif (dmg < 0) dmg = 0;\n\t\treturn dmg;\n\t}\n\t\n\t@Override\n\tpublic float speed() {\n\n\t\tfloat speed = super.speed();\n\n\t\tspeed *= RingOfHaste.speedMultiplier(this);\n\t\t\n\t\tif (belongings.armor() != null) {\n\t\t\tspeed = belongings.armor().speedFactor(this, speed);\n\t\t}\n\t\t\n\t\tMomentum momentum = buff(Momentum.class);\n\t\tif (momentum != null){\n\t\t\t((HeroSprite)sprite).sprint( momentum.freerunning() ? 1.5f : 1f );\n\t\t\tspeed *= momentum.speedMultiplier();\n\t\t} else {\n\t\t\t((HeroSprite)sprite).sprint( 1f );\n\t\t}\n\n\t\tNaturesPower.naturesPowerTracker natStrength = buff(NaturesPower.naturesPowerTracker.class);\n\t\tif (natStrength != null){\n\t\t\tspeed *= (2f + 0.25f*pointsInTalent(Talent.GROWING_POWER));\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.MOVESPEED_ENHANCE)) {\n\t\t\tspeed *= 1 + 0.1*hero.pointsInTalent(Talent.MOVESPEED_ENHANCE);\n\t\t}\n\n\t\tif (subClass == HeroSubClass.MONK && buff(MonkEnergy.class) != null && buff(MonkEnergy.class).harmonized(this)) {\n\t\t\tspeed *= 1.5f;\n\t\t}\n\n\t\tif (hero.buff(ReinforcedArmor.ReinforcedArmorTracker.class) != null && hero.hasTalent(Talent.PLATE_ADD)) {\n\t\t\tspeed *= (1 - hero.pointsInTalent(Talent.PLATE_ADD)/8f);\n\t\t}\n\n\t\tif (hero.buff(Riot.RiotTracker.class) != null && hero.hasTalent(Talent.HASTE_MOVE)) {\n\t\t\tspeed *= 1f + 0.25f * hero.pointsInTalent(Talent.HASTE_MOVE);\n\t\t}\n\n\t\tspeed = AscensionChallenge.modifyHeroSpeed(speed);\n\t\t\n\t\treturn speed;\n\t\t\n\t}\n\n\t@Override\n\tpublic boolean canSurpriseAttack(){\n\t\tKindOfWeapon w = belongings.attackingWeapon();\n\t\tif (!(w instanceof Weapon)) return true;\n\t\tif (RingOfForce.fightingUnarmed(this)) return true;\n\t\tif (STR() < ((Weapon)w).STRReq()) return false;\n\t\tif (w instanceof Flail) return false;\n\t\tif (w instanceof ChainFlail) return false;\n\t\tif (w instanceof SG.SGBullet) return false;\n\n\t\treturn super.canSurpriseAttack();\n\t}\n\n\tpublic boolean canAttack(Char enemy){\n\t\tif (enemy == null || pos == enemy.pos || !Actor.chars().contains(enemy)) {\n\t\t\treturn false;\n\t\t}\n\n\t\t//can always attack adjacent enemies\n\t\tif (Dungeon.level.adjacent(pos, enemy.pos)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tKindOfWeapon wep = Dungeon.hero.belongings.attackingWeapon();\n\n\t\tif (wep != null){\n\t\t\treturn wep.canReach(this, enemy.pos);\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic float attackDelay() {\n\t\tif (buff(Talent.LethalMomentumTracker.class) != null){\n\t\t\tbuff(Talent.LethalMomentumTracker.class).detach();\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (buff(Talent.CounterAttackTracker.class) != null && hero.belongings.weapon == null) {\n\t\t\tbuff(Talent.CounterAttackTracker.class).detach();\n\t\t\treturn 0;\n\t\t}\n\n\t\tfloat delay = 1f;\n\n\t\tif ( buff(Adrenaline.class) != null) delay /= 1.5f;\n\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\t\n\t\t\treturn delay * belongings.attackingWeapon().delayFactor( this );\n\t\t\t\n\t\t} else {\n\t\t\t//Normally putting furor speed on unarmed attacks would be unnecessary\n\t\t\t//But there's going to be that one guy who gets a furor+force ring combo\n\t\t\t//This is for that one guy, you shall get your fists of fury!\n\t\t\tfloat speed = RingOfFuror.attackSpeedMultiplier(this);\n\n\t\t\tif (hero.hasTalent(Talent.LESS_RESIST)) {\n\t\t\t\tint aEnc = hero.belongings.armor.STRReq() - hero.STR();\n\t\t\t\tif (aEnc < 0) {\n\t\t\t\t\tspeed *= 1 + 0.05f * hero.pointsInTalent(Talent.LESS_RESIST) * (-aEnc);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.QUICK_FOLLOWUP) && hero.buff(Talent.QuickFollowupTracker.class) != null) {\n\t\t\t\tspeed *= 1+hero.pointsInTalent(Talent.QUICK_FOLLOWUP)/3f;\n\t\t\t}\n\n\t\t\tif (hero.subClass == HeroSubClass.MONK && hero.buff(MonkEnergy.class) != null && hero.buff(MonkEnergy.class).harmonized(hero)) {\n\t\t\t\tspeed *= 1.5f;\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.ATK_SPEED_ENHANCE)) {\n\t\t\t\tspeed *= 1 + 0.05f * hero.pointsInTalent(Talent.ATK_SPEED_ENHANCE);\n\t\t\t}\n\n\t\t\t//ditto for furor + sword dance!\n\t\t\tif (buff(Scimitar.SwordDance.class) != null){\n\t\t\t\tspeed += 0.6f;\n\t\t\t}\n\n\t\t\t//and augments + brawler's stance! My goodness, so many options now compared to 2014!\n\t\t\tif (RingOfForce.unarmedGetsWeaponAugment(this)){\n\t\t\t\tdelay = ((Weapon)belongings.weapon).augment.delayFactor(delay);\n\t\t\t}\n\n\t\t\treturn delay/speed;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void spend( float time ) {\n\t\tsuper.spend(time);\n\t}\n\n\t@Override\n\tpublic void spendConstant(float time) {\n\t\tjustMoved = false;\n\t\tsuper.spendConstant(time);\n\t}\n\n\tpublic void spendAndNextConstant(float time ) {\n\t\tbusy();\n\t\tspendConstant( time );\n\t\tnext();\n\t}\n\n\tpublic void spendAndNext( float time ) {\n\t\tbusy();\n\t\tspend( time );\n\t\tnext();\n\t}\n\t\n\t@Override\n\tpublic boolean act() {\n\t\t\n\t\t//calls to dungeon.observe will also update hero's local FOV.\n\t\tfieldOfView = Dungeon.level.heroFOV;\n\n\t\tif (buff(Endure.EndureTracker.class) != null){\n\t\t\tbuff(Endure.EndureTracker.class).endEnduring();\n\t\t}\n\t\t\n\t\tif (!ready) {\n\t\t\t//do a full observe (including fog update) if not resting.\n\t\t\tif (!resting || buff(MindVision.class) != null || buff(Awareness.class) != null) {\n\t\t\t\tDungeon.observe();\n\t\t\t} else {\n\t\t\t\t//otherwise just directly re-calculate FOV\n\t\t\t\tDungeon.level.updateFieldOfView(this, fieldOfView);\n\t\t\t}\n\t\t}\n\t\t\n\t\tcheckVisibleMobs();\n\t\tBuffIndicator.refreshHero();\n\t\tBuffIndicator.refreshBoss();\n\t\t\n\t\tif (paralysed > 0) {\n\t\t\t\n\t\t\tcurAction = null;\n\t\t\t\n\t\t\tspendAndNext( TICK );\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tboolean actResult;\n\t\tif (curAction == null) {\n\t\t\t\n\t\t\tif (resting) {\n\t\t\t\tspendConstant( TIME_TO_REST );\n\t\t\t\tnext();\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\t\t\t\n\t\t\tactResult = false;\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tresting = false;\n\t\t\t\n\t\t\tready = false;\n\t\t\t\n\t\t\tif (curAction instanceof HeroAction.Move) {\n\t\t\t\tactResult = actMove( (HeroAction.Move)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Interact) {\n\t\t\t\tactResult = actInteract( (HeroAction.Interact)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Buy) {\n\t\t\t\tactResult = actBuy( (HeroAction.Buy)curAction );\n\t\t\t\t\n\t\t\t}else if (curAction instanceof HeroAction.PickUp) {\n\t\t\t\tactResult = actPickUp( (HeroAction.PickUp)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.OpenChest) {\n\t\t\t\tactResult = actOpenChest( (HeroAction.OpenChest)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Unlock) {\n\t\t\t\tactResult = actUnlock((HeroAction.Unlock) curAction);\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Mine) {\n\t\t\t\tactResult = actMine( (HeroAction.Mine)curAction );\n\n\t\t\t}else if (curAction instanceof HeroAction.LvlTransition) {\n\t\t\t\tactResult = actTransition( (HeroAction.LvlTransition)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Attack) {\n\t\t\t\tactResult = actAttack( (HeroAction.Attack)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Alchemy) {\n\t\t\t\tactResult = actAlchemy( (HeroAction.Alchemy)curAction );\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tactResult = false;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(hasTalent(Talent.BARKSKIN) && Dungeon.level.map[pos] == Terrain.FURROWED_GRASS){\n\t\t\tBarkskin.conditionallyAppend(this, (lvl*pointsInTalent(Talent.BARKSKIN))/2, 1 );\n\t\t}\n\n\t\tif (hasTalent(Talent.PARRY) && buff(Talent.ParryCooldown.class) == null){\n\t\t\tBuff.affect(this, Talent.ParryTracker.class);\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.CURSED_DUNGEON) && hero.buff(GhostSpawner.class) == null) {\n\t\t\tBuff.affect(hero, GhostSpawner.class);\n\t\t}\n\t\t\n\t\treturn actResult;\n\t}\n\t\n\tpublic void busy() {\n\t\tready = false;\n\t}\n\t\n\tprivate void ready() {\n\t\tif (sprite.looping()) sprite.idle();\n\t\tcurAction = null;\n\t\tdamageInterrupt = true;\n\t\twaitOrPickup = false;\n\t\tready = true;\n\t\tcanSelfTrample = true;\n\n\t\tAttackIndicator.updateState();\n\t\t\n\t\tGameScene.ready();\n\t}\n\t\n\tpublic void interrupt() {\n\t\tif (isAlive() && curAction != null &&\n\t\t\t((curAction instanceof HeroAction.Move && curAction.dst != pos) ||\n\t\t\t(curAction instanceof HeroAction.LvlTransition))) {\n\t\t\tlastAction = curAction;\n\t\t}\n\t\tcurAction = null;\n\t\tGameScene.resetKeyHold();\n\t}\n\t\n\tpublic void resume() {\n\t\tcurAction = lastAction;\n\t\tlastAction = null;\n\t\tdamageInterrupt = false;\n\t\tnext();\n\t}\n\n\tprivate boolean canSelfTrample = false;\n\tpublic boolean canSelfTrample(){\n\t\treturn canSelfTrample && !rooted && !flying &&\n\t\t\t\t//standing in high grass\n\t\t\t\t(Dungeon.level.map[pos] == Terrain.HIGH_GRASS ||\n\t\t\t\t//standing in furrowed grass and not huntress\n\t\t\t\t((heroClass != HeroClass.HUNTRESS && hero.subClass != HeroSubClass.SPECIALIST) && Dungeon.level.map[pos] == Terrain.FURROWED_GRASS) ||\n\t\t\t\t//standing on a plant\n\t\t\t\tDungeon.level.plants.get(pos) != null);\n\t}\n\t\n\tprivate boolean actMove( HeroAction.Move action ) {\n\n\t\tif (getCloser( action.dst )) {\n\t\t\tcanSelfTrample = false;\n\t\t\treturn true;\n\n\t\t//Hero moves in place if there is grass to trample\n\t\t} else if (pos == action.dst && canSelfTrample()){\n\t\t\tcanSelfTrample = false;\n\t\t\tDungeon.level.pressCell(pos);\n\t\t\tspendAndNext( 1 / speed() );\n\t\t\treturn false;\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actInteract( HeroAction.Interact action ) {\n\t\t\n\t\tChar ch = action.ch;\n\n\t\tif (ch.isAlive() && ch.canInteract(this)) {\n\t\t\t\n\t\t\tready();\n\t\t\tsprite.turnTo( pos, ch.pos );\n\t\t\treturn ch.interact(this);\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tif (fieldOfView[ch.pos] && getCloser( ch.pos )) {\n\n\t\t\t\treturn true;\n\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\t\n\tprivate boolean actBuy( HeroAction.Buy action ) {\n\t\tint dst = action.dst;\n\t\tif (pos == dst) {\n\n\t\t\tready();\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( dst );\n\t\t\tif (heap != null && heap.type == Type.FOR_SALE && heap.size() == 1) {\n\t\t\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\tGameScene.show( new WndTradeItem( heap ) );\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate boolean actAlchemy( HeroAction.Alchemy action ) {\n\t\tint dst = action.dst;\n\t\tif (Dungeon.level.distance(dst, pos) <= 1) {\n\n\t\t\tready();\n\t\t\t\n\t\t\tAlchemistsToolkit.kitEnergy kit = buff(AlchemistsToolkit.kitEnergy.class);\n\t\t\tif (kit != null && kit.isCursed()){\n\t\t\t\tGLog.w( Messages.get(AlchemistsToolkit.class, \"cursed\"));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tAlchemyScene.clearToolkit();\n\t\t\tShatteredPixelDungeon.switchScene(AlchemyScene.class);\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t//used to keep track if the wait/pickup action was used\n\t// so that the hero spends a turn even if the fail to pick up an item\n\tpublic boolean waitOrPickup = false;\n\n\tprivate boolean actPickUp( HeroAction.PickUp action ) {\n\t\tint dst = action.dst;\n\t\tif (pos == dst) {\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( pos );\n\t\t\tif (heap != null) {\n\t\t\t\tItem item = heap.peek();\n\t\t\t\tif (item.doPickUp( this )) {\n\t\t\t\t\theap.pickUp();\n\n\t\t\t\t\tif (item instanceof Dewdrop\n\t\t\t\t\t\t\t|| item instanceof TimekeepersHourglass.sandBag\n\t\t\t\t\t\t\t|| item instanceof DriedRose.Petal\n\t\t\t\t\t\t\t|| item instanceof Key\n\t\t\t\t\t\t\t|| item instanceof Guidebook) {\n\t\t\t\t\t\t//Do Nothing\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t//TODO make all unique items important? or just POS / SOU?\n\t\t\t\t\t\tboolean important = item.unique && item.isIdentified() &&\n\t\t\t\t\t\t\t\t(item instanceof Scroll || item instanceof Potion);\n\t\t\t\t\t\tif (important) {\n\t\t\t\t\t\t\tGLog.p( Messages.capitalize(Messages.get(this, \"you_now_have\", item.name())) );\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tGLog.i( Messages.capitalize(Messages.get(this, \"you_now_have\", item.name())) );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tcurAction = null;\n\t\t\t\t} else {\n\n\t\t\t\t\tif (waitOrPickup) {\n\t\t\t\t\t\tspendAndNextConstant(TIME_TO_REST);\n\t\t\t\t\t}\n\n\t\t\t\t\t//allow the hero to move between levels even if they can't collect the item\n\t\t\t\t\tif (Dungeon.level.getTransition(pos) != null){\n\t\t\t\t\t\tthrowItems();\n\t\t\t\t\t} else {\n\t\t\t\t\t\theap.sprite.drop();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (item instanceof Dewdrop\n\t\t\t\t\t\t\t|| item instanceof TimekeepersHourglass.sandBag\n\t\t\t\t\t\t\t|| item instanceof DriedRose.Petal\n\t\t\t\t\t\t\t|| item instanceof Key) {\n\t\t\t\t\t\t//Do Nothing\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGLog.newLine();\n\t\t\t\t\t\tGLog.n(Messages.capitalize(Messages.get(this, \"you_cant_have\", item.name())));\n\t\t\t\t\t}\n\n\t\t\t\t\tready();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actOpenChest( HeroAction.OpenChest action ) {\n\t\tint dst = action.dst;\n\t\tif (Dungeon.level.adjacent( pos, dst ) || pos == dst) {\n\t\t\tpath = null;\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( dst );\n\t\t\tif (heap != null && (heap.type != Type.HEAP && heap.type != Type.FOR_SALE)) {\n\t\t\t\t\n\t\t\t\tif ((heap.type == Type.LOCKED_CHEST && Notes.keyCount(new GoldenKey(Dungeon.depth)) < 1)\n\t\t\t\t\t|| (heap.type == Type.CRYSTAL_CHEST && Notes.keyCount(new CrystalKey(Dungeon.depth)) < 1)){\n\n\t\t\t\t\t\tGLog.w( Messages.get(this, \"locked_chest\") );\n\t\t\t\t\t\tready();\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tswitch (heap.type) {\n\t\t\t\tcase TOMB:\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.TOMB );\n\t\t\t\t\tPixelScene.shake( 1, 0.5f );\n\t\t\t\t\tbreak;\n\t\t\t\tcase SKELETON:\n\t\t\t\tcase REMAINS:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.UNLOCK );\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tsprite.operate( dst );\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actUnlock( HeroAction.Unlock action ) {\n\t\tint doorCell = action.dst;\n\t\tif (Dungeon.level.adjacent( pos, doorCell )) {\n\t\t\tpath = null;\n\t\t\t\n\t\t\tboolean hasKey = false;\n\t\t\tint door = Dungeon.level.map[doorCell];\n\t\t\t\n\t\t\tif (door == Terrain.LOCKED_DOOR\n\t\t\t\t\t&& Notes.keyCount(new IronKey(Dungeon.depth)) > 0) {\n\t\t\t\t\n\t\t\t\thasKey = true;\n\t\t\t\t\n\t\t\t} else if (door == Terrain.CRYSTAL_DOOR\n\t\t\t\t\t&& Notes.keyCount(new CrystalKey(Dungeon.depth, Dungeon.branch)) > 0) {\n\n\t\t\t\thasKey = true;\n\n\t\t\t} else if (door == Terrain.LOCKED_EXIT\n\t\t\t\t\t&& Notes.keyCount(new SkeletonKey(Dungeon.depth)) > 0) {\n\n\t\t\t\thasKey = true;\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tif (hasKey) {\n\t\t\t\t\n\t\t\t\tsprite.operate( doorCell );\n\t\t\t\t\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.UNLOCK );\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tGLog.w( Messages.get(this, \"locked_door\") );\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( doorCell )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic boolean actMine(HeroAction.Mine action){\n\t\tif (Dungeon.level.adjacent(pos, action.dst)){\n\t\t\tpath = null;\n\t\t\tif ((Dungeon.level.map[action.dst] == Terrain.WALL\n\t\t\t\t\t|| Dungeon.level.map[action.dst] == Terrain.WALL_DECO\n\t\t\t\t\t|| Dungeon.level.map[action.dst] == Terrain.MINE_CRYSTAL\n\t\t\t\t\t|| Dungeon.level.map[action.dst] == Terrain.MINE_BOULDER)\n\t\t\t\t&& Dungeon.level.insideMap(action.dst)){\n\t\t\t\tsprite.attack(action.dst, new Callback() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void call() {\n\n\t\t\t\t\t\tboolean crystalAdjacent = false;\n\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS8) {\n\t\t\t\t\t\t\tif (Dungeon.level.map[action.dst + i] == Terrain.MINE_CRYSTAL){\n\t\t\t\t\t\t\t\tcrystalAdjacent = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//1 hunger spent total\n\t\t\t\t\t\tif (Dungeon.level.map[action.dst] == Terrain.WALL_DECO){\n\t\t\t\t\t\t\tDarkGold gold = new DarkGold();\n\t\t\t\t\t\t\tif (gold.doPickUp( Dungeon.hero )) {\n\t\t\t\t\t\t\t\tDarkGold existing = Dungeon.hero.belongings.getItem(DarkGold.class);\n\t\t\t\t\t\t\t\tif (existing != null && existing.quantity()%5 == 0){\n\t\t\t\t\t\t\t\t\tif (existing.quantity() >= 40) {\n\t\t\t\t\t\t\t\t\t\tGLog.p(Messages.get(DarkGold.class, \"you_now_have\", existing.quantity()));\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tGLog.i(Messages.get(DarkGold.class, \"you_now_have\", existing.quantity()));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tspend(-Actor.TICK); //picking up the gold doesn't spend a turn here\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tDungeon.level.drop( gold, pos ).sprite.drop();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tPixelScene.shake(0.5f, 0.5f);\n\t\t\t\t\t\t\tCellEmitter.center( action.dst ).burst( Speck.factory( Speck.STAR ), 7 );\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.EVOKE );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY_DECO );\n\n\t\t\t\t\t\t\t//mining gold doesn't break crystals\n\t\t\t\t\t\t\tcrystalAdjacent = false;\n\n\t\t\t\t\t\t//4 hunger spent total\n\t\t\t\t\t\t} else if (Dungeon.level.map[action.dst] == Terrain.WALL){\n\t\t\t\t\t\t\tbuff(Hunger.class).affectHunger(-3);\n\t\t\t\t\t\t\tPixelScene.shake(0.5f, 0.5f);\n\t\t\t\t\t\t\tCellEmitter.get( action.dst ).burst( Speck.factory( Speck.ROCK ), 2 );\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.MINE );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY_DECO );\n\n\t\t\t\t\t\t//1 hunger spent total\n\t\t\t\t\t\t} else if (Dungeon.level.map[action.dst] == Terrain.MINE_CRYSTAL){\n\t\t\t\t\t\t\tSplash.at(action.dst, 0xFFFFFF, 5);\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.SHATTER );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY );\n\n\t\t\t\t\t\t//1 hunger spent total\n\t\t\t\t\t\t} else if (Dungeon.level.map[action.dst] == Terrain.MINE_BOULDER){\n\t\t\t\t\t\t\tSplash.at(action.dst, ColorMath.random( 0x444444, 0x777766 ), 5);\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.MINE, 0.6f );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\t\tDungeon.level.discoverable[action.dst + i] = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\t\tGameScene.updateMap( action.dst+i );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (crystalAdjacent){\n\t\t\t\t\t\t\tsprite.parent.add(new Delayer(0.2f){\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tprotected void onComplete() {\n\t\t\t\t\t\t\t\t\tboolean broke = false;\n\t\t\t\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS8) {\n\t\t\t\t\t\t\t\t\t\tif (Dungeon.level.map[action.dst+i] == Terrain.MINE_CRYSTAL){\n\t\t\t\t\t\t\t\t\t\t\tSplash.at(action.dst+i, 0xFFFFFF, 5);\n\t\t\t\t\t\t\t\t\t\t\tLevel.set( action.dst+i, Terrain.EMPTY );\n\t\t\t\t\t\t\t\t\t\t\tbroke = true;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (broke){\n\t\t\t\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.SHATTER );\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\t\t\t\t\tGameScene.updateMap( action.dst+i );\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tspendAndNext(TICK);\n\t\t\t\t\t\t\t\t\tready();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tspendAndNext(TICK);\n\t\t\t\t\t\t\tready();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tDungeon.observe();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\t\t\treturn false;\n\t\t} else if (getCloser( action.dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actTransition(HeroAction.LvlTransition action ) {\n\t\tint stairs = action.dst;\n\t\tLevelTransition transition = Dungeon.level.getTransition(stairs);\n\n\t\tif (rooted) {\n\t\t\tPixelScene.shake(1, 1f);\n\t\t\tready();\n\t\t\treturn false;\n\n\t\t} else if (!Dungeon.level.locked && transition != null && transition.inside(pos)) {\n\n\t\t\tif (Dungeon.level.activateTransition(this, transition)){\n\t\t\t\tcurAction = null;\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( stairs )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actAttack( HeroAction.Attack action ) {\n\n\t\tenemy = action.target;\n\n\t\tif (enemy.isAlive() && canAttack( enemy ) && !isCharmedBy( enemy ) && enemy.invisible == 0) {\n\n\t\t\tif (heroClass != HeroClass.DUELIST\n\t\t\t\t\t&& hasTalent(Talent.AGGRESSIVE_BARRIER)\n\t\t\t\t\t&& buff(Talent.AggressiveBarrierCooldown.class) == null\n\t\t\t\t\t&& (HP / (float)HT) < 0.20f*(1+pointsInTalent(Talent.AGGRESSIVE_BARRIER))){\n\t\t\t\tBuff.affect(this, Barrier.class).setShield(3);\n\t\t\t\tBuff.affect(this, Talent.AggressiveBarrierCooldown.class, 50f);\n\t\t\t}\n\t\t\tsprite.attack( enemy.pos );\n\n\t\t\treturn false;\n\n\t\t} else {\n\n\t\t\tif (fieldOfView[enemy.pos] && getCloser( enemy.pos )) {\n\n\t\t\t\treturn true;\n\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t}\n\t}\n\n\tpublic Char enemy(){\n\t\treturn enemy;\n\t}\n\t\n\tpublic void rest( boolean fullRest ) {\n\t\tspendAndNextConstant( TIME_TO_REST );\n\t\tif (hasTalent(Talent.HOLD_FAST)){\n\t\t\tBuff.affect(this, HoldFast.class).pos = pos;\n\t\t}\n\t\tif (hasTalent(Talent.PATIENT_STRIKE)){\n\t\t\tBuff.affect(Dungeon.hero, Talent.PatientStrikeTracker.class).pos = Dungeon.hero.pos;\n\t\t}\n\t\tif (!fullRest) {\n\t\t\tif (sprite != null) {\n\t\t\t\tsprite.showStatus(CharSprite.DEFAULT, Messages.get(this, \"wait\"));\n\t\t\t}\n\n\t\t\tif (belongings.weapon instanceof LargeSword || belongings.secondWep instanceof LargeSword){\n\t\t\t\tBuff.affect(this, LargeSword.LargeSwordBuff.class).setDamageFactor(belongings.weapon.buffedLvl(), (belongings.secondWep instanceof LargeSword));\n\t\t\t\tif (hero.sprite != null) {\n\t\t\t\t\tEmitter e = hero.sprite.centerEmitter();\n\t\t\t\t\tif (e != null) e.burst(EnergyParticle.FACTORY, 15);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Dungeon.hero.subClass == HeroSubClass.CHASER\n\t\t\t\t\t&& hero.buff(Talent.ChaseCooldown.class) == null\n\t\t\t\t\t&& hero.buff(Invisibility.class) == null\n\t\t\t\t\t&& hero.buff(CloakOfShadows.cloakStealth.class) == null ) {\n\t\t\t\tif (hero.hasTalent(Talent.MASTER_OF_CLOAKING)) {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Invisibility.class, 6f);\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Invisibility.class, 5f);\n\t\t\t\t}\n\t\t\t\tif (hero.pointsInTalent(Talent.MASTER_OF_CLOAKING) > 1) {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.ChaseCooldown.class, 10f);\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.ChaseCooldown.class, 15f);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Dungeon.level.map[pos] == Terrain.FURROWED_GRASS && hero.subClass == HeroSubClass.SPECIALIST) {\n\t\t\t\tboolean adjacentMob = false;\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] )) {\n\t\t\t\t\tif (level.adjacent(hero.pos, mob.pos)) {\n\t\t\t\t\t\tadjacentMob = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (hero.pointsInTalent(Talent.STEALTH_MASTER) > 1) {\n\t\t\t\t\tadjacentMob = false;\n\t\t\t\t}\n\t\t\t\tif (!adjacentMob && hero.hasTalent(Talent.INTO_THE_SHADOW) && hero.buff(Talent.IntoTheShadowCooldown.class) == null) {\n\t\t\t\t\tBuff.affect(this, Invisibility.class, 3f*hero.pointsInTalent(Talent.INTO_THE_SHADOW));\n\t\t\t\t\tBuff.affect(this, Talent.IntoTheShadowCooldown.class, 15);\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(this, Cloaking.class);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresting = fullRest;\n\t}\n\t\n\t@Override\n\tpublic int attackProc( final Char enemy, int damage ) {\n\t\tdamage = super.attackProc( enemy, damage );\n\n\t\tKindOfWeapon wep;\n\t\tif (RingOfForce.fightingUnarmed(this) && !RingOfForce.unarmedGetsWeaponEnchantment(this)){\n\t\t\twep = null;\n\t\t} else {\n\t\t\twep = belongings.attackingWeapon();\n\t\t}\n\n\t\tif (hero.buff(MeleeWeapon.DashAttack.class) != null) {\n\t\t\tdamage *= hero.buff(MeleeWeapon.DashAttack.class).getDmgMulti();\n\t\t\thero.buff(MeleeWeapon.DashAttack.class).detach();\n\t\t}\n\n\t\tif (wep != null) damage = wep.proc( this, enemy, damage );\n\n\t\tdamage = Talent.onAttackProc( this, enemy, damage );\n\t\t\n\t\tswitch (subClass) {\n\t\t\tcase SNIPER:\n\t\t\t\tif (wep instanceof MissileWeapon && !(wep instanceof SpiritBow.SpiritArrow) && enemy != this) {\n\t\t\t\t\tActor.add(new Actor() {\n\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tactPriority = VFX_PRIO;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tprotected boolean act() {\n\t\t\t\t\t\t\tif (enemy.isAlive()) {\n\t\t\t\t\t\t\t\tint bonusTurns = hasTalent(Talent.SHARED_UPGRADES) ? wep.buffedLvl() : 0;\n\t\t\t\t\t\t\t\tBuff.prolong(Hero.this, SnipersMark.class, SnipersMark.DURATION + bonusTurns).set(enemy.id(), bonusTurns);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tActor.remove(this);\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (hero.hasTalent(Talent.KICK)\n\t\t\t\t\t\t&& enemy.buff(PinCushion.class) != null\n\t\t\t\t\t\t&& level.adjacent(hero.pos, enemy.pos)\n\t\t\t\t\t\t&& hero.buff(Talent.KickCooldown.class) == null) {\n\t\t\t\t\tItem item = enemy.buff(PinCushion.class).grabOne();\n\t\t\t\t\tif (item.doPickUp(hero, enemy.pos)){\n\t\t\t\t\t\thero.spend(-1); //attacking enemy already takes a turn\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGLog.w(Messages.get(this, \"cant_grab\"));\n\t\t\t\t\t\tDungeon.level.drop(item, enemy.pos).sprite.drop();\n\t\t\t\t\t}\n\t\t\t\t\tBallistica trajectory = new Ballistica(hero.pos, enemy.pos, Ballistica.STOP_TARGET);\n\t\t\t\t\ttrajectory = new Ballistica(trajectory.collisionPos, trajectory.path.get(trajectory.path.size() - 1), Ballistica.PROJECTILE);\n\t\t\t\t\tint dist = hero.pointsInTalent(Talent.KICK);\n\t\t\t\t\tWandOfBlastWave.throwChar(enemy, trajectory, dist, true, false ,hero.getClass());\n\t\t\t\t\tBuff.affect(hero, Talent.KickCooldown.class, 10f);\n\t\t\t\t}\n\t\t\t\tif (wep instanceof MissileWeapon\n\t\t\t\t\t\t&& hero.hasTalent(Talent.SHOOTING_EYES)\n\t\t\t\t\t\t&& enemy.buff(Talent.ShootingEyesTracker.class) == null) {\n\t\t\t\t\tif (Random.Float() < hero.pointsInTalent(Talent.SHOOTING_EYES)/3f) {\n\t\t\t\t\t\tBuff.affect(enemy, Blindness.class, 2f);\n\t\t\t\t\t}\n\t\t\t\t\tBuff.affect(enemy, Talent.ShootingEyesTracker.class);\n\t\t\t\t}\n\t\t\t\tif (wep instanceof MissileWeapon\n\t\t\t\t\t\t&& hero.hasTalent(Talent.TARGET_SPOTTING)\n\t\t\t\t\t\t&& hero.buff(SnipersMark.class) != null\n\t\t\t\t\t\t&& hero.buff(SnipersMark.class).object == enemy.id()) {\n\t\t\t\t\tdamage *= 1+0.1f*hero.pointsInTalent(Talent.TARGET_SPOTTING);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase FIGHTER:\n\t\t\t\tif (wep == null && Random.Int(3) < hero.pointsInTalent(Talent.QUICK_STEP)) {\n\t\t\t\t\tBuff.prolong(hero, Talent.QuickStep.class, 1.0001f);\n\t\t\t\t}\n\t\t\t\tif (wep == null && hero.hasTalent(Talent.RING_KNUCKLE) && hero.buff(RingOfForce.Force.class) == null) {\n\t\t\t\t\tBuff.prolong(hero, EnhancedRingsCombo.class, (Dungeon.hero.pointsInTalent(Talent.RING_KNUCKLE) >= 2) ? 2f : 1f).hit();\n\t\t\t\t\thero.updateHT(false);\n\t\t\t\t\tupdateQuickslot();\n\t\t\t\t}\n\t\t\t\tif (wep == null && Random.Float() < hero.pointsInTalent(Talent.MYSTICAL_PUNCH)/3f) {\n\t\t\t\t\tif (hero.belongings.ring != null) {\n\t\t\t\t\t\tdamage *= Ring.onHit(hero, enemy, damage, Ring.ringTypes.get(hero.belongings.ring.getClass()));\n\t\t\t\t\t}\n\t\t\t\t\tif (hero.belongings.misc instanceof Ring) {\n\t\t\t\t\t\tdamage *= Ring.onHit(hero, enemy, damage, Ring.ringTypes.get(hero.belongings.misc.getClass()));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CHAMPION:\n\t\t\t\tif (hero.belongings.weapon != null && hero.belongings.secondWep != null\n\t\t\t\t\t\t&& hero.pointsInTalent(Talent.TWIN_SWORD) > 1\n\t\t\t\t\t\t&& hero.belongings.weapon.getClass() == hero.belongings.secondWep.getClass()) {\n\t\t\t\t\tKindOfWeapon other = hero.belongings.secondWep;\n\t\t\t\t\tif (hero.belongings.secondWep == wep) {\n\t\t\t\t\t\tother = hero.belongings.weapon;\n\t\t\t\t\t}\n\t\t\t\t\tdamage = other.proc( this, enemy, damage );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase VETERAN:\n\t\t\t\tif (level.adjacent(enemy.pos, pos) && hero.buff(Tackle.TackleTracker.class) == null) {\n\t\t\t\t\tActor.add(new Actor() {\n\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tactPriority = VFX_PRIO;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tprotected boolean act() {\n\t\t\t\t\t\t\tif (enemy.isAlive()) {\n\t\t\t\t\t\t\t\tBuff.prolong(Hero.this, Tackle.class, 1).set(enemy.id());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tActor.remove(this);\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OUTLAW:\n\t\t\t\tif (wep instanceof Gun.Bullet) {\n\t\t\t\t\tif (hero.hasTalent(Talent.HEADSHOT) && Random.Float() < 0.01f*hero.pointsInTalent(Talent.HEADSHOT)) {\n\t\t\t\t\t\tif (!Char.hasProp(enemy, Property.BOSS) && !Char.hasProp(enemy, Property.MINIBOSS)) {\n\t\t\t\t\t\t\tdamage = enemy.HP;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdamage *= 1.2f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemy.sprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\t\t}\n\n\t\t\t\t\tif (hero.buff(Talent.HonorableShotTracker.class) != null\n\t\t\t\t\t\t\t&& (enemy.HP/(float)enemy.HT) <= 0.4f*hero.pointsInTalent(Talent.HONORABLE_SHOT)/3f) {\n\t\t\t\t\t\tif (!Char.hasProp(enemy, Property.BOSS) && !Char.hasProp(enemy, Property.MINIBOSS)) {\n\t\t\t\t\t\t\tdamage = enemy.HP;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdamage *= 1.2f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemy.sprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\t\t\thero.buff(Talent.HonorableShotTracker.class).detach();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (hero.buff(RouletteOfDeath.class) == null || !hero.buff(RouletteOfDeath.class).timeToDeath()) {\n\t\t\t\t\t\tBuff.affect(this, RouletteOfDeath.class).hit();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (!Char.hasProp(enemy, Property.BOSS) && !Char.hasProp(enemy, Property.MINIBOSS)) {\n\t\t\t\t\t\t\tdamage = enemy.HP;\n\t\t\t\t\t\t\tif (hero.belongings.weapon instanceof Gun) {\n\t\t\t\t\t\t\t\t((Gun)hero.belongings.weapon).quickReload();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (hero.hasTalent(Talent.BULLET_TIME)) {\n\t\t\t\t\t\t\t\tfor (Char ch : Actor.chars()) {\n\t\t\t\t\t\t\t\t\tif (level.heroFOV[ch.pos]) {\n\t\t\t\t\t\t\t\t\t\tBuff.affect(ch, Slow.class, 4*hero.pointsInTalent(Talent.BULLET_TIME));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdamage *= 1.2f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemy.sprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\t\t\thero.buff(RouletteOfDeath.class).detach();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.WATER_FRIENDLY) && Dungeon.level.map[hero.pos] == Terrain.WATER) {\n\t\t\tdamage += Random.NormalIntRange(1, hero.pointsInTalent(Talent.WATER_FRIENDLY));\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t}\n\n\t\tif (hero.buff(Talent.SkilledHandTracker.class) != null) {\n\t\t\tdamage += 1+hero.pointsInTalent(Talent.SKILLED_HAND);\n\t\t\thero.buff(Talent.SkilledHandTracker.class).detach();\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t}\n\n\t\tif (Random.Float() < hero.pointsInTalent(Talent.MADNESS)/10f) {\n\t\t\tBuff.prolong(enemy, Amok.class, 3f);\n\t\t}\n\n\t\tSpellBook.SpellBookCoolDown spellBookCoolDown = buff(SpellBook.SpellBookCoolDown.class);\n\t\tif (hero.hasTalent(Talent.BRIG_BOOST) && spellBookCoolDown != null) {\n\t\t\tspellBookCoolDown.hit(hero.pointsInTalent(Talent.BRIG_BOOST));\n\t\t}\n\n\t\tif (hero.buff(Bible.Angel.class) != null) {\n\t\t\thero.heal(Math.max(Math.round(0.2f*damage), 1));\n\t\t}\n\n\t\tif (hero.buff(UnholyBible.Demon.class) != null) {\n\t\t\tdamage *= 1.33f;\n\t\t}\n\n\t\tif (hero.buff(DualDagger.ReverseBlade.class) != null) {\n\t\t\tdamage *= 0.5f;\n\t\t\tBuff.affect(enemy, Bleeding.class).add(Random.NormalIntRange(1, 3));\n\t\t\tif (enemy.sprite.visible) {\n\t\t\t\tSplash.at( enemy.sprite.center(), -PointF.PI / 2, PointF.PI / 6,\n\t\t\t\t\t\tenemy.sprite.blood(), Math.min( 10 * Random.NormalIntRange(1, 3) / enemy.HT, 10 ) );\n\t\t\t}\n\t\t}\n\n\t\tif (enemy instanceof Mob && ((Mob) enemy).surprisedBy(hero)) {\n\t\t\tif (hero.hasTalent(Talent.POISONOUS_BLADE)) {\n\t\t\t\tBuff.affect(enemy, Poison.class).set(2+hero.pointsInTalent(Talent.POISONOUS_BLADE));\n\t\t\t}\n\t\t\tif (hero.hasTalent(Talent.SOUL_COLLECT) && damage >= enemy.HP) {\n\t\t\t\tint healAmt = 3*hero.pointsInTalent(Talent.SOUL_COLLECT);\n\t\t\t\thealAmt = Math.min( healAmt, hero.HT - hero.HP );\n\t\t\t\tif (healAmt > 0 && hero.isAlive()) {\n\t\t\t\t\thero.HP += healAmt;\n\t\t\t\t\thero.sprite.emitter().start( Speck.factory( Speck.HEALING ), 0.4f, 2 );\n\t\t\t\t\thero.sprite.showStatus( CharSprite.POSITIVE, Integer.toString( healAmt ) );\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hero.hasTalent(Talent.TRAIL_TRACKING) && damage >= enemy.HP) {\n\t\t\t\tBuff.affect(hero, MindVision.class, hero.pointsInTalent(Talent.TRAIL_TRACKING));\n\t\t\t}\n\n\t\t\tif (hero.pointsInTalent(Talent.MASTER_OF_CLOAKING) == 3) {\n\t\t\t\tif (hero.buff(Talent.ChaseCooldown.class) != null) {\n\t\t\t\t\thero.buff(Talent.ChaseCooldown.class).spendTime();\n\t\t\t\t}\n\t\t\t\tif (hero.buff(Talent.ChainCooldown.class) != null) {\n\t\t\t\t\thero.buff(Talent.ChainCooldown.class).spendTime();\n\t\t\t\t}\n\t\t\t\tif (hero.buff(Talent.LethalCooldown.class) != null) {\n\t\t\t\t\thero.buff(Talent.LethalCooldown.class).spendTime();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.BAYONET) && hero.buff(ReinforcedArmor.ReinforcedArmorTracker.class) != null){\n\t\t\tif (wep instanceof Gun) {\n\t\t\t\tBuff.affect( enemy, Bleeding.class ).set( 4 + hero.pointsInTalent(Talent.BAYONET));\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.SUPERMAN)) {\n\t\t\tdamage *= 3f;\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.PYRO)) {\n\t\t\tBuff.affect(enemy, Burning.class).reignite(enemy, 8f);\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.FATIGUE)) {\n\t\t\tBuff.affect(this, Fatigue.class).hit(true);\n\t\t}\n\t\t\n\t\treturn damage;\n\t}\n\t\n\t@Override\n\tpublic int defenseProc( Char enemy, int damage ) {\n\t\t\n\t\tif (damage > 0 && subClass == HeroSubClass.BERSERKER){\n\t\t\tBerserk berserk = Buff.affect(this, Berserk.class);\n\t\t\tberserk.damage(damage);\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.GLADIATOR && Random.Float() < hero.pointsInTalent(Talent.OFFENSIVE_DEFENSE)/3f) {\n\t\t\tCombo combo = Buff.affect(this, Combo.class);\n\t\t\tcombo.hit(enemy);\n\t\t}\n\t\t\n\t\tif (belongings.armor() != null) {\n\t\t\tdamage = belongings.armor().proc( enemy, this, damage );\n\t\t}\n\n\t\tWandOfLivingEarth.RockArmor rockArmor = buff(WandOfLivingEarth.RockArmor.class);\n\t\tif (rockArmor != null) {\n\t\t\tdamage = rockArmor.absorb(damage);\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.EMERGENCY_ESCAPE) && Random.Float() < hero.pointsInTalent(Talent.EMERGENCY_ESCAPE)/50f) {\n\t\t\tBuff.prolong(this, Invisibility.class, 3f);\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.OVERCOMING)) {\n\t\t\tMomentum momentum = buff(Momentum.class);\n\t\t\tif (momentum != null && momentum.freerunning()) {\n\t\t\t\tBuff.affect(this, Haste.class, 2f);\n\t\t\t\tif (hero.pointsInTalent(Talent.OVERCOMING) > 1) Buff.affect(this, Adrenaline.class, 2f);\n\t\t\t\tif (hero.pointsInTalent(Talent.OVERCOMING) > 2) Buff.affect(this, EvasiveMove.class, 2f);\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.FATIGUE)) {\n\t\t\tBuff.affect(this, Fatigue.class).hit(false);\n\t\t}\n\t\t\n\t\treturn super.defenseProc( enemy, damage );\n\t}\n\t\n\t@Override\n\tpublic void damage( int dmg, Object src ) {\n\t\tif (buff(TimekeepersHourglass.timeStasis.class) != null)\n\t\t\treturn;\n\n\t\t//regular damage interrupt, triggers on any damage except specific mild DOT effects\n\t\t// unless the player recently hit 'continue moving', in which case this is ignored\n\t\tif (!(src instanceof Hunger || src instanceof Viscosity.DeferedDamage) && damageInterrupt) {\n\t\t\tinterrupt();\n\t\t\tresting = false;\n\t\t}\n\n\t\tif (this.buff(Drowsy.class) != null){\n\t\t\tBuff.detach(this, Drowsy.class);\n\t\t\tGLog.w( Messages.get(this, \"pain_resist\") );\n\t\t}\n\n\t\tEndure.EndureTracker endure = buff(Endure.EndureTracker.class);\n\t\tif (!(src instanceof Char)){\n\t\t\t//reduce damage here if it isn't coming from a character (if it is we already reduced it)\n\t\t\tif (endure != null){\n\t\t\t\tdmg = Math.round(endure.adjustDamageTaken(dmg));\n\t\t\t}\n\t\t\t//the same also applies to challenge scroll damage reduction\n\t\t\tif (buff(ScrollOfChallenge.ChallengeArena.class) != null){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\t\t\t//and to monk meditate damage reduction\n\t\t\tif (buff(MonkEnergy.MonkAbility.Meditate.MeditateResistance.class) != null){\n\t\t\t\tdmg *= 0.2f;\n\t\t\t}\n\t\t}\n\n\t\tCapeOfThorns.Thorns thorns = buff( CapeOfThorns.Thorns.class );\n\t\tif (thorns != null) {\n\t\t\tdmg = thorns.proc(dmg, (src instanceof Char ? (Char)src : null), this);\n\t\t}\n\n\t\tdmg = (int)Math.ceil(dmg * RingOfTenacity.damageMultiplier( this ));\n\n\t\tLargeSword.LargeSwordBuff largeSwordBuff = hero.buff(LargeSword.LargeSwordBuff.class);\n\t\tif (largeSwordBuff != null) {\n\t\t\tdmg = (int)Math.ceil(dmg * largeSwordBuff.getDefenseFactor());\n\t\t}\n\n\t\t//TODO improve this when I have proper damage source logic\n\t\tif (belongings.armor() != null && belongings.armor().hasGlyph(AntiMagic.class, this)\n\t\t\t\t&& AntiMagic.RESISTS.contains(src.getClass())){\n\t\t\tdmg -= AntiMagic.drRoll(this, belongings.armor().buffedLvl());\n\t\t}\n\n\t\tif (buff(Talent.WarriorFoodImmunity.class) != null){\n\t\t\tif (pointsInTalent(Talent.IRON_STOMACH) == 1) dmg = Math.round(dmg*0.25f);\n\t\t\telse if (pointsInTalent(Talent.IRON_STOMACH) == 2) dmg = Math.round(dmg*0.00f);\n\t\t}\n\n\t\tif (buff(Tackle.SuperArmorTracker.class) != null) {\n\t\t\tswitch (pointsInTalent(Talent.SUPER_ARMOR)) {\n\t\t\t\tcase 1:\n\t\t\t\t\tdmg = Math.round(dmg*0.67f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tdmg = Math.round(dmg*0.33f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tdmg = Math.round(dmg*0.00f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0: default:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tint preHP = HP + shielding();\n\t\tif (src instanceof Hunger) preHP -= shielding();\n\t\tsuper.damage( dmg, src );\n\t\tint postHP = HP + shielding();\n\t\tif (src instanceof Hunger) postHP -= shielding();\n\t\tint effectiveDamage = preHP - postHP;\n\n\t\tif (effectiveDamage <= 0) return;\n\n\t\tif (buff(Challenge.DuelParticipant.class) != null){\n\t\t\tbuff(Challenge.DuelParticipant.class).addDamage(effectiveDamage);\n\t\t}\n\n\t\t//flash red when hit for serious damage.\n\t\tfloat percentDMG = effectiveDamage / (float)preHP; //percent of current HP that was taken\n\t\tfloat percentHP = 1 - ((HT - postHP) / (float)HT); //percent health after damage was taken\n\t\t// The flash intensity increases primarily based on damage taken and secondarily on missing HP.\n\t\tfloat flashIntensity = 0.25f * (percentDMG * percentDMG) / percentHP;\n\t\t//if the intensity is very low don't flash at all\n\t\tif (flashIntensity >= 0.05f){\n\t\t\tflashIntensity = Math.min(1/3f, flashIntensity); //cap intensity at 1/3\n\t\t\tGameScene.flash( (int)(0xFF*flashIntensity) << 16 );\n\t\t\tif (isAlive()) {\n\t\t\t\tif (flashIntensity >= 1/6f) {\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HEALTH_CRITICAL, 1/3f + flashIntensity * 2f);\n\t\t\t\t} else {\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HEALTH_WARN, 1/3f + flashIntensity * 4f);\n\t\t\t\t}\n\t\t\t\t//hero gets interrupted on taking serious damage, regardless of any other factor\n\t\t\t\tinterrupt();\n\t\t\t\tresting = false;\n\t\t\t\tdamageInterrupt = true;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void checkVisibleMobs() {\n\t\tArrayList<Mob> visible = new ArrayList<>();\n\n\t\tboolean newMob = false;\n\n\t\tMob target = null;\n\t\tfor (Mob m : Dungeon.level.mobs.toArray(new Mob[0])) {\n\t\t\tif (fieldOfView[ m.pos ] && m.alignment == Alignment.ENEMY) {\n\t\t\t\tvisible.add(m);\n\t\t\t\tif (!visibleEnemies.contains( m )) {\n\t\t\t\t\tnewMob = true;\n\t\t\t\t}\n\n\t\t\t\tif (!mindVisionEnemies.contains(m) && QuickSlotButton.autoAim(m) != -1){\n\t\t\t\t\tif (target == null){\n\t\t\t\t\t\ttarget = m;\n\t\t\t\t\t} else if (distance(target) > distance(m)) {\n\t\t\t\t\t\ttarget = m;\n\t\t\t\t\t}\n\t\t\t\t\tif (m instanceof Snake && Dungeon.level.distance(m.pos, pos) <= 4\n\t\t\t\t\t\t\t&& !Document.ADVENTURERS_GUIDE.isPageRead(Document.GUIDE_EXAMINING)){\n\t\t\t\t\t\tGLog.p(Messages.get(Guidebook.class, \"hint\"));\n\t\t\t\t\t\tGameScene.flashForDocument(Document.ADVENTURERS_GUIDE, Document.GUIDE_EXAMINING);\n\t\t\t\t\t\t//we set to read here to prevent this message popping up a bunch\n\t\t\t\t\t\tDocument.ADVENTURERS_GUIDE.readPage(Document.GUIDE_EXAMINING);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tChar lastTarget = QuickSlotButton.lastTarget;\n\t\tif (target != null && (lastTarget == null ||\n\t\t\t\t\t\t\t!lastTarget.isAlive() || !lastTarget.isActive() ||\n\t\t\t\t\t\t\tlastTarget.alignment == Alignment.ALLY ||\n\t\t\t\t\t\t\t!fieldOfView[lastTarget.pos])){\n\t\t\tQuickSlotButton.target(target);\n\t\t}\n\t\t\n\t\tif (newMob) {\n\t\t\tinterrupt();\n\t\t\tif (resting){\n\t\t\t\tDungeon.observe();\n\t\t\t\tresting = false;\n\t\t\t}\n\t\t}\n\n\t\tvisibleEnemies = visible;\n\t}\n\t\n\tpublic int visibleEnemies() {\n\t\treturn visibleEnemies.size();\n\t}\n\t\n\tpublic Mob visibleEnemy( int index ) {\n\t\treturn visibleEnemies.get(index % visibleEnemies.size());\n\t}\n\n\tpublic ArrayList<Mob> getVisibleEnemies(){\n\t\treturn new ArrayList<>(visibleEnemies);\n\t}\n\t\n\tprivate boolean walkingToVisibleTrapInFog = false;\n\t\n\t//FIXME this is a fairly crude way to track this, really it would be nice to have a short\n\t//history of hero actions\n\tpublic boolean justMoved = false;\n\t\n\tprivate boolean getCloser( final int target ) {\n\n\t\tif (target == pos)\n\t\t\treturn false;\n\n\t\tif (rooted) {\n\t\t\tPixelScene.shake( 1, 1f );\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tint step = -1;\n\t\t\n\t\tif (Dungeon.level.adjacent( pos, target )) {\n\n\t\t\tpath = null;\n\n\t\t\tif (Actor.findChar( target ) == null) {\n\t\t\t\tif (Dungeon.level.passable[target] || Dungeon.level.avoid[target]) {\n\t\t\t\t\tstep = target;\n\t\t\t\t}\n\t\t\t\tif (walkingToVisibleTrapInFog\n\t\t\t\t\t\t&& Dungeon.level.traps.get(target) != null\n\t\t\t\t\t\t&& Dungeon.level.traps.get(target).visible){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t} else {\n\n\t\t\tboolean newPath = false;\n\t\t\tif (path == null || path.isEmpty() || !Dungeon.level.adjacent(pos, path.getFirst()))\n\t\t\t\tnewPath = true;\n\t\t\telse if (path.getLast() != target)\n\t\t\t\tnewPath = true;\n\t\t\telse {\n\t\t\t\tif (!Dungeon.level.passable[path.get(0)] || Actor.findChar(path.get(0)) != null) {\n\t\t\t\t\tnewPath = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (newPath) {\n\n\t\t\t\tint len = Dungeon.level.length();\n\t\t\t\tboolean[] p = Dungeon.level.passable;\n\t\t\t\tboolean[] v = Dungeon.level.visited;\n\t\t\t\tboolean[] m = Dungeon.level.mapped;\n\t\t\t\tboolean[] passable = new boolean[len];\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\tpassable[i] = p[i] && (v[i] || m[i]);\n\t\t\t\t}\n\n\t\t\t\tPathFinder.Path newpath = Dungeon.findPath(this, target, passable, fieldOfView, true);\n\t\t\t\tif (newpath != null && path != null && newpath.size() > 2*path.size()){\n\t\t\t\t\tpath = null;\n\t\t\t\t} else {\n\t\t\t\t\tpath = newpath;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (path == null) return false;\n\t\t\tstep = path.removeFirst();\n\n\t\t}\n\n\t\tif (step != -1) {\n\n\t\t\tfloat delay = 1 / speed();\n\n\t\t\tif (Dungeon.level.pit[step] && !Dungeon.level.solid[step]\n\t\t\t\t\t&& (!flying || buff(Levitation.class) != null && buff(Levitation.class).detachesWithinDelay(delay))){\n\t\t\t\tif (!Chasm.jumpConfirmed){\n\t\t\t\t\tChasm.heroJump(this);\n\t\t\t\t\tinterrupt();\n\t\t\t\t} else {\n\t\t\t\t\tflying = false;\n\t\t\t\t\tremove(buff(Levitation.class)); //directly remove to prevent cell pressing\n\t\t\t\t\tChasm.heroFall(target);\n\t\t\t\t}\n\t\t\t\tcanSelfTrample = false;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif ((hero.belongings.weapon instanceof Lance ||\n\t\t\t\t\thero.belongings.secondWep instanceof Lance ||\n\t\t\t\t\t(hero.belongings.weapon instanceof LanceNShield && ((LanceNShield)hero.belongings.weapon).stance) ||\n\t\t\t\t\t(hero.belongings.secondWep instanceof LanceNShield && ((LanceNShield)hero.belongings.secondWep).stance))) {\n\t\t\t\tBuff.affect(this, Lance.LanceBuff.class).setDamageFactor(1 + (hero.speed()), hero.belongings.secondWep instanceof Lance || (hero.belongings.secondWep instanceof LanceNShield && ((LanceNShield) hero.belongings.secondWep).stance));\n\t\t\t}\n\n\t\t\tif (subClass == HeroSubClass.FREERUNNER){\n\t\t\t\tBuff.affect(this, Momentum.class).gainStack();\n\t\t\t}\n\n\t\t\tif (hero.buff(Talent.RollingTracker.class) != null && hero.belongings.weapon instanceof Gun && Dungeon.bullet > 1) {\n\t\t\t\tDungeon.bullet --;\n\t\t\t\t((Gun)hero.belongings.weapon).manualReload();\n\t\t\t\thero.buff(Talent.RollingTracker.class).detach();\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.QUICK_RELOAD) && hero.belongings.weapon instanceof Gun && Random.Float() < 0.03f * hero.pointsInTalent(Talent.QUICK_RELOAD) && Dungeon.bullet > 1) {\n\t\t\t\tDungeon.bullet --;\n\t\t\t\t((Gun)hero.belongings.weapon).manualReload();\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.MIND_VISION) && Random.Float() < 0.01f*hero.pointsInTalent(Talent.MIND_VISION)) {\n\t\t\t\tBuff.affect(this, MindVision.class, 1f);\n\t\t\t}\n\t\t\t\n\t\t\tsprite.move(pos, step);\n\t\t\tmove(step);\n\n\t\t\tif (buff(Talent.QuickStep.class) != null) {\n\t\t\t\tspend(-delay);\n\t\t\t\tbuff(Talent.QuickStep.class).detach();\n\t\t\t}\n\n\t\t\tspend( delay );\n\t\t\tjustMoved = true;\n\t\t\t\n\t\t\tsearch(false);\n\n\t\t\treturn true;\n\n\t\t} else {\n\n\t\t\treturn false;\n\t\t\t\n\t\t}\n\n\t}\n\t\n\tpublic boolean handle( int cell ) {\n\t\t\n\t\tif (cell == -1) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (fieldOfView == null || fieldOfView.length != Dungeon.level.length()){\n\t\t\tfieldOfView = new boolean[Dungeon.level.length()];\n\t\t\tDungeon.level.updateFieldOfView( this, fieldOfView );\n\t\t}\n\t\t\n\t\tChar ch = Actor.findChar( cell );\n\t\tHeap heap = Dungeon.level.heaps.get( cell );\n\n\t\tif (Dungeon.level.map[cell] == Terrain.ALCHEMY && cell != pos) {\n\t\t\t\n\t\t\tcurAction = new HeroAction.Alchemy( cell );\n\t\t\t\n\t\t} else if (fieldOfView[cell] && ch instanceof Mob) {\n\n\t\t\tif (ch.alignment != Alignment.ENEMY && ch.buff(Amok.class) == null) {\n\t\t\t\tcurAction = new HeroAction.Interact( ch );\n\t\t\t} else {\n\t\t\t\tcurAction = new HeroAction.Attack( ch );\n\t\t\t}\n\n\t\t//TODO perhaps only trigger this if hero is already adjacent? reducing mistaps\n\t\t} else if (Dungeon.level instanceof MiningLevel &&\n\t\t\t\t\tbelongings.getItem(Pickaxe.class) != null &&\n\t\t\t\t(Dungeon.level.map[cell] == Terrain.WALL\n\t\t\t\t\t\t|| Dungeon.level.map[cell] == Terrain.WALL_DECO\n\t\t\t\t\t\t|| Dungeon.level.map[cell] == Terrain.MINE_CRYSTAL\n\t\t\t\t\t\t|| Dungeon.level.map[cell] == Terrain.MINE_BOULDER)){\n\n\t\t\tcurAction = new HeroAction.Mine( cell );\n\n\t\t} else if (heap != null\n\t\t\t\t//moving to an item doesn't auto-pickup when enemies are near...\n\t\t\t\t&& (visibleEnemies.size() == 0 || cell == pos ||\n\t\t\t\t//...but only for standard heaps. Chests and similar open as normal.\n\t\t\t\t(heap.type != Type.HEAP && heap.type != Type.FOR_SALE))) {\n\n\t\t\tswitch (heap.type) {\n\t\t\tcase HEAP:\n\t\t\t\tcurAction = new HeroAction.PickUp( cell );\n\t\t\t\tbreak;\n\t\t\tcase FOR_SALE:\n\t\t\t\tcurAction = heap.size() == 1 && heap.peek().value() > 0 ?\n\t\t\t\t\tnew HeroAction.Buy( cell ) :\n\t\t\t\t\tnew HeroAction.PickUp( cell );\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tcurAction = new HeroAction.OpenChest( cell );\n\t\t\t}\n\t\t\t\n\t\t} else if (Dungeon.level.map[cell] == Terrain.LOCKED_DOOR || Dungeon.level.map[cell] == Terrain.CRYSTAL_DOOR || Dungeon.level.map[cell] == Terrain.LOCKED_EXIT) {\n\t\t\t\n\t\t\tcurAction = new HeroAction.Unlock( cell );\n\t\t\t\n\t\t} else if (Dungeon.level.getTransition(cell) != null\n\t\t\t\t//moving to a transition doesn't automatically trigger it when enemies are near\n\t\t\t\t&& (visibleEnemies.size() == 0 || cell == pos)\n\t\t\t\t&& !Dungeon.level.locked\n\t\t\t\t&& (Dungeon.depth < 31 || Dungeon.level.getTransition(cell).type == LevelTransition.Type.REGULAR_ENTRANCE) ) {\n\n\t\t\tcurAction = new HeroAction.LvlTransition( cell );\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tif (!Dungeon.level.visited[cell] && !Dungeon.level.mapped[cell]\n\t\t\t\t\t&& Dungeon.level.traps.get(cell) != null && Dungeon.level.traps.get(cell).visible) {\n\t\t\t\twalkingToVisibleTrapInFog = true;\n\t\t\t} else {\n\t\t\t\twalkingToVisibleTrapInFog = false;\n\t\t\t}\n\t\t\t\n\t\t\tcurAction = new HeroAction.Move( cell );\n\t\t\tlastAction = null;\n\t\t\t\n\t\t}\n\n\t\treturn true;\n\t}\n\t\n\tpublic void earnExp( int exp, Class source ) {\n\n\t\t//xp granted by ascension challenge is only for on-exp gain effects\n\t\tif (source != AscensionChallenge.class) {\n\t\t\tthis.exp += exp;\n\t\t}\n\t\tfloat percent = exp/(float)maxExp();\n\n\t\tEtherealChains.chainsRecharge chains = buff(EtherealChains.chainsRecharge.class);\n\t\tif (chains != null) chains.gainExp(percent);\n\n\t\tHornOfPlenty.hornRecharge horn = buff(HornOfPlenty.hornRecharge.class);\n\t\tif (horn != null) horn.gainCharge(percent);\n\t\t\n\t\tAlchemistsToolkit.kitEnergy kit = buff(AlchemistsToolkit.kitEnergy.class);\n\t\tif (kit != null) kit.gainCharge(percent);\n\n\t\tMasterThievesArmband.Thievery armband = buff(MasterThievesArmband.Thievery.class);\n\t\tif (armband != null) armband.gainCharge(percent);\n\t\t\n\t\tBerserk berserk = buff(Berserk.class);\n\t\tif (berserk != null) berserk.recover(percent);\n\t\t\n\t\tif (source != PotionOfExperience.class) {\n\t\t\tfor (Item i : belongings) {\n\t\t\t\ti.onHeroGainExp(percent, this);\n\t\t\t}\n\t\t\tif (buff(Talent.RejuvenatingStepsFurrow.class) != null){\n\t\t\t\tbuff(Talent.RejuvenatingStepsFurrow.class).countDown(percent*200f);\n\t\t\t\tif (buff(Talent.RejuvenatingStepsFurrow.class).count() <= 0){\n\t\t\t\t\tbuff(Talent.RejuvenatingStepsFurrow.class).detach();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (buff(ElementalStrike.ElementalStrikeFurrowCounter.class) != null){\n\t\t\t\tbuff(ElementalStrike.ElementalStrikeFurrowCounter.class).countDown(percent*20f);\n\t\t\t\tif (buff(ElementalStrike.ElementalStrikeFurrowCounter.class).count() <= 0){\n\t\t\t\t\tbuff(ElementalStrike.ElementalStrikeFurrowCounter.class).detach();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tboolean levelUp = false;\n\t\twhile (this.exp >= maxExp()) {\n\t\t\tthis.exp -= maxExp();\n\t\t\tif (lvl < MAX_LEVEL) {\n\t\t\t\tlvl++;\n\t\t\t\tlevelUp = true;\n\t\t\t\t\n\t\t\t\tif (buff(ElixirOfMight.HTBoost.class) != null){\n\t\t\t\t\tbuff(ElixirOfMight.HTBoost.class).onLevelUp();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tupdateHT( true );\n\t\t\t\tattackSkill++;\n\t\t\t\tdefenseSkill++;\n\n\t\t\t} else {\n\t\t\t\tBuff.prolong(this, Bless.class, Bless.DURATION);\n\t\t\t\tthis.exp = 0;\n\n\t\t\t\tGLog.newLine();\n\t\t\t\tGLog.p( Messages.get(this, \"level_cap\"));\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.LEVELUP );\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tif (levelUp) {\n\t\t\t\n\t\t\tif (sprite != null) {\n\t\t\t\tGLog.newLine();\n\t\t\t\tGLog.p( Messages.get(this, \"new_level\") );\n\t\t\t\tsprite.showStatus( CharSprite.POSITIVE, Messages.get(Hero.class, \"level_up\") );\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.LEVELUP );\n\t\t\t\tif (lvl < Talent.tierLevelThresholds[Talent.MAX_TALENT_TIERS+1]){\n\t\t\t\t\tGLog.newLine();\n\t\t\t\t\tGLog.p( Messages.get(this, \"new_talent\") );\n\t\t\t\t\tStatusPane.talentBlink = 10f;\n\t\t\t\t\tWndHero.lastIdx = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tItem.updateQuickslot();\n\t\t\t\n\t\t\tBadges.validateLevelReached();\n\t\t}\n\t}\n\t\n\tpublic int maxExp() {\n\t\treturn maxExp( lvl );\n\t}\n\t\n\tpublic static int maxExp( int lvl ){\n\t\treturn 5 + lvl * 5;\n\t}\n\t\n\tpublic boolean isStarving() {\n\t\treturn Buff.affect(this, Hunger.class).isStarving();\n\t}\n\t\n\t@Override\n\tpublic boolean add( Buff buff ) {\n\n\t\tif (buff(TimekeepersHourglass.timeStasis.class) != null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tboolean added = super.add( buff );\n\n\t\tif (sprite != null && added) {\n\t\t\tString msg = buff.heroMessage();\n\t\t\tif (msg != null){\n\t\t\t\tGLog.w(msg);\n\t\t\t}\n\n\t\t\tif (buff instanceof Paralysis || buff instanceof Vertigo) {\n\t\t\t\tinterrupt();\n\t\t\t}\n\n\t\t}\n\t\t\n\t\tBuffIndicator.refreshHero();\n\n\t\treturn added;\n\t}\n\t\n\t@Override\n\tpublic boolean remove( Buff buff ) {\n\t\tif (super.remove( buff )) {\n\t\t\tBuffIndicator.refreshHero();\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic float stealth() {\n\t\tfloat stealth = super.stealth();\n\t\t\n\t\tif (belongings.armor() != null){\n\t\t\tstealth = belongings.armor().stealthFactor(this, stealth);\n\t\t}\n\t\t\n\t\treturn stealth;\n\t}\n\t\n\t@Override\n\tpublic void die( Object cause ) {\n\n\t\tif (buff(Enduring.class) != null) {\n\t\t\tthis.HP = 1;\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tcurAction = null;\n\n\t\tAnkh ankh = null;\n\n\t\t//look for ankhs in player inventory, prioritize ones which are blessed.\n\t\tfor (Ankh i : belongings.getAllItems(Ankh.class)){\n\t\t\tif (ankh == null || i.isBlessed()) {\n\t\t\t\tankh = i;\n\t\t\t}\n\t\t}\n\n\t\tif (ankh != null) {\n\t\t\tinterrupt();\n\t\t\tresting = false;\n\n\t\t\tif (ankh.isBlessed()) {\n\t\t\t\tthis.HP = HT / 4;\n\n\t\t\t\tPotionOfHealing.cure(this);\n\t\t\t\tBuff.prolong(this, AnkhInvulnerability.class, AnkhInvulnerability.DURATION);\n\n\t\t\t\tSpellSprite.show(this, SpellSprite.ANKH);\n\t\t\t\tGameScene.flash(0x80FFFF40);\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TELEPORT);\n\t\t\t\tGLog.w(Messages.get(this, \"revive\"));\n\t\t\t\tStatistics.ankhsUsed++;\n\n\t\t\t\tankh.detach(belongings.backpack);\n\n\t\t\t\tfor (Char ch : Actor.chars()) {\n\t\t\t\t\tif (ch instanceof DriedRose.GhostHero) {\n\t\t\t\t\t\t((DriedRose.GhostHero) ch).sayAnhk();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\n\t\t\t\t//this is hacky, basically we want to declare that a wndResurrect exists before\n\t\t\t\t//it actually gets created. This is important so that the game knows to not\n\t\t\t\t//delete the run or submit it to rankings, because a WndResurrect is about to exist\n\t\t\t\t//this is needed because the actual creation of the window is delayed here\n\t\t\t\tWndResurrect.instance = new Object();\n\t\t\t\tAnkh finalAnkh = ankh;\n\t\t\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\tGameScene.show( new WndResurrect(finalAnkh) );\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (cause instanceof Hero.Doom) {\n\t\t\t\t\t((Hero.Doom)cause).onDeath();\n\t\t\t\t}\n\n\t\t\t\tSacrificialFire.Marked sacMark = buff(SacrificialFire.Marked.class);\n\t\t\t\tif (sacMark != null){\n\t\t\t\t\tsacMark.detach();\n\t\t\t\t}\n\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tActor.fixTime();\n\t\tsuper.die( cause );\n\t\treallyDie( cause );\n\t}\n\t\n\tpublic static void reallyDie( Object cause ) {\n\t\t\n\t\tint length = Dungeon.level.length();\n\t\tint[] map = Dungeon.level.map;\n\t\tboolean[] visited = Dungeon.level.visited;\n\t\tboolean[] discoverable = Dungeon.level.discoverable;\n\t\t\n\t\tfor (int i=0; i < length; i++) {\n\t\t\t\n\t\t\tint terr = map[i];\n\t\t\t\n\t\t\tif (discoverable[i]) {\n\t\t\t\t\n\t\t\t\tvisited[i] = true;\n\t\t\t\tif ((Terrain.flags[terr] & Terrain.SECRET) != 0) {\n\t\t\t\t\tDungeon.level.discover( i );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tBones.leave();\n\t\t\n\t\tDungeon.observe();\n\t\tGameScene.updateFog();\n\t\t\t\t\n\t\tDungeon.hero.belongings.identify();\n\n\t\tint pos = Dungeon.hero.pos;\n\n\t\tArrayList<Integer> passable = new ArrayList<>();\n\t\tfor (Integer ofs : PathFinder.NEIGHBOURS8) {\n\t\t\tint cell = pos + ofs;\n\t\t\tif ((Dungeon.level.passable[cell] || Dungeon.level.avoid[cell]) && Dungeon.level.heaps.get( cell ) == null) {\n\t\t\t\tpassable.add( cell );\n\t\t\t}\n\t\t}\n\t\tCollections.shuffle( passable );\n\n\t\tArrayList<Item> items = new ArrayList<>(Dungeon.hero.belongings.backpack.items);\n\t\tfor (Integer cell : passable) {\n\t\t\tif (items.isEmpty()) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tItem item = Random.element( items );\n\t\t\tDungeon.level.drop( item, cell ).sprite.drop( pos );\n\t\t\titems.remove( item );\n\t\t}\n\n\t\tfor (Char c : Actor.chars()){\n\t\t\tif (c instanceof DriedRose.GhostHero){\n\t\t\t\t((DriedRose.GhostHero) c).sayHeroKilled();\n\t\t\t}\n\t\t}\n\n\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t@Override\n\t\t\tpublic void call() {\n\t\t\t\tGameScene.gameOver();\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.DEATH );\n\t\t\t}\n\t\t});\n\n\t\tif (cause instanceof Hero.Doom) {\n\t\t\t((Hero.Doom)cause).onDeath();\n\t\t}\n\n\t\tDungeon.deleteGame( GamesInProgress.curSlot, true );\n\t}\n\n\t//effectively cache this buff to prevent having to call buff(...) a bunch.\n\t//This is relevant because we call isAlive during drawing, which has both performance\n\t//and thread coordination implications if that method calls buff(...) frequently\n\tprivate Berserk berserk;\n\n\t@Override\n\tpublic boolean isAlive() {\n\t\t\n\t\tif (HP <= 0){\n\t\t\tif (berserk == null) berserk = buff(Berserk.class);\n\t\t\treturn berserk != null && berserk.berserking();\n\t\t} else {\n\t\t\tberserk = null;\n\t\t\treturn super.isAlive();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void move(int step, boolean travelling) {\n\t\tboolean wasHighGrass = Dungeon.level.map[step] == Terrain.HIGH_GRASS;\n\n\t\tsuper.move( step, travelling);\n\t\t\n\t\tif (!flying && travelling) {\n\t\t\tif (Dungeon.level.water[pos]) {\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.WATER, 1, Random.Float( 0.8f, 1.25f ) );\n\t\t\t} else if (Dungeon.level.map[pos] == Terrain.EMPTY_SP) {\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.STURDY, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t} else if (Dungeon.level.map[pos] == Terrain.GRASS\n\t\t\t\t\t|| Dungeon.level.map[pos] == Terrain.EMBERS\n\t\t\t\t\t|| Dungeon.level.map[pos] == Terrain.FURROWED_GRASS){\n\t\t\t\tif (step == pos && wasHighGrass) {\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TRAMPLE, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t\t} else {\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.GRASS, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.STEP, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void onAttackComplete() {\n\n\t\tif (enemy == null){\n\t\t\tcurAction = null;\n\t\t\tsuper.onAttackComplete();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tAttackIndicator.target(enemy);\n\t\tboolean wasEnemy = enemy.alignment == Alignment.ENEMY\n\t\t\t\t|| (enemy instanceof Mimic && enemy.alignment == Alignment.NEUTRAL);\n\n\t\tboolean hit = attack( enemy );\n\t\t\n\t\tInvisibility.dispel();\n\t\tspend( attackDelay() );\n\n\t\tif (hit && subClass == HeroSubClass.GLADIATOR && wasEnemy){\n\t\t\tBuff.affect( this, Combo.class ).hit( enemy );\n\t\t}\n\n\t\tif (hit && subClass == HeroSubClass.BATTLEMAGE && hero.belongings.attackingWeapon() instanceof MagesStaff && hero.hasTalent(Talent.BATTLE_MAGIC) && wasEnemy) {\n\t\t\tBuff.affect( this, MagicalCombo.class).hit( enemy );\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.CHASER\n\t\t\t\t&& hero.hasTalent(Talent.CHAIN_CLOCK)\n\t\t\t\t&& ((Mob) enemy).surprisedBy(hero)\n\t\t\t\t&& hero.buff(Talent.ChainCooldown.class) == null){\n\t\t\tBuff.affect( this, Invisibility.class, 1f * hero.pointsInTalent(Talent.CHAIN_CLOCK));\n\t\t\tBuff.affect( this, Haste.class, 1f * hero.pointsInTalent(Talent.CHAIN_CLOCK));\n\t\t\tBuff.affect( this, Talent.ChainCooldown.class, 10f);\n\t\t\tSample.INSTANCE.play( Assets.Sounds.MELD );\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.CHASER\n\t\t\t\t&& hero.hasTalent(Talent.LETHAL_SURPRISE)\n\t\t\t\t&& ((Mob) enemy).surprisedBy(hero)\n\t\t\t\t&& !enemy.isAlive()\n\t\t\t\t&& hero.buff(Talent.LethalCooldown.class) == null) {\n\t\t\tif (hero.pointsInTalent(Talent.LETHAL_SURPRISE) >= 1) {\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] )) {\n\t\t\t\t\tif (mob.alignment != Char.Alignment.ALLY && Dungeon.level.heroFOV[mob.pos]) {\n\t\t\t\t\t\tBuff.affect( mob, Vulnerable.class, 1f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tBuff.affect(hero, Talent.LethalCooldown.class, 5f);\n\t\t\t}\n\t\t\tif (hero.pointsInTalent(Talent.LETHAL_SURPRISE) >= 2) {\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] )) {\n\t\t\t\t\tif (mob.alignment != Char.Alignment.ALLY && Dungeon.level.heroFOV[mob.pos]) {\n\t\t\t\t\t\tBuff.affect( mob, Paralysis.class, 1f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hero.pointsInTalent(Talent.LETHAL_SURPRISE) == 3) {\n\t\t\t\tBuff.affect(hero, Swiftthistle.TimeBubble.class).twoTurns();\n\t\t\t}\n\t\t}\n\n\t\tif (hit && heroClass == HeroClass.DUELIST && wasEnemy){\n\t\t\tBuff.affect( this, Sai.ComboStrikeTracker.class).addHit();\n\t\t}\n\n\t\tRingOfForce.BrawlersStance brawlStance = buff(RingOfForce.BrawlersStance.class);\n\t\tif (brawlStance != null && brawlStance.hitsLeft() > 0){\n\t\t\tMeleeWeapon.Charger charger = Buff.affect(this, MeleeWeapon.Charger.class);\n\t\t\tcharger.partialCharge -= RingOfForce.BrawlersStance.HIT_CHARGE_USE;\n\t\t\twhile (charger.partialCharge < 0) {\n\t\t\t\tcharger.charges--;\n\t\t\t\tcharger.partialCharge++;\n\t\t\t}\n\t\t\tBuffIndicator.refreshHero();\n\t\t\tItem.updateQuickslot();\n\t\t}\n\n\t\tif (!hit && hero.belongings.weapon == null && hero.subClass == HeroSubClass.FIGHTER && Random.Int(5) == 0 && hero.pointsInTalent(Talent.SWIFT_MOVEMENT) > 1) {\n\t\t\tBuff.prolong(hero, EvasiveMove.class, 0.9999f);\n\t\t}\n\n\t\tcurAction = null;\n\n\t\tsuper.onAttackComplete();\n\t}\n\t\n\t@Override\n\tpublic void onMotionComplete() {\n\t\tGameScene.checkKeyHold();\n\t}\n\t\n\t@Override\n\tpublic void onOperateComplete() {\n\t\t\n\t\tif (curAction instanceof HeroAction.Unlock) {\n\n\t\t\tint doorCell = ((HeroAction.Unlock)curAction).dst;\n\t\t\tint door = Dungeon.level.map[doorCell];\n\t\t\t\n\t\t\tif (Dungeon.level.distance(pos, doorCell) <= 1) {\n\t\t\t\tboolean hasKey = true;\n\t\t\t\tif (door == Terrain.LOCKED_DOOR) {\n\t\t\t\t\thasKey = Notes.remove(new IronKey(Dungeon.depth));\n\t\t\t\t\tif (hasKey) Level.set(doorCell, Terrain.DOOR);\n\t\t\t\t} else if (door == Terrain.CRYSTAL_DOOR) {\n\t\t\t\t\thasKey = Notes.remove(new CrystalKey(Dungeon.depth, Dungeon.branch));\n\t\t\t\t\tif (hasKey) {\n\t\t\t\t\t\tLevel.set(doorCell, Terrain.EMPTY);\n\t\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TELEPORT);\n\t\t\t\t\t\tCellEmitter.get( doorCell ).start( Speck.factory( Speck.DISCOVER ), 0.025f, 20 );\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\thasKey = Notes.remove(new SkeletonKey(Dungeon.depth));\n\t\t\t\t\tif (hasKey) Level.set(doorCell, Terrain.UNLOCKED_EXIT);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (hasKey) {\n\t\t\t\t\tGameScene.updateKeyDisplay();\n\t\t\t\t\tGameScene.updateMap(doorCell);\n\t\t\t\t\tspend(Key.TIME_TO_UNLOCK);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t} else if (curAction instanceof HeroAction.OpenChest) {\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( ((HeroAction.OpenChest)curAction).dst );\n\t\t\t\n\t\t\tif (Dungeon.level.distance(pos, heap.pos) <= 1){\n\t\t\t\tboolean hasKey = true;\n\t\t\t\tif (heap.type == Type.SKELETON || heap.type == Type.REMAINS) {\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.BONES );\n\t\t\t\t} else if (heap.type == Type.LOCKED_CHEST){\n\t\t\t\t\thasKey = Notes.remove(new GoldenKey(Dungeon.depth));\n\t\t\t\t} else if (heap.type == Type.CRYSTAL_CHEST){\n\t\t\t\t\thasKey = Notes.remove(new CrystalKey(Dungeon.depth));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (hasKey) {\n\t\t\t\t\tGameScene.updateKeyDisplay();\n\t\t\t\t\theap.open(this);\n\t\t\t\t\tspend(Key.TIME_TO_UNLOCK);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t\tcurAction = null;\n\n\t\tif (!ready) {\n\t\t\tsuper.onOperateComplete();\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean isImmune(Class effect) {\n\t\tif (effect == Burning.class\n\t\t\t\t&& belongings.armor() != null\n\t\t\t\t&& belongings.armor().hasGlyph(Brimstone.class, this)){\n\t\t\treturn true;\n\t\t}\n\t\treturn super.isImmune(effect);\n\t}\n\n\t@Override\n\tpublic boolean isInvulnerable(Class effect) {\n\t\treturn super.isInvulnerable(effect) || buff(AnkhInvulnerability.class) != null;\n\t}\n\n\tpublic boolean search( boolean intentional ) {\n\t\t\n\t\tif (!isAlive()) return false;\n\t\t\n\t\tboolean smthFound = false;\n\n\t\tboolean circular = pointsInTalent(Talent.WIDE_SEARCH) == 1;\n\t\tint distance = heroClass == HeroClass.ROGUE ? 2 : 1;\n\t\tif (hasTalent(Talent.WIDE_SEARCH)) distance++;\n\t\t\n\t\tboolean foresight = buff(Foresight.class) != null;\n\t\tboolean foresightScan = foresight && !Dungeon.level.mapped[pos];\n\n\t\tif (foresightScan){\n\t\t\tDungeon.level.mapped[pos] = true;\n\t\t}\n\n\t\tif (foresight) {\n\t\t\tdistance = Foresight.DISTANCE;\n\t\t\tcircular = true;\n\t\t}\n\n\t\tPoint c = Dungeon.level.cellToPoint(pos);\n\n\t\tTalismanOfForesight.Foresight talisman = buff( TalismanOfForesight.Foresight.class );\n\t\tboolean cursed = talisman != null && talisman.isCursed();\n\n\t\tint[] rounding = ShadowCaster.rounding[distance];\n\n\t\tint left, right;\n\t\tint curr;\n\t\tfor (int y = Math.max(0, c.y - distance); y <= Math.min(Dungeon.level.height()-1, c.y + distance); y++) {\n\t\t\tif (!circular){\n\t\t\t\tleft = c.x - distance;\n\t\t\t} else if (rounding[Math.abs(c.y - y)] < Math.abs(c.y - y)) {\n\t\t\t\tleft = c.x - rounding[Math.abs(c.y - y)];\n\t\t\t} else {\n\t\t\t\tleft = distance;\n\t\t\t\twhile (rounding[left] < rounding[Math.abs(c.y - y)]){\n\t\t\t\t\tleft--;\n\t\t\t\t}\n\t\t\t\tleft = c.x - left;\n\t\t\t}\n\t\t\tright = Math.min(Dungeon.level.width()-1, c.x + c.x - left);\n\t\t\tleft = Math.max(0, left);\n\t\t\tfor (curr = left + y * Dungeon.level.width(); curr <= right + y * Dungeon.level.width(); curr++){\n\n\t\t\t\tif ((foresight || fieldOfView[curr]) && curr != pos) {\n\n\t\t\t\t\tif ((foresight && (!Dungeon.level.mapped[curr] || foresightScan))){\n\t\t\t\t\t\tGameScene.effectOverFog(new CheckedCell(curr, foresightScan ? pos : curr));\n\t\t\t\t\t} else if (intentional) {\n\t\t\t\t\t\tGameScene.effectOverFog(new CheckedCell(curr, pos));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (foresight){\n\t\t\t\t\t\tDungeon.level.mapped[curr] = true;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (Dungeon.level.secret[curr]){\n\t\t\t\t\t\t\n\t\t\t\t\t\tTrap trap = Dungeon.level.traps.get( curr );\n\t\t\t\t\t\tfloat chance;\n\n\t\t\t\t\t\t//searches aided by foresight always succeed, even if trap isn't searchable\n\t\t\t\t\t\tif (foresight){\n\t\t\t\t\t\t\tchance = 1f;\n\n\t\t\t\t\t\t//otherwise if the trap isn't searchable, searching always fails\n\t\t\t\t\t\t} else if (trap != null && !trap.canBeSearched){\n\t\t\t\t\t\t\tchance = 0f;\n\n\t\t\t\t\t\t//intentional searches always succeed against regular traps and doors\n\t\t\t\t\t\t} else if (intentional){\n\t\t\t\t\t\t\tchance = 1f;\n\t\t\t\t\t\t\n\t\t\t\t\t\t//unintentional searches always fail with a cursed talisman\n\t\t\t\t\t\t} else if (cursed) {\n\t\t\t\t\t\t\tchance = 0f;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t//unintentional trap detection scales from 40% at floor 0 to 30% at floor 25\n\t\t\t\t\t\t} else if (Dungeon.level.map[curr] == Terrain.SECRET_TRAP) {\n\t\t\t\t\t\t\tchance = 0.4f - (Dungeon.depth / 250f);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t//unintentional door detection scales from 20% at floor 0 to 0% at floor 20\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tchance = 0.2f - (Dungeon.depth / 100f);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//don't want to let the player search though hidden doors in tutorial\n\t\t\t\t\t\tif (SPDSettings.intro()){\n\t\t\t\t\t\t\tchance = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (Random.Float() < chance) {\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tint oldValue = Dungeon.level.map[curr];\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tGameScene.discoverTile( curr, oldValue );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tDungeon.level.discover( curr );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tScrollOfMagicMapping.discover( curr );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (fieldOfView[curr]) smthFound = true;\n\t\n\t\t\t\t\t\t\tif (talisman != null){\n\t\t\t\t\t\t\t\tif (oldValue == Terrain.SECRET_TRAP){\n\t\t\t\t\t\t\t\t\ttalisman.charge(2);\n\t\t\t\t\t\t\t\t} else if (oldValue == Terrain.SECRET_DOOR){\n\t\t\t\t\t\t\t\t\ttalisman.charge(10);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (intentional) {\n\t\t\tsprite.showStatus( CharSprite.DEFAULT, Messages.get(this, \"search\") );\n\t\t\tsprite.operate( pos );\n\t\t\tif (!Dungeon.level.locked) {\n\t\t\t\tif (cursed) {\n\t\t\t\t\tGLog.n(Messages.get(this, \"search_distracted\"));\n\t\t\t\t\tBuff.affect(this, Hunger.class).affectHunger(TIME_TO_SEARCH - (2 * HUNGER_FOR_SEARCH));\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(this, Hunger.class).affectHunger(TIME_TO_SEARCH - HUNGER_FOR_SEARCH);\n\t\t\t\t}\n\t\t\t}\n\t\t\tspendAndNext(TIME_TO_SEARCH);\n\t\t\t\n\t\t}\n\t\t\n\t\tif (smthFound) {\n\t\t\tGLog.w( Messages.get(this, \"noticed_smth\") );\n\t\t\tSample.INSTANCE.play( Assets.Sounds.SECRET );\n\t\t\tinterrupt();\n\t\t}\n\n\t\tif (foresight){\n\t\t\tGameScene.updateFog(pos, Foresight.DISTANCE+1);\n\t\t}\n\t\t\n\t\treturn smthFound;\n\t}\n\t\n\tpublic void resurrect() {\n\t\tHP = HT;\n\t\tlive();\n\n\t\tMagicalHolster holster = belongings.getItem(MagicalHolster.class);\n\n\t\tBuff.affect(this, LostInventory.class);\n\t\tBuff.affect(this, Invisibility.class, 3f);\n\t\t//lost inventory is dropped in interlevelscene\n\n\t\t//activate items that persist after lost inventory\n\t\t//FIXME this is very messy, maybe it would be better to just have one buff that\n\t\t// handled all items that recharge over time?\n\t\tfor (Item i : belongings){\n\t\t\tif (i instanceof EquipableItem && i.isEquipped(this)){\n\t\t\t\t((EquipableItem) i).activate(this);\n\t\t\t} else if (i instanceof CloakOfShadows && i.keptThroughLostInventory() && hasTalent(Talent.LIGHT_CLOAK)){\n\t\t\t\t((CloakOfShadows) i).activate(this);\n\t\t\t} else if (i instanceof Wand && i.keptThroughLostInventory()){\n\t\t\t\tif (holster != null && holster.contains(i)){\n\t\t\t\t\t((Wand) i).charge(this, MagicalHolster.HOLSTER_SCALE_FACTOR);\n\t\t\t\t} else {\n\t\t\t\t\t((Wand) i).charge(this);\n\t\t\t\t}\n\t\t\t} else if (i instanceof MagesStaff && i.keptThroughLostInventory()){\n\t\t\t\t((MagesStaff) i).applyWandChargeBuff(this);\n\t\t\t}\n\t\t}\n\n\t\tupdateHT(false);\n\t}\n\n\t@Override\n\tpublic void next() {\n\t\tif (isAlive())\n\t\t\tsuper.next();\n\t}\n\n\tpublic static interface Doom {\n\t\tpublic void onDeath();\n\t}\n}" }, { "identifier": "Terrain", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/Terrain.java", "snippet": "public class Terrain {\n\n\tpublic static final int CHASM\t\t\t= 0;\n\tpublic static final int EMPTY\t\t\t= 1;\n\tpublic static final int GRASS\t\t\t= 2;\n\tpublic static final int EMPTY_WELL\t\t= 3;\n\tpublic static final int WALL\t\t\t= 4;\n\tpublic static final int DOOR\t\t\t= 5;\n\tpublic static final int OPEN_DOOR\t\t= 6;\n\tpublic static final int ENTRANCE\t\t= 7;\n\tpublic static final int EXIT\t\t\t= 8;\n\tpublic static final int EMBERS\t\t\t= 9;\n\tpublic static final int LOCKED_DOOR\t\t= 10;\n\tpublic static final int CRYSTAL_DOOR\t= 31;\n\tpublic static final int PEDESTAL\t\t= 11;\n\tpublic static final int WALL_DECO\t\t= 12;\n\tpublic static final int BARRICADE\t\t= 13;\n\tpublic static final int EMPTY_SP\t\t= 14;\n\tpublic static final int HIGH_GRASS\t\t= 15;\n\tpublic static final int FURROWED_GRASS\t= 30;\n\n\tpublic static final int SECRET_DOOR\t = 16;\n\tpublic static final int SECRET_TRAP = 17;\n\tpublic static final int TRAP = 18;\n\tpublic static final int INACTIVE_TRAP = 19;\n\n\tpublic static final int EMPTY_DECO\t\t= 20;\n\tpublic static final int LOCKED_EXIT\t\t= 21;\n\tpublic static final int UNLOCKED_EXIT\t= 22;\n\tpublic static final int WELL\t\t\t= 24;\n\tpublic static final int BOOKSHELF\t\t= 27;\n\tpublic static final int ALCHEMY\t\t\t= 28;\n\n\tpublic static final int CUSTOM_DECO_EMPTY = 32; //regular empty tile that can't be overridden, used for custom visuals mainly\n\t//solid environment decorations\n\tpublic static final int CUSTOM_DECO\t = 23; //invisible decoration that will also be a custom visual, re-uses the old terrain ID for signs\n\tpublic static final int STATUE\t\t\t= 25;\n\tpublic static final int STATUE_SP\t\t= 26;\n\t//These decorations are environment-specific\n\t//33 and 34 are reserved for future statue-like decorations\n\tpublic static final int MINE_CRYSTAL = 35;\n\tpublic static final int MINE_BOULDER = 36;\n\n\tpublic static final int WATER\t\t = 29;\n\t\n\tpublic static final int PASSABLE\t\t= 0x01;\n\tpublic static final int LOS_BLOCKING\t= 0x02;\n\tpublic static final int FLAMABLE\t\t= 0x04;\n\tpublic static final int SECRET\t\t\t= 0x08;\n\tpublic static final int SOLID\t\t\t= 0x10;\n\tpublic static final int AVOID\t\t\t= 0x20;\n\tpublic static final int LIQUID\t\t\t= 0x40;\n\tpublic static final int PIT\t\t\t\t= 0x80;\n\t\n\tpublic static final int[] flags = new int[256];\n\tstatic {\n\t\tflags[CHASM]\t\t= AVOID\t| PIT;\n\t\tflags[EMPTY]\t\t= PASSABLE;\n\t\tflags[GRASS]\t\t= PASSABLE | FLAMABLE;\n\t\tflags[EMPTY_WELL]\t= PASSABLE;\n\t\tflags[WATER]\t\t= PASSABLE | LIQUID;\n\t\tflags[WALL]\t\t\t= LOS_BLOCKING | SOLID;\n\t\tflags[DOOR]\t\t\t= PASSABLE | LOS_BLOCKING | FLAMABLE | SOLID;\n\t\tflags[OPEN_DOOR]\t= PASSABLE | FLAMABLE;\n\t\tflags[ENTRANCE]\t\t= PASSABLE/* | SOLID*/;\n\t\tflags[EXIT]\t\t\t= PASSABLE;\n\t\tflags[EMBERS]\t\t= PASSABLE;\n\t\tflags[LOCKED_DOOR]\t= LOS_BLOCKING | SOLID;\n\t\tflags[CRYSTAL_DOOR]\t= SOLID;\n\t\tflags[PEDESTAL]\t\t= PASSABLE;\n\t\tflags[WALL_DECO]\t= flags[WALL];\n\t\tflags[BARRICADE]\t= FLAMABLE | SOLID | LOS_BLOCKING;\n\t\tflags[EMPTY_SP]\t\t= flags[EMPTY];\n\t\tflags[HIGH_GRASS]\t= PASSABLE | LOS_BLOCKING | FLAMABLE;\n\t\tflags[FURROWED_GRASS]= flags[HIGH_GRASS];\n\n\t\tflags[SECRET_DOOR] = flags[WALL] | SECRET;\n\t\tflags[SECRET_TRAP] = flags[EMPTY] | SECRET;\n\t\tflags[TRAP] = AVOID;\n\t\tflags[INACTIVE_TRAP]= flags[EMPTY];\n\n\t\tflags[EMPTY_DECO]\t= flags[EMPTY];\n\t\tflags[LOCKED_EXIT]\t= SOLID;\n\t\tflags[UNLOCKED_EXIT]= PASSABLE;\n\t\tflags[WELL]\t\t\t= AVOID;\n\t\tflags[BOOKSHELF]\t= flags[BARRICADE];\n\t\tflags[ALCHEMY]\t\t= SOLID;\n\n\t\tflags[CUSTOM_DECO_EMPTY] = flags[EMPTY];\n\t\tflags[CUSTOM_DECO] = SOLID;\n\t\tflags[STATUE] = SOLID;\n\t\tflags[STATUE_SP] = flags[STATUE];\n\n\t\tflags[MINE_CRYSTAL] = SOLID;\n\t\tflags[MINE_BOULDER] = SOLID;\n\n\t}\n\n\tpublic static int discover( int terr ) {\n\t\tswitch (terr) {\n\t\tcase SECRET_DOOR:\n\t\t\treturn DOOR;\n\t\tcase SECRET_TRAP:\n\t\t\treturn TRAP;\n\t\tdefault:\n\t\t\treturn terr;\n\t\t}\n\t}\n\n}" }, { "identifier": "Door", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/features/Door.java", "snippet": "public class Door {\n\n\tpublic static void enter( int pos ) {\n\t\tLevel.set( pos, Terrain.OPEN_DOOR );\n\t\tGameScene.updateMap( pos );\n\n\t\tif (Dungeon.level.heroFOV[pos]) {\n\t\t\tDungeon.observe();\n\t\t\tSample.INSTANCE.play( Assets.Sounds.OPEN );\n\t\t}\n\t}\n\n\tpublic static void leave( int pos ) {\n\t\tint chars = 0;\n\t\t\n\t\tfor (Char ch : Actor.chars()){\n\t\t\tif (ch.pos == pos) chars++;\n\t\t}\n\t\t\n\t\t//door does not shut if anything else is also on it\n\t\tif (Dungeon.level.heaps.get( pos ) == null && chars <= 1) {\n\t\t\tLevel.set( pos, Terrain.DOOR );\n\t\t\tGameScene.updateMap( pos );\n\t\t\tif (Dungeon.level.heroFOV[pos])\n\t\t\t\tDungeon.observe();\n\t\t}\n\t}\n}" }, { "identifier": "Messages", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/messages/Messages.java", "snippet": "public class Messages {\n\n\tprivate static ArrayList<I18NBundle> bundles;\n\tprivate static Languages lang;\n\tprivate static Locale locale;\n\n\tpublic static final String NO_TEXT_FOUND = \"!!!NO TEXT FOUND!!!\";\n\n\tpublic static Languages lang(){\n\t\treturn lang;\n\t}\n\n\tpublic static Locale locale(){\n\t\treturn locale;\n\t}\n\n\t/**\n\t * Setup Methods\n\t */\n\n\tprivate static String[] prop_files = new String[]{\n\t\t\tAssets.Messages.ACTORS,\n\t\t\tAssets.Messages.ITEMS,\n\t\t\tAssets.Messages.JOURNAL,\n\t\t\tAssets.Messages.LEVELS,\n\t\t\tAssets.Messages.MISC,\n\t\t\tAssets.Messages.PLANTS,\n\t\t\tAssets.Messages.SCENES,\n\t\t\tAssets.Messages.UI,\n\t\t\tAssets.Messages.WINDOWS\n\t};\n\n\tstatic{\n\t\tsetup(SPDSettings.language());\n\t}\n\n\tpublic static void setup( Languages lang ){\n\t\t//seeing as missing keys are part of our process, this is faster than throwing an exception\n\t\tI18NBundle.setExceptionOnMissingKey(false);\n\n\t\t//store language and locale info for various string logic\n\t\tMessages.lang = lang;\n\t\tif (lang == Languages.ENGLISH){\n\t\t\tlocale = Locale.ENGLISH;\n\t\t} else {\n\t\t\tlocale = new Locale(lang.code());\n\t\t}\n\n\t\t//strictly match the language code when fetching bundles however\n\t\tbundles = new ArrayList<>();\n\t\tLocale bundleLocal = new Locale(lang.code());\n\t\tfor (String file : prop_files) {\n\t\t\tbundles.add(I18NBundle.createBundle(Gdx.files.internal(file), bundleLocal));\n\t\t}\n\t}\n\n\n\n\t/**\n\t * Resource grabbing methods\n\t */\n\n\tpublic static String get(String key, Object...args){\n\t\treturn get(null, key, args);\n\t}\n\n\tpublic static String get(Object o, String k, Object...args){\n\t\treturn get(o.getClass(), k, args);\n\t}\n\n\tpublic static String get(Class c, String k, Object...args){\n\t\tString key;\n\t\tif (c != null){\n\t\t\tkey = c.getName().replace(\"com.shatteredpixel.shatteredpixeldungeon.\", \"\");\n\t\t\tkey += \".\" + k;\n\t\t} else\n\t\t\tkey = k;\n\n\t\tString value = getFromBundle(key.toLowerCase(Locale.ENGLISH));\n\t\tif (value != null){\n\t\t\tif (args.length > 0) return format(value, args);\n\t\t\telse return value;\n\t\t} else {\n\t\t\t//this is so child classes can inherit properties from their parents.\n\t\t\t//in cases where text is commonly grabbed as a utility from classes that aren't mean to be instantiated\n\t\t\t//(e.g. flavourbuff.dispTurns()) using .class directly is probably smarter to prevent unnecessary recursive calls.\n\t\t\tif (c != null && c.getSuperclass() != null){\n\t\t\t\treturn get(c.getSuperclass(), k, args);\n\t\t\t} else {\n\t\t\t\treturn NO_TEXT_FOUND;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static String getFromBundle(String key){\n\t\tString result;\n\t\tfor (I18NBundle b : bundles){\n\t\t\tresult = b.get(key);\n\t\t\t//if it isn't the return string for no key found, return it\n\t\t\tif (result.length() != key.length()+6 || !result.contains(key)){\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\n\n\t/**\n\t * String Utility Methods\n\t */\n\n\tpublic static String format( String format, Object...args ) {\n\t\ttry {\n\t\t\treturn String.format(Locale.ENGLISH, format, args);\n\t\t} catch (IllegalFormatException e) {\n\t\t\tShatteredPixelDungeon.reportException( new Exception(\"formatting error for the string: \" + format, e) );\n\t\t\treturn format;\n\t\t}\n\t}\n\n\tprivate static HashMap<String, DecimalFormat> formatters = new HashMap<>();\n\n\tpublic static String decimalFormat( String format, double number ){\n\t\tif (!formatters.containsKey(format)){\n\t\t\tformatters.put(format, new DecimalFormat(format, DecimalFormatSymbols.getInstance(Locale.ENGLISH)));\n\t\t}\n\t\treturn formatters.get(format).format(number);\n\t}\n\n\tpublic static String capitalize( String str ){\n\t\tif (str.length() == 0) return str;\n\t\telse return str.substring( 0, 1 ).toUpperCase(locale) + str.substring( 1 );\n\t}\n\n\t//Words which should not be capitalized in title case, mostly prepositions which appear ingame\n\t//This list is not comprehensive!\n\tprivate static final HashSet<String> noCaps = new HashSet<>(\n\t\t\tArrays.asList(\"a\", \"an\", \"and\", \"of\", \"by\", \"to\", \"the\", \"x\", \"for\")\n\t);\n\n\tpublic static String titleCase( String str ){\n\t\t//English capitalizes every word except for a few exceptions\n\t\tif (lang == Languages.ENGLISH){\n\t\t\tString result = \"\";\n\t\t\t//split by any unicode space character\n\t\t\tfor (String word : str.split(\"(?<=\\\\p{Zs})\")){\n\t\t\t\tif (noCaps.contains(word.trim().toLowerCase(Locale.ENGLISH).replaceAll(\":|[0-9]\", \"\"))){\n\t\t\t\t\tresult += word;\n\t\t\t\t} else {\n\t\t\t\t\tresult += capitalize(word);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//first character is always capitalized.\n\t\t\treturn capitalize(result);\n\t\t}\n\n\t\t//Otherwise, use sentence case\n\t\treturn capitalize(str);\n\t}\n\n\tpublic static String upperCase( String str ){\n\t\treturn str.toUpperCase(locale);\n\t}\n\n\tpublic static String lowerCase( String str ){\n\t\treturn str.toLowerCase(locale);\n\t}\n}" }, { "identifier": "PixelScene", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/scenes/PixelScene.java", "snippet": "public class PixelScene extends Scene {\n\n\t// Minimum virtual display size for mobile portrait orientation\n\tpublic static final float MIN_WIDTH_P = 135;\n\tpublic static final float MIN_HEIGHT_P = 225;\n\n\t// Minimum virtual display size for mobile landscape orientation\n\tpublic static final float MIN_WIDTH_L = 240;\n\tpublic static final float MIN_HEIGHT_L = 160;\n\n\t// Minimum virtual display size for full desktop UI (landscape only)\n\t//TODO maybe include another scale for mixed UI? might make it more accessible to mobile devices\n\t// mixed UI has similar requirements to mobile landscape tbh... Maybe just merge them?\n\t// mixed UI can possible be used on mobile portrait for tablets though.. Does that happen often?\n\tpublic static final float MIN_WIDTH_FULL = 360;\n\tpublic static final float MIN_HEIGHT_FULL = 200;\n\n\tpublic static int defaultZoom = 0;\n\tpublic static int maxDefaultZoom = 0;\n\tpublic static int maxScreenZoom = 0;\n\tpublic static float minZoom;\n\tpublic static float maxZoom;\n\n\tpublic static Camera uiCamera;\n\n\t//stylized 3x5 bitmapped pixel font. Only latin characters supported.\n\tpublic static BitmapText.Font pixelFont;\n\n\tprotected boolean inGameScene = false;\n\n\tprivate Signal.Listener<KeyEvent> fullscreenListener;\n\n\t@Override\n\tpublic void create() {\n\n\t\tsuper.create();\n\n\t\tGameScene.scene = null;\n\n\t\t//flush the texture cache whenever moving from ingame to menu, helps reduce memory load\n\t\tif (!inGameScene && InterlevelScene.lastRegion != -1){\n\t\t\tInterlevelScene.lastRegion = -1;\n\t\t\tTextureCache.clear();\n\t\t}\n\n\t\tfloat minWidth, minHeight, scaleFactor;\n\t\tif (SPDSettings.interfaceSize() > 0){\n\t\t\tminWidth = MIN_WIDTH_FULL;\n\t\t\tminHeight = MIN_HEIGHT_FULL;\n\t\t\tscaleFactor = 3.75f;\n\t\t} else if (landscape()) {\n\t\t\tminWidth = MIN_WIDTH_L;\n\t\t\tminHeight = MIN_HEIGHT_L;\n\t\t\tscaleFactor = 2.5f;\n\t\t} else {\n\t\t\tminWidth = MIN_WIDTH_P;\n\t\t\tminHeight = MIN_HEIGHT_P;\n\t\t\tscaleFactor = 2.5f;\n\t\t}\n\n\t\tmaxDefaultZoom = (int)Math.min(Game.width/minWidth, Game.height/minHeight);\n\t\tmaxScreenZoom = (int)Math.min(Game.dispWidth/minWidth, Game.dispHeight/minHeight);\n\t\tdefaultZoom = SPDSettings.scale();\n\n\t\tif (defaultZoom < Math.ceil( Game.density * 2 ) || defaultZoom > maxDefaultZoom){\n\t\t\tdefaultZoom = (int)GameMath.gate(2, (int)Math.ceil( Game.density * scaleFactor ), maxDefaultZoom);\n\n\t\t\tif (SPDSettings.interfaceSize() > 0 && defaultZoom < (maxDefaultZoom+1)/2){\n\t\t\t\tdefaultZoom = (maxDefaultZoom+1)/2;\n\t\t\t}\n\t\t}\n\n\t\tminZoom = 1;\n\t\tmaxZoom = defaultZoom * 2;\n\n\t\tCamera.reset( new PixelCamera( defaultZoom ) );\n\n\t\tfloat uiZoom = defaultZoom;\n\t\tuiCamera = Camera.createFullscreen( uiZoom );\n\t\tCamera.add( uiCamera );\n\n\t\t// 3x5 (6)\n\t\tpixelFont = Font.colorMarked(\n\t\t\tTextureCache.get( Assets.Fonts.PIXELFONT), 0x00000000, BitmapText.Font.LATIN_FULL );\n\t\tpixelFont.baseLine = 6;\n\t\tpixelFont.tracking = -1;\n\t\t\n\t\t//set up the texture size which rendered text will use for any new glyphs.\n\t\tint renderedTextPageSize;\n\t\tif (defaultZoom <= 3){\n\t\t\trenderedTextPageSize = 256;\n\t\t} else if (defaultZoom <= 8){\n\t\t\trenderedTextPageSize = 512;\n\t\t} else {\n\t\t\trenderedTextPageSize = 1024;\n\t\t}\n\t\t//asian languages have many more unique characters, so increase texture size to anticipate that\n\t\tif (Messages.lang() == Languages.KOREAN ||\n\t\t\t\tMessages.lang() == Languages.CHINESE ||\n\t\t\t\tMessages.lang() == Languages.JAPANESE){\n\t\t\trenderedTextPageSize *= 2;\n\t\t}\n\t\tGame.platform.setupFontGenerators(renderedTextPageSize, SPDSettings.systemFont());\n\n\t\tTooltip.resetLastUsedTime();\n\n\t\tCursor.setCustomCursor(Cursor.Type.DEFAULT, defaultZoom);\n\n\t}\n\n\t@Override\n\tpublic void update() {\n\t\t//we create this here so that it is last in the scene\n\t\tif (DeviceCompat.isDesktop() && fullscreenListener == null){\n\t\t\tKeyEvent.addKeyListener(fullscreenListener = new Signal.Listener<KeyEvent>() {\n\n\t\t\t\tprivate boolean alt;\n\t\t\t\tprivate boolean enter;\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean onSignal(KeyEvent keyEvent) {\n\n\t\t\t\t\t//we don't use keybindings for these as we want the user to be able to\n\t\t\t\t\t// bind these keys to other actions when pressed individually\n\t\t\t\t\tif (keyEvent.code == Input.Keys.ALT_RIGHT){\n\t\t\t\t\t\talt = keyEvent.pressed;\n\t\t\t\t\t} else if (keyEvent.code == Input.Keys.ENTER){\n\t\t\t\t\t\tenter = keyEvent.pressed;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (alt && enter){\n\t\t\t\t\t\tSPDSettings.fullscreen(!SPDSettings.fullscreen());\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tsuper.update();\n\t\t//20% deadzone\n\t\tif (!Cursor.isCursorCaptured()) {\n\t\t\tif (Math.abs(ControllerHandler.rightStickPosition.x) >= 0.2f\n\t\t\t\t\t|| Math.abs(ControllerHandler.rightStickPosition.y) >= 0.2f) {\n\t\t\t\tif (!ControllerHandler.controllerPointerActive()) {\n\t\t\t\t\tControllerHandler.setControllerPointer(true);\n\t\t\t\t}\n\n\t\t\t\tint sensitivity = SPDSettings.controllerPointerSensitivity() * 100;\n\n\t\t\t\t//cursor moves 100xsens scaled pixels per second at full speed\n\t\t\t\t//35x at 50% movement, ~9x at 20% deadzone threshold\n\t\t\t\tfloat xMove = (float) Math.pow(Math.abs(ControllerHandler.rightStickPosition.x), 1.5);\n\t\t\t\tif (ControllerHandler.rightStickPosition.x < 0) xMove = -xMove;\n\n\t\t\t\tfloat yMove = (float) Math.pow(Math.abs(ControllerHandler.rightStickPosition.y), 1.5);\n\t\t\t\tif (ControllerHandler.rightStickPosition.y < 0) yMove = -yMove;\n\n\t\t\t\tPointF virtualCursorPos = ControllerHandler.getControllerPointerPos();\n\t\t\t\tvirtualCursorPos.x += defaultZoom * sensitivity * Game.elapsed * xMove;\n\t\t\t\tvirtualCursorPos.y += defaultZoom * sensitivity * Game.elapsed * yMove;\n\n\t\t\t\tPointF cameraShift = new PointF();\n\n\t\t\t\tif (virtualCursorPos.x < 0){\n\t\t\t\t\tcameraShift.x = virtualCursorPos.x;\n\t\t\t\t\tvirtualCursorPos.x = 0;\n\t\t\t\t} else if (virtualCursorPos.x > Camera.main.screenWidth()){\n\t\t\t\t\tcameraShift.x = (virtualCursorPos.x - Camera.main.screenWidth());\n\t\t\t\t\tvirtualCursorPos.x = Camera.main.screenWidth();\n\t\t\t\t}\n\n\t\t\t\tif (virtualCursorPos.y < 0){\n\t\t\t\t\tcameraShift.y = virtualCursorPos.y;\n\t\t\t\t\tvirtualCursorPos.y = 0;\n\t\t\t\t} else if (virtualCursorPos.y > Camera.main.screenHeight()){\n\t\t\t\t\tcameraShift.y = (virtualCursorPos.y - Camera.main.screenHeight());\n\t\t\t\t\tvirtualCursorPos.y = Camera.main.screenHeight();\n\t\t\t\t}\n\n\t\t\t\tcameraShift.invScale(Camera.main.zoom);\n\t\t\t\tcameraShift.x *= Camera.main.edgeScroll.x;\n\t\t\t\tcameraShift.y *= Camera.main.edgeScroll.y;\n\t\t\t\tif (cameraShift.length() > 0){\n\t\t\t\t\tCamera.main.shift(cameraShift);\n\t\t\t\t}\n\t\t\t\tControllerHandler.updateControllerPointer(virtualCursorPos, true);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate Image cursor = null;\n\n\t@Override\n\tpublic synchronized void draw() {\n\t\tsuper.draw();\n\n\t\t//cursor is separate from the rest of the scene, always appears above\n\t\tif (ControllerHandler.controllerPointerActive()){\n\t\t\tif (cursor == null){\n\t\t\t\tcursor = new Image(Cursor.Type.CONTROLLER.file);\n\t\t\t}\n\n\t\t\tPointF virtualCursorPos = ControllerHandler.getControllerPointerPos();\n\t\t\tcursor.x = (virtualCursorPos.x / defaultZoom) - cursor.width()/2f;\n\t\t\tcursor.y = (virtualCursorPos.y / defaultZoom) - cursor.height()/2f;\n\t\t\tcursor.camera = uiCamera;\n\t\t\talign(cursor);\n\t\t\tcursor.draw();\n\t\t}\n\t}\n\n\t//FIXME this system currently only works for a subset of windows\n\tprivate static ArrayList<Class<?extends Window>> savedWindows = new ArrayList<>();\n\tprivate static Class<?extends PixelScene> savedClass = null;\n\t\n\tpublic synchronized void saveWindows(){\n\t\tif (members == null) return;\n\n\t\tsavedWindows.clear();\n\t\tsavedClass = getClass();\n\t\tfor (Gizmo g : members.toArray(new Gizmo[0])){\n\t\t\tif (g instanceof Window){\n\t\t\t\tsavedWindows.add((Class<? extends Window>) g.getClass());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic synchronized void restoreWindows(){\n\t\tif (getClass().equals(savedClass)){\n\t\t\tfor (Class<?extends Window> w : savedWindows){\n\t\t\t\ttry{\n\t\t\t\t\tadd(Reflection.newInstanceUnhandled(w));\n\t\t\t\t} catch (Exception e){\n\t\t\t\t\t//window has no public zero-arg constructor, just eat the exception\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsavedWindows.clear();\n\t}\n\n\t@Override\n\tpublic void destroy() {\n\t\tsuper.destroy();\n\t\tPointerEvent.clearListeners();\n\t\tif (fullscreenListener != null){\n\t\t\tKeyEvent.removeKeyListener(fullscreenListener);\n\t\t}\n\t\tif (cursor != null){\n\t\t\tcursor.destroy();\n\t\t}\n\t}\n\n\tpublic static boolean landscape(){\n\t\treturn SPDSettings.interfaceSize() > 0 || Game.width > Game.height;\n\t}\n\n\n\tpublic static RenderedTextBlock renderTextBlock(int size ){\n\t\treturn renderTextBlock(\"\", size);\n\t}\n\n\tpublic static RenderedTextBlock renderTextBlock(String text, int size ){\n\t\tRenderedTextBlock result = new RenderedTextBlock( text, size*defaultZoom);\n\t\tresult.zoom(1/(float)defaultZoom);\n\t\treturn result;\n\t}\n\n\t/**\n\t * These methods align UI elements to device pixels.\n\t * e.g. if we have a scale of 3x then valid positions are #.0, #.33, #.67\n\t */\n\n\tpublic static float align( float pos ) {\n\t\treturn Math.round(pos * defaultZoom) / (float)defaultZoom;\n\t}\n\n\tpublic static float align( Camera camera, float pos ) {\n\t\treturn Math.round(pos * camera.zoom) / camera.zoom;\n\t}\n\n\tpublic static void align( Visual v ) {\n\t\tv.x = align( v.x );\n\t\tv.y = align( v.y );\n\t}\n\n\tpublic static void align( Component c ){\n\t\tc.setPos(align(c.left()), align(c.top()));\n\t}\n\n\tpublic static boolean noFade = false;\n\tprotected void fadeIn() {\n\t\tif (noFade) {\n\t\t\tnoFade = false;\n\t\t} else {\n\t\t\tfadeIn( 0xFF000000, false );\n\t\t}\n\t}\n\t\n\tprotected void fadeIn( int color, boolean light ) {\n\t\tadd( new Fader( color, light ) );\n\t}\n\t\n\tpublic static void showBadge( Badges.Badge badge ) {\n\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t@Override\n\t\t\tpublic void call() {\n\t\t\t\tScene s = Game.scene();\n\t\t\t\tif (s != null) {\n\t\t\t\t\tBadgeBanner banner = BadgeBanner.show(badge.image);\n\t\t\t\t\ts.add(banner);\n\t\t\t\t\tfloat offset = Camera.main.centerOffset.y;\n\n\t\t\t\t\tint left = uiCamera.width/2 - BadgeBanner.SIZE/2;\n\t\t\t\t\tleft -= (BadgeBanner.SIZE * BadgeBanner.DEFAULT_SCALE * (BadgeBanner.showing.size()-1))/2;\n\t\t\t\t\tfor (int i = 0; i < BadgeBanner.showing.size(); i++){\n\t\t\t\t\t\tbanner = BadgeBanner.showing.get(i);\n\t\t\t\t\t\tbanner.camera = uiCamera;\n\t\t\t\t\t\tbanner.x = align(banner.camera, left);\n\t\t\t\t\t\tbanner.y = align(uiCamera, (uiCamera.height - banner.height) / 2 - banner.height / 2 - 16 - offset);\n\t\t\t\t\t\tleft += BadgeBanner.SIZE * BadgeBanner.DEFAULT_SCALE;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\t\n\tpublic static void shake( float magnitude, float duration){\n\t\tmagnitude *= SPDSettings.screenShake();\n\t\tCamera.main.shake(magnitude, duration);\n\t}\n\t\n\tprotected static class Fader extends ColorBlock {\n\t\t\n\t\tprivate static float FADE_TIME = 1f;\n\t\t\n\t\tprivate boolean light;\n\t\t\n\t\tprivate float time;\n\n\t\tprivate static Fader INSTANCE;\n\t\t\n\t\tpublic Fader( int color, boolean light ) {\n\t\t\tsuper( uiCamera.width, uiCamera.height, color );\n\t\t\t\n\t\t\tthis.light = light;\n\t\t\t\n\t\t\tcamera = uiCamera;\n\t\t\t\n\t\t\talpha( 1f );\n\t\t\ttime = FADE_TIME;\n\n\t\t\tif (INSTANCE != null){\n\t\t\t\tINSTANCE.killAndErase();\n\t\t\t}\n\t\t\tINSTANCE = this;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void update() {\n\t\t\t\n\t\t\tsuper.update();\n\t\t\t\n\t\t\tif ((time -= Game.elapsed) <= 0) {\n\t\t\t\talpha( 0f );\n\t\t\t\tparent.remove( this );\n\t\t\t\tdestroy();\n\t\t\t\tif (INSTANCE == this) {\n\t\t\t\t\tINSTANCE = null;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\talpha( time / FADE_TIME );\n\t\t\t}\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void draw() {\n\t\t\tif (light) {\n\t\t\t\tBlending.setLightMode();\n\t\t\t\tsuper.draw();\n\t\t\t\tBlending.setNormalMode();\n\t\t\t} else {\n\t\t\t\tsuper.draw();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate static class PixelCamera extends Camera {\n\t\t\n\t\tpublic PixelCamera( float zoom ) {\n\t\t\tsuper(\n\t\t\t\t(int)(Game.width - Math.ceil( Game.width / zoom ) * zoom) / 2,\n\t\t\t\t(int)(Game.height - Math.ceil( Game.height / zoom ) * zoom) / 2,\n\t\t\t\t(int)Math.ceil( Game.width / zoom ),\n\t\t\t\t(int)Math.ceil( Game.height / zoom ), zoom );\n\t\t\tfullScreen = true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected void updateMatrix() {\n\t\t\tfloat sx = align( this, scroll.x + shakeX );\n\t\t\tfloat sy = align( this, scroll.y + shakeY );\n\t\t\t\n\t\t\tmatrix[0] = +zoom * invW2;\n\t\t\tmatrix[5] = -zoom * invH2;\n\t\t\t\n\t\t\tmatrix[12] = -1 + x * invW2 - sx * matrix[0];\n\t\t\tmatrix[13] = +1 - y * invH2 - sy * matrix[5];\n\t\t\t\n\t\t}\n\t}\n}" }, { "identifier": "ItemSpriteSheet", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/sprites/ItemSpriteSheet.java", "snippet": "public class ItemSpriteSheet {\n\n\tprivate static final int WIDTH = 16;\n\tpublic static final int SIZE = 16;\n\n\tpublic static TextureFilm film = new TextureFilm( Assets.Sprites.ITEMS, SIZE, SIZE );\n\n\tprivate static int xy(int x, int y){\n\t\tx -= 1; y -= 1;\n\t\treturn x + WIDTH*y;\n\t}\n\n\tprivate static void assignItemRect( int item, int width, int height ){\n\t\tint x = (item % WIDTH) * SIZE;\n\t\tint y = (item / WIDTH) * SIZE;\n\t\tfilm.add( item, x, y, x+width, y+height);\n\t}\n\n\tprivate static final int PLACEHOLDERS = xy(1, 1); //16 slots\n\t//SOMETHING is the default item sprite at position 0. May show up ingame if there are bugs.\n\tpublic static final int SOMETHING = PLACEHOLDERS+0;\n\tpublic static final int WEAPON_HOLDER = PLACEHOLDERS+1;\n\tpublic static final int ARMOR_HOLDER = PLACEHOLDERS+2;\n\tpublic static final int MISSILE_HOLDER = PLACEHOLDERS+3;\n\tpublic static final int WAND_HOLDER = PLACEHOLDERS+4;\n\tpublic static final int RING_HOLDER = PLACEHOLDERS+5;\n\tpublic static final int ARTIFACT_HOLDER = PLACEHOLDERS+6;\n\tpublic static final int FOOD_HOLDER = PLACEHOLDERS+7;\n\tpublic static final int BOMB_HOLDER = PLACEHOLDERS+8;\n\tpublic static final int POTION_HOLDER = PLACEHOLDERS+9;\n\tpublic static final int SCROLL_HOLDER = PLACEHOLDERS+11;\n\tpublic static final int SEED_HOLDER = PLACEHOLDERS+10;\n\tpublic static final int STONE_HOLDER = PLACEHOLDERS+12;\n\tpublic static final int CATA_HOLDER = PLACEHOLDERS+13;\n\tpublic static final int ELIXIR_HOLDER = PLACEHOLDERS+14;\n\tpublic static final int SPELL_HOLDER = PLACEHOLDERS+15;\n\tstatic{\n\t\tassignItemRect(SOMETHING, 8, 13);\n\t\tassignItemRect(WEAPON_HOLDER, 14, 14);\n\t\tassignItemRect(ARMOR_HOLDER, 14, 12);\n\t\tassignItemRect(MISSILE_HOLDER, 15, 15);\n\t\tassignItemRect(WAND_HOLDER, 14, 14);\n\t\tassignItemRect(RING_HOLDER, 8, 10);\n\t\tassignItemRect(ARTIFACT_HOLDER, 15, 15);\n\t\tassignItemRect(FOOD_HOLDER, 15, 11);\n\t\tassignItemRect(BOMB_HOLDER, 10, 13);\n\t\tassignItemRect(POTION_HOLDER, 12, 14);\n\t\tassignItemRect(SEED_HOLDER, 10, 10);\n\t\tassignItemRect(SCROLL_HOLDER, 15, 14);\n\t\tassignItemRect(STONE_HOLDER, 14, 12);\n\t\tassignItemRect(CATA_HOLDER, 6, 15);\n\t\tassignItemRect(ELIXIR_HOLDER, 12, 14);\n\t\tassignItemRect(SPELL_HOLDER, 8, 16);\n\t}\n\n\tprivate static final int UNCOLLECTIBLE = xy(1, 2); //16 slots\n\tpublic static final int GOLD = UNCOLLECTIBLE+0;\n\tpublic static final int ENERGY = UNCOLLECTIBLE+1;\n\n\tpublic static final int DEWDROP = UNCOLLECTIBLE+3;\n\tpublic static final int PETAL = UNCOLLECTIBLE+4;\n\tpublic static final int SANDBAG = UNCOLLECTIBLE+5;\n\tpublic static final int SPIRIT_ARROW = UNCOLLECTIBLE+6;\n\t\n\tpublic static final int TENGU_BOMB = UNCOLLECTIBLE+8;\n\tpublic static final int TENGU_SHOCKER = UNCOLLECTIBLE+9;\n\tstatic{\n\t\tassignItemRect(GOLD, 15, 13);\n\t\tassignItemRect(ENERGY, 16, 16);\n\n\t\tassignItemRect(DEWDROP, 10, 10);\n\t\tassignItemRect(PETAL, 8, 8);\n\t\tassignItemRect(SANDBAG, 10, 10);\n\t\tassignItemRect(SPIRIT_ARROW,11, 11);\n\t\t\n\t\tassignItemRect(TENGU_BOMB, 10, 10);\n\t\tassignItemRect(TENGU_SHOCKER, 10, 10);\n\t}\n\n\tprivate static final int CONTAINERS = xy(1, 3); //16 slots\n\tpublic static final int BONES = CONTAINERS+0;\n\tpublic static final int REMAINS = CONTAINERS+1;\n\tpublic static final int TOMB = CONTAINERS+2;\n\tpublic static final int GRAVE = CONTAINERS+3;\n\tpublic static final int CHEST = CONTAINERS+4;\n\tpublic static final int LOCKED_CHEST = CONTAINERS+5;\n\tpublic static final int CRYSTAL_CHEST = CONTAINERS+6;\n\tpublic static final int EBONY_CHEST = CONTAINERS+7;\n\tstatic{\n\t\tassignItemRect(BONES, 14, 11);\n\t\tassignItemRect(REMAINS, 14, 11);\n\t\tassignItemRect(TOMB, 14, 15);\n\t\tassignItemRect(GRAVE, 14, 15);\n\t\tassignItemRect(CHEST, 16, 14);\n\t\tassignItemRect(LOCKED_CHEST, 16, 14);\n\t\tassignItemRect(CRYSTAL_CHEST, 16, 14);\n\t\tassignItemRect(EBONY_CHEST, 16, 14);\n\t}\n\n\tprivate static final int MISC_CONSUMABLE = xy(1, 4); //16 slots\n\tpublic static final int ANKH = MISC_CONSUMABLE +0;\n\tpublic static final int STYLUS = MISC_CONSUMABLE +1;\n\tpublic static final int SEAL = MISC_CONSUMABLE +2;\n\tpublic static final int TORCH = MISC_CONSUMABLE +3;\n\tpublic static final int BEACON = MISC_CONSUMABLE +4;\n\tpublic static final int HONEYPOT = MISC_CONSUMABLE +5;\n\tpublic static final int SHATTPOT = MISC_CONSUMABLE +6;\n\tpublic static final int IRON_KEY = MISC_CONSUMABLE +7;\n\tpublic static final int GOLDEN_KEY = MISC_CONSUMABLE +8;\n\tpublic static final int CRYSTAL_KEY = MISC_CONSUMABLE +9;\n\tpublic static final int SKELETON_KEY = MISC_CONSUMABLE +10;\n\tpublic static final int MASK = MISC_CONSUMABLE +11;\n\tpublic static final int CROWN = MISC_CONSUMABLE +12;\n\tpublic static final int AMULET = MISC_CONSUMABLE +13;\n\tpublic static final int MASTERY = MISC_CONSUMABLE +14;\n\tpublic static final int KIT = MISC_CONSUMABLE +15;\n\tstatic{\n\t\tassignItemRect(ANKH, 10, 16);\n\t\tassignItemRect(STYLUS, 12, 13);\n\t\t\n\t\tassignItemRect(SEAL, 9, 15);\n\t\tassignItemRect(TORCH, 12, 15);\n\t\tassignItemRect(BEACON, 16, 15);\n\t\t\n\t\tassignItemRect(HONEYPOT, 14, 12);\n\t\tassignItemRect(SHATTPOT, 14, 12);\n\t\tassignItemRect(IRON_KEY, 8, 14);\n\t\tassignItemRect(GOLDEN_KEY, 8, 14);\n\t\tassignItemRect(CRYSTAL_KEY, 8, 14);\n\t\tassignItemRect(SKELETON_KEY, 8, 14);\n\t\tassignItemRect(MASK, 11, 9);\n\t\tassignItemRect(CROWN, 13, 7);\n\t\tassignItemRect(AMULET, 16, 16);\n\t\tassignItemRect(MASTERY, 13, 16);\n\t\tassignItemRect(KIT, 16, 15);\n\t}\n\t\n\tprivate static final int BOMBS = xy(1, 5); //16 slots\n\tpublic static final int BOMB = BOMBS+0;\n\tpublic static final int DBL_BOMB = BOMBS+1;\n\tpublic static final int FIRE_BOMB = BOMBS+2;\n\tpublic static final int FROST_BOMB = BOMBS+3;\n\tpublic static final int REGROWTH_BOMB = BOMBS+4;\n\tpublic static final int FLASHBANG = BOMBS+5;\n\tpublic static final int SHOCK_BOMB = BOMBS+6;\n\tpublic static final int HOLY_BOMB = BOMBS+7;\n\tpublic static final int WOOLY_BOMB = BOMBS+8;\n\tpublic static final int NOISEMAKER = BOMBS+9;\n\tpublic static final int ARCANE_BOMB = BOMBS+10;\n\tpublic static final int SHRAPNEL_BOMB = BOMBS+11;\n\t\n\tstatic{\n\t\tassignItemRect(BOMB, 10, 13);\n\t\tassignItemRect(DBL_BOMB, 14, 13);\n\t\tassignItemRect(FIRE_BOMB, 13, 12);\n\t\tassignItemRect(FROST_BOMB, 13, 12);\n\t\tassignItemRect(REGROWTH_BOMB, 13, 12);\n\t\tassignItemRect(FLASHBANG, 13, 12);\n\t\tassignItemRect(SHOCK_BOMB, 10, 13);\n\t\tassignItemRect(HOLY_BOMB, 10, 13);\n\t\tassignItemRect(WOOLY_BOMB, 10, 13);\n\t\tassignItemRect(NOISEMAKER, 10, 13);\n\t\tassignItemRect(ARCANE_BOMB, 10, 13);\n\t\tassignItemRect(SHRAPNEL_BOMB, 10, 13);\n\t}\n\n\t\n\t //16 free slots\n\n\tprivate static final int WEP_TIER1 = xy(1, 7); //8 slots\n\tpublic static final int WORN_SHORTSWORD = WEP_TIER1+0;\n\tpublic static final int CUDGEL = WEP_TIER1+1;\n\tpublic static final int GLOVES = WEP_TIER1+2;\n\tpublic static final int RAPIER = WEP_TIER1+3;\n\tpublic static final int DAGGER = WEP_TIER1+4;\n\tpublic static final int MAGES_STAFF = WEP_TIER1+5;\n\tstatic{\n\t\tassignItemRect(WORN_SHORTSWORD, 13, 13);\n\t\tassignItemRect(GLOVES, 12, 16);\n\t\tassignItemRect(RAPIER, 13, 14);\n\t\tassignItemRect(DAGGER, 12, 13);\n\t\tassignItemRect(MAGES_STAFF, 15, 16);\n\t}\n\n\tprivate static final int WEP_TIER2 = xy(9, 7); //8 slots\n\tpublic static final int SHORTSWORD = WEP_TIER2+0;\n\tpublic static final int HAND_AXE = WEP_TIER2+1;\n\tpublic static final int SPEAR = WEP_TIER2+2;\n\tpublic static final int QUARTERSTAFF = WEP_TIER2+3;\n\tpublic static final int DIRK = WEP_TIER2+4;\n\tpublic static final int SICKLE = WEP_TIER2+5;\n\tstatic{\n\t\tassignItemRect(SHORTSWORD, 13, 13);\n\t\tassignItemRect(HAND_AXE, 12, 14);\n\t\tassignItemRect(SPEAR, 16, 16);\n\t\tassignItemRect(QUARTERSTAFF, 16, 16);\n\t\tassignItemRect(DIRK, 13, 14);\n\t\tassignItemRect(SICKLE, 15, 15);\n\t}\n\n\tprivate static final int WEP_TIER3 = xy(1, 8); //8 slots\n\tpublic static final int SWORD = WEP_TIER3+0;\n\tpublic static final int MACE = WEP_TIER3+1;\n\tpublic static final int SCIMITAR = WEP_TIER3+2;\n\tpublic static final int ROUND_SHIELD = WEP_TIER3+3;\n\tpublic static final int SAI = WEP_TIER3+4;\n\tpublic static final int WHIP = WEP_TIER3+5;\n\tstatic{\n\t\tassignItemRect(SWORD, 14, 14);\n\t\tassignItemRect(MACE, 15, 15);\n\t\tassignItemRect(SCIMITAR, 13, 16);\n\t\tassignItemRect(ROUND_SHIELD, 16, 16);\n\t\tassignItemRect(SAI, 16, 16);\n\t\tassignItemRect(WHIP, 14, 14);\n\t}\n\n\tprivate static final int WEP_TIER4 = xy(9, 8); //8 slots\n\tpublic static final int LONGSWORD = WEP_TIER4+0;\n\tpublic static final int BATTLE_AXE = WEP_TIER4+1;\n\tpublic static final int FLAIL = WEP_TIER4+2;\n\tpublic static final int RUNIC_BLADE = WEP_TIER4+3;\n\tpublic static final int ASSASSINS_BLADE = WEP_TIER4+4;\n\tpublic static final int CROSSBOW = WEP_TIER4+5;\n\tpublic static final int KATANA = WEP_TIER4+6;\n\tstatic{\n\t\tassignItemRect(LONGSWORD, 15, 15);\n\t\tassignItemRect(BATTLE_AXE, 16, 16);\n\t\tassignItemRect(FLAIL, 14, 14);\n\t\tassignItemRect(RUNIC_BLADE, 14, 14);\n\t\tassignItemRect(ASSASSINS_BLADE, 14, 15);\n\t\tassignItemRect(CROSSBOW, 15, 15);\n\t\tassignItemRect(KATANA, 15, 16);\n\t}\n\n\tprivate static final int WEP_TIER5 = xy(1, 9); //8 slots\n\tpublic static final int GREATSWORD = WEP_TIER5+0;\n\tpublic static final int WAR_HAMMER = WEP_TIER5+1;\n\tpublic static final int GLAIVE = WEP_TIER5+2;\n\tpublic static final int GREATAXE = WEP_TIER5+3;\n\tpublic static final int GREATSHIELD = WEP_TIER5+4;\n\tpublic static final int GAUNTLETS = WEP_TIER5+5;\n\tpublic static final int WAR_SCYTHE = WEP_TIER5+6;\n\tstatic{\n\t\tassignItemRect(GREATSWORD, 16, 16);\n\t\tassignItemRect(WAR_HAMMER, 16, 16);\n\t\tassignItemRect(GLAIVE, 16, 16);\n\t\tassignItemRect(GREATAXE, 12, 16);\n\t\tassignItemRect(GREATSHIELD, 12, 16);\n\t\tassignItemRect(GAUNTLETS, 13, 15);\n\t\tassignItemRect(WAR_SCYTHE, 14, 15);\n\t}\n\n\t //8 free slots\n\n\tprivate static final int MISSILE_WEP = xy(1, 10); //16 slots. 3 per tier + bow\n\tpublic static final int SPIRIT_BOW = MISSILE_WEP+0;\n\t\n\tpublic static final int THROWING_SPIKE = MISSILE_WEP+1;\n\tpublic static final int THROWING_KNIFE = MISSILE_WEP+2;\n\tpublic static final int THROWING_STONE = MISSILE_WEP+3;\n\t\n\tpublic static final int FISHING_SPEAR = MISSILE_WEP+4;\n\tpublic static final int SHURIKEN = MISSILE_WEP+5;\n\tpublic static final int THROWING_CLUB = MISSILE_WEP+6;\n\t\n\tpublic static final int THROWING_SPEAR = MISSILE_WEP+7;\n\tpublic static final int BOLAS = MISSILE_WEP+8;\n\tpublic static final int KUNAI = MISSILE_WEP+9;\n\t\n\tpublic static final int JAVELIN = MISSILE_WEP+10;\n\tpublic static final int TOMAHAWK = MISSILE_WEP+11;\n\tpublic static final int BOOMERANG = MISSILE_WEP+12;\n\t\n\tpublic static final int TRIDENT = MISSILE_WEP+13;\n\tpublic static final int THROWING_HAMMER = MISSILE_WEP+14;\n\tpublic static final int FORCE_CUBE = MISSILE_WEP+15;\n\t\n\tstatic{\n\t\tassignItemRect(SPIRIT_BOW, 16, 16);\n\t\t\n\t\tassignItemRect(THROWING_SPIKE, 11, 10);\n\t\tassignItemRect(THROWING_KNIFE, 12, 13);\n\t\tassignItemRect(THROWING_STONE, 12, 10);\n\t\t\n\t\tassignItemRect(FISHING_SPEAR, 11, 11);\n\t\tassignItemRect(SHURIKEN, 12, 12);\n\t\tassignItemRect(THROWING_CLUB, 12, 12);\n\t\t\n\t\tassignItemRect(THROWING_SPEAR, 13, 13);\n\t\tassignItemRect(BOLAS, 15, 14);\n\t\tassignItemRect(KUNAI, 15, 15);\n\t\t\n\t\tassignItemRect(JAVELIN, 16, 16);\n\t\tassignItemRect(TOMAHAWK, 13, 13);\n\t\tassignItemRect(BOOMERANG, 14, 14);\n\t\t\n\t\tassignItemRect(TRIDENT, 16, 16);\n\t\tassignItemRect(THROWING_HAMMER, 12, 12);\n\t\tassignItemRect(FORCE_CUBE, 11, 12);\n\t}\n\t\n\tpublic static final int DARTS = xy(1, 11); //16 slots\n\tpublic static final int DART = DARTS+0;\n\tpublic static final int ROT_DART = DARTS+1;\n\tpublic static final int INCENDIARY_DART = DARTS+2;\n\tpublic static final int ADRENALINE_DART = DARTS+3;\n\tpublic static final int HEALING_DART = DARTS+4;\n\tpublic static final int CHILLING_DART = DARTS+5;\n\tpublic static final int SHOCKING_DART = DARTS+6;\n\tpublic static final int POISON_DART = DARTS+7;\n\tpublic static final int CLEANSING_DART = DARTS+8;\n\tpublic static final int PARALYTIC_DART = DARTS+9;\n\tpublic static final int HOLY_DART = DARTS+10;\n\tpublic static final int DISPLACING_DART = DARTS+11;\n\tpublic static final int BLINDING_DART = DARTS+12;\n\tstatic {\n\t\tfor (int i = DARTS; i < DARTS+16; i++)\n\t\t\tassignItemRect(i, 15, 15);\n\t}\n\t\n\tprivate static final int ARMOR = xy(1, 12); //16 slots\n\tpublic static final int ARMOR_CLOTH = ARMOR+0;\n\tpublic static final int ARMOR_LEATHER = ARMOR+1;\n\tpublic static final int ARMOR_MAIL = ARMOR+2;\n\tpublic static final int ARMOR_SCALE = ARMOR+3;\n\tpublic static final int ARMOR_PLATE = ARMOR+4;\n\tpublic static final int ARMOR_WARRIOR = ARMOR+5;\n\tpublic static final int ARMOR_MAGE = ARMOR+6;\n\tpublic static final int ARMOR_ROGUE = ARMOR+7;\n\tpublic static final int ARMOR_HUNTRESS = ARMOR+8;\n\tpublic static final int ARMOR_DUELIST = ARMOR+9;\n\tstatic{\n\t\tassignItemRect(ARMOR_CLOTH, 15, 12);\n\t\tassignItemRect(ARMOR_LEATHER, 14, 13);\n\t\tassignItemRect(ARMOR_MAIL, 14, 12);\n\t\tassignItemRect(ARMOR_SCALE, 14, 11);\n\t\tassignItemRect(ARMOR_PLATE, 12, 12);\n\t\tassignItemRect(ARMOR_WARRIOR, 12, 12);\n\t\tassignItemRect(ARMOR_MAGE, 15, 15);\n\t\tassignItemRect(ARMOR_ROGUE, 14, 12);\n\t\tassignItemRect(ARMOR_HUNTRESS, 13, 15);\n\t\tassignItemRect(ARMOR_DUELIST, 12, 13);\n\t}\n\n\t //16 free slots\n\n\tprivate static final int WANDS = xy(1, 14); //16 slots\n\tpublic static final int WAND_MAGIC_MISSILE = WANDS+0;\n\tpublic static final int WAND_FIREBOLT = WANDS+1;\n\tpublic static final int WAND_FROST = WANDS+2;\n\tpublic static final int WAND_LIGHTNING = WANDS+3;\n\tpublic static final int WAND_DISINTEGRATION = WANDS+4;\n\tpublic static final int WAND_PRISMATIC_LIGHT= WANDS+5;\n\tpublic static final int WAND_CORROSION = WANDS+6;\n\tpublic static final int WAND_LIVING_EARTH = WANDS+7;\n\tpublic static final int WAND_BLAST_WAVE = WANDS+8;\n\tpublic static final int WAND_CORRUPTION = WANDS+9;\n\tpublic static final int WAND_WARDING = WANDS+10;\n\tpublic static final int WAND_REGROWTH = WANDS+11;\n\tpublic static final int WAND_TRANSFUSION = WANDS+12;\n\tstatic {\n\t\tfor (int i = WANDS; i < WANDS+16; i++)\n\t\t\tassignItemRect(i, 14, 14);\n\t}\n\n\tprivate static final int RINGS = xy(1, 15); //16 slots\n\tpublic static final int RING_GARNET = RINGS+0;\n\tpublic static final int RING_RUBY = RINGS+1;\n\tpublic static final int RING_TOPAZ = RINGS+2;\n\tpublic static final int RING_EMERALD = RINGS+3;\n\tpublic static final int RING_ONYX = RINGS+4;\n\tpublic static final int RING_OPAL = RINGS+5;\n\tpublic static final int RING_TOURMALINE = RINGS+6;\n\tpublic static final int RING_SAPPHIRE = RINGS+7;\n\tpublic static final int RING_AMETHYST = RINGS+8;\n\tpublic static final int RING_QUARTZ = RINGS+9;\n\tpublic static final int RING_AGATE = RINGS+10;\n\tpublic static final int RING_DIAMOND = RINGS+11;\n\tstatic {\n\t\tfor (int i = RINGS; i < RINGS+16; i++)\n\t\t\tassignItemRect(i, 8, 10);\n\t}\n\n\tprivate static final int ARTIFACTS = xy(1, 16); //32 slots\n\tpublic static final int ARTIFACT_CLOAK = ARTIFACTS+0;\n\tpublic static final int ARTIFACT_ARMBAND = ARTIFACTS+1;\n\tpublic static final int ARTIFACT_CAPE = ARTIFACTS+2;\n\tpublic static final int ARTIFACT_TALISMAN = ARTIFACTS+3;\n\tpublic static final int ARTIFACT_HOURGLASS = ARTIFACTS+4;\n\tpublic static final int ARTIFACT_TOOLKIT = ARTIFACTS+5;\n\tpublic static final int ARTIFACT_SPELLBOOK = ARTIFACTS+6;\n\tpublic static final int ARTIFACT_BEACON = ARTIFACTS+7;\n\tpublic static final int ARTIFACT_CHAINS = ARTIFACTS+8;\n\tpublic static final int ARTIFACT_HORN1 = ARTIFACTS+9;\n\tpublic static final int ARTIFACT_HORN2 = ARTIFACTS+10;\n\tpublic static final int ARTIFACT_HORN3 = ARTIFACTS+11;\n\tpublic static final int ARTIFACT_HORN4 = ARTIFACTS+12;\n\tpublic static final int ARTIFACT_CHALICE1 = ARTIFACTS+13;\n\tpublic static final int ARTIFACT_CHALICE2 = ARTIFACTS+14;\n\tpublic static final int ARTIFACT_CHALICE3 = ARTIFACTS+15;\n\tpublic static final int ARTIFACT_SANDALS = ARTIFACTS+16;\n\tpublic static final int ARTIFACT_SHOES = ARTIFACTS+17;\n\tpublic static final int ARTIFACT_BOOTS = ARTIFACTS+18;\n\tpublic static final int ARTIFACT_GREAVES = ARTIFACTS+19;\n\tpublic static final int ARTIFACT_ROSE1 = ARTIFACTS+20;\n\tpublic static final int ARTIFACT_ROSE2 = ARTIFACTS+21;\n\tpublic static final int ARTIFACT_ROSE3 = ARTIFACTS+22;\n\tstatic{\n\t\tassignItemRect(ARTIFACT_CLOAK, 9, 15);\n\t\tassignItemRect(ARTIFACT_ARMBAND, 16, 13);\n\t\tassignItemRect(ARTIFACT_CAPE, 16, 14);\n\t\tassignItemRect(ARTIFACT_TALISMAN, 15, 13);\n\t\tassignItemRect(ARTIFACT_HOURGLASS, 13, 16);\n\t\tassignItemRect(ARTIFACT_TOOLKIT, 15, 13);\n\t\tassignItemRect(ARTIFACT_SPELLBOOK, 13, 16);\n\t\tassignItemRect(ARTIFACT_BEACON, 16, 16);\n\t\tassignItemRect(ARTIFACT_CHAINS, 16, 16);\n\t\tassignItemRect(ARTIFACT_HORN1, 15, 15);\n\t\tassignItemRect(ARTIFACT_HORN2, 15, 15);\n\t\tassignItemRect(ARTIFACT_HORN3, 15, 15);\n\t\tassignItemRect(ARTIFACT_HORN4, 15, 15);\n\t\tassignItemRect(ARTIFACT_CHALICE1, 12, 15);\n\t\tassignItemRect(ARTIFACT_CHALICE2, 12, 15);\n\t\tassignItemRect(ARTIFACT_CHALICE3, 12, 15);\n\t\tassignItemRect(ARTIFACT_SANDALS, 16, 6 );\n\t\tassignItemRect(ARTIFACT_SHOES, 16, 6 );\n\t\tassignItemRect(ARTIFACT_BOOTS, 16, 9 );\n\t\tassignItemRect(ARTIFACT_GREAVES, 16, 14);\n\t\tassignItemRect(ARTIFACT_ROSE1, 14, 14);\n\t\tassignItemRect(ARTIFACT_ROSE2, 14, 14);\n\t\tassignItemRect(ARTIFACT_ROSE3, 14, 14);\n\t}\n\n\t //16 free slots\n\n\tprivate static final int SCROLLS = xy(1, 19); //16 slots\n\tpublic static final int SCROLL_KAUNAN = SCROLLS+0;\n\tpublic static final int SCROLL_SOWILO = SCROLLS+1;\n\tpublic static final int SCROLL_LAGUZ = SCROLLS+2;\n\tpublic static final int SCROLL_YNGVI = SCROLLS+3;\n\tpublic static final int SCROLL_GYFU = SCROLLS+4;\n\tpublic static final int SCROLL_RAIDO = SCROLLS+5;\n\tpublic static final int SCROLL_ISAZ = SCROLLS+6;\n\tpublic static final int SCROLL_MANNAZ = SCROLLS+7;\n\tpublic static final int SCROLL_NAUDIZ = SCROLLS+8;\n\tpublic static final int SCROLL_BERKANAN = SCROLLS+9;\n\tpublic static final int SCROLL_ODAL = SCROLLS+10;\n\tpublic static final int SCROLL_TIWAZ = SCROLLS+11;\n\t\n\tpublic static final int SCROLL_CATALYST = SCROLLS+13;\n\tpublic static final int ARCANE_RESIN = SCROLLS+14;\n\tstatic {\n\t\tfor (int i = SCROLLS; i < SCROLLS+16; i++)\n\t\t\tassignItemRect(i, 15, 14);\n\t\tassignItemRect(SCROLL_CATALYST, 12, 11);\n\t\tassignItemRect(ARCANE_RESIN , 12, 11);\n\t}\n\t\n\tprivate static final int EXOTIC_SCROLLS = xy(1, 20); //16 slots\n\tpublic static final int EXOTIC_KAUNAN = EXOTIC_SCROLLS+0;\n\tpublic static final int EXOTIC_SOWILO = EXOTIC_SCROLLS+1;\n\tpublic static final int EXOTIC_LAGUZ = EXOTIC_SCROLLS+2;\n\tpublic static final int EXOTIC_YNGVI = EXOTIC_SCROLLS+3;\n\tpublic static final int EXOTIC_GYFU = EXOTIC_SCROLLS+4;\n\tpublic static final int EXOTIC_RAIDO = EXOTIC_SCROLLS+5;\n\tpublic static final int EXOTIC_ISAZ = EXOTIC_SCROLLS+6;\n\tpublic static final int EXOTIC_MANNAZ = EXOTIC_SCROLLS+7;\n\tpublic static final int EXOTIC_NAUDIZ = EXOTIC_SCROLLS+8;\n\tpublic static final int EXOTIC_BERKANAN = EXOTIC_SCROLLS+9;\n\tpublic static final int EXOTIC_ODAL = EXOTIC_SCROLLS+10;\n\tpublic static final int EXOTIC_TIWAZ = EXOTIC_SCROLLS+11;\n\tstatic {\n\t\tfor (int i = EXOTIC_SCROLLS; i < EXOTIC_SCROLLS+16; i++)\n\t\t\tassignItemRect(i, 15, 14);\n\t}\n\t\n\tprivate static final int STONES = xy(1, 21); //16 slots\n\tpublic static final int STONE_AGGRESSION = STONES+0;\n\tpublic static final int STONE_AUGMENTATION = STONES+1;\n\tpublic static final int STONE_FEAR = STONES+2;\n\tpublic static final int STONE_BLAST = STONES+3;\n\tpublic static final int STONE_BLINK = STONES+4;\n\tpublic static final int STONE_CLAIRVOYANCE = STONES+5;\n\tpublic static final int STONE_SLEEP = STONES+6;\n\tpublic static final int STONE_DISARM = STONES+7;\n\tpublic static final int STONE_ENCHANT = STONES+8;\n\tpublic static final int STONE_FLOCK = STONES+9;\n\tpublic static final int STONE_INTUITION = STONES+10;\n\tpublic static final int STONE_SHOCK = STONES+11;\n\tstatic {\n\t\tfor (int i = STONES; i < STONES+16; i++)\n\t\t\tassignItemRect(i, 14, 12);\n\t}\n\n\tprivate static final int POTIONS = xy(1, 22); //16 slots\n\tpublic static final int POTION_CRIMSON = POTIONS+0;\n\tpublic static final int POTION_AMBER = POTIONS+1;\n\tpublic static final int POTION_GOLDEN = POTIONS+2;\n\tpublic static final int POTION_JADE = POTIONS+3;\n\tpublic static final int POTION_TURQUOISE= POTIONS+4;\n\tpublic static final int POTION_AZURE = POTIONS+5;\n\tpublic static final int POTION_INDIGO = POTIONS+6;\n\tpublic static final int POTION_MAGENTA = POTIONS+7;\n\tpublic static final int POTION_BISTRE = POTIONS+8;\n\tpublic static final int POTION_CHARCOAL = POTIONS+9;\n\tpublic static final int POTION_SILVER = POTIONS+10;\n\tpublic static final int POTION_IVORY = POTIONS+11;\n\tpublic static final int POTION_CATALYST = POTIONS+13;\n\tpublic static final int LIQUID_METAL = POTIONS+14;\n\tstatic {\n\t\tfor (int i = POTIONS; i < POTIONS+16; i++)\n\t\t\tassignItemRect(i, 12, 14);\n\t\tassignItemRect(POTION_CATALYST, 6, 15);\n\t\tassignItemRect(LIQUID_METAL, 8, 15);\n\t}\n\t\n\tprivate static final int EXOTIC_POTIONS = xy(1, 23); //16 slots\n\tpublic static final int EXOTIC_CRIMSON = EXOTIC_POTIONS+0;\n\tpublic static final int EXOTIC_AMBER = EXOTIC_POTIONS+1;\n\tpublic static final int EXOTIC_GOLDEN = EXOTIC_POTIONS+2;\n\tpublic static final int EXOTIC_JADE = EXOTIC_POTIONS+3;\n\tpublic static final int EXOTIC_TURQUOISE= EXOTIC_POTIONS+4;\n\tpublic static final int EXOTIC_AZURE = EXOTIC_POTIONS+5;\n\tpublic static final int EXOTIC_INDIGO = EXOTIC_POTIONS+6;\n\tpublic static final int EXOTIC_MAGENTA = EXOTIC_POTIONS+7;\n\tpublic static final int EXOTIC_BISTRE = EXOTIC_POTIONS+8;\n\tpublic static final int EXOTIC_CHARCOAL = EXOTIC_POTIONS+9;\n\tpublic static final int EXOTIC_SILVER = EXOTIC_POTIONS+10;\n\tpublic static final int EXOTIC_IVORY = EXOTIC_POTIONS+11;\n\tstatic {\n\t\tfor (int i = EXOTIC_POTIONS; i < EXOTIC_POTIONS+16; i++)\n\t\t\tassignItemRect(i, 12, 13);\n\t}\n\n\tprivate static final int SEEDS = xy(1, 24); //16 slots\n\tpublic static final int SEED_ROTBERRY = SEEDS+0;\n\tpublic static final int SEED_FIREBLOOM = SEEDS+1;\n\tpublic static final int SEED_SWIFTTHISTLE = SEEDS+2;\n\tpublic static final int SEED_SUNGRASS = SEEDS+3;\n\tpublic static final int SEED_ICECAP = SEEDS+4;\n\tpublic static final int SEED_STORMVINE = SEEDS+5;\n\tpublic static final int SEED_SORROWMOSS = SEEDS+6;\n\tpublic static final int SEED_MAGEROYAL = SEEDS+7;\n\tpublic static final int SEED_EARTHROOT = SEEDS+8;\n\tpublic static final int SEED_STARFLOWER = SEEDS+9;\n\tpublic static final int SEED_FADELEAF = SEEDS+10;\n\tpublic static final int SEED_BLINDWEED = SEEDS+11;\n\tstatic{\n\t\tfor (int i = SEEDS; i < SEEDS+16; i++)\n\t\t\tassignItemRect(i, 10, 10);\n\t}\n\t\n\tprivate static final int BREWS = xy(1, 25); //8 slots\n\tpublic static final int BREW_INFERNAL = BREWS+0;\n\tpublic static final int BREW_BLIZZARD = BREWS+1;\n\tpublic static final int BREW_SHOCKING = BREWS+2;\n\tpublic static final int BREW_CAUSTIC = BREWS+3;\n\t\n\tprivate static final int ELIXIRS = xy(9, 25); //8 slots\n\tpublic static final int ELIXIR_HONEY = ELIXIRS+0;\n\tpublic static final int ELIXIR_AQUA = ELIXIRS+1;\n\tpublic static final int ELIXIR_MIGHT = ELIXIRS+2;\n\tpublic static final int ELIXIR_DRAGON = ELIXIRS+3;\n\tpublic static final int ELIXIR_TOXIC = ELIXIRS+4;\n\tpublic static final int ELIXIR_ICY = ELIXIRS+5;\n\tpublic static final int ELIXIR_ARCANE = ELIXIRS+6;\n\tstatic{\n\t\tfor (int i = BREWS; i < BREWS+16; i++)\n\t\t\tassignItemRect(i, 12, 14);\n\t}\n\t\n\t //16 free slots\n\t\n\tprivate static final int SPELLS = xy(1, 27); //16 slots\n\tpublic static final int MAGIC_PORTER = SPELLS+0;\n\tpublic static final int PHASE_SHIFT = SPELLS+1;\n\tpublic static final int TELE_GRAB = SPELLS+2;\n\tpublic static final int WILD_ENERGY = SPELLS+3;\n\tpublic static final int RETURN_BEACON = SPELLS+4;\n\tpublic static final int SUMMON_ELE = SPELLS+5;\n\t\n\tpublic static final int AQUA_BLAST = SPELLS+7;\n\tpublic static final int FEATHER_FALL = SPELLS+8;\n\tpublic static final int RECLAIM_TRAP = SPELLS+9;\n\t\n\tpublic static final int CURSE_INFUSE = SPELLS+11;\n\tpublic static final int MAGIC_INFUSE = SPELLS+12;\n\tpublic static final int ALCHEMIZE = SPELLS+13;\n\tpublic static final int RECYCLE = SPELLS+14;\n\tstatic{\n\t\tassignItemRect(MAGIC_PORTER, 12, 11);\n\t\tassignItemRect(PHASE_SHIFT, 12, 11);\n\t\tassignItemRect(TELE_GRAB, 12, 11);\n\t\tassignItemRect(WILD_ENERGY, 8, 16);\n\t\tassignItemRect(RETURN_BEACON, 8, 16);\n\t\tassignItemRect(SUMMON_ELE, 8, 16);\n\t\t\n\t\tassignItemRect(AQUA_BLAST, 11, 11);\n\t\tassignItemRect(FEATHER_FALL, 11, 11);\n\t\tassignItemRect(RECLAIM_TRAP, 11, 11);\n\t\t\n\t\tassignItemRect(CURSE_INFUSE, 10, 15);\n\t\tassignItemRect(MAGIC_INFUSE, 10, 15);\n\t\tassignItemRect(ALCHEMIZE, 10, 15);\n\t\tassignItemRect(RECYCLE, 10, 15);\n\t}\n\t\n\tprivate static final int FOOD = xy(1, 28); //16 slots\n\tpublic static final int MEAT = FOOD+0;\n\tpublic static final int STEAK = FOOD+1;\n\tpublic static final int STEWED = FOOD+2;\n\tpublic static final int OVERPRICED = FOOD+3;\n\tpublic static final int CARPACCIO = FOOD+4;\n\tpublic static final int RATION = FOOD+5;\n\tpublic static final int PASTY = FOOD+6;\n\tpublic static final int PUMPKIN_PIE = FOOD+7;\n\tpublic static final int CANDY_CANE = FOOD+8;\n\tpublic static final int MEAT_PIE = FOOD+9;\n\tpublic static final int BLANDFRUIT = FOOD+10;\n\tpublic static final int BLAND_CHUNKS= FOOD+11;\n\tpublic static final int BERRY = FOOD+12;\n\tpublic static final int PHANTOM_MEAT= FOOD+13;\n\tstatic{\n\t\tassignItemRect(MEAT, 15, 11);\n\t\tassignItemRect(STEAK, 15, 11);\n\t\tassignItemRect(STEWED, 15, 11);\n\t\tassignItemRect(OVERPRICED, 14, 11);\n\t\tassignItemRect(CARPACCIO, 15, 11);\n\t\tassignItemRect(RATION, 16, 12);\n\t\tassignItemRect(PASTY, 16, 11);\n\t\tassignItemRect(PUMPKIN_PIE, 16, 12);\n\t\tassignItemRect(CANDY_CANE, 13, 16);\n\t\tassignItemRect(MEAT_PIE, 16, 12);\n\t\tassignItemRect(BLANDFRUIT, 9, 12);\n\t\tassignItemRect(BLAND_CHUNKS,14, 6);\n\t\tassignItemRect(BERRY, 9, 11);\n\t\tassignItemRect(PHANTOM_MEAT,15, 11);\n\t}\n\n\tprivate static final int QUEST = xy(1, 29); //32 slots\n\tpublic static final int SKULL = QUEST+0;\n\tpublic static final int DUST = QUEST+1;\n\tpublic static final int CANDLE = QUEST+2;\n\tpublic static final int EMBER = QUEST+3;\n\tpublic static final int PICKAXE = QUEST+4;\n\tpublic static final int ORE = QUEST+5;\n\tpublic static final int TOKEN = QUEST+6;\n\tpublic static final int BLOB = QUEST+7;\n\tpublic static final int SHARD = QUEST+8;\n\tstatic{\n\t\tassignItemRect(SKULL, 16, 11);\n\t\tassignItemRect(DUST, 12, 11);\n\t\tassignItemRect(CANDLE, 12, 12);\n\t\tassignItemRect(EMBER, 12, 11);\n\t\tassignItemRect(PICKAXE, 14, 14);\n\t\tassignItemRect(ORE, 15, 15);\n\t\tassignItemRect(TOKEN, 12, 12);\n\t\tassignItemRect(BLOB, 10, 9);\n\t\tassignItemRect(SHARD, 8, 10);\n\t}\n\n\tprivate static final int BAGS = xy(1, 31); //16 slots\n\tpublic static final int WATERSKIN = BAGS+0;\n\tpublic static final int BACKPACK = BAGS+1;\n\tpublic static final int POUCH = BAGS+2;\n\tpublic static final int HOLDER = BAGS+3;\n\tpublic static final int BANDOLIER = BAGS+4;\n\tpublic static final int HOLSTER = BAGS+5;\n\tpublic static final int VIAL = BAGS+6;\n\tstatic{\n\t\tassignItemRect(WATERSKIN, 16, 14);\n\t\tassignItemRect(BACKPACK, 16, 16);\n\t\tassignItemRect(POUCH, 14, 15);\n\t\tassignItemRect(HOLDER, 16, 16);\n\t\tassignItemRect(BANDOLIER, 15, 16);\n\t\tassignItemRect(HOLSTER, 15, 16);\n\t\tassignItemRect(VIAL, 12, 12);\n\t}\n\n\tprivate static final int DOCUMENTS = xy(1, 32); //16 slots\n\tpublic static final int GUIDE_PAGE = DOCUMENTS+0;\n\tpublic static final int ALCH_PAGE = DOCUMENTS+1;\n\tpublic static final int SEWER_PAGE = DOCUMENTS+2;\n\tpublic static final int PRISON_PAGE = DOCUMENTS+3;\n\tpublic static final int CAVES_PAGE = DOCUMENTS+4;\n\tpublic static final int CITY_PAGE = DOCUMENTS+5;\n\tpublic static final int HALLS_PAGE = DOCUMENTS+6;\n\tpublic static final int LABS_PAGE = DOCUMENTS+7;\n\tstatic{\n\t\tassignItemRect(GUIDE_PAGE, 10, 11);\n\t\tassignItemRect(ALCH_PAGE, 10, 11);\n\t\tassignItemRect(SEWER_PAGE, 10, 11);\n\t\tassignItemRect(PRISON_PAGE, 10, 11);\n\t\tassignItemRect(CAVES_PAGE, 10, 11);\n\t\tassignItemRect(CITY_PAGE, 10, 11);\n\t\tassignItemRect(HALLS_PAGE, 10, 11);\n\t\tassignItemRect(LABS_PAGE, \t10, 11);\n\t}\n\n\t// ****** new sprites ******\n\n//\tprivate static final int \t\t\t \t=\t\t\txy(1, ); //16 slots\n//\tpublic static final int \t\t\t\t= +0;\n//\tpublic static final int \t\t\t\t= +1;\n//\tpublic static final int \t\t\t\t= +2;\n//\tpublic static final int \t\t\t\t= +3;\n//\tpublic static final int \t\t\t\t= +4;\n//\tpublic static final int \t\t\t\t= +5;\n//\tpublic static final int \t\t\t\t= +6;\n//\tstatic{\n//\t\tassignItemRect(, 16, 16);\n//\t\tassignItemRect(, 16, 16);\n//\t\tassignItemRect(, 16, 16);\n//\t\tassignItemRect(, 16, 16);\n//\t\tassignItemRect(, 16, 16);\n//\t\tassignItemRect(, 16, 16);\n//\t\tassignItemRect(, 16, 16);\n//\t}\n\n\t//free 16 slots\n\n\t//free 16 slots\n\n\tprivate static final int NEW_SPECIAL_ITEM\t=\t\txy(1, 35); //16 slots\n\tpublic static final int AMMO_BELT\t\t\t= NEW_SPECIAL_ITEM+0;\n\tpublic static final int SHEATH\t\t\t\t= NEW_SPECIAL_ITEM+1;\n\tpublic static final int KNIGHT_SHIELD\t\t= NEW_SPECIAL_ITEM+2;\n\tpublic static final int GAMMA_GUN\t\t\t= NEW_SPECIAL_ITEM+3;\n\tpublic static final int HAND_MIRROR\t\t\t= NEW_SPECIAL_ITEM+4;\n\tpublic static final int TELEPORTER\t\t\t= NEW_SPECIAL_ITEM+5;\n\tstatic{\n\t\tassignItemRect(AMMO_BELT\t, 15, 15);\n\t\tassignItemRect(SHEATH\t\t, 13, 13);\n\t\tassignItemRect(KNIGHT_SHIELD, 16, 15);\n\t\tassignItemRect(GAMMA_GUN\t, 12, 15);\n\t\tassignItemRect(HAND_MIRROR\t, 10, 16);\n\t\tassignItemRect(TELEPORTER\t, 14, 14);\n\t}\n\n\tprivate static final int NEW_ARMOR\t \t=\t\t\txy(1, 36); //16 slots\n\tpublic static final int ARMOR_GUNNER\t= NEW_ARMOR+0;\n\tpublic static final int ARMOR_SAMURAI\t= NEW_ARMOR+1;\n\tpublic static final int ARMOR_PLANTER\t= NEW_ARMOR+2;\n\tpublic static final int ARMOR_KNIGHT\t= NEW_ARMOR+3;\n\tpublic static final int ARMOR_NURSE\t\t= NEW_ARMOR+4;\n\tstatic{\n\t\tassignItemRect(ARMOR_GUNNER\t, 15, 13);\n\t\tassignItemRect(ARMOR_SAMURAI, 12, 16);\n\t\tassignItemRect(ARMOR_PLANTER, 15, 12);\n\t\tassignItemRect(ARMOR_KNIGHT\t, 14, 12);\n\t\tassignItemRect(ARMOR_NURSE\t, 14, 12);\n\t}\n\n\tprivate static final int NEW_SCROLL \t=\t\t\txy(1, 37); //16 slots\n\tpublic static final int SCROLL_PLUS\t\t= NEW_SCROLL+0;\n\tpublic static final int BLUEPRINT\t\t= NEW_SCROLL+1;\n\tstatic{\n\t\tassignItemRect(SCROLL_PLUS, 15, 14);\n\t}\n\n\tprivate static final int NEW_EXOTIC_SCROLL \t=\t\txy(1, 38); //16 slots\n\tpublic static final int EXOTIC_SCROLL_PLUS\t= NEW_EXOTIC_SCROLL+0;\n\tstatic{\n\t\tassignItemRect(EXOTIC_SCROLL_PLUS, 15, 14);\n\t}\n\n\tprivate static final int NEW_RING\t\t=\t\t\txy(1, 39); //16 slots\n\tpublic static final int RING_OBSIDIAN = NEW_RING+0;\n\tpublic static final int RING_PEARL \t= NEW_RING+1;\n\tpublic static final int RING_GOLD \t= NEW_RING+2;\n\tpublic static final int RING_EMBER \t= NEW_RING+3;\n\tpublic static final int RING_IOLITE\t\t= NEW_RING+4;\n\tpublic static final int RING_AQUAMARINE = NEW_RING+5;\n\tpublic static final int RING_JADE\t\t= NEW_RING+6;\n\tstatic{\n\t\tfor (int i = NEW_RING; i < NEW_RING+6; i++)\n\t\t\tassignItemRect(i, 8, 10);\n\t}\n\n\t//free 16 slots\n\n\tprivate static final int BULLET_ITEM\t=\t\t\txy(1, 41); //16 slots\n\tpublic static final int BULLET\t\t= BULLET_ITEM+0;\n\tpublic static final int HP_BULLET\t= BULLET_ITEM+1;\n\tpublic static final int AP_BULLET\t= BULLET_ITEM+2;\n\tpublic static final int CARTRIDGE\t= BULLET_ITEM+3;\n\tpublic static final int BULLET_BELT\t= BULLET_ITEM+4;\n\tpublic static final int OLD_AMULET\t= BULLET_ITEM+5;\n\tstatic{\n\t\tassignItemRect(BULLET\t\t, 13, 13);\n\t\tassignItemRect(HP_BULLET\t, 13, 13);\n\t\tassignItemRect(AP_BULLET\t, 13, 13);\n\t\tassignItemRect(CARTRIDGE\t, 11, 11);\n\t\tassignItemRect(BULLET_BELT\t, 15, 15);\n\t\tassignItemRect(OLD_AMULET\t, 16, 16);\n\t}\n\n\tprivate static final int BULLETS\t\t=\t\t\txy(1, 42); //16 slots\n\tpublic static final int SINGLE_BULLET\t= BULLETS+0;\n\tpublic static final int DOUBLE_BULLET\t= BULLETS+1;\n\tpublic static final int TRIPLE_BULLET\t= BULLETS+2;\n\tpublic static final int SNIPER_BULLET\t= BULLETS+3;\n\tpublic static final int GHOST_BULLET\t= BULLETS+4;\n\tstatic{\n\t\tassignItemRect(SINGLE_BULLET\t, 8, 8);\n\t\tassignItemRect(DOUBLE_BULLET\t, 11, 10);\n\t\tassignItemRect(TRIPLE_BULLET\t, 11, 11);\n\t\tassignItemRect(SNIPER_BULLET\t, 8, 8);\n\t\tassignItemRect(GHOST_BULLET\t\t, 8, 8);\n\t}\n\n\tprivate static final int SPECIAL_BULLETS=\t\t\txy(1, 43); //16 slots\n\tpublic static final int GRENADE_GREEN\t= SPECIAL_BULLETS+0;\n\tpublic static final int GRENADE_RED\t\t= SPECIAL_BULLETS+1;\n\tpublic static final int GRENADE_WHITE\t= SPECIAL_BULLETS+2;\n\tpublic static final int ROCKET\t\t\t= SPECIAL_BULLETS+3;\n\tpublic static final int BATTERY_SINGLE\t= SPECIAL_BULLETS+4;\n\tpublic static final int BATTERY_DOUBLE\t= SPECIAL_BULLETS+5;\n\tpublic static final int BATTERY_POWER\t= SPECIAL_BULLETS+6;\n\tstatic{\n\t\tassignItemRect(GRENADE_GREEN\t, 7, 7);\n\t\tassignItemRect(GRENADE_RED\t\t, 7, 7);\n\t\tassignItemRect(GRENADE_WHITE\t, 7, 7);\n\t\tassignItemRect(ROCKET\t\t\t, 9, 9);\n\t\tassignItemRect(BATTERY_SINGLE\t, 10, 10);\n\t\tassignItemRect(BATTERY_DOUBLE\t, 12, 12);\n\t\tassignItemRect(BATTERY_POWER\t, 12, 12);\n\t}\n\n\tprivate static final int ARROWS\t\t\t=\t\t\txy(1, 44); //16 slots\n\tpublic static final int ARROW_WIND\t\t= ARROWS+0;\n\tpublic static final int ARROW_NATURE\t= ARROWS+1;\n\tpublic static final int ARROW_GOLD\t\t= ARROWS+2;\n\tpublic static final int ARROW_CORROSION\t= ARROWS+3;\n\tpublic static final int ARROW_TACTICAL\t= ARROWS+4;\n\tstatic{\n\t\tassignItemRect(ARROW_WIND\t\t, 11, 11);\n\t\tassignItemRect(ARROW_NATURE\t\t, 11, 11);\n\t\tassignItemRect(ARROW_GOLD\t\t, 11, 11);\n\t\tassignItemRect(ARROW_CORROSION\t, 11, 11);\n\t\tassignItemRect(ARROW_TACTICAL\t, 11, 11);\n\t}\n\n\tprivate static final int NEW_WEP_TIER_1\t=\t\t\txy(1, 45); //8 slots\n\tpublic static final int WORN_KATANA\t\t= NEW_WEP_TIER_1+0;\n\tpublic static final int SABER\t\t\t= NEW_WEP_TIER_1+1;\n\tpublic static final int HEALING_BOOK\t= NEW_WEP_TIER_1+2;\n\tstatic{\n\t\tassignItemRect(WORN_KATANA\t, 13, 13);\n\t\tassignItemRect(SABER\t\t, 13, 15);\n\t\tassignItemRect(HEALING_BOOK\t, 13, 15);\n\t}\n\n\tprivate static final int NEW_WEP_TIER_2\t=\t\t\txy(9, 45); //8 slots\n\tpublic static final int SHORT_KATANA\t= NEW_WEP_TIER_2+0;\n\tpublic static final int KNIFE\t\t\t= NEW_WEP_TIER_2+1;\n\tpublic static final int NUNCHAKU\t\t= NEW_WEP_TIER_2+2;\n\tpublic static final int DUAL_DAGGER\t\t= NEW_WEP_TIER_2+3;\n\tstatic{\n\t\tassignItemRect(SHORT_KATANA\t, 14, 14);\n\t\tassignItemRect(KNIFE\t\t, 12, 13);\n\t\tassignItemRect(NUNCHAKU\t\t, 16, 16);\n\t\tassignItemRect(DUAL_DAGGER\t, 16, 16);\n\t}\n\n\tprivate static final int NEW_WEP_TIER_3\t=\t\t\txy(1, 46); //8 slots\n\tpublic static final int NORMAL_KATANA\t= NEW_WEP_TIER_3+0;\n\tpublic static final int BIBLE\t\t\t= NEW_WEP_TIER_3+1;\n\tpublic static final int RUNE_DAGGER\t\t= NEW_WEP_TIER_3+2;\n\tstatic{\n\t\tassignItemRect(NORMAL_KATANA, 14, 15);\n\t\tassignItemRect(BIBLE\t\t, 13, 16);\n\t\tassignItemRect(RUNE_DAGGER\t, 13, 14);\n\t}\n\n\tprivate static final int NEW_WEP_TIER_4 =\t\t\txy(9, 46); //8 slots\n\tpublic static final int LONG_KATANA\t\t= NEW_WEP_TIER_4+0;\n\tstatic{\n\t\tassignItemRect(LONG_KATANA, 15, 16);\n\t}\n\n\tprivate static final int NEW_WEP_TIER_5\t=\t\t\txy(1, 47); //8 slots\n\tpublic static final int LARGE_KATANA= NEW_WEP_TIER_5+0;\n\tpublic static final int LARGE_SHORD\t= NEW_WEP_TIER_5+1;\n\tstatic{\n\t\tassignItemRect(LARGE_KATANA\t, 12, 16);\n\t\tassignItemRect(LARGE_SHORD\t, 14, 16);\n\t}\n\n//\tprivate static final int NEW_WEP_TIER_6\t=\t\t\txy(9, 47); //8 slots\n//\tstatic{\n//\t}\n\n\tprivate static final int HG\t \t=\t\t\txy(1, 48); //8 slots\n\tpublic static final int HG_T1\t\t= HG+0;\n\tpublic static final int HG_T2\t\t= HG+1;\n\tpublic static final int HG_T3\t\t= HG+2;\n\tpublic static final int HG_T4\t\t= HG+3;\n\tpublic static final int HG_T5\t\t= HG+4;\n\tpublic static final int HG_AL\t\t= HG+5;\n\tpublic static final int HG_T6\t\t= HG+6;\n\tstatic{\n\t\tassignItemRect(HG_T1, 10, 13);\n\t\tassignItemRect(HG_T2, 11, 15);\n\t\tassignItemRect(HG_T3, 12, 15);\n\t\tassignItemRect(HG_T4, 13, 16);\n\t\tassignItemRect(HG_T5, 12, 16);\n\t\tassignItemRect(HG_AL, 12, 15);\n\t\tassignItemRect(HG_T6, 16, 16);\n\t}\n\n\tprivate static final int SMG\t=\t\t\txy(9, 48); //8 slots\n//\tpublic static final int SMG_T1\t\t= SMG+0;\n\tpublic static final int SMG_T2\t\t= SMG+1;\n//\tpublic static final int SMG_T3\t\t= SMG+2;\n//\tpublic static final int SMG_T4\t\t= SMG+3;\n\tpublic static final int SMG_T5\t\t= SMG+4;\n//\tpublic static final int SMG_AL\t\t= SMG+5;\n//\tpublic static final int SMG_T6\t\t= SMG+6;\n\tstatic{\n//\t\tassignItemRect(SMG_T1, 16, 16);\n\t\tassignItemRect(SMG_T2, 15, 16);\n//\t\tassignItemRect(SMG_T3, 16, 16);\n//\t\tassignItemRect(SMG_T4, 16, 16);\n\t\tassignItemRect(SMG_T5, 15, 15);\n//\t\tassignItemRect(SMG_AL, 16, 16);\n//\t\tassignItemRect(SMG_T6, 16, 16);\n\t}\n\n\tprivate static final int MG\t \t=\t\t\txy(1, 49); //8 slots\n//\tpublic static final int MG_T1\t\t= MG+0;\n//\tpublic static final int MG_T2\t\t= MG+1;\n\tpublic static final int MG_T3\t\t= MG+2;\n//\tpublic static final int MG_T4\t\t= MG+3;\n\tpublic static final int MG_T5\t\t= MG+4;\n//\tpublic static final int MG_AL\t\t= MG+5;\n//\tpublic static final int MG_T6\t\t= MG+6;\n\tstatic{\n//\t\tassignItemRect(MG_T1, 16, 16);\n//\t\tassignItemRect(MG_T2, 16, 16);\n\t\tassignItemRect(MG_T3, 13, 15);\n//\t\tassignItemRect(MG_T4, 16, 16);\n\t\tassignItemRect(MG_T5, 16, 15);\n//\t\tassignItemRect(MG_AL, 16, 16);\n//\t\tassignItemRect(MG_T6, 16, 16);\n\t}\n\n\n\n\tprivate static final int SG\t \t=\t\t\txy(9, 49); //8 slots\n//\tpublic static final int SG_T1\t\t= SG+0;\n//\tpublic static final int SG_T2\t\t= SG+1;\n\tpublic static final int SG_T3\t\t= SG+2;\n//\tpublic static final int SG_T4\t\t= SG+3;\n\tpublic static final int SG_T5\t\t= SG+4;\n//\tpublic static final int SG_AL\t\t= SG+5;\n//\tpublic static final int SG_T6\t\t= SG+6;\n\tstatic{\n//\t\tassignItemRect(SG_T1, 16, 16);\n//\t\tassignItemRect(SG_T2, 16, 16);\n\t\tassignItemRect(SG_T3, 14, 16);\n//\t\tassignItemRect(SG_T4, 16, 16);\n\t\tassignItemRect(SG_T5, 15, 16);\n//\t\tassignItemRect(SG_AL, 16, 16);\n//\t\tassignItemRect(SG_T6, 16, 16);\n\t}\n\n\tprivate static final int SR\t\t\t \t=\t\t\txy(1, 50); //8 slots\n\tpublic static final int SR_T1\t\t\t= SR+0;\n\tpublic static final int SR_T2\t\t\t= SR+1;\n\tpublic static final int SR_T3\t\t\t= SR+2;\n\tpublic static final int SR_T4\t\t\t= SR+3;\n\tpublic static final int SR_T5\t\t\t= SR+4;\n\tpublic static final int SR_AL\t\t\t= SR+5;\n\tpublic static final int SR_T6\t\t\t= SR+6;\n\tstatic{\n\t\tassignItemRect(SR_T1, 11, 15);\n\t\tassignItemRect(SR_T2, 13, 16);\n\t\tassignItemRect(SR_T3, 13, 16);\n\t\tassignItemRect(SR_T4, 14, 16);\n\t\tassignItemRect(SR_T5, 15, 16);\n\t\tassignItemRect(SR_AL, 16, 16);\n\t\tassignItemRect(SR_T6, 15, 16);\n\t}\n\n\tprivate static final int AR\t\t\t \t=\t\t\txy(9, 50); //8 slots\n\tpublic static final int AR_T1\t\t\t= AR+0;\n\tpublic static final int AR_T2\t\t\t= AR+1;\n\tpublic static final int AR_T3\t\t\t= AR+2;\n\tpublic static final int AR_T4\t\t\t= AR+3;\n\tpublic static final int AR_T5\t\t\t= AR+4;\n\tpublic static final int AR_AL\t\t\t= AR+5;\n\tpublic static final int AR_T6\t\t\t= AR+6;\n\tstatic{\n\t\tassignItemRect(AR_T1, 12, 13);\n\t\tassignItemRect(AR_T2, 13, 14);\n\t\tassignItemRect(AR_T3, 15, 16);\n\t\tassignItemRect(AR_T4, 16, 15);\n\t\tassignItemRect(AR_T5, 15, 16);\n\t\tassignItemRect(AR_AL, 16, 16);\n\t\tassignItemRect(AR_T6, 15, 16);\n\t}\n\n\t//GL, RL, 화염방사기, 레이저총 추후 추가\n\n\tprivate static final int BOWS\t\t\t=\t\t\txy(1, 53); //8 slots\n\tpublic static final int WIND_BOW\t\t= BOWS+0;\n\tpublic static final int NATURE_BOW\t\t= BOWS+1;\n\tpublic static final int GOLDEN_BOW\t\t= BOWS+2;\n\tpublic static final int CORROSION_BOW\t= BOWS+3;\n\tpublic static final int TACTICAL_BOW\t= BOWS+4;\n\tstatic{\n\t\tassignItemRect(WIND_BOW\t\t, 16, 16);\n\t\tassignItemRect(NATURE_BOW\t, 16, 16);\n\t\tassignItemRect(GOLDEN_BOW\t, 16, 16);\n\t\tassignItemRect(CORROSION_BOW, 16, 16);\n\t\tassignItemRect(TACTICAL_BOW\t, 16, 16);\n\t}\n\n\t//보조무기 추후 추가\n\n\t//free 16 slots\n\n\t//Alchemy melee weapons\n\n\tprivate static final int AL_WEP_T3\t\t\t=\t\t\txy(1, 56); //16 slots\n\tpublic static final int SPEAR_N_SHIELD\t\t= AL_WEP_T3+0;\n\tpublic static final int UNHOLY_SWORD\t\t= AL_WEP_T3+1;\n\tpublic static final int CHAOS_SWORD\t\t\t= AL_WEP_T3+2;\n\tpublic static final int FIRE_SCIMITAR\t\t= AL_WEP_T3+3;\n\tpublic static final int FROST_SCIMITAR\t\t= AL_WEP_T3+4;\n\tpublic static final int POISON_SCIMITAR\t\t= AL_WEP_T3+5;\n\tpublic static final int ELECTRIC_SCIMITAR\t= AL_WEP_T3+6;\n\tstatic{\n\t\tassignItemRect(SPEAR_N_SHIELD\t, 16, 15);\n\t\tassignItemRect(UNHOLY_SWORD\t\t, 14, 14);\n\t\tassignItemRect(CHAOS_SWORD\t\t, 14, 14);\n\t\tassignItemRect(FIRE_SCIMITAR\t, 13, 16);\n\t\tassignItemRect(FROST_SCIMITAR\t, 13, 16);\n\t\tassignItemRect(POISON_SCIMITAR\t, 13, 16);\n\t\tassignItemRect(ELECTRIC_SCIMITAR, 13, 16);\n\t}\n\n\tprivate static final int AL_WEP_T4\t\t=\t\t\txy(1, 57); //16 slots\n\tpublic static final int UNHOLY_BIBLE\t\t= AL_WEP_T4+0;\n\tstatic{\n\t\tassignItemRect(UNHOLY_BIBLE\t, \t13, 16);\n\t}\n\n\tprivate static final int AL_WEP_T5\t\t=\t\t\txy(1, 58); //16 slots\n\tpublic static final int TRUE_RUNIC_BLADE= AL_WEP_T5+0;\n\tpublic static final int CHAIN_WHIP\t\t= AL_WEP_T5+1;\n\tstatic{\n\t\tassignItemRect(TRUE_RUNIC_BLADE, 14, 14);\n\t\tassignItemRect(CHAIN_WHIP, \t\t 14, 14);\n\t}\n\n\tprivate static final int AL_WEP_T6\t \t=\t\t\txy(1, 59); //16 slots\n\tpublic static final int DUAL_GREATSWORD\t= AL_WEP_T6+0;\n\tpublic static final int FORCE_GLOVE\t\t= AL_WEP_T6+1;\n\tpublic static final int CHAIN_FLAIL\t\t= AL_WEP_T6+2;\n\tpublic static final int UNFORMED_BLADE\t= AL_WEP_T6+3;\n\tpublic static final int ASSASSINS_SPEAR\t= AL_WEP_T6+4;\n\tpublic static final int SHARP_KATANA\t= AL_WEP_T6+5;\n\tpublic static final int OBSIDIAN_SHIELD\t= AL_WEP_T6+6;\n\tpublic static final int LANCE\t\t\t= AL_WEP_T6+7;\n\tpublic static final int BEAM_SABER\t\t= AL_WEP_T6+8;\n\tpublic static final int MEISTER_HAMMER\t= AL_WEP_T6+9;\n\tpublic static final int HUGE_SWORD\t\t= AL_WEP_T6+10;\n\tstatic{\n\t\tassignItemRect(DUAL_GREATSWORD\t, 16, 16);\n\t\tassignItemRect(FORCE_GLOVE\t\t, 13, 15);\n\t\tassignItemRect(CHAIN_FLAIL\t\t, 16, 16);\n\t\tassignItemRect(UNFORMED_BLADE\t, 14, 15);\n\t\tassignItemRect(ASSASSINS_SPEAR\t, 16, 16);\n\t\tassignItemRect(SHARP_KATANA\t\t, 12, 16);\n\t\tassignItemRect(OBSIDIAN_SHIELD\t, 12, 16);\n\t\tassignItemRect(LANCE\t\t\t, 15, 15);\n\t\tassignItemRect(BEAM_SABER\t\t, 16, 15);\n\t\tassignItemRect(MEISTER_HAMMER\t, 16, 16);\n\t\tassignItemRect(HUGE_SWORD\t\t, 16, 16);\n\t}\n\n\tprivate static final int AL_WEP_T7\t\t=\t\t\txy(1, 60); //16 slots\n\tpublic static final int LANCE_N_SHIELD\t= AL_WEP_T7+0;\n\tpublic static final int TACTICAL_SHIELD\t= AL_WEP_T7+1;\n\tpublic static final int HOLYSWORD_TRUE\t= AL_WEP_T7+2;\n\tpublic static final int HOLYSWORD\t\t= AL_WEP_T7+3;\n\tstatic{\n\t\tassignItemRect(LANCE_N_SHIELD\t, 16, 15);\n\t\tassignItemRect(TACTICAL_SHIELD\t, 12, 16);\n\t\tassignItemRect(HOLYSWORD_TRUE\t, 16, 16);\n\t\tassignItemRect(HOLYSWORD\t\t, 16, 16);\n\t}\n\n\tprivate static final int ENERGY_WEP\t\t\t \t=\t\t\txy(1, 61); //16 slots\n\tpublic static final int WORN_SHORTSWORD_ENERGY\t= ENERGY_WEP+0;\n//\tpublic static final int \t\t\t\t\t\t= ENERGY_WEP+1;\n\tpublic static final int DAGGER_ENERGY\t\t\t= ENERGY_WEP+2;\n\tpublic static final int GLOVES_ENERGY\t\t\t= ENERGY_WEP+3;\n\tpublic static final int RAPIER_ENERGY\t\t\t= ENERGY_WEP+4;\n\tpublic static final int HG_T1_ENERGY\t\t\t= ENERGY_WEP+5;\n\tpublic static final int WORN_KATANA_ENERGY\t\t= ENERGY_WEP+6;\n\tpublic static final int SABER_ENERGY\t\t\t= ENERGY_WEP+7;\n\tstatic{\n\t\tassignItemRect(WORN_SHORTSWORD_ENERGY\t, 13, 13);\n//\t\tassignItemRect(\t\t\t\t\t\t\t, 16, 16);\n\t\tassignItemRect(DAGGER_ENERGY\t\t\t, 12, 13);\n\t\tassignItemRect(GLOVES_ENERGY\t\t\t, 12, 16);\n\t\tassignItemRect(RAPIER_ENERGY\t\t\t, 13, 14);\n\t\tassignItemRect(HG_T1_ENERGY\t\t\t\t, 10, 13);\n\t\tassignItemRect(WORN_KATANA_ENERGY\t\t, 13, 13);\n\t\tassignItemRect(SABER_ENERGY\t\t\t\t, 13, 15);\n\t}\n\n\tprivate static final int SPELLBOOK\t\t\t \t\t=\t\txy(1, 62); //16 slots\n\tpublic static final int BOOK_OF_MAGIC \t\t\t= SPELLBOOK+0;\n\tpublic static final int BOOK_OF_FIRE \t\t= SPELLBOOK+1;\n\tpublic static final int BOOK_OF_FROST \t= SPELLBOOK+2;\n\tpublic static final int BOOK_OF_THUNDERBOLT \t= SPELLBOOK+3;\n\tpublic static final int BOOK_OF_DISINTEGRATION \t= SPELLBOOK+4;\n\tpublic static final int BOOK_OF_LIGHT\t\t\t= SPELLBOOK+5;\n\tpublic static final int BOOK_OF_CORROSION \t= SPELLBOOK+6;\n\tpublic static final int BOOK_OF_EARTH \t\t= SPELLBOOK+7;\n\tpublic static final int BOOK_OF_BLAST \t\t= SPELLBOOK+8;\n\tpublic static final int BOOK_OF_CORRUPTION \t= SPELLBOOK+9;\n\tpublic static final int BOOK_OF_WARDING \t= SPELLBOOK+10;\n\tpublic static final int BOOK_OF_REGROWTH \t= SPELLBOOK+11;\n\tpublic static final int BOOK_OF_TRANSFUSION \t= SPELLBOOK+12;\n\tstatic{\n\t\tassignItemRect(BOOK_OF_MAGIC \t\t\t, 12, 16);\n\t\tassignItemRect(BOOK_OF_FIRE \t\t, 12, 16);\n\t\tassignItemRect(BOOK_OF_FROST \t, 12, 16);\n\t\tassignItemRect(BOOK_OF_THUNDERBOLT \t, 12, 16);\n\t\tassignItemRect(BOOK_OF_DISINTEGRATION \t, 12, 16);\n\t\tassignItemRect(BOOK_OF_LIGHT\t\t\t, 12, 16);\n\t\tassignItemRect(BOOK_OF_CORROSION \t, 12, 16);\n\t\tassignItemRect(BOOK_OF_EARTH \t\t\t, 12, 16);\n\t\tassignItemRect(BOOK_OF_BLAST \t\t, 12, 16);\n\t\tassignItemRect(BOOK_OF_CORRUPTION \t, 12, 16);\n\t\tassignItemRect(BOOK_OF_WARDING \t, 12, 16);\n\t\tassignItemRect(BOOK_OF_REGROWTH \t, 12, 16);\n\t\tassignItemRect(BOOK_OF_TRANSFUSION \t, 12, 16);\n\t}\n\n\tprivate static final int SHOVEL\t\t\t=\t\t\t\txy(1, 63); //8 slots\n\tpublic static final int PLANTER_SHOVEL\t= SHOVEL+0;\n\tpublic static final int GILDED_SHOVEL\t= SHOVEL+1;\n\tpublic static final int BATTLE_SHOVEL\t= SHOVEL+2;\n\tpublic static final int MINERS_TOOL\t\t= SHOVEL+3;\n\tstatic{\n\t\tassignItemRect(PLANTER_SHOVEL\t, 16, 16);\n\t\tassignItemRect(GILDED_SHOVEL\t, 16, 16);\n\t\tassignItemRect(BATTLE_SHOVEL\t, 16, 16);\n\t\tassignItemRect(MINERS_TOOL\t\t, 16, 16);\n\t}\n\n\tprivate static final int SPECIAL_ITEM\t\t\t=\t\txy(9, 63); //8 slots\n\tpublic static final int HERO_SWORD\t= SPECIAL_ITEM+0;\n\tstatic{\n\t\tassignItemRect(HERO_SWORD\t, 14, 14);\n\t}\n\n\tprivate static final int NEW_POTIONS\t\t=\t\t\txy(1, 64); //16 slots\n\tpublic static final int POTION_FLUORESCENT\t= NEW_POTIONS+0;\n\tpublic static final int POTION_ASH\t\t\t= NEW_POTIONS+1;\n\tstatic{\n\t\tfor (int i = NEW_POTIONS; i < NEW_POTIONS+1; i++)\n\t\t\tassignItemRect(i, 12, 14);\n\t}\n\n\tprivate static final int NEW_EXOTIC_POTIONS\t=\t\t\txy(1, 65); //16 slots\n\tpublic static final int EXOTIC_FLUORESCENT\t= NEW_EXOTIC_POTIONS+0;\n\tpublic static final int EXOTIC_ASH\t\t\t= NEW_EXOTIC_POTIONS+1;\n\tstatic{\n\t\tfor (int i = NEW_EXOTIC_POTIONS; i < NEW_EXOTIC_POTIONS+1; i++)\n\t\t\tassignItemRect(i, 12, 13);\n\t}\n\n\tprivate static final int NEW_BREWS\t\t\t=\t\t\txy(1, 66); //16 slots\n\tpublic static final int BREW_SATISFACTION\t= NEW_BREWS+0;\n\tpublic static final int BREW_TALENT\t\t\t= NEW_BREWS+1;\n\tstatic{\n\t\tfor (int i = NEW_BREWS; i < NEW_BREWS+2; i++)\n\t\t\tassignItemRect(i, 12, 14);\n\t}\n\n\tprivate static final int NEW_SPELLS\t\t\t=\t\t\txy(1, 67); //16 slots\n\tpublic static final int FIRE_IMBUE\t\t\t= NEW_SPELLS+0;\n\tpublic static final int XRAY\t\t\t\t= NEW_SPELLS+1;\n\tpublic static final int FIREMAKER\t\t\t= NEW_SPELLS+2;\n\tpublic static final int ICEMAKER\t\t\t= NEW_SPELLS+3;\n\tpublic static final int RAPID_GROWTH\t\t= NEW_SPELLS+4;\n\tpublic static final int\tHANDY_BARRICADE\t\t= NEW_SPELLS+5;\n\tpublic static final int ADVANCED_EVOLUTION\t= NEW_SPELLS+6;\n\tpublic static final int EVOLUTION\t\t\t= NEW_SPELLS+7;\n\tpublic static final int UPGRADE_DUST\t\t= NEW_SPELLS+8;\n\tstatic{\n\t\tassignItemRect(FIRE_IMBUE\t\t\t, 11, 11);\n\t\tassignItemRect(XRAY\t\t\t\t\t, 11, 11);\n\t\tassignItemRect(FIREMAKER\t\t\t, 12, 11);\n\t\tassignItemRect(ICEMAKER\t\t\t\t, 12, 11);\n\t\tassignItemRect(RAPID_GROWTH\t\t\t, 8, 16);\n\t\tassignItemRect(HANDY_BARRICADE\t\t, 8, 16);\n\t\tassignItemRect(ADVANCED_EVOLUTION\t, 10, 15);\n\t\tassignItemRect(EVOLUTION\t\t\t, 10, 15);\n\t\tassignItemRect(UPGRADE_DUST\t\t\t, 12, 11);\n\t}\n\n\t// ****** new sprites end ******\n\n\n\n\t//for smaller 8x8 icons that often accompany an item sprite\n\tpublic static class Icons {\n\n\t\tprivate static final int WIDTH = 16;\n\t\tpublic static final int SIZE = 8;\n\n\t\tpublic static TextureFilm film = new TextureFilm( Assets.Sprites.ITEM_ICONS, SIZE, SIZE );\n\n\t\tprivate static int xy(int x, int y){\n\t\t\tx -= 1; y -= 1;\n\t\t\treturn x + WIDTH*y;\n\t\t}\n\n\t\tprivate static void assignIconRect( int item, int width, int height ){\n\t\t\tint x = (item % WIDTH) * SIZE;\n\t\t\tint y = (item / WIDTH) * SIZE;\n\t\t\tfilm.add( item, x, y, x+width, y+height);\n\t\t}\n\n\t\tprivate static final int RINGS = xy(1, 1); //16 slots\n\t\tpublic static final int RING_ACCURACY = RINGS+0;\n\t\tpublic static final int RING_ARCANA = RINGS+1;\n\t\tpublic static final int RING_ELEMENTS = RINGS+2;\n\t\tpublic static final int RING_ENERGY = RINGS+3;\n\t\tpublic static final int RING_EVASION = RINGS+4;\n\t\tpublic static final int RING_FORCE = RINGS+5;\n\t\tpublic static final int RING_FUROR = RINGS+6;\n\t\tpublic static final int RING_HASTE = RINGS+7;\n\t\tpublic static final int RING_MIGHT = RINGS+8;\n\t\tpublic static final int RING_SHARPSHOOT = RINGS+9;\n\t\tpublic static final int RING_TENACITY = RINGS+10;\n\t\tpublic static final int RING_WEALTH = RINGS+11;\n\t\tstatic {\n\t\t\tassignIconRect( RING_ACCURACY, 7, 7 );\n\t\t\tassignIconRect( RING_ARCANA, 7, 7 );\n\t\t\tassignIconRect( RING_ELEMENTS, 7, 7 );\n\t\t\tassignIconRect( RING_ENERGY, 7, 5 );\n\t\t\tassignIconRect( RING_EVASION, 7, 7 );\n\t\t\tassignIconRect( RING_FORCE, 5, 6 );\n\t\t\tassignIconRect( RING_FUROR, 7, 6 );\n\t\t\tassignIconRect( RING_HASTE, 6, 6 );\n\t\t\tassignIconRect( RING_MIGHT, 7, 7 );\n\t\t\tassignIconRect( RING_SHARPSHOOT, 7, 7 );\n\t\t\tassignIconRect( RING_TENACITY, 6, 6 );\n\t\t\tassignIconRect( RING_WEALTH, 7, 6 );\n\t\t}\n\n\t\t //16 free slots\n\n\t\tprivate static final int SCROLLS = xy(1, 3); //16 slots\n\t\tpublic static final int SCROLL_UPGRADE = SCROLLS+0;\n\t\tpublic static final int SCROLL_IDENTIFY = SCROLLS+1;\n\t\tpublic static final int SCROLL_REMCURSE = SCROLLS+2;\n\t\tpublic static final int SCROLL_MIRRORIMG= SCROLLS+3;\n\t\tpublic static final int SCROLL_RECHARGE = SCROLLS+4;\n\t\tpublic static final int SCROLL_TELEPORT = SCROLLS+5;\n\t\tpublic static final int SCROLL_LULLABY = SCROLLS+6;\n\t\tpublic static final int SCROLL_MAGICMAP = SCROLLS+7;\n\t\tpublic static final int SCROLL_RAGE = SCROLLS+8;\n\t\tpublic static final int SCROLL_RETRIB = SCROLLS+9;\n\t\tpublic static final int SCROLL_TERROR = SCROLLS+10;\n\t\tpublic static final int SCROLL_TRANSMUTE= SCROLLS+11;\n\t\tstatic {\n\t\t\tassignIconRect( SCROLL_UPGRADE, 7, 7 );\n\t\t\tassignIconRect( SCROLL_IDENTIFY, 4, 7 );\n\t\t\tassignIconRect( SCROLL_REMCURSE, 7, 7 );\n\t\t\tassignIconRect( SCROLL_MIRRORIMG, 7, 5 );\n\t\t\tassignIconRect( SCROLL_RECHARGE, 7, 5 );\n\t\t\tassignIconRect( SCROLL_TELEPORT, 7, 7 );\n\t\t\tassignIconRect( SCROLL_LULLABY, 7, 6 );\n\t\t\tassignIconRect( SCROLL_MAGICMAP, 7, 7 );\n\t\t\tassignIconRect( SCROLL_RAGE, 6, 6 );\n\t\t\tassignIconRect( SCROLL_RETRIB, 5, 6 );\n\t\t\tassignIconRect( SCROLL_TERROR, 5, 7 );\n\t\t\tassignIconRect( SCROLL_TRANSMUTE, 7, 7 );\n\t\t}\n\n\t\tprivate static final int EXOTIC_SCROLLS = xy(1, 4); //16 slots\n\t\tpublic static final int SCROLL_ENCHANT = EXOTIC_SCROLLS+0;\n\t\tpublic static final int SCROLL_DIVINATE = EXOTIC_SCROLLS+1;\n\t\tpublic static final int SCROLL_ANTIMAGIC= EXOTIC_SCROLLS+2;\n\t\tpublic static final int SCROLL_PRISIMG = EXOTIC_SCROLLS+3;\n\t\tpublic static final int SCROLL_MYSTENRG = EXOTIC_SCROLLS+4;\n\t\tpublic static final int SCROLL_PASSAGE = EXOTIC_SCROLLS+5;\n\t\tpublic static final int SCROLL_SIREN = EXOTIC_SCROLLS+6;\n\t\tpublic static final int SCROLL_FORESIGHT= EXOTIC_SCROLLS+7;\n\t\tpublic static final int SCROLL_CHALLENGE= EXOTIC_SCROLLS+8;\n\t\tpublic static final int SCROLL_PSIBLAST = EXOTIC_SCROLLS+9;\n\t\tpublic static final int SCROLL_DREAD = EXOTIC_SCROLLS+10;\n\t\tpublic static final int SCROLL_METAMORPH= EXOTIC_SCROLLS+11;\n\t\tstatic {\n\t\t\tassignIconRect( SCROLL_ENCHANT, 7, 7 );\n\t\t\tassignIconRect( SCROLL_DIVINATE, 7, 6 );\n\t\t\tassignIconRect( SCROLL_ANTIMAGIC, 7, 7 );\n\t\t\tassignIconRect( SCROLL_PRISIMG, 5, 7 );\n\t\t\tassignIconRect( SCROLL_MYSTENRG, 7, 5 );\n\t\t\tassignIconRect( SCROLL_PASSAGE, 5, 7 );\n\t\t\tassignIconRect( SCROLL_SIREN, 7, 6 );\n\t\t\tassignIconRect( SCROLL_FORESIGHT, 7, 5 );\n\t\t\tassignIconRect( SCROLL_CHALLENGE, 7, 7 );\n\t\t\tassignIconRect( SCROLL_PSIBLAST, 5, 6 );\n\t\t\tassignIconRect( SCROLL_DREAD, 5, 7 );\n\t\t\tassignIconRect( SCROLL_METAMORPH, 7, 7 );\n\t\t}\n\n\t\t //16 free slots\n\n\t\tprivate static final int POTIONS = xy(1, 6); //16 slots\n\t\tpublic static final int POTION_STRENGTH = POTIONS+0;\n\t\tpublic static final int POTION_HEALING = POTIONS+1;\n\t\tpublic static final int POTION_MINDVIS = POTIONS+2;\n\t\tpublic static final int POTION_FROST = POTIONS+3;\n\t\tpublic static final int POTION_LIQFLAME = POTIONS+4;\n\t\tpublic static final int POTION_TOXICGAS = POTIONS+5;\n\t\tpublic static final int POTION_HASTE = POTIONS+6;\n\t\tpublic static final int POTION_INVIS = POTIONS+7;\n\t\tpublic static final int POTION_LEVITATE = POTIONS+8;\n\t\tpublic static final int POTION_PARAGAS = POTIONS+9;\n\t\tpublic static final int POTION_PURITY = POTIONS+10;\n\t\tpublic static final int POTION_EXP = POTIONS+11;\n\t\tstatic {\n\t\t\tassignIconRect( POTION_STRENGTH, 7, 7 );\n\t\t\tassignIconRect( POTION_HEALING, 6, 7 );\n\t\t\tassignIconRect( POTION_MINDVIS, 7, 5 );\n\t\t\tassignIconRect( POTION_FROST, 7, 7 );\n\t\t\tassignIconRect( POTION_LIQFLAME, 5, 7 );\n\t\t\tassignIconRect( POTION_TOXICGAS, 7, 7 );\n\t\t\tassignIconRect( POTION_HASTE, 6, 6 );\n\t\t\tassignIconRect( POTION_INVIS, 5, 7 );\n\t\t\tassignIconRect( POTION_LEVITATE, 6, 7 );\n\t\t\tassignIconRect( POTION_PARAGAS, 7, 7 );\n\t\t\tassignIconRect( POTION_PURITY, 5, 7 );\n\t\t\tassignIconRect( POTION_EXP, 7, 7 );\n\t\t}\n\n\t\tprivate static final int EXOTIC_POTIONS = xy(1, 7); //16 slots\n\t\tpublic static final int POTION_MASTERY = EXOTIC_POTIONS+0;\n\t\tpublic static final int POTION_SHIELDING= EXOTIC_POTIONS+1;\n\t\tpublic static final int POTION_MAGISIGHT= EXOTIC_POTIONS+2;\n\t\tpublic static final int POTION_SNAPFREEZ= EXOTIC_POTIONS+3;\n\t\tpublic static final int POTION_DRGBREATH= EXOTIC_POTIONS+4;\n\t\tpublic static final int POTION_CORROGAS = EXOTIC_POTIONS+5;\n\t\tpublic static final int POTION_STAMINA = EXOTIC_POTIONS+6;\n\t\tpublic static final int POTION_SHROUDFOG= EXOTIC_POTIONS+7;\n\t\tpublic static final int POTION_STRMCLOUD= EXOTIC_POTIONS+8;\n\t\tpublic static final int POTION_EARTHARMR= EXOTIC_POTIONS+9;\n\t\tpublic static final int POTION_CLEANSE = EXOTIC_POTIONS+10;\n\t\tpublic static final int POTION_DIVINE = EXOTIC_POTIONS+11;\n\t\tstatic {\n\t\t\tassignIconRect( POTION_MASTERY, 7, 7 );\n\t\t\tassignIconRect( POTION_SHIELDING, 6, 6 );\n\t\t\tassignIconRect( POTION_MAGISIGHT, 7, 5 );\n\t\t\tassignIconRect( POTION_SNAPFREEZ, 7, 7 );\n\t\t\tassignIconRect( POTION_DRGBREATH, 7, 7 );\n\t\t\tassignIconRect( POTION_CORROGAS, 7, 7 );\n\t\t\tassignIconRect( POTION_STAMINA, 6, 6 );\n\t\t\tassignIconRect( POTION_SHROUDFOG, 7, 7 );\n\t\t\tassignIconRect( POTION_STRMCLOUD, 7, 7 );\n\t\t\tassignIconRect( POTION_EARTHARMR, 6, 6 );\n\t\t\tassignIconRect( POTION_CLEANSE, 7, 7 );\n\t\t\tassignIconRect( POTION_DIVINE, 7, 7 );\n\t\t}\n\n\t\t //16 free slots\n\n\t}\n\n}" }, { "identifier": "AttackIndicator", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/ui/AttackIndicator.java", "snippet": "public class AttackIndicator extends Tag {\n\t\n\tprivate static final float ENABLED\t= 1.0f;\n\tprivate static final float DISABLED\t= 0.3f;\n\n\tprivate static float delay;\n\t\n\tprivate static AttackIndicator instance;\n\t\n\tprivate CharSprite sprite = null;\n\t\n\tprivate Mob lastTarget;\n\tprivate ArrayList<Mob> candidates = new ArrayList<>();\n\t\n\tpublic AttackIndicator() {\n\t\tsuper( DangerIndicator.COLOR );\n\n\t\tsynchronized (this) {\n\t\t\tinstance = this;\n\t\t\tlastTarget = null;\n\n\t\t\tsetSize(SIZE, SIZE);\n\t\t\tvisible(false);\n\t\t\tenable(false);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic GameAction keyAction() {\n\t\treturn SPDAction.TAG_ATTACK;\n\t}\n\t\n\t@Override\n\tprotected void createChildren() {\n\t\tsuper.createChildren();\n\t}\n\t\n\t@Override\n\tprotected synchronized void layout() {\n\t\tsuper.layout();\n\n\t\tif (sprite != null) {\n\t\t\tif (!flipped) sprite.x = x + (SIZE - sprite.width()) / 2f + 1;\n\t\t\telse sprite.x = x + width - (SIZE + sprite.width()) / 2f - 1;\n\t\t\tsprite.y = y + (height - sprite.height()) / 2f;\n\t\t\tPixelScene.align(sprite);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic synchronized void update() {\n\t\tsuper.update();\n\n\t\tif (!bg.visible){\n\t\t\tif (sprite != null) sprite.visible = false;\n\t\t\tenable(false);\n\t\t\tif (delay > 0f) delay -= Game.elapsed;\n\t\t\tif (delay <= 0f) active = false;\n\t\t} else {\n\t\t\tdelay = 0.75f;\n\t\t\tactive = true;\n\t\t\tif (bg.width > 0 && sprite != null)sprite.visible = true;\n\n\t\t\tif (Dungeon.hero.isAlive()) {\n\n\t\t\t\tenable(Dungeon.hero.ready);\n\n\t\t\t} else {\n\t\t\t\tvisible( false );\n\t\t\t\tenable( false );\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate synchronized void checkEnemies() {\n\n\t\tcandidates.clear();\n\t\tint v = Dungeon.hero.visibleEnemies();\n\t\tfor (int i=0; i < v; i++) {\n\t\t\tMob mob = Dungeon.hero.visibleEnemy( i );\n\t\t\tif ( Dungeon.hero.canAttack( mob) ) {\n\t\t\t\tcandidates.add( mob );\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (!candidates.contains( lastTarget )) {\n\t\t\tif (candidates.isEmpty()) {\n\t\t\t\tlastTarget = null;\n\t\t\t} else {\n\t\t\t\tactive = true;\n\t\t\t\tlastTarget = Random.element( candidates );\n\t\t\t\tupdateImage();\n\t\t\t\tflash();\n\t\t\t}\n\t\t} else {\n\t\t\tif (!bg.visible) {\n\t\t\t\tactive = true;\n\t\t\t\tflash();\n\t\t\t}\n\t\t}\n\t\t\n\t\tvisible( lastTarget != null );\n\t\tenable( bg.visible );\n\t}\n\t\n\tprivate synchronized void updateImage() {\n\t\t\n\t\tif (sprite != null) {\n\t\t\tsprite.killAndErase();\n\t\t\tsprite = null;\n\t\t}\n\t\t\n\t\tsprite = Reflection.newInstance(lastTarget.spriteClass);\n\t\tactive = true;\n\t\tsprite.linkVisuals(lastTarget);\n\t\tsprite.idle();\n\t\tsprite.paused = true;\n\t\tsprite.visible = bg.visible;\n\n\t\tif (sprite.width() > 20 || sprite.height() > 20){\n\t\t\tsprite.scale.set(PixelScene.align(20f/Math.max(sprite.width(), sprite.height())));\n\t\t}\n\n\t\tadd( sprite );\n\n\t\tlayout();\n\t}\n\t\n\tprivate boolean enabled = true;\n\tprivate synchronized void enable( boolean value ) {\n\t\tenabled = value;\n\t\tif (sprite != null) {\n\t\t\tsprite.alpha( value ? ENABLED : DISABLED );\n\t\t}\n\t}\n\t\n\tprivate synchronized void visible( boolean value ) {\n\t\tbg.visible = value;\n\t}\n\t\n\t@Override\n\tprotected void onClick() {\n\t\tsuper.onClick();\n\t\tif (enabled && Dungeon.hero.ready) {\n\t\t\tif (Dungeon.hero.handle( lastTarget.pos )) {\n\t\t\t\tDungeon.hero.next();\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tprotected String hoverText() {\n\t\treturn Messages.titleCase(Messages.get(WndKeyBindings.class, \"tag_attack\"));\n\t}\n\n\tpublic static void target(Char target ) {\n\t\tif (target == null) return;\n\t\tsynchronized (instance) {\n\t\t\tinstance.lastTarget = (Mob) target;\n\t\t\tinstance.updateImage();\n\n\t\t\tQuickSlotButton.target(target);\n\t\t}\n\t}\n\t\n\tpublic static void updateState() {\n\t\tinstance.checkEnemies();\n\t}\n}" }, { "identifier": "GLog", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/utils/GLog.java", "snippet": "public class GLog {\n\n\tpublic static final String TAG = \"GAME\";\n\t\n\tpublic static final String POSITIVE\t\t= \"++ \";\n\tpublic static final String NEGATIVE\t\t= \"-- \";\n\tpublic static final String WARNING\t\t= \"** \";\n\tpublic static final String HIGHLIGHT\t= \"@@ \";\n\n\tpublic static final String NEW_LINE\t = \"\\n\";\n\t\n\tpublic static Signal<String> update = new Signal<>();\n\n\tpublic static void newLine(){\n\t\tupdate.dispatch( NEW_LINE );\n\t}\n\t\n\tpublic static void i( String text, Object... args ) {\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttext = Messages.format( text, args );\n\t\t}\n\t\t\n\t\tDeviceCompat.log( TAG, text );\n\t\tupdate.dispatch( text );\n\t}\n\t\n\tpublic static void p( String text, Object... args ) {\n\t\ti( POSITIVE + text, args );\n\t}\n\t\n\tpublic static void n( String text, Object... args ) {\n\t\ti( NEGATIVE + text, args );\n\t}\n\t\n\tpublic static void w( String text, Object... args ) {\n\t\ti( WARNING + text, args );\n\t}\n\t\n\tpublic static void h( String text, Object... args ) {\n\t\ti( HIGHLIGHT + text, args );\n\t}\n}" }, { "identifier": "Sample", "path": "SPD-classes/src/main/java/com/watabou/noosa/audio/Sample.java", "snippet": "public enum Sample {\n\n\tINSTANCE;\n\n\tprotected HashMap<Object, Sound> ids = new HashMap<>();\n\n\tprivate boolean enabled = true;\n\tprivate float globalVolume = 1f;\n\n\tpublic synchronized void reset() {\n\n\t\tfor (Sound sound : ids.values()){\n\t\t\tsound.dispose();\n\t\t}\n\t\t\n\t\tids.clear();\n\t\tdelayedSFX.clear();\n\n\t}\n\n\tpublic synchronized void pause() {\n\t\tfor (Sound sound : ids.values()) {\n\t\t\tsound.pause();\n\t\t}\n\t}\n\n\tpublic synchronized void resume() {\n\t\tfor (Sound sound : ids.values()) {\n\t\t\tsound.resume();\n\t\t}\n\t}\n\n\tpublic synchronized void load( final String... assets ) {\n\n\t\tfinal ArrayList<String> toLoad = new ArrayList<>();\n\n\t\tfor (String asset : assets){\n\t\t\tif (!ids.containsKey(asset)){\n\t\t\t\ttoLoad.add(asset);\n\t\t\t}\n\t\t}\n\n\t\t//don't make a new thread of all assets are already loaded\n\t\tif (toLoad.isEmpty()) return;\n\n\t\t//load in a separate thread to prevent this blocking the UI\n\t\tnew Thread(){\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tfor (String asset : toLoad) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tSound newSound = Gdx.audio.newSound(Gdx.files.internal(asset));\n\t\t\t\t\t\tsynchronized (INSTANCE) {\n\t\t\t\t\t\t\tids.put(asset, newSound);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (Exception e){\n\t\t\t\t\t\tGame.reportException(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}.start();\n\t\t\n\t}\n\n\tpublic synchronized void unload( Object src ) {\n\t\tif (ids.containsKey( src )) {\n\t\t\tids.get( src ).dispose();\n\t\t\tids.remove( src );\n\t\t}\n\t}\n\n\tpublic long play( Object id ) {\n\t\treturn play( id, 1 );\n\t}\n\n\tpublic long play( Object id, float volume ) {\n\t\treturn play( id, volume, volume, 1 );\n\t}\n\t\n\tpublic long play( Object id, float volume, float pitch ) {\n\t\treturn play( id, volume, volume, pitch );\n\t}\n\t\n\tpublic synchronized long play( Object id, float leftVolume, float rightVolume, float pitch ) {\n\t\tfloat volume = Math.max(leftVolume, rightVolume);\n\t\tfloat pan = rightVolume - leftVolume;\n\t\tif (enabled && ids.containsKey( id )) {\n\t\t\treturn ids.get(id).play( globalVolume*volume, pitch, pan );\n\t\t} else {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tprivate class DelayedSoundEffect{\n\t\tObject id;\n\t\tfloat delay;\n\n\t\tfloat leftVol;\n\t\tfloat rightVol;\n\t\tfloat pitch;\n\t}\n\n\tprivate static final HashSet<DelayedSoundEffect> delayedSFX = new HashSet<>();\n\n\tpublic void playDelayed( Object id, float delay ){\n\t\tplayDelayed( id, delay, 1 );\n\t}\n\n\tpublic void playDelayed( Object id, float delay, float volume ) {\n\t\tplayDelayed( id, delay, volume, volume, 1 );\n\t}\n\n\tpublic void playDelayed( Object id, float delay, float volume, float pitch ) {\n\t\tplayDelayed( id, delay, volume, volume, pitch );\n\t}\n\n\tpublic void playDelayed( Object id, float delay, float leftVolume, float rightVolume, float pitch ) {\n\t\tif (delay <= 0) {\n\t\t\tplay(id, leftVolume, rightVolume, pitch);\n\t\t\treturn;\n\t\t}\n\t\tDelayedSoundEffect sfx = new DelayedSoundEffect();\n\t\tsfx.id = id;\n\t\tsfx.delay = delay;\n\t\tsfx.leftVol = leftVolume;\n\t\tsfx.rightVol = rightVolume;\n\t\tsfx.pitch = pitch;\n\t\tsynchronized (delayedSFX) {\n\t\t\tdelayedSFX.add(sfx);\n\t\t}\n\t}\n\n\tpublic void update(){\n\t\tsynchronized (delayedSFX) {\n\t\t\tif (delayedSFX.isEmpty()) return;\n\t\t\tfor (DelayedSoundEffect sfx : delayedSFX.toArray(new DelayedSoundEffect[0])) {\n\t\t\t\tsfx.delay -= Game.elapsed;\n\t\t\t\tif (sfx.delay <= 0) {\n\t\t\t\t\tdelayedSFX.remove(sfx);\n\t\t\t\t\tplay(sfx.id, sfx.leftVol, sfx.rightVol, sfx.pitch);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void enable( boolean value ) {\n\t\tenabled = value;\n\t}\n\n\tpublic void volume( float value ) {\n\t\tglobalVolume = value;\n\t}\n\n\tpublic boolean isEnabled() {\n\t\treturn enabled;\n\t}\n\t\n}" }, { "identifier": "Callback", "path": "SPD-classes/src/main/java/com/watabou/utils/Callback.java", "snippet": "public interface Callback {\n\n\tvoid call();\n\t\n}" }, { "identifier": "PathFinder", "path": "SPD-classes/src/main/java/com/watabou/utils/PathFinder.java", "snippet": "public class PathFinder {\n\t\n\tpublic static int[] distance;\n\tprivate static int[] maxVal;\n\t\n\tprivate static boolean[] goals;\n\tprivate static int[] queue;\n\tprivate static boolean[] queued; //currently only used in getStepBack, other can piggyback on distance\n\t\n\tprivate static int size = 0;\n\tprivate static int width = 0;\n\n\tprivate static int[] dir;\n\tprivate static int[] dirLR;\n\n\t//performance-light shortcuts for some common pathfinder cases\n\t//they are in array-access order for increased memory performance\n\tpublic static int[] NEIGHBOURS4;\n\tpublic static int[] NEIGHBOURS8;\n\tpublic static int[] NEIGHBOURS9;\n\n\t//similar to their equivalent neighbour arrays, but the order is clockwise.\n\t//Useful for some logic functions, but is slower due to lack of array-access order.\n\tpublic static int[] CIRCLE4;\n\tpublic static int[] CIRCLE8;\n\t\n\tpublic static void setMapSize( int width, int height ) {\n\t\t\n\t\tPathFinder.width = width;\n\t\tPathFinder.size = width * height;\n\t\t\n\t\tdistance = new int[size];\n\t\tgoals = new boolean[size];\n\t\tqueue = new int[size];\n\t\tqueued = new boolean[size];\n\n\t\tmaxVal = new int[size];\n\t\tArrays.fill(maxVal, Integer.MAX_VALUE);\n\n\t\tdir = new int[]{-1, +1, -width, +width, -width-1, -width+1, +width-1, +width+1};\n\t\tdirLR = new int[]{-1-width, -1, -1+width, -width, +width, +1-width, +1, +1+width};\n\n\t\tNEIGHBOURS4 = new int[]{-width, -1, +1, +width};\n\t\tNEIGHBOURS8 = new int[]{-width-1, -width, -width+1, -1, +1, +width-1, +width, +width+1};\n\t\tNEIGHBOURS9 = new int[]{-width-1, -width, -width+1, -1, 0, +1, +width-1, +width, +width+1};\n\n\t\tCIRCLE4 = new int[]{-width, +1, +width, -1};\n\t\tCIRCLE8 = new int[]{-width-1, -width, -width+1, +1, +width+1, +width, +width-1, -1};\n\t}\n\n\tpublic static Path find( int from, int to, boolean[] passable ) {\n\n\t\tif (!buildDistanceMap( from, to, passable )) {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tPath result = new Path();\n\t\tint s = from;\n\n\t\t// From the starting position we are moving downwards,\n\t\t// until we reach the ending point\n\t\tdo {\n\t\t\tint minD = distance[s];\n\t\t\tint mins = s;\n\t\t\t\n\t\t\tfor (int i=0; i < dir.length; i++) {\n\t\t\t\t\n\t\t\t\tint n = s + dir[i];\n\t\t\t\t\n\t\t\t\tint thisD = distance[n];\n\t\t\t\tif (thisD < minD) {\n\t\t\t\t\tminD = thisD;\n\t\t\t\t\tmins = n;\n\t\t\t\t}\n\t\t\t}\n\t\t\ts = mins;\n\t\t\tresult.add( s );\n\t\t} while (s != to);\n\t\t\n\t\treturn result;\n\t}\n\t\n\tpublic static int getStep( int from, int to, boolean[] passable ) {\n\t\t\n\t\tif (!buildDistanceMap( from, to, passable )) {\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\t// From the starting position we are making one step downwards\n\t\tint minD = distance[from];\n\t\tint best = from;\n\t\t\n\t\tint step, stepD;\n\t\t\n\t\tfor (int i=0; i < dir.length; i++) {\n\n\t\t\tif ((stepD = distance[step = from + dir[i]]) < minD) {\n\t\t\t\tminD = stepD;\n\t\t\t\tbest = step;\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t}\n\t\n\tpublic static int getStepBack( int cur, int from, int lookahead, boolean[] passable, boolean canApproachFromPos ) {\n\n\t\tint d = buildEscapeDistanceMap( cur, from, lookahead, passable );\n\t\tif (d == 0) return -1;\n\n\t\tif (!canApproachFromPos) {\n\t\t\t//We can't approach the position we are retreating from\n\t\t\t//re-calculate based on this, and reduce the target distance if need-be\n\t\t\tint head = 0;\n\t\t\tint tail = 0;\n\n\t\t\tint newD = distance[cur];\n\t\t\tBArray.setFalse(queued);\n\n\t\t\tqueue[tail++] = cur;\n\t\t\tqueued[cur] = true;\n\n\t\t\twhile (head < tail) {\n\t\t\t\tint step = queue[head++];\n\n\t\t\t\tif (distance[step] > newD) {\n\t\t\t\t\tnewD = distance[step];\n\t\t\t\t}\n\n\t\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\t\tint end = ((step + 1) % width == 0 ? 3 : 0);\n\t\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\t\tint n = step + dirLR[i];\n\t\t\t\t\tif (n >= 0 && n < size && passable[n]) {\n\t\t\t\t\t\tif (distance[n] < distance[cur]) {\n\t\t\t\t\t\t\tpassable[n] = false;\n\t\t\t\t\t\t} else if (distance[n] >= distance[step] && !queued[n]) {\n\t\t\t\t\t\t\t// Add to queue\n\t\t\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\t\t\tqueued[n] = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\td = Math.min(newD, d);\n\t\t}\n\n\t\tfor (int i=0; i < size; i++) {\n\t\t\tgoals[i] = distance[i] == d;\n\t\t}\n\t\tif (!buildDistanceMap( cur, goals, passable )) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tint s = cur;\n\t\t\n\t\t// From the starting position we are making one step downwards\n\t\tint minD = distance[s];\n\t\tint mins = s;\n\t\t\n\t\tfor (int i=0; i < dir.length; i++) {\n\n\t\t\tint n = s + dir[i];\n\t\t\tint thisD = distance[n];\n\t\t\t\n\t\t\tif (thisD < minD) {\n\t\t\t\tminD = thisD;\n\t\t\t\tmins = n;\n\t\t\t}\n\t\t}\n\n\t\treturn mins;\n\t}\n\t\n\tprivate static boolean buildDistanceMap( int from, int to, boolean[] passable ) {\n\t\t\n\t\tif (from == to) {\n\t\t\treturn false;\n\t\t}\n\n\t\tSystem.arraycopy(maxVal, 0, distance, 0, maxVal.length);\n\t\t\n\t\tboolean pathFound = false;\n\t\t\n\t\tint head = 0;\n\t\tint tail = 0;\n\t\t\n\t\t// Add to queue\n\t\tqueue[tail++] = to;\n\t\tdistance[to] = 0;\n\t\t\n\t\twhile (head < tail) {\n\t\t\t\n\t\t\t// Remove from queue\n\t\t\tint step = queue[head++];\n\t\t\tif (step == from) {\n\t\t\t\tpathFound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tint nextDistance = distance[step] + 1;\n\t\t\t\n\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\tint end = ((step+1) % width == 0 ? 3 : 0);\n\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\tint n = step + dirLR[i];\n\t\t\t\tif (n == from || (n >= 0 && n < size && passable[n] && (distance[n] > nextDistance))) {\n\t\t\t\t\t// Add to queue\n\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\tdistance[n] = nextDistance;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn pathFound;\n\t}\n\t\n\tpublic static void buildDistanceMap( int to, boolean[] passable, int limit ) {\n\t\t\n\t\tSystem.arraycopy(maxVal, 0, distance, 0, maxVal.length);\n\t\t\n\t\tint head = 0;\n\t\tint tail = 0;\n\t\t\n\t\t// Add to queue\n\t\tqueue[tail++] = to;\n\t\tdistance[to] = 0;\n\t\t\n\t\twhile (head < tail) {\n\t\t\t\n\t\t\t// Remove from queue\n\t\t\tint step = queue[head++];\n\t\t\t\n\t\t\tint nextDistance = distance[step] + 1;\n\t\t\tif (nextDistance > limit) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\tint end = ((step+1) % width == 0 ? 3 : 0);\n\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\tint n = step + dirLR[i];\n\t\t\t\tif (n >= 0 && n < size && passable[n] && (distance[n] > nextDistance)) {\n\t\t\t\t\t// Add to queue\n\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\tdistance[n] = nextDistance;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate static boolean buildDistanceMap( int from, boolean[] to, boolean[] passable ) {\n\t\t\n\t\tif (to[from]) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tSystem.arraycopy(maxVal, 0, distance, 0, maxVal.length);\n\t\t\n\t\tboolean pathFound = false;\n\t\t\n\t\tint head = 0;\n\t\tint tail = 0;\n\t\t\n\t\t// Add to queue\n\t\tfor (int i=0; i < size; i++) {\n\t\t\tif (to[i]) {\n\t\t\t\tqueue[tail++] = i;\n\t\t\t\tdistance[i] = 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\twhile (head < tail) {\n\t\t\t\n\t\t\t// Remove from queue\n\t\t\tint step = queue[head++];\n\t\t\tif (step == from) {\n\t\t\t\tpathFound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tint nextDistance = distance[step] + 1;\n\t\t\t\n\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\tint end = ((step+1) % width == 0 ? 3 : 0);\n\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\tint n = step + dirLR[i];\n\t\t\t\tif (n == from || (n >= 0 && n < size && passable[n] && (distance[n] > nextDistance))) {\n\t\t\t\t\t// Add to queue\n\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\tdistance[n] = nextDistance;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn pathFound;\n\t}\n\n\t//the lookahead is the target number of cells to retreat toward from our current position's\n\t// distance from the position we are escaping from. Returns the highest found distance, up to the lookahead\n\tprivate static int buildEscapeDistanceMap( int cur, int from, int lookAhead, boolean[] passable ) {\n\t\t\n\t\tSystem.arraycopy(maxVal, 0, distance, 0, maxVal.length);\n\t\t\n\t\tint destDist = Integer.MAX_VALUE;\n\t\t\n\t\tint head = 0;\n\t\tint tail = 0;\n\t\t\n\t\t// Add to queue\n\t\tqueue[tail++] = from;\n\t\tdistance[from] = 0;\n\t\t\n\t\tint dist = 0;\n\t\t\n\t\twhile (head < tail) {\n\t\t\t\n\t\t\t// Remove from queue\n\t\t\tint step = queue[head++];\n\t\t\tdist = distance[step];\n\t\t\t\n\t\t\tif (dist > destDist) {\n\t\t\t\treturn destDist;\n\t\t\t}\n\t\t\t\n\t\t\tif (step == cur) {\n\t\t\t\tdestDist = dist + lookAhead;\n\t\t\t}\n\t\t\t\n\t\t\tint nextDistance = dist + 1;\n\t\t\t\n\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\tint end = ((step+1) % width == 0 ? 3 : 0);\n\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\tint n = step + dirLR[i];\n\t\t\t\tif (n >= 0 && n < size && passable[n] && distance[n] > nextDistance) {\n\t\t\t\t\t// Add to queue\n\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\tdistance[n] = nextDistance;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn dist;\n\t}\n\t\n\tpublic static void buildDistanceMap( int to, boolean[] passable ) {\n\t\t\n\t\tSystem.arraycopy(maxVal, 0, distance, 0, maxVal.length);\n\t\t\n\t\tint head = 0;\n\t\tint tail = 0;\n\t\t\n\t\t// Add to queue\n\t\tqueue[tail++] = to;\n\t\tdistance[to] = 0;\n\t\t\n\t\twhile (head < tail) {\n\t\t\t\n\t\t\t// Remove from queue\n\t\t\tint step = queue[head++];\n\t\t\tint nextDistance = distance[step] + 1;\n\t\t\t\n\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\tint end = ((step+1) % width == 0 ? 3 : 0);\n\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\tint n = step + dirLR[i];\n\t\t\t\tif (n >= 0 && n < size && passable[n] && (distance[n] > nextDistance)) {\n\t\t\t\t\t// Add to queue\n\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\tdistance[n] = nextDistance;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@SuppressWarnings(\"serial\")\n\tpublic static class Path extends LinkedList<Integer> {\n\t}\n}" } ]
import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene; import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet; import com.shatteredpixel.shatteredpixeldungeon.ui.AttackIndicator; import com.shatteredpixel.shatteredpixeldungeon.utils.GLog; import com.watabou.noosa.audio.Sample; import com.watabou.utils.Callback; import com.watabou.utils.PathFinder; import com.shatteredpixel.shatteredpixeldungeon.Assets; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.actors.Actor; import com.shatteredpixel.shatteredpixeldungeon.actors.Char; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Invisibility; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero; import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain; import com.shatteredpixel.shatteredpixeldungeon.levels.features.Door; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
88,716
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee; public class Rapier extends MeleeWeapon { {
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee; public class Rapier extends MeleeWeapon { {
image = ItemSpriteSheet.RAPIER;
10
2023-11-27 05:56:58+00:00
128k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/tests/org/jfree/chart/BarChart3DTest.java
[ { "identifier": "ValueAxis", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/axis/ValueAxis.java", "snippet": "public abstract class ValueAxis extends Axis\r\n implements Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 3698345477322391456L;\r\n\r\n /** The default axis range. */\r\n public static final Range DEFAULT_RANGE = new Range(0.0, 1.0);\r\n\r\n /** The default auto-range value. */\r\n public static final boolean DEFAULT_AUTO_RANGE = true;\r\n\r\n /** The default inverted flag setting. */\r\n public static final boolean DEFAULT_INVERTED = false;\r\n\r\n /** The default minimum auto range. */\r\n public static final double DEFAULT_AUTO_RANGE_MINIMUM_SIZE = 0.00000001;\r\n\r\n /** The default value for the lower margin (0.05 = 5%). */\r\n public static final double DEFAULT_LOWER_MARGIN = 0.05;\r\n\r\n /** The default value for the upper margin (0.05 = 5%). */\r\n public static final double DEFAULT_UPPER_MARGIN = 0.05;\r\n\r\n /**\r\n * The default lower bound for the axis.\r\n *\r\n * @deprecated From 1.0.5 onwards, the axis defines a defaultRange\r\n * attribute (see {@link #getDefaultAutoRange()}).\r\n */\r\n public static final double DEFAULT_LOWER_BOUND = 0.0;\r\n\r\n /**\r\n * The default upper bound for the axis.\r\n *\r\n * @deprecated From 1.0.5 onwards, the axis defines a defaultRange\r\n * attribute (see {@link #getDefaultAutoRange()}).\r\n */\r\n public static final double DEFAULT_UPPER_BOUND = 1.0;\r\n\r\n /** The default auto-tick-unit-selection value. */\r\n public static final boolean DEFAULT_AUTO_TICK_UNIT_SELECTION = true;\r\n\r\n /** The maximum tick count. */\r\n public static final int MAXIMUM_TICK_COUNT = 500;\r\n\r\n /**\r\n * A flag that controls whether an arrow is drawn at the positive end of\r\n * the axis line.\r\n */\r\n private boolean positiveArrowVisible;\r\n\r\n /**\r\n * A flag that controls whether an arrow is drawn at the negative end of\r\n * the axis line.\r\n */\r\n private boolean negativeArrowVisible;\r\n\r\n /** The shape used for an up arrow. */\r\n private transient Shape upArrow;\r\n\r\n /** The shape used for a down arrow. */\r\n private transient Shape downArrow;\r\n\r\n /** The shape used for a left arrow. */\r\n private transient Shape leftArrow;\r\n\r\n /** The shape used for a right arrow. */\r\n private transient Shape rightArrow;\r\n\r\n /** A flag that affects the orientation of the values on the axis. */\r\n private boolean inverted;\r\n\r\n /** The axis range. */\r\n private Range range;\r\n\r\n /**\r\n * Flag that indicates whether the axis automatically scales to fit the\r\n * chart data.\r\n */\r\n private boolean autoRange;\r\n\r\n /** The minimum size for the 'auto' axis range (excluding margins). */\r\n private double autoRangeMinimumSize;\r\n\r\n /**\r\n * The default range is used when the dataset is empty and the axis needs\r\n * to determine the auto range.\r\n *\r\n * @since 1.0.5\r\n */\r\n private Range defaultAutoRange;\r\n\r\n /**\r\n * The upper margin percentage. This indicates the amount by which the\r\n * maximum axis value exceeds the maximum data value (as a percentage of\r\n * the range on the axis) when the axis range is determined automatically.\r\n */\r\n private double upperMargin;\r\n\r\n /**\r\n * The lower margin. This is a percentage that indicates the amount by\r\n * which the minimum axis value is \"less than\" the minimum data value when\r\n * the axis range is determined automatically.\r\n */\r\n private double lowerMargin;\r\n\r\n /**\r\n * If this value is positive, the amount is subtracted from the maximum\r\n * data value to determine the lower axis range. This can be used to\r\n * provide a fixed \"window\" on dynamic data.\r\n */\r\n private double fixedAutoRange;\r\n\r\n /**\r\n * Flag that indicates whether or not the tick unit is selected\r\n * automatically.\r\n */\r\n private boolean autoTickUnitSelection;\r\n\r\n /** The standard tick units for the axis. */\r\n private TickUnitSource standardTickUnits;\r\n\r\n /** An index into an array of standard tick values. */\r\n private int autoTickIndex;\r\n\r\n /**\r\n * The number of minor ticks per major tick unit. This is an override\r\n * field, if the value is &gt; 0 it is used, otherwise the axis refers to the\r\n * minorTickCount in the current tickUnit.\r\n */\r\n private int minorTickCount;\r\n\r\n /** A flag indicating whether or not tick labels are rotated to vertical. */\r\n private boolean verticalTickLabels;\r\n\r\n /**\r\n * Constructs a value axis.\r\n *\r\n * @param label the axis label (<code>null</code> permitted).\r\n * @param standardTickUnits the source for standard tick units\r\n * (<code>null</code> permitted).\r\n */\r\n protected ValueAxis(String label, TickUnitSource standardTickUnits) {\r\n\r\n super(label);\r\n\r\n this.positiveArrowVisible = false;\r\n this.negativeArrowVisible = false;\r\n\r\n this.range = DEFAULT_RANGE;\r\n this.autoRange = DEFAULT_AUTO_RANGE;\r\n this.defaultAutoRange = DEFAULT_RANGE;\r\n\r\n this.inverted = DEFAULT_INVERTED;\r\n this.autoRangeMinimumSize = DEFAULT_AUTO_RANGE_MINIMUM_SIZE;\r\n\r\n this.lowerMargin = DEFAULT_LOWER_MARGIN;\r\n this.upperMargin = DEFAULT_UPPER_MARGIN;\r\n\r\n this.fixedAutoRange = 0.0;\r\n\r\n this.autoTickUnitSelection = DEFAULT_AUTO_TICK_UNIT_SELECTION;\r\n this.standardTickUnits = standardTickUnits;\r\n\r\n Polygon p1 = new Polygon();\r\n p1.addPoint(0, 0);\r\n p1.addPoint(-2, 2);\r\n p1.addPoint(2, 2);\r\n\r\n this.upArrow = p1;\r\n\r\n Polygon p2 = new Polygon();\r\n p2.addPoint(0, 0);\r\n p2.addPoint(-2, -2);\r\n p2.addPoint(2, -2);\r\n\r\n this.downArrow = p2;\r\n\r\n Polygon p3 = new Polygon();\r\n p3.addPoint(0, 0);\r\n p3.addPoint(-2, -2);\r\n p3.addPoint(-2, 2);\r\n\r\n this.rightArrow = p3;\r\n\r\n Polygon p4 = new Polygon();\r\n p4.addPoint(0, 0);\r\n p4.addPoint(2, -2);\r\n p4.addPoint(2, 2);\r\n\r\n this.leftArrow = p4;\r\n\r\n this.verticalTickLabels = false;\r\n this.minorTickCount = 0;\r\n\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the tick labels should be rotated (to\r\n * vertical), and <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setVerticalTickLabels(boolean)\r\n */\r\n public boolean isVerticalTickLabels() {\r\n return this.verticalTickLabels;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether the tick labels are displayed\r\n * vertically (that is, rotated 90 degrees from horizontal). If the flag\r\n * is changed, an {@link AxisChangeEvent} is sent to all registered\r\n * listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isVerticalTickLabels()\r\n */\r\n public void setVerticalTickLabels(boolean flag) {\r\n if (this.verticalTickLabels != flag) {\r\n this.verticalTickLabels = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not the axis line has an arrow\r\n * drawn that points in the positive direction for the axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setPositiveArrowVisible(boolean)\r\n */\r\n public boolean isPositiveArrowVisible() {\r\n return this.positiveArrowVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not the axis lines has an arrow\r\n * drawn that points in the positive direction for the axis, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isPositiveArrowVisible()\r\n */\r\n public void setPositiveArrowVisible(boolean visible) {\r\n this.positiveArrowVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not the axis line has an arrow\r\n * drawn that points in the negative direction for the axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNegativeArrowVisible(boolean)\r\n */\r\n public boolean isNegativeArrowVisible() {\r\n return this.negativeArrowVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not the axis lines has an arrow\r\n * drawn that points in the negative direction for the axis, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #setNegativeArrowVisible(boolean)\r\n */\r\n public void setNegativeArrowVisible(boolean visible) {\r\n this.negativeArrowVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing upwards at\r\n * the end of an axis line.\r\n *\r\n * @return A shape (never <code>null</code>).\r\n *\r\n * @see #setUpArrow(Shape)\r\n */\r\n public Shape getUpArrow() {\r\n return this.upArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing upwards at\r\n * the end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (<code>null</code> not permitted).\r\n *\r\n * @see #getUpArrow()\r\n */\r\n public void setUpArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.upArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing downwards at\r\n * the end of an axis line.\r\n *\r\n * @return A shape (never <code>null</code>).\r\n *\r\n * @see #setDownArrow(Shape)\r\n */\r\n public Shape getDownArrow() {\r\n return this.downArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing downwards at\r\n * the end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (<code>null</code> not permitted).\r\n *\r\n * @see #getDownArrow()\r\n */\r\n public void setDownArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.downArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing left at the\r\n * end of an axis line.\r\n *\r\n * @return A shape (never <code>null</code>).\r\n *\r\n * @see #setLeftArrow(Shape)\r\n */\r\n public Shape getLeftArrow() {\r\n return this.leftArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing left at the\r\n * end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (<code>null</code> not permitted).\r\n *\r\n * @see #getLeftArrow()\r\n */\r\n public void setLeftArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.leftArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing right at the\r\n * end of an axis line.\r\n *\r\n * @return A shape (never <code>null</code>).\r\n *\r\n * @see #setRightArrow(Shape)\r\n */\r\n public Shape getRightArrow() {\r\n return this.rightArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing rightwards at\r\n * the end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (<code>null</code> not permitted).\r\n *\r\n * @see #getRightArrow()\r\n */\r\n public void setRightArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.rightArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Draws an axis line at the current cursor position and edge.\r\n *\r\n * @param g2 the graphics device ({@code null} not permitted).\r\n * @param cursor the cursor position.\r\n * @param dataArea the data area.\r\n * @param edge the edge.\r\n */\r\n @Override\r\n protected void drawAxisLine(Graphics2D g2, double cursor,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n Line2D axisLine = null;\r\n double c = cursor;\r\n if (edge == RectangleEdge.TOP) {\r\n axisLine = new Line2D.Double(dataArea.getX(), c, dataArea.getMaxX(),\r\n c);\r\n } else if (edge == RectangleEdge.BOTTOM) {\r\n axisLine = new Line2D.Double(dataArea.getX(), c, dataArea.getMaxX(),\r\n c);\r\n } else if (edge == RectangleEdge.LEFT) {\r\n axisLine = new Line2D.Double(c, dataArea.getY(), c, \r\n dataArea.getMaxY());\r\n } else if (edge == RectangleEdge.RIGHT) {\r\n axisLine = new Line2D.Double(c, dataArea.getY(), c,\r\n dataArea.getMaxY());\r\n }\r\n g2.setPaint(getAxisLinePaint());\r\n g2.setStroke(getAxisLineStroke());\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n g2.draw(axisLine);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n\r\n boolean drawUpOrRight = false;\r\n boolean drawDownOrLeft = false;\r\n if (this.positiveArrowVisible) {\r\n if (this.inverted) {\r\n drawDownOrLeft = true;\r\n }\r\n else {\r\n drawUpOrRight = true;\r\n }\r\n }\r\n if (this.negativeArrowVisible) {\r\n if (this.inverted) {\r\n drawUpOrRight = true;\r\n } else {\r\n drawDownOrLeft = true;\r\n }\r\n }\r\n if (drawUpOrRight) {\r\n double x = 0.0;\r\n double y = 0.0;\r\n Shape arrow = null;\r\n if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {\r\n x = dataArea.getMaxX();\r\n y = cursor;\r\n arrow = this.rightArrow;\r\n } else if (edge == RectangleEdge.LEFT\r\n || edge == RectangleEdge.RIGHT) {\r\n x = cursor;\r\n y = dataArea.getMinY();\r\n arrow = this.upArrow;\r\n }\r\n\r\n // draw the arrow...\r\n AffineTransform transformer = new AffineTransform();\r\n transformer.setToTranslation(x, y);\r\n Shape shape = transformer.createTransformedShape(arrow);\r\n g2.fill(shape);\r\n g2.draw(shape);\r\n }\r\n\r\n if (drawDownOrLeft) {\r\n double x = 0.0;\r\n double y = 0.0;\r\n Shape arrow = null;\r\n if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {\r\n x = dataArea.getMinX();\r\n y = cursor;\r\n arrow = this.leftArrow;\r\n } else if (edge == RectangleEdge.LEFT\r\n || edge == RectangleEdge.RIGHT) {\r\n x = cursor;\r\n y = dataArea.getMaxY();\r\n arrow = this.downArrow;\r\n }\r\n\r\n // draw the arrow...\r\n AffineTransform transformer = new AffineTransform();\r\n transformer.setToTranslation(x, y);\r\n Shape shape = transformer.createTransformedShape(arrow);\r\n g2.fill(shape);\r\n g2.draw(shape);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Calculates the anchor point for a tick label.\r\n *\r\n * @param tick the tick.\r\n * @param cursor the cursor.\r\n * @param dataArea the data area.\r\n * @param edge the edge on which the axis is drawn.\r\n *\r\n * @return The x and y coordinates of the anchor point.\r\n */\r\n protected float[] calculateAnchorPoint(ValueTick tick, double cursor,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n RectangleInsets insets = getTickLabelInsets();\r\n float[] result = new float[2];\r\n if (edge == RectangleEdge.TOP) {\r\n result[0] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n result[1] = (float) (cursor - insets.getBottom() - 2.0);\r\n }\r\n else if (edge == RectangleEdge.BOTTOM) {\r\n result[0] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n result[1] = (float) (cursor + insets.getTop() + 2.0);\r\n }\r\n else if (edge == RectangleEdge.LEFT) {\r\n result[0] = (float) (cursor - insets.getLeft() - 2.0);\r\n result[1] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n }\r\n else if (edge == RectangleEdge.RIGHT) {\r\n result[0] = (float) (cursor + insets.getRight() + 2.0);\r\n result[1] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Draws the axis line, tick marks and tick mark labels.\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param cursor the cursor.\r\n * @param plotArea the plot area (<code>null</code> not permitted).\r\n * @param dataArea the data area (<code>null</code> not permitted).\r\n * @param edge the edge that the axis is aligned with (<code>null</code> \r\n * not permitted).\r\n *\r\n * @return The width or height used to draw the axis.\r\n */\r\n protected AxisState drawTickMarksAndLabels(Graphics2D g2,\r\n double cursor, Rectangle2D plotArea, Rectangle2D dataArea,\r\n RectangleEdge edge) {\r\n\r\n AxisState state = new AxisState(cursor);\r\n if (isAxisLineVisible()) {\r\n drawAxisLine(g2, cursor, dataArea, edge);\r\n }\r\n List ticks = refreshTicks(g2, state, dataArea, edge);\r\n state.setTicks(ticks);\r\n g2.setFont(getTickLabelFont());\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if (isTickLabelsVisible()) {\r\n g2.setPaint(getTickLabelPaint());\r\n float[] anchorPoint = calculateAnchorPoint(tick, cursor,\r\n dataArea, edge);\r\n if (tick instanceof LogTick) {\r\n LogTick lt = (LogTick) tick;\r\n if (lt.getAttributedLabel() == null) {\r\n continue;\r\n }\r\n AttrStringUtils.drawRotatedString(lt.getAttributedLabel(), \r\n g2, anchorPoint[0], anchorPoint[1], \r\n tick.getTextAnchor(), tick.getAngle(), \r\n tick.getRotationAnchor());\r\n } else {\r\n if (tick.getText() == null) {\r\n continue;\r\n }\r\n TextUtilities.drawRotatedString(tick.getText(), g2,\r\n anchorPoint[0], anchorPoint[1], \r\n tick.getTextAnchor(), tick.getAngle(), \r\n tick.getRotationAnchor());\r\n }\r\n }\r\n\r\n if ((isTickMarksVisible() && tick.getTickType().equals(\r\n TickType.MAJOR)) || (isMinorTickMarksVisible()\r\n && tick.getTickType().equals(TickType.MINOR))) {\r\n\r\n double ol = (tick.getTickType().equals(TickType.MINOR)) \r\n ? getMinorTickMarkOutsideLength()\r\n : getTickMarkOutsideLength();\r\n\r\n double il = (tick.getTickType().equals(TickType.MINOR)) \r\n ? getMinorTickMarkInsideLength()\r\n : getTickMarkInsideLength();\r\n\r\n float xx = (float) valueToJava2D(tick.getValue(), dataArea,\r\n edge);\r\n Line2D mark = null;\r\n g2.setStroke(getTickMarkStroke());\r\n g2.setPaint(getTickMarkPaint());\r\n if (edge == RectangleEdge.LEFT) {\r\n mark = new Line2D.Double(cursor - ol, xx, cursor + il, xx);\r\n }\r\n else if (edge == RectangleEdge.RIGHT) {\r\n mark = new Line2D.Double(cursor + ol, xx, cursor - il, xx);\r\n }\r\n else if (edge == RectangleEdge.TOP) {\r\n mark = new Line2D.Double(xx, cursor - ol, xx, cursor + il);\r\n }\r\n else if (edge == RectangleEdge.BOTTOM) {\r\n mark = new Line2D.Double(xx, cursor + ol, xx, cursor - il);\r\n }\r\n g2.draw(mark);\r\n }\r\n }\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n \r\n // need to work out the space used by the tick labels...\r\n // so we can update the cursor...\r\n double used = 0.0;\r\n if (isTickLabelsVisible()) {\r\n if (edge == RectangleEdge.LEFT) {\r\n used += findMaximumTickLabelWidth(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorLeft(used);\r\n } else if (edge == RectangleEdge.RIGHT) {\r\n used = findMaximumTickLabelWidth(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorRight(used);\r\n } else if (edge == RectangleEdge.TOP) {\r\n used = findMaximumTickLabelHeight(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorUp(used);\r\n } else if (edge == RectangleEdge.BOTTOM) {\r\n used = findMaximumTickLabelHeight(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorDown(used);\r\n }\r\n }\r\n\r\n return state;\r\n }\r\n\r\n /**\r\n * Returns the space required to draw the axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plot the plot that the axis belongs to.\r\n * @param plotArea the area within which the plot should be drawn.\r\n * @param edge the axis location.\r\n * @param space the space already reserved (for other axes).\r\n *\r\n * @return The space required to draw the axis (including pre-reserved\r\n * space).\r\n */\r\n @Override\r\n public AxisSpace reserveSpace(Graphics2D g2, Plot plot, \r\n Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) {\r\n\r\n // create a new space object if one wasn't supplied...\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // if the axis is not visible, no additional space is required...\r\n if (!isVisible()) {\r\n return space;\r\n }\r\n\r\n // if the axis has a fixed dimension, return it...\r\n double dimension = getFixedDimension();\r\n if (dimension > 0.0) {\r\n space.add(dimension, edge);\r\n return space;\r\n }\r\n\r\n // calculate the max size of the tick labels (if visible)...\r\n double tickLabelHeight = 0.0;\r\n double tickLabelWidth = 0.0;\r\n if (isTickLabelsVisible()) {\r\n g2.setFont(getTickLabelFont());\r\n List ticks = refreshTicks(g2, new AxisState(), plotArea, edge);\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n tickLabelHeight = findMaximumTickLabelHeight(ticks, g2,\r\n plotArea, isVerticalTickLabels());\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n tickLabelWidth = findMaximumTickLabelWidth(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n }\r\n }\r\n\r\n // get the axis label size and update the space object...\r\n Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge);\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n double labelHeight = labelEnclosure.getHeight();\r\n space.add(labelHeight + tickLabelHeight, edge);\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n double labelWidth = labelEnclosure.getWidth();\r\n space.add(labelWidth + tickLabelWidth, edge);\r\n }\r\n\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * A utility method for determining the height of the tallest tick label.\r\n *\r\n * @param ticks the ticks.\r\n * @param g2 the graphics device.\r\n * @param drawArea the area within which the plot and axes should be drawn.\r\n * @param vertical a flag that indicates whether or not the tick labels\r\n * are 'vertical'.\r\n *\r\n * @return The height of the tallest tick label.\r\n */\r\n protected double findMaximumTickLabelHeight(List ticks, Graphics2D g2,\r\n Rectangle2D drawArea, boolean vertical) {\r\n\r\n RectangleInsets insets = getTickLabelInsets();\r\n Font font = getTickLabelFont();\r\n g2.setFont(font);\r\n double maxHeight = 0.0;\r\n if (vertical) {\r\n FontMetrics fm = g2.getFontMetrics(font);\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n Tick tick = (Tick) iterator.next();\r\n Rectangle2D labelBounds = null;\r\n if (tick instanceof LogTick) {\r\n LogTick lt = (LogTick) tick;\r\n if (lt.getAttributedLabel() != null) {\r\n labelBounds = AttrStringUtils.getTextBounds(\r\n lt.getAttributedLabel(), g2);\r\n }\r\n } else if (tick.getText() != null) {\r\n labelBounds = TextUtilities.getTextBounds(\r\n tick.getText(), g2, fm);\r\n }\r\n if (labelBounds != null && labelBounds.getWidth() \r\n + insets.getTop() + insets.getBottom() > maxHeight) {\r\n maxHeight = labelBounds.getWidth()\r\n + insets.getTop() + insets.getBottom();\r\n }\r\n }\r\n } else {\r\n LineMetrics metrics = font.getLineMetrics(\"ABCxyz\",\r\n g2.getFontRenderContext());\r\n maxHeight = metrics.getHeight()\r\n + insets.getTop() + insets.getBottom();\r\n }\r\n return maxHeight;\r\n\r\n }\r\n\r\n /**\r\n * A utility method for determining the width of the widest tick label.\r\n *\r\n * @param ticks the ticks.\r\n * @param g2 the graphics device.\r\n * @param drawArea the area within which the plot and axes should be drawn.\r\n * @param vertical a flag that indicates whether or not the tick labels\r\n * are 'vertical'.\r\n *\r\n * @return The width of the tallest tick label.\r\n */\r\n protected double findMaximumTickLabelWidth(List ticks, Graphics2D g2,\r\n Rectangle2D drawArea, boolean vertical) {\r\n\r\n RectangleInsets insets = getTickLabelInsets();\r\n Font font = getTickLabelFont();\r\n double maxWidth = 0.0;\r\n if (!vertical) {\r\n FontMetrics fm = g2.getFontMetrics(font);\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n Tick tick = (Tick) iterator.next();\r\n Rectangle2D labelBounds = null;\r\n if (tick instanceof LogTick) {\r\n LogTick lt = (LogTick) tick;\r\n if (lt.getAttributedLabel() != null) {\r\n labelBounds = AttrStringUtils.getTextBounds(\r\n lt.getAttributedLabel(), g2);\r\n }\r\n } else if (tick.getText() != null) {\r\n labelBounds = TextUtilities.getTextBounds(tick.getText(), \r\n g2, fm);\r\n }\r\n if (labelBounds != null \r\n && labelBounds.getWidth() + insets.getLeft()\r\n + insets.getRight() > maxWidth) {\r\n maxWidth = labelBounds.getWidth()\r\n + insets.getLeft() + insets.getRight();\r\n }\r\n }\r\n } else {\r\n LineMetrics metrics = font.getLineMetrics(\"ABCxyz\",\r\n g2.getFontRenderContext());\r\n maxWidth = metrics.getHeight()\r\n + insets.getTop() + insets.getBottom();\r\n }\r\n return maxWidth;\r\n\r\n }\r\n\r\n /**\r\n * Returns a flag that controls the direction of values on the axis.\r\n * <P>\r\n * For a regular axis, values increase from left to right (for a horizontal\r\n * axis) and bottom to top (for a vertical axis). When the axis is\r\n * 'inverted', the values increase in the opposite direction.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setInverted(boolean)\r\n */\r\n public boolean isInverted() {\r\n return this.inverted;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls the direction of values on the axis, and\r\n * notifies registered listeners that the axis has changed.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isInverted()\r\n */\r\n public void setInverted(boolean flag) {\r\n if (this.inverted != flag) {\r\n this.inverted = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the axis range is\r\n * automatically adjusted to fit the data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAutoRange(boolean)\r\n */\r\n public boolean isAutoRange() {\r\n return this.autoRange;\r\n }\r\n\r\n /**\r\n * Sets a flag that determines whether or not the axis range is\r\n * automatically adjusted to fit the data, and notifies registered\r\n * listeners that the axis has been modified.\r\n *\r\n * @param auto the new value of the flag.\r\n *\r\n * @see #isAutoRange()\r\n */\r\n public void setAutoRange(boolean auto) {\r\n setAutoRange(auto, true);\r\n }\r\n\r\n /**\r\n * Sets the auto range attribute. If the <code>notify</code> flag is set,\r\n * an {@link AxisChangeEvent} is sent to registered listeners.\r\n *\r\n * @param auto the flag.\r\n * @param notify notify listeners?\r\n *\r\n * @see #isAutoRange()\r\n */\r\n protected void setAutoRange(boolean auto, boolean notify) {\r\n if (this.autoRange != auto) {\r\n this.autoRange = auto;\r\n if (this.autoRange) {\r\n autoAdjustRange();\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the minimum size allowed for the axis range when it is\r\n * automatically calculated.\r\n *\r\n * @return The minimum range.\r\n *\r\n * @see #setAutoRangeMinimumSize(double)\r\n */\r\n public double getAutoRangeMinimumSize() {\r\n return this.autoRangeMinimumSize;\r\n }\r\n\r\n /**\r\n * Sets the auto range minimum size and sends an {@link AxisChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param size the size.\r\n *\r\n * @see #getAutoRangeMinimumSize()\r\n */\r\n public void setAutoRangeMinimumSize(double size) {\r\n setAutoRangeMinimumSize(size, true);\r\n }\r\n\r\n /**\r\n * Sets the minimum size allowed for the axis range when it is\r\n * automatically calculated.\r\n * <p>\r\n * If requested, an {@link AxisChangeEvent} is forwarded to all registered\r\n * listeners.\r\n *\r\n * @param size the new minimum.\r\n * @param notify notify listeners?\r\n */\r\n public void setAutoRangeMinimumSize(double size, boolean notify) {\r\n if (size <= 0.0) {\r\n throw new IllegalArgumentException(\r\n \"NumberAxis.setAutoRangeMinimumSize(double): must be > 0.0.\");\r\n }\r\n if (this.autoRangeMinimumSize != size) {\r\n this.autoRangeMinimumSize = size;\r\n if (this.autoRange) {\r\n autoAdjustRange();\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the default auto range.\r\n *\r\n * @return The default auto range (never <code>null</code>).\r\n *\r\n * @see #setDefaultAutoRange(Range)\r\n *\r\n * @since 1.0.5\r\n */\r\n public Range getDefaultAutoRange() {\r\n return this.defaultAutoRange;\r\n }\r\n\r\n /**\r\n * Sets the default auto range and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n *\r\n * @see #getDefaultAutoRange()\r\n *\r\n * @since 1.0.5\r\n */\r\n public void setDefaultAutoRange(Range range) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n this.defaultAutoRange = range;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the lower margin for the axis, expressed as a percentage of the\r\n * axis range. This controls the space added to the lower end of the axis\r\n * when the axis range is automatically calculated (it is ignored when the\r\n * axis range is set explicitly). The default value is 0.05 (five percent).\r\n *\r\n * @return The lower margin.\r\n *\r\n * @see #setLowerMargin(double)\r\n */\r\n public double getLowerMargin() {\r\n return this.lowerMargin;\r\n }\r\n\r\n /**\r\n * Sets the lower margin for the axis (as a percentage of the axis range)\r\n * and sends an {@link AxisChangeEvent} to all registered listeners. This\r\n * margin is added only when the axis range is auto-calculated - if you set\r\n * the axis range manually, the margin is ignored.\r\n *\r\n * @param margin the margin percentage (for example, 0.05 is five percent).\r\n *\r\n * @see #getLowerMargin()\r\n * @see #setUpperMargin(double)\r\n */\r\n public void setLowerMargin(double margin) {\r\n this.lowerMargin = margin;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the upper margin for the axis, expressed as a percentage of the\r\n * axis range. This controls the space added to the lower end of the axis\r\n * when the axis range is automatically calculated (it is ignored when the\r\n * axis range is set explicitly). The default value is 0.05 (five percent).\r\n *\r\n * @return The upper margin.\r\n *\r\n * @see #setUpperMargin(double)\r\n */\r\n public double getUpperMargin() {\r\n return this.upperMargin;\r\n }\r\n\r\n /**\r\n * Sets the upper margin for the axis (as a percentage of the axis range)\r\n * and sends an {@link AxisChangeEvent} to all registered listeners. This\r\n * margin is added only when the axis range is auto-calculated - if you set\r\n * the axis range manually, the margin is ignored.\r\n *\r\n * @param margin the margin percentage (for example, 0.05 is five percent).\r\n *\r\n * @see #getLowerMargin()\r\n * @see #setLowerMargin(double)\r\n */\r\n public void setUpperMargin(double margin) {\r\n this.upperMargin = margin;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the fixed auto range.\r\n *\r\n * @return The length.\r\n *\r\n * @see #setFixedAutoRange(double)\r\n */\r\n public double getFixedAutoRange() {\r\n return this.fixedAutoRange;\r\n }\r\n\r\n /**\r\n * Sets the fixed auto range for the axis.\r\n *\r\n * @param length the range length.\r\n *\r\n * @see #getFixedAutoRange()\r\n */\r\n public void setFixedAutoRange(double length) {\r\n this.fixedAutoRange = length;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the lower bound of the axis range.\r\n *\r\n * @return The lower bound.\r\n *\r\n * @see #setLowerBound(double)\r\n */\r\n public double getLowerBound() {\r\n return this.range.getLowerBound();\r\n }\r\n\r\n /**\r\n * Sets the lower bound for the axis range. An {@link AxisChangeEvent} is\r\n * sent to all registered listeners.\r\n *\r\n * @param min the new minimum.\r\n *\r\n * @see #getLowerBound()\r\n */\r\n public void setLowerBound(double min) {\r\n if (this.range.getUpperBound() > min) {\r\n setRange(new Range(min, this.range.getUpperBound()));\r\n }\r\n else {\r\n setRange(new Range(min, min + 1.0));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the upper bound for the axis range.\r\n *\r\n * @return The upper bound.\r\n *\r\n * @see #setUpperBound(double)\r\n */\r\n public double getUpperBound() {\r\n return this.range.getUpperBound();\r\n }\r\n\r\n /**\r\n * Sets the upper bound for the axis range, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param max the new maximum.\r\n *\r\n * @see #getUpperBound()\r\n */\r\n public void setUpperBound(double max) {\r\n if (this.range.getLowerBound() < max) {\r\n setRange(new Range(this.range.getLowerBound(), max));\r\n }\r\n else {\r\n setRange(max - 1.0, max);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range for the axis.\r\n *\r\n * @return The axis range (never <code>null</code>).\r\n *\r\n * @see #setRange(Range)\r\n */\r\n public Range getRange() {\r\n return this.range;\r\n }\r\n\r\n /**\r\n * Sets the range for the axis and sends a change event to all registered \r\n * listeners. As a side-effect, the auto-range flag is set to\r\n * <code>false</code>.\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n *\r\n * @see #getRange()\r\n */\r\n public void setRange(Range range) {\r\n // defer argument checking\r\n setRange(range, true, true);\r\n }\r\n\r\n /**\r\n * Sets the range for the axis and, if requested, sends a change event to \r\n * all registered listeners. Furthermore, if <code>turnOffAutoRange</code>\r\n * is <code>true</code>, the auto-range flag is set to <code>false</code> \r\n * (normally when setting the axis range manually the caller expects that\r\n * range to remain in force).\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n * @param turnOffAutoRange a flag that controls whether or not the auto\r\n * range is turned off.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n *\r\n * @see #getRange()\r\n */\r\n public void setRange(Range range, boolean turnOffAutoRange, \r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n if (range.getLength() <= 0.0) {\r\n throw new IllegalArgumentException(\r\n \"A positive range length is required: \" + range);\r\n }\r\n if (turnOffAutoRange) {\r\n this.autoRange = false;\r\n }\r\n this.range = range;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the range for the axis and sends a change event to all registered \r\n * listeners. As a side-effect, the auto-range flag is set to\r\n * <code>false</code>.\r\n *\r\n * @param lower the lower axis limit.\r\n * @param upper the upper axis limit.\r\n *\r\n * @see #getRange()\r\n * @see #setRange(Range)\r\n */\r\n public void setRange(double lower, double upper) {\r\n setRange(new Range(lower, upper));\r\n }\r\n\r\n /**\r\n * Sets the range for the axis (after first adding the current margins to\r\n * the specified range) and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n */\r\n public void setRangeWithMargins(Range range) {\r\n setRangeWithMargins(range, true, true);\r\n }\r\n\r\n /**\r\n * Sets the range for the axis after first adding the current margins to\r\n * the range and, if requested, sends an {@link AxisChangeEvent} to all\r\n * registered listeners. As a side-effect, the auto-range flag is set to\r\n * <code>false</code> (optional).\r\n *\r\n * @param range the range (excluding margins, <code>null</code> not\r\n * permitted).\r\n * @param turnOffAutoRange a flag that controls whether or not the auto\r\n * range is turned off.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n */\r\n public void setRangeWithMargins(Range range, boolean turnOffAutoRange,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n setRange(Range.expand(range, getLowerMargin(), getUpperMargin()),\r\n turnOffAutoRange, notify);\r\n }\r\n\r\n /**\r\n * Sets the axis range (after first adding the current margins to the\r\n * range) and sends an {@link AxisChangeEvent} to all registered listeners.\r\n * As a side-effect, the auto-range flag is set to <code>false</code>.\r\n *\r\n * @param lower the lower axis limit.\r\n * @param upper the upper axis limit.\r\n */\r\n public void setRangeWithMargins(double lower, double upper) {\r\n setRangeWithMargins(new Range(lower, upper));\r\n }\r\n\r\n /**\r\n * Sets the axis range, where the new range is 'size' in length, and\r\n * centered on 'value'.\r\n *\r\n * @param value the central value.\r\n * @param length the range length.\r\n */\r\n public void setRangeAboutValue(double value, double length) {\r\n setRange(new Range(value - length / 2, value + length / 2));\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the tick unit is automatically\r\n * selected from a range of standard tick units.\r\n *\r\n * @return A flag indicating whether or not the tick unit is automatically\r\n * selected.\r\n *\r\n * @see #setAutoTickUnitSelection(boolean)\r\n */\r\n public boolean isAutoTickUnitSelection() {\r\n return this.autoTickUnitSelection;\r\n }\r\n\r\n /**\r\n * Sets a flag indicating whether or not the tick unit is automatically\r\n * selected from a range of standard tick units. If the flag is changed,\r\n * registered listeners are notified that the chart has changed.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isAutoTickUnitSelection()\r\n */\r\n public void setAutoTickUnitSelection(boolean flag) {\r\n setAutoTickUnitSelection(flag, true);\r\n }\r\n\r\n /**\r\n * Sets a flag indicating whether or not the tick unit is automatically\r\n * selected from a range of standard tick units.\r\n *\r\n * @param flag the new value of the flag.\r\n * @param notify notify listeners?\r\n *\r\n * @see #isAutoTickUnitSelection()\r\n */\r\n public void setAutoTickUnitSelection(boolean flag, boolean notify) {\r\n\r\n if (this.autoTickUnitSelection != flag) {\r\n this.autoTickUnitSelection = flag;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the source for obtaining standard tick units for the axis.\r\n *\r\n * @return The source (possibly <code>null</code>).\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n */\r\n public TickUnitSource getStandardTickUnits() {\r\n return this.standardTickUnits;\r\n }\r\n\r\n /**\r\n * Sets the source for obtaining standard tick units for the axis and sends\r\n * an {@link AxisChangeEvent} to all registered listeners. The axis will\r\n * try to select the smallest tick unit from the source that does not cause\r\n * the tick labels to overlap (see also the\r\n * {@link #setAutoTickUnitSelection(boolean)} method.\r\n *\r\n * @param source the source for standard tick units (<code>null</code>\r\n * permitted).\r\n *\r\n * @see #getStandardTickUnits()\r\n */\r\n public void setStandardTickUnits(TickUnitSource source) {\r\n this.standardTickUnits = source;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the number of minor tick marks to display.\r\n *\r\n * @return The number of minor tick marks to display.\r\n *\r\n * @see #setMinorTickCount(int)\r\n *\r\n * @since 1.0.12\r\n */\r\n public int getMinorTickCount() {\r\n return this.minorTickCount;\r\n }\r\n\r\n /**\r\n * Sets the number of minor tick marks to display, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param count the count.\r\n *\r\n * @see #getMinorTickCount()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setMinorTickCount(int count) {\r\n this.minorTickCount = count;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Converts a data value to a coordinate in Java2D space, assuming that the\r\n * axis runs along one edge of the specified dataArea.\r\n * <p>\r\n * Note that it is possible for the coordinate to fall outside the area.\r\n *\r\n * @param value the data value.\r\n * @param area the area for plotting the data.\r\n * @param edge the edge along which the axis lies.\r\n *\r\n * @return The Java2D coordinate.\r\n *\r\n * @see #java2DToValue(double, Rectangle2D, RectangleEdge)\r\n */\r\n public abstract double valueToJava2D(double value, Rectangle2D area,\r\n RectangleEdge edge);\r\n\r\n /**\r\n * Converts a length in data coordinates into the corresponding length in\r\n * Java2D coordinates.\r\n *\r\n * @param length the length.\r\n * @param area the plot area.\r\n * @param edge the edge along which the axis lies.\r\n *\r\n * @return The length in Java2D coordinates.\r\n */\r\n public double lengthToJava2D(double length, Rectangle2D area,\r\n RectangleEdge edge) {\r\n double zero = valueToJava2D(0.0, area, edge);\r\n double l = valueToJava2D(length, area, edge);\r\n return Math.abs(l - zero);\r\n }\r\n\r\n /**\r\n * Converts a coordinate in Java2D space to the corresponding data value,\r\n * assuming that the axis runs along one edge of the specified dataArea.\r\n *\r\n * @param java2DValue the coordinate in Java2D space.\r\n * @param area the area in which the data is plotted.\r\n * @param edge the edge along which the axis lies.\r\n *\r\n * @return The data value.\r\n *\r\n * @see #valueToJava2D(double, Rectangle2D, RectangleEdge)\r\n */\r\n public abstract double java2DToValue(double java2DValue, Rectangle2D area, \r\n RectangleEdge edge);\r\n\r\n /**\r\n * Automatically sets the axis range to fit the range of values in the\r\n * dataset. Sometimes this can depend on the renderer used as well (for\r\n * example, the renderer may \"stack\" values, requiring an axis range\r\n * greater than otherwise necessary).\r\n */\r\n protected abstract void autoAdjustRange();\r\n\r\n /**\r\n * Centers the axis range about the specified value and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param value the center value.\r\n */\r\n public void centerRange(double value) {\r\n double central = this.range.getCentralValue();\r\n Range adjusted = new Range(this.range.getLowerBound() + value - central,\r\n this.range.getUpperBound() + value - central);\r\n setRange(adjusted);\r\n }\r\n\r\n /**\r\n * Increases or decreases the axis range by the specified percentage about\r\n * the central value and sends an {@link AxisChangeEvent} to all registered\r\n * listeners.\r\n * <P>\r\n * To double the length of the axis range, use 200% (2.0).\r\n * To halve the length of the axis range, use 50% (0.5).\r\n *\r\n * @param percent the resize factor.\r\n *\r\n * @see #resizeRange(double, double)\r\n */\r\n public void resizeRange(double percent) {\r\n resizeRange(percent, this.range.getCentralValue());\r\n }\r\n\r\n /**\r\n * Increases or decreases the axis range by the specified percentage about\r\n * the specified anchor value and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n * <P>\r\n * To double the length of the axis range, use 200% (2.0).\r\n * To halve the length of the axis range, use 50% (0.5).\r\n *\r\n * @param percent the resize factor.\r\n * @param anchorValue the new central value after the resize.\r\n *\r\n * @see #resizeRange(double)\r\n */\r\n public void resizeRange(double percent, double anchorValue) {\r\n if (percent > 0.0) {\r\n double halfLength = this.range.getLength() * percent / 2;\r\n Range adjusted = new Range(anchorValue - halfLength,\r\n anchorValue + halfLength);\r\n setRange(adjusted);\r\n }\r\n else {\r\n setAutoRange(true);\r\n }\r\n }\r\n\r\n /**\r\n * Increases or decreases the axis range by the specified percentage about\r\n * the specified anchor value and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n * <P>\r\n * To double the length of the axis range, use 200% (2.0).\r\n * To halve the length of the axis range, use 50% (0.5).\r\n *\r\n * @param percent the resize factor.\r\n * @param anchorValue the new central value after the resize.\r\n *\r\n * @see #resizeRange(double)\r\n *\r\n * @since 1.0.13\r\n */\r\n public void resizeRange2(double percent, double anchorValue) {\r\n if (percent > 0.0) {\r\n double left = anchorValue - getLowerBound();\r\n double right = getUpperBound() - anchorValue;\r\n Range adjusted = new Range(anchorValue - left * percent,\r\n anchorValue + right * percent);\r\n setRange(adjusted);\r\n }\r\n else {\r\n setAutoRange(true);\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the current range.\r\n *\r\n * @param lowerPercent the new lower bound.\r\n * @param upperPercent the new upper bound.\r\n */\r\n public void zoomRange(double lowerPercent, double upperPercent) {\r\n double start = this.range.getLowerBound();\r\n double length = this.range.getLength();\r\n double r0, r1;\r\n if (isInverted()) {\r\n r0 = start + (length * (1 - upperPercent));\r\n r1 = start + (length * (1 - lowerPercent));\r\n }\r\n else {\r\n r0 = start + length * lowerPercent;\r\n r1 = start + length * upperPercent;\r\n }\r\n if ((r1 > r0) && !Double.isInfinite(r1 - r0)) {\r\n setRange(new Range(r0, r1));\r\n }\r\n }\r\n\r\n /**\r\n * Slides the axis range by the specified percentage.\r\n *\r\n * @param percent the percentage.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void pan(double percent) {\r\n Range r = getRange();\r\n double length = range.getLength();\r\n double adj = length * percent;\r\n double lower = r.getLowerBound() + adj;\r\n double upper = r.getUpperBound() + adj;\r\n setRange(lower, upper);\r\n }\r\n\r\n /**\r\n * Returns the auto tick index.\r\n *\r\n * @return The auto tick index.\r\n *\r\n * @see #setAutoTickIndex(int)\r\n */\r\n protected int getAutoTickIndex() {\r\n return this.autoTickIndex;\r\n }\r\n\r\n /**\r\n * Sets the auto tick index.\r\n *\r\n * @param index the new value.\r\n *\r\n * @see #getAutoTickIndex()\r\n */\r\n protected void setAutoTickIndex(int index) {\r\n this.autoTickIndex = index;\r\n }\r\n\r\n /**\r\n * Tests the axis for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof ValueAxis)) {\r\n return false;\r\n }\r\n ValueAxis that = (ValueAxis) obj;\r\n if (this.positiveArrowVisible != that.positiveArrowVisible) {\r\n return false;\r\n }\r\n if (this.negativeArrowVisible != that.negativeArrowVisible) {\r\n return false;\r\n }\r\n if (this.inverted != that.inverted) {\r\n return false;\r\n }\r\n // if autoRange is true, then the current range is irrelevant\r\n if (!this.autoRange && !ObjectUtilities.equal(this.range, that.range)) {\r\n return false;\r\n }\r\n if (this.autoRange != that.autoRange) {\r\n return false;\r\n }\r\n if (this.autoRangeMinimumSize != that.autoRangeMinimumSize) {\r\n return false;\r\n }\r\n if (!this.defaultAutoRange.equals(that.defaultAutoRange)) {\r\n return false;\r\n }\r\n if (this.upperMargin != that.upperMargin) {\r\n return false;\r\n }\r\n if (this.lowerMargin != that.lowerMargin) {\r\n return false;\r\n }\r\n if (this.fixedAutoRange != that.fixedAutoRange) {\r\n return false;\r\n }\r\n if (this.autoTickUnitSelection != that.autoTickUnitSelection) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.standardTickUnits,\r\n that.standardTickUnits)) {\r\n return false;\r\n }\r\n if (this.verticalTickLabels != that.verticalTickLabels) {\r\n return false;\r\n }\r\n if (this.minorTickCount != that.minorTickCount) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a clone of the object.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if some component of the axis does\r\n * not support cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n ValueAxis clone = (ValueAxis) super.clone();\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeShape(this.upArrow, stream);\r\n SerialUtilities.writeShape(this.downArrow, stream);\r\n SerialUtilities.writeShape(this.leftArrow, stream);\r\n SerialUtilities.writeShape(this.rightArrow, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n\r\n stream.defaultReadObject();\r\n this.upArrow = SerialUtilities.readShape(stream);\r\n this.downArrow = SerialUtilities.readShape(stream);\r\n this.leftArrow = SerialUtilities.readShape(stream);\r\n this.rightArrow = SerialUtilities.readShape(stream);\r\n }\r\n\r\n}\r" }, { "identifier": "ChartChangeEvent", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/event/ChartChangeEvent.java", "snippet": "public class ChartChangeEvent extends EventObject {\r\n\r\n /** The type of event. */\r\n private ChartChangeEventType type;\r\n\r\n /** The chart that generated the event. */\r\n private JFreeChart chart;\r\n\r\n /**\r\n * Creates a new chart change event.\r\n *\r\n * @param source the source of the event (could be the chart, a title,\r\n * an axis etc.)\r\n */\r\n public ChartChangeEvent(Object source) {\r\n this(source, null, ChartChangeEventType.GENERAL);\r\n }\r\n\r\n /**\r\n * Creates a new chart change event.\r\n *\r\n * @param source the source of the event (could be the chart, a title, an\r\n * axis etc.)\r\n * @param chart the chart that generated the event.\r\n */\r\n public ChartChangeEvent(Object source, JFreeChart chart) {\r\n this(source, chart, ChartChangeEventType.GENERAL);\r\n }\r\n\r\n /**\r\n * Creates a new chart change event.\r\n *\r\n * @param source the source of the event (could be the chart, a title, an\r\n axis etc.)\r\n * @param chart the chart that generated the event.\r\n * @param type the type of event.\r\n */\r\n public ChartChangeEvent(Object source, JFreeChart chart,\r\n ChartChangeEventType type) {\r\n super(source);\r\n this.chart = chart;\r\n this.type = type;\r\n }\r\n\r\n /**\r\n * Returns the chart that generated the change event.\r\n *\r\n * @return The chart that generated the change event.\r\n */\r\n public JFreeChart getChart() {\r\n return this.chart;\r\n }\r\n\r\n /**\r\n * Sets the chart that generated the change event.\r\n *\r\n * @param chart the chart that generated the event.\r\n */\r\n public void setChart(JFreeChart chart) {\r\n this.chart = chart;\r\n }\r\n\r\n /**\r\n * Returns the event type.\r\n *\r\n * @return The event type.\r\n */\r\n public ChartChangeEventType getType() {\r\n return this.type;\r\n }\r\n\r\n /**\r\n * Sets the event type.\r\n *\r\n * @param type the event type.\r\n */\r\n public void setType(ChartChangeEventType type) {\r\n this.type = type;\r\n }\r\n\r\n}\r" }, { "identifier": "ChartChangeListener", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/event/ChartChangeListener.java", "snippet": "public interface ChartChangeListener extends EventListener {\r\n\r\n /**\r\n * Receives notification of a chart change event.\r\n *\r\n * @param event the event.\r\n */\r\n public void chartChanged(ChartChangeEvent event);\r\n\r\n}\r" }, { "identifier": "CategoryToolTipGenerator", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/labels/CategoryToolTipGenerator.java", "snippet": "public interface CategoryToolTipGenerator {\r\n\r\n /**\r\n * Generates the tool tip text for an item in a dataset. Note: in the\r\n * current dataset implementation, each row is a series, and each column\r\n * contains values for a particular category.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param row the row index (zero-based).\r\n * @param column the column index (zero-based).\r\n *\r\n * @return The tooltip text (possibly <code>null</code>).\r\n */\r\n public String generateToolTip(CategoryDataset dataset, int row, int column);\r\n\r\n}\r" }, { "identifier": "StandardCategoryToolTipGenerator", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/labels/StandardCategoryToolTipGenerator.java", "snippet": "public class StandardCategoryToolTipGenerator\r\n extends AbstractCategoryItemLabelGenerator\r\n implements CategoryToolTipGenerator, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -6768806592218710764L;\r\n\r\n /** The default format string. */\r\n public static final String DEFAULT_TOOL_TIP_FORMAT_STRING\r\n = \"({0}, {1}) = {2}\";\r\n\r\n /**\r\n * Creates a new generator with a default number formatter.\r\n */\r\n public StandardCategoryToolTipGenerator() {\r\n super(DEFAULT_TOOL_TIP_FORMAT_STRING, NumberFormat.getInstance());\r\n }\r\n\r\n /**\r\n * Creates a new generator with the specified number formatter.\r\n *\r\n * @param labelFormat the label format string (<code>null</code> not\r\n * permitted).\r\n * @param formatter the number formatter (<code>null</code> not permitted).\r\n */\r\n public StandardCategoryToolTipGenerator(String labelFormat,\r\n NumberFormat formatter) {\r\n super(labelFormat, formatter);\r\n }\r\n\r\n /**\r\n * Creates a new generator with the specified date formatter.\r\n *\r\n * @param labelFormat the label format string (<code>null</code> not\r\n * permitted).\r\n * @param formatter the date formatter (<code>null</code> not permitted).\r\n */\r\n public StandardCategoryToolTipGenerator(String labelFormat,\r\n DateFormat formatter) {\r\n super(labelFormat, formatter);\r\n }\r\n\r\n /**\r\n * Generates the tool tip text for an item in a dataset. Note: in the\r\n * current dataset implementation, each row is a series, and each column\r\n * contains values for a particular category.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param row the row index (zero-based).\r\n * @param column the column index (zero-based).\r\n *\r\n * @return The tooltip text (possibly <code>null</code>).\r\n */\r\n @Override\r\n public String generateToolTip(CategoryDataset dataset,\r\n int row, int column) {\r\n return generateLabelString(dataset, row, column);\r\n }\r\n\r\n /**\r\n * Tests this generator for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof StandardCategoryToolTipGenerator)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n}\r" }, { "identifier": "CategoryPlot", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/CategoryPlot.java", "snippet": "public class CategoryPlot extends Plot implements ValueAxisPlot, Pannable,\r\n Zoomable, AnnotationChangeListener, RendererChangeListener,\r\n Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -3537691700434728188L;\r\n\r\n /**\r\n * The default visibility of the grid lines plotted against the domain\r\n * axis.\r\n */\r\n public static final boolean DEFAULT_DOMAIN_GRIDLINES_VISIBLE = false;\r\n\r\n /**\r\n * The default visibility of the grid lines plotted against the range\r\n * axis.\r\n */\r\n public static final boolean DEFAULT_RANGE_GRIDLINES_VISIBLE = true;\r\n\r\n /** The default grid line stroke. */\r\n public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f,\r\n BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f, new float[]\r\n {2.0f, 2.0f}, 0.0f);\r\n\r\n /** The default grid line paint. */\r\n public static final Paint DEFAULT_GRIDLINE_PAINT = Color.lightGray;\r\n\r\n /** The default value label font. */\r\n public static final Font DEFAULT_VALUE_LABEL_FONT = new Font(\"SansSerif\",\r\n Font.PLAIN, 10);\r\n\r\n /**\r\n * The default crosshair visibility.\r\n *\r\n * @since 1.0.5\r\n */\r\n public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false;\r\n\r\n /**\r\n * The default crosshair stroke.\r\n *\r\n * @since 1.0.5\r\n */\r\n public static final Stroke DEFAULT_CROSSHAIR_STROKE\r\n = DEFAULT_GRIDLINE_STROKE;\r\n\r\n /**\r\n * The default crosshair paint.\r\n *\r\n * @since 1.0.5\r\n */\r\n public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.blue;\r\n\r\n /** The resourceBundle for the localization. */\r\n protected static ResourceBundle localizationResources\r\n = ResourceBundleWrapper.getBundle(\r\n \"org.jfree.chart.plot.LocalizationBundle\");\r\n\r\n /** The plot orientation. */\r\n private PlotOrientation orientation;\r\n\r\n /** The offset between the data area and the axes. */\r\n private RectangleInsets axisOffset;\r\n\r\n /** Storage for the domain axes. */\r\n private Map<Integer, CategoryAxis> domainAxes;\r\n\r\n /** Storage for the domain axis locations. */\r\n private Map<Integer, AxisLocation> domainAxisLocations;\r\n\r\n /**\r\n * A flag that controls whether or not the shared domain axis is drawn\r\n * (only relevant when the plot is being used as a subplot).\r\n */\r\n private boolean drawSharedDomainAxis;\r\n\r\n /** Storage for the range axes. */\r\n private Map<Integer, ValueAxis> rangeAxes;\r\n\r\n /** Storage for the range axis locations. */\r\n private Map<Integer, AxisLocation> rangeAxisLocations;\r\n\r\n /** Storage for the datasets. */\r\n private Map<Integer, CategoryDataset> datasets;\r\n\r\n /** Storage for keys that map datasets to domain axes. */\r\n private TreeMap datasetToDomainAxesMap;\r\n\r\n /** Storage for keys that map datasets to range axes. */\r\n private TreeMap datasetToRangeAxesMap;\r\n\r\n /** Storage for the renderers. */\r\n private Map<Integer, CategoryItemRenderer> renderers;\r\n\r\n /** The dataset rendering order. */\r\n private DatasetRenderingOrder renderingOrder\r\n = DatasetRenderingOrder.REVERSE;\r\n\r\n /**\r\n * Controls the order in which the columns are traversed when rendering the\r\n * data items.\r\n */\r\n private SortOrder columnRenderingOrder = SortOrder.ASCENDING;\r\n\r\n /**\r\n * Controls the order in which the rows are traversed when rendering the\r\n * data items.\r\n */\r\n private SortOrder rowRenderingOrder = SortOrder.ASCENDING;\r\n\r\n /**\r\n * A flag that controls whether the grid-lines for the domain axis are\r\n * visible.\r\n */\r\n private boolean domainGridlinesVisible;\r\n\r\n /** The position of the domain gridlines relative to the category. */\r\n private CategoryAnchor domainGridlinePosition;\r\n\r\n /** The stroke used to draw the domain grid-lines. */\r\n private transient Stroke domainGridlineStroke;\r\n\r\n /** The paint used to draw the domain grid-lines. */\r\n private transient Paint domainGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not the zero baseline against the range\r\n * axis is visible.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean rangeZeroBaselineVisible;\r\n\r\n /**\r\n * The stroke used for the zero baseline against the range axis.\r\n *\r\n * @since 1.0.13\r\n */\r\n private transient Stroke rangeZeroBaselineStroke;\r\n\r\n /**\r\n * The paint used for the zero baseline against the range axis.\r\n *\r\n * @since 1.0.13\r\n */\r\n private transient Paint rangeZeroBaselinePaint;\r\n\r\n /**\r\n * A flag that controls whether the grid-lines for the range axis are\r\n * visible.\r\n */\r\n private boolean rangeGridlinesVisible;\r\n\r\n /** The stroke used to draw the range axis grid-lines. */\r\n private transient Stroke rangeGridlineStroke;\r\n\r\n /** The paint used to draw the range axis grid-lines. */\r\n private transient Paint rangeGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not gridlines are shown for the minor\r\n * tick values on the primary range axis.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean rangeMinorGridlinesVisible;\r\n\r\n /**\r\n * The stroke used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.13\r\n */\r\n private transient Stroke rangeMinorGridlineStroke;\r\n\r\n /**\r\n * The paint used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.13\r\n */\r\n private transient Paint rangeMinorGridlinePaint;\r\n\r\n /** The anchor value. */\r\n private double anchorValue;\r\n\r\n /**\r\n * The index for the dataset that the crosshairs are linked to (this\r\n * determines which axes the crosshairs are plotted against).\r\n *\r\n * @since 1.0.11\r\n */\r\n private int crosshairDatasetIndex;\r\n\r\n /**\r\n * A flag that controls the visibility of the domain crosshair.\r\n *\r\n * @since 1.0.11\r\n */\r\n private boolean domainCrosshairVisible;\r\n\r\n /**\r\n * The row key for the crosshair point.\r\n *\r\n * @since 1.0.11\r\n */\r\n private Comparable domainCrosshairRowKey;\r\n\r\n /**\r\n * The column key for the crosshair point.\r\n *\r\n * @since 1.0.11\r\n */\r\n private Comparable domainCrosshairColumnKey;\r\n\r\n /**\r\n * The stroke used to draw the domain crosshair if it is visible.\r\n *\r\n * @since 1.0.11\r\n */\r\n private transient Stroke domainCrosshairStroke;\r\n\r\n /**\r\n * The paint used to draw the domain crosshair if it is visible.\r\n *\r\n * @since 1.0.11\r\n */\r\n private transient Paint domainCrosshairPaint;\r\n\r\n /** A flag that controls whether or not a range crosshair is drawn. */\r\n private boolean rangeCrosshairVisible;\r\n\r\n /** The range crosshair value. */\r\n private double rangeCrosshairValue;\r\n\r\n /** The pen/brush used to draw the crosshair (if any). */\r\n private transient Stroke rangeCrosshairStroke;\r\n\r\n /** The color used to draw the crosshair (if any). */\r\n private transient Paint rangeCrosshairPaint;\r\n\r\n /**\r\n * A flag that controls whether or not the crosshair locks onto actual\r\n * data points.\r\n */\r\n private boolean rangeCrosshairLockedOnData = true;\r\n\r\n /** A map containing lists of markers for the domain axes. */\r\n private Map foregroundDomainMarkers;\r\n\r\n /** A map containing lists of markers for the domain axes. */\r\n private Map backgroundDomainMarkers;\r\n\r\n /** A map containing lists of markers for the range axes. */\r\n private Map foregroundRangeMarkers;\r\n\r\n /** A map containing lists of markers for the range axes. */\r\n private Map backgroundRangeMarkers;\r\n\r\n /**\r\n * A (possibly empty) list of annotations for the plot. The list should\r\n * be initialised in the constructor and never allowed to be\r\n * <code>null</code>.\r\n */\r\n private List annotations;\r\n\r\n /**\r\n * The weight for the plot (only relevant when the plot is used as a subplot\r\n * within a combined plot).\r\n */\r\n private int weight;\r\n\r\n /** The fixed space for the domain axis. */\r\n private AxisSpace fixedDomainAxisSpace;\r\n\r\n /** The fixed space for the range axis. */\r\n private AxisSpace fixedRangeAxisSpace;\r\n\r\n /**\r\n * An optional collection of legend items that can be returned by the\r\n * getLegendItems() method.\r\n */\r\n private LegendItemCollection fixedLegendItems;\r\n\r\n /**\r\n * A flag that controls whether or not panning is enabled for the\r\n * range axis/axes.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean rangePannable;\r\n\r\n /**\r\n * The shadow generator for the plot (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n private ShadowGenerator shadowGenerator;\r\n\r\n /**\r\n * Default constructor.\r\n */\r\n public CategoryPlot() {\r\n this(null, null, null, null);\r\n }\r\n\r\n /**\r\n * Creates a new plot.\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n * @param domainAxis the domain axis (<code>null</code> permitted).\r\n * @param rangeAxis the range axis (<code>null</code> permitted).\r\n * @param renderer the item renderer (<code>null</code> permitted).\r\n *\r\n */\r\n public CategoryPlot(CategoryDataset dataset, CategoryAxis domainAxis,\r\n ValueAxis rangeAxis, CategoryItemRenderer renderer) {\r\n\r\n super();\r\n\r\n this.orientation = PlotOrientation.VERTICAL;\r\n\r\n // allocate storage for dataset, axes and renderers\r\n this.domainAxes = new HashMap<Integer, CategoryAxis>();\r\n this.domainAxisLocations = new HashMap<Integer, AxisLocation>();\r\n this.rangeAxes = new HashMap<Integer, ValueAxis>();\r\n this.rangeAxisLocations = new HashMap<Integer, AxisLocation>();\r\n\r\n this.datasetToDomainAxesMap = new TreeMap();\r\n this.datasetToRangeAxesMap = new TreeMap();\r\n\r\n this.renderers = new HashMap<Integer, CategoryItemRenderer>();\r\n\r\n this.datasets = new HashMap<Integer, CategoryDataset>();\r\n this.datasets.put(0, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n\r\n this.axisOffset = RectangleInsets.ZERO_INSETS;\r\n this.domainAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT);\r\n this.rangeAxisLocations.put(0, AxisLocation.TOP_OR_LEFT);\r\n\r\n this.renderers.put(0, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n\r\n this.domainAxes.put(0, domainAxis);\r\n mapDatasetToDomainAxis(0, 0);\r\n if (domainAxis != null) {\r\n domainAxis.setPlot(this);\r\n domainAxis.addChangeListener(this);\r\n }\r\n this.drawSharedDomainAxis = false;\r\n\r\n this.rangeAxes.put(0, rangeAxis);\r\n mapDatasetToRangeAxis(0, 0);\r\n if (rangeAxis != null) {\r\n rangeAxis.setPlot(this);\r\n rangeAxis.addChangeListener(this);\r\n }\r\n\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n\r\n this.domainGridlinesVisible = DEFAULT_DOMAIN_GRIDLINES_VISIBLE;\r\n this.domainGridlinePosition = CategoryAnchor.MIDDLE;\r\n this.domainGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.domainGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.rangeZeroBaselineVisible = false;\r\n this.rangeZeroBaselinePaint = Color.black;\r\n this.rangeZeroBaselineStroke = new BasicStroke(0.5f);\r\n\r\n this.rangeGridlinesVisible = DEFAULT_RANGE_GRIDLINES_VISIBLE;\r\n this.rangeGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.rangeMinorGridlinesVisible = false;\r\n this.rangeMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeMinorGridlinePaint = Color.white;\r\n\r\n this.foregroundDomainMarkers = new HashMap();\r\n this.backgroundDomainMarkers = new HashMap();\r\n this.foregroundRangeMarkers = new HashMap();\r\n this.backgroundRangeMarkers = new HashMap();\r\n\r\n this.anchorValue = 0.0;\r\n\r\n this.domainCrosshairVisible = false;\r\n this.domainCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.domainCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n\r\n this.rangeCrosshairVisible = DEFAULT_CROSSHAIR_VISIBLE;\r\n this.rangeCrosshairValue = 0.0;\r\n this.rangeCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.rangeCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n\r\n this.annotations = new java.util.ArrayList();\r\n\r\n this.rangePannable = false;\r\n this.shadowGenerator = null;\r\n }\r\n\r\n /**\r\n * Returns a string describing the type of plot.\r\n *\r\n * @return The type.\r\n */\r\n @Override\r\n public String getPlotType() {\r\n return localizationResources.getString(\"Category_Plot\");\r\n }\r\n\r\n /**\r\n * Returns the orientation of the plot.\r\n *\r\n * @return The orientation of the plot (never <code>null</code>).\r\n *\r\n * @see #setOrientation(PlotOrientation)\r\n */\r\n @Override\r\n public PlotOrientation getOrientation() {\r\n return this.orientation;\r\n }\r\n\r\n /**\r\n * Sets the orientation for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param orientation the orientation (<code>null</code> not permitted).\r\n *\r\n * @see #getOrientation()\r\n */\r\n public void setOrientation(PlotOrientation orientation) {\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n this.orientation = orientation;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the axis offset.\r\n *\r\n * @return The axis offset (never <code>null</code>).\r\n *\r\n * @see #setAxisOffset(RectangleInsets)\r\n */\r\n public RectangleInsets getAxisOffset() {\r\n return this.axisOffset;\r\n }\r\n\r\n /**\r\n * Sets the axis offsets (gap between the data area and the axes) and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param offset the offset (<code>null</code> not permitted).\r\n *\r\n * @see #getAxisOffset()\r\n */\r\n public void setAxisOffset(RectangleInsets offset) {\r\n ParamChecks.nullNotPermitted(offset, \"offset\");\r\n this.axisOffset = offset;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the domain axis for the plot. If the domain axis for this plot\r\n * is <code>null</code>, then the method will return the parent plot's\r\n * domain axis (if there is a parent plot).\r\n *\r\n * @return The domain axis (<code>null</code> permitted).\r\n *\r\n * @see #setDomainAxis(CategoryAxis)\r\n */\r\n public CategoryAxis getDomainAxis() {\r\n return getDomainAxis(0);\r\n }\r\n\r\n /**\r\n * Returns a domain axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The axis (<code>null</code> possible).\r\n *\r\n * @see #setDomainAxis(int, CategoryAxis)\r\n */\r\n public CategoryAxis getDomainAxis(int index) {\r\n CategoryAxis result = (CategoryAxis) this.domainAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof CategoryPlot) {\r\n CategoryPlot cp = (CategoryPlot) parent;\r\n result = cp.getDomainAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the domain axis for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis()\r\n */\r\n public void setDomainAxis(CategoryAxis axis) {\r\n setDomainAxis(0, axis);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis(int)\r\n */\r\n public void setDomainAxis(int index, CategoryAxis axis) {\r\n setDomainAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n */\r\n public void setDomainAxis(int index, CategoryAxis axis, boolean notify) {\r\n CategoryAxis existing = (CategoryAxis) this.domainAxes.get(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.domainAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the domain axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setRangeAxes(ValueAxis[])\r\n */\r\n public void setDomainAxes(CategoryAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setDomainAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified axis, or <code>-1</code> if the axis\r\n * is not assigned to the plot.\r\n *\r\n * @param axis the axis (<code>null</code> not permitted).\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getDomainAxis(int)\r\n * @see #getRangeAxisIndex(ValueAxis)\r\n *\r\n * @since 1.0.3\r\n */\r\n public int getDomainAxisIndex(CategoryAxis axis) {\r\n ParamChecks.nullNotPermitted(axis, \"axis\");\r\n for (Entry<Integer, CategoryAxis> entry : this.domainAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the domain axis location for the primary domain axis.\r\n *\r\n * @return The location (never <code>null</code>).\r\n *\r\n * @see #getRangeAxisLocation()\r\n */\r\n public AxisLocation getDomainAxisLocation() {\r\n return getDomainAxisLocation(0);\r\n }\r\n\r\n /**\r\n * Returns the location for a domain axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The location.\r\n *\r\n * @see #setDomainAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getDomainAxisLocation(int index) {\r\n AxisLocation result = this.domainAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getDomainAxisLocation(0));\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location of the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param location the axis location (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainAxisLocation()\r\n * @see #setDomainAxisLocation(int, AxisLocation)\r\n */\r\n public void setDomainAxisLocation(AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the axis location (<code>null</code> not permitted).\r\n * @param notify a flag that controls whether listeners are notified.\r\n */\r\n public void setDomainAxisLocation(AxisLocation location, boolean notify) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Sets the location for a domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location.\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n * @see #setRangeAxisLocation(int, AxisLocation)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location for a domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location.\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n * @see #setRangeAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.domainAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the domain axis edge. This is derived from the axis location\r\n * and the plot orientation.\r\n *\r\n * @return The edge (never <code>null</code>).\r\n */\r\n public RectangleEdge getDomainAxisEdge() {\r\n return getDomainAxisEdge(0);\r\n }\r\n\r\n /**\r\n * Returns the edge for a domain axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge (never <code>null</code>).\r\n */\r\n public RectangleEdge getDomainAxisEdge(int index) {\r\n RectangleEdge result;\r\n AxisLocation location = getDomainAxisLocation(index);\r\n if (location != null) {\r\n result = Plot.resolveDomainAxisLocation(location, this.orientation);\r\n } else {\r\n result = RectangleEdge.opposite(getDomainAxisEdge(0));\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the number of domain axes.\r\n *\r\n * @return The axis count.\r\n */\r\n public int getDomainAxisCount() {\r\n return this.domainAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the domain axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n */\r\n public void clearDomainAxes() {\r\n for (CategoryAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n xAxis.removeChangeListener(this);\r\n }\r\n }\r\n this.domainAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the domain axes.\r\n */\r\n public void configureDomainAxes() {\r\n for (CategoryAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n xAxis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range axis for the plot. If the range axis for this plot is\r\n * null, then the method will return the parent plot's range axis (if there\r\n * is a parent plot).\r\n *\r\n * @return The range axis (possibly <code>null</code>).\r\n */\r\n public ValueAxis getRangeAxis() {\r\n return getRangeAxis(0);\r\n }\r\n\r\n /**\r\n * Returns a range axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The axis (<code>null</code> possible).\r\n */\r\n public ValueAxis getRangeAxis(int index) {\r\n ValueAxis result = this.rangeAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof CategoryPlot) {\r\n CategoryPlot cp = (CategoryPlot) parent;\r\n result = cp.getRangeAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the range axis for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param axis the axis (<code>null</code> permitted).\r\n */\r\n public void setRangeAxis(ValueAxis axis) {\r\n setRangeAxis(0, axis);\r\n }\r\n\r\n /**\r\n * Sets a range axis and sends a {@link PlotChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis.\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis) {\r\n setRangeAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a range axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis.\r\n * @param notify notify listeners?\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis, boolean notify) {\r\n ValueAxis existing = this.rangeAxes.get(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.rangeAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the range axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setDomainAxes(CategoryAxis[])\r\n */\r\n public void setRangeAxes(ValueAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setRangeAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified axis, or <code>-1</code> if the axis\r\n * is not assigned to the plot.\r\n *\r\n * @param axis the axis (<code>null</code> not permitted).\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getRangeAxis(int)\r\n * @see #getDomainAxisIndex(CategoryAxis)\r\n *\r\n * @since 1.0.7\r\n */\r\n public int getRangeAxisIndex(ValueAxis axis) {\r\n ParamChecks.nullNotPermitted(axis, \"axis\");\r\n int result = findRangeAxisIndex(axis);\r\n if (result < 0) { // try the parent plot\r\n Plot parent = getParent();\r\n if (parent instanceof CategoryPlot) {\r\n CategoryPlot p = (CategoryPlot) parent;\r\n result = p.getRangeAxisIndex(axis);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n private int findRangeAxisIndex(ValueAxis axis) {\r\n for (Entry<Integer, ValueAxis> entry : this.rangeAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n \r\n /**\r\n * Returns the range axis location.\r\n *\r\n * @return The location (never <code>null</code>).\r\n */\r\n public AxisLocation getRangeAxisLocation() {\r\n return getRangeAxisLocation(0);\r\n }\r\n\r\n /**\r\n * Returns the location for a range axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The location.\r\n *\r\n * @see #setRangeAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getRangeAxisLocation(int index) {\r\n AxisLocation result = this.rangeAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getRangeAxisLocation(0));\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location of the range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n *\r\n * @see #setRangeAxisLocation(AxisLocation, boolean)\r\n * @see #setDomainAxisLocation(AxisLocation)\r\n */\r\n public void setRangeAxisLocation(AxisLocation location) {\r\n // defer argument checking...\r\n setRangeAxisLocation(location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the range axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #setDomainAxisLocation(AxisLocation, boolean)\r\n */\r\n public void setRangeAxisLocation(AxisLocation location, boolean notify) {\r\n setRangeAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Sets the location for a range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location.\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #setRangeAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location) {\r\n setRangeAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location for a range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #setDomainAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.rangeAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the edge where the primary range axis is located.\r\n *\r\n * @return The edge (never <code>null</code>).\r\n */\r\n public RectangleEdge getRangeAxisEdge() {\r\n return getRangeAxisEdge(0);\r\n }\r\n\r\n /**\r\n * Returns the edge for a range axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge.\r\n */\r\n public RectangleEdge getRangeAxisEdge(int index) {\r\n AxisLocation location = getRangeAxisLocation(index);\r\n return Plot.resolveRangeAxisLocation(location, this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the number of range axes.\r\n *\r\n * @return The axis count.\r\n */\r\n public int getRangeAxisCount() {\r\n return this.rangeAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the range axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n */\r\n public void clearRangeAxes() {\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.removeChangeListener(this);\r\n }\r\n }\r\n this.rangeAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the range axes.\r\n */\r\n public void configureRangeAxes() {\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the primary dataset for the plot.\r\n *\r\n * @return The primary dataset (possibly <code>null</code>).\r\n *\r\n * @see #setDataset(CategoryDataset)\r\n */\r\n public CategoryDataset getDataset() {\r\n return getDataset(0);\r\n }\r\n\r\n /**\r\n * Returns the dataset with the given index, or {@code null} if there is\r\n * no dataset.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The dataset (possibly {@code null}).\r\n *\r\n * @see #setDataset(int, CategoryDataset)\r\n */\r\n public CategoryDataset getDataset(int index) {\r\n return this.datasets.get(index);\r\n }\r\n\r\n /**\r\n * Sets the dataset for the plot, replacing the existing dataset, if there\r\n * is one. This method also calls the\r\n * {@link #datasetChanged(DatasetChangeEvent)} method, which adjusts the\r\n * axis ranges if necessary and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n *\r\n * @see #getDataset()\r\n */\r\n public void setDataset(CategoryDataset dataset) {\r\n setDataset(0, dataset);\r\n }\r\n\r\n /**\r\n * Sets a dataset for the plot and sends a change notification to all\r\n * registered listeners.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n * @param dataset the dataset ({@code null} permitted).\r\n *\r\n * @see #getDataset(int)\r\n */\r\n public void setDataset(int index, CategoryDataset dataset) {\r\n CategoryDataset existing = (CategoryDataset) this.datasets.get(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.datasets.put(index, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n // send a dataset change event to self...\r\n DatasetChangeEvent event = new DatasetChangeEvent(this, dataset);\r\n datasetChanged(event);\r\n }\r\n\r\n /**\r\n * Returns the number of datasets.\r\n *\r\n * @return The number of datasets.\r\n *\r\n * @since 1.0.2\r\n */\r\n public int getDatasetCount() {\r\n return this.datasets.size();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified dataset, or <code>-1</code> if the\r\n * dataset does not belong to the plot.\r\n *\r\n * @param dataset the dataset ({@code null} not permitted).\r\n *\r\n * @return The index.\r\n *\r\n * @since 1.0.11\r\n */\r\n public int indexOf(CategoryDataset dataset) {\r\n for (Entry<Integer, CategoryDataset> entry: this.datasets.entrySet()) {\r\n if (entry.getValue() == dataset) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular domain axis.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index (zero-based).\r\n *\r\n * @see #getDomainAxisForDataset(int)\r\n */\r\n public void mapDatasetToDomainAxis(int index, int axisIndex) {\r\n List<Integer> axisIndices = new java.util.ArrayList<Integer>(1);\r\n axisIndices.add(axisIndex);\r\n mapDatasetToDomainAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToDomainAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n this.datasetToDomainAxesMap.put(index, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * This method is used to perform argument checking on the list of\r\n * axis indices passed to mapDatasetToDomainAxes() and\r\n * mapDatasetToRangeAxes().\r\n *\r\n * @param indices the list of indices (<code>null</code> permitted).\r\n */\r\n private void checkAxisIndices(List indices) {\r\n // axisIndices can be:\r\n // 1. null;\r\n // 2. non-empty, containing only Integer objects that are unique.\r\n if (indices == null) {\r\n return; // OK\r\n }\r\n int count = indices.size();\r\n if (count == 0) {\r\n throw new IllegalArgumentException(\"Empty list not permitted.\");\r\n }\r\n HashSet set = new HashSet();\r\n for (int i = 0; i < count; i++) {\r\n Object item = indices.get(i);\r\n if (!(item instanceof Integer)) {\r\n throw new IllegalArgumentException(\r\n \"Indices must be Integer instances.\");\r\n }\r\n if (set.contains(item)) {\r\n throw new IllegalArgumentException(\"Indices must be unique.\");\r\n }\r\n set.add(item);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the domain axis for a dataset. You can change the axis for a\r\n * dataset using the {@link #mapDatasetToDomainAxis(int, int)} method.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The domain axis.\r\n *\r\n * @see #mapDatasetToDomainAxis(int, int)\r\n */\r\n public CategoryAxis getDomainAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n CategoryAxis axis;\r\n List axisIndices = (List) this.datasetToDomainAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n axis = getDomainAxis(axisIndex.intValue());\r\n } else {\r\n axis = getDomainAxis(0);\r\n }\r\n return axis;\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular range axis.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index (zero-based).\r\n *\r\n * @see #getRangeAxisForDataset(int)\r\n */\r\n public void mapDatasetToRangeAxis(int index, int axisIndex) {\r\n List axisIndices = new java.util.ArrayList(1);\r\n axisIndices.add(new Integer(axisIndex));\r\n mapDatasetToRangeAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToRangeAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n this.datasetToRangeAxesMap.put(index, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * Returns the range axis for a dataset. You can change the axis for a\r\n * dataset using the {@link #mapDatasetToRangeAxis(int, int)} method.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The range axis.\r\n *\r\n * @see #mapDatasetToRangeAxis(int, int)\r\n */\r\n public ValueAxis getRangeAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n ValueAxis axis;\r\n List axisIndices = (List) this.datasetToRangeAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n axis = getRangeAxis(axisIndex.intValue());\r\n } else {\r\n axis = getRangeAxis(0);\r\n }\r\n return axis;\r\n }\r\n\r\n /**\r\n * Returns the number of renderer slots for this plot.\r\n *\r\n * @return The number of renderer slots.\r\n *\r\n * @since 1.0.11\r\n */\r\n public int getRendererCount() {\r\n return this.renderers.size();\r\n }\r\n\r\n /**\r\n * Returns a reference to the renderer for the plot.\r\n *\r\n * @return The renderer.\r\n *\r\n * @see #setRenderer(CategoryItemRenderer)\r\n */\r\n public CategoryItemRenderer getRenderer() {\r\n return getRenderer(0);\r\n }\r\n\r\n /**\r\n * Returns the renderer at the given index.\r\n *\r\n * @param index the renderer index.\r\n *\r\n * @return The renderer (possibly {@code null}).\r\n *\r\n * @see #setRenderer(int, CategoryItemRenderer)\r\n */\r\n public CategoryItemRenderer getRenderer(int index) {\r\n CategoryItemRenderer renderer = this.renderers.get(index);\r\n if (renderer == null) {\r\n return this.renderers.get(0);\r\n }\r\n return renderer;\r\n }\r\n\r\n /**\r\n * Sets the renderer at index 0 (sometimes referred to as the \"primary\"\r\n * renderer) and sends a change event to all registered listeners.\r\n *\r\n * @param renderer the renderer (<code>null</code> permitted.\r\n *\r\n * @see #getRenderer()\r\n */\r\n public void setRenderer(CategoryItemRenderer renderer) {\r\n setRenderer(0, renderer, true);\r\n }\r\n\r\n /**\r\n * Sets the renderer at index 0 (sometimes referred to as the \"primary\"\r\n * renderer) and, if requested, sends a change event to all registered \r\n * listeners.\r\n * <p>\r\n * You can set the renderer to <code>null</code>, but this is not\r\n * recommended because:\r\n * <ul>\r\n * <li>no data will be displayed;</li>\r\n * <li>the plot background will not be painted;</li>\r\n * </ul>\r\n *\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRenderer()\r\n */\r\n public void setRenderer(CategoryItemRenderer renderer, boolean notify) {\r\n setRenderer(0, renderer, notify);\r\n }\r\n\r\n /**\r\n * Sets the renderer to use for the dataset with the specified index and\r\n * sends a change event to all registered listeners. Note that each\r\n * dataset should have its own renderer, you should not use one renderer\r\n * for multiple datasets.\r\n *\r\n * @param index the index.\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n *\r\n * @see #getRenderer(int)\r\n * @see #setRenderer(int, CategoryItemRenderer, boolean)\r\n */\r\n public void setRenderer(int index, CategoryItemRenderer renderer) {\r\n setRenderer(index, renderer, true);\r\n }\r\n\r\n /**\r\n * Sets the renderer to use for the dataset with the specified index and,\r\n * if requested, sends a change event to all registered listeners. Note \r\n * that each dataset should have its own renderer, you should not use one \r\n * renderer for multiple datasets.\r\n *\r\n * @param index the index.\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRenderer(int)\r\n */\r\n public void setRenderer(int index, CategoryItemRenderer renderer,\r\n boolean notify) {\r\n CategoryItemRenderer existing = this.renderers.get(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.renderers.put(index, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the renderers for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param renderers the renderers.\r\n */\r\n public void setRenderers(CategoryItemRenderer[] renderers) {\r\n for (int i = 0; i < renderers.length; i++) {\r\n setRenderer(i, renderers[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the renderer for the specified dataset. If the dataset doesn't\r\n * belong to the plot, this method will return <code>null</code>.\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n *\r\n * @return The renderer (possibly <code>null</code>).\r\n */\r\n public CategoryItemRenderer getRendererForDataset(CategoryDataset dataset) {\r\n int datasetIndex = indexOf(dataset);\r\n if (datasetIndex < 0) {\r\n return null;\r\n } \r\n CategoryItemRenderer renderer = this.renderers.get(datasetIndex);\r\n if (renderer == null) {\r\n return getRenderer();\r\n }\r\n return renderer;\r\n }\r\n\r\n /**\r\n * Returns the index of the specified renderer, or <code>-1</code> if the\r\n * renderer is not assigned to this plot.\r\n *\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n *\r\n * @return The renderer index.\r\n */\r\n public int getIndexOf(CategoryItemRenderer renderer) {\r\n for (Entry<Integer, CategoryItemRenderer> entry \r\n : this.renderers.entrySet()) {\r\n if (entry.getValue() == renderer) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the dataset rendering order.\r\n *\r\n * @return The order (never <code>null</code>).\r\n *\r\n * @see #setDatasetRenderingOrder(DatasetRenderingOrder)\r\n */\r\n public DatasetRenderingOrder getDatasetRenderingOrder() {\r\n return this.renderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the rendering order and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. By default, the plot renders the primary dataset\r\n * last (so that the primary dataset overlays the secondary datasets). You\r\n * can reverse this if you want to.\r\n *\r\n * @param order the rendering order (<code>null</code> not permitted).\r\n *\r\n * @see #getDatasetRenderingOrder()\r\n */\r\n public void setDatasetRenderingOrder(DatasetRenderingOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.renderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the order in which the columns are rendered. The default value\r\n * is <code>SortOrder.ASCENDING</code>.\r\n *\r\n * @return The column rendering order (never <code>null</code>).\r\n *\r\n * @see #setColumnRenderingOrder(SortOrder)\r\n */\r\n public SortOrder getColumnRenderingOrder() {\r\n return this.columnRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the column order in which the items in each dataset should be\r\n * rendered and sends a {@link PlotChangeEvent} to all registered\r\n * listeners. Note that this affects the order in which items are drawn,\r\n * NOT their position in the chart.\r\n *\r\n * @param order the order (<code>null</code> not permitted).\r\n *\r\n * @see #getColumnRenderingOrder()\r\n * @see #setRowRenderingOrder(SortOrder)\r\n */\r\n public void setColumnRenderingOrder(SortOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.columnRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the order in which the rows should be rendered. The default\r\n * value is <code>SortOrder.ASCENDING</code>.\r\n *\r\n * @return The order (never <code>null</code>).\r\n *\r\n * @see #setRowRenderingOrder(SortOrder)\r\n */\r\n public SortOrder getRowRenderingOrder() {\r\n return this.rowRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the row order in which the items in each dataset should be\r\n * rendered and sends a {@link PlotChangeEvent} to all registered\r\n * listeners. Note that this affects the order in which items are drawn,\r\n * NOT their position in the chart.\r\n *\r\n * @param order the order (<code>null</code> not permitted).\r\n *\r\n * @see #getRowRenderingOrder()\r\n * @see #setColumnRenderingOrder(SortOrder)\r\n */\r\n public void setRowRenderingOrder(SortOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.rowRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether the domain grid-lines are visible.\r\n *\r\n * @return The <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setDomainGridlinesVisible(boolean)\r\n */\r\n public boolean isDomainGridlinesVisible() {\r\n return this.domainGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not grid-lines are drawn against\r\n * the domain axis.\r\n * <p>\r\n * If the flag value changes, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isDomainGridlinesVisible()\r\n */\r\n public void setDomainGridlinesVisible(boolean visible) {\r\n if (this.domainGridlinesVisible != visible) {\r\n this.domainGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the position used for the domain gridlines.\r\n *\r\n * @return The gridline position (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlinePosition(CategoryAnchor)\r\n */\r\n public CategoryAnchor getDomainGridlinePosition() {\r\n return this.domainGridlinePosition;\r\n }\r\n\r\n /**\r\n * Sets the position used for the domain gridlines and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param position the position (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainGridlinePosition()\r\n */\r\n public void setDomainGridlinePosition(CategoryAnchor position) {\r\n ParamChecks.nullNotPermitted(position, \"position\");\r\n this.domainGridlinePosition = position;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw grid-lines against the domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlineStroke(Stroke)\r\n */\r\n public Stroke getDomainGridlineStroke() {\r\n return this.domainGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw grid-lines against the domain axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainGridlineStroke()\r\n */\r\n public void setDomainGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw grid-lines against the domain axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlinePaint(Paint)\r\n */\r\n public Paint getDomainGridlinePaint() {\r\n return this.domainGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the grid-lines (if any) against the domain\r\n * axis and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainGridlinePaint()\r\n */\r\n public void setDomainGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a zero baseline is\r\n * displayed for the range axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n *\r\n * @since 1.0.13\r\n */\r\n public boolean isRangeZeroBaselineVisible() {\r\n return this.rangeZeroBaselineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the zero baseline is\r\n * displayed for the range axis, and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isRangeZeroBaselineVisible()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangeZeroBaselineVisible(boolean visible) {\r\n this.rangeZeroBaselineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used for the zero baseline against the range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselineStroke(Stroke)\r\n *\r\n * @since 1.0.13\r\n */\r\n public Stroke getRangeZeroBaselineStroke() {\r\n return this.rangeZeroBaselineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the zero baseline for the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselineStroke()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangeZeroBaselineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeZeroBaselineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the zero baseline (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselinePaint(Paint)\r\n *\r\n * @since 1.0.13\r\n */\r\n public Paint getRangeZeroBaselinePaint() {\r\n return this.rangeZeroBaselinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the zero baseline plotted against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselinePaint()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangeZeroBaselinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeZeroBaselinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether the range grid-lines are visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeGridlinesVisible(boolean)\r\n */\r\n public boolean isRangeGridlinesVisible() {\r\n return this.rangeGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not grid-lines are drawn against\r\n * the range axis. If the flag changes value, a {@link PlotChangeEvent} is\r\n * sent to all registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeGridlinesVisible()\r\n */\r\n public void setRangeGridlinesVisible(boolean visible) {\r\n if (this.rangeGridlinesVisible != visible) {\r\n this.rangeGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the grid-lines against the range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlineStroke(Stroke)\r\n */\r\n public Stroke getRangeGridlineStroke() {\r\n return this.rangeGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the grid-lines against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlineStroke()\r\n */\r\n public void setRangeGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the grid-lines against the range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlinePaint(Paint)\r\n */\r\n public Paint getRangeGridlinePaint() {\r\n return this.rangeGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the grid lines against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlinePaint()\r\n */\r\n public void setRangeGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range axis minor grid is visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeMinorGridlinesVisible(boolean)\r\n *\r\n * @since 1.0.13\r\n */\r\n public boolean isRangeMinorGridlinesVisible() {\r\n return this.rangeMinorGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the range axis minor grid\r\n * lines are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeMinorGridlinesVisible()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangeMinorGridlinesVisible(boolean visible) {\r\n if (this.rangeMinorGridlinesVisible != visible) {\r\n this.rangeMinorGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlineStroke(Stroke)\r\n *\r\n * @since 1.0.13\r\n */\r\n public Stroke getRangeMinorGridlineStroke() {\r\n return this.rangeMinorGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the minor grid lines plotted against the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlineStroke()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangeMinorGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeMinorGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlinePaint(Paint)\r\n *\r\n * @since 1.0.13\r\n */\r\n public Paint getRangeMinorGridlinePaint() {\r\n return this.rangeMinorGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the minor grid lines plotted against the range axis\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlinePaint()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangeMinorGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeMinorGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the fixed legend items, if any.\r\n *\r\n * @return The legend items (possibly <code>null</code>).\r\n *\r\n * @see #setFixedLegendItems(LegendItemCollection)\r\n */\r\n public LegendItemCollection getFixedLegendItems() {\r\n return this.fixedLegendItems;\r\n }\r\n\r\n /**\r\n * Sets the fixed legend items for the plot. Leave this set to\r\n * <code>null</code> if you prefer the legend items to be created\r\n * automatically.\r\n *\r\n * @param items the legend items (<code>null</code> permitted).\r\n *\r\n * @see #getFixedLegendItems()\r\n */\r\n public void setFixedLegendItems(LegendItemCollection items) {\r\n this.fixedLegendItems = items;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the legend items for the plot. By default, this method creates\r\n * a legend item for each series in each of the datasets. You can change\r\n * this behaviour by overriding this method.\r\n *\r\n * @return The legend items.\r\n */\r\n @Override\r\n public LegendItemCollection getLegendItems() {\r\n if (this.fixedLegendItems != null) {\r\n return this.fixedLegendItems;\r\n }\r\n LegendItemCollection result = new LegendItemCollection();\r\n // get the legend items for the datasets...\r\n for (CategoryDataset dataset: this.datasets.values()) {\r\n if (dataset != null) {\r\n int datasetIndex = indexOf(dataset);\r\n CategoryItemRenderer renderer = getRenderer(datasetIndex);\r\n if (renderer != null) {\r\n result.addAll(renderer.getLegendItems());\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the plot by updating the anchor value.\r\n *\r\n * @param x x-coordinate of the click (in Java2D space).\r\n * @param y y-coordinate of the click (in Java2D space).\r\n * @param info information about the plot's dimensions.\r\n *\r\n */\r\n @Override\r\n public void handleClick(int x, int y, PlotRenderingInfo info) {\r\n\r\n Rectangle2D dataArea = info.getDataArea();\r\n if (dataArea.contains(x, y)) {\r\n // set the anchor value for the range axis...\r\n double java2D = 0.0;\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n java2D = x;\r\n } else if (this.orientation == PlotOrientation.VERTICAL) {\r\n java2D = y;\r\n }\r\n RectangleEdge edge = Plot.resolveRangeAxisLocation(\r\n getRangeAxisLocation(), this.orientation);\r\n double value = getRangeAxis().java2DToValue(\r\n java2D, info.getDataArea(), edge);\r\n setAnchorValue(value);\r\n setRangeCrosshairValue(value);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Zooms (in or out) on the plot's value axis.\r\n * <p>\r\n * If the value 0.0 is passed in as the zoom percent, the auto-range\r\n * calculation for the axis is restored (which sets the range to include\r\n * the minimum and maximum data values, thus displaying all the data).\r\n *\r\n * @param percent the zoom amount.\r\n */\r\n @Override\r\n public void zoom(double percent) {\r\n if (percent > 0.0) {\r\n double range = getRangeAxis().getRange().getLength();\r\n double scaledRange = range * percent;\r\n getRangeAxis().setRange(this.anchorValue - scaledRange / 2.0,\r\n this.anchorValue + scaledRange / 2.0);\r\n }\r\n else {\r\n getRangeAxis().setAutoRange(true);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a change to an {@link Annotation} added to\r\n * this plot.\r\n *\r\n * @param event information about the event (not used here).\r\n *\r\n * @since 1.0.14\r\n */\r\n @Override\r\n public void annotationChanged(AnnotationChangeEvent event) {\r\n if (getParent() != null) {\r\n getParent().annotationChanged(event);\r\n } else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a change to the plot's dataset.\r\n * <P>\r\n * The range axis bounds will be recalculated if necessary.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void datasetChanged(DatasetChangeEvent event) {\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.configure();\r\n }\r\n }\r\n if (getParent() != null) {\r\n getParent().datasetChanged(event);\r\n } else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n e.setType(ChartChangeEventType.DATASET_UPDATED);\r\n notifyListeners(e);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Receives notification of a renderer change event.\r\n *\r\n * @param event the event.\r\n */\r\n @Override\r\n public void rendererChanged(RendererChangeEvent event) {\r\n Plot parent = getParent();\r\n if (parent != null) {\r\n if (parent instanceof RendererChangeListener) {\r\n RendererChangeListener rcl = (RendererChangeListener) parent;\r\n rcl.rendererChanged(event);\r\n } else {\r\n // this should never happen with the existing code, but throw\r\n // an exception in case future changes make it possible...\r\n throw new RuntimeException(\r\n \"The renderer has changed and I don't know what to do!\");\r\n }\r\n } else {\r\n configureRangeAxes();\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Adds a marker for display (in the foreground) against the domain axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners. Typically a\r\n * marker will be drawn by the renderer as a line perpendicular to the\r\n * domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #removeDomainMarker(Marker)\r\n */\r\n public void addDomainMarker(CategoryMarker marker) {\r\n addDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for display against the domain axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. Typically a marker\r\n * will be drawn by the renderer as a line perpendicular to the domain\r\n * axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background) (<code>null</code>\r\n * not permitted).\r\n *\r\n * @see #removeDomainMarker(Marker, Layer)\r\n */\r\n public void addDomainMarker(CategoryMarker marker, Layer layer) {\r\n addDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Adds a marker for display by a particular renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to a domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (<code>null</code> not permitted).\r\n *\r\n * @see #removeDomainMarker(int, Marker, Layer)\r\n */\r\n public void addDomainMarker(int index, CategoryMarker marker, Layer layer) {\r\n addDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for display by a particular renderer and, if requested,\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to a domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n *\r\n * @see #removeDomainMarker(int, Marker, Layer, boolean)\r\n */\r\n public void addDomainMarker(int index, CategoryMarker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ParamChecks.nullNotPermitted(layer, \"layer\");\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n } else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Clears all the domain markers for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @see #clearRangeMarkers()\r\n */\r\n public void clearDomainMarkers() {\r\n if (this.backgroundDomainMarkers != null) {\r\n Set keys = this.backgroundDomainMarkers.keySet();\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Integer key = (Integer) iterator.next();\r\n clearDomainMarkers(key.intValue());\r\n }\r\n this.backgroundDomainMarkers.clear();\r\n }\r\n if (this.foregroundDomainMarkers != null) {\r\n Set keys = this.foregroundDomainMarkers.keySet();\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Integer key = (Integer) iterator.next();\r\n clearDomainMarkers(key.intValue());\r\n }\r\n this.foregroundDomainMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the list of domain markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of domain markers.\r\n */\r\n public Collection getDomainMarkers(Layer layer) {\r\n return getDomainMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns a collection of domain markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n */\r\n public Collection getDomainMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundDomainMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundDomainMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Clears all the domain markers for the specified renderer.\r\n *\r\n * @param index the renderer index.\r\n *\r\n * @see #clearRangeMarkers(int)\r\n */\r\n public void clearDomainMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundDomainMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundDomainMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker) {\r\n return removeDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker, Layer layer) {\r\n return removeDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer) {\r\n return removeDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and, if requested,\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ArrayList markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (ArrayList) this.foregroundDomainMarkers.get(new Integer(\r\n index));\r\n } else {\r\n markers = (ArrayList) this.backgroundDomainMarkers.get(new Integer(\r\n index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Adds a marker for display (in the foreground) against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners. Typically a\r\n * marker will be drawn by the renderer as a line perpendicular to the\r\n * range axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #removeRangeMarker(Marker)\r\n */\r\n public void addRangeMarker(Marker marker) {\r\n addRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for display against the range axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. Typically a marker\r\n * will be drawn by the renderer as a line perpendicular to the range axis,\r\n * however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background) (<code>null</code>\r\n * not permitted).\r\n *\r\n * @see #removeRangeMarker(Marker, Layer)\r\n */\r\n public void addRangeMarker(Marker marker, Layer layer) {\r\n addRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Adds a marker for display by a particular renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to a range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer.\r\n *\r\n * @see #removeRangeMarker(int, Marker, Layer)\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer) {\r\n addRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for display by a particular renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to a range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer.\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n *\r\n * @see #removeRangeMarker(int, Marker, Layer, boolean)\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n } else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Clears all the range markers for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @see #clearDomainMarkers()\r\n */\r\n public void clearRangeMarkers() {\r\n if (this.backgroundRangeMarkers != null) {\r\n Set keys = this.backgroundRangeMarkers.keySet();\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Integer key = (Integer) iterator.next();\r\n clearRangeMarkers(key.intValue());\r\n }\r\n this.backgroundRangeMarkers.clear();\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Set keys = this.foregroundRangeMarkers.keySet();\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Integer key = (Integer) iterator.next();\r\n clearRangeMarkers(key.intValue());\r\n }\r\n this.foregroundRangeMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the list of range markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of range markers.\r\n *\r\n * @see #getRangeMarkers(int, Layer)\r\n */\r\n public Collection getRangeMarkers(Layer layer) {\r\n return getRangeMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns a collection of range markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n */\r\n public Collection getRangeMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundRangeMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundRangeMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Clears all the range markers for the specified renderer.\r\n *\r\n * @param index the renderer index.\r\n *\r\n * @see #clearDomainMarkers(int)\r\n */\r\n public void clearRangeMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n *\r\n * @see #addRangeMarker(Marker)\r\n */\r\n public boolean removeRangeMarker(Marker marker) {\r\n return removeRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n *\r\n * @see #addRangeMarker(Marker, Layer)\r\n */\r\n public boolean removeRangeMarker(Marker marker, Layer layer) {\r\n return removeRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n *\r\n * @see #addRangeMarker(int, Marker, Layer)\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer) {\r\n return removeRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n *\r\n * @see #addRangeMarker(int, Marker, Layer, boolean)\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ArrayList markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (ArrayList) this.foregroundRangeMarkers.get(new Integer(\r\n index));\r\n } else {\r\n markers = (ArrayList) this.backgroundRangeMarkers.get(new Integer(\r\n index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the domain crosshair is\r\n * displayed by the plot.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #setDomainCrosshairVisible(boolean)\r\n */\r\n public boolean isDomainCrosshairVisible() {\r\n return this.domainCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the domain crosshair is\r\n * displayed by the plot, and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param flag the new flag value.\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #isDomainCrosshairVisible()\r\n * @see #setRangeCrosshairVisible(boolean)\r\n */\r\n public void setDomainCrosshairVisible(boolean flag) {\r\n if (this.domainCrosshairVisible != flag) {\r\n this.domainCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the row key for the domain crosshair.\r\n *\r\n * @return The row key.\r\n *\r\n * @since 1.0.11\r\n */\r\n public Comparable getDomainCrosshairRowKey() {\r\n return this.domainCrosshairRowKey;\r\n }\r\n\r\n /**\r\n * Sets the row key for the domain crosshair and sends a\r\n * {PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param key the key.\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setDomainCrosshairRowKey(Comparable key) {\r\n setDomainCrosshairRowKey(key, true);\r\n }\r\n\r\n /**\r\n * Sets the row key for the domain crosshair and, if requested, sends a\r\n * {PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param key the key.\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setDomainCrosshairRowKey(Comparable key, boolean notify) {\r\n this.domainCrosshairRowKey = key;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the column key for the domain crosshair.\r\n *\r\n * @return The column key.\r\n *\r\n * @since 1.0.11\r\n */\r\n public Comparable getDomainCrosshairColumnKey() {\r\n return this.domainCrosshairColumnKey;\r\n }\r\n\r\n /**\r\n * Sets the column key for the domain crosshair and sends\r\n * a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param key the key.\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setDomainCrosshairColumnKey(Comparable key) {\r\n setDomainCrosshairColumnKey(key, true);\r\n }\r\n\r\n /**\r\n * Sets the column key for the domain crosshair and, if requested, sends\r\n * a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param key the key.\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setDomainCrosshairColumnKey(Comparable key, boolean notify) {\r\n this.domainCrosshairColumnKey = key;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the dataset index for the crosshair.\r\n *\r\n * @return The dataset index.\r\n *\r\n * @since 1.0.11\r\n */\r\n public int getCrosshairDatasetIndex() {\r\n return this.crosshairDatasetIndex;\r\n }\r\n\r\n /**\r\n * Sets the dataset index for the crosshair and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the index.\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setCrosshairDatasetIndex(int index) {\r\n setCrosshairDatasetIndex(index, true);\r\n }\r\n\r\n /**\r\n * Sets the dataset index for the crosshair and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the index.\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setCrosshairDatasetIndex(int index, boolean notify) {\r\n this.crosshairDatasetIndex = index;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the domain crosshair.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #setDomainCrosshairPaint(Paint)\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public Paint getDomainCrosshairPaint() {\r\n return this.domainCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the domain crosshair.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public void setDomainCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the domain crosshair.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #setDomainCrosshairStroke(Stroke)\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public Stroke getDomainCrosshairStroke() {\r\n return this.domainCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the domain crosshair, and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public void setDomainCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainCrosshairStroke = stroke;\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the range crosshair is visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairVisible(boolean)\r\n */\r\n public boolean isRangeCrosshairVisible() {\r\n return this.rangeCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair is visible.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isRangeCrosshairVisible()\r\n */\r\n public void setRangeCrosshairVisible(boolean flag) {\r\n if (this.rangeCrosshairVisible != flag) {\r\n this.rangeCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the crosshair should \"lock-on\"\r\n * to actual data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairLockedOnData(boolean)\r\n */\r\n public boolean isRangeCrosshairLockedOnData() {\r\n return this.rangeCrosshairLockedOnData;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair should\r\n * \"lock-on\" to actual data values, and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isRangeCrosshairLockedOnData()\r\n */\r\n public void setRangeCrosshairLockedOnData(boolean flag) {\r\n if (this.rangeCrosshairLockedOnData != flag) {\r\n this.rangeCrosshairLockedOnData = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range crosshair value.\r\n *\r\n * @return The value.\r\n *\r\n * @see #setRangeCrosshairValue(double)\r\n */\r\n public double getRangeCrosshairValue() {\r\n return this.rangeCrosshairValue;\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value and, if the crosshair is visible, sends\r\n * a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param value the new value.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value) {\r\n setRangeCrosshairValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners (but only if the\r\n * crosshair is visible).\r\n *\r\n * @param value the new value.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value, boolean notify) {\r\n this.rangeCrosshairValue = value;\r\n if (isRangeCrosshairVisible() && notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the pen-style (<code>Stroke</code>) used to draw the crosshair\r\n * (if visible).\r\n *\r\n * @return The crosshair stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairStroke(Stroke)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public Stroke getRangeCrosshairStroke() {\r\n return this.rangeCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the pen-style (<code>Stroke</code>) used to draw the range\r\n * crosshair (if visible), and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param stroke the new crosshair stroke (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public void setRangeCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeCrosshairStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the range crosshair.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairPaint(Paint)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public Paint getRangeCrosshairPaint() {\r\n return this.rangeCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the range crosshair (if visible) and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public void setRangeCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the list of annotations.\r\n *\r\n * @return The list of annotations (never <code>null</code>).\r\n *\r\n * @see #addAnnotation(CategoryAnnotation)\r\n * @see #clearAnnotations()\r\n */\r\n public List getAnnotations() {\r\n return this.annotations;\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @see #removeAnnotation(CategoryAnnotation)\r\n */\r\n public void addAnnotation(CategoryAnnotation annotation) {\r\n addAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addAnnotation(CategoryAnnotation annotation, boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n this.annotations.add(annotation);\r\n annotation.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @see #addAnnotation(CategoryAnnotation)\r\n */\r\n public boolean removeAnnotation(CategoryAnnotation annotation) {\r\n return removeAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeAnnotation(CategoryAnnotation annotation,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n boolean removed = this.annotations.remove(annotation);\r\n annotation.removeChangeListener(this);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Clears all the annotations and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n */\r\n public void clearAnnotations() {\r\n for (int i = 0; i < this.annotations.size(); i++) {\r\n CategoryAnnotation annotation\r\n = (CategoryAnnotation) this.annotations.get(i);\r\n annotation.removeChangeListener(this);\r\n }\r\n this.annotations.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the shadow generator for the plot, if any.\r\n *\r\n * @return The shadow generator (possibly <code>null</code>).\r\n *\r\n * @since 1.0.14\r\n */\r\n public ShadowGenerator getShadowGenerator() {\r\n return this.shadowGenerator;\r\n }\r\n\r\n /**\r\n * Sets the shadow generator for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setShadowGenerator(ShadowGenerator generator) {\r\n this.shadowGenerator = generator;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Calculates the space required for the domain axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateDomainAxisSpace(Graphics2D g2,\r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the domain axis...\r\n if (this.fixedDomainAxisSpace != null) {\r\n if (this.orientation.isHorizontal()) {\r\n space.ensureAtLeast(\r\n this.fixedDomainAxisSpace.getLeft(), RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n } else if (this.orientation.isVertical()) {\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n }\r\n }\r\n else {\r\n // reserve space for the primary domain axis...\r\n RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(\r\n getDomainAxisLocation(), this.orientation);\r\n if (this.drawSharedDomainAxis) {\r\n space = getDomainAxis().reserveSpace(g2, this, plotArea,\r\n domainEdge, space);\r\n }\r\n\r\n // reserve space for any domain axes...\r\n for (CategoryAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n int i = getDomainAxisIndex(xAxis);\r\n RectangleEdge edge = getDomainAxisEdge(i);\r\n space = xAxis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the space required for the range axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateRangeAxisSpace(Graphics2D g2,\r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the range axis...\r\n if (this.fixedRangeAxisSpace != null) {\r\n if (this.orientation.isHorizontal()) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n } else if (this.orientation == PlotOrientation.VERTICAL) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getLeft(),\r\n RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n }\r\n } else {\r\n // reserve space for the range axes (if any)...\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n int i = findRangeAxisIndex(yAxis);\r\n RectangleEdge edge = getRangeAxisEdge(i);\r\n space = yAxis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Trims a rectangle to integer coordinates.\r\n *\r\n * @param rect the incoming rectangle.\r\n *\r\n * @return A rectangle with integer coordinates.\r\n */\r\n private Rectangle integerise(Rectangle2D rect) {\r\n int x0 = (int) Math.ceil(rect.getMinX());\r\n int y0 = (int) Math.ceil(rect.getMinY());\r\n int x1 = (int) Math.floor(rect.getMaxX());\r\n int y1 = (int) Math.floor(rect.getMaxY());\r\n return new Rectangle(x0, y0, (x1 - x0), (y1 - y0));\r\n }\r\n\r\n /**\r\n * Calculates the space required for the axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n *\r\n * @return The space required for the axes.\r\n */\r\n protected AxisSpace calculateAxisSpace(Graphics2D g2, \r\n Rectangle2D plotArea) {\r\n AxisSpace space = new AxisSpace();\r\n space = calculateRangeAxisSpace(g2, plotArea, space);\r\n space = calculateDomainAxisSpace(g2, plotArea, space);\r\n return space;\r\n }\r\n\r\n /**\r\n * Draws the plot on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * At your option, you may supply an instance of {@link PlotRenderingInfo}.\r\n * If you do, it will be populated with information about the drawing,\r\n * including various plot dimensions and tooltip info.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot (including axes) should\r\n * be drawn.\r\n * @param anchor the anchor point (<code>null</code> permitted).\r\n * @param parentState the state from the parent plot, if there is one.\r\n * @param state collects info as the chart is drawn (possibly\r\n * <code>null</code>).\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor,\r\n PlotState parentState, PlotRenderingInfo state) {\r\n\r\n // if the plot area is too small, just return...\r\n boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW);\r\n boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW);\r\n if (b1 || b2) {\r\n return;\r\n }\r\n\r\n // record the plot area...\r\n if (state == null) {\r\n // if the incoming state is null, no information will be passed\r\n // back to the caller - but we create a temporary state to record\r\n // the plot area, since that is used later by the axes\r\n state = new PlotRenderingInfo(null);\r\n }\r\n state.setPlotArea(area);\r\n\r\n // adjust the drawing area for the plot insets (if any)...\r\n RectangleInsets insets = getInsets();\r\n insets.trim(area);\r\n\r\n // calculate the data area...\r\n AxisSpace space = calculateAxisSpace(g2, area);\r\n Rectangle2D dataArea = space.shrink(area, null);\r\n this.axisOffset.trim(dataArea);\r\n dataArea = integerise(dataArea);\r\n if (dataArea.isEmpty()) {\r\n return;\r\n }\r\n state.setDataArea(dataArea);\r\n createAndAddEntity((Rectangle2D) dataArea.clone(), state, null, null);\r\n\r\n // if there is a renderer, it draws the background, otherwise use the\r\n // default background...\r\n if (getRenderer() != null) {\r\n getRenderer().drawBackground(g2, this, dataArea);\r\n } else {\r\n drawBackground(g2, dataArea);\r\n }\r\n\r\n Map axisStateMap = drawAxes(g2, area, dataArea, state);\r\n\r\n // the anchor point is typically the point where the mouse last\r\n // clicked - the crosshairs will be driven off this point...\r\n if (anchor != null && !dataArea.contains(anchor)) {\r\n anchor = ShapeUtilities.getPointInRectangle(anchor.getX(),\r\n anchor.getY(), dataArea);\r\n }\r\n CategoryCrosshairState crosshairState = new CategoryCrosshairState();\r\n crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY);\r\n crosshairState.setAnchor(anchor);\r\n\r\n // specify the anchor X and Y coordinates in Java2D space, for the\r\n // cases where these are not updated during rendering (i.e. no lock\r\n // on data)\r\n crosshairState.setAnchorX(Double.NaN);\r\n crosshairState.setAnchorY(Double.NaN);\r\n if (anchor != null) {\r\n ValueAxis rangeAxis = getRangeAxis();\r\n if (rangeAxis != null) {\r\n double y;\r\n if (getOrientation() == PlotOrientation.VERTICAL) {\r\n y = rangeAxis.java2DToValue(anchor.getY(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n else {\r\n y = rangeAxis.java2DToValue(anchor.getX(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n crosshairState.setAnchorY(y);\r\n }\r\n }\r\n crosshairState.setRowKey(getDomainCrosshairRowKey());\r\n crosshairState.setColumnKey(getDomainCrosshairColumnKey());\r\n crosshairState.setCrosshairY(getRangeCrosshairValue());\r\n\r\n // don't let anyone draw outside the data area\r\n Shape savedClip = g2.getClip();\r\n g2.clip(dataArea);\r\n\r\n drawDomainGridlines(g2, dataArea);\r\n\r\n AxisState rangeAxisState = (AxisState) axisStateMap.get(getRangeAxis());\r\n if (rangeAxisState == null) {\r\n if (parentState != null) {\r\n rangeAxisState = (AxisState) parentState.getSharedAxisStates()\r\n .get(getRangeAxis());\r\n }\r\n }\r\n if (rangeAxisState != null) {\r\n drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks());\r\n drawZeroRangeBaseline(g2, dataArea);\r\n }\r\n\r\n Graphics2D savedG2 = g2;\r\n BufferedImage dataImage = null;\r\n boolean suppressShadow = Boolean.TRUE.equals(g2.getRenderingHint(\r\n JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION));\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n dataImage = new BufferedImage((int) dataArea.getWidth(),\r\n (int)dataArea.getHeight(), BufferedImage.TYPE_INT_ARGB);\r\n g2 = dataImage.createGraphics();\r\n g2.translate(-dataArea.getX(), -dataArea.getY());\r\n g2.setRenderingHints(savedG2.getRenderingHints());\r\n }\r\n\r\n // draw the markers...\r\n for (CategoryItemRenderer renderer : this.renderers.values()) {\r\n int i = getIndexOf(renderer);\r\n drawDomainMarkers(g2, dataArea, i, Layer.BACKGROUND);\r\n }\r\n for (CategoryItemRenderer renderer : this.renderers.values()) {\r\n int i = getIndexOf(renderer);\r\n drawRangeMarkers(g2, dataArea, i, Layer.BACKGROUND);\r\n }\r\n\r\n // now render data items...\r\n boolean foundData = false;\r\n\r\n // set up the alpha-transparency...\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(\r\n AlphaComposite.SRC_OVER, getForegroundAlpha()));\r\n\r\n DatasetRenderingOrder order = getDatasetRenderingOrder();\r\n List<Integer> datasetIndices = getDatasetIndices(order);\r\n for (int i : datasetIndices) {\r\n foundData = render(g2, dataArea, i, state, crosshairState)\r\n || foundData;\r\n }\r\n\r\n // draw the foreground markers...\r\n List<Integer> rendererIndices = getRendererIndices(order);\r\n for (int i : rendererIndices) {\r\n drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n for (int i : rendererIndices) {\r\n drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n\r\n // draw the annotations (if any)...\r\n drawAnnotations(g2, dataArea);\r\n\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n BufferedImage shadowImage = this.shadowGenerator.createDropShadow(\r\n dataImage);\r\n g2 = savedG2;\r\n g2.drawImage(shadowImage, (int) dataArea.getX()\r\n + this.shadowGenerator.calculateOffsetX(),\r\n (int) dataArea.getY()\r\n + this.shadowGenerator.calculateOffsetY(), null);\r\n g2.drawImage(dataImage, (int) dataArea.getX(),\r\n (int) dataArea.getY(), null);\r\n }\r\n g2.setClip(savedClip);\r\n g2.setComposite(originalComposite);\r\n\r\n if (!foundData) {\r\n drawNoDataMessage(g2, dataArea);\r\n }\r\n\r\n int datasetIndex = crosshairState.getDatasetIndex();\r\n setCrosshairDatasetIndex(datasetIndex, false);\r\n\r\n // draw domain crosshair if required...\r\n Comparable rowKey = crosshairState.getRowKey();\r\n Comparable columnKey = crosshairState.getColumnKey();\r\n setDomainCrosshairRowKey(rowKey, false);\r\n setDomainCrosshairColumnKey(columnKey, false);\r\n if (isDomainCrosshairVisible() && columnKey != null) {\r\n Paint paint = getDomainCrosshairPaint();\r\n Stroke stroke = getDomainCrosshairStroke();\r\n drawDomainCrosshair(g2, dataArea, this.orientation,\r\n datasetIndex, rowKey, columnKey, stroke, paint);\r\n }\r\n\r\n // draw range crosshair if required...\r\n ValueAxis yAxis = getRangeAxisForDataset(datasetIndex);\r\n RectangleEdge yAxisEdge = getRangeAxisEdge();\r\n if (!this.rangeCrosshairLockedOnData && anchor != null) {\r\n double yy;\r\n if (getOrientation() == PlotOrientation.VERTICAL) {\r\n yy = yAxis.java2DToValue(anchor.getY(), dataArea, yAxisEdge);\r\n }\r\n else {\r\n yy = yAxis.java2DToValue(anchor.getX(), dataArea, yAxisEdge);\r\n }\r\n crosshairState.setCrosshairY(yy);\r\n }\r\n setRangeCrosshairValue(crosshairState.getCrosshairY(), false);\r\n if (isRangeCrosshairVisible()) {\r\n double y = getRangeCrosshairValue();\r\n Paint paint = getRangeCrosshairPaint();\r\n Stroke stroke = getRangeCrosshairStroke();\r\n drawRangeCrosshair(g2, dataArea, getOrientation(), y, yAxis,\r\n stroke, paint);\r\n }\r\n\r\n // draw an outline around the plot area...\r\n if (isOutlineVisible()) {\r\n if (getRenderer() != null) {\r\n getRenderer().drawOutline(g2, this, dataArea);\r\n }\r\n else {\r\n drawOutline(g2, dataArea);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the indices of the non-null datasets in the specified order.\r\n * \r\n * @param order the order ({@code null} not permitted).\r\n * \r\n * @return The list of indices. \r\n */\r\n private List<Integer> getDatasetIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Map.Entry<Integer, CategoryDataset> entry : \r\n this.datasets.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result;\r\n }\r\n \r\n /**\r\n * Returns the indices of the non-null renderers for the plot, in the \r\n * specified order.\r\n * \r\n * @param order the rendering order {@code null} not permitted).\r\n * \r\n * @return A list of indices.\r\n */\r\n private List<Integer> getRendererIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Map.Entry<Integer, CategoryItemRenderer> entry: \r\n this.renderers.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result; \r\n }\r\n \r\n /**\r\n * Draws the plot background (the background color and/or image).\r\n * <P>\r\n * This method will be called during the chart drawing process and is\r\n * declared public so that it can be accessed by the renderers used by\r\n * certain subclasses. You shouldn't need to call this method directly.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot should be drawn.\r\n */\r\n @Override\r\n public void drawBackground(Graphics2D g2, Rectangle2D area) {\r\n fillBackground(g2, area, this.orientation);\r\n drawBackgroundImage(g2, area);\r\n }\r\n\r\n /**\r\n * A utility method for drawing the plot's axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param dataArea the data area.\r\n * @param plotState collects information about the plot (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A map containing the axis states.\r\n */\r\n protected Map drawAxes(Graphics2D g2, Rectangle2D plotArea, \r\n Rectangle2D dataArea, PlotRenderingInfo plotState) {\r\n\r\n AxisCollection axisCollection = new AxisCollection();\r\n\r\n // add domain axes to lists...\r\n for (CategoryAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n int index = getDomainAxisIndex(xAxis);\r\n axisCollection.add(xAxis, getDomainAxisEdge(index));\r\n }\r\n }\r\n\r\n // add range axes to lists...\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n int index = findRangeAxisIndex(yAxis);\r\n axisCollection.add(yAxis, getRangeAxisEdge(index));\r\n }\r\n }\r\n\r\n Map axisStateMap = new HashMap();\r\n\r\n // draw the top axes\r\n double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset(\r\n dataArea.getHeight());\r\n Iterator iterator = axisCollection.getAxesAtTop().iterator();\r\n while (iterator.hasNext()) {\r\n Axis axis = (Axis) iterator.next();\r\n if (axis != null) {\r\n AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.TOP, plotState);\r\n cursor = axisState.getCursor();\r\n axisStateMap.put(axis, axisState);\r\n }\r\n }\r\n\r\n // draw the bottom axes\r\n cursor = dataArea.getMaxY()\r\n + this.axisOffset.calculateBottomOutset(dataArea.getHeight());\r\n iterator = axisCollection.getAxesAtBottom().iterator();\r\n while (iterator.hasNext()) {\r\n Axis axis = (Axis) iterator.next();\r\n if (axis != null) {\r\n AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.BOTTOM, plotState);\r\n cursor = axisState.getCursor();\r\n axisStateMap.put(axis, axisState);\r\n }\r\n }\r\n\r\n // draw the left axes\r\n cursor = dataArea.getMinX()\r\n - this.axisOffset.calculateLeftOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtLeft().iterator();\r\n while (iterator.hasNext()) {\r\n Axis axis = (Axis) iterator.next();\r\n if (axis != null) {\r\n AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.LEFT, plotState);\r\n cursor = axisState.getCursor();\r\n axisStateMap.put(axis, axisState);\r\n }\r\n }\r\n\r\n // draw the right axes\r\n cursor = dataArea.getMaxX()\r\n + this.axisOffset.calculateRightOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtRight().iterator();\r\n while (iterator.hasNext()) {\r\n Axis axis = (Axis) iterator.next();\r\n if (axis != null) {\r\n AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.RIGHT, plotState);\r\n cursor = axisState.getCursor();\r\n axisStateMap.put(axis, axisState);\r\n }\r\n }\r\n\r\n return axisStateMap;\r\n\r\n }\r\n\r\n /**\r\n * Draws a representation of a dataset within the dataArea region using the\r\n * appropriate renderer.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the region in which the data is to be drawn.\r\n * @param index the dataset and renderer index.\r\n * @param info an optional object for collection dimension information.\r\n * @param crosshairState a state object for tracking crosshair info\r\n * (<code>null</code> permitted).\r\n *\r\n * @return A boolean that indicates whether or not real data was found.\r\n *\r\n * @since 1.0.11\r\n */\r\n public boolean render(Graphics2D g2, Rectangle2D dataArea, int index,\r\n PlotRenderingInfo info, CategoryCrosshairState crosshairState) {\r\n\r\n boolean foundData = false;\r\n CategoryDataset currentDataset = getDataset(index);\r\n CategoryItemRenderer renderer = getRenderer(index);\r\n CategoryAxis domainAxis = getDomainAxisForDataset(index);\r\n ValueAxis rangeAxis = getRangeAxisForDataset(index);\r\n boolean hasData = !DatasetUtilities.isEmptyOrNull(currentDataset);\r\n if (hasData && renderer != null) {\r\n\r\n foundData = true;\r\n CategoryItemRendererState state = renderer.initialise(g2, dataArea,\r\n this, index, info);\r\n state.setCrosshairState(crosshairState);\r\n int columnCount = currentDataset.getColumnCount();\r\n int rowCount = currentDataset.getRowCount();\r\n int passCount = renderer.getPassCount();\r\n for (int pass = 0; pass < passCount; pass++) {\r\n if (this.columnRenderingOrder == SortOrder.ASCENDING) {\r\n for (int column = 0; column < columnCount; column++) {\r\n if (this.rowRenderingOrder == SortOrder.ASCENDING) {\r\n for (int row = 0; row < rowCount; row++) {\r\n renderer.drawItem(g2, state, dataArea, this,\r\n domainAxis, rangeAxis, currentDataset,\r\n row, column, pass);\r\n }\r\n }\r\n else {\r\n for (int row = rowCount - 1; row >= 0; row--) {\r\n renderer.drawItem(g2, state, dataArea, this,\r\n domainAxis, rangeAxis, currentDataset,\r\n row, column, pass);\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n for (int column = columnCount - 1; column >= 0; column--) {\r\n if (this.rowRenderingOrder == SortOrder.ASCENDING) {\r\n for (int row = 0; row < rowCount; row++) {\r\n renderer.drawItem(g2, state, dataArea, this,\r\n domainAxis, rangeAxis, currentDataset,\r\n row, column, pass);\r\n }\r\n }\r\n else {\r\n for (int row = rowCount - 1; row >= 0; row--) {\r\n renderer.drawItem(g2, state, dataArea, this,\r\n domainAxis, rangeAxis, currentDataset,\r\n row, column, pass);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return foundData;\r\n\r\n }\r\n\r\n /**\r\n * Draws the domain gridlines for the plot, if they are visible.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area inside the axes.\r\n *\r\n * @see #drawRangeGridlines(Graphics2D, Rectangle2D, List)\r\n */\r\n protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea) {\r\n\r\n if (!isDomainGridlinesVisible()) {\r\n return;\r\n }\r\n CategoryAnchor anchor = getDomainGridlinePosition();\r\n RectangleEdge domainAxisEdge = getDomainAxisEdge();\r\n CategoryDataset dataset = getDataset();\r\n if (dataset == null) {\r\n return;\r\n }\r\n CategoryAxis axis = getDomainAxis();\r\n if (axis != null) {\r\n int columnCount = dataset.getColumnCount();\r\n for (int c = 0; c < columnCount; c++) {\r\n double xx = axis.getCategoryJava2DCoordinate(anchor, c,\r\n columnCount, dataArea, domainAxisEdge);\r\n CategoryItemRenderer renderer1 = getRenderer();\r\n if (renderer1 != null) {\r\n renderer1.drawDomainGridline(g2, this, dataArea, xx);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws the range gridlines for the plot, if they are visible.\r\n *\r\n * @param g2 the graphics device ({@code null} not permitted).\r\n * @param dataArea the area inside the axes ({@code null} not permitted).\r\n * @param ticks the ticks.\r\n *\r\n * @see #drawDomainGridlines(Graphics2D, Rectangle2D)\r\n */\r\n protected void drawRangeGridlines(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n // draw the range grid lines, if any...\r\n if (!isRangeGridlinesVisible() && !isRangeMinorGridlinesVisible()) {\r\n return;\r\n }\r\n // no axis, no gridlines...\r\n ValueAxis axis = getRangeAxis();\r\n if (axis == null) {\r\n return;\r\n }\r\n // no renderer, no gridlines...\r\n CategoryItemRenderer r = getRenderer();\r\n if (r == null) {\r\n return;\r\n }\r\n\r\n Stroke gridStroke = null;\r\n Paint gridPaint = null;\r\n boolean paintLine;\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n paintLine = false;\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if ((tick.getTickType() == TickType.MINOR)\r\n && isRangeMinorGridlinesVisible()) {\r\n gridStroke = getRangeMinorGridlineStroke();\r\n gridPaint = getRangeMinorGridlinePaint();\r\n paintLine = true;\r\n }\r\n else if ((tick.getTickType() == TickType.MAJOR)\r\n && isRangeGridlinesVisible()) {\r\n gridStroke = getRangeGridlineStroke();\r\n gridPaint = getRangeGridlinePaint();\r\n paintLine = true;\r\n }\r\n if (((tick.getValue() != 0.0)\r\n || !isRangeZeroBaselineVisible()) && paintLine) {\r\n // the method we want isn't in the CategoryItemRenderer\r\n // interface...\r\n if (r instanceof AbstractCategoryItemRenderer) {\r\n AbstractCategoryItemRenderer aci\r\n = (AbstractCategoryItemRenderer) r;\r\n aci.drawRangeLine(g2, this, axis, dataArea,\r\n tick.getValue(), gridPaint, gridStroke);\r\n }\r\n else {\r\n // we'll have to use the method in the interface, but\r\n // this doesn't have the paint and stroke settings...\r\n r.drawRangeGridline(g2, this, axis, dataArea,\r\n tick.getValue());\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws a base line across the chart at value zero on the range axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n *\r\n * @since 1.0.13\r\n */\r\n protected void drawZeroRangeBaseline(Graphics2D g2, Rectangle2D area) {\r\n if (!isRangeZeroBaselineVisible()) {\r\n return;\r\n }\r\n CategoryItemRenderer r = getRenderer();\r\n if (r instanceof AbstractCategoryItemRenderer) {\r\n AbstractCategoryItemRenderer aci = (AbstractCategoryItemRenderer) r;\r\n aci.drawRangeLine(g2, this, getRangeAxis(), area, 0.0,\r\n this.rangeZeroBaselinePaint, this.rangeZeroBaselineStroke);\r\n }\r\n else {\r\n r.drawRangeGridline(g2, this, getRangeAxis(), area, 0.0);\r\n }\r\n }\r\n\r\n /**\r\n * Draws the annotations.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n */\r\n protected void drawAnnotations(Graphics2D g2, Rectangle2D dataArea) {\r\n\r\n if (getAnnotations() != null) {\r\n Iterator iterator = getAnnotations().iterator();\r\n while (iterator.hasNext()) {\r\n CategoryAnnotation annotation\r\n = (CategoryAnnotation) iterator.next();\r\n annotation.draw(g2, this, dataArea, getDomainAxis(),\r\n getRangeAxis());\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the domain markers (if any) for an axis and layer. This method is\r\n * typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the renderer index.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #drawRangeMarkers(Graphics2D, Rectangle2D, int, Layer)\r\n */\r\n protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n CategoryItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n\r\n Collection markers = getDomainMarkers(index, layer);\r\n CategoryAxis axis = getDomainAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n CategoryMarker marker = (CategoryMarker) iterator.next();\r\n r.drawDomainMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the range markers (if any) for an axis and layer. This method is\r\n * typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the renderer index.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #drawDomainMarkers(Graphics2D, Rectangle2D, int, Layer)\r\n */\r\n protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n CategoryItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n\r\n Collection markers = getRangeMarkers(index, layer);\r\n ValueAxis axis = getRangeAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker marker = (Marker) iterator.next();\r\n r.drawRangeMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Utility method for drawing a line perpendicular to the range axis (used\r\n * for crosshairs).\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area defined by the axes.\r\n * @param value the data value.\r\n * @param stroke the line stroke (<code>null</code> not permitted).\r\n * @param paint the line paint (<code>null</code> not permitted).\r\n */\r\n protected void drawRangeLine(Graphics2D g2, Rectangle2D dataArea,\r\n double value, Stroke stroke, Paint paint) {\r\n\r\n double java2D = getRangeAxis().valueToJava2D(value, dataArea,\r\n getRangeAxisEdge());\r\n Line2D line = null;\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n line = new Line2D.Double(java2D, dataArea.getMinY(), java2D,\r\n dataArea.getMaxY());\r\n }\r\n else if (this.orientation == PlotOrientation.VERTICAL) {\r\n line = new Line2D.Double(dataArea.getMinX(), java2D,\r\n dataArea.getMaxX(), java2D);\r\n }\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n\r\n }\r\n\r\n /**\r\n * Draws a domain crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param datasetIndex the dataset index.\r\n * @param rowKey the row key.\r\n * @param columnKey the column key.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @see #drawRangeCrosshair(Graphics2D, Rectangle2D, PlotOrientation,\r\n * double, ValueAxis, Stroke, Paint)\r\n *\r\n * @since 1.0.11\r\n */\r\n protected void drawDomainCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, int datasetIndex,\r\n Comparable rowKey, Comparable columnKey, Stroke stroke,\r\n Paint paint) {\r\n\r\n CategoryDataset dataset = getDataset(datasetIndex);\r\n CategoryAxis axis = getDomainAxisForDataset(datasetIndex);\r\n CategoryItemRenderer renderer = getRenderer(datasetIndex);\r\n Line2D line;\r\n if (orientation == PlotOrientation.VERTICAL) {\r\n double xx = renderer.getItemMiddle(rowKey, columnKey, dataset, axis,\r\n dataArea, RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n }\r\n else {\r\n double yy = renderer.getItemMiddle(rowKey, columnKey, dataset, axis,\r\n dataArea, RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n\r\n }\r\n\r\n /**\r\n * Draws a range crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param value the crosshair value.\r\n * @param axis the axis against which the value is measured.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @see #drawDomainCrosshair(Graphics2D, Rectangle2D, PlotOrientation, int,\r\n * Comparable, Comparable, Stroke, Paint)\r\n *\r\n * @since 1.0.5\r\n */\r\n protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, double value, ValueAxis axis,\r\n Stroke stroke, Paint paint) {\r\n\r\n if (!axis.getRange().contains(value)) {\r\n return;\r\n }\r\n Line2D line;\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n double xx = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n }\r\n else {\r\n double yy = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n\r\n }\r\n\r\n /**\r\n * Returns the range of data values that will be plotted against the range\r\n * axis. If the dataset is <code>null</code>, this method returns\r\n * <code>null</code>.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The data range.\r\n */\r\n @Override\r\n public Range getDataRange(ValueAxis axis) {\r\n Range result = null;\r\n List<CategoryDataset> mappedDatasets = new ArrayList<CategoryDataset>();\r\n int rangeIndex = findRangeAxisIndex(axis);\r\n if (rangeIndex >= 0) {\r\n mappedDatasets.addAll(datasetsMappedToRangeAxis(rangeIndex));\r\n }\r\n else if (axis == getRangeAxis()) {\r\n mappedDatasets.addAll(datasetsMappedToRangeAxis(0));\r\n }\r\n\r\n // iterate through the datasets that map to the axis and get the union\r\n // of the ranges.\r\n for (CategoryDataset d : mappedDatasets) {\r\n CategoryItemRenderer r = getRendererForDataset(d);\r\n if (r != null) {\r\n result = Range.combine(result, r.findRangeBounds(d));\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a list of the datasets that are mapped to the axis with the\r\n * specified index.\r\n *\r\n * @param axisIndex the axis index.\r\n *\r\n * @return The list (possibly empty, but never <code>null</code>).\r\n *\r\n * @since 1.0.3\r\n */\r\n private List<CategoryDataset> datasetsMappedToDomainAxis(int axisIndex) {\r\n Integer key = new Integer(axisIndex);\r\n List<CategoryDataset> result = new ArrayList<CategoryDataset>();\r\n for (CategoryDataset dataset : this.datasets.values()) {\r\n if (dataset == null) {\r\n continue;\r\n }\r\n int i = indexOf(dataset);\r\n List mappedAxes = (List) this.datasetToDomainAxesMap.get(\r\n new Integer(i));\r\n if (mappedAxes == null) {\r\n if (key.equals(ZERO)) {\r\n result.add(dataset);\r\n }\r\n } else {\r\n if (mappedAxes.contains(key)) {\r\n result.add(dataset);\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * A utility method that returns a list of datasets that are mapped to a\r\n * given range axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return A list of datasets.\r\n */\r\n private List datasetsMappedToRangeAxis(int index) {\r\n Integer key = new Integer(index);\r\n List result = new ArrayList();\r\n for (CategoryDataset dataset : this.datasets.values()) {\r\n int i = indexOf(dataset);\r\n List mappedAxes = (List) this.datasetToRangeAxesMap.get(\r\n new Integer(i));\r\n if (mappedAxes == null) {\r\n if (key.equals(ZERO)) {\r\n result.add(this.datasets.get(i));\r\n }\r\n } else {\r\n if (mappedAxes.contains(key)) {\r\n result.add(this.datasets.get(i));\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the weight for this plot when it is used as a subplot within a\r\n * combined plot.\r\n *\r\n * @return The weight.\r\n *\r\n * @see #setWeight(int)\r\n */\r\n public int getWeight() {\r\n return this.weight;\r\n }\r\n\r\n /**\r\n * Sets the weight for the plot and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param weight the weight.\r\n *\r\n * @see #getWeight()\r\n */\r\n public void setWeight(int weight) {\r\n this.weight = weight;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the fixed domain axis space.\r\n *\r\n * @return The fixed domain axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedDomainAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedDomainAxisSpace() {\r\n return this.fixedDomainAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space) {\r\n setFixedDomainAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n *\r\n * @since 1.0.7\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedDomainAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the fixed range axis space.\r\n *\r\n * @return The fixed range axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedRangeAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedRangeAxisSpace() {\r\n return this.fixedRangeAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space) {\r\n setFixedRangeAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n *\r\n * @since 1.0.7\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedRangeAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a list of the categories in the plot's primary dataset.\r\n *\r\n * @return A list of the categories in the plot's primary dataset.\r\n *\r\n * @see #getCategoriesForAxis(CategoryAxis)\r\n */\r\n public List getCategories() {\r\n List result = null;\r\n if (getDataset() != null) {\r\n result = Collections.unmodifiableList(getDataset().getColumnKeys());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a list of the categories that should be displayed for the\r\n * specified axis.\r\n *\r\n * @param axis the axis (<code>null</code> not permitted)\r\n *\r\n * @return The categories.\r\n *\r\n * @since 1.0.3\r\n */\r\n public List getCategoriesForAxis(CategoryAxis axis) {\r\n List result = new ArrayList();\r\n int axisIndex = getDomainAxisIndex(axis);\r\n for (CategoryDataset dataset : datasetsMappedToDomainAxis(axisIndex)) {\r\n // add the unique categories from this dataset\r\n for (int i = 0; i < dataset.getColumnCount(); i++) {\r\n Comparable category = dataset.getColumnKey(i);\r\n if (!result.contains(category)) {\r\n result.add(category);\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the shared domain axis is\r\n * drawn for each subplot.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setDrawSharedDomainAxis(boolean)\r\n */\r\n public boolean getDrawSharedDomainAxis() {\r\n return this.drawSharedDomainAxis;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether the shared domain axis is drawn when\r\n * this plot is being used as a subplot.\r\n *\r\n * @param draw a boolean.\r\n *\r\n * @see #getDrawSharedDomainAxis()\r\n */\r\n public void setDrawSharedDomainAxis(boolean draw) {\r\n this.drawSharedDomainAxis = draw;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>false</code> always, because the plot cannot be panned\r\n * along the domain axis/axes.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isRangePannable()\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isDomainPannable() {\r\n return false;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if panning is enabled for the range axes,\r\n * and <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangePannable(boolean)\r\n * @see #isDomainPannable()\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isRangePannable() {\r\n return this.rangePannable;\r\n }\r\n\r\n /**\r\n * Sets the flag that enables or disables panning of the plot along\r\n * the range axes.\r\n *\r\n * @param pannable the new flag value.\r\n *\r\n * @see #isRangePannable()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangePannable(boolean pannable) {\r\n this.rangePannable = pannable;\r\n }\r\n\r\n /**\r\n * Pans the domain axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panDomainAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n // do nothing, because the plot is not pannable along the domain axes\r\n }\r\n\r\n /**\r\n * Pans the range axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panRangeAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n if (!isRangePannable()) {\r\n return;\r\n }\r\n for (ValueAxis axis : this.rangeAxes.values()) {\r\n if (axis == null) {\r\n continue;\r\n }\r\n double length = axis.getRange().getLength();\r\n double adj = percent * length;\r\n if (axis.isInverted()) {\r\n adj = -adj;\r\n }\r\n axis.setRange(axis.getLowerBound() + adj,\r\n axis.getUpperBound() + adj);\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>false</code> to indicate that the domain axes are not\r\n * zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isRangeZoomable()\r\n */\r\n @Override\r\n public boolean isDomainZoomable() {\r\n return false;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> to indicate that the range axes are zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isDomainZoomable()\r\n */\r\n @Override\r\n public boolean isRangeZoomable() {\r\n return true;\r\n }\r\n\r\n /**\r\n * This method does nothing, because <code>CategoryPlot</code> doesn't\r\n * support zooming on the domain.\r\n *\r\n * @param factor the zoom factor.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D space) for the zoom.\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo state,\r\n Point2D source) {\r\n // can't zoom domain axis\r\n }\r\n\r\n /**\r\n * This method does nothing, because <code>CategoryPlot</code> doesn't\r\n * support zooming on the domain.\r\n *\r\n * @param lowerPercent the lower bound.\r\n * @param upperPercent the upper bound.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D space) for the zoom.\r\n */\r\n @Override\r\n public void zoomDomainAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo state, Point2D source) {\r\n // can't zoom domain axis\r\n }\r\n\r\n /**\r\n * This method does nothing, because <code>CategoryPlot</code> doesn't\r\n * support zooming on the domain.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point (in Java2D space).\r\n * @param useAnchor use source point as zoom anchor?\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n // can't zoom domain axis\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D space) for the zoom.\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo state,\r\n Point2D source) {\r\n // delegate to other method\r\n zoomRangeAxes(factor, state, source, false);\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n * @param useAnchor a flag that controls whether or not the source point\r\n * is used for the zoom anchor.\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n\r\n // perform the zoom on each range axis\r\n for (ValueAxis rangeAxis : this.rangeAxes.values()) {\r\n if (rangeAxis == null) {\r\n continue;\r\n }\r\n if (useAnchor) {\r\n // get the relevant source coordinate given the plot orientation\r\n double sourceY = source.getY();\r\n if (this.orientation.isHorizontal()) {\r\n sourceY = source.getX();\r\n }\r\n double anchorY = rangeAxis.java2DToValue(sourceY,\r\n info.getDataArea(), getRangeAxisEdge());\r\n rangeAxis.resizeRange2(factor, anchorY);\r\n } else {\r\n rangeAxis.resizeRange(factor);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the range axes.\r\n *\r\n * @param lowerPercent the lower bound.\r\n * @param upperPercent the upper bound.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D space) for the zoom.\r\n */\r\n @Override\r\n public void zoomRangeAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo state, Point2D source) {\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.zoomRange(lowerPercent, upperPercent);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the anchor value.\r\n *\r\n * @return The anchor value.\r\n *\r\n * @see #setAnchorValue(double)\r\n */\r\n public double getAnchorValue() {\r\n return this.anchorValue;\r\n }\r\n\r\n /**\r\n * Sets the anchor value and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param value the anchor value.\r\n *\r\n * @see #getAnchorValue()\r\n */\r\n public void setAnchorValue(double value) {\r\n setAnchorValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the anchor value and, if requested, sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param value the value.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getAnchorValue()\r\n */\r\n public void setAnchorValue(double value, boolean notify) {\r\n this.anchorValue = value;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Tests the plot for equality with an arbitrary object.\r\n *\r\n * @param obj the object to test against (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof CategoryPlot)) {\r\n return false;\r\n }\r\n CategoryPlot that = (CategoryPlot) obj;\r\n if (this.orientation != that.orientation) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.axisOffset, that.axisOffset)) {\r\n return false;\r\n }\r\n if (!this.domainAxes.equals(that.domainAxes)) {\r\n return false;\r\n }\r\n if (!this.domainAxisLocations.equals(that.domainAxisLocations)) {\r\n return false;\r\n }\r\n if (this.drawSharedDomainAxis != that.drawSharedDomainAxis) {\r\n return false;\r\n }\r\n if (!this.rangeAxes.equals(that.rangeAxes)) {\r\n return false;\r\n }\r\n if (!this.rangeAxisLocations.equals(that.rangeAxisLocations)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToDomainAxesMap,\r\n that.datasetToDomainAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToRangeAxesMap,\r\n that.datasetToRangeAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.renderers, that.renderers)) {\r\n return false;\r\n }\r\n if (this.renderingOrder != that.renderingOrder) {\r\n return false;\r\n }\r\n if (this.columnRenderingOrder != that.columnRenderingOrder) {\r\n return false;\r\n }\r\n if (this.rowRenderingOrder != that.rowRenderingOrder) {\r\n return false;\r\n }\r\n if (this.domainGridlinesVisible != that.domainGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.domainGridlinePosition != that.domainGridlinePosition) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainGridlineStroke,\r\n that.domainGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainGridlinePaint,\r\n that.domainGridlinePaint)) {\r\n return false;\r\n }\r\n if (this.rangeGridlinesVisible != that.rangeGridlinesVisible) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeGridlineStroke,\r\n that.rangeGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeGridlinePaint,\r\n that.rangeGridlinePaint)) {\r\n return false;\r\n }\r\n if (this.anchorValue != that.anchorValue) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairVisible != that.rangeCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairValue != that.rangeCrosshairValue) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeCrosshairStroke,\r\n that.rangeCrosshairStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeCrosshairPaint,\r\n that.rangeCrosshairPaint)) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairLockedOnData\r\n != that.rangeCrosshairLockedOnData) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundDomainMarkers,\r\n that.foregroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundDomainMarkers,\r\n that.backgroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundRangeMarkers,\r\n that.foregroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundRangeMarkers,\r\n that.backgroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.annotations, that.annotations)) {\r\n return false;\r\n }\r\n if (this.weight != that.weight) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.fixedDomainAxisSpace,\r\n that.fixedDomainAxisSpace)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.fixedRangeAxisSpace,\r\n that.fixedRangeAxisSpace)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.fixedLegendItems,\r\n that.fixedLegendItems)) {\r\n return false;\r\n }\r\n if (this.domainCrosshairVisible != that.domainCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.crosshairDatasetIndex != that.crosshairDatasetIndex) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainCrosshairColumnKey,\r\n that.domainCrosshairColumnKey)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainCrosshairRowKey,\r\n that.domainCrosshairRowKey)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainCrosshairPaint,\r\n that.domainCrosshairPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainCrosshairStroke,\r\n that.domainCrosshairStroke)) {\r\n return false;\r\n }\r\n if (this.rangeMinorGridlinesVisible\r\n != that.rangeMinorGridlinesVisible) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeMinorGridlinePaint,\r\n that.rangeMinorGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeMinorGridlineStroke,\r\n that.rangeMinorGridlineStroke)) {\r\n return false;\r\n }\r\n if (this.rangeZeroBaselineVisible != that.rangeZeroBaselineVisible) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeZeroBaselinePaint,\r\n that.rangeZeroBaselinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeZeroBaselineStroke,\r\n that.rangeZeroBaselineStroke)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.shadowGenerator,\r\n that.shadowGenerator)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a clone of the plot.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the cloning is not supported.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n CategoryPlot clone = (CategoryPlot) super.clone();\r\n clone.domainAxes = CloneUtils.cloneMapValues(this.domainAxes);\r\n for (CategoryAxis axis : clone.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n clone.rangeAxes = CloneUtils.cloneMapValues(this.rangeAxes);\r\n for (ValueAxis axis : clone.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n\r\n // AxisLocation is immutable, so we can just copy the maps\r\n clone.domainAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.domainAxisLocations);\r\n clone.rangeAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.rangeAxisLocations);\r\n\r\n clone.datasets = new HashMap<Integer, CategoryDataset>(this.datasets);\r\n for (CategoryDataset dataset : clone.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(clone);\r\n }\r\n }\r\n clone.datasetToDomainAxesMap = new TreeMap();\r\n clone.datasetToDomainAxesMap.putAll(this.datasetToDomainAxesMap);\r\n clone.datasetToRangeAxesMap = new TreeMap();\r\n clone.datasetToRangeAxesMap.putAll(this.datasetToRangeAxesMap);\r\n\r\n clone.renderers = CloneUtils.cloneMapValues(this.renderers);\r\n for (CategoryItemRenderer renderer : clone.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.setPlot(clone);\r\n renderer.addChangeListener(clone);\r\n }\r\n }\r\n if (this.fixedDomainAxisSpace != null) {\r\n clone.fixedDomainAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedDomainAxisSpace);\r\n }\r\n if (this.fixedRangeAxisSpace != null) {\r\n clone.fixedRangeAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedRangeAxisSpace);\r\n }\r\n\r\n clone.annotations = (List) ObjectUtilities.deepClone(this.annotations);\r\n clone.foregroundDomainMarkers = cloneMarkerMap(\r\n this.foregroundDomainMarkers);\r\n clone.backgroundDomainMarkers = cloneMarkerMap(\r\n this.backgroundDomainMarkers);\r\n clone.foregroundRangeMarkers = cloneMarkerMap(\r\n this.foregroundRangeMarkers);\r\n clone.backgroundRangeMarkers = cloneMarkerMap(\r\n this.backgroundRangeMarkers);\r\n if (this.fixedLegendItems != null) {\r\n clone.fixedLegendItems\r\n = (LegendItemCollection) this.fixedLegendItems.clone();\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * A utility method to clone the marker maps.\r\n *\r\n * @param map the map to clone.\r\n *\r\n * @return A clone of the map.\r\n *\r\n * @throws CloneNotSupportedException if there is some problem cloning the\r\n * map.\r\n */\r\n private Map cloneMarkerMap(Map map) throws CloneNotSupportedException {\r\n Map clone = new HashMap();\r\n Set keys = map.keySet();\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Object key = iterator.next();\r\n List entry = (List) map.get(key);\r\n Object toAdd = ObjectUtilities.deepClone(entry);\r\n clone.put(key, toAdd);\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.domainGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.domainGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.rangeCrosshairPaint, stream);\r\n SerialUtilities.writeStroke(this.domainCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.domainCrosshairPaint, stream);\r\n SerialUtilities.writeStroke(this.rangeMinorGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeMinorGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeZeroBaselineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeZeroBaselinePaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n\r\n stream.defaultReadObject();\r\n this.domainGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.domainGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.rangeCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.domainCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.domainCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.rangeMinorGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeMinorGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeZeroBaselineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeZeroBaselinePaint = SerialUtilities.readPaint(stream);\r\n\r\n for (CategoryAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n xAxis.setPlot(this);\r\n xAxis.addChangeListener(this);\r\n }\r\n }\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.setPlot(this);\r\n yAxis.addChangeListener(this);\r\n }\r\n }\r\n for (CategoryDataset dataset : this.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n }\r\n for (CategoryItemRenderer renderer : this.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.addChangeListener(this);\r\n }\r\n }\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "PlotOrientation", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/PlotOrientation.java", "snippet": "public final class PlotOrientation implements Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -2508771828190337782L;\r\n\r\n /** For a plot where the range axis is horizontal. */\r\n public static final PlotOrientation HORIZONTAL\r\n = new PlotOrientation(\"PlotOrientation.HORIZONTAL\");\r\n\r\n /** For a plot where the range axis is vertical. */\r\n public static final PlotOrientation VERTICAL\r\n = new PlotOrientation(\"PlotOrientation.VERTICAL\");\r\n\r\n /** The name. */\r\n private String name;\r\n\r\n /**\r\n * Private constructor.\r\n *\r\n * @param name the name.\r\n */\r\n private PlotOrientation(String name) {\r\n this.name = name;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this orientation is <code>HORIZONTAL</code>,\r\n * and <code>false</code> otherwise. \r\n * \r\n * @return A boolean.\r\n * \r\n * @since 1.0.18\r\n */\r\n public boolean isHorizontal() {\r\n return this.equals(PlotOrientation.HORIZONTAL);\r\n }\r\n \r\n /**\r\n * Returns <code>true</code> if this orientation is <code>VERTICAL</code>,\r\n * and <code>false</code> otherwise.\r\n * \r\n * @return A boolean.\r\n * \r\n * @since 1.0.18\r\n */\r\n public boolean isVertical() {\r\n return this.equals(PlotOrientation.VERTICAL);\r\n }\r\n \r\n /**\r\n * Returns a string representing the object.\r\n *\r\n * @return The string.\r\n */\r\n @Override\r\n public String toString() {\r\n return this.name;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this object is equal to the specified\r\n * object, and <code>false</code> otherwise.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) {\r\n return true;\r\n }\r\n if (!(obj instanceof PlotOrientation)) {\r\n return false;\r\n }\r\n PlotOrientation orientation = (PlotOrientation) obj;\r\n if (!this.name.equals(orientation.toString())) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code for this instance.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n return this.name.hashCode();\r\n }\r\n\r\n /**\r\n * Ensures that serialization returns the unique instances.\r\n *\r\n * @return The object.\r\n *\r\n * @throws ObjectStreamException if there is a problem.\r\n */\r\n private Object readResolve() throws ObjectStreamException {\r\n Object result = null;\r\n if (this.equals(PlotOrientation.HORIZONTAL)) {\r\n result = PlotOrientation.HORIZONTAL;\r\n }\r\n else if (this.equals(PlotOrientation.VERTICAL)) {\r\n result = PlotOrientation.VERTICAL;\r\n }\r\n return result;\r\n }\r\n\r\n}\r" }, { "identifier": "CategoryItemRenderer", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/renderer/category/CategoryItemRenderer.java", "snippet": "public interface CategoryItemRenderer extends LegendItemSource {\r\n\r\n /**\r\n * Returns the number of passes through the dataset required by the\r\n * renderer. Usually this will be one, but some renderers may use\r\n * a second or third pass to overlay items on top of things that were\r\n * drawn in an earlier pass.\r\n *\r\n * @return The pass count.\r\n */\r\n public int getPassCount();\r\n\r\n /**\r\n * Returns the plot that the renderer has been assigned to (where\r\n * <code>null</code> indicates that the renderer is not currently assigned\r\n * to a plot).\r\n *\r\n * @return The plot (possibly <code>null</code>).\r\n *\r\n * @see #setPlot(CategoryPlot)\r\n */\r\n public CategoryPlot getPlot();\r\n\r\n /**\r\n * Sets the plot that the renderer has been assigned to. This method is\r\n * usually called by the {@link CategoryPlot}, in normal usage you\r\n * shouldn't need to call this method directly.\r\n *\r\n * @param plot the plot (<code>null</code> not permitted).\r\n *\r\n * @see #getPlot()\r\n */\r\n public void setPlot(CategoryPlot plot);\r\n\r\n /**\r\n * Adds a change listener.\r\n *\r\n * @param listener the listener.\r\n *\r\n * @see #removeChangeListener(RendererChangeListener)\r\n */\r\n public void addChangeListener(RendererChangeListener listener);\r\n\r\n /**\r\n * Removes a change listener.\r\n *\r\n * @param listener the listener.\r\n *\r\n * @see #addChangeListener(RendererChangeListener)\r\n */\r\n public void removeChangeListener(RendererChangeListener listener);\r\n\r\n /**\r\n * Returns the range of values the renderer requires to display all the\r\n * items from the specified dataset.\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n *\r\n * @return The range (or <code>null</code> if the dataset is\r\n * <code>null</code> or empty).\r\n */\r\n public Range findRangeBounds(CategoryDataset dataset);\r\n\r\n /**\r\n * Initialises the renderer. This method will be called before the first\r\n * item is rendered, giving the renderer an opportunity to initialise any\r\n * state information it wants to maintain. The renderer can do nothing if\r\n * it chooses.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area inside the axes.\r\n * @param plot the plot.\r\n * @param rendererIndex the renderer index.\r\n * @param info collects chart rendering information for return to caller.\r\n *\r\n * @return A state object (maintains state information relevant to one\r\n * chart drawing).\r\n */\r\n public CategoryItemRendererState initialise(Graphics2D g2,\r\n Rectangle2D dataArea,\r\n CategoryPlot plot,\r\n int rendererIndex,\r\n PlotRenderingInfo info);\r\n\r\n /**\r\n * Returns a boolean that indicates whether or not the specified item\r\n * should be drawn (this is typically used to hide an entire series).\r\n *\r\n * @param series the series index.\r\n * @param item the item index.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean getItemVisible(int series, int item);\r\n\r\n /**\r\n * Returns a boolean that indicates whether or not the specified series\r\n * should be drawn (this is typically used to hide an entire series).\r\n *\r\n * @param series the series index.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean isSeriesVisible(int series);\r\n\r\n /**\r\n * Returns the flag that controls the visibility of ALL series. This flag\r\n * overrides the per series and default settings - you must set it to\r\n * <code>null</code> if you want the other settings to apply.\r\n *\r\n * @return The flag (possibly <code>null</code>).\r\n *\r\n * @see #setSeriesVisible(Boolean)\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #getSeriesVisible(int)} and\r\n * {@link #getBaseSeriesVisible()}.\r\n */\r\n public Boolean getSeriesVisible();\r\n\r\n /**\r\n * Sets the flag that controls the visibility of ALL series and sends a\r\n * {@link RendererChangeEvent} to all registered listeners. This flag\r\n * overrides the per series and default settings - you must set it to\r\n * <code>null</code> if you want the other settings to apply.\r\n *\r\n * @param visible the flag (<code>null</code> permitted).\r\n *\r\n * @see #getSeriesVisible()\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesVisible(int, Boolean)}\r\n * and {@link #setBaseSeriesVisible(boolean)}.\r\n */\r\n public void setSeriesVisible(Boolean visible);\r\n\r\n /**\r\n * Sets the flag that controls the visibility of ALL series and sends a\r\n * {@link RendererChangeEvent} to all registered listeners. This flag\r\n * overrides the per series and default settings - you must set it to\r\n * <code>null</code> if you want the other settings to apply.\r\n *\r\n * @param visible the flag (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getSeriesVisible()\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesVisible(int, Boolean,\r\n * boolean)} and {@link #setBaseSeriesVisible(boolean, boolean)}.\r\n */\r\n public void setSeriesVisible(Boolean visible, boolean notify);\r\n\r\n /**\r\n * Returns the flag that controls whether a series is visible.\r\n *\r\n * @param series the series index (zero-based).\r\n *\r\n * @return The flag (possibly <code>null</code>).\r\n *\r\n * @see #setSeriesVisible(int, Boolean)\r\n */\r\n public Boolean getSeriesVisible(int series);\r\n\r\n /**\r\n * Sets the flag that controls whether a series is visible and sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param visible the flag (<code>null</code> permitted).\r\n *\r\n * @see #getSeriesVisible(int)\r\n */\r\n public void setSeriesVisible(int series, Boolean visible);\r\n\r\n /**\r\n * Sets the flag that controls whether a series is visible and, if\r\n * requested, sends a {@link RendererChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param series the series index.\r\n * @param visible the flag (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getSeriesVisible(int)\r\n */\r\n public void setSeriesVisible(int series, Boolean visible, boolean notify);\r\n\r\n /**\r\n * Returns the base visibility for all series.\r\n *\r\n * @return The base visibility.\r\n *\r\n * @see #setBaseSeriesVisible(boolean)\r\n */\r\n public boolean getBaseSeriesVisible();\r\n\r\n /**\r\n * Sets the base visibility and sends a {@link RendererChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #getBaseSeriesVisible()\r\n */\r\n public void setBaseSeriesVisible(boolean visible);\r\n\r\n /**\r\n * Sets the base visibility and, if requested, sends\r\n * a {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the visibility.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getBaseSeriesVisible()\r\n */\r\n public void setBaseSeriesVisible(boolean visible, boolean notify);\r\n\r\n // SERIES VISIBLE IN LEGEND (not yet respected by all renderers)\r\n\r\n /**\r\n * Returns <code>true</code> if the series should be shown in the legend,\r\n * and <code>false</code> otherwise.\r\n *\r\n * @param series the series index.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean isSeriesVisibleInLegend(int series);\r\n\r\n /**\r\n * Returns the flag that controls the visibility of ALL series in the\r\n * legend. This flag overrides the per series and default settings - you\r\n * must set it to <code>null</code> if you want the other settings to\r\n * apply.\r\n *\r\n * @return The flag (possibly <code>null</code>).\r\n *\r\n * @see #setSeriesVisibleInLegend(Boolean)\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #getSeriesVisibleInLegend(int)}\r\n * and {@link #getBaseSeriesVisibleInLegend()}.\r\n */\r\n public Boolean getSeriesVisibleInLegend();\r\n\r\n /**\r\n * Sets the flag that controls the visibility of ALL series in the legend\r\n * and sends a {@link RendererChangeEvent} to all registered listeners.\r\n * This flag overrides the per series and default settings - you must set\r\n * it to <code>null</code> if you want the other settings to apply.\r\n *\r\n * @param visible the flag (<code>null</code> permitted).\r\n *\r\n * @see #getSeriesVisibleInLegend()\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesVisibleInLegend(int,\r\n * Boolean)} and {@link #setBaseSeriesVisibleInLegend(boolean)}.\r\n */\r\n public void setSeriesVisibleInLegend(Boolean visible);\r\n\r\n /**\r\n * Sets the flag that controls the visibility of ALL series in the legend\r\n * and sends a {@link RendererChangeEvent} to all registered listeners.\r\n * This flag overrides the per series and default settings - you must set\r\n * it to <code>null</code> if you want the other settings to apply.\r\n *\r\n * @param visible the flag (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getSeriesVisibleInLegend()\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesVisibleInLegend(int,\r\n * Boolean, boolean)} and {@link #setBaseSeriesVisibleInLegend(boolean,\r\n * boolean)}.\r\n */\r\n public void setSeriesVisibleInLegend(Boolean visible, boolean notify);\r\n\r\n /**\r\n * Returns the flag that controls whether a series is visible in the\r\n * legend. This method returns only the \"per series\" settings - to\r\n * incorporate the override and base settings as well, you need to use the\r\n * {@link #isSeriesVisibleInLegend(int)} method.\r\n *\r\n * @param series the series index (zero-based).\r\n *\r\n * @return The flag (possibly <code>null</code>).\r\n *\r\n * @see #setSeriesVisibleInLegend(int, Boolean)\r\n */\r\n public Boolean getSeriesVisibleInLegend(int series);\r\n\r\n /**\r\n * Sets the flag that controls whether a series is visible in the legend\r\n * and sends a {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param visible the flag (<code>null</code> permitted).\r\n *\r\n * @see #getSeriesVisibleInLegend(int)\r\n */\r\n public void setSeriesVisibleInLegend(int series, Boolean visible);\r\n\r\n /**\r\n * Sets the flag that controls whether a series is visible in the legend\r\n * and, if requested, sends a {@link RendererChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param series the series index.\r\n * @param visible the flag (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getSeriesVisibleInLegend(int)\r\n */\r\n public void setSeriesVisibleInLegend(int series, Boolean visible,\r\n boolean notify);\r\n\r\n /**\r\n * Returns the base visibility in the legend for all series.\r\n *\r\n * @return The base visibility.\r\n *\r\n * @see #setBaseSeriesVisibleInLegend(boolean)\r\n */\r\n public boolean getBaseSeriesVisibleInLegend();\r\n\r\n /**\r\n * Sets the base visibility in the legend and sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #getBaseSeriesVisibleInLegend()\r\n */\r\n public void setBaseSeriesVisibleInLegend(boolean visible);\r\n\r\n /**\r\n * Sets the base visibility in the legend and, if requested, sends\r\n * a {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the visibility.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getBaseSeriesVisibleInLegend()\r\n */\r\n public void setBaseSeriesVisibleInLegend(boolean visible, boolean notify);\r\n\r\n\r\n //// PAINT /////////////////////////////////////////////////////////////////\r\n\r\n /**\r\n * Returns the paint used to fill data items as they are drawn.\r\n *\r\n * @param row the row (or series) index (zero-based).\r\n * @param column the column (or category) index (zero-based).\r\n *\r\n * @return The paint (never <code>null</code>).\r\n */\r\n public Paint getItemPaint(int row, int column);\r\n\r\n /**\r\n * Sets the paint to be used for ALL series, and sends a\r\n * {@link RendererChangeEvent} to all registered listeners. If this is\r\n * <code>null</code>, the renderer will use the paint for the series.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesPaint(int, Paint)} and\r\n * {@link #setBasePaint(Paint)}.\r\n */\r\n public void setPaint(Paint paint);\r\n\r\n /**\r\n * Returns the paint used to fill an item drawn by the renderer.\r\n *\r\n * @param series the series index (zero-based).\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setSeriesPaint(int, Paint)\r\n */\r\n public Paint getSeriesPaint(int series);\r\n\r\n /**\r\n * Sets the paint used for a series and sends a {@link RendererChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getSeriesPaint(int)\r\n */\r\n public void setSeriesPaint(int series, Paint paint);\r\n\r\n // FIXME: add setSeriesPaint(int, Paint, boolean)?\r\n\r\n /**\r\n * Returns the base paint.\r\n *\r\n * @return The base paint (never <code>null</code>).\r\n *\r\n * @see #setBasePaint(Paint)\r\n */\r\n public Paint getBasePaint();\r\n\r\n /**\r\n * Sets the base paint and sends a {@link RendererChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getBasePaint()\r\n */\r\n public void setBasePaint(Paint paint);\r\n\r\n // FIXME: add setBasePaint(int, Paint, boolean)?\r\n\r\n //// FILL PAINT /////////////////////////////////////////////////////////\r\n\r\n// /**\r\n// * Returns the paint used to fill data items as they are drawn.\r\n// *\r\n// * @param row the row (or series) index (zero-based).\r\n// * @param column the column (or category) index (zero-based).\r\n// *\r\n// * @return The paint (never <code>null</code>).\r\n// */\r\n// public Paint getItemFillPaint(int row, int column);\r\n//\r\n// /**\r\n// * Returns the paint used to fill an item drawn by the renderer.\r\n// *\r\n// * @param series the series (zero-based index).\r\n// *\r\n// * @return The paint (possibly <code>null</code>).\r\n// *\r\n// * @see #setSeriesFillPaint(int, Paint)\r\n// */\r\n// public Paint getSeriesFillPaint(int series);\r\n//\r\n// /**\r\n// * Sets the paint used for a series outline and sends a\r\n// * {@link RendererChangeEvent} to all registered listeners.\r\n// *\r\n// * @param series the series index (zero-based).\r\n// * @param paint the paint (<code>null</code> permitted).\r\n// *\r\n// * @see #getSeriesFillPaint(int)\r\n// */\r\n// public void setSeriesFillPaint(int series, Paint paint);\r\n//\r\n// /**\r\n// * Returns the base outline paint.\r\n// *\r\n// * @return The paint (never <code>null</code>).\r\n// *\r\n// * @see #setBaseFillPaint(Paint)\r\n// */\r\n// public Paint getBaseFillPaint();\r\n//\r\n// /**\r\n// * Sets the base outline paint and sends a {@link RendererChangeEvent} to\r\n// * all registered listeners.\r\n// *\r\n// * @param paint the paint (<code>null</code> not permitted).\r\n// *\r\n// * @see #getBaseFillPaint()\r\n// */\r\n// public void setBaseFillPaint(Paint paint);\r\n\r\n //// OUTLINE PAINT /////////////////////////////////////////////////////////\r\n\r\n /**\r\n * Returns the paint used to outline data items as they are drawn.\r\n *\r\n * @param row the row (or series) index (zero-based).\r\n * @param column the column (or category) index (zero-based).\r\n *\r\n * @return The paint (never <code>null</code>).\r\n */\r\n public Paint getItemOutlinePaint(int row, int column);\r\n\r\n /**\r\n * Sets the outline paint for ALL series (optional).\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesOutlinePaint(int,\r\n * Paint)} and {@link #setBaseOutlinePaint(Paint)}.\r\n */\r\n public void setOutlinePaint(Paint paint);\r\n\r\n /**\r\n * Returns the paint used to outline an item drawn by the renderer.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setSeriesOutlinePaint(int, Paint)\r\n */\r\n public Paint getSeriesOutlinePaint(int series);\r\n\r\n /**\r\n * Sets the paint used for a series outline and sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getSeriesOutlinePaint(int)\r\n */\r\n public void setSeriesOutlinePaint(int series, Paint paint);\r\n\r\n // FIXME: add setSeriesOutlinePaint(int, Paint, boolean)?\r\n\r\n /**\r\n * Returns the base outline paint.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setBaseOutlinePaint(Paint)\r\n */\r\n public Paint getBaseOutlinePaint();\r\n\r\n /**\r\n * Sets the base outline paint and sends a {@link RendererChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getBaseOutlinePaint()\r\n */\r\n public void setBaseOutlinePaint(Paint paint);\r\n\r\n // FIXME: add setBaseOutlinePaint(Paint, boolean)?\r\n\r\n //// STROKE ////////////////////////////////////////////////////////////////\r\n\r\n /**\r\n * Returns the stroke used to draw data items.\r\n *\r\n * @param row the row (or series) index (zero-based).\r\n * @param column the column (or category) index (zero-based).\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n */\r\n public Stroke getItemStroke(int row, int column);\r\n\r\n /**\r\n * Sets the stroke for ALL series and sends a {@link RendererChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> permitted).\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesStroke(int, Stroke)}\r\n * and {@link #setBaseStroke(Stroke)}.\r\n */\r\n public void setStroke(Stroke stroke);\r\n\r\n /**\r\n * Returns the stroke used to draw the items in a series.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setSeriesStroke(int, Stroke)\r\n */\r\n public Stroke getSeriesStroke(int series);\r\n\r\n /**\r\n * Sets the stroke used for a series and sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param stroke the stroke (<code>null</code> permitted).\r\n *\r\n * @see #getSeriesStroke(int)\r\n */\r\n public void setSeriesStroke(int series, Stroke stroke);\r\n\r\n // FIXME: add setSeriesStroke(int, Stroke, boolean) ?\r\n\r\n /**\r\n * Returns the base stroke.\r\n *\r\n * @return The base stroke (never <code>null</code>).\r\n *\r\n * @see #setBaseStroke(Stroke)\r\n */\r\n public Stroke getBaseStroke();\r\n\r\n /**\r\n * Sets the base stroke and sends a {@link RendererChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getBaseStroke()\r\n */\r\n public void setBaseStroke(Stroke stroke);\r\n\r\n // FIXME: add setBaseStroke(Stroke, boolean) ?\r\n\r\n //// OUTLINE STROKE ////////////////////////////////////////////////////////\r\n\r\n /**\r\n * Returns the stroke used to outline data items.\r\n * <p>\r\n * The default implementation passes control to the\r\n * lookupSeriesOutlineStroke method. You can override this method if you\r\n * require different behaviour.\r\n *\r\n * @param row the row (or series) index (zero-based).\r\n * @param column the column (or category) index (zero-based).\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n */\r\n public Stroke getItemOutlineStroke(int row, int column);\r\n\r\n /**\r\n * Sets the outline stroke for ALL series and sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> permitted).\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesOutlineStroke(int,\r\n * Stroke)} and {@link #setBaseOutlineStroke(Stroke)}.\r\n */\r\n public void setOutlineStroke(Stroke stroke);\r\n\r\n /**\r\n * Returns the stroke used to outline the items in a series.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The stroke (possibly <code>null</code>).\r\n *\r\n * @see #setSeriesOutlineStroke(int, Stroke)\r\n */\r\n public Stroke getSeriesOutlineStroke(int series);\r\n\r\n /**\r\n * Sets the outline stroke used for a series and sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param stroke the stroke (<code>null</code> permitted).\r\n *\r\n * @see #getSeriesOutlineStroke(int)\r\n */\r\n public void setSeriesOutlineStroke(int series, Stroke stroke);\r\n\r\n // FIXME: add setSeriesOutlineStroke(int, Stroke, boolean) ?\r\n\r\n /**\r\n * Returns the base outline stroke.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setBaseOutlineStroke(Stroke)\r\n */\r\n public Stroke getBaseOutlineStroke();\r\n\r\n /**\r\n * Sets the base outline stroke and sends a {@link RendererChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getBaseOutlineStroke()\r\n */\r\n public void setBaseOutlineStroke(Stroke stroke);\r\n\r\n // FIXME: add setBaseOutlineStroke(Stroke, boolean) ?\r\n\r\n //// SHAPE /////////////////////////////////////////////////////////////////\r\n\r\n /**\r\n * Returns a shape used to represent a data item.\r\n *\r\n * @param row the row (or series) index (zero-based).\r\n * @param column the column (or category) index (zero-based).\r\n *\r\n * @return The shape (never <code>null</code>).\r\n */\r\n public Shape getItemShape(int row, int column);\r\n\r\n /**\r\n * Sets the shape for ALL series (optional) and sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param shape the shape (<code>null</code> permitted).\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesShape(int, Shape)} and\r\n * {@link #setBaseShape(Shape)}.\r\n */\r\n public void setShape(Shape shape);\r\n\r\n /**\r\n * Returns a shape used to represent the items in a series.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The shape (possibly <code>null</code>).\r\n *\r\n * @see #setSeriesShape(int, Shape)\r\n */\r\n public Shape getSeriesShape(int series);\r\n\r\n /**\r\n * Sets the shape used for a series and sends a {@link RendererChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param shape the shape (<code>null</code> permitted).\r\n *\r\n * @see #getSeriesShape(int)\r\n */\r\n public void setSeriesShape(int series, Shape shape);\r\n\r\n // FIXME: add setSeriesShape(int, Shape, boolean) ?\r\n\r\n /**\r\n * Returns the base shape.\r\n *\r\n * @return The shape (never <code>null</code>).\r\n *\r\n * @see #setBaseShape(Shape)\r\n */\r\n public Shape getBaseShape();\r\n\r\n /**\r\n * Sets the base shape and sends a {@link RendererChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param shape the shape (<code>null</code> not permitted).\r\n *\r\n * @see #getBaseShape()\r\n */\r\n public void setBaseShape(Shape shape);\r\n\r\n // FIXME: add setBaseShape(Shape, boolean) ?\r\n\r\n // ITEM LABELS VISIBLE\r\n\r\n /**\r\n * Returns <code>true</code> if an item label is visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @param row the row index (zero-based).\r\n * @param column the column index (zero-based).\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean isItemLabelVisible(int row, int column);\r\n\r\n /**\r\n * Sets a flag that controls whether or not the item labels for ALL series\r\n * are visible.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #setItemLabelsVisible(Boolean)\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesItemLabelsVisible(int,\r\n * Boolean)} and {@link #setBaseItemLabelsVisible(boolean)}.\r\n */\r\n public void setItemLabelsVisible(boolean visible);\r\n\r\n /**\r\n * Sets a flag that controls whether or not the item labels for ALL series\r\n * are visible.\r\n *\r\n * @param visible the flag (<code>null</code> permitted).\r\n *\r\n * @see #setItemLabelsVisible(boolean)\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesItemLabelsVisible(int,\r\n * Boolean)} and {@link #setBaseItemLabelsVisible(boolean)}.\r\n */\r\n public void setItemLabelsVisible(Boolean visible);\r\n\r\n /**\r\n * Sets the visibility of item labels for ALL series and, if requested,\r\n * sends a {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param visible a flag that controls whether or not the item labels are\r\n * visible (<code>null</code> permitted).\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesItemLabelsVisible(int,\r\n * Boolean, boolean)} and {@link #setBaseItemLabelsVisible(Boolean,\r\n * boolean)}.\r\n */\r\n public void setItemLabelsVisible(Boolean visible, boolean notify);\r\n\r\n /**\r\n * Returns <code>true</code> if the item labels for a series are visible,\r\n * and <code>false</code> otherwise.\r\n *\r\n * @param series the series index (zero-based).\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setSeriesItemLabelsVisible(int, Boolean)\r\n */\r\n public boolean isSeriesItemLabelsVisible(int series);\r\n\r\n /**\r\n * Sets a flag that controls the visibility of the item labels for a series.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param visible the flag.\r\n *\r\n * @see #isSeriesItemLabelsVisible(int)\r\n */\r\n public void setSeriesItemLabelsVisible(int series, boolean visible);\r\n\r\n /**\r\n * Sets a flag that controls the visibility of the item labels for a series.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param visible the flag (<code>null</code> permitted).\r\n *\r\n * @see #isSeriesItemLabelsVisible(int)\r\n */\r\n public void setSeriesItemLabelsVisible(int series, Boolean visible);\r\n\r\n /**\r\n * Sets the visibility of item labels for a series and, if requested, sends\r\n * a {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param visible the visible flag.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n *\r\n * @see #isSeriesItemLabelsVisible(int)\r\n */\r\n public void setSeriesItemLabelsVisible(int series, Boolean visible,\r\n boolean notify);\r\n\r\n /**\r\n * Returns the base setting for item label visibility. A <code>null</code>\r\n * result should be interpreted as equivalent to <code>Boolean.FALSE</code>\r\n * (this is an error in the API design, the return value should have been\r\n * a boolean primitive).\r\n *\r\n * @return A flag (possibly <code>null</code>).\r\n *\r\n * @see #setBaseItemLabelsVisible(Boolean)\r\n */\r\n public Boolean getBaseItemLabelsVisible();\r\n\r\n /**\r\n * Sets the base flag that controls whether or not item labels are visible\r\n * and sends a {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #getBaseItemLabelsVisible()\r\n */\r\n public void setBaseItemLabelsVisible(boolean visible);\r\n\r\n /**\r\n * Sets the base setting for item label visibility and sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the flag (<code>null</code> permitted).\r\n *\r\n * @see #getBaseItemLabelsVisible()\r\n */\r\n public void setBaseItemLabelsVisible(Boolean visible);\r\n\r\n /**\r\n * Sets the base visibility for item labels and, if requested, sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the visibility flag.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n *\r\n * @see #getBaseItemLabelsVisible()\r\n */\r\n public void setBaseItemLabelsVisible(Boolean visible, boolean notify);\r\n\r\n // ITEM LABEL GENERATOR\r\n\r\n /**\r\n * Returns the item label generator for the specified data item.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param item the item index (zero-based).\r\n *\r\n * @return The generator (possibly <code>null</code>).\r\n */\r\n public CategoryItemLabelGenerator getItemLabelGenerator(int series,\r\n int item);\r\n\r\n /**\r\n * Sets the item label generator for ALL series and sends a\r\n * {@link RendererChangeEvent} to all registered listeners. This overrides\r\n * the per-series settings.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesItemLabelGenerator(int,\r\n * CategoryItemLabelGenerator)} and\r\n * {@link #setBaseItemLabelGenerator(CategoryItemLabelGenerator)}.\r\n */\r\n public void setItemLabelGenerator(CategoryItemLabelGenerator generator);\r\n\r\n /**\r\n * Returns the item label generator for a series.\r\n *\r\n * @param series the series index (zero-based).\r\n *\r\n * @return The label generator (possibly <code>null</code>).\r\n *\r\n * @see #setSeriesItemLabelGenerator(int, CategoryItemLabelGenerator)\r\n */\r\n public CategoryItemLabelGenerator getSeriesItemLabelGenerator(int series);\r\n\r\n /**\r\n * Sets the item label generator for a series and sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param generator the generator.\r\n *\r\n * @see #getSeriesItemLabelGenerator(int)\r\n */\r\n public void setSeriesItemLabelGenerator(int series,\r\n CategoryItemLabelGenerator generator);\r\n\r\n // FIXME: add setSeriesItemLabelGenerator(int, CategoryItemLabelGenerator,\r\n // boolean)\r\n\r\n /**\r\n * Returns the base item label generator.\r\n *\r\n * @return The generator (possibly <code>null</code>).\r\n *\r\n * @see #setBaseItemLabelGenerator(CategoryItemLabelGenerator)\r\n */\r\n public CategoryItemLabelGenerator getBaseItemLabelGenerator();\r\n\r\n /**\r\n * Sets the base item label generator and sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @see #getBaseItemLabelGenerator()\r\n */\r\n public void setBaseItemLabelGenerator(CategoryItemLabelGenerator generator);\r\n\r\n // FIXME: add setBaseItemLabelGenerator(CategoryItemLabelGenerator,\r\n // boolean) ?\r\n\r\n // TOOL TIP GENERATOR\r\n\r\n /**\r\n * Returns the tool tip generator that should be used for the specified\r\n * item. This method looks up the generator using the \"three-layer\"\r\n * approach outlined in the general description of this interface.\r\n *\r\n * @param row the row index (zero-based).\r\n * @param column the column index (zero-based).\r\n *\r\n * @return The generator (possibly <code>null</code>).\r\n */\r\n public CategoryToolTipGenerator getToolTipGenerator(int row, int column);\r\n\r\n /**\r\n * Returns the tool tip generator that will be used for ALL items in the\r\n * dataset (the \"layer 0\" generator).\r\n *\r\n * @return A tool tip generator (possibly <code>null</code>).\r\n *\r\n * @see #setToolTipGenerator(CategoryToolTipGenerator)\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #getSeriesToolTipGenerator(int)}\r\n * and {@link #getBaseToolTipGenerator()}.\r\n */\r\n public CategoryToolTipGenerator getToolTipGenerator();\r\n\r\n /**\r\n * Sets the tool tip generator for ALL series and sends a\r\n * {@link org.jfree.chart.event.RendererChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @see #getToolTipGenerator()\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesToolTipGenerator(int,\r\n * CategoryToolTipGenerator)} and\r\n * {@link #setBaseToolTipGenerator(CategoryToolTipGenerator)}.\r\n */\r\n public void setToolTipGenerator(CategoryToolTipGenerator generator);\r\n\r\n /**\r\n * Returns the tool tip generator for the specified series (a \"layer 1\"\r\n * generator).\r\n *\r\n * @param series the series index (zero-based).\r\n *\r\n * @return The tool tip generator (possibly <code>null</code>).\r\n *\r\n * @see #setSeriesToolTipGenerator(int, CategoryToolTipGenerator)\r\n */\r\n public CategoryToolTipGenerator getSeriesToolTipGenerator(int series);\r\n\r\n /**\r\n * Sets the tool tip generator for a series and sends a\r\n * {@link org.jfree.chart.event.RendererChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @see #getSeriesToolTipGenerator(int)\r\n */\r\n public void setSeriesToolTipGenerator(int series,\r\n CategoryToolTipGenerator generator);\r\n\r\n // FIXME: add setSeriesToolTipGenerator(int, CategoryToolTipGenerator,\r\n // boolean) ?\r\n\r\n /**\r\n * Returns the base tool tip generator (the \"layer 2\" generator).\r\n *\r\n * @return The tool tip generator (possibly <code>null</code>).\r\n *\r\n * @see #setBaseToolTipGenerator(CategoryToolTipGenerator)\r\n */\r\n public CategoryToolTipGenerator getBaseToolTipGenerator();\r\n\r\n /**\r\n * Sets the base tool tip generator and sends a\r\n * {@link org.jfree.chart.event.RendererChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @see #getBaseToolTipGenerator()\r\n */\r\n public void setBaseToolTipGenerator(CategoryToolTipGenerator generator);\r\n\r\n // FIXME: add setBaseToolTipGenerator(CategoryToolTipGenerator, boolean) ?\r\n\r\n //// ITEM LABEL FONT //////////////////////////////////////////////////////\r\n\r\n /**\r\n * Returns the font for an item label.\r\n *\r\n * @param row the row index (zero-based).\r\n * @param column the column index (zero-based).\r\n *\r\n * @return The font (never <code>null</code>).\r\n */\r\n public Font getItemLabelFont(int row, int column);\r\n\r\n /**\r\n * Returns the font used for all item labels. This may be\r\n * <code>null</code>, in which case the per series font settings will apply.\r\n *\r\n * @return The font (possibly <code>null</code>).\r\n *\r\n * @see #setItemLabelFont(Font)\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #getSeriesItemLabelFont(int)} and\r\n * {@link #getBaseItemLabelFont()}.\r\n */\r\n public Font getItemLabelFont();\r\n\r\n /**\r\n * Sets the item label font for ALL series and sends a\r\n * {@link RendererChangeEvent} to all registered listeners. You can set\r\n * this to <code>null</code> if you prefer to set the font on a per series\r\n * basis.\r\n *\r\n * @param font the font (<code>null</code> permitted).\r\n *\r\n * @see #getItemLabelFont()\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesItemLabelFont(int,\r\n * Font)} and {@link #setBaseItemLabelFont(Font)}.\r\n */\r\n public void setItemLabelFont(Font font);\r\n\r\n /**\r\n * Returns the font for all the item labels in a series.\r\n *\r\n * @param series the series index (zero-based).\r\n *\r\n * @return The font (possibly <code>null</code>).\r\n *\r\n * @see #setSeriesItemLabelFont(int, Font)\r\n */\r\n public Font getSeriesItemLabelFont(int series);\r\n\r\n /**\r\n * Sets the item label font for a series and sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param font the font (<code>null</code> permitted).\r\n *\r\n * @see #getSeriesItemLabelFont(int)\r\n */\r\n public void setSeriesItemLabelFont(int series, Font font);\r\n\r\n // FIXME: add setSeriesItemLabelFont(int, Font, boolean) ?\r\n\r\n /**\r\n * Returns the base item label font (this is used when no other font\r\n * setting is available).\r\n *\r\n * @return The font (<code>never</code> null).\r\n *\r\n * @see #setBaseItemLabelFont(Font)\r\n */\r\n public Font getBaseItemLabelFont();\r\n\r\n /**\r\n * Sets the base item label font and sends a {@link RendererChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param font the font (<code>null</code> not permitted).\r\n *\r\n * @see #getBaseItemLabelFont()\r\n */\r\n public void setBaseItemLabelFont(Font font);\r\n\r\n // FIXME: add setBaseItemLabelFont(Font, boolean) ?\r\n\r\n //// ITEM LABEL PAINT /////////////////////////////////////////////////////\r\n\r\n /**\r\n * Returns the paint used to draw an item label.\r\n *\r\n * @param row the row index (zero based).\r\n * @param column the column index (zero based).\r\n *\r\n * @return The paint (never <code>null</code>).\r\n */\r\n public Paint getItemLabelPaint(int row, int column);\r\n\r\n /**\r\n * Returns the paint used for all item labels. This may be\r\n * <code>null</code>, in which case the per series paint settings will\r\n * apply.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setItemLabelPaint(Paint)\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #getSeriesItemLabelPaint(int)}\r\n * and {@link #getBaseItemLabelPaint()}.\r\n */\r\n public Paint getItemLabelPaint();\r\n\r\n /**\r\n * Sets the item label paint for ALL series and sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getItemLabelPaint()\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesItemLabelPaint(int,\r\n * Paint)} and {@link #setBaseItemLabelPaint(Paint)}.\r\n */\r\n public void setItemLabelPaint(Paint paint);\r\n\r\n /**\r\n * Returns the paint used to draw the item labels for a series.\r\n *\r\n * @param series the series index (zero based).\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setSeriesItemLabelPaint(int, Paint)\r\n */\r\n public Paint getSeriesItemLabelPaint(int series);\r\n\r\n /**\r\n * Sets the item label paint for a series and sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series (zero based index).\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getSeriesItemLabelPaint(int)\r\n */\r\n public void setSeriesItemLabelPaint(int series, Paint paint);\r\n\r\n // FIXME: add setSeriesItemLabelPaint(int, Paint, boolean) ?\r\n\r\n /**\r\n * Returns the base item label paint.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setBaseItemLabelPaint(Paint)\r\n */\r\n public Paint getBaseItemLabelPaint();\r\n\r\n /**\r\n * Sets the base item label paint and sends a {@link RendererChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getBaseItemLabelPaint()\r\n */\r\n public void setBaseItemLabelPaint(Paint paint);\r\n\r\n // FIXME: add setBaseItemLabelPaint(Paint, boolean) ?\r\n\r\n // POSITIVE ITEM LABEL POSITION...\r\n\r\n /**\r\n * Returns the item label position for positive values.\r\n *\r\n * @param row the row index (zero-based).\r\n * @param column the column index (zero-based).\r\n *\r\n * @return The item label position (never <code>null</code>).\r\n */\r\n public ItemLabelPosition getPositiveItemLabelPosition(int row, int column);\r\n\r\n /**\r\n * Returns the item label position for positive values in ALL series.\r\n *\r\n * @return The item label position (possibly <code>null</code>).\r\n *\r\n * @see #setPositiveItemLabelPosition(ItemLabelPosition)\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on\r\n * {@link #getSeriesPositiveItemLabelPosition(int)}\r\n * and {@link #getBasePositiveItemLabelPosition()}.\r\n */\r\n public ItemLabelPosition getPositiveItemLabelPosition();\r\n\r\n /**\r\n * Sets the item label position for positive values in ALL series, and\r\n * sends a {@link RendererChangeEvent} to all registered listeners. You\r\n * need to set this to <code>null</code> to expose the settings for\r\n * individual series.\r\n *\r\n * @param position the position (<code>null</code> permitted).\r\n *\r\n * @see #getPositiveItemLabelPosition()\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on\r\n * {@link #setSeriesPositiveItemLabelPosition(int, ItemLabelPosition)}\r\n * and {@link #setBasePositiveItemLabelPosition(ItemLabelPosition)}.\r\n */\r\n public void setPositiveItemLabelPosition(ItemLabelPosition position);\r\n\r\n /**\r\n * Sets the positive item label position for ALL series and (if requested)\r\n * sends a {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param position the position (<code>null</code> permitted).\r\n * @param notify notify registered listeners?\r\n *\r\n * @see #getPositiveItemLabelPosition()\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on\r\n * {@link #setSeriesPositiveItemLabelPosition(int, ItemLabelPosition,\r\n * boolean)} and {@link #setBasePositiveItemLabelPosition(\r\n * ItemLabelPosition, boolean)}.\r\n */\r\n public void setPositiveItemLabelPosition(ItemLabelPosition position,\r\n boolean notify);\r\n\r\n /**\r\n * Returns the item label position for all positive values in a series.\r\n *\r\n * @param series the series index (zero-based).\r\n *\r\n * @return The item label position.\r\n *\r\n * @see #setSeriesPositiveItemLabelPosition(int, ItemLabelPosition)\r\n */\r\n public ItemLabelPosition getSeriesPositiveItemLabelPosition(int series);\r\n\r\n /**\r\n * Sets the item label position for all positive values in a series and\r\n * sends a {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param position the position (<code>null</code> permitted).\r\n *\r\n * @see #getSeriesPositiveItemLabelPosition(int)\r\n */\r\n public void setSeriesPositiveItemLabelPosition(int series,\r\n ItemLabelPosition position);\r\n\r\n /**\r\n * Sets the item label position for all positive values in a series and (if\r\n * requested) sends a {@link RendererChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param position the position (<code>null</code> permitted).\r\n * @param notify notify registered listeners?\r\n *\r\n * @see #getSeriesPositiveItemLabelPosition(int)\r\n */\r\n public void setSeriesPositiveItemLabelPosition(int series,\r\n ItemLabelPosition position, boolean notify);\r\n\r\n /**\r\n * Returns the base positive item label position.\r\n *\r\n * @return The position.\r\n *\r\n * @see #setBasePositiveItemLabelPosition(ItemLabelPosition)\r\n */\r\n public ItemLabelPosition getBasePositiveItemLabelPosition();\r\n\r\n /**\r\n * Sets the base positive item label position.\r\n *\r\n * @param position the position.\r\n *\r\n * @see #getBasePositiveItemLabelPosition()\r\n */\r\n public void setBasePositiveItemLabelPosition(ItemLabelPosition position);\r\n\r\n /**\r\n * Sets the base positive item label position and, if requested, sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param position the position.\r\n * @param notify notify registered listeners?\r\n *\r\n * @see #getBasePositiveItemLabelPosition()\r\n */\r\n public void setBasePositiveItemLabelPosition(ItemLabelPosition position,\r\n boolean notify);\r\n\r\n\r\n // NEGATIVE ITEM LABEL POSITION...\r\n\r\n /**\r\n * Returns the item label position for negative values. This method can be\r\n * overridden to provide customisation of the item label position for\r\n * individual data items.\r\n *\r\n * @param row the row index (zero-based).\r\n * @param column the column (zero-based).\r\n *\r\n * @return The item label position.\r\n */\r\n public ItemLabelPosition getNegativeItemLabelPosition(int row, int column);\r\n\r\n /**\r\n * Returns the item label position for negative values in ALL series.\r\n *\r\n * @return The item label position (possibly <code>null</code>).\r\n *\r\n * @see #setNegativeItemLabelPosition(ItemLabelPosition)\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on\r\n * {@link #getSeriesNegativeItemLabelPosition(int)}\r\n * and {@link #getBaseNegativeItemLabelPosition()}.\r\n */\r\n public ItemLabelPosition getNegativeItemLabelPosition();\r\n\r\n /**\r\n * Sets the item label position for negative values in ALL series, and\r\n * sends a {@link RendererChangeEvent} to all registered listeners. You\r\n * need to set this to <code>null</code> to expose the settings for\r\n * individual series.\r\n *\r\n * @param position the position (<code>null</code> permitted).\r\n *\r\n * @see #getNegativeItemLabelPosition()\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on\r\n * {@link #setSeriesNegativeItemLabelPosition(int, ItemLabelPosition)}\r\n * and {@link #setBaseNegativeItemLabelPosition(ItemLabelPosition)}.\r\n */\r\n public void setNegativeItemLabelPosition(ItemLabelPosition position);\r\n\r\n /**\r\n * Sets the item label position for negative values in ALL series and (if\r\n * requested) sends a {@link RendererChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param position the position (<code>null</code> permitted).\r\n * @param notify notify registered listeners?\r\n *\r\n * @see #getNegativeItemLabelPosition()\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on\r\n * {@link #setSeriesNegativeItemLabelPosition(int, ItemLabelPosition,\r\n * boolean)} and {@link #setBaseNegativeItemLabelPosition(\r\n * ItemLabelPosition, boolean)}.\r\n */\r\n public void setNegativeItemLabelPosition(ItemLabelPosition position,\r\n boolean notify);\r\n\r\n /**\r\n * Returns the item label position for all negative values in a series.\r\n *\r\n * @param series the series index (zero-based).\r\n *\r\n * @return The item label position.\r\n *\r\n * @see #setSeriesNegativeItemLabelPosition(int, ItemLabelPosition)\r\n */\r\n public ItemLabelPosition getSeriesNegativeItemLabelPosition(int series);\r\n\r\n /**\r\n * Sets the item label position for negative values in a series and sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param position the position (<code>null</code> permitted).\r\n *\r\n * @see #getSeriesNegativeItemLabelPosition(int)\r\n */\r\n public void setSeriesNegativeItemLabelPosition(int series,\r\n ItemLabelPosition position);\r\n\r\n /**\r\n * Sets the item label position for negative values in a series and (if\r\n * requested) sends a {@link RendererChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param position the position (<code>null</code> permitted).\r\n * @param notify notify registered listeners?\r\n *\r\n * @see #getSeriesNegativeItemLabelPosition(int)\r\n */\r\n public void setSeriesNegativeItemLabelPosition(int series,\r\n ItemLabelPosition position,\r\n boolean notify);\r\n\r\n /**\r\n * Returns the base item label position for negative values.\r\n *\r\n * @return The position.\r\n *\r\n * @see #setBaseNegativeItemLabelPosition(ItemLabelPosition)\r\n */\r\n public ItemLabelPosition getBaseNegativeItemLabelPosition();\r\n\r\n /**\r\n * Sets the base item label position for negative values and sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param position the position.\r\n *\r\n * @see #getBaseNegativeItemLabelPosition()\r\n */\r\n public void setBaseNegativeItemLabelPosition(ItemLabelPosition position);\r\n\r\n /**\r\n * Sets the base negative item label position and, if requested, sends a\r\n * {@link RendererChangeEvent} to all registered listeners.\r\n *\r\n * @param position the position.\r\n * @param notify notify registered listeners?\r\n *\r\n * @see #getBaseNegativeItemLabelPosition()\r\n */\r\n public void setBaseNegativeItemLabelPosition(ItemLabelPosition position,\r\n boolean notify);\r\n\r\n // CREATE ENTITIES\r\n // FIXME: these methods should be defined\r\n\r\n// public boolean getItemCreateEntity(int series, int item);\r\n//\r\n// public Boolean getSeriesCreateEntities(int series);\r\n//\r\n// public void setSeriesCreateEntities(int series, Boolean create);\r\n//\r\n// public void setSeriesCreateEntities(int series, Boolean create,\r\n// boolean notify);\r\n//\r\n// public boolean getBaseCreateEntities();\r\n//\r\n// public void setBaseCreateEntities(boolean create);\r\n//\r\n// public void setBaseCreateEntities(boolean create, boolean notify);\r\n\r\n\r\n // ITEM URL GENERATOR\r\n\r\n /**\r\n * Returns the URL generator for an item.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param item the item index (zero-based).\r\n *\r\n * @return The item URL generator.\r\n */\r\n public CategoryURLGenerator getItemURLGenerator(int series, int item);\r\n\r\n /**\r\n * Sets the item URL generator for ALL series.\r\n *\r\n * @param generator the generator.\r\n *\r\n * @see #getSeriesItemURLGenerator(int)\r\n *\r\n * @deprecated This method should no longer be used (as of version 1.0.6).\r\n * It is sufficient to rely on {@link #setSeriesItemURLGenerator(int,\r\n * CategoryURLGenerator)} and\r\n * {@link #setBaseItemURLGenerator(CategoryURLGenerator)}.\r\n */\r\n public void setItemURLGenerator(CategoryURLGenerator generator);\r\n\r\n /**\r\n * Returns the item URL generator for a series.\r\n *\r\n * @param series the series index (zero-based).\r\n *\r\n * @return The URL generator.\r\n *\r\n * @see #setSeriesItemURLGenerator(int, CategoryURLGenerator)\r\n */\r\n public CategoryURLGenerator getSeriesItemURLGenerator(int series);\r\n\r\n /**\r\n * Sets the item URL generator for a series.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param generator the generator.\r\n *\r\n * @see #getSeriesItemURLGenerator(int)\r\n */\r\n public void setSeriesItemURLGenerator(int series,\r\n CategoryURLGenerator generator);\r\n\r\n // FIXME: add setSeriesItemURLGenerator(int, CategoryURLGenerator, boolean)?\r\n\r\n /**\r\n * Returns the base item URL generator.\r\n *\r\n * @return The item URL generator (possibly <code>null</code>).\r\n *\r\n * @see #setBaseItemURLGenerator(CategoryURLGenerator)\r\n */\r\n public CategoryURLGenerator getBaseItemURLGenerator();\r\n\r\n /**\r\n * Sets the base item URL generator and sends a {@link RendererChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param generator the item URL generator (<code>null</code> permitted).\r\n *\r\n * @see #getBaseItemURLGenerator()\r\n */\r\n public void setBaseItemURLGenerator(CategoryURLGenerator generator);\r\n\r\n // FIXME: add setBaseItemURLGenerator(CategoryURLGenerator, boolean) ?\r\n\r\n /**\r\n * Returns a legend item for a series. This method can return\r\n * <code>null</code>, in which case the series will have no entry in the\r\n * legend.\r\n *\r\n * @param datasetIndex the dataset index (zero-based).\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The legend item (possibly <code>null</code>).\r\n */\r\n public LegendItem getLegendItem(int datasetIndex, int series);\r\n\r\n /**\r\n * Draws a background for the data area.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plot the plot.\r\n * @param dataArea the data area.\r\n */\r\n public void drawBackground(Graphics2D g2, CategoryPlot plot,\r\n Rectangle2D dataArea);\r\n\r\n /**\r\n * Draws an outline for the data area.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plot the plot.\r\n * @param dataArea the data area.\r\n */\r\n public void drawOutline(Graphics2D g2, CategoryPlot plot,\r\n Rectangle2D dataArea);\r\n\r\n /**\r\n * Draws a single data item.\r\n *\r\n * @param g2 the graphics device.\r\n * @param state state information for one chart.\r\n * @param dataArea the data plot area.\r\n * @param plot the plot.\r\n * @param domainAxis the domain axis.\r\n * @param rangeAxis the range axis.\r\n * @param dataset the data.\r\n * @param row the row index (zero-based).\r\n * @param column the column index (zero-based).\r\n * @param pass the pass index.\r\n */\r\n public void drawItem(Graphics2D g2, CategoryItemRendererState state,\r\n Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis,\r\n ValueAxis rangeAxis, CategoryDataset dataset, int row, int column,\r\n int pass);\r\n\r\n /**\r\n * Draws a grid line against the domain axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plot the plot.\r\n * @param dataArea the area for plotting data (not yet adjusted for any\r\n * 3D effect).\r\n * @param value the value.\r\n *\r\n * @see #drawRangeGridline(Graphics2D, CategoryPlot, ValueAxis,\r\n * Rectangle2D, double)\r\n */\r\n public void drawDomainGridline(Graphics2D g2, CategoryPlot plot,\r\n Rectangle2D dataArea, double value);\r\n\r\n /**\r\n * Draws a grid line against the range axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plot the plot.\r\n * @param axis the value axis.\r\n * @param dataArea the area for plotting data (not yet adjusted for any\r\n * 3D effect).\r\n * @param value the value.\r\n *\r\n * @see #drawDomainGridline(Graphics2D, CategoryPlot, Rectangle2D, double)\r\n */\r\n public void drawRangeGridline(Graphics2D g2, CategoryPlot plot,\r\n ValueAxis axis, Rectangle2D dataArea, double value);\r\n\r\n /**\r\n * Draws a line (or some other marker) to indicate a particular category on\r\n * the domain axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plot the plot.\r\n * @param axis the category axis.\r\n * @param marker the marker.\r\n * @param dataArea the area for plotting data (not including 3D effect).\r\n *\r\n * @see #drawRangeMarker(Graphics2D, CategoryPlot, ValueAxis, Marker,\r\n * Rectangle2D)\r\n */\r\n public void drawDomainMarker(Graphics2D g2, CategoryPlot plot,\r\n CategoryAxis axis, CategoryMarker marker, Rectangle2D dataArea);\r\n\r\n /**\r\n * Draws a line (or some other marker) to indicate a particular value on\r\n * the range axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plot the plot.\r\n * @param axis the value axis.\r\n * @param marker the marker.\r\n * @param dataArea the area for plotting data (not including 3D effect).\r\n *\r\n * @see #drawDomainMarker(Graphics2D, CategoryPlot, CategoryAxis,\r\n * CategoryMarker, Rectangle2D)\r\n */\r\n public void drawRangeMarker(Graphics2D g2, CategoryPlot plot,\r\n ValueAxis axis, Marker marker, Rectangle2D dataArea);\r\n\r\n /**\r\n * Returns the Java2D coordinate for the middle of the specified data item.\r\n *\r\n * @param rowKey the row key.\r\n * @param columnKey the column key.\r\n * @param dataset the dataset.\r\n * @param axis the axis.\r\n * @param area the data area.\r\n * @param edge the edge along which the axis lies.\r\n *\r\n * @return The Java2D coordinate for the middle of the item.\r\n *\r\n * @since 1.0.11\r\n */\r\n public double getItemMiddle(Comparable rowKey, Comparable columnKey,\r\n CategoryDataset dataset, CategoryAxis axis, Rectangle2D area,\r\n RectangleEdge edge);\r\n\r\n}\r" }, { "identifier": "CategoryURLGenerator", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/urls/CategoryURLGenerator.java", "snippet": "public interface CategoryURLGenerator {\r\n\r\n /**\r\n * Returns a URL for one item in a dataset. As a guideline, the URL\r\n * should be valid within the context of an XHTML 1.0 document. Classes\r\n * that implement this interface are responsible for correctly escaping\r\n * any text that is derived from the dataset, as this may be user-specified\r\n * and could pose a security risk.\r\n *\r\n * @param dataset the dataset.\r\n * @param series the series (zero-based index).\r\n * @param category the category.\r\n *\r\n * @return A string containing the URL.\r\n */\r\n public String generateURL(CategoryDataset dataset, int series,\r\n int category);\r\n\r\n}\r" }, { "identifier": "StandardCategoryURLGenerator", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/urls/StandardCategoryURLGenerator.java", "snippet": "public class StandardCategoryURLGenerator implements CategoryURLGenerator,\r\n Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 2276668053074881909L;\r\n\r\n /** Prefix to the URL */\r\n private String prefix = \"index.html\";\r\n\r\n /** Series parameter name to go in each URL */\r\n private String seriesParameterName = \"series\";\r\n\r\n /** Category parameter name to go in each URL */\r\n private String categoryParameterName = \"category\";\r\n\r\n /**\r\n * Creates a new generator with default settings.\r\n */\r\n public StandardCategoryURLGenerator() {\r\n super();\r\n }\r\n\r\n /**\r\n * Constructor that overrides default prefix to the URL.\r\n *\r\n * @param prefix the prefix to the URL (<code>null</code> not permitted).\r\n */\r\n public StandardCategoryURLGenerator(String prefix) {\r\n ParamChecks.nullNotPermitted(prefix, \"prefix\");\r\n this.prefix = prefix;\r\n }\r\n\r\n /**\r\n * Constructor that overrides all the defaults.\r\n *\r\n * @param prefix the prefix to the URL (<code>null</code> not permitted).\r\n * @param seriesParameterName the name of the series parameter to go in\r\n * each URL (<code>null</code> not permitted).\r\n * @param categoryParameterName the name of the category parameter to go in\r\n * each URL (<code>null</code> not permitted).\r\n */\r\n public StandardCategoryURLGenerator(String prefix, \r\n String seriesParameterName, String categoryParameterName) {\r\n\r\n ParamChecks.nullNotPermitted(prefix, \"prefix\");\r\n ParamChecks.nullNotPermitted(seriesParameterName, \r\n \"seriesParameterName\");\r\n ParamChecks.nullNotPermitted(categoryParameterName, \r\n \"categoryParameterName\");\r\n this.prefix = prefix;\r\n this.seriesParameterName = seriesParameterName;\r\n this.categoryParameterName = categoryParameterName;\r\n\r\n }\r\n\r\n /**\r\n * Generates a URL for a particular item within a series.\r\n *\r\n * @param dataset the dataset.\r\n * @param series the series index (zero-based).\r\n * @param category the category index (zero-based).\r\n *\r\n * @return The generated URL.\r\n */\r\n @Override\r\n public String generateURL(CategoryDataset dataset, int series, \r\n int category) {\r\n String url = this.prefix;\r\n Comparable seriesKey = dataset.getRowKey(series);\r\n Comparable categoryKey = dataset.getColumnKey(category);\r\n boolean firstParameter = !url.contains(\"?\");\r\n url += firstParameter ? \"?\" : \"&amp;\";\r\n try {\r\n url += this.seriesParameterName + \"=\" + URLEncoder.encode(\r\n seriesKey.toString(), \"UTF-8\");\r\n url += \"&amp;\" + this.categoryParameterName + \"=\"\r\n + URLEncoder.encode(categoryKey.toString(), \"UTF-8\");\r\n } catch (UnsupportedEncodingException ex) {\r\n throw new RuntimeException(ex); // this won't happen :)\r\n }\r\n return url;\r\n }\r\n\r\n /**\r\n * Returns an independent copy of the URL generator.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException not thrown by this class, but\r\n * subclasses (if any) might.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n // all attributes are immutable, so we can just return the super.clone()\r\n // FIXME: in fact, the generator itself is immutable, so cloning is\r\n // not necessary\r\n return super.clone();\r\n }\r\n\r\n /**\r\n * Tests the generator for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof StandardCategoryURLGenerator)) {\r\n return false;\r\n }\r\n StandardCategoryURLGenerator that = (StandardCategoryURLGenerator) obj;\r\n if (!ObjectUtilities.equal(this.prefix, that.prefix)) {\r\n return false;\r\n }\r\n\r\n if (!ObjectUtilities.equal(this.seriesParameterName,\r\n that.seriesParameterName)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.categoryParameterName,\r\n that.categoryParameterName)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result;\r\n result = (this.prefix != null ? this.prefix.hashCode() : 0);\r\n result = 29 * result\r\n + (this.seriesParameterName != null\r\n ? this.seriesParameterName.hashCode() : 0);\r\n result = 29 * result\r\n + (this.categoryParameterName != null\r\n ? this.categoryParameterName.hashCode() : 0);\r\n return result;\r\n }\r\n\r\n}\r" }, { "identifier": "Range", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/Range.java", "snippet": "public strictfp class Range implements Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -906333695431863380L;\r\n\r\n /** The lower bound of the range. */\r\n private double lower;\r\n\r\n /** The upper bound of the range. */\r\n private double upper;\r\n\r\n /**\r\n * Creates a new range.\r\n *\r\n * @param lower the lower bound (must be &lt;= upper bound).\r\n * @param upper the upper bound (must be &gt;= lower bound).\r\n */\r\n public Range(double lower, double upper) {\r\n if (lower > upper) {\r\n String msg = \"Range(double, double): require lower (\" + lower\r\n + \") <= upper (\" + upper + \").\";\r\n throw new IllegalArgumentException(msg);\r\n }\r\n this.lower = lower;\r\n this.upper = upper;\r\n }\r\n\r\n /**\r\n * Returns the lower bound for the range.\r\n *\r\n * @return The lower bound.\r\n */\r\n public double getLowerBound() {\r\n return this.lower;\r\n }\r\n\r\n /**\r\n * Returns the upper bound for the range.\r\n *\r\n * @return The upper bound.\r\n */\r\n public double getUpperBound() {\r\n return this.upper;\r\n }\r\n\r\n /**\r\n * Returns the length of the range.\r\n *\r\n * @return The length.\r\n */\r\n public double getLength() {\r\n return this.upper - this.lower;\r\n }\r\n\r\n /**\r\n * Returns the central value for the range.\r\n *\r\n * @return The central value.\r\n */\r\n public double getCentralValue() {\r\n return this.lower / 2.0 + this.upper / 2.0;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range contains the specified value and\r\n * <code>false</code> otherwise.\r\n *\r\n * @param value the value to lookup.\r\n *\r\n * @return <code>true</code> if the range contains the specified value.\r\n */\r\n public boolean contains(double value) {\r\n return (value >= this.lower && value <= this.upper);\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range intersects with the specified\r\n * range, and <code>false</code> otherwise.\r\n *\r\n * @param b0 the lower bound (should be &lt;= b1).\r\n * @param b1 the upper bound (should be &gt;= b0).\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean intersects(double b0, double b1) {\r\n if (b0 <= this.lower) {\r\n return (b1 > this.lower);\r\n }\r\n else {\r\n return (b0 < this.upper && b1 >= b0);\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range intersects with the specified\r\n * range, and <code>false</code> otherwise.\r\n *\r\n * @param range another range (<code>null</code> not permitted).\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.9\r\n */\r\n public boolean intersects(Range range) {\r\n return intersects(range.getLowerBound(), range.getUpperBound());\r\n }\r\n\r\n /**\r\n * Returns the value within the range that is closest to the specified\r\n * value.\r\n *\r\n * @param value the value.\r\n *\r\n * @return The constrained value.\r\n */\r\n public double constrain(double value) {\r\n double result = value;\r\n if (!contains(value)) {\r\n if (value > this.upper) {\r\n result = this.upper;\r\n }\r\n else if (value < this.lower) {\r\n result = this.lower;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates a new range by combining two existing ranges.\r\n * <P>\r\n * Note that:\r\n * <ul>\r\n * <li>either range can be <code>null</code>, in which case the other\r\n * range is returned;</li>\r\n * <li>if both ranges are <code>null</code> the return value is\r\n * <code>null</code>.</li>\r\n * </ul>\r\n *\r\n * @param range1 the first range (<code>null</code> permitted).\r\n * @param range2 the second range (<code>null</code> permitted).\r\n *\r\n * @return A new range (possibly <code>null</code>).\r\n */\r\n public static Range combine(Range range1, Range range2) {\r\n if (range1 == null) {\r\n return range2;\r\n }\r\n if (range2 == null) {\r\n return range1;\r\n }\r\n double l = Math.min(range1.getLowerBound(), range2.getLowerBound());\r\n double u = Math.max(range1.getUpperBound(), range2.getUpperBound());\r\n return new Range(l, u);\r\n }\r\n\r\n /**\r\n * Returns a new range that spans both <code>range1</code> and \r\n * <code>range2</code>. This method has a special handling to ignore\r\n * Double.NaN values.\r\n *\r\n * @param range1 the first range (<code>null</code> permitted).\r\n * @param range2 the second range (<code>null</code> permitted).\r\n *\r\n * @return A new range (possibly <code>null</code>).\r\n *\r\n * @since 1.0.15\r\n */\r\n public static Range combineIgnoringNaN(Range range1, Range range2) {\r\n if (range1 == null) {\r\n if (range2 != null && range2.isNaNRange()) {\r\n return null;\r\n }\r\n return range2;\r\n }\r\n if (range2 == null) {\r\n if (range1.isNaNRange()) {\r\n return null;\r\n }\r\n return range1;\r\n }\r\n double l = min(range1.getLowerBound(), range2.getLowerBound());\r\n double u = max(range1.getUpperBound(), range2.getUpperBound());\r\n if (Double.isNaN(l) && Double.isNaN(u)) {\r\n return null;\r\n }\r\n return new Range(l, u);\r\n }\r\n \r\n /**\r\n * Returns the minimum value. If either value is NaN, the other value is \r\n * returned. If both are NaN, NaN is returned.\r\n * \r\n * @param d1 value 1.\r\n * @param d2 value 2.\r\n * \r\n * @return The minimum of the two values. \r\n */\r\n private static double min(double d1, double d2) {\r\n if (Double.isNaN(d1)) {\r\n return d2;\r\n }\r\n if (Double.isNaN(d2)) {\r\n return d1;\r\n }\r\n return Math.min(d1, d2);\r\n }\r\n\r\n private static double max(double d1, double d2) {\r\n if (Double.isNaN(d1)) {\r\n return d2;\r\n }\r\n if (Double.isNaN(d2)) {\r\n return d1;\r\n }\r\n return Math.max(d1, d2);\r\n }\r\n\r\n /**\r\n * Returns a range that includes all the values in the specified\r\n * <code>range</code> AND the specified <code>value</code>.\r\n *\r\n * @param range the range (<code>null</code> permitted).\r\n * @param value the value that must be included.\r\n *\r\n * @return A range.\r\n *\r\n * @since 1.0.1\r\n */\r\n public static Range expandToInclude(Range range, double value) {\r\n if (range == null) {\r\n return new Range(value, value);\r\n }\r\n if (value < range.getLowerBound()) {\r\n return new Range(value, range.getUpperBound());\r\n }\r\n else if (value > range.getUpperBound()) {\r\n return new Range(range.getLowerBound(), value);\r\n }\r\n else {\r\n return range;\r\n }\r\n }\r\n\r\n /**\r\n * Creates a new range by adding margins to an existing range.\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n * @param lowerMargin the lower margin (expressed as a percentage of the\r\n * range length).\r\n * @param upperMargin the upper margin (expressed as a percentage of the\r\n * range length).\r\n *\r\n * @return The expanded range.\r\n */\r\n public static Range expand(Range range,\r\n double lowerMargin, double upperMargin) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n double length = range.getLength();\r\n double lower = range.getLowerBound() - length * lowerMargin;\r\n double upper = range.getUpperBound() + length * upperMargin;\r\n if (lower > upper) {\r\n lower = lower / 2.0 + upper / 2.0;\r\n upper = lower;\r\n }\r\n return new Range(lower, upper);\r\n }\r\n\r\n /**\r\n * Shifts the range by the specified amount.\r\n *\r\n * @param base the base range (<code>null</code> not permitted).\r\n * @param delta the shift amount.\r\n *\r\n * @return A new range.\r\n */\r\n public static Range shift(Range base, double delta) {\r\n return shift(base, delta, false);\r\n }\r\n\r\n /**\r\n * Shifts the range by the specified amount.\r\n *\r\n * @param base the base range (<code>null</code> not permitted).\r\n * @param delta the shift amount.\r\n * @param allowZeroCrossing a flag that determines whether or not the\r\n * bounds of the range are allowed to cross\r\n * zero after adjustment.\r\n *\r\n * @return A new range.\r\n */\r\n public static Range shift(Range base, double delta,\r\n boolean allowZeroCrossing) {\r\n ParamChecks.nullNotPermitted(base, \"base\");\r\n if (allowZeroCrossing) {\r\n return new Range(base.getLowerBound() + delta,\r\n base.getUpperBound() + delta);\r\n }\r\n else {\r\n return new Range(shiftWithNoZeroCrossing(base.getLowerBound(),\r\n delta), shiftWithNoZeroCrossing(base.getUpperBound(),\r\n delta));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the given <code>value</code> adjusted by <code>delta</code> but\r\n * with a check to prevent the result from crossing <code>0.0</code>.\r\n *\r\n * @param value the value.\r\n * @param delta the adjustment.\r\n *\r\n * @return The adjusted value.\r\n */\r\n private static double shiftWithNoZeroCrossing(double value, double delta) {\r\n if (value > 0.0) {\r\n return Math.max(value + delta, 0.0);\r\n }\r\n else if (value < 0.0) {\r\n return Math.min(value + delta, 0.0);\r\n }\r\n else {\r\n return value + delta;\r\n }\r\n }\r\n\r\n /**\r\n * Scales the range by the specified factor.\r\n *\r\n * @param base the base range (<code>null</code> not permitted).\r\n * @param factor the scaling factor (must be non-negative).\r\n *\r\n * @return A new range.\r\n *\r\n * @since 1.0.9\r\n */\r\n public static Range scale(Range base, double factor) {\r\n ParamChecks.nullNotPermitted(base, \"base\");\r\n if (factor < 0) {\r\n throw new IllegalArgumentException(\"Negative 'factor' argument.\");\r\n }\r\n return new Range(base.getLowerBound() * factor,\r\n base.getUpperBound() * factor);\r\n }\r\n\r\n /**\r\n * Tests this object for equality with an arbitrary object.\r\n *\r\n * @param obj the object to test against (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (!(obj instanceof Range)) {\r\n return false;\r\n }\r\n Range range = (Range) obj;\r\n if (!(this.lower == range.lower)) {\r\n return false;\r\n }\r\n if (!(this.upper == range.upper)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if both the lower and upper bounds are \r\n * <code>Double.NaN</code>, and <code>false</code> otherwise.\r\n * \r\n * @return A boolean.\r\n * \r\n * @since 1.0.18\r\n */\r\n public boolean isNaNRange() {\r\n return Double.isNaN(this.lower) && Double.isNaN(this.upper);\r\n }\r\n \r\n /**\r\n * Returns a hash code.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result;\r\n long temp;\r\n temp = Double.doubleToLongBits(this.lower);\r\n result = (int) (temp ^ (temp >>> 32));\r\n temp = Double.doubleToLongBits(this.upper);\r\n result = 29 * result + (int) (temp ^ (temp >>> 32));\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a string representation of this Range.\r\n *\r\n * @return A String \"Range[lower,upper]\" where lower=lower range and\r\n * upper=upper range.\r\n */\r\n @Override\r\n public String toString() {\r\n return (\"Range[\" + this.lower + \",\" + this.upper + \"]\");\r\n }\r\n\r\n}\r" }, { "identifier": "CategoryDataset", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/category/CategoryDataset.java", "snippet": "public interface CategoryDataset extends KeyedValues2D, Dataset {\r\n\r\n // no additional methods required\r\n\r\n}\r" }, { "identifier": "DatasetUtilities", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/general/DatasetUtilities.java", "snippet": "public final class DatasetUtilities {\r\n\r\n /**\r\n * Private constructor for non-instanceability.\r\n */\r\n private DatasetUtilities() {\r\n // now try to instantiate this ;-)\r\n }\r\n\r\n /**\r\n * Calculates the total of all the values in a {@link PieDataset}. If\r\n * the dataset contains negative or <code>null</code> values, they are\r\n * ignored.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The total.\r\n */\r\n public static double calculatePieDatasetTotal(PieDataset dataset) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n List keys = dataset.getKeys();\r\n double totalValue = 0;\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable current = (Comparable) iterator.next();\r\n if (current != null) {\r\n Number value = dataset.getValue(current);\r\n double v = 0.0;\r\n if (value != null) {\r\n v = value.doubleValue();\r\n }\r\n if (v > 0) {\r\n totalValue = totalValue + v;\r\n }\r\n }\r\n }\r\n return totalValue;\r\n }\r\n\r\n /**\r\n * Creates a pie dataset from a table dataset by taking all the values\r\n * for a single row.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param rowKey the row key.\r\n *\r\n * @return A pie dataset.\r\n */\r\n public static PieDataset createPieDatasetForRow(CategoryDataset dataset,\r\n Comparable rowKey) {\r\n int row = dataset.getRowIndex(rowKey);\r\n return createPieDatasetForRow(dataset, row);\r\n }\r\n\r\n /**\r\n * Creates a pie dataset from a table dataset by taking all the values\r\n * for a single row.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param row the row (zero-based index).\r\n *\r\n * @return A pie dataset.\r\n */\r\n public static PieDataset createPieDatasetForRow(CategoryDataset dataset,\r\n int row) {\r\n DefaultPieDataset result = new DefaultPieDataset();\r\n int columnCount = dataset.getColumnCount();\r\n for (int current = 0; current < columnCount; current++) {\r\n Comparable columnKey = dataset.getColumnKey(current);\r\n result.setValue(columnKey, dataset.getValue(row, current));\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates a pie dataset from a table dataset by taking all the values\r\n * for a single column.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param columnKey the column key.\r\n *\r\n * @return A pie dataset.\r\n */\r\n public static PieDataset createPieDatasetForColumn(CategoryDataset dataset,\r\n Comparable columnKey) {\r\n int column = dataset.getColumnIndex(columnKey);\r\n return createPieDatasetForColumn(dataset, column);\r\n }\r\n\r\n /**\r\n * Creates a pie dataset from a {@link CategoryDataset} by taking all the\r\n * values for a single column.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param column the column (zero-based index).\r\n *\r\n * @return A pie dataset.\r\n */\r\n public static PieDataset createPieDatasetForColumn(CategoryDataset dataset,\r\n int column) {\r\n DefaultPieDataset result = new DefaultPieDataset();\r\n int rowCount = dataset.getRowCount();\r\n for (int i = 0; i < rowCount; i++) {\r\n Comparable rowKey = dataset.getRowKey(i);\r\n result.setValue(rowKey, dataset.getValue(i, column));\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates a new pie dataset based on the supplied dataset, but modified\r\n * by aggregating all the low value items (those whose value is lower\r\n * than the <code>percentThreshold</code>) into a single item with the\r\n * key \"Other\".\r\n *\r\n * @param source the source dataset (<code>null</code> not permitted).\r\n * @param key a new key for the aggregated items (<code>null</code> not\r\n * permitted).\r\n * @param minimumPercent the percent threshold.\r\n *\r\n * @return The pie dataset with (possibly) aggregated items.\r\n */\r\n public static PieDataset createConsolidatedPieDataset(PieDataset source,\r\n Comparable key, double minimumPercent) {\r\n return DatasetUtilities.createConsolidatedPieDataset(source, key,\r\n minimumPercent, 2);\r\n }\r\n\r\n /**\r\n * Creates a new pie dataset based on the supplied dataset, but modified\r\n * by aggregating all the low value items (those whose value is lower\r\n * than the <code>percentThreshold</code>) into a single item. The\r\n * aggregated items are assigned the specified key. Aggregation only\r\n * occurs if there are at least <code>minItems</code> items to aggregate.\r\n *\r\n * @param source the source dataset (<code>null</code> not permitted).\r\n * @param key the key to represent the aggregated items.\r\n * @param minimumPercent the percent threshold (ten percent is 0.10).\r\n * @param minItems only aggregate low values if there are at least this\r\n * many.\r\n *\r\n * @return The pie dataset with (possibly) aggregated items.\r\n */\r\n public static PieDataset createConsolidatedPieDataset(PieDataset source,\r\n Comparable key, double minimumPercent, int minItems) {\r\n\r\n DefaultPieDataset result = new DefaultPieDataset();\r\n double total = DatasetUtilities.calculatePieDatasetTotal(source);\r\n\r\n // Iterate and find all keys below threshold percentThreshold\r\n List keys = source.getKeys();\r\n ArrayList otherKeys = new ArrayList();\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable currentKey = (Comparable) iterator.next();\r\n Number dataValue = source.getValue(currentKey);\r\n if (dataValue != null) {\r\n double value = dataValue.doubleValue();\r\n if (value / total < minimumPercent) {\r\n otherKeys.add(currentKey);\r\n }\r\n }\r\n }\r\n\r\n // Create new dataset with keys above threshold percentThreshold\r\n iterator = keys.iterator();\r\n double otherValue = 0;\r\n while (iterator.hasNext()) {\r\n Comparable currentKey = (Comparable) iterator.next();\r\n Number dataValue = source.getValue(currentKey);\r\n if (dataValue != null) {\r\n if (otherKeys.contains(currentKey)\r\n && otherKeys.size() >= minItems) {\r\n // Do not add key to dataset\r\n otherValue += dataValue.doubleValue();\r\n }\r\n else {\r\n // Add key to dataset\r\n result.setValue(currentKey, dataValue);\r\n }\r\n }\r\n }\r\n // Add other category if applicable\r\n if (otherKeys.size() >= minItems) {\r\n result.setValue(key, otherValue);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates a {@link CategoryDataset} that contains a copy of the data in an\r\n * array (instances of <code>Double</code> are created to represent the\r\n * data items).\r\n * <p>\r\n * Row and column keys are created by appending 0, 1, 2, ... to the\r\n * supplied prefixes.\r\n *\r\n * @param rowKeyPrefix the row key prefix.\r\n * @param columnKeyPrefix the column key prefix.\r\n * @param data the data.\r\n *\r\n * @return The dataset.\r\n */\r\n public static CategoryDataset createCategoryDataset(String rowKeyPrefix,\r\n String columnKeyPrefix, double[][] data) {\r\n\r\n DefaultCategoryDataset result = new DefaultCategoryDataset();\r\n for (int r = 0; r < data.length; r++) {\r\n String rowKey = rowKeyPrefix + (r + 1);\r\n for (int c = 0; c < data[r].length; c++) {\r\n String columnKey = columnKeyPrefix + (c + 1);\r\n result.addValue(new Double(data[r][c]), rowKey, columnKey);\r\n }\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Creates a {@link CategoryDataset} that contains a copy of the data in\r\n * an array.\r\n * <p>\r\n * Row and column keys are created by appending 0, 1, 2, ... to the\r\n * supplied prefixes.\r\n *\r\n * @param rowKeyPrefix the row key prefix.\r\n * @param columnKeyPrefix the column key prefix.\r\n * @param data the data.\r\n *\r\n * @return The dataset.\r\n */\r\n public static CategoryDataset createCategoryDataset(String rowKeyPrefix,\r\n String columnKeyPrefix, Number[][] data) {\r\n\r\n DefaultCategoryDataset result = new DefaultCategoryDataset();\r\n for (int r = 0; r < data.length; r++) {\r\n String rowKey = rowKeyPrefix + (r + 1);\r\n for (int c = 0; c < data[r].length; c++) {\r\n String columnKey = columnKeyPrefix + (c + 1);\r\n result.addValue(data[r][c], rowKey, columnKey);\r\n }\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Creates a {@link CategoryDataset} that contains a copy of the data in\r\n * an array (instances of <code>Double</code> are created to represent the\r\n * data items).\r\n * <p>\r\n * Row and column keys are taken from the supplied arrays.\r\n *\r\n * @param rowKeys the row keys (<code>null</code> not permitted).\r\n * @param columnKeys the column keys (<code>null</code> not permitted).\r\n * @param data the data.\r\n *\r\n * @return The dataset.\r\n */\r\n public static CategoryDataset createCategoryDataset(Comparable[] rowKeys,\r\n Comparable[] columnKeys, double[][] data) {\r\n\r\n ParamChecks.nullNotPermitted(rowKeys, \"rowKeys\");\r\n ParamChecks.nullNotPermitted(columnKeys, \"columnKeys\");\r\n if (ArrayUtilities.hasDuplicateItems(rowKeys)) {\r\n throw new IllegalArgumentException(\"Duplicate items in 'rowKeys'.\");\r\n }\r\n if (ArrayUtilities.hasDuplicateItems(columnKeys)) {\r\n throw new IllegalArgumentException(\r\n \"Duplicate items in 'columnKeys'.\");\r\n }\r\n if (rowKeys.length != data.length) {\r\n throw new IllegalArgumentException(\r\n \"The number of row keys does not match the number of rows in \"\r\n + \"the data array.\");\r\n }\r\n int columnCount = 0;\r\n for (int r = 0; r < data.length; r++) {\r\n columnCount = Math.max(columnCount, data[r].length);\r\n }\r\n if (columnKeys.length != columnCount) {\r\n throw new IllegalArgumentException(\r\n \"The number of column keys does not match the number of \"\r\n + \"columns in the data array.\");\r\n }\r\n\r\n // now do the work...\r\n DefaultCategoryDataset result = new DefaultCategoryDataset();\r\n for (int r = 0; r < data.length; r++) {\r\n Comparable rowKey = rowKeys[r];\r\n for (int c = 0; c < data[r].length; c++) {\r\n Comparable columnKey = columnKeys[c];\r\n result.addValue(new Double(data[r][c]), rowKey, columnKey);\r\n }\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Creates a {@link CategoryDataset} by copying the data from the supplied\r\n * {@link KeyedValues} instance.\r\n *\r\n * @param rowKey the row key (<code>null</code> not permitted).\r\n * @param rowData the row data (<code>null</code> not permitted).\r\n *\r\n * @return A dataset.\r\n */\r\n public static CategoryDataset createCategoryDataset(Comparable rowKey,\r\n KeyedValues rowData) {\r\n\r\n ParamChecks.nullNotPermitted(rowKey, \"rowKey\");\r\n ParamChecks.nullNotPermitted(rowData, \"rowData\");\r\n DefaultCategoryDataset result = new DefaultCategoryDataset();\r\n for (int i = 0; i < rowData.getItemCount(); i++) {\r\n result.addValue(rowData.getValue(i), rowKey, rowData.getKey(i));\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Creates an {@link XYDataset} by sampling the specified function over a\r\n * fixed range.\r\n *\r\n * @param f the function (<code>null</code> not permitted).\r\n * @param start the start value for the range.\r\n * @param end the end value for the range.\r\n * @param samples the number of sample points (must be &gt; 1).\r\n * @param seriesKey the key to give the resulting series\r\n * (<code>null</code> not permitted).\r\n *\r\n * @return A dataset.\r\n */\r\n public static XYDataset sampleFunction2D(Function2D f, double start,\r\n double end, int samples, Comparable seriesKey) {\r\n\r\n // defer argument checking\r\n XYSeries series = sampleFunction2DToSeries(f, start, end, samples,\r\n seriesKey);\r\n XYSeriesCollection collection = new XYSeriesCollection(series);\r\n return collection;\r\n }\r\n\r\n /**\r\n * Creates an {@link XYSeries} by sampling the specified function over a\r\n * fixed range.\r\n *\r\n * @param f the function (<code>null</code> not permitted).\r\n * @param start the start value for the range.\r\n * @param end the end value for the range.\r\n * @param samples the number of sample points (must be &gt; 1).\r\n * @param seriesKey the key to give the resulting series\r\n * (<code>null</code> not permitted).\r\n *\r\n * @return A series.\r\n *\r\n * @since 1.0.13\r\n */\r\n public static XYSeries sampleFunction2DToSeries(Function2D f,\r\n double start, double end, int samples, Comparable seriesKey) {\r\n\r\n ParamChecks.nullNotPermitted(f, \"f\");\r\n ParamChecks.nullNotPermitted(seriesKey, \"seriesKey\");\r\n if (start >= end) {\r\n throw new IllegalArgumentException(\"Requires 'start' < 'end'.\");\r\n }\r\n if (samples < 2) {\r\n throw new IllegalArgumentException(\"Requires 'samples' > 1\");\r\n }\r\n\r\n XYSeries series = new XYSeries(seriesKey);\r\n double step = (end - start) / (samples - 1);\r\n for (int i = 0; i < samples; i++) {\r\n double x = start + (step * i);\r\n series.add(x, f.getValue(x));\r\n }\r\n return series;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the dataset is empty (or <code>null</code>),\r\n * and <code>false</code> otherwise.\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n public static boolean isEmptyOrNull(PieDataset dataset) {\r\n\r\n if (dataset == null) {\r\n return true;\r\n }\r\n\r\n int itemCount = dataset.getItemCount();\r\n if (itemCount == 0) {\r\n return true;\r\n }\r\n\r\n for (int item = 0; item < itemCount; item++) {\r\n Number y = dataset.getValue(item);\r\n if (y != null) {\r\n double yy = y.doubleValue();\r\n if (yy > 0.0) {\r\n return false;\r\n }\r\n }\r\n }\r\n\r\n return true;\r\n\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the dataset is empty (or <code>null</code>),\r\n * and <code>false</code> otherwise.\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n public static boolean isEmptyOrNull(CategoryDataset dataset) {\r\n\r\n if (dataset == null) {\r\n return true;\r\n }\r\n\r\n int rowCount = dataset.getRowCount();\r\n int columnCount = dataset.getColumnCount();\r\n if (rowCount == 0 || columnCount == 0) {\r\n return true;\r\n }\r\n\r\n for (int r = 0; r < rowCount; r++) {\r\n for (int c = 0; c < columnCount; c++) {\r\n if (dataset.getValue(r, c) != null) {\r\n return false;\r\n }\r\n\r\n }\r\n }\r\n\r\n return true;\r\n\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the dataset is empty (or <code>null</code>),\r\n * and <code>false</code> otherwise.\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n public static boolean isEmptyOrNull(XYDataset dataset) {\r\n if (dataset != null) {\r\n for (int s = 0; s < dataset.getSeriesCount(); s++) {\r\n if (dataset.getItemCount(s) > 0) {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns the range of values in the domain (x-values) of a dataset.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The range of values (possibly <code>null</code>).\r\n */\r\n public static Range findDomainBounds(XYDataset dataset) {\r\n return findDomainBounds(dataset, true);\r\n }\r\n\r\n /**\r\n * Returns the range of values in the domain (x-values) of a dataset.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param includeInterval determines whether or not the x-interval is taken\r\n * into account (only applies if the dataset is an\r\n * {@link IntervalXYDataset}).\r\n *\r\n * @return The range of values (possibly <code>null</code>).\r\n */\r\n public static Range findDomainBounds(XYDataset dataset,\r\n boolean includeInterval) {\r\n\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n\r\n Range result;\r\n // if the dataset implements DomainInfo, life is easier\r\n if (dataset instanceof DomainInfo) {\r\n DomainInfo info = (DomainInfo) dataset;\r\n result = info.getDomainBounds(includeInterval);\r\n }\r\n else {\r\n result = iterateDomainBounds(dataset, includeInterval);\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Returns the bounds of the x-values in the specified <code>dataset</code>\r\n * taking into account only the visible series and including any x-interval\r\n * if requested.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param visibleSeriesKeys the visible series keys (<code>null</code>\r\n * not permitted).\r\n * @param includeInterval include the x-interval (if any)?\r\n *\r\n * @return The bounds (or <code>null</code> if the dataset contains no\r\n * values.\r\n *\r\n * @since 1.0.13\r\n */\r\n public static Range findDomainBounds(XYDataset dataset,\r\n List visibleSeriesKeys, boolean includeInterval) {\r\n \r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n Range result;\r\n if (dataset instanceof XYDomainInfo) {\r\n XYDomainInfo info = (XYDomainInfo) dataset;\r\n result = info.getDomainBounds(visibleSeriesKeys, includeInterval);\r\n }\r\n else {\r\n result = iterateToFindDomainBounds(dataset, visibleSeriesKeys,\r\n includeInterval);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Iterates over the items in an {@link XYDataset} to find\r\n * the range of x-values. If the dataset is an instance of\r\n * {@link IntervalXYDataset}, the starting and ending x-values\r\n * will be used for the bounds calculation.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n */\r\n public static Range iterateDomainBounds(XYDataset dataset) {\r\n return iterateDomainBounds(dataset, true);\r\n }\r\n\r\n /**\r\n * Iterates over the items in an {@link XYDataset} to find\r\n * the range of x-values.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param includeInterval a flag that determines, for an\r\n * {@link IntervalXYDataset}, whether the x-interval or just the\r\n * x-value is used to determine the overall range.\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n */\r\n public static Range iterateDomainBounds(XYDataset dataset,\r\n boolean includeInterval) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n double minimum = Double.POSITIVE_INFINITY;\r\n double maximum = Double.NEGATIVE_INFINITY;\r\n int seriesCount = dataset.getSeriesCount();\r\n double lvalue, uvalue;\r\n if (includeInterval && dataset instanceof IntervalXYDataset) {\r\n IntervalXYDataset intervalXYData = (IntervalXYDataset) dataset;\r\n for (int series = 0; series < seriesCount; series++) {\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n double value = intervalXYData.getXValue(series, item);\r\n lvalue = intervalXYData.getStartXValue(series, item);\r\n uvalue = intervalXYData.getEndXValue(series, item);\r\n if (!Double.isNaN(value)) {\r\n minimum = Math.min(minimum, value);\r\n maximum = Math.max(maximum, value);\r\n }\r\n if (!Double.isNaN(lvalue)) {\r\n minimum = Math.min(minimum, lvalue);\r\n maximum = Math.max(maximum, lvalue);\r\n }\r\n if (!Double.isNaN(uvalue)) {\r\n minimum = Math.min(minimum, uvalue);\r\n maximum = Math.max(maximum, uvalue);\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n for (int series = 0; series < seriesCount; series++) {\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n lvalue = dataset.getXValue(series, item);\r\n uvalue = lvalue;\r\n if (!Double.isNaN(lvalue)) {\r\n minimum = Math.min(minimum, lvalue);\r\n maximum = Math.max(maximum, uvalue);\r\n }\r\n }\r\n }\r\n }\r\n if (minimum > maximum) {\r\n return null;\r\n }\r\n else {\r\n return new Range(minimum, maximum);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range of values in the range for the dataset.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n */\r\n public static Range findRangeBounds(CategoryDataset dataset) {\r\n return findRangeBounds(dataset, true);\r\n }\r\n\r\n /**\r\n * Returns the range of values in the range for the dataset.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param includeInterval a flag that determines whether or not the\r\n * y-interval is taken into account.\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n */\r\n public static Range findRangeBounds(CategoryDataset dataset,\r\n boolean includeInterval) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n Range result;\r\n if (dataset instanceof RangeInfo) {\r\n RangeInfo info = (RangeInfo) dataset;\r\n result = info.getRangeBounds(includeInterval);\r\n }\r\n else {\r\n result = iterateRangeBounds(dataset, includeInterval);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Finds the bounds of the y-values in the specified dataset, including\r\n * only those series that are listed in visibleSeriesKeys.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param visibleSeriesKeys the keys for the visible series\r\n * (<code>null</code> not permitted).\r\n * @param includeInterval include the y-interval (if the dataset has a\r\n * y-interval).\r\n *\r\n * @return The data bounds.\r\n *\r\n * @since 1.0.13\r\n */\r\n public static Range findRangeBounds(CategoryDataset dataset,\r\n List visibleSeriesKeys, boolean includeInterval) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n Range result;\r\n if (dataset instanceof CategoryRangeInfo) {\r\n CategoryRangeInfo info = (CategoryRangeInfo) dataset;\r\n result = info.getRangeBounds(visibleSeriesKeys, includeInterval);\r\n }\r\n else {\r\n result = iterateToFindRangeBounds(dataset, visibleSeriesKeys,\r\n includeInterval);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the range of values in the range for the dataset. This method\r\n * is the partner for the {@link #findDomainBounds(XYDataset)} method.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n */\r\n public static Range findRangeBounds(XYDataset dataset) {\r\n return findRangeBounds(dataset, true);\r\n }\r\n\r\n /**\r\n * Returns the range of values in the range for the dataset. This method\r\n * is the partner for the {@link #findDomainBounds(XYDataset, boolean)}\r\n * method.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param includeInterval a flag that determines whether or not the\r\n * y-interval is taken into account.\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n */\r\n public static Range findRangeBounds(XYDataset dataset,\r\n boolean includeInterval) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n Range result;\r\n if (dataset instanceof RangeInfo) {\r\n RangeInfo info = (RangeInfo) dataset;\r\n result = info.getRangeBounds(includeInterval);\r\n }\r\n else {\r\n result = iterateRangeBounds(dataset, includeInterval);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Finds the bounds of the y-values in the specified dataset, including\r\n * only those series that are listed in visibleSeriesKeys, and those items\r\n * whose x-values fall within the specified range.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param visibleSeriesKeys the keys for the visible series\r\n * (<code>null</code> not permitted).\r\n * @param xRange the x-range (<code>null</code> not permitted).\r\n * @param includeInterval include the y-interval (if the dataset has a\r\n * y-interval).\r\n *\r\n * @return The data bounds.\r\n * \r\n * @since 1.0.13\r\n */\r\n public static Range findRangeBounds(XYDataset dataset,\r\n List visibleSeriesKeys, Range xRange, boolean includeInterval) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n Range result;\r\n if (dataset instanceof XYRangeInfo) {\r\n XYRangeInfo info = (XYRangeInfo) dataset;\r\n result = info.getRangeBounds(visibleSeriesKeys, xRange,\r\n includeInterval);\r\n }\r\n else {\r\n result = iterateToFindRangeBounds(dataset, visibleSeriesKeys,\r\n xRange, includeInterval);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Iterates over the data item of the category dataset to find\r\n * the range bounds.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param includeInterval a flag that determines whether or not the\r\n * y-interval is taken into account.\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n *\r\n * @deprecated As of 1.0.10, use\r\n * {@link #iterateRangeBounds(CategoryDataset, boolean)}.\r\n */\r\n public static Range iterateCategoryRangeBounds(CategoryDataset dataset,\r\n boolean includeInterval) {\r\n return iterateRangeBounds(dataset, includeInterval);\r\n }\r\n\r\n /**\r\n * Iterates over the data item of the category dataset to find\r\n * the range bounds.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n *\r\n * @since 1.0.10\r\n */\r\n public static Range iterateRangeBounds(CategoryDataset dataset) {\r\n return iterateRangeBounds(dataset, true);\r\n }\r\n\r\n /**\r\n * Iterates over the data item of the category dataset to find\r\n * the range bounds.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param includeInterval a flag that determines whether or not the\r\n * y-interval is taken into account.\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n *\r\n * @since 1.0.10\r\n */\r\n public static Range iterateRangeBounds(CategoryDataset dataset,\r\n boolean includeInterval) {\r\n double minimum = Double.POSITIVE_INFINITY;\r\n double maximum = Double.NEGATIVE_INFINITY;\r\n int rowCount = dataset.getRowCount();\r\n int columnCount = dataset.getColumnCount();\r\n if (includeInterval && dataset instanceof IntervalCategoryDataset) {\r\n // handle the special case where the dataset has y-intervals that\r\n // we want to measure\r\n IntervalCategoryDataset icd = (IntervalCategoryDataset) dataset;\r\n Number value, lvalue, uvalue;\r\n for (int row = 0; row < rowCount; row++) {\r\n for (int column = 0; column < columnCount; column++) {\r\n value = icd.getValue(row, column);\r\n double v;\r\n if ((value != null)\r\n && !Double.isNaN(v = value.doubleValue())) {\r\n minimum = Math.min(v, minimum);\r\n maximum = Math.max(v, maximum);\r\n }\r\n lvalue = icd.getStartValue(row, column);\r\n if (lvalue != null\r\n && !Double.isNaN(v = lvalue.doubleValue())) {\r\n minimum = Math.min(v, minimum);\r\n maximum = Math.max(v, maximum);\r\n }\r\n uvalue = icd.getEndValue(row, column);\r\n if (uvalue != null\r\n && !Double.isNaN(v = uvalue.doubleValue())) {\r\n minimum = Math.min(v, minimum);\r\n maximum = Math.max(v, maximum);\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n // handle the standard case (plain CategoryDataset)\r\n for (int row = 0; row < rowCount; row++) {\r\n for (int column = 0; column < columnCount; column++) {\r\n Number value = dataset.getValue(row, column);\r\n if (value != null) {\r\n double v = value.doubleValue();\r\n if (!Double.isNaN(v)) {\r\n minimum = Math.min(minimum, v);\r\n maximum = Math.max(maximum, v);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (minimum == Double.POSITIVE_INFINITY) {\r\n return null;\r\n }\r\n else {\r\n return new Range(minimum, maximum);\r\n }\r\n }\r\n\r\n /**\r\n * Iterates over the data item of the category dataset to find\r\n * the range bounds.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param includeInterval a flag that determines whether or not the\r\n * y-interval is taken into account.\r\n * @param visibleSeriesKeys the visible series keys.\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n *\r\n * @since 1.0.13\r\n */\r\n public static Range iterateToFindRangeBounds(CategoryDataset dataset,\r\n List visibleSeriesKeys, boolean includeInterval) {\r\n\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n ParamChecks.nullNotPermitted(visibleSeriesKeys, \"visibleSeriesKeys\");\r\n\r\n double minimum = Double.POSITIVE_INFINITY;\r\n double maximum = Double.NEGATIVE_INFINITY;\r\n int columnCount = dataset.getColumnCount();\r\n if (includeInterval\r\n && dataset instanceof BoxAndWhiskerCategoryDataset) {\r\n // handle special case of BoxAndWhiskerDataset\r\n BoxAndWhiskerCategoryDataset bx\r\n = (BoxAndWhiskerCategoryDataset) dataset;\r\n Iterator iterator = visibleSeriesKeys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable seriesKey = (Comparable) iterator.next();\r\n int series = dataset.getRowIndex(seriesKey);\r\n int itemCount = dataset.getColumnCount();\r\n for (int item = 0; item < itemCount; item++) {\r\n Number lvalue = bx.getMinRegularValue(series, item);\r\n if (lvalue == null) {\r\n lvalue = bx.getValue(series, item);\r\n }\r\n Number uvalue = bx.getMaxRegularValue(series, item);\r\n if (uvalue == null) {\r\n uvalue = bx.getValue(series, item);\r\n }\r\n if (lvalue != null) {\r\n minimum = Math.min(minimum, lvalue.doubleValue());\r\n }\r\n if (uvalue != null) {\r\n maximum = Math.max(maximum, uvalue.doubleValue());\r\n }\r\n }\r\n }\r\n }\r\n else if (includeInterval\r\n && dataset instanceof IntervalCategoryDataset) {\r\n // handle the special case where the dataset has y-intervals that\r\n // we want to measure\r\n IntervalCategoryDataset icd = (IntervalCategoryDataset) dataset;\r\n Number lvalue, uvalue;\r\n Iterator iterator = visibleSeriesKeys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable seriesKey = (Comparable) iterator.next();\r\n int series = dataset.getRowIndex(seriesKey);\r\n for (int column = 0; column < columnCount; column++) {\r\n lvalue = icd.getStartValue(series, column);\r\n uvalue = icd.getEndValue(series, column);\r\n if (lvalue != null && !Double.isNaN(lvalue.doubleValue())) {\r\n minimum = Math.min(minimum, lvalue.doubleValue());\r\n }\r\n if (uvalue != null && !Double.isNaN(uvalue.doubleValue())) {\r\n maximum = Math.max(maximum, uvalue.doubleValue());\r\n }\r\n }\r\n }\r\n }\r\n else if (includeInterval\r\n && dataset instanceof MultiValueCategoryDataset) {\r\n // handle the special case where the dataset has y-intervals that\r\n // we want to measure\r\n MultiValueCategoryDataset mvcd\r\n = (MultiValueCategoryDataset) dataset;\r\n Iterator iterator = visibleSeriesKeys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable seriesKey = (Comparable) iterator.next();\r\n int series = dataset.getRowIndex(seriesKey);\r\n for (int column = 0; column < columnCount; column++) {\r\n List values = mvcd.getValues(series, column);\r\n Iterator valueIterator = values.iterator();\r\n while (valueIterator.hasNext()) {\r\n Object o = valueIterator.next();\r\n if (o instanceof Number){\r\n double v = ((Number) o).doubleValue();\r\n if (!Double.isNaN(v)){\r\n minimum = Math.min(minimum, v);\r\n maximum = Math.max(maximum, v);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n else if (includeInterval \r\n && dataset instanceof StatisticalCategoryDataset) {\r\n // handle the special case where the dataset has y-intervals that\r\n // we want to measure\r\n StatisticalCategoryDataset scd\r\n = (StatisticalCategoryDataset) dataset;\r\n Iterator iterator = visibleSeriesKeys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable seriesKey = (Comparable) iterator.next();\r\n int series = dataset.getRowIndex(seriesKey);\r\n for (int column = 0; column < columnCount; column++) {\r\n Number meanN = scd.getMeanValue(series, column);\r\n if (meanN != null) {\r\n double std = 0.0;\r\n Number stdN = scd.getStdDevValue(series, column);\r\n if (stdN != null) {\r\n std = stdN.doubleValue();\r\n if (Double.isNaN(std)) {\r\n std = 0.0;\r\n }\r\n }\r\n double mean = meanN.doubleValue();\r\n if (!Double.isNaN(mean)) {\r\n minimum = Math.min(minimum, mean - std);\r\n maximum = Math.max(maximum, mean + std);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n // handle the standard case (plain CategoryDataset)\r\n Iterator iterator = visibleSeriesKeys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable seriesKey = (Comparable) iterator.next();\r\n int series = dataset.getRowIndex(seriesKey);\r\n for (int column = 0; column < columnCount; column++) {\r\n Number value = dataset.getValue(series, column);\r\n if (value != null) {\r\n double v = value.doubleValue();\r\n if (!Double.isNaN(v)) {\r\n minimum = Math.min(minimum, v);\r\n maximum = Math.max(maximum, v);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (minimum == Double.POSITIVE_INFINITY) {\r\n return null;\r\n }\r\n else {\r\n return new Range(minimum, maximum);\r\n }\r\n }\r\n\r\n /**\r\n * Iterates over the data item of the xy dataset to find\r\n * the range bounds.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n *\r\n * @deprecated As of 1.0.10, use {@link #iterateRangeBounds(XYDataset)}.\r\n */\r\n public static Range iterateXYRangeBounds(XYDataset dataset) {\r\n return iterateRangeBounds(dataset);\r\n }\r\n\r\n /**\r\n * Iterates over the data item of the xy dataset to find\r\n * the range bounds.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n *\r\n * @since 1.0.10\r\n */\r\n public static Range iterateRangeBounds(XYDataset dataset) {\r\n return iterateRangeBounds(dataset, true);\r\n }\r\n\r\n /**\r\n * Iterates over the data items of the xy dataset to find\r\n * the range bounds.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param includeInterval a flag that determines, for an\r\n * {@link IntervalXYDataset}, whether the y-interval or just the\r\n * y-value is used to determine the overall range.\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n *\r\n * @since 1.0.10\r\n */\r\n public static Range iterateRangeBounds(XYDataset dataset,\r\n boolean includeInterval) {\r\n double minimum = Double.POSITIVE_INFINITY;\r\n double maximum = Double.NEGATIVE_INFINITY;\r\n int seriesCount = dataset.getSeriesCount();\r\n\r\n // handle three cases by dataset type\r\n if (includeInterval && dataset instanceof IntervalXYDataset) {\r\n // handle special case of IntervalXYDataset\r\n IntervalXYDataset ixyd = (IntervalXYDataset) dataset;\r\n for (int series = 0; series < seriesCount; series++) {\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n double value = ixyd.getYValue(series, item);\r\n double lvalue = ixyd.getStartYValue(series, item);\r\n double uvalue = ixyd.getEndYValue(series, item);\r\n if (!Double.isNaN(value)) {\r\n minimum = Math.min(minimum, value);\r\n maximum = Math.max(maximum, value);\r\n }\r\n if (!Double.isNaN(lvalue)) {\r\n minimum = Math.min(minimum, lvalue);\r\n maximum = Math.max(maximum, lvalue);\r\n }\r\n if (!Double.isNaN(uvalue)) {\r\n minimum = Math.min(minimum, uvalue);\r\n maximum = Math.max(maximum, uvalue);\r\n }\r\n }\r\n }\r\n }\r\n else if (includeInterval && dataset instanceof OHLCDataset) {\r\n // handle special case of OHLCDataset\r\n OHLCDataset ohlc = (OHLCDataset) dataset;\r\n for (int series = 0; series < seriesCount; series++) {\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n double lvalue = ohlc.getLowValue(series, item);\r\n double uvalue = ohlc.getHighValue(series, item);\r\n if (!Double.isNaN(lvalue)) {\r\n minimum = Math.min(minimum, lvalue);\r\n }\r\n if (!Double.isNaN(uvalue)) {\r\n maximum = Math.max(maximum, uvalue);\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n // standard case - plain XYDataset\r\n for (int series = 0; series < seriesCount; series++) {\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n double value = dataset.getYValue(series, item);\r\n if (!Double.isNaN(value)) {\r\n minimum = Math.min(minimum, value);\r\n maximum = Math.max(maximum, value);\r\n }\r\n }\r\n }\r\n }\r\n if (minimum == Double.POSITIVE_INFINITY) {\r\n return null;\r\n }\r\n else {\r\n return new Range(minimum, maximum);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range of values in the z-dimension for the dataset. This\r\n * method is the partner for the {@link #findRangeBounds(XYDataset)}\r\n * and {@link #findDomainBounds(XYDataset)} methods.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n */\r\n public static Range findZBounds(XYZDataset dataset) {\r\n return findZBounds(dataset, true);\r\n }\r\n\r\n /**\r\n * Returns the range of values in the z-dimension for the dataset. This\r\n * method is the partner for the\r\n * {@link #findRangeBounds(XYDataset, boolean)} and\r\n * {@link #findDomainBounds(XYDataset, boolean)} methods.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param includeInterval a flag that determines whether or not the\r\n * z-interval is taken into account.\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n */\r\n public static Range findZBounds(XYZDataset dataset,\r\n boolean includeInterval) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n Range result = iterateZBounds(dataset, includeInterval);\r\n return result;\r\n }\r\n\r\n /**\r\n * Finds the bounds of the z-values in the specified dataset, including\r\n * only those series that are listed in visibleSeriesKeys, and those items\r\n * whose x-values fall within the specified range.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param visibleSeriesKeys the keys for the visible series\r\n * (<code>null</code> not permitted).\r\n * @param xRange the x-range (<code>null</code> not permitted).\r\n * @param includeInterval include the z-interval (if the dataset has a\r\n * z-interval).\r\n *\r\n * @return The data bounds.\r\n */\r\n public static Range findZBounds(XYZDataset dataset,\r\n List visibleSeriesKeys, Range xRange, boolean includeInterval) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n Range result = iterateToFindZBounds(dataset, visibleSeriesKeys,\r\n xRange, includeInterval);\r\n return result;\r\n }\r\n\r\n /**\r\n * Iterates over the data item of the xyz dataset to find\r\n * the z-dimension bounds.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n */\r\n public static Range iterateZBounds(XYZDataset dataset) {\r\n return iterateZBounds(dataset, true);\r\n }\r\n\r\n /**\r\n * Iterates over the data items of the xyz dataset to find\r\n * the z-dimension bounds.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param includeInterval include the z-interval (if the dataset has a\r\n * z-interval.\r\n *\r\n * @return The range (possibly <code>null</code>).\r\n */\r\n public static Range iterateZBounds(XYZDataset dataset,\r\n boolean includeInterval) {\r\n double minimum = Double.POSITIVE_INFINITY;\r\n double maximum = Double.NEGATIVE_INFINITY;\r\n int seriesCount = dataset.getSeriesCount();\r\n\r\n for (int series = 0; series < seriesCount; series++) {\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n double value = dataset.getZValue(series, item);\r\n if (!Double.isNaN(value)) {\r\n minimum = Math.min(minimum, value);\r\n maximum = Math.max(maximum, value);\r\n }\r\n }\r\n }\r\n\r\n if (minimum == Double.POSITIVE_INFINITY) {\r\n return null;\r\n }\r\n else {\r\n return new Range(minimum, maximum);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range of x-values in the specified dataset for the\r\n * data items belonging to the visible series.\r\n * \r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param visibleSeriesKeys the visible series keys (<code>null</code> not\r\n * permitted).\r\n * @param includeInterval a flag that determines whether or not the\r\n * y-interval for the dataset is included (this only applies if the\r\n * dataset is an instance of IntervalXYDataset).\r\n * \r\n * @return The x-range (possibly <code>null</code>).\r\n * \r\n * @since 1.0.13\r\n */\r\n public static Range iterateToFindDomainBounds(XYDataset dataset,\r\n List visibleSeriesKeys, boolean includeInterval) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n ParamChecks.nullNotPermitted(visibleSeriesKeys, \"visibleSeriesKeys\");\r\n\r\n double minimum = Double.POSITIVE_INFINITY;\r\n double maximum = Double.NEGATIVE_INFINITY;\r\n\r\n if (includeInterval && dataset instanceof IntervalXYDataset) {\r\n // handle special case of IntervalXYDataset\r\n IntervalXYDataset ixyd = (IntervalXYDataset) dataset;\r\n Iterator iterator = visibleSeriesKeys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable seriesKey = (Comparable) iterator.next();\r\n int series = dataset.indexOf(seriesKey);\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n double lvalue = ixyd.getStartXValue(series, item);\r\n double uvalue = ixyd.getEndXValue(series, item);\r\n if (!Double.isNaN(lvalue)) {\r\n minimum = Math.min(minimum, lvalue);\r\n }\r\n if (!Double.isNaN(uvalue)) {\r\n maximum = Math.max(maximum, uvalue);\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n // standard case - plain XYDataset\r\n Iterator iterator = visibleSeriesKeys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable seriesKey = (Comparable) iterator.next();\r\n int series = dataset.indexOf(seriesKey);\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n double x = dataset.getXValue(series, item);\r\n if (!Double.isNaN(x)) {\r\n minimum = Math.min(minimum, x);\r\n maximum = Math.max(maximum, x);\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (minimum == Double.POSITIVE_INFINITY) {\r\n return null;\r\n }\r\n else {\r\n return new Range(minimum, maximum);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range of y-values in the specified dataset for the\r\n * data items belonging to the visible series and with x-values in the\r\n * given range.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param visibleSeriesKeys the visible series keys (<code>null</code> not\r\n * permitted).\r\n * @param xRange the x-range (<code>null</code> not permitted).\r\n * @param includeInterval a flag that determines whether or not the\r\n * y-interval for the dataset is included (this only applies if the\r\n * dataset is an instance of IntervalXYDataset).\r\n *\r\n * @return The y-range (possibly <code>null</code>).\r\n *\r\n * @since 1.0.13\r\n */\r\n public static Range iterateToFindRangeBounds(XYDataset dataset,\r\n List visibleSeriesKeys, Range xRange, boolean includeInterval) {\r\n\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n ParamChecks.nullNotPermitted(visibleSeriesKeys, \"visibleSeriesKeys\");\r\n ParamChecks.nullNotPermitted(xRange, \"xRange\");\r\n\r\n double minimum = Double.POSITIVE_INFINITY;\r\n double maximum = Double.NEGATIVE_INFINITY;\r\n\r\n // handle three cases by dataset type\r\n if (includeInterval && dataset instanceof OHLCDataset) {\r\n // handle special case of OHLCDataset\r\n OHLCDataset ohlc = (OHLCDataset) dataset;\r\n Iterator iterator = visibleSeriesKeys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable seriesKey = (Comparable) iterator.next();\r\n int series = dataset.indexOf(seriesKey);\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n double x = ohlc.getXValue(series, item);\r\n if (xRange.contains(x)) {\r\n double lvalue = ohlc.getLowValue(series, item);\r\n double uvalue = ohlc.getHighValue(series, item);\r\n if (!Double.isNaN(lvalue)) {\r\n minimum = Math.min(minimum, lvalue);\r\n }\r\n if (!Double.isNaN(uvalue)) {\r\n maximum = Math.max(maximum, uvalue);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n else if (includeInterval && dataset instanceof BoxAndWhiskerXYDataset) {\r\n // handle special case of BoxAndWhiskerXYDataset\r\n BoxAndWhiskerXYDataset bx = (BoxAndWhiskerXYDataset) dataset;\r\n Iterator iterator = visibleSeriesKeys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable seriesKey = (Comparable) iterator.next();\r\n int series = dataset.indexOf(seriesKey);\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n double x = bx.getXValue(series, item);\r\n if (xRange.contains(x)) {\r\n Number lvalue = bx.getMinRegularValue(series, item);\r\n Number uvalue = bx.getMaxRegularValue(series, item);\r\n if (lvalue != null) {\r\n minimum = Math.min(minimum, lvalue.doubleValue());\r\n }\r\n if (uvalue != null) {\r\n maximum = Math.max(maximum, uvalue.doubleValue());\r\n }\r\n }\r\n }\r\n }\r\n }\r\n else if (includeInterval && dataset instanceof IntervalXYDataset) {\r\n // handle special case of IntervalXYDataset\r\n IntervalXYDataset ixyd = (IntervalXYDataset) dataset;\r\n Iterator iterator = visibleSeriesKeys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable seriesKey = (Comparable) iterator.next();\r\n int series = dataset.indexOf(seriesKey);\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n double x = ixyd.getXValue(series, item);\r\n if (xRange.contains(x)) {\r\n double lvalue = ixyd.getStartYValue(series, item);\r\n double uvalue = ixyd.getEndYValue(series, item);\r\n if (!Double.isNaN(lvalue)) {\r\n minimum = Math.min(minimum, lvalue);\r\n }\r\n if (!Double.isNaN(uvalue)) {\r\n maximum = Math.max(maximum, uvalue);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n // standard case - plain XYDataset\r\n Iterator iterator = visibleSeriesKeys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable seriesKey = (Comparable) iterator.next();\r\n int series = dataset.indexOf(seriesKey);\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n double x = dataset.getXValue(series, item);\r\n double y = dataset.getYValue(series, item);\r\n if (xRange.contains(x)) {\r\n if (!Double.isNaN(y)) {\r\n minimum = Math.min(minimum, y);\r\n maximum = Math.max(maximum, y);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (minimum == Double.POSITIVE_INFINITY) {\r\n return null;\r\n }\r\n else {\r\n return new Range(minimum, maximum);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range of z-values in the specified dataset for the\r\n * data items belonging to the visible series and with x-values in the\r\n * given range.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param visibleSeriesKeys the visible series keys (<code>null</code> not\r\n * permitted).\r\n * @param xRange the x-range (<code>null</code> not permitted).\r\n * @param includeInterval a flag that determines whether or not the\r\n * z-interval for the dataset is included (this only applies if the\r\n * dataset has an interval, which is currently not supported).\r\n *\r\n * @return The y-range (possibly <code>null</code>).\r\n */\r\n public static Range iterateToFindZBounds(XYZDataset dataset,\r\n List visibleSeriesKeys, Range xRange, boolean includeInterval) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n ParamChecks.nullNotPermitted(visibleSeriesKeys, \"visibleSeriesKeys\");\r\n ParamChecks.nullNotPermitted(xRange, \"xRange\");\r\n \r\n double minimum = Double.POSITIVE_INFINITY;\r\n double maximum = Double.NEGATIVE_INFINITY;\r\n \r\n Iterator iterator = visibleSeriesKeys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable seriesKey = (Comparable) iterator.next();\r\n int series = dataset.indexOf(seriesKey);\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n double x = dataset.getXValue(series, item);\r\n double z = dataset.getZValue(series, item);\r\n if (xRange.contains(x)) {\r\n if (!Double.isNaN(z)) {\r\n minimum = Math.min(minimum, z);\r\n maximum = Math.max(maximum, z);\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (minimum == Double.POSITIVE_INFINITY) {\r\n return null;\r\n }\r\n else {\r\n return new Range(minimum, maximum);\r\n }\r\n }\r\n\r\n /**\r\n * Finds the minimum domain (or X) value for the specified dataset. This\r\n * is easy if the dataset implements the {@link DomainInfo} interface (a\r\n * good idea if there is an efficient way to determine the minimum value).\r\n * Otherwise, it involves iterating over the entire data-set.\r\n * <p>\r\n * Returns <code>null</code> if all the data values in the dataset are\r\n * <code>null</code>.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The minimum value (possibly <code>null</code>).\r\n */\r\n public static Number findMinimumDomainValue(XYDataset dataset) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n Number result;\r\n // if the dataset implements DomainInfo, life is easy\r\n if (dataset instanceof DomainInfo) {\r\n DomainInfo info = (DomainInfo) dataset;\r\n return new Double(info.getDomainLowerBound(true));\r\n }\r\n else {\r\n double minimum = Double.POSITIVE_INFINITY;\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n\r\n double value;\r\n if (dataset instanceof IntervalXYDataset) {\r\n IntervalXYDataset intervalXYData\r\n = (IntervalXYDataset) dataset;\r\n value = intervalXYData.getStartXValue(series, item);\r\n }\r\n else {\r\n value = dataset.getXValue(series, item);\r\n }\r\n if (!Double.isNaN(value)) {\r\n minimum = Math.min(minimum, value);\r\n }\r\n\r\n }\r\n }\r\n if (minimum == Double.POSITIVE_INFINITY) {\r\n result = null;\r\n }\r\n else {\r\n result = new Double(minimum);\r\n }\r\n }\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the maximum domain value for the specified dataset. This is\r\n * easy if the dataset implements the {@link DomainInfo} interface (a good\r\n * idea if there is an efficient way to determine the maximum value).\r\n * Otherwise, it involves iterating over the entire data-set. Returns\r\n * <code>null</code> if all the data values in the dataset are\r\n * <code>null</code>.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The maximum value (possibly <code>null</code>).\r\n */\r\n public static Number findMaximumDomainValue(XYDataset dataset) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n Number result;\r\n // if the dataset implements DomainInfo, life is easy\r\n if (dataset instanceof DomainInfo) {\r\n DomainInfo info = (DomainInfo) dataset;\r\n return new Double(info.getDomainUpperBound(true));\r\n }\r\n\r\n // hasn't implemented DomainInfo, so iterate...\r\n else {\r\n double maximum = Double.NEGATIVE_INFINITY;\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n\r\n double value;\r\n if (dataset instanceof IntervalXYDataset) {\r\n IntervalXYDataset intervalXYData\r\n = (IntervalXYDataset) dataset;\r\n value = intervalXYData.getEndXValue(series, item);\r\n }\r\n else {\r\n value = dataset.getXValue(series, item);\r\n }\r\n if (!Double.isNaN(value)) {\r\n maximum = Math.max(maximum, value);\r\n }\r\n }\r\n }\r\n if (maximum == Double.NEGATIVE_INFINITY) {\r\n result = null;\r\n }\r\n else {\r\n result = new Double(maximum);\r\n }\r\n\r\n }\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the minimum range value for the specified dataset. This is\r\n * easy if the dataset implements the {@link RangeInfo} interface (a good\r\n * idea if there is an efficient way to determine the minimum value).\r\n * Otherwise, it involves iterating over the entire data-set. Returns\r\n * <code>null</code> if all the data values in the dataset are\r\n * <code>null</code>.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The minimum value (possibly <code>null</code>).\r\n */\r\n public static Number findMinimumRangeValue(CategoryDataset dataset) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n if (dataset instanceof RangeInfo) {\r\n RangeInfo info = (RangeInfo) dataset;\r\n return new Double(info.getRangeLowerBound(true));\r\n }\r\n\r\n // hasn't implemented RangeInfo, so we'll have to iterate...\r\n else {\r\n double minimum = Double.POSITIVE_INFINITY;\r\n int seriesCount = dataset.getRowCount();\r\n int itemCount = dataset.getColumnCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n for (int item = 0; item < itemCount; item++) {\r\n Number value;\r\n if (dataset instanceof IntervalCategoryDataset) {\r\n IntervalCategoryDataset icd\r\n = (IntervalCategoryDataset) dataset;\r\n value = icd.getStartValue(series, item);\r\n }\r\n else {\r\n value = dataset.getValue(series, item);\r\n }\r\n if (value != null) {\r\n minimum = Math.min(minimum, value.doubleValue());\r\n }\r\n }\r\n }\r\n if (minimum == Double.POSITIVE_INFINITY) {\r\n return null;\r\n }\r\n else {\r\n return new Double(minimum);\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the minimum range value for the specified dataset. This is\r\n * easy if the dataset implements the {@link RangeInfo} interface (a good\r\n * idea if there is an efficient way to determine the minimum value).\r\n * Otherwise, it involves iterating over the entire data-set. Returns\r\n * <code>null</code> if all the data values in the dataset are\r\n * <code>null</code>.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The minimum value (possibly <code>null</code>).\r\n */\r\n public static Number findMinimumRangeValue(XYDataset dataset) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n\r\n // work out the minimum value...\r\n if (dataset instanceof RangeInfo) {\r\n RangeInfo info = (RangeInfo) dataset;\r\n return new Double(info.getRangeLowerBound(true));\r\n }\r\n\r\n // hasn't implemented RangeInfo, so we'll have to iterate...\r\n else {\r\n double minimum = Double.POSITIVE_INFINITY;\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n\r\n double value;\r\n if (dataset instanceof IntervalXYDataset) {\r\n IntervalXYDataset intervalXYData\r\n = (IntervalXYDataset) dataset;\r\n value = intervalXYData.getStartYValue(series, item);\r\n }\r\n else if (dataset instanceof OHLCDataset) {\r\n OHLCDataset highLowData = (OHLCDataset) dataset;\r\n value = highLowData.getLowValue(series, item);\r\n }\r\n else {\r\n value = dataset.getYValue(series, item);\r\n }\r\n if (!Double.isNaN(value)) {\r\n minimum = Math.min(minimum, value);\r\n }\r\n\r\n }\r\n }\r\n if (minimum == Double.POSITIVE_INFINITY) {\r\n return null;\r\n }\r\n else {\r\n return new Double(minimum);\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the maximum range value for the specified dataset. This is easy\r\n * if the dataset implements the {@link RangeInfo} interface (a good idea\r\n * if there is an efficient way to determine the maximum value).\r\n * Otherwise, it involves iterating over the entire data-set. Returns\r\n * <code>null</code> if all the data values are <code>null</code>.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The maximum value (possibly <code>null</code>).\r\n */\r\n public static Number findMaximumRangeValue(CategoryDataset dataset) {\r\n\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n\r\n // work out the minimum value...\r\n if (dataset instanceof RangeInfo) {\r\n RangeInfo info = (RangeInfo) dataset;\r\n return new Double(info.getRangeUpperBound(true));\r\n }\r\n\r\n // hasn't implemented RangeInfo, so we'll have to iterate...\r\n else {\r\n\r\n double maximum = Double.NEGATIVE_INFINITY;\r\n int seriesCount = dataset.getRowCount();\r\n int itemCount = dataset.getColumnCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n for (int item = 0; item < itemCount; item++) {\r\n Number value;\r\n if (dataset instanceof IntervalCategoryDataset) {\r\n IntervalCategoryDataset icd\r\n = (IntervalCategoryDataset) dataset;\r\n value = icd.getEndValue(series, item);\r\n }\r\n else {\r\n value = dataset.getValue(series, item);\r\n }\r\n if (value != null) {\r\n maximum = Math.max(maximum, value.doubleValue());\r\n }\r\n }\r\n }\r\n if (maximum == Double.NEGATIVE_INFINITY) {\r\n return null;\r\n }\r\n else {\r\n return new Double(maximum);\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the maximum range value for the specified dataset. This is\r\n * easy if the dataset implements the {@link RangeInfo} interface (a good\r\n * idea if there is an efficient way to determine the maximum value).\r\n * Otherwise, it involves iterating over the entire data-set. Returns\r\n * <code>null</code> if all the data values are <code>null</code>.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The maximum value (possibly <code>null</code>).\r\n */\r\n public static Number findMaximumRangeValue(XYDataset dataset) {\r\n\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n\r\n // work out the minimum value...\r\n if (dataset instanceof RangeInfo) {\r\n RangeInfo info = (RangeInfo) dataset;\r\n return new Double(info.getRangeUpperBound(true));\r\n }\r\n\r\n // hasn't implemented RangeInfo, so we'll have to iterate...\r\n else {\r\n\r\n double maximum = Double.NEGATIVE_INFINITY;\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n int itemCount = dataset.getItemCount(series);\r\n for (int item = 0; item < itemCount; item++) {\r\n double value;\r\n if (dataset instanceof IntervalXYDataset) {\r\n IntervalXYDataset intervalXYData\r\n = (IntervalXYDataset) dataset;\r\n value = intervalXYData.getEndYValue(series, item);\r\n }\r\n else if (dataset instanceof OHLCDataset) {\r\n OHLCDataset highLowData = (OHLCDataset) dataset;\r\n value = highLowData.getHighValue(series, item);\r\n }\r\n else {\r\n value = dataset.getYValue(series, item);\r\n }\r\n if (!Double.isNaN(value)) {\r\n maximum = Math.max(maximum, value);\r\n }\r\n }\r\n }\r\n if (maximum == Double.NEGATIVE_INFINITY) {\r\n return null;\r\n }\r\n else {\r\n return new Double(maximum);\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the minimum and maximum values for the dataset's range\r\n * (y-values), assuming that the series in one category are stacked.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The range (<code>null</code> if the dataset contains no values).\r\n */\r\n public static Range findStackedRangeBounds(CategoryDataset dataset) {\r\n return findStackedRangeBounds(dataset, 0.0);\r\n }\r\n\r\n /**\r\n * Returns the minimum and maximum values for the dataset's range\r\n * (y-values), assuming that the series in one category are stacked.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param base the base value for the bars.\r\n *\r\n * @return The range (<code>null</code> if the dataset contains no values).\r\n */\r\n public static Range findStackedRangeBounds(CategoryDataset dataset,\r\n double base) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n Range result = null;\r\n double minimum = Double.POSITIVE_INFINITY;\r\n double maximum = Double.NEGATIVE_INFINITY;\r\n int categoryCount = dataset.getColumnCount();\r\n for (int item = 0; item < categoryCount; item++) {\r\n double positive = base;\r\n double negative = base;\r\n int seriesCount = dataset.getRowCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n Number number = dataset.getValue(series, item);\r\n if (number != null) {\r\n double value = number.doubleValue();\r\n if (value > 0.0) {\r\n positive = positive + value;\r\n }\r\n if (value < 0.0) {\r\n negative = negative + value;\r\n // '+', remember value is negative\r\n }\r\n }\r\n }\r\n minimum = Math.min(minimum, negative);\r\n maximum = Math.max(maximum, positive);\r\n }\r\n if (minimum <= maximum) {\r\n result = new Range(minimum, maximum);\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Returns the minimum and maximum values for the dataset's range\r\n * (y-values), assuming that the series in one category are stacked.\r\n *\r\n * @param dataset the dataset.\r\n * @param map a structure that maps series to groups.\r\n *\r\n * @return The value range (<code>null</code> if the dataset contains no\r\n * values).\r\n */\r\n public static Range findStackedRangeBounds(CategoryDataset dataset,\r\n KeyToGroupMap map) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n boolean hasValidData = false;\r\n Range result = null;\r\n\r\n // create an array holding the group indices for each series...\r\n int[] groupIndex = new int[dataset.getRowCount()];\r\n for (int i = 0; i < dataset.getRowCount(); i++) {\r\n groupIndex[i] = map.getGroupIndex(map.getGroup(\r\n dataset.getRowKey(i)));\r\n }\r\n\r\n // minimum and maximum for each group...\r\n int groupCount = map.getGroupCount();\r\n double[] minimum = new double[groupCount];\r\n double[] maximum = new double[groupCount];\r\n\r\n int categoryCount = dataset.getColumnCount();\r\n for (int item = 0; item < categoryCount; item++) {\r\n double[] positive = new double[groupCount];\r\n double[] negative = new double[groupCount];\r\n int seriesCount = dataset.getRowCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n Number number = dataset.getValue(series, item);\r\n if (number != null) {\r\n hasValidData = true;\r\n double value = number.doubleValue();\r\n if (value > 0.0) {\r\n positive[groupIndex[series]]\r\n = positive[groupIndex[series]] + value;\r\n }\r\n if (value < 0.0) {\r\n negative[groupIndex[series]]\r\n = negative[groupIndex[series]] + value;\r\n // '+', remember value is negative\r\n }\r\n }\r\n }\r\n for (int g = 0; g < groupCount; g++) {\r\n minimum[g] = Math.min(minimum[g], negative[g]);\r\n maximum[g] = Math.max(maximum[g], positive[g]);\r\n }\r\n }\r\n if (hasValidData) {\r\n for (int j = 0; j < groupCount; j++) {\r\n result = Range.combine(result, new Range(minimum[j],\r\n maximum[j]));\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the minimum value in the dataset range, assuming that values in\r\n * each category are \"stacked\".\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The minimum value.\r\n *\r\n * @see #findMaximumStackedRangeValue(CategoryDataset)\r\n */\r\n public static Number findMinimumStackedRangeValue(CategoryDataset dataset) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n Number result = null;\r\n boolean hasValidData = false;\r\n double minimum = 0.0;\r\n int categoryCount = dataset.getColumnCount();\r\n for (int item = 0; item < categoryCount; item++) {\r\n double total = 0.0;\r\n int seriesCount = dataset.getRowCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n Number number = dataset.getValue(series, item);\r\n if (number != null) {\r\n hasValidData = true;\r\n double value = number.doubleValue();\r\n if (value < 0.0) {\r\n total = total + value;\r\n // '+', remember value is negative\r\n }\r\n }\r\n }\r\n minimum = Math.min(minimum, total);\r\n }\r\n if (hasValidData) {\r\n result = new Double(minimum);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the maximum value in the dataset range, assuming that values in\r\n * each category are \"stacked\".\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The maximum value (possibly <code>null</code>).\r\n *\r\n * @see #findMinimumStackedRangeValue(CategoryDataset)\r\n */\r\n public static Number findMaximumStackedRangeValue(CategoryDataset dataset) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n Number result = null;\r\n boolean hasValidData = false;\r\n double maximum = 0.0;\r\n int categoryCount = dataset.getColumnCount();\r\n for (int item = 0; item < categoryCount; item++) {\r\n double total = 0.0;\r\n int seriesCount = dataset.getRowCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n Number number = dataset.getValue(series, item);\r\n if (number != null) {\r\n hasValidData = true;\r\n double value = number.doubleValue();\r\n if (value > 0.0) {\r\n total = total + value;\r\n }\r\n }\r\n }\r\n maximum = Math.max(maximum, total);\r\n }\r\n if (hasValidData) {\r\n result = new Double(maximum);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the minimum and maximum values for the dataset's range,\r\n * assuming that the series are stacked.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The range ([0.0, 0.0] if the dataset contains no values).\r\n */\r\n public static Range findStackedRangeBounds(TableXYDataset dataset) {\r\n return findStackedRangeBounds(dataset, 0.0);\r\n }\r\n\r\n /**\r\n * Returns the minimum and maximum values for the dataset's range,\r\n * assuming that the series are stacked, using the specified base value.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param base the base value.\r\n *\r\n * @return The range (<code>null</code> if the dataset contains no values).\r\n */\r\n public static Range findStackedRangeBounds(TableXYDataset dataset,\r\n double base) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n double minimum = base;\r\n double maximum = base;\r\n for (int itemNo = 0; itemNo < dataset.getItemCount(); itemNo++) {\r\n double positive = base;\r\n double negative = base;\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int seriesNo = 0; seriesNo < seriesCount; seriesNo++) {\r\n double y = dataset.getYValue(seriesNo, itemNo);\r\n if (!Double.isNaN(y)) {\r\n if (y > 0.0) {\r\n positive += y;\r\n }\r\n else {\r\n negative += y;\r\n }\r\n }\r\n }\r\n if (positive > maximum) {\r\n maximum = positive;\r\n }\r\n if (negative < minimum) {\r\n minimum = negative;\r\n }\r\n }\r\n if (minimum <= maximum) {\r\n return new Range(minimum, maximum);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Calculates the total for the y-values in all series for a given item\r\n * index.\r\n *\r\n * @param dataset the dataset.\r\n * @param item the item index.\r\n *\r\n * @return The total.\r\n *\r\n * @since 1.0.5\r\n */\r\n public static double calculateStackTotal(TableXYDataset dataset, int item) {\r\n double total = 0.0;\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int s = 0; s < seriesCount; s++) {\r\n double value = dataset.getYValue(s, item);\r\n if (!Double.isNaN(value)) {\r\n total = total + value;\r\n }\r\n }\r\n return total;\r\n }\r\n\r\n /**\r\n * Calculates the range of values for a dataset where each item is the\r\n * running total of the items for the current series.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n *\r\n * @return The range.\r\n *\r\n * @see #findRangeBounds(CategoryDataset)\r\n */\r\n public static Range findCumulativeRangeBounds(CategoryDataset dataset) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n boolean allItemsNull = true; // we'll set this to false if there is at\r\n // least one non-null data item...\r\n double minimum = 0.0;\r\n double maximum = 0.0;\r\n for (int row = 0; row < dataset.getRowCount(); row++) {\r\n double runningTotal = 0.0;\r\n for (int column = 0; column <= dataset.getColumnCount() - 1;\r\n column++) {\r\n Number n = dataset.getValue(row, column);\r\n if (n != null) {\r\n allItemsNull = false;\r\n double value = n.doubleValue();\r\n if (!Double.isNaN(value)) {\r\n runningTotal = runningTotal + value;\r\n minimum = Math.min(minimum, runningTotal);\r\n maximum = Math.max(maximum, runningTotal);\r\n }\r\n }\r\n }\r\n }\r\n if (!allItemsNull) {\r\n return new Range(minimum, maximum);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Returns the interpolated value of y that corresponds to the specified\r\n * x-value in the given series. If the x-value falls outside the range of\r\n * x-values for the dataset, this method returns <code>Double.NaN</code>.\r\n * \r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param series the series index.\r\n * @param x the x-value.\r\n * \r\n * @return The y value.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static double findYValue(XYDataset dataset, int series, double x) {\r\n // delegate null check on dataset\r\n int[] indices = findItemIndicesForX(dataset, series, x);\r\n if (indices[0] == -1) {\r\n return Double.NaN;\r\n }\r\n if (indices[0] == indices[1]) {\r\n return dataset.getYValue(series, indices[0]);\r\n }\r\n double x0 = dataset.getXValue(series, indices[0]);\r\n double x1 = dataset.getXValue(series, indices[1]);\r\n double y0 = dataset.getYValue(series, indices[0]);\r\n double y1 = dataset.getYValue(series, indices[1]);\r\n return y0 + (y1 - y0) * (x - x0) / (x1 - x0);\r\n }\r\n \r\n /**\r\n * Finds the indices of the the items in the dataset that span the \r\n * specified x-value. There are three cases for the return value:\r\n * <ul>\r\n * <li>there is an exact match for the x-value at index i \r\n * (returns <code>int[] {i, i}</code>);</li>\r\n * <li>the x-value falls between two (adjacent) items at index i and i+1 \r\n * (returns <code>int[] {i, i+1}</code>);</li>\r\n * <li>the x-value falls outside the domain bounds, in which case the \r\n * method returns <code>int[] {-1, -1}</code>.</li>\r\n * </ul>\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param series the series index.\r\n * @param x the x-value.\r\n *\r\n * @return The indices of the two items that span the x-value.\r\n *\r\n * @since 1.0.16\r\n * \r\n * @see #findYValue(org.jfree.data.xy.XYDataset, int, double) \r\n */\r\n public static int[] findItemIndicesForX(XYDataset dataset, int series,\r\n double x) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n int itemCount = dataset.getItemCount(series);\r\n if (itemCount == 0) {\r\n return new int[] {-1, -1};\r\n }\r\n if (itemCount == 1) {\r\n if (x == dataset.getXValue(series, 0)) {\r\n return new int[] {0, 0};\r\n } else {\r\n return new int[] {-1, -1};\r\n }\r\n }\r\n if (dataset.getDomainOrder() == DomainOrder.ASCENDING) {\r\n int low = 0;\r\n int high = itemCount - 1;\r\n double lowValue = dataset.getXValue(series, low);\r\n if (lowValue > x) {\r\n return new int[] {-1, -1};\r\n }\r\n if (lowValue == x) {\r\n return new int[] {low, low};\r\n }\r\n double highValue = dataset.getXValue(series, high);\r\n if (highValue < x) {\r\n return new int[] {-1, -1};\r\n }\r\n if (highValue == x) {\r\n return new int[] {high, high};\r\n }\r\n int mid = (low + high) / 2;\r\n while (high - low > 1) {\r\n double midV = dataset.getXValue(series, mid);\r\n if (x == midV) {\r\n return new int[] {mid, mid};\r\n }\r\n if (midV < x) {\r\n low = mid;\r\n }\r\n else {\r\n high = mid;\r\n }\r\n mid = (low + high) / 2;\r\n }\r\n return new int[] {low, high};\r\n }\r\n else if (dataset.getDomainOrder() == DomainOrder.DESCENDING) {\r\n int high = 0;\r\n int low = itemCount - 1;\r\n double lowValue = dataset.getXValue(series, low);\r\n if (lowValue > x) {\r\n return new int[] {-1, -1};\r\n }\r\n double highValue = dataset.getXValue(series, high);\r\n if (highValue < x) {\r\n return new int[] {-1, -1};\r\n }\r\n int mid = (low + high) / 2;\r\n while (high - low > 1) {\r\n double midV = dataset.getXValue(series, mid);\r\n if (x == midV) {\r\n return new int[] {mid, mid};\r\n }\r\n if (midV < x) {\r\n low = mid;\r\n }\r\n else {\r\n high = mid;\r\n }\r\n mid = (low + high) / 2;\r\n }\r\n return new int[] {low, high};\r\n }\r\n else {\r\n // we don't know anything about the ordering of the x-values,\r\n // so we iterate until we find the first crossing of x (if any)\r\n // we know there are at least 2 items in the series at this point\r\n double prev = dataset.getXValue(series, 0);\r\n if (x == prev) {\r\n return new int[] {0, 0}; // exact match on first item\r\n }\r\n for (int i = 1; i < itemCount; i++) {\r\n double next = dataset.getXValue(series, i);\r\n if (x == next) {\r\n return new int[] {i, i}; // exact match\r\n }\r\n if ((x > prev && x < next) || (x < prev && x > next)) {\r\n return new int[] {i - 1, i}; // spanning match\r\n }\r\n }\r\n return new int[] {-1, -1}; // no crossing of x\r\n }\r\n }\r\n\r\n}\r" } ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.event.ChartChangeEvent; import org.jfree.chart.event.ChartChangeListener; import org.jfree.chart.labels.CategoryToolTipGenerator; import org.jfree.chart.labels.StandardCategoryToolTipGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.CategoryItemRenderer; import org.jfree.chart.urls.CategoryURLGenerator; import org.jfree.chart.urls.StandardCategoryURLGenerator; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.general.DatasetUtilities; import org.junit.Before; import org.junit.Test;
97,894
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------- * BarChart3DTest.java * ------------------- * (C) Copyright 2002-2013, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 11-Jun-2002 : Version 1 (DG); * 25-Jun-2002 : Removed redundant code (DG); * 17-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 14-Jul-2003 : Renamed BarChart3DTests.java (DG); * */ package org.jfree.chart; /** * Tests for a 3D bar chart. */ public class BarChart3DTest { /** The chart. */ private JFreeChart chart; /** * Common test setup. */ @Before public void setUp() { this.chart = createBarChart3D(); } /** * Draws the chart with a null info object to make sure that no exceptions * are thrown (a problem that was occurring at one point). */ @Test public void testDrawWithNullInfo() { try { BufferedImage image = new BufferedImage(200 , 100, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); this.chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, null); g2.dispose(); } catch (Exception e) { fail("There should be no exception."); } } /** * Replaces the dataset and checks that the data range is as expected. */ @Test public void testReplaceDataset() { // create a dataset... Number[][] data = new Integer[][] {{new Integer(-30), new Integer(-20)}, {new Integer(-10), new Integer(10)}, {new Integer(20), new Integer(30)}};
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------- * BarChart3DTest.java * ------------------- * (C) Copyright 2002-2013, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 11-Jun-2002 : Version 1 (DG); * 25-Jun-2002 : Removed redundant code (DG); * 17-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 14-Jul-2003 : Renamed BarChart3DTests.java (DG); * */ package org.jfree.chart; /** * Tests for a 3D bar chart. */ public class BarChart3DTest { /** The chart. */ private JFreeChart chart; /** * Common test setup. */ @Before public void setUp() { this.chart = createBarChart3D(); } /** * Draws the chart with a null info object to make sure that no exceptions * are thrown (a problem that was occurring at one point). */ @Test public void testDrawWithNullInfo() { try { BufferedImage image = new BufferedImage(200 , 100, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); this.chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, null); g2.dispose(); } catch (Exception e) { fail("There should be no exception."); } } /** * Replaces the dataset and checks that the data range is as expected. */ @Test public void testReplaceDataset() { // create a dataset... Number[][] data = new Integer[][] {{new Integer(-30), new Integer(-20)}, {new Integer(-10), new Integer(10)}, {new Integer(20), new Integer(30)}};
CategoryDataset newData = DatasetUtilities.createCategoryDataset("S",
12
2023-12-24 12:36:47+00:00
128k
DrMango14/Create-Design-n-Decor
src/main/java/com/mangomilk/design_decor/registry/MmbBlocks.java
[ { "identifier": "DecorBuilderTransformer", "path": "src/main/java/com/mangomilk/design_decor/base/DecorBuilderTransformer.java", "snippet": "public class DecorBuilderTransformer {\n\n public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> connected(\n Supplier<CTSpriteShiftEntry> ct) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get()))\n .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> layeredConnected(\n Supplier<CTSpriteShiftEntry> ct, Supplier<CTSpriteShiftEntry> ct2) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get(), p.models()\n .cubeColumn(c.getName(), ct.get()\n .getOriginalResourceLocation(),\n ct2.get()\n .getOriginalResourceLocation())))\n .onRegister(connectedTextures(() -> new HorizontalCTBehaviour(ct.get(), ct2.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n public static <B extends OrnateGrateBlock> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> ornateconnected(\n Supplier<CTSpriteShiftEntry> ct) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get(), AssetLookup.standardModel(c, p)))\n .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n private static BlockBehaviour.Properties glassProperties(BlockBehaviour.Properties p) {\n return p.isValidSpawn(DecorBuilderTransformer::never)\n .isRedstoneConductor(DecorBuilderTransformer::never)\n .isSuffocating(DecorBuilderTransformer::never)\n .isViewBlocking(DecorBuilderTransformer::never)\n .noOcclusion();\n }\n\n public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(Supplier<ConnectedTextureBehaviour> behaviour) {\n return CreateMMBuilding.REGISTRATE.block(\"tinted_framed_glass\", ConnectedTintedGlassBlock::new)\n .onRegister(connectedTextures(behaviour))\n .addLayer(() -> RenderType::translucent)\n .initialProperties(() -> Blocks.TINTED_GLASS)\n .properties(DecorBuilderTransformer::glassProperties)\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get))\n .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, \"palettes/\", \"tinted_framed_glass\"))\n .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE)\n .lang(\"Tinted Framed Glass\")\n .item()\n .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS)\n .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()),\n p.modLoc(\"block/palettes/tinted_framed_glass\")))\n .build()\n .register();\n }\n\n public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(String type,String name, Supplier<ConnectedTextureBehaviour> behaviour) {\n return CreateMMBuilding.REGISTRATE.block(type + \"_tinted_framed_glass\", ConnectedTintedGlassBlock::new)\n .onRegister(connectedTextures(behaviour))\n .addLayer(() -> RenderType::translucent)\n .initialProperties(() -> Blocks.TINTED_GLASS)\n .properties(DecorBuilderTransformer::glassProperties)\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get))\n .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, \"palettes/\", type + \"_tinted_framed_glass\"))\n .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE)\n .lang(name + \" Tinted Framed Glass\")\n .item()\n .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS)\n .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()),\n p.modLoc(\"block/palettes/\" + type + \"_tinted_framed_glass\")))\n .build()\n .register();\n }\n\n\n\n\n public static BlockEntry<Block> CastelBricks(String id, String lang, MaterialColor color, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Brick Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_bricks\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_bricks\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Brick Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Brick Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_bricks\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Bricks\")\n .register();\n }\n\n public static BlockEntry<Block> CastelBricks(String id, String lang, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Brick Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_bricks\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_bricks\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Brick Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Brick Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_bricks\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Bricks\")\n .register();\n }\n public static BlockEntry<Block> CastelTiles(String id, String lang, MaterialColor color, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Tile Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_tiles\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_tiles\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Tile Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Tile Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_tiles\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Tiles\")\n .register();\n }\n public static BlockEntry<Block> CastelTiles(String id, String lang, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Tile Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_tiles\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_tiles\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Tile Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Tile Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_tiles\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Tiles\")\n .register();\n }\n private static boolean never(BlockState p_235436_0_, BlockGetter p_235436_1_, BlockPos p_235436_2_) {return false;}\n private static Boolean never(BlockState p_235427_0_, BlockGetter p_235427_1_, BlockPos p_235427_2_, EntityType<?> p_235427_3_) {return false;}\n private static String palettesDir() {return \"block/palettes/\";}\n}" }, { "identifier": "MmbSpriteShifts", "path": "src/main/java/com/mangomilk/design_decor/base/MmbSpriteShifts.java", "snippet": "@SuppressWarnings({\"unused\"})\npublic class MmbSpriteShifts {\n public static final Couple<CTSpriteShiftEntry>\n RED_CONTAINER_TOP = vault(\"red\",\"top\"),\n RED_CONTAINER_FRONT = vault(\"red\",\"front\"),\n RED_CONTAINER_SIDE = vault(\"red\",\"side\"),\n RED_CONTAINER_BOTTOM = vault(\"red\",\"bottom\");\n public static final Couple<CTSpriteShiftEntry>\n BLUE_CONTAINER_TOP = vault(\"blue\",\"top\"),\n BLUE_CONTAINER_FRONT = vault(\"blue\",\"front\"),\n BLUE_CONTAINER_SIDE = vault(\"blue\",\"side\"),\n BLUE_CONTAINER_BOTTOM = vault(\"blue\",\"bottom\");\n public static final Couple<CTSpriteShiftEntry>\n GREEN_CONTAINER_TOP = vault(\"green\",\"top\"),\n GREEN_CONTAINER_FRONT = vault(\"green\",\"front\"),\n GREEN_CONTAINER_SIDE = vault(\"green\",\"side\"),\n GREEN_CONTAINER_BOTTOM = vault(\"green\",\"bottom\");\n\n public static final CTSpriteShiftEntry\n ORNATE_GRATE = omni(\"ornate_grate\"),\n INDUSTRIAL_PLATING_BLOCK = omni(\"industrial_plating_block\"),\n INDUSTRIAL_PLATING_BLOCK_SIDE = omni(\"industrial_plating_block_side\"),\n TINTED_FRAMED_GLASS = omni(\"palettes/tinted_framed_glass\"),\n TINTED_HORIZONTAL_FRAMED_GLASS = omni(\"palettes/horizontal_tinted_framed_glass\"),\n TINTED_VERTICAL_FRAMED_GLASS = omni(\"palettes/vertical_tinted_framed_glass\");\n\n private static Couple<CTSpriteShiftEntry> vault(String color,String name) {\n final String prefixed = \"block/\"+color+\"_container/container_\" + name;\n return Couple.createWithContext(\n medium -> CTSpriteShifter.getCT(AllCTTypes.RECTANGLE, CreateMMBuilding.asResource(prefixed + \"_small\"),\n CreateMMBuilding.asResource(medium ? prefixed + \"_medium\" : prefixed + \"_large\")));\n }\n\n private static CTSpriteShiftEntry omni(String name) {\n return getCT(AllCTTypes.OMNIDIRECTIONAL, name);\n }\n\n private static CTSpriteShiftEntry horizontal(String name) {\n return getCT(AllCTTypes.HORIZONTAL, name);\n }\n\n private static CTSpriteShiftEntry vertical(String name) {\n return getCT(AllCTTypes.VERTICAL, name);\n }\n\n\n private static CTSpriteShiftEntry getCT(CTType type, String blockTextureName, String connectedTextureName) {\n return CTSpriteShifter.getCT(type, CreateMMBuilding.asResource(\"block/\" + blockTextureName),\n CreateMMBuilding.asResource(\"block/\" + connectedTextureName + \"_connected\"));\n }\n\n private static CTSpriteShiftEntry getCT(CTType type, String blockTextureName) {\n return getCT(type, blockTextureName, blockTextureName);\n }\n\n public static void init(){}\n\n}" }, { "identifier": "SignBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/SignBlock.java", "snippet": "public class SignBlock extends DirectionalBlock implements IWrenchable {\n\n public static final VoxelShape SHAPE_UP = Block.box(0.0D, 15.0D, 0.0D, 16.0D, 16.0D, 16.0D);\n public static final VoxelShape SHAPE_DOWN = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 1.0D, 16.0D);\n public static final VoxelShape SHAPE_NORTH = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 1.0D);\n public static final VoxelShape SHAPE_WEST = Block.box(0.0D, 0.0D, 0.0D, 1.0D, 16.0D, 16.0D);\n public static final VoxelShape SHAPE_EAST = Block.box(15.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D);\n public static final VoxelShape SHAPE_SOUTH = Block.box(0.0D, 0.0D, 15.0D, 16.0D, 16.0D, 16.0D);\n\n\n\n public static final VoxelShape SHAPE_UP_OUTLINE = Block.box(1.0D, 15.0D, 1.0D, 15.0D, 16.0D, 15.0D);\n public static final VoxelShape SHAPE_DOWN_OUTLINE = Block.box(1.0D, 0.0D, 1.0D, 15.0D, 1.0D, 15.0D);\n\n public static final VoxelShape SHAPE_WEST_OUTLINE = Block.box(0.0D, 1.0D, 1.0D, 1.0D, 15.0D, 15.0D);\n public static final VoxelShape SHAPE_EAST_OUTLINE = Block.box(15.0D, 1.0D, 1.0D, 16.0D, 15.0D, 15.0D);\n public static final VoxelShape SHAPE_SOUTH_OUTLINE = Block.box(1.0D, 1.0D, 15.0D, 15.0D, 15.0D, 16.0D);\n public static final VoxelShape SHAPE_NORTH_OUTLINE = Block.box(1.0D, 1.0D, 0.0D, 15.0D, 15.0D, 1.0D);\n public SignBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP));\n }\n\n public VoxelShape getShape(BlockState p_54561_, BlockGetter p_54562_, BlockPos p_54563_, CollisionContext p_54564_) {\n switch (p_54561_.getValue(FACING)) {\n case NORTH:\n return SHAPE_NORTH_OUTLINE;\n case SOUTH:\n return SHAPE_SOUTH_OUTLINE;\n case EAST:\n return SHAPE_EAST_OUTLINE;\n case WEST:\n return SHAPE_WEST_OUTLINE;\n case UP:\n return SHAPE_UP_OUTLINE;\n case DOWN:\n return SHAPE_DOWN_OUTLINE;\n default:\n return SHAPE_NORTH_OUTLINE;\n }\n }\n\n @Override\n public VoxelShape getBlockSupportShape(BlockState pState, BlockGetter pReader, BlockPos pPos) {\n switch (pState.getValue(FACING)) {\n case NORTH:\n return SHAPE_NORTH;\n case SOUTH:\n return SHAPE_SOUTH;\n case EAST:\n return SHAPE_EAST;\n case WEST:\n return SHAPE_WEST;\n case UP:\n return SHAPE_UP;\n case DOWN:\n return SHAPE_DOWN;\n default:\n return SHAPE_NORTH;\n }\n }\n\n public BlockState updateShape(BlockState p_57503_, Direction p_57504_, BlockState p_57505_, LevelAccessor p_57506_, BlockPos p_57507_, BlockPos p_57508_) {\n return !this.canSurvive(p_57503_, p_57506_, p_57507_) ? Blocks.AIR.defaultBlockState() : super.updateShape(p_57503_, p_57504_, p_57505_, p_57506_, p_57507_, p_57508_);\n }\n\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_55125_) {\n p_55125_.add(FACING);\n }\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_58126_) {\n BlockState blockstate = this.defaultBlockState();\n LevelReader levelreader = p_58126_.getLevel();\n BlockPos blockpos = p_58126_.getClickedPos();\n Direction[] adirection = p_58126_.getNearestLookingDirections();\n\n for(Direction direction : adirection) {\n blockstate = blockstate.setValue(FACING, direction);\n if (blockstate.canSurvive(levelreader, blockpos)) {\n return blockstate;\n }\n\n }\n\n return null;\n }\n public boolean canSurvive(BlockState p_58133_, LevelReader p_58134_, BlockPos p_58135_) {\n Direction direction = p_58133_.getValue(FACING);\n BlockPos blockpos = p_58135_.relative(direction);\n BlockState blockstate = p_58134_.getBlockState(blockpos);\n return !blockstate.isAir();\n }\n}" }, { "identifier": "LargeChain", "path": "src/main/java/com/mangomilk/design_decor/blocks/chain/LargeChain.java", "snippet": "@SuppressWarnings({\"unused\"})\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class LargeChain extends ChainBlock implements SimpleWaterloggedBlock, IWrenchable {\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n protected static final float AABB_MIN = 4;\n protected static final float AABB_MAX = 12;\n\n protected static final VoxelShape Y_AXIS_AABB = Block.box(4, 0, 4, 12, 16, 12);\n protected static final VoxelShape Z_AXIS_AABB = Block.box(4, 4, 0, 12, 12, 16);\n protected static final VoxelShape X_AXIS_AABB = Block.box(0, 4, 4, 16, 12, 12);\n\n public static final int placementHelperId = PlacementHelpers.register(new LargeChain.PlacementHelper());\n\n public LargeChain(Properties p_55926_) {\n super(p_55926_.noCollission().noOcclusion().isSuffocating(LargeChain::never).requiresCorrectToolForDrops().strength(5.0F, 6.0F)\n .sound(new ForgeSoundType(1f, .95f, () -> DecoSoundEvents.LARGE_CHAIN_BREAK.get(),\n () -> DecoSoundEvents.LARGE_CHAIN_STEP.get(), () -> DecoSoundEvents.LARGE_CHAIN_PLACE.get(),\n () -> DecoSoundEvents.LARGE_CHAIN_HIT.get(), () -> DecoSoundEvents.LARGE_CHAIN_FALL.get())));\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE).setValue(AXIS, Direction.Axis.Y));\n }\n\n @Override\n public VoxelShape getShape(BlockState p_51470_, BlockGetter p_51471_, BlockPos p_51472_, CollisionContext p_51473_) {\n switch ((Direction.Axis)p_51470_.getValue(AXIS)) {\n case X:\n default:\n return X_AXIS_AABB;\n case Z:\n return Z_AXIS_AABB;\n case Y:\n return Y_AXIS_AABB;\n }\n }\n\n @Override\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_51454_) {\n FluidState fluidstate = p_51454_.getLevel().getFluidState(p_51454_.getClickedPos());\n boolean flag = fluidstate.getType() == Fluids.WATER;\n return Objects.requireNonNull(super.getStateForPlacement(p_51454_)).setValue(WATERLOGGED, flag);\n }\n\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_51468_) {\n p_51468_.add(WATERLOGGED).add(AXIS);\n }\n\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n\n @Override\n public boolean isPathfindable(BlockState p_51456_, BlockGetter p_51457_, BlockPos p_51458_, PathComputationType p_51459_) {\n return false;\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction.Axis> {\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof LargeChain, state -> state.getValue(AXIS), AXIS);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof LargeChain;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof LargeChain;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectLargeChain(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n if (pPlayer == null)\n return InteractionResult.PASS;\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n public static BlockState pickCorrectLargeChain(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n private static boolean never(BlockState p_235436_0_, BlockGetter p_235436_1_, BlockPos p_235436_2_) {\n return false;\n }\n}" }, { "identifier": "TagDependentLargeChain", "path": "src/main/java/com/mangomilk/design_decor/blocks/chain/TagDependentLargeChain.java", "snippet": "@SuppressWarnings({\"unused\"})\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class TagDependentLargeChain extends ChainBlock implements SimpleWaterloggedBlock, IWrenchable {\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n protected static final float AABB_MIN = 4;\n protected static final float AABB_MAX = 12;\n\n protected static final VoxelShape Y_AXIS_AABB = Block.box(4, 0, 4, 12, 16, 12);\n protected static final VoxelShape Z_AXIS_AABB = Block.box(4, 4, 0, 12, 12, 16);\n protected static final VoxelShape X_AXIS_AABB = Block.box(0, 4, 4, 16, 12, 12);\n\n public static final int placementHelperId = PlacementHelpers.register(new TagDependentLargeChain.PlacementHelper());\n\n private TagKey<Item> tag;\n\n public TagDependentLargeChain(Properties p_55926_, TagKey<Item> itemTagKey) {\n super(p_55926_.noCollission().noOcclusion().isSuffocating(TagDependentLargeChain::never).requiresCorrectToolForDrops().strength(5.0F, 6.0F)\n .sound(new ForgeSoundType(1f, .95f, () -> DecoSoundEvents.LARGE_CHAIN_BREAK.get(),\n () -> DecoSoundEvents.LARGE_CHAIN_STEP.get(), () -> DecoSoundEvents.LARGE_CHAIN_PLACE.get(),\n () -> DecoSoundEvents.LARGE_CHAIN_HIT.get(), () -> DecoSoundEvents.LARGE_CHAIN_FALL.get())));\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE).setValue(AXIS, Direction.Axis.Y));\n this.tag = itemTagKey;\n }\n\n @Override\n public VoxelShape getShape(BlockState p_51470_, BlockGetter p_51471_, BlockPos p_51472_, CollisionContext p_51473_) {\n switch ((Direction.Axis)p_51470_.getValue(AXIS)) {\n case X:\n default:\n return X_AXIS_AABB;\n case Z:\n return Z_AXIS_AABB;\n case Y:\n return Y_AXIS_AABB;\n }\n }\n\n @Override\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_51454_) {\n FluidState fluidstate = p_51454_.getLevel().getFluidState(p_51454_.getClickedPos());\n boolean flag = fluidstate.getType() == Fluids.WATER;\n return Objects.requireNonNull(super.getStateForPlacement(p_51454_)).setValue(WATERLOGGED, flag);\n }\n\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_51468_) {\n p_51468_.add(WATERLOGGED).add(AXIS);\n }\n\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n\n @Override\n public boolean isPathfindable(BlockState p_51456_, BlockGetter p_51457_, BlockPos p_51458_, PathComputationType p_51459_) {\n return false;\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction.Axis> {\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof TagDependentLargeChain, state -> state.getValue(AXIS), AXIS);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof TagDependentLargeChain;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof TagDependentLargeChain;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectLargeChain(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n if (pPlayer == null)\n return InteractionResult.PASS;\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n public static BlockState pickCorrectLargeChain(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n private static boolean never(BlockState p_235436_0_, BlockGetter p_235436_1_, BlockPos p_235436_2_) {\n return false;\n }\n\n\n @Override\n public void fillItemCategory(CreativeModeTab tab, NonNullList<ItemStack> list) {\n if (!shouldHide())\n super.fillItemCategory(tab, list);\n }\n\n public boolean shouldHide() {\n ITagManager<Item> tagManager = ForgeRegistries.ITEMS.tags();\n return !tagManager.isKnownTagName(tag) || tagManager.getTag(tag).isEmpty();\n }\n}" }, { "identifier": "RedContainerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/red/RedContainerBlock.java", "snippet": "public class RedContainerBlock extends Block implements IWrenchable, IBE<RedContainerBlockEntity> {\n\n\tpublic static final Property<Axis> HORIZONTAL_AXIS = BlockStateProperties.HORIZONTAL_AXIS;\n\tpublic static final BooleanProperty LARGE = BooleanProperty.create(\"large\");\n\n\n\tpublic RedContainerBlock(Properties p_i48440_1_) {\n\t\tsuper(p_i48440_1_);\n\t\tregisterDefaultState(defaultBlockState().setValue(LARGE, false));\n\t}\n\n\t@Override\n\tprotected void createBlockStateDefinition(Builder<Block, BlockState> pBuilder) {\n\t\tpBuilder.add(HORIZONTAL_AXIS, LARGE);\n\t\tsuper.createBlockStateDefinition(pBuilder);\n\t}\n\n\t@Override\n\tpublic BlockState getStateForPlacement(BlockPlaceContext pContext) {\n\t\tif (pContext.getPlayer() == null || !pContext.getPlayer()\n\t\t\t.isSteppingCarefully()) {\n\t\t\tBlockState placedOn = pContext.getLevel()\n\t\t\t\t.getBlockState(pContext.getClickedPos()\n\t\t\t\t\t.relative(pContext.getClickedFace()\n\t\t\t\t\t\t.getOpposite()));\n\t\t\tAxis preferredAxis = getContainerBlockAxis(placedOn);\n\t\t\tif (preferredAxis != null)\n\t\t\t\treturn this.defaultBlockState()\n\t\t\t\t\t.setValue(HORIZONTAL_AXIS, preferredAxis);\n\t\t}\n\t\treturn this.defaultBlockState()\n\t\t\t.setValue(HORIZONTAL_AXIS, pContext.getHorizontalDirection()\n\t\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic void onPlace(BlockState pState, Level pLevel, BlockPos pPos, BlockState pOldState, boolean pIsMoving) {\n\t\tif (pOldState.getBlock() == pState.getBlock())\n\t\t\treturn;\n\t\tif (pIsMoving)\n\t\t\treturn;\n\t\twithBlockEntityDo(pLevel, pPos, RedContainerBlockEntity::updateConnectivity);\n\t}\n\n\t@Override\n\tpublic InteractionResult onWrenched(BlockState state, UseOnContext context) {\n\t\tif (context.getClickedFace()\n\t\t\t.getAxis()\n\t\t\t.isVertical()) {\n\t\t\tBlockEntity be = context.getLevel()\n\t\t\t\t.getBlockEntity(context.getClickedPos());\n\t\t\tif (be instanceof RedContainerBlockEntity) {\n\t\t\t\tRedContainerBlockEntity container = (RedContainerBlockEntity) be;\n\t\t\t\tConnectivityHandler.splitMulti(container);\n\t\t\t\tcontainer.removeController(true);\n\t\t\t}\n\t\t\tstate = state.setValue(LARGE, false);\n\t\t}\n\t\tInteractionResult onWrenched = IWrenchable.super.onWrenched(state, context);\n\t\treturn onWrenched;\n\t}\n\n\t@Override\n\tpublic void onRemove(BlockState state, Level world, BlockPos pos, BlockState newState, boolean pIsMoving) {\n\t\tif (state.hasBlockEntity() && (state.getBlock() != newState.getBlock() || !newState.hasBlockEntity())) {\n\t\t\tBlockEntity be = world.getBlockEntity(pos);\n\t\t\tif (!(be instanceof RedContainerBlockEntity))\n\t\t\t\treturn;\n\t\t\tRedContainerBlockEntity containerBE = (RedContainerBlockEntity) be;\n\t\t\tItemHelper.dropContents(world, pos, containerBE.inventory);\n\t\t\tworld.removeBlockEntity(pos);\n\t\t\tConnectivityHandler.splitMulti(containerBE);\n\t\t}\n\t}\n\n\tpublic static boolean isContainer(BlockState state) {\n\n\n\t\treturn MmbBlocks.RED_CONTAINER.has(state);\n\t}\n\n\t@Nullable\n\tpublic static Axis getContainerBlockAxis(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn null;\n\t\treturn state.getValue(HORIZONTAL_AXIS);\n\t}\n\n\tpublic static boolean isLarge(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn false;\n\t\treturn state.getValue(LARGE);\n\t}\n\n\t@Override\n\tpublic BlockState rotate(BlockState state, Rotation rot) {\n\t\tAxis axis = state.getValue(HORIZONTAL_AXIS);\n\t\treturn state.setValue(HORIZONTAL_AXIS, rot.rotate(Direction.fromAxisAndDirection(axis, AxisDirection.POSITIVE))\n\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic BlockState mirror(BlockState state, Mirror mirrorIn) {\n\t\treturn state;\n\t}\n\n\n\tpublic static final SoundType SILENCED_METAL =\n\t\tnew ForgeSoundType(0.1F, 1.5F, () -> SoundEvents.NETHERITE_BLOCK_BREAK, () -> SoundEvents.NETHERITE_BLOCK_STEP,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_PLACE, () -> SoundEvents.NETHERITE_BLOCK_HIT,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_FALL);\n\n\t@Override\n\tpublic SoundType getSoundType(BlockState state, LevelReader world, BlockPos pos, Entity entity) {\n\t\tSoundType soundType = super.getSoundType(state, world, pos, entity);\n\t\tif (entity != null && entity.getPersistentData()\n\t\t\t.contains(\"SilenceVaultSound\"))\n\t\t\treturn SILENCED_METAL;\n\t\treturn soundType;\n\t}\n\n\t@Override\n\tpublic boolean hasAnalogOutputSignal(BlockState p_149740_1_) {\n\t\treturn true;\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"removal\")\n\tpublic int getAnalogOutputSignal(BlockState pState, Level pLevel, BlockPos pPos) {\n\t\treturn getBlockEntityOptional(pLevel, pPos)\n\t\t\t.map(vte -> vte.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY))\n\t\t\t.map(lo -> lo.map(ItemHelper::calcRedstoneFromInventory)\n\t\t\t\t.orElse(0))\n\t\t\t.orElse(0);\n\t}\n\n\t@Override\n\tpublic BlockEntityType<? extends RedContainerBlockEntity> getBlockEntityType() {\n\t\treturn MmbBlockEntities.RED_CONTAINER.get();\n\t}\n\n\t@Override\n\tpublic Class<RedContainerBlockEntity> getBlockEntityClass() {\n\t\treturn RedContainerBlockEntity.class;\n\t}\n\n\n\n\n\n\n}" }, { "identifier": "RedContainerCTBehaviour", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/red/RedContainerCTBehaviour.java", "snippet": "public class RedContainerCTBehaviour extends ConnectedTextureBehaviour.Base {\n\n\t@Override\n\tpublic CTSpriteShiftEntry getShift(BlockState state, Direction direction, @Nullable TextureAtlasSprite sprite) {\n\t\tAxis containerBlockAxis = RedContainerBlock.getContainerBlockAxis(state);\n\t\tboolean small = !RedContainerBlock.isLarge(state);\n\t\tif (containerBlockAxis == null)\n\t\t\treturn null;\n\n\t\tif (direction.getAxis() == containerBlockAxis)\n\t\t\treturn MmbSpriteShifts.RED_CONTAINER_FRONT.get(small);\n\t\tif (direction == Direction.UP)\n\t\t\treturn MmbSpriteShifts.RED_CONTAINER_TOP.get(small);\n\t\tif (direction == Direction.DOWN)\n\t\t\treturn MmbSpriteShifts.RED_CONTAINER_BOTTOM.get(small);\n\n\t\treturn MmbSpriteShifts.RED_CONTAINER_SIDE.get(small);\n\t}\n\n\t@Override\n\tprotected Direction getUpDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = RedContainerBlock.getContainerBlockAxis(state);\n\t\tboolean alongX = containerBlockAxis == Axis.X;\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && alongX)\n\t\t\treturn super.getUpDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getUpDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(containerBlockAxis, alongX ? AxisDirection.POSITIVE : AxisDirection.NEGATIVE);\n\t}\n\n\t@Override\n\tprotected Direction getRightDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = RedContainerBlock.getContainerBlockAxis(state);\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && containerBlockAxis == Axis.X)\n\t\t\treturn super.getRightDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getRightDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(Axis.Y, face.getAxisDirection());\n\t}\n\n\tpublic boolean buildContextForOccludedDirections() {\n\t\treturn super.buildContextForOccludedDirections();\n\t}\n\n\t@Override\n\tpublic boolean connectsTo(BlockState state, BlockState other, BlockAndTintGetter reader, BlockPos pos,\n\t\tBlockPos otherPos, Direction face) {\n\t\treturn state == other && ConnectivityHandler.isConnected(reader, pos, otherPos); //ItemVaultConnectivityHandler.isConnected(reader, pos, otherPos);\n\t}\n\n}" }, { "identifier": "RedContainerItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/red/RedContainerItem.java", "snippet": "public class RedContainerItem extends BlockItem {\n\n\tpublic RedContainerItem(Block p_i48527_1_, Properties p_i48527_2_) {\n\t\tsuper(p_i48527_1_, p_i48527_2_);\n\t}\n\n\t@Override\n\tpublic InteractionResult place(BlockPlaceContext ctx) {\n\t\tInteractionResult initialResult = super.place(ctx);\n\t\tif (!initialResult.consumesAction())\n\t\t\treturn initialResult;\n\t\ttryMultiPlace(ctx);\n\t\treturn initialResult;\n\t}\n\n\t@Override\n\tprotected boolean updateCustomBlockEntityTag(BlockPos p_195943_1_, Level p_195943_2_, Player p_195943_3_,\n\t\tItemStack p_195943_4_, BlockState p_195943_5_) {\n\t\tMinecraftServer minecraftserver = p_195943_2_.getServer();\n\t\tif (minecraftserver == null)\n\t\t\treturn false;\n\t\tCompoundTag nbt = p_195943_4_.getTagElement(\"BlockEntityTag\");\n\t\tif (nbt != null) {\n\t\t\tnbt.remove(\"Length\");\n\t\t\tnbt.remove(\"Size\");\n\t\t\tnbt.remove(\"Controller\");\n\t\t\tnbt.remove(\"LastKnownPos\");\n\t\t}\n\t\treturn super.updateCustomBlockEntityTag(p_195943_1_, p_195943_2_, p_195943_3_, p_195943_4_, p_195943_5_);\n\t}\n\n\tpublic void tryMultiPlace(BlockPlaceContext ctx) {\n\t\tPlayer player = ctx.getPlayer();\n\t\tif (player == null)\n\t\t\treturn;\n\t\tif (player.isSteppingCarefully())\n\t\t\treturn;\n\t\tDirection face = ctx.getClickedFace();\n\t\tItemStack stack = ctx.getItemInHand();\n\t\tLevel world = ctx.getLevel();\n\t\tBlockPos pos = ctx.getClickedPos();\n\t\tBlockPos placedOnPos = pos.relative(face.getOpposite());\n\t\tBlockState placedOnState = world.getBlockState(placedOnPos);\n\n\t\tif (!RedContainerBlock.isContainer(placedOnState))\n\t\t\treturn;\n\t\tRedContainerBlockEntity tankAt = ConnectivityHandler.partAt(MmbBlockEntities.RED_CONTAINER.get(), world, placedOnPos);\n\t\tif (tankAt == null)\n\t\t\treturn;\n\t\tRedContainerBlockEntity controllerBE = tankAt.getControllerBE();\n\t\tif (controllerBE == null)\n\t\t\treturn;\n\n\t\tint width = controllerBE.radius;\n\t\tif (width == 1)\n\t\t\treturn;\n\n\t\tint tanksToPlace = 0;\n\t\tAxis vaultBlockAxis = RedContainerBlock.getContainerBlockAxis(placedOnState);\n\t\tif (vaultBlockAxis == null)\n\t\t\treturn;\n\t\tif (face.getAxis() != vaultBlockAxis)\n\t\t\treturn;\n\n\t\tDirection vaultFacing = Direction.fromAxisAndDirection(vaultBlockAxis, AxisDirection.POSITIVE);\n\t\tBlockPos startPos = face == vaultFacing.getOpposite() ? controllerBE.getBlockPos()\n\t\t\t.relative(vaultFacing.getOpposite())\n\t\t\t: controllerBE.getBlockPos()\n\t\t\t\t.relative(vaultFacing, controllerBE.length);\n\n\t\tif (VecHelper.getCoordinate(startPos, vaultBlockAxis) != VecHelper.getCoordinate(pos, vaultBlockAxis))\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\t\t\t\tif (RedContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!blockState.getMaterial()\n\t\t\t\t\t.isReplaceable())\n\t\t\t\t\treturn;\n\t\t\t\ttanksToPlace++;\n\t\t\t}\n\t\t}\n\n\t\tif (!player.isCreative() && stack.getCount() < tanksToPlace)\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\n\n\t\t\t\tif (RedContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\n\n\t\t\t\tBlockPlaceContext context = BlockPlaceContext.at(ctx, offsetPos, face);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.putBoolean(\"SilenceVaultSound\", true);\n\t\t\t\tsuper.place(context);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.remove(\"SilenceVaultSound\");\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "BlueContainerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/blue/BlueContainerBlock.java", "snippet": "public class BlueContainerBlock extends Block implements IWrenchable, IBE<BlueContainerBlockEntity> {\n\n\tpublic static final Property<Axis> HORIZONTAL_AXIS = BlockStateProperties.HORIZONTAL_AXIS;\n\tpublic static final BooleanProperty LARGE = BooleanProperty.create(\"large\");\n\n\n\tpublic BlueContainerBlock(Properties p_i48440_1_) {\n\t\tsuper(p_i48440_1_);\n\t\tregisterDefaultState(defaultBlockState().setValue(LARGE, false));\n\t}\n\n\t@Override\n\tprotected void createBlockStateDefinition(Builder<Block, BlockState> pBuilder) {\n\t\tpBuilder.add(HORIZONTAL_AXIS, LARGE);\n\t\tsuper.createBlockStateDefinition(pBuilder);\n\t}\n\n\t@Override\n\tpublic BlockState getStateForPlacement(BlockPlaceContext pContext) {\n\t\tif (pContext.getPlayer() == null || !pContext.getPlayer()\n\t\t\t.isSteppingCarefully()) {\n\t\t\tBlockState placedOn = pContext.getLevel()\n\t\t\t\t.getBlockState(pContext.getClickedPos()\n\t\t\t\t\t.relative(pContext.getClickedFace()\n\t\t\t\t\t\t.getOpposite()));\n\t\t\tAxis preferredAxis = getContainerBlockAxis(placedOn);\n\t\t\tif (preferredAxis != null)\n\t\t\t\treturn this.defaultBlockState()\n\t\t\t\t\t.setValue(HORIZONTAL_AXIS, preferredAxis);\n\t\t}\n\t\treturn this.defaultBlockState()\n\t\t\t.setValue(HORIZONTAL_AXIS, pContext.getHorizontalDirection()\n\t\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic void onPlace(BlockState pState, Level pLevel, BlockPos pPos, BlockState pOldState, boolean pIsMoving) {\n\t\tif (pOldState.getBlock() == pState.getBlock())\n\t\t\treturn;\n\t\tif (pIsMoving)\n\t\t\treturn;\n\t\twithBlockEntityDo(pLevel, pPos, BlueContainerBlockEntity::updateConnectivity);\n\t}\n\n\t@Override\n\tpublic InteractionResult onWrenched(BlockState state, UseOnContext context) {\n\t\tif (context.getClickedFace()\n\t\t\t.getAxis()\n\t\t\t.isVertical()) {\n\t\t\tBlockEntity be = context.getLevel()\n\t\t\t\t.getBlockEntity(context.getClickedPos());\n\t\t\tif (be instanceof BlueContainerBlockEntity) {\n\t\t\t\tBlueContainerBlockEntity container = (BlueContainerBlockEntity) be;\n\t\t\t\tConnectivityHandler.splitMulti(container);\n\t\t\t\tcontainer.removeController(true);\n\t\t\t}\n\t\t\tstate = state.setValue(LARGE, false);\n\t\t}\n\t\tInteractionResult onWrenched = IWrenchable.super.onWrenched(state, context);\n\t\treturn onWrenched;\n\t}\n\n\t@Override\n\tpublic void onRemove(BlockState state, Level world, BlockPos pos, BlockState newState, boolean pIsMoving) {\n\t\tif (state.hasBlockEntity() && (state.getBlock() != newState.getBlock() || !newState.hasBlockEntity())) {\n\t\t\tBlockEntity be = world.getBlockEntity(pos);\n\t\t\tif (!(be instanceof BlueContainerBlockEntity))\n\t\t\t\treturn;\n\t\t\tBlueContainerBlockEntity containerBE = (BlueContainerBlockEntity) be;\n\t\t\tItemHelper.dropContents(world, pos, containerBE.inventory);\n\t\t\tworld.removeBlockEntity(pos);\n\t\t\tConnectivityHandler.splitMulti(containerBE);\n\t\t}\n\t}\n\n\tpublic static boolean isContainer(BlockState state) {\n\n\n\t\treturn MmbBlocks.BLUE_CONTAINER.has(state);\n\t}\n\n\t@Nullable\n\tpublic static Axis getContainerBlockAxis(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn null;\n\t\treturn state.getValue(HORIZONTAL_AXIS);\n\t}\n\n\tpublic static boolean isLarge(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn false;\n\t\treturn state.getValue(LARGE);\n\t}\n\n\t@Override\n\tpublic BlockState rotate(BlockState state, Rotation rot) {\n\t\tAxis axis = state.getValue(HORIZONTAL_AXIS);\n\t\treturn state.setValue(HORIZONTAL_AXIS, rot.rotate(Direction.fromAxisAndDirection(axis, AxisDirection.POSITIVE))\n\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic BlockState mirror(BlockState state, Mirror mirrorIn) {\n\t\treturn state;\n\t}\n\n\n\tpublic static final SoundType SILENCED_METAL =\n\t\tnew ForgeSoundType(0.1F, 1.5F, () -> SoundEvents.NETHERITE_BLOCK_BREAK, () -> SoundEvents.NETHERITE_BLOCK_STEP,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_PLACE, () -> SoundEvents.NETHERITE_BLOCK_HIT,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_FALL);\n\n\t@Override\n\tpublic SoundType getSoundType(BlockState state, LevelReader world, BlockPos pos, Entity entity) {\n\t\tSoundType soundType = super.getSoundType(state, world, pos, entity);\n\t\tif (entity != null && entity.getPersistentData()\n\t\t\t.contains(\"SilenceVaultSound\"))\n\t\t\treturn SILENCED_METAL;\n\t\treturn soundType;\n\t}\n\n\t@Override\n\tpublic boolean hasAnalogOutputSignal(BlockState p_149740_1_) {\n\t\treturn true;\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"removal\")\n\tpublic int getAnalogOutputSignal(BlockState pState, Level pLevel, BlockPos pPos) {\n\t\treturn getBlockEntityOptional(pLevel, pPos)\n\t\t\t.map(vte -> vte.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY))\n\t\t\t.map(lo -> lo.map(ItemHelper::calcRedstoneFromInventory)\n\t\t\t\t.orElse(0))\n\t\t\t.orElse(0);\n\t}\n\n\t@Override\n\tpublic BlockEntityType<? extends BlueContainerBlockEntity> getBlockEntityType() {\n\t\treturn MmbBlockEntities.BLUE_CONTAINER.get();\n\t}\n\n\t@Override\n\tpublic Class<BlueContainerBlockEntity> getBlockEntityClass() {\n\t\treturn BlueContainerBlockEntity.class;\n\t}\n\n\n\n\n\n\n}" }, { "identifier": "BlueContainerCTBehaviour", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/blue/BlueContainerCTBehaviour.java", "snippet": "public class BlueContainerCTBehaviour extends ConnectedTextureBehaviour.Base {\n\n\t@Override\n\tpublic CTSpriteShiftEntry getShift(BlockState state, Direction direction, @Nullable TextureAtlasSprite sprite) {\n\t\tAxis containerBlockAxis = BlueContainerBlock.getContainerBlockAxis(state);\n\t\tboolean small = !BlueContainerBlock.isLarge(state);\n\t\tif (containerBlockAxis == null)\n\t\t\treturn null;\n\n\t\tif (direction.getAxis() == containerBlockAxis)\n\t\t\treturn MmbSpriteShifts.BLUE_CONTAINER_FRONT.get(small);\n\t\tif (direction == Direction.UP)\n\t\t\treturn MmbSpriteShifts.BLUE_CONTAINER_TOP.get(small);\n\t\tif (direction == Direction.DOWN)\n\t\t\treturn MmbSpriteShifts.BLUE_CONTAINER_BOTTOM.get(small);\n\n\t\treturn MmbSpriteShifts.BLUE_CONTAINER_SIDE.get(small);\n\t}\n\n\t@Override\n\tprotected Direction getUpDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = BlueContainerBlock.getContainerBlockAxis(state);\n\t\tboolean alongX = containerBlockAxis == Axis.X;\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && alongX)\n\t\t\treturn super.getUpDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getUpDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(containerBlockAxis, alongX ? AxisDirection.POSITIVE : AxisDirection.NEGATIVE);\n\t}\n\n\t@Override\n\tprotected Direction getRightDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = BlueContainerBlock.getContainerBlockAxis(state);\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && containerBlockAxis == Axis.X)\n\t\t\treturn super.getRightDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getRightDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(Axis.Y, face.getAxisDirection());\n\t}\n\n\tpublic boolean buildContextForOccludedDirections() {\n\t\treturn super.buildContextForOccludedDirections();\n\t}\n\n\t@Override\n\tpublic boolean connectsTo(BlockState state, BlockState other, BlockAndTintGetter reader, BlockPos pos,\n\t\tBlockPos otherPos, Direction face) {\n\t\treturn state == other && ConnectivityHandler.isConnected(reader, pos, otherPos); //ItemVaultConnectivityHandler.isConnected(reader, pos, otherPos);\n\t}\n\n}" }, { "identifier": "BlueContainerItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/blue/BlueContainerItem.java", "snippet": "public class BlueContainerItem extends BlockItem {\n\n\tpublic BlueContainerItem(Block p_i48527_1_, Properties p_i48527_2_) {\n\t\tsuper(p_i48527_1_, p_i48527_2_);\n\t}\n\n\t@Override\n\tpublic InteractionResult place(BlockPlaceContext ctx) {\n\t\tInteractionResult initialResult = super.place(ctx);\n\t\tif (!initialResult.consumesAction())\n\t\t\treturn initialResult;\n\t\ttryMultiPlace(ctx);\n\t\treturn initialResult;\n\t}\n\n\t@Override\n\tprotected boolean updateCustomBlockEntityTag(BlockPos p_195943_1_, Level p_195943_2_, Player p_195943_3_,\n\t\tItemStack p_195943_4_, BlockState p_195943_5_) {\n\t\tMinecraftServer minecraftserver = p_195943_2_.getServer();\n\t\tif (minecraftserver == null)\n\t\t\treturn false;\n\t\tCompoundTag nbt = p_195943_4_.getTagElement(\"BlockEntityTag\");\n\t\tif (nbt != null) {\n\t\t\tnbt.remove(\"Length\");\n\t\t\tnbt.remove(\"Size\");\n\t\t\tnbt.remove(\"Controller\");\n\t\t\tnbt.remove(\"LastKnownPos\");\n\t\t}\n\t\treturn super.updateCustomBlockEntityTag(p_195943_1_, p_195943_2_, p_195943_3_, p_195943_4_, p_195943_5_);\n\t}\n\n\tpublic void tryMultiPlace(BlockPlaceContext ctx) {\n\t\tPlayer player = ctx.getPlayer();\n\t\tif (player == null)\n\t\t\treturn;\n\t\tif (player.isSteppingCarefully())\n\t\t\treturn;\n\t\tDirection face = ctx.getClickedFace();\n\t\tItemStack stack = ctx.getItemInHand();\n\t\tLevel world = ctx.getLevel();\n\t\tBlockPos pos = ctx.getClickedPos();\n\t\tBlockPos placedOnPos = pos.relative(face.getOpposite());\n\t\tBlockState placedOnState = world.getBlockState(placedOnPos);\n\n\t\tif (!BlueContainerBlock.isContainer(placedOnState))\n\t\t\treturn;\n\t\tBlueContainerBlockEntity tankAt = ConnectivityHandler.partAt(MmbBlockEntities.BLUE_CONTAINER.get(), world, placedOnPos);\n\t\tif (tankAt == null)\n\t\t\treturn;\n\t\tBlueContainerBlockEntity controllerBE = tankAt.getControllerBE();\n\t\tif (controllerBE == null)\n\t\t\treturn;\n\n\t\tint width = controllerBE.radius;\n\t\tif (width == 1)\n\t\t\treturn;\n\n\t\tint tanksToPlace = 0;\n\t\tAxis vaultBlockAxis = BlueContainerBlock.getContainerBlockAxis(placedOnState);\n\t\tif (vaultBlockAxis == null)\n\t\t\treturn;\n\t\tif (face.getAxis() != vaultBlockAxis)\n\t\t\treturn;\n\n\t\tDirection vaultFacing = Direction.fromAxisAndDirection(vaultBlockAxis, AxisDirection.POSITIVE);\n\t\tBlockPos startPos = face == vaultFacing.getOpposite() ? controllerBE.getBlockPos()\n\t\t\t.relative(vaultFacing.getOpposite())\n\t\t\t: controllerBE.getBlockPos()\n\t\t\t\t.relative(vaultFacing, controllerBE.length);\n\n\t\tif (VecHelper.getCoordinate(startPos, vaultBlockAxis) != VecHelper.getCoordinate(pos, vaultBlockAxis))\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\t\t\t\tif (BlueContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!blockState.getMaterial()\n\t\t\t\t\t.isReplaceable())\n\t\t\t\t\treturn;\n\t\t\t\ttanksToPlace++;\n\t\t\t}\n\t\t}\n\n\t\tif (!player.isCreative() && stack.getCount() < tanksToPlace)\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\n\n\t\t\t\tif (BlueContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\n\n\t\t\t\tBlockPlaceContext context = BlockPlaceContext.at(ctx, offsetPos, face);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.putBoolean(\"SilenceVaultSound\", true);\n\t\t\t\tsuper.place(context);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.remove(\"SilenceVaultSound\");\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "GreenContainerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/green/GreenContainerBlock.java", "snippet": "public class GreenContainerBlock extends Block implements IWrenchable, IBE<GreenContainerBlockEntity> {\n\n\tpublic static final Property<Axis> HORIZONTAL_AXIS = BlockStateProperties.HORIZONTAL_AXIS;\n\tpublic static final BooleanProperty LARGE = BooleanProperty.create(\"large\");\n\n\n\tpublic GreenContainerBlock(Properties p_i48440_1_) {\n\t\tsuper(p_i48440_1_);\n\t\tregisterDefaultState(defaultBlockState().setValue(LARGE, false));\n\t}\n\n\t@Override\n\tprotected void createBlockStateDefinition(Builder<Block, BlockState> pBuilder) {\n\t\tpBuilder.add(HORIZONTAL_AXIS, LARGE);\n\t\tsuper.createBlockStateDefinition(pBuilder);\n\t}\n\n\t@Override\n\tpublic BlockState getStateForPlacement(BlockPlaceContext pContext) {\n\t\tif (pContext.getPlayer() == null || !pContext.getPlayer()\n\t\t\t.isSteppingCarefully()) {\n\t\t\tBlockState placedOn = pContext.getLevel()\n\t\t\t\t.getBlockState(pContext.getClickedPos()\n\t\t\t\t\t.relative(pContext.getClickedFace()\n\t\t\t\t\t\t.getOpposite()));\n\t\t\tAxis preferredAxis = getContainerBlockAxis(placedOn);\n\t\t\tif (preferredAxis != null)\n\t\t\t\treturn this.defaultBlockState()\n\t\t\t\t\t.setValue(HORIZONTAL_AXIS, preferredAxis);\n\t\t}\n\t\treturn this.defaultBlockState()\n\t\t\t.setValue(HORIZONTAL_AXIS, pContext.getHorizontalDirection()\n\t\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic void onPlace(BlockState pState, Level pLevel, BlockPos pPos, BlockState pOldState, boolean pIsMoving) {\n\t\tif (pOldState.getBlock() == pState.getBlock())\n\t\t\treturn;\n\t\tif (pIsMoving)\n\t\t\treturn;\n\t\twithBlockEntityDo(pLevel, pPos, GreenContainerBlockEntity::updateConnectivity);\n\t}\n\n\t@Override\n\tpublic InteractionResult onWrenched(BlockState state, UseOnContext context) {\n\t\tif (context.getClickedFace()\n\t\t\t.getAxis()\n\t\t\t.isVertical()) {\n\t\t\tBlockEntity be = context.getLevel()\n\t\t\t\t.getBlockEntity(context.getClickedPos());\n\t\t\tif (be instanceof GreenContainerBlockEntity) {\n\t\t\t\tGreenContainerBlockEntity container = (GreenContainerBlockEntity) be;\n\t\t\t\tConnectivityHandler.splitMulti(container);\n\t\t\t\tcontainer.removeController(true);\n\t\t\t}\n\t\t\tstate = state.setValue(LARGE, false);\n\t\t}\n\t\tInteractionResult onWrenched = IWrenchable.super.onWrenched(state, context);\n\t\treturn onWrenched;\n\t}\n\n\t@Override\n\tpublic void onRemove(BlockState state, Level world, BlockPos pos, BlockState newState, boolean pIsMoving) {\n\t\tif (state.hasBlockEntity() && (state.getBlock() != newState.getBlock() || !newState.hasBlockEntity())) {\n\t\t\tBlockEntity be = world.getBlockEntity(pos);\n\t\t\tif (!(be instanceof GreenContainerBlockEntity))\n\t\t\t\treturn;\n\t\t\tGreenContainerBlockEntity containerBE = (GreenContainerBlockEntity) be;\n\t\t\tItemHelper.dropContents(world, pos, containerBE.inventory);\n\t\t\tworld.removeBlockEntity(pos);\n\t\t\tConnectivityHandler.splitMulti(containerBE);\n\t\t}\n\t}\n\n\tpublic static boolean isContainer(BlockState state) {\n\n\n\t\treturn MmbBlocks.GREEN_CONTAINER.has(state);\n\t}\n\n\t@Nullable\n\tpublic static Axis getContainerBlockAxis(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn null;\n\t\treturn state.getValue(HORIZONTAL_AXIS);\n\t}\n\n\tpublic static boolean isLarge(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn false;\n\t\treturn state.getValue(LARGE);\n\t}\n\n\t@Override\n\tpublic BlockState rotate(BlockState state, Rotation rot) {\n\t\tAxis axis = state.getValue(HORIZONTAL_AXIS);\n\t\treturn state.setValue(HORIZONTAL_AXIS, rot.rotate(Direction.fromAxisAndDirection(axis, AxisDirection.POSITIVE))\n\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic BlockState mirror(BlockState state, Mirror mirrorIn) {\n\t\treturn state;\n\t}\n\n\n\tpublic static final SoundType SILENCED_METAL =\n\t\tnew ForgeSoundType(0.1F, 1.5F, () -> SoundEvents.NETHERITE_BLOCK_BREAK, () -> SoundEvents.NETHERITE_BLOCK_STEP,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_PLACE, () -> SoundEvents.NETHERITE_BLOCK_HIT,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_FALL);\n\n\t@Override\n\tpublic SoundType getSoundType(BlockState state, LevelReader world, BlockPos pos, Entity entity) {\n\t\tSoundType soundType = super.getSoundType(state, world, pos, entity);\n\t\tif (entity != null && entity.getPersistentData()\n\t\t\t.contains(\"SilenceVaultSound\"))\n\t\t\treturn SILENCED_METAL;\n\t\treturn soundType;\n\t}\n\n\t@Override\n\tpublic boolean hasAnalogOutputSignal(BlockState p_149740_1_) {\n\t\treturn true;\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"removal\")\n\tpublic int getAnalogOutputSignal(BlockState pState, Level pLevel, BlockPos pPos) {\n\t\treturn getBlockEntityOptional(pLevel, pPos)\n\t\t\t.map(vte -> vte.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY))\n\t\t\t.map(lo -> lo.map(ItemHelper::calcRedstoneFromInventory)\n\t\t\t\t.orElse(0))\n\t\t\t.orElse(0);\n\t}\n\n\t@Override\n\tpublic BlockEntityType<? extends GreenContainerBlockEntity> getBlockEntityType() {\n\t\treturn MmbBlockEntities.GREEN_CONTAINER.get();\n\t}\n\n\t@Override\n\tpublic Class<GreenContainerBlockEntity> getBlockEntityClass() {\n\t\treturn GreenContainerBlockEntity.class;\n\t}\n\n\n\n\n\n\n}" }, { "identifier": "GreenContainerCTBehaviour", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/green/GreenContainerCTBehaviour.java", "snippet": "public class GreenContainerCTBehaviour extends ConnectedTextureBehaviour.Base {\n\n\t@Override\n\tpublic CTSpriteShiftEntry getShift(BlockState state, Direction direction, @Nullable TextureAtlasSprite sprite) {\n\t\tAxis containerBlockAxis = GreenContainerBlock.getContainerBlockAxis(state);\n\t\tboolean small = !GreenContainerBlock.isLarge(state);\n\t\tif (containerBlockAxis == null)\n\t\t\treturn null;\n\n\t\tif (direction.getAxis() == containerBlockAxis)\n\t\t\treturn MmbSpriteShifts.GREEN_CONTAINER_FRONT.get(small);\n\t\tif (direction == Direction.UP)\n\t\t\treturn MmbSpriteShifts.GREEN_CONTAINER_TOP.get(small);\n\t\tif (direction == Direction.DOWN)\n\t\t\treturn MmbSpriteShifts.GREEN_CONTAINER_BOTTOM.get(small);\n\n\t\treturn MmbSpriteShifts.GREEN_CONTAINER_SIDE.get(small);\n\t}\n\n\t@Override\n\tprotected Direction getUpDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = GreenContainerBlock.getContainerBlockAxis(state);\n\t\tboolean alongX = containerBlockAxis == Axis.X;\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && alongX)\n\t\t\treturn super.getUpDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getUpDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(containerBlockAxis, alongX ? AxisDirection.POSITIVE : AxisDirection.NEGATIVE);\n\t}\n\n\t@Override\n\tprotected Direction getRightDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = GreenContainerBlock.getContainerBlockAxis(state);\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && containerBlockAxis == Axis.X)\n\t\t\treturn super.getRightDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getRightDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(Axis.Y, face.getAxisDirection());\n\t}\n\n\tpublic boolean buildContextForOccludedDirections() {\n\t\treturn super.buildContextForOccludedDirections();\n\t}\n\n\t@Override\n\tpublic boolean connectsTo(BlockState state, BlockState other, BlockAndTintGetter reader, BlockPos pos,\n\t\tBlockPos otherPos, Direction face) {\n\t\treturn state == other && ConnectivityHandler.isConnected(reader, pos, otherPos); //ItemVaultConnectivityHandler.isConnected(reader, pos, otherPos);\n\t}\n\n}" }, { "identifier": "GreenContainerItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/green/GreenContainerItem.java", "snippet": "public class GreenContainerItem extends BlockItem {\n\n\tpublic GreenContainerItem(Block p_i48527_1_, Properties p_i48527_2_) {\n\t\tsuper(p_i48527_1_, p_i48527_2_);\n\t}\n\n\t@Override\n\tpublic InteractionResult place(BlockPlaceContext ctx) {\n\t\tInteractionResult initialResult = super.place(ctx);\n\t\tif (!initialResult.consumesAction())\n\t\t\treturn initialResult;\n\t\ttryMultiPlace(ctx);\n\t\treturn initialResult;\n\t}\n\n\t@Override\n\tprotected boolean updateCustomBlockEntityTag(BlockPos p_195943_1_, Level p_195943_2_, Player p_195943_3_,\n\t\tItemStack p_195943_4_, BlockState p_195943_5_) {\n\t\tMinecraftServer minecraftserver = p_195943_2_.getServer();\n\t\tif (minecraftserver == null)\n\t\t\treturn false;\n\t\tCompoundTag nbt = p_195943_4_.getTagElement(\"BlockEntityTag\");\n\t\tif (nbt != null) {\n\t\t\tnbt.remove(\"Length\");\n\t\t\tnbt.remove(\"Size\");\n\t\t\tnbt.remove(\"Controller\");\n\t\t\tnbt.remove(\"LastKnownPos\");\n\t\t}\n\t\treturn super.updateCustomBlockEntityTag(p_195943_1_, p_195943_2_, p_195943_3_, p_195943_4_, p_195943_5_);\n\t}\n\n\tpublic void tryMultiPlace(BlockPlaceContext ctx) {\n\t\tPlayer player = ctx.getPlayer();\n\t\tif (player == null)\n\t\t\treturn;\n\t\tif (player.isSteppingCarefully())\n\t\t\treturn;\n\t\tDirection face = ctx.getClickedFace();\n\t\tItemStack stack = ctx.getItemInHand();\n\t\tLevel world = ctx.getLevel();\n\t\tBlockPos pos = ctx.getClickedPos();\n\t\tBlockPos placedOnPos = pos.relative(face.getOpposite());\n\t\tBlockState placedOnState = world.getBlockState(placedOnPos);\n\n\t\tif (!GreenContainerBlock.isContainer(placedOnState))\n\t\t\treturn;\n\t\tGreenContainerBlockEntity tankAt = ConnectivityHandler.partAt(MmbBlockEntities.GREEN_CONTAINER.get(), world, placedOnPos);\n\t\tif (tankAt == null)\n\t\t\treturn;\n\t\tGreenContainerBlockEntity controllerBE = tankAt.getControllerBE();\n\t\tif (controllerBE == null)\n\t\t\treturn;\n\n\t\tint width = controllerBE.radius;\n\t\tif (width == 1)\n\t\t\treturn;\n\n\t\tint tanksToPlace = 0;\n\t\tAxis vaultBlockAxis = GreenContainerBlock.getContainerBlockAxis(placedOnState);\n\t\tif (vaultBlockAxis == null)\n\t\t\treturn;\n\t\tif (face.getAxis() != vaultBlockAxis)\n\t\t\treturn;\n\n\t\tDirection vaultFacing = Direction.fromAxisAndDirection(vaultBlockAxis, AxisDirection.POSITIVE);\n\t\tBlockPos startPos = face == vaultFacing.getOpposite() ? controllerBE.getBlockPos()\n\t\t\t.relative(vaultFacing.getOpposite())\n\t\t\t: controllerBE.getBlockPos()\n\t\t\t\t.relative(vaultFacing, controllerBE.length);\n\n\t\tif (VecHelper.getCoordinate(startPos, vaultBlockAxis) != VecHelper.getCoordinate(pos, vaultBlockAxis))\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\t\t\t\tif (GreenContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!blockState.getMaterial()\n\t\t\t\t\t.isReplaceable())\n\t\t\t\t\treturn;\n\t\t\t\ttanksToPlace++;\n\t\t\t}\n\t\t}\n\n\t\tif (!player.isCreative() && stack.getCount() < tanksToPlace)\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\n\n\t\t\t\tif (GreenContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\n\n\t\t\t\tBlockPlaceContext context = BlockPlaceContext.at(ctx, offsetPos, face);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.putBoolean(\"SilenceVaultSound\", true);\n\t\t\t\tsuper.place(context);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.remove(\"SilenceVaultSound\");\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "MmbCrushingWheelBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/crushing_wheels/MmbCrushingWheelBlock.java", "snippet": "public class MmbCrushingWheelBlock extends CrushingWheelBlock {\n\n\tpublic MmbCrushingWheelBlock(Properties properties) {\n\t\tsuper(properties);\n\t}\n\n\n\t@Override\n\tpublic void onRemove(BlockState state, Level worldIn, BlockPos pos, BlockState newState, boolean isMoving) {\n\t\tfor (Direction d : Iterate.directions) {\n\t\t\tif (d.getAxis() == state.getValue(AXIS))\n\t\t\t\tcontinue;\n\t\t\tif (MmbBlocks.MMB_CRUSHING_WHEEL_CONTROLLER.has(worldIn.getBlockState(pos.relative(d))))\n\t\t\t\tworldIn.removeBlock(pos.relative(d), isMoving);\n\t\t\tif (AllBlocks.CRUSHING_WHEEL_CONTROLLER.has(worldIn.getBlockState(pos.relative(d))))\n\t\t\t\tworldIn.removeBlock(pos.relative(d), isMoving);\n\t\t}\n\n\t\tsuper.onRemove(state, worldIn, pos, newState, isMoving);\n\t}\n\n\n\tpublic void updateControllers(BlockState state, Level world, BlockPos pos, Direction side) {\n\t\tif (side.getAxis() == state.getValue(AXIS))\n\t\t\treturn;\n\t\tif (world == null)\n\t\t\treturn;\n\n\t\tBlockPos controllerPos = pos.relative(side);\n\t\tBlockPos otherWheelPos = pos.relative(side, 2);\n\n\t\tboolean controllerExists =\n\t\t\t\tMmbBlocks.MMB_CRUSHING_WHEEL_CONTROLLER.has(world.getBlockState(controllerPos));\n\t\tboolean controllerIsValid = controllerExists && world.getBlockState(controllerPos)\n\t\t\t\t.getValue(VALID);\n\t\tDirection controllerOldDirection = controllerExists ? world.getBlockState(controllerPos)\n\t\t\t\t.getValue(CrushingWheelControllerBlock.FACING) : null;\n\n\t\tboolean controllerShouldExist = false;\n\t\tboolean controllerShouldBeValid = false;\n\t\tDirection controllerNewDirection = Direction.DOWN;\n\n\t\tBlockState otherState = world.getBlockState(otherWheelPos);\n\t\tif (\n\t\t\t\tAllBlocks.CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.GRANITE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.DIORITE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.LIMESTONE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.OCHRUM_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.SCORCHIA_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.SCORIA_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.TUFF_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.VERIDIUM_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.DRIPSTONE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.DEEPSLATE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.CRIMSITE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.CALCITE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.ASURINE_CRUSHING_WHEEL.has(otherState)\n\n\t\t) {\n\t\t\tcontrollerShouldExist = true;\n\n\t\t\tCrushingWheelBlockEntity be = getBlockEntity(world, pos);\n\t\t\tCrushingWheelBlockEntity otherBE = getBlockEntity(world, otherWheelPos);\n\n\t\t\tif (be != null && otherBE != null && (be.getSpeed() > 0) != (otherBE.getSpeed() > 0)\n\t\t\t\t\t&& be.getSpeed() != 0) {\n\t\t\t\tAxis wheelAxis = state.getValue(AXIS);\n\t\t\t\tAxis sideAxis = side.getAxis();\n\t\t\t\tint controllerADO = Math.round(Math.signum(be.getSpeed())) * side.getAxisDirection()\n\t\t\t\t\t\t.getStep();\n\t\t\t\tVec3 controllerDirVec = new Vec3(wheelAxis == Axis.X ? 1 : 0, wheelAxis == Axis.Y ? 1 : 0,\n\t\t\t\t\t\twheelAxis == Axis.Z ? 1 : 0).cross(\n\t\t\t\t\t\tnew Vec3(sideAxis == Axis.X ? 1 : 0, sideAxis == Axis.Y ? 1 : 0, sideAxis == Axis.Z ? 1 : 0));\n\n\t\t\t\tcontrollerNewDirection = Direction.getNearest(controllerDirVec.x * controllerADO,\n\t\t\t\t\t\tcontrollerDirVec.y * controllerADO, controllerDirVec.z * controllerADO);\n\n\t\t\t\tcontrollerShouldBeValid = true;\n\t\t\t}\n\t\t\tif (otherState.getValue(AXIS) != state.getValue(AXIS))\n\t\t\t\tcontrollerShouldExist = false;\n\t\t}\n\n\t\tif (!controllerShouldExist) {\n\t\t\tif (controllerExists)\n\t\t\t\tworld.setBlockAndUpdate(controllerPos, Blocks.AIR.defaultBlockState());\n\t\t\treturn;\n\t\t}\n\n\t\tif (!controllerExists) {\n\t\t\tif (!world.getBlockState(controllerPos)\n\t\t\t\t\t.getMaterial()\n\t\t\t\t\t.isReplaceable())\n\t\t\t\treturn;\n\t\t\tworld.setBlockAndUpdate(controllerPos, MmbBlocks.MMB_CRUSHING_WHEEL_CONTROLLER.getDefaultState()\n\t\t\t\t\t.setValue(VALID, controllerShouldBeValid)\n\t\t\t\t\t.setValue(CrushingWheelControllerBlock.FACING, controllerNewDirection));\n\t\t} else if (controllerIsValid != controllerShouldBeValid || controllerOldDirection != controllerNewDirection) {\n\t\t\tworld.setBlockAndUpdate(controllerPos, world.getBlockState(controllerPos)\n\t\t\t\t\t.setValue(VALID, controllerShouldBeValid)\n\t\t\t\t\t.setValue(CrushingWheelControllerBlock.FACING, controllerNewDirection));\n\t\t}\n\n\t\t( MmbBlocks.MMB_CRUSHING_WHEEL_CONTROLLER.get())\n\t\t\t\t.updateSpeed(world.getBlockState(controllerPos), world, controllerPos);\n\n\t}\n\n\n\t@Override\n\tpublic boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) {\n\t\tfor (Direction direction : Iterate.directions) {\n\t\t\tBlockPos neighbourPos = pos.relative(direction);\n\t\t\tBlockState neighbourState = worldIn.getBlockState(neighbourPos);\n\t\t\tAxis stateAxis = state.getValue(AXIS);\n\t\t\tif (MmbBlocks.MMB_CRUSHING_WHEEL_CONTROLLER.has(neighbourState) && direction.getAxis() != stateAxis)\n\t\t\t\treturn false;\n\t\t\tif (AllBlocks.CRUSHING_WHEEL_CONTROLLER.has(neighbourState) && direction.getAxis() != stateAxis)\n\t\t\t\treturn false;\n\t\t\tif (!(worldIn.getBlockState(neighbourPos).getBlock() instanceof CrushingWheelBlock))\n\t\t\t\tcontinue;\n\t\t\tif (neighbourState.getValue(AXIS) != stateAxis || stateAxis != direction.getAxis())\n\t\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic Class<CrushingWheelBlockEntity> getBlockEntityClass() {\n\t\treturn CrushingWheelBlockEntity.class;\n\t}\n\t\n\t@Override\n\tpublic BlockEntityType<? extends CrushingWheelBlockEntity> getBlockEntityType() {\n\t\treturn MmbBlockEntities.MMB_CRUSHING_WHEEL.get();\n\t}\n\n}" }, { "identifier": "MmbCrushingWheelControllerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/crushing_wheels/MmbCrushingWheelControllerBlock.java", "snippet": "public class MmbCrushingWheelControllerBlock extends CrushingWheelControllerBlock {\n\n\tpublic MmbCrushingWheelControllerBlock(Properties p_i48440_1_) {\n\t\tsuper(p_i48440_1_);\n\t}\n\n\n\t@Override\n\tpublic boolean canBeReplaced(BlockState state, BlockPlaceContext useContext) {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean addRunningEffects(BlockState state, Level world, BlockPos pos, Entity entity) {\n\t\treturn true;\n\t}\n\n\t@Override\n\tprotected void createBlockStateDefinition(Builder<Block, BlockState> builder) {\n\t\tsuper.createBlockStateDefinition(builder);\n\t}\n\n\tpublic void entityInside(BlockState state, Level worldIn, BlockPos pos, Entity entityIn) {\n\t\tif (!state.getValue(VALID))\n\t\t\treturn;\n\n\t\tDirection facing = state.getValue(FACING);\n\t\tAxis axis = facing.getAxis();\n\n\t\tcheckEntityForProcessing(worldIn, pos, entityIn);\n\n\t\twithBlockEntityDo(worldIn, pos, be -> {\n\t\t\tif (be.processingEntity == entityIn)\n\n\t\t\t\tentityIn.makeStuckInBlock(state, new Vec3(axis == Axis.X ? (double) 0.05F : 0.25D,\n\t\t\t\t\taxis == Axis.Y ? (double) 0.05F : 0.25D, axis == Axis.Z ? (double) 0.05F : 0.25D));\n\t\t});\n\t}\n\n\tpublic void checkEntityForProcessing(Level worldIn, BlockPos pos, Entity entityIn) {\n\t\tCrushingWheelControllerBlockEntity be = getBlockEntity(worldIn, pos);\n\t\tif (be == null)\n\t\t\treturn;\n\t\tif (be.crushingspeed == 0)\n\t\t\treturn;\n//\t\tif (entityIn instanceof ItemEntity)\n//\t\t\t((ItemEntity) entityIn).setPickUpDelay(10);\n\t\tCompoundTag data = entityIn.getPersistentData();\n\t\tif (data.contains(\"BypassCrushingWheel\")) {\n\t\t\tif (pos.equals(NbtUtils.readBlockPos(data.getCompound(\"BypassCrushingWheel\"))))\n\t\t\t\treturn;\n\t\t}\n\t\tif (be.isOccupied())\n\t\t\treturn;\n\t\tboolean isPlayer = entityIn instanceof Player;\n\t\tif (isPlayer && ((Player) entityIn).isCreative())\n\t\t\treturn;\n\t\tif (isPlayer && entityIn.level.getDifficulty() == Difficulty.PEACEFUL)\n\t\t\treturn;\n\n\t\tbe.startCrushing(entityIn);\n\t}\n\n\t@Override\n\tpublic void updateEntityAfterFallOn(BlockGetter worldIn, Entity entityIn) {\n\t\tsuper.updateEntityAfterFallOn(worldIn, entityIn);\n\t\t// Moved to onEntityCollision to allow for omnidirectional input\n\t}\n\n\t@Override\n\tpublic void animateTick(BlockState stateIn, Level worldIn, BlockPos pos, RandomSource rand) {\n\t\tif (!stateIn.getValue(VALID))\n\t\t\treturn;\n\t\tif (rand.nextInt(1) != 0)\n\t\t\treturn;\n\t\tdouble d0 = (double) ((float) pos.getX() + rand.nextFloat());\n\t\tdouble d1 = (double) ((float) pos.getY() + rand.nextFloat());\n\t\tdouble d2 = (double) ((float) pos.getZ() + rand.nextFloat());\n\t\tworldIn.addParticle(ParticleTypes.CRIT, d0, d1, d2, 0.0D, 0.0D, 0.0D);\n\t}\n\n\t@Override\n\tpublic BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn,\n\t\tBlockPos currentPos, BlockPos facingPos) {\n\t\tupdateSpeed(stateIn, worldIn, currentPos);\n\t\treturn stateIn;\n\t}\n\n\tpublic void updateSpeed(BlockState state, LevelAccessor world, BlockPos pos) {\n\t\twithBlockEntityDo(world, pos, be -> {\n\t\t\tif (!state.getValue(VALID)) {\n\t\t\t\tif (be.crushingspeed != 0) {\n\t\t\t\t\tbe.crushingspeed = 0;\n\t\t\t\t\tbe.sendData();\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (Direction d : Iterate.directions) {\n\t\t\t\tBlockState neighbour = world.getBlockState(pos.relative(d));\n\t\t\t\tif (\n\t\t\t\t\t\t!MmbBlocks.GRANITE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t\t\t!MmbBlocks.DIORITE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t\t\t\t\t!AllBlocks.CRUSHING_WHEEL.has(neighbour)&&\n\n\t\t\t\t\t\t\t\t!MmbBlocks.LIMESTONE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.OCHRUM_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.SCORCHIA_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.SCORIA_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.TUFF_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.VERIDIUM_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.DRIPSTONE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.DEEPSLATE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.CRIMSITE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.CALCITE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.ASURINE_CRUSHING_WHEEL.has(neighbour))\n\t\t\t\t\tcontinue;\n\t\t\t\tif (neighbour.getValue(BlockStateProperties.AXIS) == d.getAxis())\n\t\t\t\t\tcontinue;\n\t\t\t\tBlockEntity adjBE = world.getBlockEntity(pos.relative(d));\n\t\t\t\tif (!(adjBE instanceof CrushingWheelBlockEntity cwbe))\n\t\t\t\t\tcontinue;\n\t\t\t\tbe.crushingspeed = Math.abs(cwbe.getSpeed() / 50f);\n\t\t\t\tbe.sendData();\n\n\t\t\t\tcwbe.award(AllAdvancements.CRUSHING_WHEEL);\n\t\t\t\tif (cwbe.getSpeed() > 255)\n\t\t\t\t\tcwbe.award(AllAdvancements.CRUSHER_MAXED);\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tpublic VoxelShape getCollisionShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) {\n\t\tVoxelShape standardShape = AllShapes.CRUSHING_WHEEL_CONTROLLER_COLLISION.get(state.getValue(FACING));\n\n\t\tif (!state.getValue(VALID))\n\t\t\treturn standardShape;\n\t\tif (!(context instanceof EntityCollisionContext))\n\t\t\treturn standardShape;\n\t\tEntity entity = ((EntityCollisionContext) context).getEntity();\n\t\tif (entity == null)\n\t\t\treturn standardShape;\n\n\t\tCompoundTag data = entity.getPersistentData();\n\t\tif (data.contains(\"BypassCrushingWheel\"))\n\t\t\tif (pos.equals(NbtUtils.readBlockPos(data.getCompound(\"BypassCrushingWheel\"))))\n\t\t\t\tif (state.getValue(FACING) != Direction.UP) // Allow output items to land on top of the block rather\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// than falling back through.\n\t\t\t\t\treturn Shapes.empty();\n\n\t\tCrushingWheelControllerBlockEntity be = getBlockEntity(worldIn, pos);\n\t\tif (be != null && be.processingEntity == entity)\n\t\t\treturn Shapes.empty();\n\n\t\treturn standardShape;\n\t}\n\n\t@Override\n\tpublic void onRemove(BlockState state, Level worldIn, BlockPos pos, BlockState newState, boolean isMoving) {\n\t\tif (!state.hasBlockEntity() || state.getBlock() == newState.getBlock())\n\t\t\treturn;\n\n\t\twithBlockEntityDo(worldIn, pos, be -> ItemHelper.dropContents(worldIn, pos, be.inventory));\n\t\tworldIn.removeBlockEntity(pos);\n\t}\n\n\t@Override\n\tpublic Class<CrushingWheelControllerBlockEntity> getBlockEntityClass() {\n\t\treturn CrushingWheelControllerBlockEntity.class;\n\t}\n\n\t@Override\n\tpublic BlockEntityType<? extends CrushingWheelControllerBlockEntity> getBlockEntityType() {\n\t\treturn MmbBlockEntities.MMB_CRUSHING_WHEEL_CONTROLLER.get();\n\t}\n\n\t@Override\n\tpublic boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) {\n\t\treturn false;\n\t}\n\n}" }, { "identifier": "DiagonalGirderBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/diagonal_girder/DiagonalGirderBlock.java", "snippet": "@SuppressWarnings({\"unused\",\"deprecation\"})\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class DiagonalGirderBlock extends DirectionalBlock implements SimpleWaterloggedBlock, IWrenchable {\n\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n public static final BooleanProperty FACING_UP = BooleanProperty.create(\"facing_up\");\n public DiagonalGirderBlock(Properties p_54120_) {\n super(p_54120_);\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE).setValue(FACING, Direction.NORTH).setValue(FACING_UP, false));\n }\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_55125_) {\n p_55125_.add(WATERLOGGED,FACING, FACING_UP);\n }\n\n public static final VoxelShape SHAPE_EAST = eShape();\n public static final VoxelShape SHAPE_WEST = wShape();\n public static final VoxelShape SHAPE_NORTH = nShape();\n public static final VoxelShape SHAPE_SOUTH = sShape();\n\n public static final VoxelShape SHAPE_UP_EAST = ueShape();\n public static final VoxelShape SHAPE_UP_WEST = uwShape();\n public static final VoxelShape SHAPE_UP_NORTH = unShape();\n public static final VoxelShape SHAPE_UP_SOUTH = usShape();\n\n public static VoxelShape nShape(){\n return Shapes.or(\n Block.box(3, 3, 0, 13, 13, 5),\n Block.box(3, 0, 3, 13, 5, 13),\n Block.box(4, 5, 5, 12, 12, 12)\n );\n }\n public static VoxelShape eShape(){\n return Shapes.or(\n Block.box(11, 3, 3, 16, 13, 13),\n Block.box(3, 0, 3, 13, 5, 13),\n Block.box(4, 5, 4, 11, 12, 12)\n );\n }\n\n public static VoxelShape sShape(){\n return Shapes.or(\n Block.box(3, 3, 11, 13, 13, 16),\n Block.box(3, 0, 3, 13, 5, 13),\n Block.box(4, 5, 4, 12, 12, 11)\n );\n }\n\n public static VoxelShape wShape(){\n return Shapes.or(\n Block.box(0, 3, 3, 5, 13, 13),\n Block.box(3, 0, 3, 13, 5, 13),\n Block.box(5, 5, 4, 12, 12, 12)\n );\n }\n\n public static VoxelShape unShape(){\n return Shapes.or(\n Block.box(3, 3, 0, 13, 13, 5),\n Block.box(3, 11, 3, 13, 16, 13),\n Block.box(4, 4, 5, 12, 11, 12)\n );\n }\n public static VoxelShape ueShape(){\n return Shapes.or(\n Block.box(11, 3, 3, 16, 13, 13),\n Block.box(3, 11, 3, 13, 16, 13),\n Block.box(4, 4, 4, 11, 11, 12)\n );\n }\n\n public static VoxelShape usShape(){\n return Shapes.or(\n Block.box(3, 3, 11, 13, 13, 16),\n Block.box(3, 11, 3, 13, 16, 13),\n Block.box(4, 4, 4, 12, 11, 11)\n );\n }\n\n public static VoxelShape uwShape(){\n return Shapes.or(\n Block.box(0, 3, 3, 5, 13, 13),\n Block.box(3, 11, 3, 13, 16, 13),\n Block.box(5, 4, 4, 12, 11, 12)\n );\n }\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n public VoxelShape getShape(BlockState p_54561_, BlockGetter p_54562_, BlockPos p_54563_, CollisionContext p_54564_) {\n if (!p_54561_.getValue(FACING_UP)) {\n return switch (p_54561_.getValue(FACING)) {\n case NORTH, UP, DOWN -> SHAPE_NORTH;\n case SOUTH -> SHAPE_SOUTH;\n case EAST -> SHAPE_EAST;\n case WEST -> SHAPE_WEST;\n };\n }\n if (p_54561_.getValue(FACING_UP)) {\n return switch (p_54561_.getValue(FACING)) {\n case NORTH, UP, DOWN -> SHAPE_UP_NORTH;\n case SOUTH -> SHAPE_UP_SOUTH;\n case EAST -> SHAPE_UP_EAST;\n case WEST -> SHAPE_UP_WEST;\n };\n }\n return SHAPE_NORTH;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n InteractionResult onWrenched = IWrenchable.super.onWrenched(state, context);\n if (!onWrenched.consumesAction())\n return onWrenched;\n\n context.getLevel().setBlock(context.getClickedPos(),state.setValue(FACING_UP,!state.getValue(FACING_UP)),2);\n\n playRotateSound(context.getLevel(), context.getClickedPos());\n return onWrenched;\n }\n\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n FluidState fluidstate = context.getLevel().getFluidState(context.getClickedPos());\n boolean flag = fluidstate.getType() == Fluids.WATER;\n Direction facing = Objects.requireNonNull(context.getPlayer()).getDirection();\n Direction clickedFace = context.getClickedFace();\n\n if (context.getPlayer() != null && context.getPlayer().isShiftKeyDown()) {\n if (clickedFace == Direction.DOWN)\n return defaultBlockState().setValue(FACING, facing.getOpposite()).setValue(FACING_UP,true).setValue(WATERLOGGED, flag);\n else\n return defaultBlockState().setValue(FACING, facing.getOpposite()).setValue(FACING_UP,false).setValue(WATERLOGGED, flag);\n }\n if (clickedFace == Direction.DOWN)\n return defaultBlockState().setValue(FACING, facing).setValue(FACING_UP,true).setValue(WATERLOGGED, flag);\n\n\n return defaultBlockState().setValue(FACING, facing).setValue(FACING_UP,false).setValue(WATERLOGGED, flag);\n }\n}" }, { "identifier": "DiagonalGirderGenerator", "path": "src/main/java/com/mangomilk/design_decor/blocks/diagonal_girder/DiagonalGirderGenerator.java", "snippet": "public class DiagonalGirderGenerator extends SpecialBlockStateGen {\n\n @Override\n protected int getXRotation(BlockState state) {\n return 0;\n }\n\n @Override\n protected int getYRotation(BlockState state) {\n return switch (state.getValue(DiagonalGirderBlock.FACING)) {\n case NORTH -> 270;\n case SOUTH -> 90;\n case WEST -> 180;\n case EAST -> 0;\n case DOWN -> 0;\n case UP -> 0;\n };\n }\n\n @Override\n public <T extends Block> ModelFile getModel(DataGenContext<Block, T> ctx, RegistrateBlockstateProvider prov,\n BlockState state) {\n // return AssetLookup.forPowered(ctx, prov)\n // .apply(state);\n\n return state.getValue(DiagonalGirderBlock.FACING_UP) ? partialBaseModel(ctx, prov, \"up\")\n : partialBaseModel(ctx, prov);\n }\n\n}" }, { "identifier": "FloodlightBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/floodlight/FloodlightBlock.java", "snippet": "@SuppressWarnings({\"unused\",\"deprecation\"})\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class FloodlightBlock extends DirectionalBlock implements SimpleWaterloggedBlock, IWrenchable {\n\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n public static final BooleanProperty TURNED_ON = BooleanProperty.create(\"turned_on\");\n public static final BooleanProperty WRENCHED = BooleanProperty.create(\"wrenched\");\n\n public static final VoxelShape SHAPE_DOWN = Block.box(3.0D, 8.0D, 3.0D, 13.0D, 16.0D, 13.0D);\n public static final VoxelShape SHAPE_UP = Block.box(3.0D, 0.0D, 3.0D, 13.0D, 8.0D, 13.0D);\n\n public static final VoxelShape SHAPE_EAST = Block.box(0.0D, 3.0D, 3.0D, 8.0D, 13.0D, 13.0D);\n public static final VoxelShape SHAPE_WEST = Block.box(8.0D, 3.0D, 3.0D, 16.0D, 13.0D, 13.0D);\n public static final VoxelShape SHAPE_NORTH = Block.box(3.0D, 3.0D, 8.0D, 13.0D, 13.0D, 16.0D);\n public static final VoxelShape SHAPE_SOUTH = Block.box(3.0D, 3.0D, 0.0D, 13.0D, 13.0D, 8.0D);\n public FloodlightBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE).setValue(FACING, Direction.UP).setValue(TURNED_ON, false).setValue(WRENCHED, false));\n }\n\n public VoxelShape getShape(BlockState p_54561_, BlockGetter p_54562_, BlockPos p_54563_, CollisionContext p_54564_) {\n return switch (p_54561_.getValue(FACING)) {\n case NORTH -> SHAPE_NORTH;\n case SOUTH -> SHAPE_SOUTH;\n case EAST -> SHAPE_EAST;\n case WEST -> SHAPE_WEST;\n case UP -> SHAPE_UP;\n case DOWN -> SHAPE_DOWN;\n default -> SHAPE_NORTH;\n };\n }\n\n @Override\n public void neighborChanged(BlockState pState, Level pLevel, BlockPos pPos, Block pBlock, BlockPos pFromPos,\n boolean pIsMoving) {\n if (pLevel.isClientSide)\n return;\n boolean beenWrenched = pState.getValue(WRENCHED);\n\n if (!beenWrenched && pLevel.hasNeighborSignal(pPos)) {\n pLevel.setBlock(pPos,pState.setValue(TURNED_ON,!pState.getValue(TURNED_ON)), 2);\n }\n }\n\n public void tick(BlockState p_221937_, ServerLevel p_221938_, BlockPos p_221939_, RandomSource p_221940_) {\n if (p_221937_.getValue(TURNED_ON) && p_221938_.hasNeighborSignal(p_221939_) != p_221937_.getValue(WRENCHED)) {\n p_221938_.setBlock(p_221939_, p_221937_.setValue(TURNED_ON, false), 2);\n }\n }\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n InteractionResult onWrenched = IWrenchable.super.onWrenched(state, context);\n if (!onWrenched.consumesAction())\n return onWrenched;\n boolean isOn = state.getValue(TURNED_ON);\n\n context.getLevel().setBlock(context.getClickedPos(),state.setValue(TURNED_ON,!state.getValue(TURNED_ON)).setValue(WRENCHED,!state.getValue(WRENCHED)),2);\n\n playRotateSound(context.getLevel(), context.getClickedPos());\n\n if (!isOn) {\n context.getLevel().playLocalSound(context.getClickedPos().getX(), context.getClickedPos().getY(), context.getClickedPos().getZ(),\n DecoSoundEvents.FLOODLIGHT_ON.get(), SoundSource.BLOCKS, 0.25F, Create.RANDOM.nextFloat() * 0.2F + 1.6F, false);\n }\n if (isOn) {\n context.getLevel().playLocalSound(context.getClickedPos().getX(), context.getClickedPos().getY(), context.getClickedPos().getZ(),\n DecoSoundEvents.FLOODLIGHT_OFF.get(), SoundSource.BLOCKS, 0.25F, Create.RANDOM.nextFloat() * 0.2F + 0.8F, false);\n }\n return onWrenched;\n }\n\n\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n\n @Override\n public boolean isPathfindable(BlockState p_51456_, BlockGetter p_51457_, BlockPos p_51458_, PathComputationType p_51459_) {\n return false;\n }\n\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_55125_) {\n p_55125_.add(WATERLOGGED,FACING,TURNED_ON,WRENCHED);\n }\n\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_58126_) {\n FluidState fluidstate = p_58126_.getLevel().getFluidState(p_58126_.getClickedPos());\n boolean flag = fluidstate.getType() == Fluids.WATER;\n\n BlockState blockstate = this.defaultBlockState();\n LevelReader levelreader = p_58126_.getLevel();\n BlockPos blockpos = p_58126_.getClickedPos();\n Direction[] adirection = p_58126_.getNearestLookingDirections();\n\n for(Direction direction : adirection) {\n Direction direction1 = direction.getOpposite();\n blockstate = blockstate.setValue(FACING, direction1).setValue(WATERLOGGED, flag);\n return blockstate;\n }\n\n return Objects.requireNonNull(super.getStateForPlacement(p_58126_)).setValue(WATERLOGGED, flag);\n }\n\n\n public void FloodlightSoundOff(Level p_49713_, BlockPos p_49714_, @Nullable Direction p_49715_) {\n this.FloodlightSoundOff((Entity) null, p_49713_, p_49714_, p_49715_);\n }\n\n public boolean FloodlightSoundOff(@Nullable Entity p_152189_, Level p_152190_, BlockPos p_152191_, @Nullable Direction p_152192_) {\n BlockEntity blockentity = p_152190_.getBlockEntity(p_152191_);\n if (!p_152190_.isClientSide) {\n\n p_152190_.playSound((Player)null, p_152191_, DecoSoundEvents.FLOODLIGHT_OFF.get(), SoundSource.BLOCKS, 0.25F, Create.RANDOM.nextFloat() * 0.2F + 0.8F);\n p_152190_.gameEvent(p_152189_, GameEvent.BLOCK_CHANGE, p_152191_);\n return true;\n } else {\n return false;\n }\n }\n\n public void FloodlightSoundOn(Level p_49713_, BlockPos p_49714_, @Nullable Direction p_49715_) {\n this.FloodlightSoundOn((Entity) null, p_49713_, p_49714_, p_49715_);\n }\n\n public boolean FloodlightSoundOn(@Nullable Entity p_152189_, Level p_152190_, BlockPos p_152191_, @Nullable Direction p_152192_) {\n BlockEntity blockentity = p_152190_.getBlockEntity(p_152191_);\n if (!p_152190_.isClientSide) {\n\n p_152190_.playSound((Player)null, p_152191_, DecoSoundEvents.FLOODLIGHT_ON.get(), SoundSource.BLOCKS, 0.25F, Create.RANDOM.nextFloat() * 0.2F + 1.6F);\n p_152190_.gameEvent(p_152189_, GameEvent.BLOCK_CHANGE, p_152191_);\n return true;\n } else {\n return false;\n }\n }\n}" }, { "identifier": "FloodlightGenerator", "path": "src/main/java/com/mangomilk/design_decor/blocks/floodlight/FloodlightGenerator.java", "snippet": "public class FloodlightGenerator extends SpecialBlockStateGen {\n public FloodlightGenerator() {\n }\n\n protected int getXRotation(BlockState state) {\n short value;\n switch ((Direction)state.getValue(FloodlightBlock.FACING)) {\n case NORTH:\n value = 0;\n break;\n case SOUTH:\n value = 0;\n break;\n case WEST:\n value = 0;\n break;\n case EAST:\n value = 0;\n break;\n case DOWN:\n value = 90;\n break;\n case UP:\n value = 270;\n break;\n default:\n throw new IncompatibleClassChangeError();\n }\n\n return value;\n }\n\n protected int getYRotation(BlockState state) {\n short value;\n switch ((Direction)state.getValue(FloodlightBlock.FACING)) {\n case NORTH:\n value = 0;\n break;\n case SOUTH:\n value = 180;\n break;\n case WEST:\n value = 270;\n break;\n case EAST:\n value = 90;\n break;\n case DOWN:\n value = 0;\n break;\n case UP:\n value = 0;\n break;\n default:\n throw new IncompatibleClassChangeError();\n }\n\n return value;\n }\n\n public <T extends Block> ModelFile getModel(DataGenContext<Block, T> ctx, RegistrateBlockstateProvider prov, BlockState state) {\n return (Boolean)state.getValue(FloodlightBlock.TURNED_ON) ? AssetLookup.partialBaseModel(ctx, prov, new String[]{\"on\"}) : AssetLookup.partialBaseModel(ctx, prov, new String[0]);\n }\n}" }, { "identifier": "GasTankBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/gas_tank/GasTankBlock.java", "snippet": "public class GasTankBlock extends Block implements SimpleWaterloggedBlock, IWrenchable, IBE<GasTankBlockEntity> {\n\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n\n public GasTankBlock(Properties p_49795_) {\n super(p_49795_);\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE));\n }\n\n public VoxelShape getShape(BlockState p_54561_, BlockGetter p_54562_, BlockPos p_54563_, CollisionContext p_54564_) {\n return Block.box(1, 0, 1, 15, 16, 15);\n }\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_55125_) {\n p_55125_.add(WATERLOGGED);\n }\n @Override\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_152019_) {\n LevelAccessor levelaccessor = p_152019_.getLevel();\n BlockPos blockpos = p_152019_.getClickedPos();\n return this.defaultBlockState().setValue(WATERLOGGED, levelaccessor.getFluidState(blockpos).getType() == Fluids.WATER);\n }\n\n @Override\n public Class<GasTankBlockEntity> getBlockEntityClass() {\n return GasTankBlockEntity.class;\n }\n\n @Override\n public BlockEntityType<? extends GasTankBlockEntity> getBlockEntityType() {\n return MmbBlockEntities.GAS_TANK.get();\n }\n}" }, { "identifier": "ConnectedTintedGlassBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/glass/ConnectedTintedGlassBlock.java", "snippet": "public class ConnectedTintedGlassBlock extends TintedGlassBlock {\n public ConnectedTintedGlassBlock(Properties p_154822_) {\n super(p_154822_);\n }\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public boolean skipRendering(BlockState state, BlockState adjacentBlockState, Direction side) {\n return adjacentBlockState.getBlock() instanceof ConnectedTintedGlassBlock || super.skipRendering(state, adjacentBlockState, side);\n }\n\n @Override\n public boolean shouldDisplayFluidOverlay(BlockState state, BlockAndTintGetter world, BlockPos pos, FluidState fluidState) {\n return true;\n }\n}" }, { "identifier": "IndustrialGearBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/industrial_gear/IndustrialGearBlock.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class IndustrialGearBlock extends ShaftBlock implements ICogWheel, EncasableBlock {\n boolean isLarge;\n\n VoxelShape largeY = Shapes.join(Block.box(-2, 2, -2, 18, 14, 18),\n Block.box(5, 0, 5, 11, 16, 11), BooleanOp.OR);\n VoxelShape smallY = Shapes.join(Block.box(1, 2, 1, 15, 14, 15),\n Block.box(5, 0, 5, 11, 16, 11), BooleanOp.OR);\n\n VoxelShape largeX = Shapes.join(Block.box(2, -2, -2, 14, 18, 18),\n Block.box(0, 5, 5, 16, 11, 11), BooleanOp.OR);\n VoxelShape smallX = Shapes.join(Block.box(2, 1, 1, 14, 15, 15),\n Block.box(0, 5, 5, 16, 11, 11), BooleanOp.OR);\n\n VoxelShape largeZ = Shapes.join(Block.box(-2, -2, 2, 18, 18, 14),\n Block.box(5, 5, 0, 11, 11, 16), BooleanOp.OR);\n VoxelShape smallZ = Shapes.join(Block.box(1, 1, 2, 15, 15, 14),\n Block.box(5, 5, 0, 11, 11, 16), BooleanOp.OR);\n\n protected IndustrialGearBlock(boolean large, Properties properties) {\n super(properties);\n isLarge = large;\n }\n\n public static IndustrialGearBlock small(Properties properties) {\n return new IndustrialGearBlock(false, properties);\n }\n\n public static IndustrialGearBlock large(Properties properties) {\n return new IndustrialGearBlock(true, properties);\n }\n\n @Override\n public boolean isLargeCog() {\n return isLarge;\n }\n\n @Override\n public boolean isSmallCog() {\n return !isLarge;\n }\n\n @Override\n public void fillItemCategory(CreativeModeTab pTab, NonNullList<ItemStack> pItems) {\n super.fillItemCategory(pTab, pItems);\n MmbBlocks.LARGE_COGWHEEL.is(this);\n }\n\n @Override\n public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) {\n if (state.getValue(AXIS) == Direction.Axis.X) {\n return (isLarge ? largeX : smallX);\n }\n if (state.getValue(AXIS) == Direction.Axis.Z) {\n return (isLarge ? largeZ : smallZ);\n }\n state.getValue(AXIS);\n return (isLarge ? largeY : smallY);\n }\n\n @Override\n public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) {\n return isValidCogwheelPosition(ICogWheel.isLargeCog(state), worldIn, pos, state.getValue(AXIS));\n }\n\n @Override\n public void setPlacedBy(Level worldIn, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {\n super.setPlacedBy(worldIn, pos, state, placer, stack);\n if (placer instanceof Player player)\n triggerShiftingGearsAdvancement(worldIn, pos, state, player);\n }\n\n protected void triggerShiftingGearsAdvancement(Level world, BlockPos pos, BlockState state, Player player) {\n if (world.isClientSide || player == null)\n return;\n\n Direction.Axis axis = state.getValue(IndustrialGearBlock.AXIS);\n for (Direction.Axis perpendicular1 : Iterate.axes) {\n if (perpendicular1 == axis)\n continue;\n\n Direction d1 = Direction.get(Direction.AxisDirection.POSITIVE, perpendicular1);\n for (Direction.Axis perpendicular2 : Iterate.axes) {\n if (perpendicular1 == perpendicular2)\n continue;\n if (axis == perpendicular2)\n continue;\n\n Direction d2 = Direction.get(Direction.AxisDirection.POSITIVE, perpendicular2);\n for (int offset1 : Iterate.positiveAndNegative) {\n for (int offset2 : Iterate.positiveAndNegative) {\n BlockPos connectedPos = pos.relative(d1, offset1)\n .relative(d2, offset2);\n BlockState blockState = world.getBlockState(connectedPos);\n if (!(blockState.getBlock() instanceof IndustrialGearBlock))\n continue;\n if (blockState.getValue(IndustrialGearBlock.AXIS) != axis)\n continue;\n if (ICogWheel.isLargeCog(blockState) == isLarge)\n continue;\n\n AllAdvancements.COGS.awardTo(player);\n }\n }\n }\n }\n }\n\n @Override\n public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand,\n BlockHitResult ray) {\n if (player.isShiftKeyDown() || !player.mayBuild())\n return InteractionResult.PASS;\n\n ItemStack heldItem = player.getItemInHand(hand);\n InteractionResult result = tryEncase(state, world, pos, heldItem, player, hand, ray);\n if (result.consumesAction())\n return result;\n\n return InteractionResult.PASS;\n }\n\n public static boolean isValidCogwheelPosition(boolean large, LevelReader worldIn, BlockPos pos, Direction.Axis cogAxis) {\n for (Direction facing : Iterate.directions) {\n if (facing.getAxis() == cogAxis)\n continue;\n\n BlockPos offsetPos = pos.relative(facing);\n BlockState blockState = worldIn.getBlockState(offsetPos);\n if (blockState.hasProperty(AXIS) && facing.getAxis() == blockState.getValue(AXIS))\n continue;\n\n if (ICogWheel.isLargeCog(blockState) || large && ICogWheel.isSmallCog(blockState))\n return false;\n }\n return true;\n }\n\n protected Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n if (context.getPlayer() != null && context.getPlayer()\n .isShiftKeyDown())\n return context.getClickedFace()\n .getAxis();\n\n Level world = context.getLevel();\n BlockState stateBelow = world.getBlockState(context.getClickedPos()\n .below());\n\n BlockPos placedOnPos = context.getClickedPos()\n .relative(context.getClickedFace()\n .getOpposite());\n BlockState placedAgainst = world.getBlockState(placedOnPos);\n\n Block block = placedAgainst.getBlock();\n if (ICogWheel.isSmallCog(placedAgainst))\n return ((IRotate) block).getRotationAxis(placedAgainst);\n\n Direction.Axis preferredAxis = getPreferredAxis(context);\n return preferredAxis != null ? preferredAxis\n : context.getClickedFace()\n .getAxis();\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n boolean shouldWaterlog = context.getLevel()\n .getFluidState(context.getClickedPos())\n .getType() == Fluids.WATER;\n return this.defaultBlockState()\n .setValue(AXIS, getAxisForPlacement(context))\n .setValue(BlockStateProperties.WATERLOGGED, shouldWaterlog);\n }\n\n @Override\n public float getParticleTargetRadius() {\n return isLargeCog() ? 1.125f : .65f;\n }\n\n @Override\n public float getParticleInitialRadius() {\n return isLargeCog() ? 1f : .75f;\n }\n\n @Override\n public boolean isDedicatedCogWheel() {\n return true;\n }\n\n}" }, { "identifier": "IndustrialGearBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/industrial_gear/IndustrialGearBlockItem.java", "snippet": "public class IndustrialGearBlockItem extends BlockItem {\n\n boolean large;\n\n private final int placementHelperId;\n private final int integratedCogHelperId;\n\n public IndustrialGearBlockItem(IndustrialGearBlock block, Properties builder) {\n super(block, builder);\n large = block.isLarge;\n\n placementHelperId = PlacementHelpers.register(large ? new IndustrialGearBlockItem.LargeCogHelper() : new IndustrialGearBlockItem.SmallCogHelper());\n integratedCogHelperId =\n PlacementHelpers.register(large ? new IndustrialGearBlockItem.IntegratedLargeCogHelper() : new IndustrialGearBlockItem.IntegratedSmallCogHelper());\n }\n\n @Override\n public InteractionResult onItemUseFirst(ItemStack stack, UseOnContext context) {\n Level world = context.getLevel();\n BlockPos pos = context.getClickedPos();\n BlockState state = world.getBlockState(pos);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n Player player = context.getPlayer();\n BlockHitResult ray = new BlockHitResult(context.getClickLocation(), context.getClickedFace(), pos, true);\n if (helper.matchesState(state) && player != null && !player.isShiftKeyDown()) {\n return helper.getOffset(player, world, state, pos, ray)\n .placeInWorld(world, this, player, context.getHand(), ray);\n }\n\n if (integratedCogHelperId != -1) {\n helper = PlacementHelpers.get(integratedCogHelperId);\n\n if (helper.matchesState(state) && player != null && !player.isShiftKeyDown()) {\n return helper.getOffset(player, world, state, pos, ray)\n .placeInWorld(world, this, player, context.getHand(), ray);\n }\n }\n\n return super.onItemUseFirst(stack, context);\n }\n\n @MethodsReturnNonnullByDefault\n private static class SmallCogHelper extends IndustrialGearBlockItem.DiagonalCogHelper {\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return ((Predicate<ItemStack>) ICogWheel::isSmallCogItem).and(ICogWheel::isDedicatedCogItem);\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n if (hitOnShaft(state, ray))\n return PlacementOffset.fail();\n\n if (!ICogWheel.isLargeCog(state)) {\n Direction.Axis axis = ((IRotate) state.getBlock()).getRotationAxis(state);\n List<Direction> directions = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), axis);\n\n for (Direction dir : directions) {\n BlockPos newPos = pos.relative(dir);\n\n if (!IndustrialGearBlock.isValidCogwheelPosition(false, world, newPos, axis))\n continue;\n\n if (!world.getBlockState(newPos)\n .getMaterial()\n .isReplaceable())\n continue;\n\n return PlacementOffset.success(newPos, s -> s.setValue(AXIS, axis));\n\n }\n\n return PlacementOffset.fail();\n }\n\n return super.getOffset(player, world, state, pos, ray);\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class LargeCogHelper extends IndustrialGearBlockItem.DiagonalCogHelper {\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return ((Predicate<ItemStack>) ICogWheel::isLargeCogItem).and(ICogWheel::isDedicatedCogItem);\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n if (hitOnShaft(state, ray))\n return PlacementOffset.fail();\n\n if (ICogWheel.isLargeCog(state)) {\n Direction.Axis axis = ((IRotate) state.getBlock()).getRotationAxis(state);\n Direction side = IPlacementHelper.orderedByDistanceOnlyAxis(pos, ray.getLocation(), axis)\n .get(0);\n List<Direction> directions = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), axis);\n for (Direction dir : directions) {\n BlockPos newPos = pos.relative(dir)\n .relative(side);\n\n if (!IndustrialGearBlock.isValidCogwheelPosition(true, world, newPos, dir.getAxis()))\n continue;\n\n if (!world.getBlockState(newPos)\n .getMaterial()\n .isReplaceable())\n continue;\n\n return PlacementOffset.success(newPos, s -> s.setValue(AXIS, dir.getAxis()));\n }\n\n return PlacementOffset.fail();\n }\n\n return super.getOffset(player, world, state, pos, ray);\n }\n }\n\n @MethodsReturnNonnullByDefault\n public abstract static class DiagonalCogHelper implements IPlacementHelper {\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> ICogWheel.isSmallCog(s) || ICogWheel.isLargeCog(s);\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n // diagonal gears of different size\n Direction.Axis axis = ((IRotate) state.getBlock()).getRotationAxis(state);\n Direction closest = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), axis)\n .get(0);\n List<Direction> directions = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), axis,\n d -> d.getAxis() != closest.getAxis());\n\n for (Direction dir : directions) {\n BlockPos newPos = pos.relative(dir)\n .relative(closest);\n if (!world.getBlockState(newPos)\n .getMaterial()\n .isReplaceable())\n continue;\n\n if (!IndustrialGearBlock.isValidCogwheelPosition(ICogWheel.isLargeCog(state), world, newPos, axis))\n continue;\n\n return PlacementOffset.success(newPos, s -> s.setValue(AXIS, axis));\n }\n\n return PlacementOffset.fail();\n }\n\n protected boolean hitOnShaft(BlockState state, BlockHitResult ray) {\n return AllShapes.SIX_VOXEL_POLE.get(((IRotate) state.getBlock()).getRotationAxis(state))\n .bounds()\n .inflate(0.001)\n .contains(ray.getLocation()\n .subtract(ray.getLocation()\n .align(Iterate.axisSet)));\n }\n }\n\n @MethodsReturnNonnullByDefault\n public static class IntegratedLargeCogHelper implements IPlacementHelper {\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return ((Predicate<ItemStack>) ICogWheel::isLargeCogItem).and(ICogWheel::isDedicatedCogItem);\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> !ICogWheel.isDedicatedCogWheel(s.getBlock()) && ICogWheel.isSmallCog(s);\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n Direction face = ray.getDirection();\n Direction.Axis newAxis;\n\n if (state.hasProperty(HorizontalKineticBlock.HORIZONTAL_FACING))\n newAxis = state.getValue(HorizontalKineticBlock.HORIZONTAL_FACING)\n .getAxis();\n else if (state.hasProperty(DirectionalKineticBlock.FACING))\n newAxis = state.getValue(DirectionalKineticBlock.FACING)\n .getAxis();\n else if (state.hasProperty(RotatedPillarKineticBlock.AXIS))\n newAxis = state.getValue(RotatedPillarKineticBlock.AXIS);\n else\n newAxis = Direction.Axis.Y;\n\n if (face.getAxis() == newAxis)\n return PlacementOffset.fail();\n\n List<Direction> directions =\n IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), face.getAxis(), newAxis);\n\n for (Direction d : directions) {\n BlockPos newPos = pos.relative(face)\n .relative(d);\n\n if (!world.getBlockState(newPos)\n .getMaterial()\n .isReplaceable())\n continue;\n\n if (!IndustrialGearBlock.isValidCogwheelPosition(false, world, newPos, newAxis))\n return PlacementOffset.fail();\n\n return PlacementOffset.success(newPos, s -> s.setValue(IndustrialGearBlock.AXIS, newAxis));\n }\n\n return PlacementOffset.fail();\n }\n\n }\n\n @MethodsReturnNonnullByDefault\n public static class IntegratedSmallCogHelper implements IPlacementHelper {\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return ((Predicate<ItemStack>) ICogWheel::isSmallCogItem).and(ICogWheel::isDedicatedCogItem);\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> !ICogWheel.isDedicatedCogWheel(s.getBlock()) && ICogWheel.isSmallCog(s);\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n Direction face = ray.getDirection();\n Direction.Axis newAxis;\n\n if (state.hasProperty(HorizontalKineticBlock.HORIZONTAL_FACING))\n newAxis = state.getValue(HorizontalKineticBlock.HORIZONTAL_FACING)\n .getAxis();\n else if (state.hasProperty(DirectionalKineticBlock.FACING))\n newAxis = state.getValue(DirectionalKineticBlock.FACING)\n .getAxis();\n else if (state.hasProperty(RotatedPillarKineticBlock.AXIS))\n newAxis = state.getValue(RotatedPillarKineticBlock.AXIS);\n else\n newAxis = Direction.Axis.Y;\n\n if (face.getAxis() == newAxis)\n return PlacementOffset.fail();\n\n List<Direction> directions = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), newAxis);\n\n for (Direction d : directions) {\n BlockPos newPos = pos.relative(d);\n\n if (!world.getBlockState(newPos)\n .getMaterial()\n .isReplaceable())\n continue;\n\n if (!IndustrialGearBlock.isValidCogwheelPosition(false, world, newPos, newAxis))\n return PlacementOffset.fail();\n\n return PlacementOffset.success()\n .at(newPos)\n .withTransform(s -> s.setValue(IndustrialGearBlock.AXIS, newAxis));\n }\n\n return PlacementOffset.fail();\n }\n\n }\n}" }, { "identifier": "AluminumBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/aluminum/AluminumBoilerStructure.java", "snippet": "public class AluminumBoilerStructure extends DirectionalBlock implements IWrenchable {\n public AluminumBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_ALUMINUM_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_ALUMINUM_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_ALUMINUM_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.ALUMINUM_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof AluminumLargeBoilerBlock\n && targetedState.getValue(AluminumLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n AluminumBoilerStructure waterWheelStructuralBlock = MmbBlocks.ALUMINUM_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(AluminumBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n AluminumBoilerStructure waterWheelStructuralBlock = MmbBlocks.ALUMINUM_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(AluminumBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "AluminumLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/aluminum/AluminumLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class AluminumLargeBoilerBlock extends TagDependentDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public AluminumLargeBoilerBlock(Properties properties, TagKey<Item> itemTagKey) {\n super(properties, itemTagKey);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.ALUMINUM_BOILER_STRUCTURAL.getDefaultState()\n .setValue(AluminumBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof AluminumLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof AluminumLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof AluminumLargeBoilerBlock || s.getBlock() instanceof AluminumLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n}" }, { "identifier": "AluminumLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/aluminum/AluminumLargeBoilerBlockItem.java", "snippet": "public class AluminumLargeBoilerBlockItem extends BlockItem {\n public AluminumLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((AluminumLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((AluminumLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "AndesiteBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/andesite/AndesiteBoilerStructure.java", "snippet": "public class AndesiteBoilerStructure extends DirectionalBlock implements IWrenchable {\n public AndesiteBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_ANDESITE_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_ANDESITE_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_ANDESITE_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.ANDESITE_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof AndesiteLargeBoilerBlock\n && targetedState.getValue(AndesiteLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n AndesiteBoilerStructure waterWheelStructuralBlock = MmbBlocks.ANDESITE_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(AndesiteBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n AndesiteBoilerStructure waterWheelStructuralBlock = MmbBlocks.ANDESITE_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(AndesiteBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "AndesiteLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/andesite/AndesiteLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class AndesiteLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public AndesiteLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.ANDESITE_BOILER_STRUCTURAL.getDefaultState()\n .setValue(AndesiteBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof AndesiteLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof AndesiteLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof AndesiteLargeBoilerBlock || s.getBlock() instanceof AndesiteLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "AndesiteLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/andesite/AndesiteLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class AndesiteLargeBoilerBlockItem extends BlockItem {\n\n public AndesiteLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((AndesiteLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((AndesiteLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "BrassBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/brass/BrassBoilerStructure.java", "snippet": "public class BrassBoilerStructure extends DirectionalBlock implements IWrenchable {\n public BrassBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_BRASS_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_BRASS_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_BRASS_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.BRASS_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof BrassLargeBoilerBlock\n && targetedState.getValue(BrassLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new BrassBoilerStructure.RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n BrassBoilerStructure waterWheelStructuralBlock = MmbBlocks.BRASS_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(BrassBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n BrassBoilerStructure waterWheelStructuralBlock = MmbBlocks.BRASS_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(BrassBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "BrassLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/brass/BrassLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class BrassLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public BrassLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.BRASS_BOILER_STRUCTURAL.getDefaultState()\n .setValue(BrassBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof BrassLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof BrassLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof BrassLargeBoilerBlock || s.getBlock() instanceof BrassLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "BrassLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/brass/BrassLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class BrassLargeBoilerBlockItem extends BlockItem {\n\n public BrassLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((BrassLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((BrassLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n\n}" }, { "identifier": "CapitalismBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/capitalism/CapitalismBoilerStructure.java", "snippet": "public class CapitalismBoilerStructure extends DirectionalBlock implements IWrenchable {\n public CapitalismBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_CAPITALISM_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_CAPITALISM_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_CAPITALISM_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.CAPITALISM_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof CapitalismLargeBoilerBlock\n && targetedState.getValue(CapitalismLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new CapitalismBoilerStructure.RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n CapitalismBoilerStructure waterWheelStructuralBlock = MmbBlocks.CAPITALISM_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(CapitalismBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n CapitalismBoilerStructure waterWheelStructuralBlock = MmbBlocks.CAPITALISM_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(CapitalismBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "CapitalismLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/capitalism/CapitalismLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CapitalismLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public CapitalismLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.CAPITALISM_BOILER_STRUCTURAL.getDefaultState()\n .setValue(CapitalismBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof CapitalismLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof CapitalismLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof CapitalismLargeBoilerBlock || s.getBlock() instanceof CapitalismLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "CapitalismLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/capitalism/CapitalismLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CapitalismLargeBoilerBlockItem extends BlockItem {\n\n public CapitalismLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((CapitalismLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((CapitalismLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "CastIronBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/cast_iron/CastIronBoilerStructure.java", "snippet": "public class CastIronBoilerStructure extends DirectionalBlock implements IWrenchable {\n public CastIronBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_CAST_IRON_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_CAST_IRON_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_CAST_IRON_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.CAST_IRON_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof CastIronLargeBoilerBlock\n && targetedState.getValue(CastIronLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new CastIronBoilerStructure.RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n CastIronBoilerStructure waterWheelStructuralBlock = MmbBlocks.CAST_IRON_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(CastIronBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n CastIronBoilerStructure waterWheelStructuralBlock = MmbBlocks.CAST_IRON_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(CastIronBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "CastIronLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/cast_iron/CastIronLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CastIronLargeBoilerBlock extends TagDependentDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public CastIronLargeBoilerBlock(Properties properties, TagKey<Item> itemTagKey) {\n super(properties, itemTagKey);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.CAST_IRON_BOILER_STRUCTURAL.getDefaultState()\n .setValue(CastIronBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof CastIronLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof CastIronLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof CastIronLargeBoilerBlock || s.getBlock() instanceof CastIronLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "CastIronLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/cast_iron/CastIronLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CastIronLargeBoilerBlockItem extends BlockItem {\n\n public CastIronLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((CastIronLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((CastIronLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n\n}" }, { "identifier": "CopperBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/copper/CopperBoilerStructure.java", "snippet": "public class CopperBoilerStructure extends DirectionalBlock implements IWrenchable {\n public CopperBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_COPPER_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_COPPER_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_COPPER_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.COPPER_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof CopperLargeBoilerBlock\n && targetedState.getValue(CopperLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n CopperBoilerStructure waterWheelStructuralBlock = MmbBlocks.COPPER_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(CopperBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n CopperBoilerStructure waterWheelStructuralBlock = MmbBlocks.COPPER_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(CopperBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "CopperLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/copper/CopperLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CopperLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public CopperLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.COPPER_BOILER_STRUCTURAL.getDefaultState()\n .setValue(CopperBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof CopperLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof CopperLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof CopperLargeBoilerBlock || s.getBlock() instanceof CopperLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "CopperLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/copper/CopperLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CopperLargeBoilerBlockItem extends BlockItem {\n\n public CopperLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((CopperLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((CopperLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "GoldBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/gold/GoldBoilerStructure.java", "snippet": "public class GoldBoilerStructure extends DirectionalBlock implements IWrenchable {\n public GoldBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_GOLD_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_GOLD_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_GOLD_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.GOLD_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof GoldLargeBoilerBlock\n && targetedState.getValue(GoldLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n GoldBoilerStructure waterWheelStructuralBlock = MmbBlocks.GOLD_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(GoldBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n GoldBoilerStructure waterWheelStructuralBlock = MmbBlocks.GOLD_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(GoldBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "GoldLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/gold/GoldLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class GoldLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public GoldLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.GOLD_BOILER_STRUCTURAL.getDefaultState()\n .setValue(GoldBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof GoldLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof GoldLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof GoldLargeBoilerBlock || s.getBlock() instanceof GoldLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "GoldLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/gold/GoldLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class GoldLargeBoilerBlockItem extends BlockItem {\n\n public GoldLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((GoldLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((GoldLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "IndustrialIronBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/industrial_iron/IndustrialIronBoilerStructure.java", "snippet": "public class IndustrialIronBoilerStructure extends DirectionalBlock implements IWrenchable {\n public IndustrialIronBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_INDUSTRIAL_IRON_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_INDUSTRIAL_IRON_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_INDUSTRIAL_IRON_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.INDUSTRIAL_IRON_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof IndustrialIronLargeBoilerBlock\n && targetedState.getValue(IndustrialIronLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n IndustrialIronBoilerStructure waterWheelStructuralBlock = MmbBlocks.INDUSTRIAL_IRON_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(IndustrialIronBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n IndustrialIronBoilerStructure waterWheelStructuralBlock = MmbBlocks.INDUSTRIAL_IRON_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(IndustrialIronBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "IndustrialIronLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/industrial_iron/IndustrialIronLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class IndustrialIronLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public IndustrialIronLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.INDUSTRIAL_IRON_BOILER_STRUCTURAL.getDefaultState()\n .setValue(IndustrialIronBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof IndustrialIronLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof IndustrialIronLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof IndustrialIronLargeBoilerBlock || s.getBlock() instanceof IndustrialIronLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "IndustrialIronLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/industrial_iron/IndustrialIronLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class IndustrialIronLargeBoilerBlockItem extends BlockItem {\n\n public IndustrialIronLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((IndustrialIronLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((IndustrialIronLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "ZincBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/zinc/ZincBoilerStructure.java", "snippet": "public class ZincBoilerStructure extends DirectionalBlock implements IWrenchable {\n public ZincBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_ZINC_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_ZINC_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_ZINC_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.ZINC_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof ZincLargeBoilerBlock\n && targetedState.getValue(ZincLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n ZincBoilerStructure waterWheelStructuralBlock = MmbBlocks.ZINC_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(ZincBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n ZincBoilerStructure waterWheelStructuralBlock = MmbBlocks.ZINC_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(ZincBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "ZincLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/zinc/ZincLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class ZincLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public ZincLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.ZINC_BOILER_STRUCTURAL.getDefaultState()\n .setValue(ZincBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof ZincLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof ZincLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof ZincLargeBoilerBlock || s.getBlock() instanceof ZincLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "ZincLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/zinc/ZincLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class ZincLargeBoilerBlockItem extends BlockItem {\n\n public ZincLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((ZincLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((ZincLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n\n\n}" }, { "identifier": "REGISTRATE", "path": "src/main/java/com/mangomilk/design_decor/CreateMMBuilding.java", "snippet": "public static final CreateRegistrate REGISTRATE = CreateRegistrate.create(CreateMMBuilding.MOD_ID).creativeModeTab(()-> MmbCreativeModeTab.BUILDING);" }, { "identifier": "DecorBuilderTransformer", "path": "src/main/java/com/mangomilk/design_decor/base/DecorBuilderTransformer.java", "snippet": "public class DecorBuilderTransformer {\n\n public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> connected(\n Supplier<CTSpriteShiftEntry> ct) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get()))\n .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> layeredConnected(\n Supplier<CTSpriteShiftEntry> ct, Supplier<CTSpriteShiftEntry> ct2) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get(), p.models()\n .cubeColumn(c.getName(), ct.get()\n .getOriginalResourceLocation(),\n ct2.get()\n .getOriginalResourceLocation())))\n .onRegister(connectedTextures(() -> new HorizontalCTBehaviour(ct.get(), ct2.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n public static <B extends OrnateGrateBlock> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> ornateconnected(\n Supplier<CTSpriteShiftEntry> ct) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get(), AssetLookup.standardModel(c, p)))\n .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n private static BlockBehaviour.Properties glassProperties(BlockBehaviour.Properties p) {\n return p.isValidSpawn(DecorBuilderTransformer::never)\n .isRedstoneConductor(DecorBuilderTransformer::never)\n .isSuffocating(DecorBuilderTransformer::never)\n .isViewBlocking(DecorBuilderTransformer::never)\n .noOcclusion();\n }\n\n public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(Supplier<ConnectedTextureBehaviour> behaviour) {\n return CreateMMBuilding.REGISTRATE.block(\"tinted_framed_glass\", ConnectedTintedGlassBlock::new)\n .onRegister(connectedTextures(behaviour))\n .addLayer(() -> RenderType::translucent)\n .initialProperties(() -> Blocks.TINTED_GLASS)\n .properties(DecorBuilderTransformer::glassProperties)\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get))\n .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, \"palettes/\", \"tinted_framed_glass\"))\n .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE)\n .lang(\"Tinted Framed Glass\")\n .item()\n .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS)\n .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()),\n p.modLoc(\"block/palettes/tinted_framed_glass\")))\n .build()\n .register();\n }\n\n public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(String type,String name, Supplier<ConnectedTextureBehaviour> behaviour) {\n return CreateMMBuilding.REGISTRATE.block(type + \"_tinted_framed_glass\", ConnectedTintedGlassBlock::new)\n .onRegister(connectedTextures(behaviour))\n .addLayer(() -> RenderType::translucent)\n .initialProperties(() -> Blocks.TINTED_GLASS)\n .properties(DecorBuilderTransformer::glassProperties)\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get))\n .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, \"palettes/\", type + \"_tinted_framed_glass\"))\n .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE)\n .lang(name + \" Tinted Framed Glass\")\n .item()\n .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS)\n .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()),\n p.modLoc(\"block/palettes/\" + type + \"_tinted_framed_glass\")))\n .build()\n .register();\n }\n\n\n\n\n public static BlockEntry<Block> CastelBricks(String id, String lang, MaterialColor color, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Brick Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_bricks\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_bricks\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Brick Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Brick Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_bricks\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Bricks\")\n .register();\n }\n\n public static BlockEntry<Block> CastelBricks(String id, String lang, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Brick Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_bricks\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_bricks\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Brick Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Brick Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_bricks\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Bricks\")\n .register();\n }\n public static BlockEntry<Block> CastelTiles(String id, String lang, MaterialColor color, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Tile Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_tiles\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_tiles\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Tile Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Tile Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_tiles\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Tiles\")\n .register();\n }\n public static BlockEntry<Block> CastelTiles(String id, String lang, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Tile Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_tiles\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_tiles\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Tile Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Tile Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_tiles\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Tiles\")\n .register();\n }\n private static boolean never(BlockState p_235436_0_, BlockGetter p_235436_1_, BlockPos p_235436_2_) {return false;}\n private static Boolean never(BlockState p_235427_0_, BlockGetter p_235427_1_, BlockPos p_235427_2_, EntityType<?> p_235427_3_) {return false;}\n private static String palettesDir() {return \"block/palettes/\";}\n}" } ]
import com.mangomilk.design_decor.base.DecorBuilderTransformer; import com.mangomilk.design_decor.base.MmbSpriteShifts; import com.mangomilk.design_decor.blocks.*; import com.mangomilk.design_decor.blocks.SignBlock; import com.mangomilk.design_decor.blocks.chain.LargeChain; import com.mangomilk.design_decor.blocks.chain.TagDependentLargeChain; import com.mangomilk.design_decor.blocks.containers.red.RedContainerBlock; import com.mangomilk.design_decor.blocks.containers.red.RedContainerCTBehaviour; import com.mangomilk.design_decor.blocks.containers.red.RedContainerItem; import com.mangomilk.design_decor.blocks.containers.blue.BlueContainerBlock; import com.mangomilk.design_decor.blocks.containers.blue.BlueContainerCTBehaviour; import com.mangomilk.design_decor.blocks.containers.blue.BlueContainerItem; import com.mangomilk.design_decor.blocks.containers.green.GreenContainerBlock; import com.mangomilk.design_decor.blocks.containers.green.GreenContainerCTBehaviour; import com.mangomilk.design_decor.blocks.containers.green.GreenContainerItem; import com.mangomilk.design_decor.blocks.crushing_wheels.MmbCrushingWheelBlock; import com.mangomilk.design_decor.blocks.crushing_wheels.MmbCrushingWheelControllerBlock; import com.mangomilk.design_decor.blocks.diagonal_girder.DiagonalGirderBlock; import com.mangomilk.design_decor.blocks.diagonal_girder.DiagonalGirderGenerator; import com.mangomilk.design_decor.blocks.floodlight.FloodlightBlock; import com.mangomilk.design_decor.blocks.floodlight.FloodlightGenerator; import com.mangomilk.design_decor.blocks.gas_tank.GasTankBlock; import com.mangomilk.design_decor.blocks.glass.ConnectedTintedGlassBlock; import com.mangomilk.design_decor.blocks.industrial_gear.IndustrialGearBlock; import com.mangomilk.design_decor.blocks.industrial_gear.IndustrialGearBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.aluminum.AluminumBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.aluminum.AluminumLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.aluminum.AluminumLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.andesite.AndesiteBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.andesite.AndesiteLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.andesite.AndesiteLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.brass.BrassBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.brass.BrassLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.brass.BrassLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.capitalism.CapitalismBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.capitalism.CapitalismLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.capitalism.CapitalismLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.cast_iron.CastIronBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.cast_iron.CastIronLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.cast_iron.CastIronLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.copper.CopperBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.copper.CopperLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.copper.CopperLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.gold.GoldBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.gold.GoldLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.gold.GoldLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.industrial_iron.IndustrialIronBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.industrial_iron.IndustrialIronLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.industrial_iron.IndustrialIronLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.zinc.ZincBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.zinc.ZincLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.zinc.ZincLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.millstone.block.*; import com.simibubi.create.AllTags; import com.simibubi.create.content.kinetics.BlockStressDefaults; import com.simibubi.create.content.kinetics.simpleRelays.BracketedKineticBlockModel; import com.simibubi.create.foundation.block.connected.HorizontalCTBehaviour; import com.simibubi.create.foundation.block.connected.SimpleCTBehaviour; import com.simibubi.create.foundation.data.AssetLookup; import com.simibubi.create.foundation.data.BlockStateGen; import com.simibubi.create.foundation.data.CreateRegistrate; import com.simibubi.create.foundation.data.SharedProperties; import com.tterrag.registrate.util.entry.BlockEntry; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.client.renderer.RenderType; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.MaterialColor; import net.minecraftforge.client.model.generators.ConfiguredModel; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.IForgeRegistry; import javax.annotation.ParametersAreNonnullByDefault; import java.util.Collections; import static com.mangomilk.design_decor.CreateMMBuilding.REGISTRATE; import static com.mangomilk.design_decor.base.DecorBuilderTransformer.*; import static com.simibubi.create.foundation.data.CreateRegistrate.connectedTextures; import static com.simibubi.create.foundation.data.ModelGen.customItemModel; import static com.simibubi.create.foundation.data.TagGen.axeOrPickaxe; import static com.simibubi.create.foundation.data.TagGen.pickaxeOnly;
74,200
REGISTRATE.block("industrial_gear_large", IndustrialGearBlock::large) .initialProperties(SharedProperties::softMetal) .properties(p -> p.color(MaterialColor.COLOR_GRAY)) .properties(p -> p.sound(SoundType.NETHERITE_BLOCK)) .properties(BlockBehaviour.Properties::requiresCorrectToolForDrops) .transform(pickaxeOnly()) .transform(BlockStressDefaults.setNoImpact()) .blockstate(BlockStateGen.axisBlockProvider(false)) .onRegister(CreateRegistrate.blockModel(() -> BracketedKineticBlockModel::new)) .item(IndustrialGearBlockItem::new) .build() .lang("Large Industrial Gear") .register(); //BOILERS public static final BlockEntry<BoilerBlock> BRASS_BOILER = REGISTRATE.block("brass_boiler", BoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Brass Boiler") .register(); public static final BlockEntry<BrassLargeBoilerBlock> LARGE_BRASS_BOILER = REGISTRATE.block("brass_boiler_large", BrassLargeBoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .properties(p -> p.isViewBlocking(MmbBlocks::never)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(BrassLargeBoilerBlockItem::new) .build() .lang("Large Brass Boiler") .register(); public static final BlockEntry<BrassBoilerStructure> BRASS_BOILER_STRUCTURAL = REGISTRATE.block("brass_boiler_structure", BrassBoilerStructure::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStatesExcept(BlockStateGen.mapToAir(p), BrassBoilerStructure.FACING)) .lang("Large Brass Boiler") .register(); public static final BlockEntry<TagBoilerBlock> ALUMINUM_BOILER = REGISTRATE.block("aluminium_boiler", p -> new TagBoilerBlock(p, AllTags.forgeItemTag("ingots/aluminium"))) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Aluminium Boiler") .register(); public static final BlockEntry<TagBoilerBlock> ALUMINUM_BOILER_SPECIAL = REGISTRATE.block("aluminium_boiler_special", p -> new TagBoilerBlock(p, AllTags.forgeItemTag("ingots/aluminium"))) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Aluminium Boiler") .register(); public static final BlockEntry<AluminumLargeBoilerBlock> LARGE_ALUMINUM_BOILER = REGISTRATE.block("aluminium_boiler_large", p -> new AluminumLargeBoilerBlock(p, AllTags.forgeItemTag("ingots/aluminium"))) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(AluminumLargeBoilerBlockItem::new) .build() .lang("Large Aluminium Boiler") .register(); public static final BlockEntry<AluminumBoilerStructure> ALUMINUM_BOILER_STRUCTURAL = REGISTRATE.block("aluminium_boiler_structure", AluminumBoilerStructure::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStatesExcept(BlockStateGen.mapToAir(p), AluminumBoilerStructure.FACING)) .lang("Large Aluminium Boiler") .register(); public static final BlockEntry<BoilerBlock> GOLD_BOILER = REGISTRATE.block("gold_boiler", BoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Gold Boiler") .register(); public static final BlockEntry<GoldLargeBoilerBlock> LARGE_GOLD_BOILER = REGISTRATE.block("gold_boiler_large", GoldLargeBoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(GoldLargeBoilerBlockItem::new) .build() .lang("Large Gold Boiler") .register();
package com.mangomilk.design_decor.registry; @SuppressWarnings({"unused", "removal"}) @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class MmbBlocks { //LAMPS public static final BlockEntry<LampBlock> BRASS_LAMP = REGISTRATE.block("brass_lamp", LampBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p->p.lightLevel(s -> 15)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(false)) .item() .build() .lang("Brass Lamp") .register(); public static final BlockEntry<LampBlock> COPPER_LAMP = REGISTRATE.block("copper_lamp", LampBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p->p.lightLevel(s -> 15)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(false)) .item() .build() .lang("Copper Lamp") .register(); public static final BlockEntry<LampBlock> ZINC_LAMP = REGISTRATE.block("zinc_lamp", LampBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p->p.lightLevel(s -> 15)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(false)) .item() .build() .lang("Zinc Lamp") .register(); public static final BlockEntry<Block> BRASS_LIGHT = REGISTRATE.block("brass_light", Block::new) .properties(p -> p.color(MaterialColor.GOLD)) .properties(p->p.lightLevel(s -> 15)) .initialProperties(SharedProperties::copperMetal) .transform(pickaxeOnly()) .item() .build() .lang("Brass Light") .register(); public static final BlockEntry<Block> COPPER_LIGHT = REGISTRATE.block("copper_light", Block::new) .properties(p -> p.color(MaterialColor.GOLD)) .properties(p->p.lightLevel(s -> 15)) .initialProperties(SharedProperties::copperMetal) .transform(pickaxeOnly()) .item() .build() .lang("Copper Light") .register(); public static final BlockEntry<Block> ZINC_LIGHT = REGISTRATE.block("zinc_light", Block::new) .properties(p -> p.color(MaterialColor.GOLD)) .properties(p->p.lightLevel(s -> 15)) .initialProperties(SharedProperties::copperMetal) .transform(pickaxeOnly()) .item() .build() .lang("Zinc Light") .register(); //FLOODLIGHTS public static final BlockEntry<FloodlightBlock> BRASS_FLOODLIGHT = REGISTRATE.block("brass_floodlight", FloodlightBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(p -> p.color(MaterialColor.TERRACOTTA_YELLOW)) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.lightLevel(s -> s.getValue(FloodlightBlock.TURNED_ON) ? 15 : 0)) .addLayer(() -> RenderType::cutout) .blockstate(new FloodlightGenerator()::generate) .transform(axeOrPickaxe()) .lang("Brass Floodlight") .item() .transform(customItemModel("_", "block")) .register(); public static final BlockEntry<FloodlightBlock> ANDESITE_FLOODLIGHT = REGISTRATE.block("andesite_floodlight", FloodlightBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(p -> p.color(MaterialColor.STONE)) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.lightLevel(s -> s.getValue(FloodlightBlock.WATERLOGGED) == s.getValue(FloodlightBlock.TURNED_ON) ? 0 : !s.getValue(FloodlightBlock.WATERLOGGED) ? 12 : 8 )) .addLayer(() -> RenderType::cutout) .blockstate(new FloodlightGenerator()::generate) .transform(axeOrPickaxe()) .lang("Andesite Floodlight") .item() .transform(customItemModel("_", "block")) .register(); public static final BlockEntry<FloodlightBlock> COPPER_FLOODLIGHT = REGISTRATE.block("copper_floodlight", FloodlightBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(p -> p.color(MaterialColor.STONE)) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.lightLevel(s -> s.getValue(FloodlightBlock.WATERLOGGED) == s.getValue(FloodlightBlock.TURNED_ON) ? 12 : 0 )) .properties(p -> p.lightLevel(s -> !s.getValue(FloodlightBlock.WATERLOGGED) == s.getValue(FloodlightBlock.TURNED_ON) ? 6 : 0 )) .addLayer(() -> RenderType::cutout) .blockstate(new FloodlightGenerator()::generate) .transform(axeOrPickaxe()) .lang("Copper Floodlight") .item() .transform(customItemModel("_", "block")) .register(); //COGWHEELS public static final BlockEntry<IndustrialGearBlock> COGWHEEL = REGISTRATE.block("industrial_gear", IndustrialGearBlock::small) .initialProperties(SharedProperties::softMetal) .properties(p -> p.color(MaterialColor.COLOR_GRAY)) .properties(p -> p.sound(SoundType.NETHERITE_BLOCK)) .properties(BlockBehaviour.Properties::requiresCorrectToolForDrops) .transform(pickaxeOnly()) .transform(BlockStressDefaults.setNoImpact()) .blockstate(BlockStateGen.axisBlockProvider(false)) .onRegister(CreateRegistrate.blockModel(() -> BracketedKineticBlockModel::new)) .item(IndustrialGearBlockItem::new) .build() .lang("Industrial Gear") .register(); public static final BlockEntry<IndustrialGearBlock> LARGE_COGWHEEL = REGISTRATE.block("industrial_gear_large", IndustrialGearBlock::large) .initialProperties(SharedProperties::softMetal) .properties(p -> p.color(MaterialColor.COLOR_GRAY)) .properties(p -> p.sound(SoundType.NETHERITE_BLOCK)) .properties(BlockBehaviour.Properties::requiresCorrectToolForDrops) .transform(pickaxeOnly()) .transform(BlockStressDefaults.setNoImpact()) .blockstate(BlockStateGen.axisBlockProvider(false)) .onRegister(CreateRegistrate.blockModel(() -> BracketedKineticBlockModel::new)) .item(IndustrialGearBlockItem::new) .build() .lang("Large Industrial Gear") .register(); //BOILERS public static final BlockEntry<BoilerBlock> BRASS_BOILER = REGISTRATE.block("brass_boiler", BoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Brass Boiler") .register(); public static final BlockEntry<BrassLargeBoilerBlock> LARGE_BRASS_BOILER = REGISTRATE.block("brass_boiler_large", BrassLargeBoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .properties(p -> p.isViewBlocking(MmbBlocks::never)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(BrassLargeBoilerBlockItem::new) .build() .lang("Large Brass Boiler") .register(); public static final BlockEntry<BrassBoilerStructure> BRASS_BOILER_STRUCTURAL = REGISTRATE.block("brass_boiler_structure", BrassBoilerStructure::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStatesExcept(BlockStateGen.mapToAir(p), BrassBoilerStructure.FACING)) .lang("Large Brass Boiler") .register(); public static final BlockEntry<TagBoilerBlock> ALUMINUM_BOILER = REGISTRATE.block("aluminium_boiler", p -> new TagBoilerBlock(p, AllTags.forgeItemTag("ingots/aluminium"))) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Aluminium Boiler") .register(); public static final BlockEntry<TagBoilerBlock> ALUMINUM_BOILER_SPECIAL = REGISTRATE.block("aluminium_boiler_special", p -> new TagBoilerBlock(p, AllTags.forgeItemTag("ingots/aluminium"))) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Aluminium Boiler") .register(); public static final BlockEntry<AluminumLargeBoilerBlock> LARGE_ALUMINUM_BOILER = REGISTRATE.block("aluminium_boiler_large", p -> new AluminumLargeBoilerBlock(p, AllTags.forgeItemTag("ingots/aluminium"))) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(AluminumLargeBoilerBlockItem::new) .build() .lang("Large Aluminium Boiler") .register(); public static final BlockEntry<AluminumBoilerStructure> ALUMINUM_BOILER_STRUCTURAL = REGISTRATE.block("aluminium_boiler_structure", AluminumBoilerStructure::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .transform(pickaxeOnly()) .blockstate((c, p) -> p.getVariantBuilder(c.get()) .forAllStatesExcept(BlockStateGen.mapToAir(p), AluminumBoilerStructure.FACING)) .lang("Large Aluminium Boiler") .register(); public static final BlockEntry<BoilerBlock> GOLD_BOILER = REGISTRATE.block("gold_boiler", BoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutoutMipped) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item() .build() .lang("Gold Boiler") .register(); public static final BlockEntry<GoldLargeBoilerBlock> LARGE_GOLD_BOILER = REGISTRATE.block("gold_boiler_large", GoldLargeBoilerBlock::new) .initialProperties(SharedProperties::copperMetal) .properties(BlockBehaviour.Properties::noOcclusion) .properties(p -> p.hasPostProcess((p_61036_, p_61037_, p_61038_) -> true)) .transform(pickaxeOnly()) .addLayer(() -> RenderType::cutout) .blockstate(BlockStateGen.directionalBlockProvider(true)) .item(GoldLargeBoilerBlockItem::new) .build() .lang("Large Gold Boiler") .register();
public static final BlockEntry<GoldBoilerStructure> GOLD_BOILER_STRUCTURAL = REGISTRATE.block("gold_boiler_structure", GoldBoilerStructure::new)
42
2023-10-14 21:51:49+00:00
128k
Hoto-Mocha/Re-ARranged-Pixel-Dungeon
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/rooms/special/MagicalFireRoom.java
[ { "identifier": "Dungeon", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/Dungeon.java", "snippet": "public class Dungeon {\n\n\t//enum of items which have limited spawns, records how many have spawned\n\t//could all be their own separate numbers, but this allows iterating, much nicer for bundling/initializing.\n\tpublic static enum LimitedDrops {\n\t\t//limited world drops\n\t\tSTRENGTH_POTIONS,\n\t\tUPGRADE_SCROLLS,\n\t\tARCANE_STYLI,\n\n\t\t//Health potion sources\n\t\t//enemies\n\t\tSWARM_HP,\n\t\tNECRO_HP,\n\t\tBAT_HP,\n\t\tWARLOCK_HP,\n\t\t//Demon spawners are already limited in their spawnrate, no need to limit their health drops\n\t\t//alchemy\n\t\tCOOKING_HP,\n\t\tBLANDFRUIT_SEED,\n\n\t\t//Other limited enemy drops\n\t\tSLIME_WEP,\n\t\tSKELE_WEP,\n\t\tTHEIF_MISC,\n\t\tGUARD_ARM,\n\t\tSHAMAN_WAND,\n\t\tDM200_EQUIP,\n\t\tGOLEM_EQUIP,\n\t\tSOLDIER_WEP,\n\t\tMEDIC_HP,\n\n\t\t//containers\n\t\tVELVET_POUCH,\n\t\tSCROLL_HOLDER,\n\t\tPOTION_BANDOLIER,\n\t\tMAGICAL_HOLSTER,\n\n\t\t//lore documents\n\t\tLORE_SEWERS,\n\t\tLORE_PRISON,\n\t\tLORE_CAVES,\n\t\tLORE_CITY,\n\t\tLORE_HALLS,\n\t\tLORE_LABS;\n\n\t\tpublic int count = 0;\n\n\t\t//for items which can only be dropped once, should directly access count otherwise.\n\t\tpublic boolean dropped(){\n\t\t\treturn count != 0;\n\t\t}\n\t\tpublic void drop(){\n\t\t\tcount = 1;\n\t\t}\n\n\t\tpublic static void reset(){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tlim.count = 0;\n\t\t\t}\n\t\t}\n\n\t\tpublic static void store( Bundle bundle ){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tbundle.put(lim.name(), lim.count);\n\t\t\t}\n\t\t}\n\n\t\tpublic static void restore( Bundle bundle ){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tif (bundle.contains(lim.name())){\n\t\t\t\t\tlim.count = bundle.getInt(lim.name());\n\t\t\t\t} else {\n\t\t\t\t\tlim.count = 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\n\t\t\t//pre-v2.2.0 saves\n\t\t\tif (Dungeon.version < 750\n\t\t\t\t\t&& Dungeon.isChallenged(Challenges.NO_SCROLLS)\n\t\t\t\t\t&& UPGRADE_SCROLLS.count > 0){\n\t\t\t\t//we now count SOU fully, and just don't drop every 2nd one\n\t\t\t\tUPGRADE_SCROLLS.count += UPGRADE_SCROLLS.count-1;\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic static int challenges;\n\tpublic static int mobsToChampion;\n\n\tpublic static Hero hero;\n\tpublic static Level level;\n\n\tpublic static QuickSlot quickslot = new QuickSlot();\n\t\n\tpublic static int depth;\n\t//determines path the hero is on. Current uses:\n\t// 0 is the default path\n\t// 1 is for quest sub-floors\n\tpublic static int branch;\n\n\t//keeps track of what levels the game should try to load instead of creating fresh\n\tpublic static ArrayList<Integer> generatedLevels = new ArrayList<>();\n\n\tpublic static int gold;\n\tpublic static int energy;\n\tpublic static int bullet;\n\n\tpublic static HashSet<Integer> chapters;\n\n\tpublic static SparseArray<ArrayList<Item>> droppedItems;\n\n\t//first variable is only assigned when game is started, second is updated every time game is saved\n\tpublic static int initialVersion;\n\tpublic static int version;\n\n\tpublic static boolean daily;\n\tpublic static boolean dailyReplay;\n\tpublic static String customSeedText = \"\";\n\tpublic static long seed;\n\t\n\tpublic static void init() {\n\n\t\tinitialVersion = version = Game.versionCode;\n\t\tchallenges = SPDSettings.challenges();\n\t\tmobsToChampion = -1;\n\n\t\tif (daily) {\n\t\t\t//Ensures that daily seeds are not in the range of user-enterable seeds\n\t\t\tseed = SPDSettings.lastDaily() + DungeonSeed.TOTAL_SEEDS;\n\t\t\tDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ROOT);\n\t\t\tformat.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\t\t\tcustomSeedText = format.format(new Date(SPDSettings.lastDaily()));\n\t\t} else if (!SPDSettings.customSeed().isEmpty()){\n\t\t\tcustomSeedText = SPDSettings.customSeed();\n\t\t\tseed = DungeonSeed.convertFromText(customSeedText);\n\t\t} else {\n\t\t\tcustomSeedText = \"\";\n\t\t\tseed = DungeonSeed.randomSeed();\n\t\t}\n\n\t\tActor.clear();\n\t\tActor.resetNextID();\n\n\t\t//offset seed slightly to avoid output patterns\n\t\tRandom.pushGenerator( seed+1 );\n\n\t\t\tScroll.initLabels();\n\t\t\tPotion.initColors();\n\t\t\tRing.initGems();\n\n\t\t\tSpecialRoom.initForRun();\n\t\t\tSecretRoom.initForRun();\n\n\t\t\tGenerator.fullReset();\n\n\t\tRandom.resetGenerators();\n\t\t\n\t\tStatistics.reset();\n\t\tNotes.reset();\n\n\t\tquickslot.reset();\n\t\tQuickSlotButton.reset();\n\t\tToolbar.swappedQuickslots = false;\n\t\t\n\t\tdepth = 1;\n\t\tbranch = 0;\n\t\tgeneratedLevels.clear();\n\n\t\tgold = 0;\n\t\tenergy = 0;\n\t\tbullet = 0;\n\n\t\tdroppedItems = new SparseArray<>();\n\n\t\tLimitedDrops.reset();\n\t\t\n\t\tchapters = new HashSet<>();\n\t\t\n\t\tGhost.Quest.reset();\n\t\tWandmaker.Quest.reset();\n\t\tBlacksmith.Quest.reset();\n\t\tImp.Quest.reset();\n\n\t\thero = new Hero();\n\t\thero.live();\n\t\t\n\t\tBadges.reset();\n\t\t\n\t\tGamesInProgress.selectedClass.initHero( hero );\n\t}\n\n\tpublic static boolean isChallenged( int mask ) {\n\t\treturn (challenges & mask) != 0;\n\t}\n\n\tpublic static boolean levelHasBeenGenerated(int depth, int branch){\n\t\treturn generatedLevels.contains(depth + 1000*branch);\n\t}\n\t\n\tpublic static Level newLevel() {\n\t\t\n\t\tDungeon.level = null;\n\t\tActor.clear();\n\t\t\n\t\tLevel level;\n\t\tif (branch == 0) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 1:\n\t\t\t\tcase 2:\n\t\t\t\tcase 3:\n\t\t\t\tcase 4:\n\t\t\t\t\tlevel = new SewerLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\tlevel = new SewerBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 6:\n\t\t\t\tcase 7:\n\t\t\t\tcase 8:\n\t\t\t\tcase 9:\n\t\t\t\t\tlevel = new PrisonLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 10:\n\t\t\t\t\tlevel = new PrisonBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 11:\n\t\t\t\tcase 12:\n\t\t\t\tcase 13:\n\t\t\t\tcase 14:\n\t\t\t\t\tlevel = new CavesLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 15:\n\t\t\t\t\tlevel = new CavesBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 16:\n\t\t\t\tcase 17:\n\t\t\t\tcase 18:\n\t\t\t\tcase 19:\n\t\t\t\t\tlevel = new CityLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tlevel = new CityBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 21:\n\t\t\t\tcase 22:\n\t\t\t\tcase 23:\n\t\t\t\tcase 24:\n\t\t\t\t\tlevel = new HallsLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 25:\n\t\t\t\t\tlevel = new HallsBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 26:\n\t\t\t\tcase 27:\n\t\t\t\tcase 28:\n\t\t\t\tcase 29:\n\t\t\t\t\tlevel = new LabsLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 30:\n\t\t\t\t\tlevel = new LabsBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 31:\n\t\t\t\t\tlevel = new NewLastLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else if (branch == 1) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 11:\n\t\t\t\tcase 12:\n\t\t\t\tcase 13:\n\t\t\t\tcase 14:\n\t\t\t\t\tlevel = new MiningLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else if (branch == 2) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 16:\n\t\t\t\tcase 17:\n\t\t\t\tcase 18:\n\t\t\t\tcase 19:\n\t\t\t\t\tlevel = new TempleLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tlevel = new TempleLastLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else {\n\t\t\tlevel = new DeadEndLevel();\n\t\t}\n\n\t\t//dead end levels get cleared, don't count as generated\n\t\tif (!(level instanceof DeadEndLevel)){\n\t\t\t//this assumes that we will never have a depth value outside the range 0 to 999\n\t\t\t// or -500 to 499, etc.\n\t\t\tif (!generatedLevels.contains(depth + 1000*branch)) {\n\t\t\t\tgeneratedLevels.add(depth + 1000 * branch);\n\t\t\t}\n\n\t\t\tif (depth > Statistics.deepestFloor && branch == 0) {\n\t\t\t\tStatistics.deepestFloor = depth;\n\n\t\t\t\tif (Statistics.qualifiedForNoKilling) {\n\t\t\t\t\tStatistics.completedWithNoKilling = true;\n\t\t\t\t} else {\n\t\t\t\t\tStatistics.completedWithNoKilling = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tlevel.create();\n\t\t\n\t\tif (branch == 0) Statistics.qualifiedForNoKilling = !bossLevel();\n\t\tStatistics.qualifiedForBossChallengeBadge = false;\n\t\t\n\t\treturn level;\n\t}\n\t\n\tpublic static void resetLevel() {\n\t\t\n\t\tActor.clear();\n\t\t\n\t\tlevel.reset();\n\t\tswitchLevel( level, level.entrance() );\n\t}\n\n\tpublic static long seedCurDepth(){\n\t\treturn seedForDepth(depth, branch);\n\t}\n\n\tpublic static long seedForDepth(int depth, int branch){\n\t\tint lookAhead = depth;\n\t\tlookAhead += 30*branch; //Assumes depth is always 1-30, and branch is always 0 or higher\n\n\t\tRandom.pushGenerator( seed );\n\n\t\t\tfor (int i = 0; i < lookAhead; i ++) {\n\t\t\t\tRandom.Long(); //we don't care about these values, just need to go through them\n\t\t\t}\n\t\t\tlong result = Random.Long();\n\n\t\tRandom.popGenerator();\n\t\treturn result;\n\t}\n\t\n\tpublic static boolean shopOnLevel() {\n\t\treturn (depth == 6 || depth == 11 || depth == 16 || depth == 26) && branch == 0;\n\t}\n\t\n\tpublic static boolean bossLevel() {\n\t\treturn bossLevel( depth );\n\t}\n\t\n\tpublic static boolean bossLevel( int depth ) {\n\t\treturn depth == 5 || depth == 10 || depth == 15 || depth == 20 || depth == 25|| depth == 30;\n\t}\n\n\t//value used for scaling of damage values and other effects.\n\t//is usually the dungeon depth, but can be set to 26 when ascending\n\tpublic static int scalingDepth(){\n\t\tif (Dungeon.hero != null && Dungeon.hero.buff(AscensionChallenge.class) != null){\n\t\t\treturn 31;\n\t\t} else {\n\t\t\treturn depth;\n\t\t}\n\t}\n\n\tpublic static boolean interfloorTeleportAllowed(){\n\t\tif (Dungeon.level.locked\n\t\t\t\t|| (Dungeon.hero != null && Dungeon.hero.belongings.getItem(Amulet.class) != null)\n\t\t\t\t|| (Dungeon.hero != null && Dungeon.hero.buff(OldAmulet.TempleCurse.class) != null)){\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\n\tpublic static void switchLevel( final Level level, int pos ) {\n\n\t\t//Position of -2 specifically means trying to place the hero the exit\n\t\tif (pos == -2){\n\t\t\tLevelTransition t = level.getTransition(LevelTransition.Type.REGULAR_EXIT);\n\t\t\tif (t != null) pos = t.cell();\n\t\t}\n\n\t\t//Place hero at the entrance if they are out of the map (often used for pox = -1)\n\t\t// or if they are in solid terrain (except in the mining level, where that happens normally)\n\t\tif (pos < 0 || pos >= level.length()\n\t\t\t\t|| (!(level instanceof MiningLevel) && !level.passable[pos] && !level.avoid[pos])){\n\t\t\tpos = level.getTransition(null).cell();\n\t\t}\n\t\t\n\t\tPathFinder.setMapSize(level.width(), level.height());\n\t\t\n\t\tDungeon.level = level;\n\t\thero.pos = pos;\n\n\t\tif (hero.buff(AscensionChallenge.class) != null){\n\t\t\thero.buff(AscensionChallenge.class).onLevelSwitch();\n\t\t}\n\n\t\tif (hero.buff(OldAmulet.TempleCurse.class) != null){\n\t\t\thero.buff(OldAmulet.TempleCurse.class).onLevelSwitch();\n\t\t}\n\n\t\tMob.restoreAllies( level, pos );\n\n\t\tActor.init();\n\n\t\tlevel.addRespawner();\n\t\t\n\t\tfor(Mob m : level.mobs){\n\t\t\tif (m.pos == hero.pos && !Char.hasProp(m, Char.Property.IMMOVABLE)){\n\t\t\t\t//displace mob\n\t\t\t\tfor(int i : PathFinder.NEIGHBOURS8){\n\t\t\t\t\tif (Actor.findChar(m.pos+i) == null && level.passable[m.pos + i]){\n\t\t\t\t\t\tm.pos += i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tLight light = hero.buff( Light.class );\n\t\thero.viewDistance = light == null ? level.viewDistance : Math.max( Light.DISTANCE, level.viewDistance );\n\t\t\n\t\thero.curAction = hero.lastAction = null;\n\n\t\tobserve();\n\t\ttry {\n\t\t\tsaveAll();\n\t\t} catch (IOException e) {\n\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t\t/*This only catches IO errors. Yes, this means things can go wrong, and they can go wrong catastrophically.\n\t\t\tBut when they do the user will get a nice 'report this issue' dialogue, and I can fix the bug.*/\n\t\t}\n\t}\n\n\tpublic static void dropToChasm( Item item ) {\n\t\tint depth = Dungeon.depth + 1;\n\t\tArrayList<Item> dropped = Dungeon.droppedItems.get( depth );\n\t\tif (dropped == null) {\n\t\t\tDungeon.droppedItems.put( depth, dropped = new ArrayList<>() );\n\t\t}\n\t\tdropped.add( item );\n\t}\n\n\tpublic static boolean posNeeded() {\n\t\t//2 POS each floor set\n\t\tint posLeftThisSet = 2 - (LimitedDrops.STRENGTH_POTIONS.count - (depth / 5) * 2);\n\t\tif (posLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\n\t\t//pos drops every two floors, (numbers 1-2, and 3-4) with a 50% chance for the earlier one each time.\n\t\tint targetPOSLeft = 2 - floorThisSet/2;\n\t\tif (floorThisSet % 2 == 1 && Random.Int(2) == 0) targetPOSLeft --;\n\n\t\tif (targetPOSLeft < posLeftThisSet) return true;\n\t\telse return false;\n\n\t}\n\t\n\tpublic static boolean souNeeded() {\n\t\tint souLeftThisSet;\n\t\t//3 SOU each floor set\n\t\tsouLeftThisSet = 3 - (LimitedDrops.UPGRADE_SCROLLS.count - (depth / 5) * 3);\n\t\tif (souLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\t\t//chance is floors left / scrolls left\n\t\treturn Random.Int(5 - floorThisSet) < souLeftThisSet;\n\t}\n\t\n\tpublic static boolean asNeeded() {\n\t\t//1 AS each floor set\n\t\tint asLeftThisSet = 1 - (LimitedDrops.ARCANE_STYLI.count - (depth / 5));\n\t\tif (asLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\t\t//chance is floors left / scrolls left\n\t\treturn Random.Int(5 - floorThisSet) < asLeftThisSet;\n\t}\n\n\tprivate static final String INIT_VER\t= \"init_ver\";\n\tprivate static final String VERSION\t\t= \"version\";\n\tprivate static final String SEED\t\t= \"seed\";\n\tprivate static final String CUSTOM_SEED\t= \"custom_seed\";\n\tprivate static final String DAILY\t = \"daily\";\n\tprivate static final String DAILY_REPLAY= \"daily_replay\";\n\tprivate static final String CHALLENGES\t= \"challenges\";\n\tprivate static final String MOBS_TO_CHAMPION\t= \"mobs_to_champion\";\n\tprivate static final String HERO\t\t= \"hero\";\n\tprivate static final String DEPTH\t\t= \"depth\";\n\tprivate static final String BRANCH\t\t= \"branch\";\n\tprivate static final String GENERATED_LEVELS = \"generated_levels\";\n\tprivate static final String GOLD\t\t= \"gold\";\n\tprivate static final String ENERGY\t\t= \"energy\";\n\tprivate static final String BULLET\t\t= \"bullet\";\n\tprivate static final String DROPPED = \"dropped%d\";\n\tprivate static final String PORTED = \"ported%d\";\n\tprivate static final String LEVEL\t\t= \"level\";\n\tprivate static final String LIMDROPS = \"limited_drops\";\n\tprivate static final String CHAPTERS\t= \"chapters\";\n\tprivate static final String QUESTS\t\t= \"quests\";\n\tprivate static final String BADGES\t\t= \"badges\";\n\n\tpublic static void saveGame( int save ) {\n\t\ttry {\n\t\t\tBundle bundle = new Bundle();\n\n\t\t\tbundle.put( INIT_VER, initialVersion );\n\t\t\tbundle.put( VERSION, version = Game.versionCode );\n\t\t\tbundle.put( SEED, seed );\n\t\t\tbundle.put( CUSTOM_SEED, customSeedText );\n\t\t\tbundle.put( DAILY, daily );\n\t\t\tbundle.put( DAILY_REPLAY, dailyReplay );\n\t\t\tbundle.put( CHALLENGES, challenges );\n\t\t\tbundle.put( MOBS_TO_CHAMPION, mobsToChampion );\n\t\t\tbundle.put( HERO, hero );\n\t\t\tbundle.put( DEPTH, depth );\n\t\t\tbundle.put( BRANCH, branch );\n\n\t\t\tbundle.put( GOLD, gold );\n\t\t\tbundle.put( ENERGY, energy );\n\t\t\tbundle.put( BULLET, bullet );\n\n\t\t\tfor (int d : droppedItems.keyArray()) {\n\t\t\t\tbundle.put(Messages.format(DROPPED, d), droppedItems.get(d));\n\t\t\t}\n\n\t\t\tquickslot.storePlaceholders( bundle );\n\n\t\t\tBundle limDrops = new Bundle();\n\t\t\tLimitedDrops.store( limDrops );\n\t\t\tbundle.put ( LIMDROPS, limDrops );\n\t\t\t\n\t\t\tint count = 0;\n\t\t\tint ids[] = new int[chapters.size()];\n\t\t\tfor (Integer id : chapters) {\n\t\t\t\tids[count++] = id;\n\t\t\t}\n\t\t\tbundle.put( CHAPTERS, ids );\n\t\t\t\n\t\t\tBundle quests = new Bundle();\n\t\t\tGhost\t\t.Quest.storeInBundle( quests );\n\t\t\tWandmaker\t.Quest.storeInBundle( quests );\n\t\t\tBlacksmith\t.Quest.storeInBundle( quests );\n\t\t\tImp\t\t\t.Quest.storeInBundle( quests );\n\t\t\tbundle.put( QUESTS, quests );\n\t\t\t\n\t\t\tSpecialRoom.storeRoomsInBundle( bundle );\n\t\t\tSecretRoom.storeRoomsInBundle( bundle );\n\t\t\t\n\t\t\tStatistics.storeInBundle( bundle );\n\t\t\tNotes.storeInBundle( bundle );\n\t\t\tGenerator.storeInBundle( bundle );\n\n\t\t\tint[] bundleArr = new int[generatedLevels.size()];\n\t\t\tfor (int i = 0; i < generatedLevels.size(); i++){\n\t\t\t\tbundleArr[i] = generatedLevels.get(i);\n\t\t\t}\n\t\t\tbundle.put( GENERATED_LEVELS, bundleArr);\n\t\t\t\n\t\t\tScroll.save( bundle );\n\t\t\tPotion.save( bundle );\n\t\t\tRing.save( bundle );\n\n\t\t\tActor.storeNextID( bundle );\n\t\t\t\n\t\t\tBundle badges = new Bundle();\n\t\t\tBadges.saveLocal( badges );\n\t\t\tbundle.put( BADGES, badges );\n\t\t\t\n\t\t\tFileUtils.bundleToFile( GamesInProgress.gameFile(save), bundle);\n\t\t\t\n\t\t} catch (IOException e) {\n\t\t\tGamesInProgress.setUnknown( save );\n\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t}\n\t}\n\t\n\tpublic static void saveLevel( int save ) throws IOException {\n\t\tBundle bundle = new Bundle();\n\t\tbundle.put( LEVEL, level );\n\t\t\n\t\tFileUtils.bundleToFile(GamesInProgress.depthFile( save, depth, branch ), bundle);\n\t}\n\t\n\tpublic static void saveAll() throws IOException {\n\t\tif (hero != null && (hero.isAlive() || WndResurrect.instance != null)) {\n\t\t\t\n\t\t\tActor.fixTime();\n\t\t\tupdateLevelExplored();\n\t\t\tsaveGame( GamesInProgress.curSlot );\n\t\t\tsaveLevel( GamesInProgress.curSlot );\n\n\t\t\tGamesInProgress.set( GamesInProgress.curSlot );\n\n\t\t}\n\t}\n\t\n\tpublic static void loadGame( int save ) throws IOException {\n\t\tloadGame( save, true );\n\t}\n\t\n\tpublic static void loadGame( int save, boolean fullLoad ) throws IOException {\n\t\t\n\t\tBundle bundle = FileUtils.bundleFromFile( GamesInProgress.gameFile( save ) );\n\n\t\t//pre-1.3.0 saves\n\t\tif (bundle.contains(INIT_VER)){\n\t\t\tinitialVersion = bundle.getInt( INIT_VER );\n\t\t} else {\n\t\t\tinitialVersion = bundle.getInt( VERSION );\n\t\t}\n\n\t\tversion = bundle.getInt( VERSION );\n\n\t\tseed = bundle.contains( SEED ) ? bundle.getLong( SEED ) : DungeonSeed.randomSeed();\n\t\tcustomSeedText = bundle.getString( CUSTOM_SEED );\n\t\tdaily = bundle.getBoolean( DAILY );\n\t\tdailyReplay = bundle.getBoolean( DAILY_REPLAY );\n\n\t\tActor.clear();\n\t\tActor.restoreNextID( bundle );\n\n\t\tquickslot.reset();\n\t\tQuickSlotButton.reset();\n\t\tToolbar.swappedQuickslots = false;\n\n\t\tDungeon.challenges = bundle.getInt( CHALLENGES );\n\t\tDungeon.mobsToChampion = bundle.getInt( MOBS_TO_CHAMPION );\n\t\t\n\t\tDungeon.level = null;\n\t\tDungeon.depth = -1;\n\t\t\n\t\tScroll.restore( bundle );\n\t\tPotion.restore( bundle );\n\t\tRing.restore( bundle );\n\n\t\tquickslot.restorePlaceholders( bundle );\n\t\t\n\t\tif (fullLoad) {\n\t\t\t\n\t\t\tLimitedDrops.restore( bundle.getBundle(LIMDROPS) );\n\n\t\t\tchapters = new HashSet<>();\n\t\t\tint ids[] = bundle.getIntArray( CHAPTERS );\n\t\t\tif (ids != null) {\n\t\t\t\tfor (int id : ids) {\n\t\t\t\t\tchapters.add( id );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tBundle quests = bundle.getBundle( QUESTS );\n\t\t\tif (!quests.isNull()) {\n\t\t\t\tGhost.Quest.restoreFromBundle( quests );\n\t\t\t\tWandmaker.Quest.restoreFromBundle( quests );\n\t\t\t\tBlacksmith.Quest.restoreFromBundle( quests );\n\t\t\t\tImp.Quest.restoreFromBundle( quests );\n\t\t\t} else {\n\t\t\t\tGhost.Quest.reset();\n\t\t\t\tWandmaker.Quest.reset();\n\t\t\t\tBlacksmith.Quest.reset();\n\t\t\t\tImp.Quest.reset();\n\t\t\t}\n\t\t\t\n\t\t\tSpecialRoom.restoreRoomsFromBundle(bundle);\n\t\t\tSecretRoom.restoreRoomsFromBundle(bundle);\n\t\t}\n\t\t\n\t\tBundle badges = bundle.getBundle(BADGES);\n\t\tif (!badges.isNull()) {\n\t\t\tBadges.loadLocal( badges );\n\t\t} else {\n\t\t\tBadges.reset();\n\t\t}\n\t\t\n\t\tNotes.restoreFromBundle( bundle );\n\t\t\n\t\thero = null;\n\t\thero = (Hero)bundle.get( HERO );\n\t\t\n\t\tdepth = bundle.getInt( DEPTH );\n\t\tbranch = bundle.getInt( BRANCH );\n\n\t\tgold = bundle.getInt( GOLD );\n\t\tenergy = bundle.getInt( ENERGY );\n\t\tbullet = bundle.getInt( BULLET );\n\n\t\tStatistics.restoreFromBundle( bundle );\n\t\tGenerator.restoreFromBundle( bundle );\n\n\t\tgeneratedLevels.clear();\n\t\tif (bundle.contains(GENERATED_LEVELS)){\n\t\t\tfor (int i : bundle.getIntArray(GENERATED_LEVELS)){\n\t\t\t\tgeneratedLevels.add(i);\n\t\t\t}\n\t\t//pre-v2.1.1 saves\n\t\t} else {\n\t\t\tfor (int i = 1; i <= Statistics.deepestFloor; i++){\n\t\t\t\tgeneratedLevels.add(i);\n\t\t\t}\n\t\t}\n\n\t\tdroppedItems = new SparseArray<>();\n\t\tfor (int i=1; i <= 31; i++) {\n\t\t\t\n\t\t\t//dropped items\n\t\t\tArrayList<Item> items = new ArrayList<>();\n\t\t\tif (bundle.contains(Messages.format( DROPPED, i )))\n\t\t\t\tfor (Bundlable b : bundle.getCollection( Messages.format( DROPPED, i ) ) ) {\n\t\t\t\t\titems.add( (Item)b );\n\t\t\t\t}\n\t\t\tif (!items.isEmpty()) {\n\t\t\t\tdroppedItems.put( i, items );\n\t\t\t}\n\n\t\t}\n\t}\n\t\n\tpublic static Level loadLevel( int save ) throws IOException {\n\t\t\n\t\tDungeon.level = null;\n\t\tActor.clear();\n\n\t\tBundle bundle = FileUtils.bundleFromFile( GamesInProgress.depthFile( save, depth, branch ));\n\n\t\tLevel level = (Level)bundle.get( LEVEL );\n\n\t\tif (level == null){\n\t\t\tthrow new IOException();\n\t\t} else {\n\t\t\treturn level;\n\t\t}\n\t}\n\t\n\tpublic static void deleteGame( int save, boolean deleteLevels ) {\n\n\t\tif (deleteLevels) {\n\t\t\tString folder = GamesInProgress.gameFolder(save);\n\t\t\tfor (String file : FileUtils.filesInDir(folder)){\n\t\t\t\tif (file.contains(\"depth\")){\n\t\t\t\t\tFileUtils.deleteFile(folder + \"/\" + file);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tFileUtils.overwriteFile(GamesInProgress.gameFile(save), 1);\n\t\t\n\t\tGamesInProgress.delete( save );\n\t}\n\t\n\tpublic static void preview( GamesInProgress.Info info, Bundle bundle ) {\n\t\tinfo.depth = bundle.getInt( DEPTH );\n\t\tinfo.version = bundle.getInt( VERSION );\n\t\tinfo.challenges = bundle.getInt( CHALLENGES );\n\t\tinfo.seed = bundle.getLong( SEED );\n\t\tinfo.customSeed = bundle.getString( CUSTOM_SEED );\n\t\tinfo.daily = bundle.getBoolean( DAILY );\n\t\tinfo.dailyReplay = bundle.getBoolean( DAILY_REPLAY );\n\n\t\tHero.preview( info, bundle.getBundle( HERO ) );\n\t\tStatistics.preview( info, bundle );\n\t}\n\t\n\tpublic static void fail( Object cause ) {\n\t\tif (WndResurrect.instance == null) {\n\t\t\tupdateLevelExplored();\n\t\t\tStatistics.gameWon = false;\n\t\t\tRankings.INSTANCE.submit( false, cause );\n\t\t}\n\t}\n\t\n\tpublic static void win( Object cause ) {\n\n\t\tupdateLevelExplored();\n\t\tStatistics.gameWon = true;\n\n\t\thero.belongings.identify();\n\n\t\tRankings.INSTANCE.submit( true, cause );\n\t}\n\n\tpublic static void updateLevelExplored(){\n\t\tif (branch == 0 && level instanceof RegularLevel && !Dungeon.bossLevel()){\n\t\t\tStatistics.floorsExplored.put( depth, level.isLevelExplored(depth));\n\t\t}\n\t}\n\n\t//default to recomputing based on max hero vision, in case vision just shrank/grew\n\tpublic static void observe(){\n\t\tint dist = Math.max(Dungeon.hero.viewDistance, 8);\n\t\tdist *= 1f + 0.25f*Dungeon.hero.pointsInTalent(Talent.FARSIGHT);\n\t\tdist *= 1f + 0.25f*Dungeon.hero.pointsInTalent(Talent.TELESCOPE);\n\n\t\tif (Dungeon.hero.buff(MagicalSight.class) != null){\n\t\t\tdist = Math.max( dist, MagicalSight.DISTANCE );\n\t\t}\n\n\t\tobserve( dist+1 );\n\t}\n\t\n\tpublic static void observe( int dist ) {\n\n\t\tif (level == null) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlevel.updateFieldOfView(hero, level.heroFOV);\n\n\t\tint x = hero.pos % level.width();\n\t\tint y = hero.pos / level.width();\n\t\n\t\t//left, right, top, bottom\n\t\tint l = Math.max( 0, x - dist );\n\t\tint r = Math.min( x + dist, level.width() - 1 );\n\t\tint t = Math.max( 0, y - dist );\n\t\tint b = Math.min( y + dist, level.height() - 1 );\n\t\n\t\tint width = r - l + 1;\n\t\tint height = b - t + 1;\n\t\t\n\t\tint pos = l + t * level.width();\n\t\n\t\tfor (int i = t; i <= b; i++) {\n\t\t\tBArray.or( level.visited, level.heroFOV, pos, width, level.visited );\n\t\t\tpos+=level.width();\n\t\t}\n\t\n\t\tGameScene.updateFog(l, t, width, height);\n\n\t\tif (hero.buff(MindVision.class) != null){\n\t\t\tfor (Mob m : level.mobs.toArray(new Mob[0])){\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1 - level.width(), 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1, 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1 + level.width(), 3, level.visited );\n\t\t\t\t//updates adjacent cells too\n\t\t\t\tGameScene.updateFog(m.pos, 2);\n\t\t\t}\n\t\t}\n\n\t\tif (hero.buff(Awareness.class) != null){\n\t\t\tfor (Heap h : level.heaps.valueList()){\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 - level.width(), 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1, 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 + level.width(), 3, level.visited );\n\t\t\t\tGameScene.updateFog(h.pos, 2);\n\t\t\t}\n\t\t}\n\n\t\tfor (TalismanOfForesight.CharAwareness c : hero.buffs(TalismanOfForesight.CharAwareness.class)){\n\t\t\tChar ch = (Char) Actor.findById(c.charID);\n\t\t\tif (ch == null || !ch.isAlive()) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(ch.pos, 2);\n\t\t}\n\n\t\tfor (TalismanOfForesight.HeapAwareness h : hero.buffs(TalismanOfForesight.HeapAwareness.class)){\n\t\t\tif (Dungeon.depth != h.depth || Dungeon.branch != h.branch) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(h.pos, 2);\n\t\t}\n\n\t\tfor (RevealedArea a : hero.buffs(RevealedArea.class)){\n\t\t\tif (Dungeon.depth != a.depth || Dungeon.branch != a.branch) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(a.pos, 2);\n\t\t}\n\n\t\tfor (Char ch : Actor.chars()){\n\t\t\tif (ch instanceof WandOfWarding.Ward\n\t\t\t\t\t|| ch instanceof WandOfRegrowth.Lotus\n\t\t\t\t\t|| ch instanceof SpiritHawk.HawkAlly){\n\t\t\t\tx = ch.pos % level.width();\n\t\t\t\ty = ch.pos / level.width();\n\n\t\t\t\t//left, right, top, bottom\n\t\t\t\tdist = ch.viewDistance+1;\n\t\t\t\tl = Math.max( 0, x - dist );\n\t\t\t\tr = Math.min( x + dist, level.width() - 1 );\n\t\t\t\tt = Math.max( 0, y - dist );\n\t\t\t\tb = Math.min( y + dist, level.height() - 1 );\n\n\t\t\t\twidth = r - l + 1;\n\t\t\t\theight = b - t + 1;\n\n\t\t\t\tpos = l + t * level.width();\n\n\t\t\t\tfor (int i = t; i <= b; i++) {\n\t\t\t\t\tBArray.or( level.visited, level.heroFOV, pos, width, level.visited );\n\t\t\t\t\tpos+=level.width();\n\t\t\t\t}\n\t\t\t\tGameScene.updateFog(ch.pos, dist);\n\t\t\t}\n\t\t}\n\n\t\tGameScene.afterObserve();\n\t}\n\n\t//we store this to avoid having to re-allocate the array with each pathfind\n\tprivate static boolean[] passable;\n\n\tprivate static void setupPassable(){\n\t\tif (passable == null || passable.length != Dungeon.level.length())\n\t\t\tpassable = new boolean[Dungeon.level.length()];\n\t\telse\n\t\t\tBArray.setFalse(passable);\n\t}\n\n\tpublic static boolean[] findPassable(Char ch, boolean[] pass, boolean[] vis, boolean chars){\n\t\treturn findPassable(ch, pass, vis, chars, chars);\n\t}\n\n\tpublic static boolean[] findPassable(Char ch, boolean[] pass, boolean[] vis, boolean chars, boolean considerLarge){\n\t\tsetupPassable();\n\t\tif (ch.flying || ch.buff( Amok.class ) != null) {\n\t\t\tBArray.or( pass, Dungeon.level.avoid, passable );\n\t\t} else {\n\t\t\tSystem.arraycopy( pass, 0, passable, 0, Dungeon.level.length() );\n\t\t}\n\n\t\tif (considerLarge && Char.hasProp(ch, Char.Property.LARGE)){\n\t\t\tBArray.and( passable, Dungeon.level.openSpace, passable );\n\t\t}\n\n\t\tch.modifyPassable(passable);\n\n\t\tif (chars) {\n\t\t\tfor (Char c : Actor.chars()) {\n\t\t\t\tif (vis[c.pos]) {\n\t\t\t\t\tpassable[c.pos] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn passable;\n\t}\n\n\tpublic static PathFinder.Path findPath(Char ch, int to, boolean[] pass, boolean[] vis, boolean chars) {\n\n\t\treturn PathFinder.find( ch.pos, to, findPassable(ch, pass, vis, chars) );\n\n\t}\n\t\n\tpublic static int findStep(Char ch, int to, boolean[] pass, boolean[] visible, boolean chars ) {\n\n\t\tif (Dungeon.level.adjacent( ch.pos, to )) {\n\t\t\treturn Actor.findChar( to ) == null && pass[to] ? to : -1;\n\t\t}\n\n\t\treturn PathFinder.getStep( ch.pos, to, findPassable(ch, pass, visible, chars) );\n\n\t}\n\t\n\tpublic static int flee( Char ch, int from, boolean[] pass, boolean[] visible, boolean chars ) {\n\t\tboolean[] passable = findPassable(ch, pass, visible, false, true);\n\t\tpassable[ch.pos] = true;\n\n\t\t//only consider other chars impassable if our retreat step may collide with them\n\t\tif (chars) {\n\t\t\tfor (Char c : Actor.chars()) {\n\t\t\t\tif (c.pos == from || Dungeon.level.adjacent(c.pos, ch.pos)) {\n\t\t\t\t\tpassable[c.pos] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//chars affected by terror have a shorter lookahead and can't approach the fear source\n\t\tboolean canApproachFromPos = ch.buff(Terror.class) == null && ch.buff(Dread.class) == null;\n\t\treturn PathFinder.getStepBack( ch.pos, from, canApproachFromPos ? 8 : 4, passable, canApproachFromPos );\n\t\t\n\t}\n\n}" }, { "identifier": "Actor", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/Actor.java", "snippet": "public abstract class Actor implements Bundlable {\n\t\n\tpublic static final float TICK\t= 1f;\n\n\tprivate float time;\n\n\tprivate int id = 0;\n\n\t//default priority values for general actor categories\n\t//note that some specific actors pick more specific values\n\t//e.g. a buff acting after all normal buffs might have priority BUFF_PRIO + 1\n\tprotected static final int VFX_PRIO = 100; //visual effects take priority\n\tprotected static final int HERO_PRIO = 0; //positive is before hero, negative after\n\tprotected static final int BLOB_PRIO = -10; //blobs act after hero, before mobs\n\tprotected static final int MOB_PRIO = -20; //mobs act between buffs and blobs\n\tprotected static final int BUFF_PRIO = -30; //buffs act last in a turn\n\tprivate static final int DEFAULT = -100; //if no priority is given, act after all else\n\n\t//used to determine what order actors act in if their time is equal. Higher values act earlier.\n\tprotected int actPriority = DEFAULT;\n\n\tprotected abstract boolean act();\n\n\t//Always spends exactly the specified amount of time, regardless of time-influencing factors\n\tprotected void spendConstant( float time ){\n\t\tthis.time += time;\n\t\t//if time is very close to a whole number, round to a whole number to fix errors\n\t\tfloat ex = Math.abs(this.time % 1f);\n\t\tif (ex < .001f){\n\t\t\tthis.time = Math.round(this.time);\n\t\t}\n\t}\n\n\t//sends time, but the amount can be influenced\n\tprotected void spend( float time ) {\n\t\tspendConstant( time );\n\t}\n\n\tpublic void spendToWhole(){\n\t\ttime = (float)Math.ceil(time);\n\t}\n\t\n\tprotected void postpone( float time ) {\n\t\tif (this.time < now + time) {\n\t\t\tthis.time = now + time;\n\t\t\t//if time is very close to a whole number, round to a whole number to fix errors\n\t\t\tfloat ex = Math.abs(this.time % 1f);\n\t\t\tif (ex < .001f){\n\t\t\t\tthis.time = Math.round(this.time);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic float cooldown() {\n\t\treturn time - now;\n\t}\n\n\tpublic void clearTime() {\n\t\ttime = 0;\n\t}\n\n\tpublic void timeToNow() {\n\t\ttime = now;\n\t}\n\t\n\tprotected void diactivate() {\n\t\ttime = Float.MAX_VALUE;\n\t}\n\t\n\tprotected void onAdd() {}\n\t\n\tprotected void onRemove() {}\n\n\tprivate static final String TIME = \"time\";\n\tprivate static final String ID = \"id\";\n\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tbundle.put( TIME, time );\n\t\tbundle.put( ID, id );\n\t}\n\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\ttime = bundle.getFloat( TIME );\n\t\tint incomingID = bundle.getInt( ID );\n\t\tif (Actor.findById(incomingID) == null){\n\t\t\tid = incomingID;\n\t\t} else {\n\t\t\tid = nextID++;\n\t\t}\n\t}\n\n\tpublic int id() {\n\t\tif (id > 0) {\n\t\t\treturn id;\n\t\t} else {\n\t\t\treturn (id = nextID++);\n\t\t}\n\t}\n\n\t// **********************\n\t// *** Static members ***\n\t// **********************\n\t\n\tprivate static HashSet<Actor> all = new HashSet<>();\n\tprivate static HashSet<Char> chars = new HashSet<>();\n\tprivate static volatile Actor current;\n\n\tprivate static SparseArray<Actor> ids = new SparseArray<>();\n\tprivate static int nextID = 1;\n\n\tprivate static float now = 0;\n\t\n\tpublic static float now(){\n\t\treturn now;\n\t}\n\t\n\tpublic static synchronized void clear() {\n\t\t\n\t\tnow = 0;\n\n\t\tall.clear();\n\t\tchars.clear();\n\n\t\tids.clear();\n\t}\n\n\tpublic static synchronized void fixTime() {\n\t\t\n\t\tif (all.isEmpty()) return;\n\t\t\n\t\tfloat min = Float.MAX_VALUE;\n\t\tfor (Actor a : all) {\n\t\t\tif (a.time < min) {\n\t\t\t\tmin = a.time;\n\t\t\t}\n\t\t}\n\n\t\t//Only pull everything back by whole numbers\n\t\t//So that turns always align with a whole number\n\t\tmin = (int)min;\n\t\tfor (Actor a : all) {\n\t\t\ta.time -= min;\n\t\t}\n\n\t\tif (Dungeon.hero != null && all.contains( Dungeon.hero )) {\n\t\t\tStatistics.duration += min;\n\t\t}\n\t\tnow -= min;\n\t}\n\t\n\tpublic static void init() {\n\t\t\n\t\tadd( Dungeon.hero );\n\t\t\n\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\tadd( mob );\n\t\t}\n\n\t\t//mobs need to remember their targets after every actor is added\n\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\tmob.restoreEnemy();\n\t\t}\n\t\t\n\t\tfor (Blob blob : Dungeon.level.blobs.values()) {\n\t\t\tadd( blob );\n\t\t}\n\t\t\n\t\tcurrent = null;\n\t}\n\n\tprivate static final String NEXTID = \"nextid\";\n\n\tpublic static void storeNextID( Bundle bundle){\n\t\tbundle.put( NEXTID, nextID );\n\t}\n\n\tpublic static void restoreNextID( Bundle bundle){\n\t\tnextID = bundle.getInt( NEXTID );\n\t}\n\n\tpublic static void resetNextID(){\n\t\tnextID = 1;\n\t}\n\n\t/*protected*/public void next() {\n\t\tif (current == this) {\n\t\t\tcurrent = null;\n\t\t}\n\t}\n\n\tpublic static boolean processing(){\n\t\treturn current != null;\n\t}\n\n\tpublic static int curActorPriority() {\n\t\treturn current != null ? current.actPriority : DEFAULT;\n\t}\n\t\n\tpublic static boolean keepActorThreadAlive = true;\n\t\n\tpublic static void process() {\n\t\t\n\t\tboolean doNext;\n\t\tboolean interrupted = false;\n\n\t\tdo {\n\t\t\t\n\t\t\tcurrent = null;\n\t\t\tif (!interrupted) {\n\t\t\t\tfloat earliest = Float.MAX_VALUE;\n\n\t\t\t\tfor (Actor actor : all) {\n\t\t\t\t\t\n\t\t\t\t\t//some actors will always go before others if time is equal.\n\t\t\t\t\tif (actor.time < earliest ||\n\t\t\t\t\t\t\tactor.time == earliest && (current == null || actor.actPriority > current.actPriority)) {\n\t\t\t\t\t\tearliest = actor.time;\n\t\t\t\t\t\tcurrent = actor;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (current != null) {\n\n\t\t\t\tnow = current.time;\n\t\t\t\tActor acting = current;\n\n\t\t\t\tif (acting instanceof Char && ((Char) acting).sprite != null) {\n\t\t\t\t\t// If it's character's turn to act, but its sprite\n\t\t\t\t\t// is moving, wait till the movement is over\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsynchronized (((Char)acting).sprite) {\n\t\t\t\t\t\t\tif (((Char)acting).sprite.isMoving) {\n\t\t\t\t\t\t\t\t((Char) acting).sprite.wait();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\tinterrupted = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tinterrupted = interrupted || Thread.interrupted();\n\t\t\t\t\n\t\t\t\tif (interrupted){\n\t\t\t\t\tdoNext = false;\n\t\t\t\t\tcurrent = null;\n\t\t\t\t} else {\n\t\t\t\t\tdoNext = acting.act();\n\t\t\t\t\tif (doNext && (Dungeon.hero == null || !Dungeon.hero.isAlive())) {\n\t\t\t\t\t\tdoNext = false;\n\t\t\t\t\t\tcurrent = null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdoNext = false;\n\t\t\t}\n\n\t\t\tif (!doNext){\n\t\t\t\tsynchronized (Thread.currentThread()) {\n\t\t\t\t\t\n\t\t\t\t\tinterrupted = interrupted || Thread.interrupted();\n\t\t\t\t\t\n\t\t\t\t\tif (interrupted){\n\t\t\t\t\t\tcurrent = null;\n\t\t\t\t\t\tinterrupted = false;\n\t\t\t\t\t}\n\n\t\t\t\t\t//signals to the gamescene that actor processing is finished for now\n\t\t\t\t\tThread.currentThread().notify();\n\t\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\tThread.currentThread().wait();\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\tinterrupted = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t} while (keepActorThreadAlive);\n\t}\n\t\n\tpublic static void add( Actor actor ) {\n\t\tadd( actor, now );\n\t}\n\t\n\tpublic static void addDelayed( Actor actor, float delay ) {\n\t\tadd( actor, now + Math.max(delay, 0) );\n\t}\n\t\n\tprivate static synchronized void add( Actor actor, float time ) {\n\t\t\n\t\tif (all.contains( actor )) {\n\t\t\treturn;\n\t\t}\n\n\t\tids.put( actor.id(), actor );\n\n\t\tall.add( actor );\n\t\tactor.time += time;\n\t\tactor.onAdd();\n\t\t\n\t\tif (actor instanceof Char) {\n\t\t\tChar ch = (Char)actor;\n\t\t\tchars.add( ch );\n\t\t\tfor (Buff buff : ch.buffs()) {\n\t\t\t\tadd(buff);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static synchronized void remove( Actor actor ) {\n\t\t\n\t\tif (actor != null) {\n\t\t\tall.remove( actor );\n\t\t\tchars.remove( actor );\n\t\t\tactor.onRemove();\n\n\t\t\tif (actor.id > 0) {\n\t\t\t\tids.remove( actor.id );\n\t\t\t}\n\t\t}\n\t}\n\n\t//'freezes' a character in time for a specified amount of time\n\t//USE CAREFULLY! Manipulating time like this is useful for some gameplay effects but is tricky\n\tpublic static void delayChar( Char ch, float time ){\n\t\tch.spendConstant(time);\n\t\tfor (Buff b : ch.buffs()){\n\t\t\tb.spendConstant(time);\n\t\t}\n\t}\n\t\n\tpublic static synchronized Char findChar( int pos ) {\n\t\tfor (Char ch : chars){\n\t\t\tif (ch.pos == pos)\n\t\t\t\treturn ch;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static synchronized Actor findById( int id ) {\n\t\treturn ids.get( id );\n\t}\n\n\tpublic static synchronized HashSet<Actor> all() {\n\t\treturn new HashSet<>(all);\n\t}\n\n\tpublic static synchronized HashSet<Char> chars() { return new HashSet<>(chars); }\n}" }, { "identifier": "Char", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/Char.java", "snippet": "public abstract class Char extends Actor {\n\t\n\tpublic int pos = 0;\n\t\n\tpublic CharSprite sprite;\n\t\n\tpublic int HT;\n\tpublic int HP;\n\t\n\tprotected float baseSpeed\t= 1;\n\tprotected PathFinder.Path path;\n\n\tpublic int paralysed\t = 0;\n\tpublic boolean rooted\t\t= false;\n\tpublic boolean flying\t\t= false;\n\tpublic int invisible\t\t= 0;\n\t\n\t//these are relative to the hero\n\tpublic enum Alignment{\n\t\tENEMY,\n\t\tNEUTRAL,\n\t\tALLY\n\t}\n\tpublic Alignment alignment;\n\t\n\tpublic int viewDistance\t= 8;\n\t\n\tpublic boolean[] fieldOfView = null;\n\t\n\tprivate LinkedHashSet<Buff> buffs = new LinkedHashSet<>();\n\t\n\t@Override\n\tprotected boolean act() {\n\t\tif (fieldOfView == null || fieldOfView.length != Dungeon.level.length()){\n\t\t\tfieldOfView = new boolean[Dungeon.level.length()];\n\t\t}\n\t\tDungeon.level.updateFieldOfView( this, fieldOfView );\n\n\t\t//throw any items that are on top of an immovable char\n\t\tif (properties().contains(Property.IMMOVABLE)){\n\t\t\tthrowItems();\n\t\t}\n\t\treturn false;\n\t}\n\n\tprotected void throwItems(){\n\t\tHeap heap = Dungeon.level.heaps.get( pos );\n\t\tif (heap != null && heap.type == Heap.Type.HEAP\n\t\t\t\t&& !(heap.peek() instanceof Tengu.BombAbility.BombItem)\n\t\t\t\t&& !(heap.peek() instanceof Tengu.ShockerAbility.ShockerItem)) {\n\t\t\tArrayList<Integer> candidates = new ArrayList<>();\n\t\t\tfor (int n : PathFinder.NEIGHBOURS8){\n\t\t\t\tif (Dungeon.level.passable[pos+n]){\n\t\t\t\t\tcandidates.add(pos+n);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!candidates.isEmpty()){\n\t\t\t\tDungeon.level.drop( heap.pickUp(), Random.element(candidates) ).sprite.drop( pos );\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic String name(){\n\t\treturn Messages.get(this, \"name\");\n\t}\n\n\tpublic boolean canInteract(Char c){\n\t\tif (Dungeon.level.adjacent( pos, c.pos )){\n\t\t\treturn true;\n\t\t} else if (c instanceof Hero\n\t\t\t\t&& alignment == Alignment.ALLY\n\t\t\t\t&& Dungeon.level.distance(pos, c.pos) <= 2*Dungeon.hero.pointsInTalent(Talent.ALLY_WARP)){\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t//swaps places by default\n\tpublic boolean interact(Char c){\n\n\t\t//don't allow char to swap onto hazard unless they're flying\n\t\t//you can swap onto a hazard though, as you're not the one instigating the swap\n\t\tif (!Dungeon.level.passable[pos] && !c.flying){\n\t\t\treturn true;\n\t\t}\n\n\t\t//can't swap into a space without room\n\t\tif (properties().contains(Property.LARGE) && !Dungeon.level.openSpace[c.pos]\n\t\t\t|| c.properties().contains(Property.LARGE) && !Dungeon.level.openSpace[pos]){\n\t\t\treturn true;\n\t\t}\n\n\t\t//we do a little raw position shuffling here so that the characters are never\n\t\t// on the same cell when logic such as occupyCell() is triggered\n\t\tint oldPos = pos;\n\t\tint newPos = c.pos;\n\n\t\t//warp instantly with allies in this case\n\t\tif (c == Dungeon.hero && Dungeon.hero.hasTalent(Talent.ALLY_WARP)){\n\t\t\tPathFinder.buildDistanceMap(c.pos, BArray.or(Dungeon.level.passable, Dungeon.level.avoid, null));\n\t\t\tif (PathFinder.distance[pos] == Integer.MAX_VALUE){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tpos = newPos;\n\t\t\tc.pos = oldPos;\n\t\t\tScrollOfTeleportation.appear(this, newPos);\n\t\t\tScrollOfTeleportation.appear(c, oldPos);\n\t\t\tDungeon.observe();\n\t\t\tGameScene.updateFog();\n\t\t\treturn true;\n\t\t}\n\n\t\t//can't swap places if one char has restricted movement\n\t\tif (rooted || c.rooted || buff(Vertigo.class) != null || c.buff(Vertigo.class) != null){\n\t\t\treturn true;\n\t\t}\n\n\t\tc.pos = oldPos;\n\t\tmoveSprite( oldPos, newPos );\n\t\tmove( newPos );\n\n\t\tc.pos = newPos;\n\t\tc.sprite.move( newPos, oldPos );\n\t\tc.move( oldPos );\n\t\t\n\t\tc.spend( 1 / c.speed() );\n\n\t\tif (c == Dungeon.hero){\n\t\t\tif (Dungeon.hero.subClass == HeroSubClass.FREERUNNER){\n\t\t\t\tBuff.affect(Dungeon.hero, Momentum.class).gainStack();\n\t\t\t}\n\n\t\t\tDungeon.hero.busy();\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t\n\tprotected boolean moveSprite( int from, int to ) {\n\t\t\n\t\tif (sprite.isVisible() && sprite.parent != null && (Dungeon.level.heroFOV[from] || Dungeon.level.heroFOV[to])) {\n\t\t\tsprite.move( from, to );\n\t\t\treturn true;\n\t\t} else {\n\t\t\tsprite.turnTo(from, to);\n\t\t\tsprite.place( to );\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic void hitSound( float pitch ){\n\t\tSample.INSTANCE.play(Assets.Sounds.HIT, 1, pitch);\n\t}\n\n\tpublic boolean blockSound( float pitch ) {\n\t\treturn false;\n\t}\n\t\n\tprotected static final String POS = \"pos\";\n\tprotected static final String TAG_HP = \"HP\";\n\tprotected static final String TAG_HT = \"HT\";\n\tprotected static final String TAG_SHLD = \"SHLD\";\n\tprotected static final String BUFFS\t = \"buffs\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.storeInBundle( bundle );\n\t\t\n\t\tbundle.put( POS, pos );\n\t\tbundle.put( TAG_HP, HP );\n\t\tbundle.put( TAG_HT, HT );\n\t\tbundle.put( BUFFS, buffs );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.restoreFromBundle( bundle );\n\t\t\n\t\tpos = bundle.getInt( POS );\n\t\tHP = bundle.getInt( TAG_HP );\n\t\tHT = bundle.getInt( TAG_HT );\n\t\t\n\t\tfor (Bundlable b : bundle.getCollection( BUFFS )) {\n\t\t\tif (b != null) {\n\t\t\t\t((Buff)b).attachTo( this );\n\t\t\t}\n\t\t}\n\t}\n\n\tfinal public boolean attack( Char enemy ){\n\t\treturn attack(enemy, 1f, 0f, 1f);\n\t}\n\t\n\tpublic boolean attack( Char enemy, float dmgMulti, float dmgBonus, float accMulti ) {\n\n\t\tif (enemy == null) return false;\n\t\t\n\t\tboolean visibleFight = Dungeon.level.heroFOV[pos] || Dungeon.level.heroFOV[enemy.pos];\n\n\t\tif (enemy.isInvulnerable(getClass())) {\n\n\t\t\tif (visibleFight) {\n\t\t\t\tenemy.sprite.showStatus( CharSprite.POSITIVE, Messages.get(this, \"invulnerable\") );\n\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1f, Random.Float(0.96f, 1.05f));\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (hit( this, enemy, accMulti, false )) {\n\t\t\t\n\t\t\tint dr = Math.round(enemy.drRoll() * AscensionChallenge.statModifier(enemy));\n\t\t\t\n\t\t\tif (this instanceof Hero){\n\t\t\t\tHero h = (Hero)this;\n\t\t\t\tif (h.belongings.attackingWeapon() instanceof MissileWeapon\n\t\t\t\t\t\t&& h.subClass == HeroSubClass.SNIPER\n\t\t\t\t\t\t&& !Dungeon.level.adjacent(h.pos, enemy.pos)){\n\t\t\t\t\tdr = 0;\n\t\t\t\t}\n\n\t\t\t\tif (h.belongings.attackingWeapon() instanceof Gun.Bullet) {\n\t\t\t\t\tdr *= ((Gun.Bullet) h.belongings.attackingWeapon()).whatBullet().armorFactor();\n\t\t\t\t}\n\n\t\t\t\tif (h.buff(MonkEnergy.MonkAbility.UnarmedAbilityTracker.class) != null){\n\t\t\t\t\tdr = 0;\n\t\t\t\t} else if (h.subClass == HeroSubClass.MONK) {\n\t\t\t\t\t//3 turns with standard attack delay\n\t\t\t\t\tBuff.prolong(h, MonkEnergy.MonkAbility.JustHitTracker.class, 4f);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//we use a float here briefly so that we don't have to constantly round while\n\t\t\t// potentially applying various multiplier effects\n\t\t\tfloat dmg;\n\t\t\tPreparation prep = buff(Preparation.class);\n\t\t\tif (prep != null){\n\t\t\t\tdmg = prep.damageRoll(this);\n\t\t\t\tif (this == Dungeon.hero && Dungeon.hero.hasTalent(Talent.BOUNTY_HUNTER)) {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.BountyHunterTracker.class, 0.0f);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdmg = damageRoll();\n\t\t\t}\n\n\t\t\tdmg = Math.round(dmg*dmgMulti);\n\n\t\t\tBerserk berserk = buff(Berserk.class);\n\t\t\tif (berserk != null) dmg = berserk.damageFactor(dmg);\n\n\t\t\tif (buff( Fury.class ) != null) {\n\t\t\t\tdmg *= 1.5f;\n\t\t\t}\n\n\t\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\t\tdmg *= buff.meleeDamageFactor();\n\t\t\t}\n\n\t\t\tdmg *= AscensionChallenge.statModifier(this);\n\n\t\t\t//flat damage bonus is applied after positive multipliers, but before negative ones\n\t\t\tdmg += dmgBonus;\n\n\t\t\t//friendly endure\n\t\t\tEndure.EndureTracker endure = buff(Endure.EndureTracker.class);\n\t\t\tif (endure != null) dmg = endure.damageFactor(dmg);\n\n\t\t\t//enemy endure\n\t\t\tendure = enemy.buff(Endure.EndureTracker.class);\n\t\t\tif (endure != null){\n\t\t\t\tdmg = endure.adjustDamageTaken(dmg);\n\t\t\t}\n\n\t\t\tif (enemy.buff(ScrollOfChallenge.ChallengeArena.class) != null){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\n\t\t\tif (enemy.buff(MonkEnergy.MonkAbility.Meditate.MeditateResistance.class) != null){\n\t\t\t\tdmg *= 0.2f;\n\t\t\t}\n\n\t\t\tif ( buff(Weakness.class) != null ){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\n\t\t\tif ( buff(SoulMark.class) != null && hero.hasTalent(Talent.MARK_OF_WEAKNESS)) {\n\t\t\t\tif (this.alignment != Alignment.ALLY) {\n\t\t\t\t\tdmg *= Math.pow(0.9f, hero.pointsInTalent(Talent.MARK_OF_WEAKNESS));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tint effectiveDamage = enemy.defenseProc( this, Math.round(dmg) );\n\t\t\t//do not trigger on-hit logic if defenseProc returned a negative value\n\t\t\tif (effectiveDamage >= 0) {\n\t\t\t\teffectiveDamage = Math.max(effectiveDamage - dr, 0);\n\n\t\t\t\tif (enemy.buff(Viscosity.ViscosityTracker.class) != null) {\n\t\t\t\t\teffectiveDamage = enemy.buff(Viscosity.ViscosityTracker.class).deferDamage(effectiveDamage);\n\t\t\t\t\tenemy.buff(Viscosity.ViscosityTracker.class).detach();\n\t\t\t\t}\n\n\t\t\t\t//vulnerable specifically applies after armor reductions\n\t\t\t\tif (enemy.buff(Vulnerable.class) != null) {\n\t\t\t\t\teffectiveDamage *= 1.33f;\n\t\t\t\t}\n\n\t\t\t\teffectiveDamage = attackProc(enemy, effectiveDamage);\n\t\t\t}\n\t\t\tif (visibleFight) {\n\t\t\t\tif (effectiveDamage > 0 || !enemy.blockSound(Random.Float(0.96f, 1.05f))) {\n\t\t\t\t\thitSound(Random.Float(0.87f, 1.15f));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If the enemy is already dead, interrupt the attack.\n\t\t\t// This matters as defence procs can sometimes inflict self-damage, such as armor glyphs.\n\t\t\tif (!enemy.isAlive()){\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tenemy.damage( effectiveDamage, this );\n\n\t\t\tif (buff(FireImbue.class) != null) buff(FireImbue.class).proc(enemy);\n\t\t\tif (buff(FrostImbue.class) != null) buff(FrostImbue.class).proc(enemy);\n\t\t\tif (buff(ThunderImbue.class) != null) buff(ThunderImbue.class).proc(enemy, (int)dmg);\n\n\t\t\tif (enemy.isAlive() && enemy.alignment != alignment && prep != null && prep.canKO(enemy)){\n\t\t\t\tenemy.HP = 0;\n\t\t\t\tif (!enemy.isAlive()) {\n\t\t\t\t\tenemy.die(this);\n\t\t\t\t} else {\n\t\t\t\t\t//helps with triggering any on-damage effects that need to activate\n\t\t\t\t\tenemy.damage(-1, this);\n\t\t\t\t\tDeathMark.processFearTheReaper(enemy);\n\t\t\t\t}\n\t\t\t\tif (enemy.sprite != null) {\n\t\t\t\t\tenemy.sprite.showStatus(CharSprite.NEGATIVE, Messages.get(Preparation.class, \"assassinated\"));\n\t\t\t\t}\n\t\t\t\tif (Random.Float() < hero.pointsInTalent(Talent.ENERGY_DRAW)/3f) {\n\t\t\t\t\tCloakOfShadows cloak = hero.belongings.getItem(CloakOfShadows.class);\n\t\t\t\t\tif (cloak != null) {\n\t\t\t\t\t\tcloak.overCharge(1);\n\t\t\t\t\t\tScrollOfRecharging.charge(Dungeon.hero);\n\t\t\t\t\t\tSpellSprite.show(hero, SpellSprite.CHARGE);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tTalent.CombinedLethalityTriggerTracker combinedLethality = buff(Talent.CombinedLethalityTriggerTracker.class);\n\t\t\tif (combinedLethality != null){\n\t\t\t\tif ( enemy.isAlive() && enemy.alignment != alignment && !Char.hasProp(enemy, Property.BOSS)\n\t\t\t\t\t\t&& !Char.hasProp(enemy, Property.MINIBOSS) && this instanceof Hero &&\n\t\t\t\t\t\t(enemy.HP/(float)enemy.HT) <= 0.4f*((Hero)this).pointsInTalent(Talent.COMBINED_LETHALITY)/3f) {\n\t\t\t\t\tenemy.HP = 0;\n\t\t\t\t\tif (!enemy.isAlive()) {\n\t\t\t\t\t\tenemy.die(this);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//helps with triggering any on-damage effects that need to activate\n\t\t\t\t\t\tenemy.damage(-1, this);\n\t\t\t\t\t\tDeathMark.processFearTheReaper(enemy);\n\t\t\t\t\t}\n\t\t\t\t\tif (enemy.sprite != null) {\n\t\t\t\t\t\tenemy.sprite.showStatus(CharSprite.NEGATIVE, Messages.get(Talent.CombinedLethalityTriggerTracker.class, \"executed\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcombinedLethality.detach();\n\t\t\t}\n\n\t\t\tif (enemy.sprite != null) {\n\t\t\t\tenemy.sprite.bloodBurstA(sprite.center(), effectiveDamage);\n\t\t\t\tenemy.sprite.flash();\n\t\t\t}\n\n\t\t\tif (!enemy.isAlive() && visibleFight) {\n\t\t\t\tif (enemy == Dungeon.hero) {\n\t\t\t\t\t\n\t\t\t\t\tif (this == Dungeon.hero) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this instanceof WandOfLivingEarth.EarthGuardian\n\t\t\t\t\t\t\t|| this instanceof MirrorImage || this instanceof PrismaticImage){\n\t\t\t\t\t\tBadges.validateDeathFromFriendlyMagic();\n\t\t\t\t\t}\n\t\t\t\t\tDungeon.fail( this );\n\t\t\t\t\tGLog.n( Messages.capitalize(Messages.get(Char.class, \"kill\", name())) );\n\t\t\t\t\t\n\t\t\t\t} else if (this == Dungeon.hero) {\n\t\t\t\t\tGLog.i( Messages.capitalize(Messages.get(Char.class, \"defeat\", enemy.name())) );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t\t\n\t\t} else {\n\n\t\t\tif (enemy instanceof Hero) {\n\t\t\t\tif (hero.pointsInTalent(Talent.SWIFT_MOVEMENT) == 3) {\n\t\t\t\t\tBuff.prolong(hero, Invisibility.class, 1.0001f);\n\t\t\t\t}\n\t\t\t\tif (Random.Int(5) < hero.pointsInTalent(Talent.COUNTER_ATTACK)) {\n\t\t\t\t\tBuff.affect(hero, Talent.CounterAttackTracker.class);\n\t\t\t\t}\n\t\t\t\tif (hero.hasTalent(Talent.QUICK_PREP)) {\n\t\t\t\t\tMomentum momentum = hero.buff(Momentum.class);\n\t\t\t\t\tif (momentum != null) {\n\t\t\t\t\t\tmomentum.quickPrep(hero.pointsInTalent(Talent.QUICK_PREP));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tenemy.sprite.showStatus( CharSprite.NEUTRAL, enemy.defenseVerb() );\n\t\t\tif (visibleFight) {\n\t\t\t\t//TODO enemy.defenseSound? currently miss plays for monks/crab even when they parry\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.MISS);\n\t\t\t}\n\t\t\t\n\t\t\treturn false;\n\t\t\t\n\t\t}\n\t}\n\n\tpublic static int INFINITE_ACCURACY = 1_000_000;\n\tpublic static int INFINITE_EVASION = 1_000_000;\n\n\tfinal public static boolean hit( Char attacker, Char defender, boolean magic ) {\n\t\treturn hit(attacker, defender, magic ? 2f : 1f, magic);\n\t}\n\n\tpublic static boolean hit( Char attacker, Char defender, float accMulti, boolean magic ) {\n\t\tfloat acuStat = attacker.attackSkill( defender );\n\t\tfloat defStat = defender.defenseSkill( attacker );\n\n\t\tif (defender instanceof Hero && ((Hero) defender).damageInterrupt){\n\t\t\t((Hero) defender).interrupt();\n\t\t}\n\n\t\t//invisible chars always hit (for the hero this is surprise attacking)\n\t\tif (attacker.invisible > 0 && attacker.canSurpriseAttack()){\n\t\t\tacuStat = INFINITE_ACCURACY;\n\t\t}\n\n\t\tif (defender.buff(MonkEnergy.MonkAbility.Focus.FocusBuff.class) != null && !magic){\n\t\t\tdefStat = INFINITE_EVASION;\n\t\t\tdefender.buff(MonkEnergy.MonkAbility.Focus.FocusBuff.class).detach();\n\t\t\tBuff.affect(defender, MonkEnergy.MonkAbility.Focus.FocusActivation.class, 0);\n\t\t}\n\n\t\t//if accuracy or evasion are large enough, treat them as infinite.\n\t\t//note that infinite evasion beats infinite accuracy\n\t\tif (defStat >= INFINITE_EVASION){\n\t\t\treturn false;\n\t\t} else if (acuStat >= INFINITE_ACCURACY){\n\t\t\treturn true;\n\t\t}\n\n\t\tfloat acuRoll = Random.Float( acuStat );\n\t\tif (attacker.buff(Bless.class) != null) acuRoll *= 1.25f;\n\t\tif (attacker.buff( Hex.class) != null) acuRoll *= 0.8f;\n\t\tif (attacker.buff( Daze.class) != null) acuRoll *= 0.5f;\n\t\tfor (ChampionEnemy buff : attacker.buffs(ChampionEnemy.class)){\n\t\t\tacuRoll *= buff.evasionAndAccuracyFactor();\n\t\t}\n\t\tacuRoll *= AscensionChallenge.statModifier(attacker);\n\t\t\n\t\tfloat defRoll = Random.Float( defStat );\n\t\tif (defender.buff(Bless.class) != null) defRoll *= 1.25f;\n\t\tif (defender.buff( Hex.class) != null) defRoll *= 0.8f;\n\t\tif (defender.buff( Daze.class) != null) defRoll *= 0.5f;\n\t\tfor (ChampionEnemy buff : defender.buffs(ChampionEnemy.class)){\n\t\t\tdefRoll *= buff.evasionAndAccuracyFactor();\n\t\t}\n\t\tdefRoll *= AscensionChallenge.statModifier(defender);\n\t\t\n\t\treturn (acuRoll * accMulti) >= defRoll;\n\t}\n\t\n\tpublic int attackSkill( Char target ) {\n\t\treturn 0;\n\t}\n\t\n\tpublic int defenseSkill( Char enemy ) {\n\t\treturn 0;\n\t}\n\t\n\tpublic String defenseVerb() {\n\t\treturn Messages.get(this, \"def_verb\");\n\t}\n\t\n\tpublic int drRoll() {\n\t\tint dr = 0;\n\n\t\tdr += Random.NormalIntRange( 0 , Barkskin.currentLevel(this) );\n\n\t\treturn dr;\n\t}\n\t\n\tpublic int damageRoll() {\n\t\treturn 1;\n\t}\n\t\n\t//TODO it would be nice to have a pre-armor and post-armor proc.\n\t// atm attack is always post-armor and defence is already pre-armor\n\t\n\tpublic int attackProc( Char enemy, int damage ) {\n\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\tbuff.onAttackProc( enemy );\n\t\t}\n\t\treturn damage;\n\t}\n\t\n\tpublic int defenseProc( Char enemy, int damage ) {\n\n\t\tEarthroot.Armor armor = buff( Earthroot.Armor.class );\n\t\tif (armor != null) {\n\t\t\tdamage = armor.absorb( damage );\n\t\t}\n\n\t\treturn damage;\n\t}\n\t\n\tpublic float speed() {\n\t\tfloat speed = baseSpeed;\n\t\tif ( buff( Cripple.class ) != null ) speed /= 2f;\n\t\tif ( buff( Stamina.class ) != null) speed *= 1.5f;\n\t\tif ( buff( Adrenaline.class ) != null) speed *= 2f;\n\t\tif ( buff( Haste.class ) != null) speed *= 3f;\n\t\tif ( buff( Dread.class ) != null) speed *= 2f;\n\t\treturn speed;\n\t}\n\n\t//currently only used by invisible chars, or by the hero\n\tpublic boolean canSurpriseAttack(){\n\t\treturn true;\n\t}\n\t\n\t//used so that buffs(Shieldbuff.class) isn't called every time unnecessarily\n\tprivate int cachedShield = 0;\n\tpublic boolean needsShieldUpdate = true;\n\t\n\tpublic int shielding(){\n\t\tif (!needsShieldUpdate){\n\t\t\treturn cachedShield;\n\t\t}\n\t\t\n\t\tcachedShield = 0;\n\t\tfor (ShieldBuff s : buffs(ShieldBuff.class)){\n\t\t\tcachedShield += s.shielding();\n\t\t}\n\t\tneedsShieldUpdate = false;\n\t\treturn cachedShield;\n\t}\n\t\n\tpublic void damage( int dmg, Object src ) {\n\t\t\n\t\tif (!isAlive() || dmg < 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tif(isInvulnerable(src.getClass())){\n\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.get(this, \"invulnerable\"));\n\t\t\treturn;\n\t\t}\n\n\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\tdmg = (int) Math.ceil(dmg * buff.damageTakenFactor());\n\t\t}\n\n\t\tif (!(src instanceof LifeLink) && buff(LifeLink.class) != null){\n\t\t\tHashSet<LifeLink> links = buffs(LifeLink.class);\n\t\t\tfor (LifeLink link : links.toArray(new LifeLink[0])){\n\t\t\t\tif (Actor.findById(link.object) == null){\n\t\t\t\t\tlinks.remove(link);\n\t\t\t\t\tlink.detach();\n\t\t\t\t}\n\t\t\t}\n\t\t\tdmg = (int)Math.ceil(dmg / (float)(links.size()+1));\n\t\t\tfor (LifeLink link : links){\n\t\t\t\tChar ch = (Char)Actor.findById(link.object);\n\t\t\t\tif (ch != null) {\n\t\t\t\t\tch.damage(dmg, link);\n\t\t\t\t\tif (!ch.isAlive()) {\n\t\t\t\t\t\tlink.detach();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tTerror t = buff(Terror.class);\n\t\tif (t != null){\n\t\t\tt.recover();\n\t\t}\n\t\tDread d = buff(Dread.class);\n\t\tif (d != null){\n\t\t\td.recover();\n\t\t}\n\t\tCharm c = buff(Charm.class);\n\t\tif (c != null){\n\t\t\tc.recover(src);\n\t\t}\n\t\tif (this.buff(Frost.class) != null){\n\t\t\tBuff.detach( this, Frost.class );\n\t\t}\n\t\tif (this.buff(MagicalSleep.class) != null){\n\t\t\tBuff.detach(this, MagicalSleep.class);\n\t\t}\n\t\tif (this.buff(Doom.class) != null && !isImmune(Doom.class)){\n\t\t\tdmg *= 1.67f;\n\t\t}\n\t\tif (alignment != Alignment.ALLY && this.buff(DeathMark.DeathMarkTracker.class) != null){\n\t\t\tdmg *= 1.25f;\n\t\t}\n\t\t\n\t\tClass<?> srcClass = src.getClass();\n\t\tif (isImmune( srcClass )) {\n\t\t\tdmg = 0;\n\t\t} else {\n\t\t\tdmg = Math.round( dmg * resist( srcClass ));\n\t\t}\n\t\t\n\t\t//TODO improve this when I have proper damage source logic\n\t\tif (AntiMagic.RESISTS.contains(src.getClass()) && buff(ArcaneArmor.class) != null){\n\t\t\tdmg -= Random.NormalIntRange(0, buff(ArcaneArmor.class).level());\n\t\t\tif (dmg < 0) dmg = 0;\n\t\t}\n\n\t\tif (buff(Sickle.HarvestBleedTracker.class) != null){\n\t\t\tif (isImmune(Bleeding.class)){\n\t\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.titleCase(Messages.get(this, \"immune\")));\n\t\t\t\tbuff(Sickle.HarvestBleedTracker.class).detach();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tBleeding b = buff(Bleeding.class);\n\t\t\tif (b == null){\n\t\t\t\tb = new Bleeding();\n\t\t\t}\n\t\t\tb.announced = false;\n\t\t\tb.set(dmg*buff(Sickle.HarvestBleedTracker.class).bleedFactor, Sickle.HarvestBleedTracker.class);\n\t\t\tb.attachTo(this);\n\t\t\tsprite.showStatus(CharSprite.WARNING, Messages.titleCase(b.name()) + \" \" + (int)b.level());\n\t\t\tbuff(Sickle.HarvestBleedTracker.class).detach();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (buff( Paralysis.class ) != null) {\n\t\t\tbuff( Paralysis.class ).processDamage(dmg);\n\t\t}\n\n\t\tint shielded = dmg;\n\t\t//FIXME: when I add proper damage properties, should add an IGNORES_SHIELDS property to use here.\n\t\tif (!(src instanceof Hunger)){\n\t\t\tfor (ShieldBuff s : buffs(ShieldBuff.class)){\n\t\t\t\tdmg = s.absorbDamage(dmg);\n\t\t\t\tif (dmg == 0) break;\n\t\t\t}\n\t\t}\n\t\tshielded -= dmg;\n\t\tHP -= dmg;\n\n\t\tif (HP > 0 && buff(Grim.GrimTracker.class) != null){\n\n\t\t\tfloat finalChance = buff(Grim.GrimTracker.class).maxChance;\n\t\t\tfinalChance *= (float)Math.pow( ((HT - HP) / (float)HT), 2);\n\n\t\t\tif (Random.Float() < finalChance) {\n\t\t\t\tint extraDmg = Math.round(HP*resist(Grim.class));\n\t\t\t\tdmg += extraDmg;\n\t\t\t\tHP -= extraDmg;\n\n\t\t\t\tsprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\tif (!isAlive() && buff(Grim.GrimTracker.class).qualifiesForBadge){\n\t\t\t\t\tBadges.validateGrimWeapon();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (HP < 0 && src instanceof Char && alignment == Alignment.ENEMY){\n\t\t\tif (((Char) src).buff(Kinetic.KineticTracker.class) != null){\n\t\t\t\tint dmgToAdd = -HP;\n\t\t\t\tdmgToAdd -= ((Char) src).buff(Kinetic.KineticTracker.class).conservedDamage;\n\t\t\t\tdmgToAdd = Math.round(dmgToAdd * Weapon.Enchantment.genericProcChanceMultiplier((Char) src));\n\t\t\t\tif (dmgToAdd > 0) {\n\t\t\t\t\tBuff.affect((Char) src, Kinetic.ConservedDamage.class).setBonus(dmgToAdd);\n\t\t\t\t}\n\t\t\t\t((Char) src).buff(Kinetic.KineticTracker.class).detach();\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (sprite != null) {\n\t\t\tsprite.showStatus(HP > HT / 2 ?\n\t\t\t\t\t\t\tCharSprite.WARNING :\n\t\t\t\t\t\t\tCharSprite.NEGATIVE,\n\t\t\t\t\tInteger.toString(dmg + shielded));\n\t\t}\n\n\t\tif (HP < 0) HP = 0;\n\n\t\tif (!isAlive()) {\n\t\t\tdie( src );\n\t\t} else if (HP == 0 && buff(DeathMark.DeathMarkTracker.class) != null){\n\t\t\tDeathMark.processFearTheReaper(this);\n\t\t}\n\t}\n\t\n\tpublic void destroy() {\n\t\tHP = 0;\n\t\tActor.remove( this );\n\n\t\tfor (Char ch : Actor.chars().toArray(new Char[0])){\n\t\t\tif (ch.buff(Charm.class) != null && ch.buff(Charm.class).object == id()){\n\t\t\t\tch.buff(Charm.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Dread.class) != null && ch.buff(Dread.class).object == id()){\n\t\t\t\tch.buff(Dread.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Terror.class) != null && ch.buff(Terror.class).object == id()){\n\t\t\t\tch.buff(Terror.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(SnipersMark.class) != null && ch.buff(SnipersMark.class).object == id()){\n\t\t\t\tch.buff(SnipersMark.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Talent.FollowupStrikeTracker.class) != null\n\t\t\t\t\t&& ch.buff(Talent.FollowupStrikeTracker.class).object == id()){\n\t\t\t\tch.buff(Talent.FollowupStrikeTracker.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Talent.DeadlyFollowupTracker.class) != null\n\t\t\t\t\t&& ch.buff(Talent.DeadlyFollowupTracker.class).object == id()){\n\t\t\t\tch.buff(Talent.DeadlyFollowupTracker.class).detach();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void die( Object src ) {\n\t\tdestroy();\n\t\tif (src != Chasm.class) sprite.die();\n\t}\n\n\t//we cache this info to prevent having to call buff(...) in isAlive.\n\t//This is relevant because we call isAlive during drawing, which has both performance\n\t//and thread coordination implications\n\tpublic boolean deathMarked = false;\n\t\n\tpublic boolean isAlive() {\n\t\treturn HP > 0 || deathMarked;\n\t}\n\n\tpublic boolean isActive() {\n\t\treturn isAlive();\n\t}\n\n\t@Override\n\tprotected void spendConstant(float time) {\n\t\tTimekeepersHourglass.timeFreeze freeze = buff(TimekeepersHourglass.timeFreeze.class);\n\t\tif (freeze != null) {\n\t\t\tfreeze.processTime(time);\n\t\t\treturn;\n\t\t}\n\n\t\tSwiftthistle.TimeBubble bubble = buff(Swiftthistle.TimeBubble.class);\n\t\tif (bubble != null){\n\t\t\tbubble.processTime(time);\n\t\t\treturn;\n\t\t}\n\n\t\tsuper.spendConstant(time);\n\t}\n\n\t@Override\n\tprotected void spend( float time ) {\n\n\t\tfloat timeScale = 1f;\n\t\tif (buff( Slow.class ) != null) {\n\t\t\ttimeScale *= 0.5f;\n\t\t\t//slowed and chilled do not stack\n\t\t} else if (buff( Chill.class ) != null) {\n\t\t\ttimeScale *= buff( Chill.class ).speedFactor();\n\t\t}\n\t\tif (buff( Speed.class ) != null) {\n\t\t\ttimeScale *= 2.0f;\n\t\t}\n\t\t\n\t\tsuper.spend( time / timeScale );\n\t}\n\t\n\tpublic synchronized LinkedHashSet<Buff> buffs() {\n\t\treturn new LinkedHashSet<>(buffs);\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\t//returns all buffs assignable from the given buff class\n\tpublic synchronized <T extends Buff> HashSet<T> buffs( Class<T> c ) {\n\t\tHashSet<T> filtered = new HashSet<>();\n\t\tfor (Buff b : buffs) {\n\t\t\tif (c.isInstance( b )) {\n\t\t\t\tfiltered.add( (T)b );\n\t\t\t}\n\t\t}\n\t\treturn filtered;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t//returns an instance of the specific buff class, if it exists. Not just assignable\n\tpublic synchronized <T extends Buff> T buff( Class<T> c ) {\n\t\tfor (Buff b : buffs) {\n\t\t\tif (b.getClass() == c) {\n\t\t\t\treturn (T)b;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic synchronized boolean isCharmedBy( Char ch ) {\n\t\tint chID = ch.id();\n\t\tfor (Buff b : buffs) {\n\t\t\tif (b instanceof Charm && ((Charm)b).object == chID) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic synchronized boolean add( Buff buff ) {\n\n\t\tif (buff(PotionOfCleansing.Cleanse.class) != null) { //cleansing buff\n\t\t\tif (buff.type == Buff.buffType.NEGATIVE\n\t\t\t\t\t&& !(buff instanceof AllyBuff)\n\t\t\t\t\t&& !(buff instanceof LostInventory)){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tif (sprite != null && buff(Challenge.SpectatorFreeze.class) != null){\n\t\t\treturn false; //can't add buffs while frozen and game is loaded\n\t\t}\n\n\t\tbuffs.add( buff );\n\t\tif (Actor.chars().contains(this)) Actor.add( buff );\n\n\t\tif (sprite != null && buff.announced) {\n\t\t\tswitch (buff.type) {\n\t\t\t\tcase POSITIVE:\n\t\t\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NEGATIVE:\n\t\t\t\t\tsprite.showStatus(CharSprite.NEGATIVE, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NEUTRAL:\n\t\t\t\tdefault:\n\t\t\t\t\tsprite.showStatus(CharSprite.NEUTRAL, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\n\t}\n\t\n\tpublic synchronized boolean remove( Buff buff ) {\n\t\t\n\t\tbuffs.remove( buff );\n\t\tActor.remove( buff );\n\n\t\treturn true;\n\t}\n\t\n\tpublic synchronized void remove( Class<? extends Buff> buffClass ) {\n\t\tfor (Buff buff : buffs( buffClass )) {\n\t\t\tremove( buff );\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected synchronized void onRemove() {\n\t\tfor (Buff buff : buffs.toArray(new Buff[buffs.size()])) {\n\t\t\tbuff.detach();\n\t\t}\n\t}\n\t\n\tpublic synchronized void updateSpriteState() {\n\t\tfor (Buff buff:buffs) {\n\t\t\tbuff.fx( true );\n\t\t}\n\t}\n\t\n\tpublic float stealth() {\n\t\treturn 0;\n\t}\n\n\tpublic final void move( int step ) {\n\t\tmove( step, true );\n\t}\n\n\t//travelling may be false when a character is moving instantaneously, such as via teleportation\n\tpublic void move( int step, boolean travelling ) {\n\n\t\tif (travelling && Dungeon.level.adjacent( step, pos ) && buff( Vertigo.class ) != null) {\n\t\t\tsprite.interruptMotion();\n\t\t\tint newPos = pos + PathFinder.NEIGHBOURS8[Random.Int( 8 )];\n\t\t\tif (!(Dungeon.level.passable[newPos] || Dungeon.level.avoid[newPos])\n\t\t\t\t\t|| (properties().contains(Property.LARGE) && !Dungeon.level.openSpace[newPos])\n\t\t\t\t\t|| Actor.findChar( newPos ) != null)\n\t\t\t\treturn;\n\t\t\telse {\n\t\t\t\tsprite.move(pos, newPos);\n\t\t\t\tstep = newPos;\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.level.map[pos] == Terrain.OPEN_DOOR) {\n\t\t\tDoor.leave( pos );\n\t\t}\n\n\t\tpos = step;\n\t\t\n\t\tif (this != Dungeon.hero) {\n\t\t\tsprite.visible = Dungeon.level.heroFOV[pos];\n\t\t}\n\t\t\n\t\tDungeon.level.occupyCell(this );\n\t}\n\t\n\tpublic int distance( Char other ) {\n\t\treturn Dungeon.level.distance( pos, other.pos );\n\t}\n\n\tpublic boolean[] modifyPassable( boolean[] passable){\n\t\t//do nothing by default, but some chars can pass over terrain that others can't\n\t\treturn passable;\n\t}\n\t\n\tpublic void onMotionComplete() {\n\t\t//Does nothing by default\n\t\t//The main actor thread already accounts for motion,\n\t\t// so calling next() here isn't necessary (see Actor.process)\n\t}\n\t\n\tpublic void onAttackComplete() {\n\t\tnext();\n\t}\n\t\n\tpublic void onOperateComplete() {\n\t\tnext();\n\t}\n\t\n\tprotected final HashSet<Class> resistances = new HashSet<>();\n\t\n\t//returns percent effectiveness after resistances\n\t//TODO currently resistances reduce effectiveness by a static 50%, and do not stack.\n\tpublic float resist( Class effect ){\n\t\tHashSet<Class> resists = new HashSet<>(resistances);\n\t\tfor (Property p : properties()){\n\t\t\tresists.addAll(p.resistances());\n\t\t}\n\t\tfor (Buff b : buffs()){\n\t\t\tresists.addAll(b.resistances());\n\t\t}\n\t\t\n\t\tfloat result = 1f;\n\t\tfor (Class c : resists){\n\t\t\tif (c.isAssignableFrom(effect)){\n\t\t\t\tresult *= 0.5f;\n\t\t\t}\n\t\t}\n\t\treturn result * RingOfElements.resist(this, effect);\n\t}\n\t\n\tprotected final HashSet<Class> immunities = new HashSet<>();\n\t\n\tpublic boolean isImmune(Class effect ){\n\t\tHashSet<Class> immunes = new HashSet<>(immunities);\n\t\tfor (Property p : properties()){\n\t\t\timmunes.addAll(p.immunities());\n\t\t}\n\t\tfor (Buff b : buffs()){\n\t\t\timmunes.addAll(b.immunities());\n\t\t}\n\t\t\n\t\tfor (Class c : immunes){\n\t\t\tif (c.isAssignableFrom(effect)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t//similar to isImmune, but only factors in damage.\n\t//Is used in AI decision-making\n\tpublic boolean isInvulnerable( Class effect ){\n\t\treturn buff(Challenge.SpectatorFreeze.class) != null;\n\t}\n\n\tprotected HashSet<Property> properties = new HashSet<>();\n\n\tpublic HashSet<Property> properties() {\n\t\tHashSet<Property> props = new HashSet<>(properties);\n\t\t//TODO any more of these and we should make it a property of the buff, like with resistances/immunities\n\t\tif (buff(ChampionEnemy.Giant.class) != null) {\n\t\t\tprops.add(Property.LARGE);\n\t\t}\n\t\treturn props;\n\t}\n\n\tpublic enum Property{\n\t\tBOSS ( new HashSet<Class>( Arrays.asList(Grim.class, GrimTrap.class, ScrollOfRetribution.class, ScrollOfPsionicBlast.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(AllyBuff.class, Dread.class) )),\n\t\tMINIBOSS ( new HashSet<Class>(),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(AllyBuff.class, Dread.class) )),\n\t\tBOSS_MINION,\n\t\tUNDEAD,\n\t\tDEMONIC,\n\t\tINORGANIC ( new HashSet<Class>(),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Bleeding.class, ToxicGas.class, Poison.class) )),\n\t\tFIERY ( new HashSet<Class>( Arrays.asList(WandOfFireblast.class, Elemental.FireElemental.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Burning.class, Blazing.class))),\n\t\tICY ( new HashSet<Class>( Arrays.asList(WandOfFrost.class, Elemental.FrostElemental.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Frost.class, Chill.class))),\n\t\tACIDIC ( new HashSet<Class>( Arrays.asList(Corrosion.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Ooze.class))),\n\t\tELECTRIC ( new HashSet<Class>( Arrays.asList(WandOfLightning.class, Shocking.class, Potential.class, Electricity.class, ShockingDart.class, Elemental.ShockElemental.class )),\n\t\t\t\tnew HashSet<Class>()),\n\t\tLARGE,\n\t\tIMMOVABLE;\n\t\t\n\t\tprivate HashSet<Class> resistances;\n\t\tprivate HashSet<Class> immunities;\n\t\t\n\t\tProperty(){\n\t\t\tthis(new HashSet<Class>(), new HashSet<Class>());\n\t\t}\n\t\t\n\t\tProperty( HashSet<Class> resistances, HashSet<Class> immunities){\n\t\t\tthis.resistances = resistances;\n\t\t\tthis.immunities = immunities;\n\t\t}\n\t\t\n\t\tpublic HashSet<Class> resistances(){\n\t\t\treturn new HashSet<>(resistances);\n\t\t}\n\t\t\n\t\tpublic HashSet<Class> immunities(){\n\t\t\treturn new HashSet<>(immunities);\n\t\t}\n\n\t}\n\n\tpublic static boolean hasProp( Char ch, Property p){\n\t\treturn (ch != null && ch.properties().contains(p));\n\t}\n\n\tpublic void heal(int amount) {\n\t\tamount = Math.min( amount, this.HT - this.HP );\n\t\tif (amount > 0 && this.isAlive()) {\n\t\t\tthis.HP += amount;\n\t\t\tthis.sprite.emitter().start( Speck.factory( Speck.HEALING ), 0.4f, 1 );\n\t\t\tthis.sprite.showStatus( CharSprite.POSITIVE, Integer.toString( amount ) );\n\t\t}\n\t}\n}" }, { "identifier": "Blizzard", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/blobs/Blizzard.java", "snippet": "public class Blizzard extends Blob {\n\t\n\t@Override\n\tprotected void evolve() {\n\t\tsuper.evolve();\n\t\t\n\t\tint cell;\n\t\t\n\t\tFire fire = (Fire)Dungeon.level.blobs.get( Fire.class );\n\t\tFreezing freeze = (Freezing)Dungeon.level.blobs.get( Freezing.class );\n\t\t\n\t\tInferno inf = (Inferno)Dungeon.level.blobs.get( Inferno.class );\n\t\t\n\t\tfor (int i = area.left; i < area.right; i++) {\n\t\t\tfor (int j = area.top; j < area.bottom; j++) {\n\t\t\t\tcell = i + j * Dungeon.level.width();\n\t\t\t\tif (cur[cell] > 0) {\n\t\t\t\t\t\n\t\t\t\t\tif (fire != null) fire.clear(cell);\n\t\t\t\t\tif (freeze != null) freeze.clear(cell);\n\t\t\t\t\t\n\t\t\t\t\tif (inf != null && inf.volume > 0 && inf.cur[cell] > 0){\n\t\t\t\t\t\tinf.clear(cell);\n\t\t\t\t\t\toff[cell] = cur[cell] = 0;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tFreezing.freeze(cell);\n\t\t\t\t\tFreezing.freeze(cell);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void use( BlobEmitter emitter ) {\n\t\tsuper.use( emitter );\n\t\temitter.pour( Speck.factory( Speck.BLIZZARD, true ), 0.4f );\n\t}\n\t\n\t@Override\n\tpublic String tileDesc() {\n\t\treturn Messages.get(this, \"desc\");\n\t}\n\t\n\t\n}" }, { "identifier": "Blob", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/blobs/Blob.java", "snippet": "public class Blob extends Actor {\n\n\t{\n\t\tactPriority = BLOB_PRIO;\n\t}\n\t\n\tpublic int volume = 0;\n\t\n\tpublic int[] cur;\n\tprotected int[] off;\n\t\n\tpublic BlobEmitter emitter;\n\n\tpublic Rect area = new Rect();\n\t\n\tpublic boolean alwaysVisible = false;\n\n\tprivate static final String CUR\t\t= \"cur\";\n\tprivate static final String START\t= \"start\";\n\tprivate static final String LENGTH\t= \"length\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tsuper.storeInBundle( bundle );\n\t\t\n\t\tif (volume > 0) {\n\t\t\n\t\t\tint start;\n\t\t\tfor (start=0; start < Dungeon.level.length(); start++) {\n\t\t\t\tif (cur[start] > 0) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tint end;\n\t\t\tfor (end=Dungeon.level.length()-1; end > start; end--) {\n\t\t\t\tif (cur[end] > 0) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tbundle.put( START, start );\n\t\t\tbundle.put( LENGTH, cur.length );\n\t\t\tbundle.put( CUR, trim( start, end + 1 ) );\n\t\t\t\n\t\t}\n\t}\n\t\n\tprivate int[] trim( int start, int end ) {\n\t\tint len = end - start;\n\t\tint[] copy = new int[len];\n\t\tSystem.arraycopy( cur, start, copy, 0, len );\n\t\treturn copy;\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.restoreFromBundle( bundle );\n\n\t\tif (bundle.contains( CUR )) {\n\n\t\t\tcur = new int[bundle.getInt(LENGTH)];\n\t\t\toff = new int[cur.length];\n\n\t\t\tint[] data = bundle.getIntArray(CUR);\n\t\t\tint start = bundle.getInt(START);\n\t\t\tfor (int i = 0; i < data.length; i++) {\n\t\t\t\tcur[i + start] = data[i];\n\t\t\t\tvolume += data[i];\n\t\t\t}\n\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic boolean act() {\n\t\t\n\t\tspend( TICK );\n\t\t\n\t\tif (volume > 0) {\n\n\t\t\tif (area.isEmpty())\n\t\t\t\tsetupArea();\n\n\t\t\tvolume = 0;\n\n\t\t\tevolve();\n\t\t\tint[] tmp = off;\n\t\t\toff = cur;\n\t\t\tcur = tmp;\n\t\t\t\n\t\t} else {\n\t\t\tif (!area.isEmpty()) {\n\t\t\t\tarea.setEmpty();\n\t\t\t\t//clear any values remaining in off\n\t\t\t\tSystem.arraycopy(cur, 0, off, 0, cur.length);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\n\tpublic void setupArea(){\n\t\tfor (int cell=0; cell < cur.length; cell++) {\n\t\t\tif (cur[cell] != 0){\n\t\t\t\tarea.union(cell%Dungeon.level.width(), cell/Dungeon.level.width());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void use( BlobEmitter emitter ) {\n\t\tthis.emitter = emitter;\n\t}\n\t\n\tprotected void evolve() {\n\t\t\n\t\tboolean[] blocking = Dungeon.level.solid;\n\t\tint cell;\n\t\tfor (int i=area.top-1; i <= area.bottom; i++) {\n\t\t\tfor (int j = area.left-1; j <= area.right; j++) {\n\t\t\t\tcell = j + i*Dungeon.level.width();\n\t\t\t\tif (Dungeon.level.insideMap(cell)) {\n\t\t\t\t\tif (!blocking[cell]) {\n\n\t\t\t\t\t\tint count = 1;\n\t\t\t\t\t\tint sum = cur[cell];\n\n\t\t\t\t\t\tif (j > area.left && !blocking[cell-1]) {\n\t\t\t\t\t\t\tsum += cur[cell-1];\n\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (j < area.right && !blocking[cell+1]) {\n\t\t\t\t\t\t\tsum += cur[cell+1];\n\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (i > area.top && !blocking[cell-Dungeon.level.width()]) {\n\t\t\t\t\t\t\tsum += cur[cell-Dungeon.level.width()];\n\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (i < area.bottom && !blocking[cell+Dungeon.level.width()]) {\n\t\t\t\t\t\t\tsum += cur[cell+Dungeon.level.width()];\n\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tint value = sum >= count ? (sum / count) - 1 : 0;\n\t\t\t\t\t\toff[cell] = value;\n\n\t\t\t\t\t\tif (value > 0){\n\t\t\t\t\t\t\tif (i < area.top)\n\t\t\t\t\t\t\t\tarea.top = i;\n\t\t\t\t\t\t\telse if (i >= area.bottom)\n\t\t\t\t\t\t\t\tarea.bottom = i+1;\n\t\t\t\t\t\t\tif (j < area.left)\n\t\t\t\t\t\t\t\tarea.left = j;\n\t\t\t\t\t\t\telse if (j >= area.right)\n\t\t\t\t\t\t\t\tarea.right = j+1;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvolume += value;\n\t\t\t\t\t} else {\n\t\t\t\t\t\toff[cell] = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void seed( Level level, int cell, int amount ) {\n\t\tif (cur == null) cur = new int[level.length()];\n\t\tif (off == null) off = new int[cur.length];\n\n\t\tcur[cell] += amount;\n\t\tvolume += amount;\n\n\t\tarea.union(cell%level.width(), cell/level.width());\n\t}\n\t\n\tpublic void clear( int cell ) {\n\t\tif (volume == 0) return;\n\t\tvolume -= cur[cell];\n\t\tcur[cell] = 0;\n\t}\n\n\tpublic void fullyClear(){\n\t\tvolume = 0;\n\t\tarea.setEmpty();\n\t\tcur = new int[Dungeon.level.length()];\n\t\toff = new int[Dungeon.level.length()];\n\t}\n\n\tpublic void onBuildFlagMaps( Level l ){\n\t\t//do nothing by default, only some blobs affect flags\n\t}\n\t\n\tpublic String tileDesc() {\n\t\treturn null;\n\t}\n\t\n\tpublic static<T extends Blob> T seed( int cell, int amount, Class<T> type ) {\n\t\treturn seed(cell, amount, type, Dungeon.level);\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static<T extends Blob> T seed( int cell, int amount, Class<T> type, Level level ) {\n\t\t\n\t\tT gas = (T)level.blobs.get( type );\n\t\t\n\t\tif (gas == null) {\n\t\t\tgas = Reflection.newInstance(type);\n\t\t\t//this ensures that gasses do not get an 'extra turn' if they are added by a mob or buff\n\t\t\tif (Actor.curActorPriority() < gas.actPriority) {\n\t\t\t\tgas.spend(1f);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (gas != null){\n\t\t\tlevel.blobs.put( type, gas );\n\t\t\tgas.seed( level, cell, amount );\n\t\t}\n\t\t\n\t\treturn gas;\n\t}\n\n\tpublic static int volumeAt( int cell, Class<? extends Blob> type){\n\t\tBlob gas = Dungeon.level.blobs.get( type );\n\t\tif (gas == null || gas.volume == 0) {\n\t\t\treturn 0;\n\t\t} else {\n\t\t\treturn gas.cur[cell];\n\t\t}\n\t}\n}" }, { "identifier": "Fire", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/blobs/Fire.java", "snippet": "public class Fire extends Blob {\n\n\t@Override\n\tprotected void evolve() {\n\n\t\tboolean[] flamable = Dungeon.level.flamable;\n\t\tint cell;\n\t\tint fire;\n\t\t\n\t\tFreezing freeze = (Freezing)Dungeon.level.blobs.get( Freezing.class );\n\n\t\tboolean observe = false;\n\n\t\tfor (int i = area.left-1; i <= area.right; i++) {\n\t\t\tfor (int j = area.top-1; j <= area.bottom; j++) {\n\t\t\t\tcell = i + j*Dungeon.level.width();\n\t\t\t\tif (cur[cell] > 0) {\n\t\t\t\t\t\n\t\t\t\t\tif (freeze != null && freeze.volume > 0 && freeze.cur[cell] > 0){\n\t\t\t\t\t\tfreeze.clear(cell);\n\t\t\t\t\t\toff[cell] = cur[cell] = 0;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tburn( cell );\n\n\t\t\t\t\tfire = cur[cell] - 1;\n\t\t\t\t\tif (fire <= 0 && flamable[cell]) {\n\n\t\t\t\t\t\tDungeon.level.destroy( cell );\n\n\t\t\t\t\t\tobserve = true;\n\t\t\t\t\t\tGameScene.updateMap( cell );\n\n\t\t\t\t\t}\n\n\t\t\t\t} else if (freeze == null || freeze.volume <= 0 || freeze.cur[cell] <= 0) {\n\n\t\t\t\t\tif (flamable[cell]\n\t\t\t\t\t\t\t&& (cur[cell-1] > 0\n\t\t\t\t\t\t\t|| cur[cell+1] > 0\n\t\t\t\t\t\t\t|| cur[cell-Dungeon.level.width()] > 0\n\t\t\t\t\t\t\t|| cur[cell+Dungeon.level.width()] > 0)) {\n\t\t\t\t\t\tfire = 4;\n\t\t\t\t\t\tburn( cell );\n\t\t\t\t\t\tarea.union(i, j);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfire = 0;\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tfire = 0;\n\t\t\t\t}\n\n\t\t\t\tvolume += (off[cell] = fire);\n\t\t\t}\n\t\t}\n\n\t\tif (observe) {\n\t\t\tDungeon.observe();\n\t\t}\n\t}\n\t\n\tpublic static void burn( int pos ) {\n\t\tChar ch = Actor.findChar( pos );\n\t\tif (ch != null && !ch.isImmune(Fire.class)) {\n\t\t\tBuff.affect( ch, Burning.class ).reignite( ch );\n\t\t}\n\t\t\n\t\tHeap heap = Dungeon.level.heaps.get( pos );\n\t\tif (heap != null) {\n\t\t\theap.burn();\n\t\t}\n\n\t\tPlant plant = Dungeon.level.plants.get( pos );\n\t\tif (plant != null){\n\t\t\tplant.wither();\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void use( BlobEmitter emitter ) {\n\t\tsuper.use( emitter );\n\t\temitter.pour( FlameParticle.FACTORY, 0.03f );\n\t}\n\t\n\t@Override\n\tpublic String tileDesc() {\n\t\treturn Messages.get(this, \"desc\");\n\t}\n}" }, { "identifier": "Freezing", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/blobs/Freezing.java", "snippet": "public class Freezing extends Blob {\n\t\n\t@Override\n\tprotected void evolve() {\n\t\t\n\t\tint cell;\n\t\t\n\t\tFire fire = (Fire)Dungeon.level.blobs.get( Fire.class );\n\t\t\n\t\tfor (int i = area.left-1; i <= area.right; i++) {\n\t\t\tfor (int j = area.top-1; j <= area.bottom; j++) {\n\t\t\t\tcell = i + j*Dungeon.level.width();\n\t\t\t\tif (cur[cell] > 0) {\n\t\t\t\t\t\n\t\t\t\t\tif (fire != null && fire.volume > 0 && fire.cur[cell] > 0){\n\t\t\t\t\t\tfire.clear(cell);\n\t\t\t\t\t\toff[cell] = cur[cell] = 0;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tFreezing.freeze(cell);\n\t\t\t\t\t\n\t\t\t\t\toff[cell] = cur[cell] - 1;\n\t\t\t\t\tvolume += off[cell];\n\t\t\t\t} else {\n\t\t\t\t\toff[cell] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void freeze( int cell ){\n\t\tChar ch = Actor.findChar( cell );\n\t\tif (ch != null && !ch.isImmune(Freezing.class)) {\n\t\t\tif (ch.buff(Frost.class) != null){\n\t\t\t\tBuff.affect(ch, Frost.class, 2f);\n\t\t\t} else {\n\t\t\t\tChill chill = ch.buff(Chill.class);\n\t\t\t\tfloat turnsToAdd = Dungeon.level.water[cell] ? 5f : 3f;\n\t\t\t\tif (chill != null){\n\t\t\t\t\tfloat chillToCap = Chill.DURATION - chill.cooldown();\n\t\t\t\t\tchillToCap /= ch.resist(Chill.class); //account for resistance to chill\n\t\t\t\t\tturnsToAdd = Math.min(turnsToAdd, chillToCap);\n\t\t\t\t}\n\t\t\t\tif (turnsToAdd > 0f) {\n\t\t\t\t\tBuff.affect(ch, Chill.class, turnsToAdd);\n\t\t\t\t}\n\t\t\t\tif (chill != null\n\t\t\t\t\t\t&& chill.cooldown() >= Chill.DURATION &&\n\t\t\t\t\t\t!ch.isImmune(Frost.class)){\n\t\t\t\t\tBuff.affect(ch, Frost.class, Frost.DURATION);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tHeap heap = Dungeon.level.heaps.get( cell );\n\t\tif (heap != null) heap.freeze();\n\t}\n\t\n\t@Override\n\tpublic void use( BlobEmitter emitter ) {\n\t\tsuper.use( emitter );\n\t\temitter.start( SnowParticle.FACTORY, 0.05f, 0 );\n\t}\n\t\n\t@Override\n\tpublic String tileDesc() {\n\t\treturn Messages.get(this, \"desc\");\n\t}\n\t\n\t//legacy functionality from before this was a proper blob. Returns true if this cell is visible\n\tpublic static boolean affect( int cell ) {\n\t\t\n\t\tChar ch = Actor.findChar( cell );\n\t\tif (ch != null) {\n\t\t\tif (Dungeon.level.water[ch.pos]){\n\t\t\t\tBuff.prolong(ch, Frost.class, Frost.DURATION * 3);\n\t\t\t} else {\n\t\t\t\tBuff.prolong(ch, Frost.class, Frost.DURATION);\n\t\t\t}\n\t\t}\n\n\t\tFire fire = (Fire) Dungeon.level.blobs.get(Fire.class);\n\t\tif (fire != null && fire.volume > 0) {\n\t\t\tfire.clear( cell );\n\t\t}\n\n\t\tMagicalFireRoom.EternalFire eternalFire = (MagicalFireRoom.EternalFire)Dungeon.level.blobs.get(MagicalFireRoom.EternalFire.class);\n\t\tif (eternalFire != null && eternalFire.volume > 0) {\n\t\t\teternalFire.clear( cell );\n\t\t}\n\t\t\n\t\tHeap heap = Dungeon.level.heaps.get( cell );\n\t\tif (heap != null) {\n\t\t\theap.freeze();\n\t\t}\n\t\t\n\t\tif (Dungeon.level.heroFOV[cell]) {\n\t\t\tCellEmitter.get( cell ).start( SnowParticle.FACTORY, 0.2f, 6 );\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n}" }, { "identifier": "Buff", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Buff.java", "snippet": "public class Buff extends Actor {\n\t\n\tpublic Char target;\n\n\t{\n\t\tactPriority = BUFF_PRIO; //low priority, towards the end of a turn\n\t}\n\n\t//determines how the buff is announced when it is shown.\n\tpublic enum buffType {POSITIVE, NEGATIVE, NEUTRAL}\n\tpublic buffType type = buffType.NEUTRAL;\n\t\n\t//whether or not the buff announces its name\n\tpublic boolean announced = false;\n\n\t//whether a buff should persist through revive effects for the hero\n\tpublic boolean revivePersists = false;\n\t\n\tprotected HashSet<Class> resistances = new HashSet<>();\n\t\n\tpublic HashSet<Class> resistances() {\n\t\treturn new HashSet<>(resistances);\n\t}\n\t\n\tprotected HashSet<Class> immunities = new HashSet<>();\n\t\n\tpublic HashSet<Class> immunities() {\n\t\treturn new HashSet<>(immunities);\n\t}\n\t\n\tpublic boolean attachTo( Char target ) {\n\n\t\tif (target.isImmune( getClass() )) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tthis.target = target;\n\n\t\tif (target.add( this )){\n\t\t\tif (target.sprite != null) fx( true );\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.target = null;\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic void detach() {\n\t\tif (target.remove( this ) && target.sprite != null) fx( false );\n\t}\n\t\n\t@Override\n\tpublic boolean act() {\n\t\tdiactivate();\n\t\treturn true;\n\t}\n\t\n\tpublic int icon() {\n\t\treturn BuffIndicator.NONE;\n\t}\n\n\t//some buffs may want to tint the base texture color of their icon\n\tpublic void tintIcon( Image icon ){\n\t\t//do nothing by default\n\t}\n\n\t//percent (0-1) to fade out out the buff icon, usually if buff is expiring\n\tpublic float iconFadePercent(){\n\t\treturn 0;\n\t}\n\n\t//text to display on large buff icons in the desktop UI\n\tpublic String iconTextDisplay(){\n\t\treturn \"\";\n\t}\n\n\t//visual effect usually attached to the sprite of the character the buff is attacked to\n\tpublic void fx(boolean on) {\n\t\t//do nothing by default\n\t}\n\n\tpublic String heroMessage(){\n\t\tString msg = Messages.get(this, \"heromsg\");\n\t\tif (msg.isEmpty()) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn msg;\n\t\t}\n\t}\n\n\tpublic String name() {\n\t\treturn Messages.get(this, \"name\");\n\t}\n\n\tpublic String desc(){\n\t\treturn Messages.get(this, \"desc\");\n\t}\n\n\t//to handle the common case of showing how many turns are remaining in a buff description.\n\tprotected String dispTurns(float input){\n\t\treturn Messages.decimalFormat(\"#.##\", input);\n\t}\n\n\t//buffs act after the hero, so it is often useful to use cooldown+1 when display buff time remaining\n\tpublic float visualcooldown(){\n\t\treturn cooldown()+1f;\n\t}\n\n\t//creates a fresh instance of the buff and attaches that, this allows duplication.\n\tpublic static<T extends Buff> T append( Char target, Class<T> buffClass ) {\n\t\tT buff = Reflection.newInstance(buffClass);\n\t\tbuff.attachTo( target );\n\t\treturn buff;\n\t}\n\n\tpublic static<T extends FlavourBuff> T append( Char target, Class<T> buffClass, float duration ) {\n\t\tT buff = append( target, buffClass );\n\t\tbuff.spend( duration * target.resist(buffClass) );\n\t\treturn buff;\n\t}\n\n\t//same as append, but prevents duplication.\n\tpublic static<T extends Buff> T affect( Char target, Class<T> buffClass ) {\n\t\tT buff = target.buff( buffClass );\n\t\tif (buff != null) {\n\t\t\treturn buff;\n\t\t} else {\n\t\t\treturn append( target, buffClass );\n\t\t}\n\t}\n\t\n\tpublic static<T extends FlavourBuff> T affect( Char target, Class<T> buffClass, float duration ) {\n\t\tT buff = affect( target, buffClass );\n\t\tbuff.spend( duration * target.resist(buffClass) );\n\t\treturn buff;\n\t}\n\n\t//postpones an already active buff, or creates & attaches a new buff and delays that.\n\tpublic static<T extends FlavourBuff> T prolong( Char target, Class<T> buffClass, float duration ) {\n\t\tT buff = affect( target, buffClass );\n\t\tbuff.postpone( duration * target.resist(buffClass) );\n\t\treturn buff;\n\t}\n\n\tpublic static<T extends CounterBuff> T count( Char target, Class<T> buffclass, float count ) {\n\t\tT buff = affect( target, buffclass );\n\t\tbuff.countUp( count );\n\t\treturn buff;\n\t}\n\t\n\tpublic static void detach( Char target, Class<? extends Buff> cl ) {\n\t\tfor ( Buff b : target.buffs( cl )){\n\t\t\tb.detach();\n\t\t}\n\t}\n}" }, { "identifier": "Burning", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Burning.java", "snippet": "public class Burning extends Buff implements Hero.Doom {\n\t\n\tprivate static final float DURATION = 8f;\n\t\n\tprivate float left;\n\t\n\t//for tracking burning of hero items\n\tprivate int burnIncrement = 0;\n\t\n\tprivate static final String LEFT\t= \"left\";\n\tprivate static final String BURN\t= \"burnIncrement\";\n\n\t{\n\t\ttype = buffType.NEGATIVE;\n\t\tannounced = true;\n\t}\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tsuper.storeInBundle( bundle );\n\t\tbundle.put( LEFT, left );\n\t\tbundle.put( BURN, burnIncrement );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tsuper.restoreFromBundle(bundle);\n\t\tleft = bundle.getFloat( LEFT );\n\t\tburnIncrement = bundle.getInt( BURN );\n\t}\n\n\t@Override\n\tpublic boolean attachTo(Char target) {\n\t\tBuff.detach( target, Chill.class);\n\n\t\treturn super.attachTo(target);\n\t}\n\n\t@Override\n\tpublic boolean act() {\n\t\t\n\t\tif (target.isAlive() && !target.isImmune(getClass())) {\n\t\t\t\n\t\t\tint damage = Random.NormalIntRange( 1, 3 + Dungeon.scalingDepth()/4 );\n\t\t\tBuff.detach( target, Chill.class);\n\n\t\t\tif (target instanceof Hero && target.buff(TimekeepersHourglass.timeStasis.class) == null) {\n\t\t\t\t\n\t\t\t\tHero hero = (Hero)target;\n\n\t\t\t\thero.damage( damage, this );\n\t\t\t\tburnIncrement++;\n\n\t\t\t\t//at 4+ turns, there is a (turns-3)/3 chance an item burns\n\t\t\t\tif (Random.Int(3) < (burnIncrement - 3)){\n\t\t\t\t\tburnIncrement = 0;\n\n\t\t\t\t\tArrayList<Item> burnable = new ArrayList<>();\n\t\t\t\t\t//does not reach inside of containers\n\t\t\t\t\tif (hero.buff(LostInventory.class) == null) {\n\t\t\t\t\t\tfor (Item i : hero.belongings.backpack.items) {\n\t\t\t\t\t\t\tif (!i.unique && (i instanceof Scroll || i instanceof MysteryMeat || i instanceof FrozenCarpaccio)) {\n\t\t\t\t\t\t\t\tburnable.add(i);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!burnable.isEmpty()){\n\t\t\t\t\t\tItem toBurn = Random.element(burnable).detach(hero.belongings.backpack);\n\t\t\t\t\t\tGLog.w( Messages.capitalize(Messages.get(this, \"burnsup\", toBurn.title())) );\n\t\t\t\t\t\tif (toBurn instanceof MysteryMeat || toBurn instanceof FrozenCarpaccio){\n\t\t\t\t\t\t\tChargrilledMeat steak = new ChargrilledMeat();\n\t\t\t\t\t\t\tif (!steak.collect( hero.belongings.backpack )) {\n\t\t\t\t\t\t\t\tDungeon.level.drop( steak, hero.pos ).sprite.drop();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tHeap.burnFX( hero.pos );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\ttarget.damage( damage, this );\n\t\t\t}\n\n\t\t\tif (target instanceof Thief && ((Thief) target).item != null) {\n\n\t\t\t\tItem item = ((Thief) target).item;\n\n\t\t\t\tif (!item.unique && item instanceof Scroll) {\n\t\t\t\t\ttarget.sprite.emitter().burst( ElmoParticle.FACTORY, 6 );\n\t\t\t\t\t((Thief)target).item = null;\n\t\t\t\t} else if (item instanceof MysteryMeat) {\n\t\t\t\t\ttarget.sprite.emitter().burst( ElmoParticle.FACTORY, 6 );\n\t\t\t\t\t((Thief)target).item = new ChargrilledMeat();\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tdetach();\n\t\t}\n\t\t\n\t\tif (Dungeon.level.flamable[target.pos] && Blob.volumeAt(target.pos, Fire.class) == 0) {\n\t\t\tGameScene.add( Blob.seed( target.pos, 4, Fire.class ) );\n\t\t}\n\t\t\n\t\tspend( TICK );\n\t\tleft -= TICK;\n\t\t\n\t\tif (left <= 0 ||\n\t\t\t(Dungeon.level.water[target.pos] && !target.flying)) {\n\t\t\t\n\t\t\tdetach();\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t\n\tpublic void reignite( Char ch ) {\n\t\treignite( ch, DURATION );\n\t}\n\t\n\tpublic void reignite( Char ch, float duration ) {\n\t\tif (ch.isImmune(Burning.class)){\n\t\t\t//TODO this only works for the hero, not others who can have brimstone+arcana effect\n\t\t\t// e.g. prismatic image, shadow clone\n\t\t\tif (ch instanceof Hero\n\t\t\t\t\t&& ((Hero) ch).belongings.armor() != null\n\t\t\t\t\t&& ((Hero) ch).belongings.armor().hasGlyph(Brimstone.class, ch)){\n\t\t\t\t//has a 2*boost/50% chance to generate 1 shield per turn, to a max of 4x boost\n\t\t\t\tfloat shieldChance = 2*(Armor.Glyph.genericProcChanceMultiplier(ch) - 1f);\n\t\t\t\tint shieldCap = Math.round(shieldChance*4f);\n\t\t\t\tif (shieldCap > 0 && Random.Float() < shieldChance){\n\t\t\t\t\tBarrier barrier = Buff.affect(ch, Barrier.class);\n\t\t\t\t\tif (barrier.shielding() < shieldCap){\n\t\t\t\t\t\tbarrier.incShield(1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tleft = duration;\n\t}\n\t\n\t@Override\n\tpublic int icon() {\n\t\treturn BuffIndicator.FIRE;\n\t}\n\n\t@Override\n\tpublic float iconFadePercent() {\n\t\treturn Math.max(0, (DURATION - left) / DURATION);\n\t}\n\n\t@Override\n\tpublic String iconTextDisplay() {\n\t\treturn Integer.toString((int)left);\n\t}\n\n\t@Override\n\tpublic void fx(boolean on) {\n\t\tif (on) target.sprite.add(CharSprite.State.BURNING);\n\t\telse target.sprite.remove(CharSprite.State.BURNING);\n\t}\n\n\t@Override\n\tpublic String desc() {\n\t\treturn Messages.get(this, \"desc\", dispTurns(left));\n\t}\n\n\t@Override\n\tpublic void onDeath() {\n\t\t\n\t\tBadges.validateDeathFromFire();\n\t\t\n\t\tDungeon.fail( this );\n\t\tGLog.n( Messages.get(this, \"ondeath\") );\n\t}\n}" }, { "identifier": "BlobEmitter", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/effects/BlobEmitter.java", "snippet": "public class BlobEmitter extends Emitter {\n\t\n\tprivate Blob blob;\n\t\n\tpublic BlobEmitter( Blob blob ) {\n\t\t\n\t\tsuper();\n\t\t\n\t\tthis.blob = blob;\n\t\tblob.use( this );\n\t}\n\n\tpublic RectF bound = new RectF(0, 0, 1, 1);\n\t\n\t@Override\n\tprotected void emit( int index ) {\n\t\t\n\t\tif (blob.volume <= 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (blob.area.isEmpty())\n\t\t\tblob.setupArea();\n\t\t\n\t\tint[] map = blob.cur;\n\t\tfloat size = DungeonTilemap.SIZE;\n\n\t\tint cell;\n\t\tfor (int i = blob.area.left; i < blob.area.right; i++) {\n\t\t\tfor (int j = blob.area.top; j < blob.area.bottom; j++) {\n\t\t\t\tcell = i + j*Dungeon.level.width();\n\t\t\t\tif (cell < Dungeon.level.heroFOV.length\n\t\t\t\t\t\t&& (Dungeon.level.heroFOV[cell] || blob.alwaysVisible)\n\t\t\t\t\t\t&& map[cell] > 0) {\n\t\t\t\t\tfloat x = (i + Random.Float(bound.left, bound.right)) * size;\n\t\t\t\t\tfloat y = (j + Random.Float(bound.top, bound.bottom)) * size;\n\t\t\t\t\tfactory.emit(this, index, x, y);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}" }, { "identifier": "ElmoParticle", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/effects/particles/ElmoParticle.java", "snippet": "public class ElmoParticle extends PixelParticle.Shrinking {\n\t\n\tpublic static final Emitter.Factory FACTORY = new Factory() {\n\t\t@Override\n\t\tpublic void emit( Emitter emitter, int index, float x, float y ) {\n\t\t\t((ElmoParticle)emitter.recycle( ElmoParticle.class )).reset( x, y );\n\t\t}\n\t\t@Override\n\t\tpublic boolean lightMode() {\n\t\t\treturn true;\n\t\t}\n\t};\n\t\n\tpublic ElmoParticle() {\n\t\tsuper();\n\t\t\n\t\tcolor( 0x22EE66 );\n\t\tlifespan = 0.6f;\n\t\t\n\t\tacc.set( 0, -80 );\n\t}\n\t\n\tpublic void reset( float x, float y ) {\n\t\trevive();\n\t\t\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\t\n\t\tleft = lifespan;\n\t\t\n\t\tsize = 4;\n\t\tspeed.set( 0 );\n\t}\n\t\n\t@Override\n\tpublic void update() {\n\t\tsuper.update();\n\t\tfloat p = left / lifespan;\n\t\tam = p > 0.8f ? (1 - p) * 5 : 1;\n\t}\n}" }, { "identifier": "Generator", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/Generator.java", "snippet": "public class Generator {\n\n\tpublic enum Category {\n\t\tWEAPON\t( 2, 2, MeleeWeapon.class),\n\t\tWEP_T1\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_T2\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_T3\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_T4\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_T5\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_AL_T3\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_AL_T4\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_AL_T5\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_AL_T6\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_AL_T7\t( 0, 0, MeleeWeapon.class),\n\n\t\tARMOR\t( 2, 1, Armor.class ),\n\t\t\n\t\tMISSILE ( 1, 2, MissileWeapon.class ),\n\t\tMIS_T1 ( 0, 0, MissileWeapon.class ),\n\t\tMIS_T2 ( 0, 0, MissileWeapon.class ),\n\t\tMIS_T3 ( 0, 0, MissileWeapon.class ),\n\t\tMIS_T4 ( 0, 0, MissileWeapon.class ),\n\t\tMIS_T5 ( 0, 0, MissileWeapon.class ),\n\t\t\n\t\tWAND\t( 1, 1, Wand.class ),\n\t\tSPELLBOOK\t( 0, 0, SpellBook.class ),\n\t\tRING\t( 1, 0, Ring.class ),\n\t\tARTIFACT( 0, 1, Artifact.class),\n\t\t\n\t\tFOOD\t( 0, 0, Food.class ),\n\t\t\n\t\tPOTION\t( 8, 8, Potion.class ),\n\t\tSEED\t( 1, 1, Plant.Seed.class ),\n\t\t\n\t\tSCROLL\t( 8, 8, Scroll.class ),\n\t\tSTONE ( 1, 1, Runestone.class),\n\t\t\n\t\tGOLD\t( 10, 10, Gold.class );\n\t\t\n\t\tpublic Class<?>[] classes;\n\n\t\t//some item types use a deck-based system, where the probs decrement as items are picked\n\t\t// until they are all 0, and then they reset. Those generator classes should define\n\t\t// defaultProbs. If defaultProbs is null then a deck system isn't used.\n\t\t//Artifacts in particular don't reset, no duplicates!\n\t\tpublic float[] probs;\n\t\tpublic float[] defaultProbs = null;\n\t\t//These variables are used as a part of the deck system, to ensure that drops are consistent\n\t\t// regardless of when they occur (either as part of seeded levelgen, or random item drops)\n\t\tpublic Long seed = null;\n\t\tpublic int dropped = 0;\n\n\t\t//game has two decks of 35 items for overall category probs\n\t\t//one deck has a ring and extra armor, the other has an artifact and extra thrown weapon\n\t\t//Note that pure random drops only happen as part of levelgen atm, so no seed is needed here\n\t\tpublic float firstProb;\n\t\tpublic float secondProb;\n\t\tpublic Class<? extends Item> superClass;\n\t\t\n\t\tprivate Category( float firstProb, float secondProb, Class<? extends Item> superClass ) {\n\t\t\tthis.firstProb = firstProb;\n\t\t\tthis.secondProb = secondProb;\n\t\t\tthis.superClass = superClass;\n\t\t}\n\t\t\n\t\tpublic static int order( Item item ) {\n\t\t\tfor (int i=0; i < values().length; i++) {\n\t\t\t\tif (values()[i].superClass.isInstance( item )) {\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//items without a category-defined order are sorted based on the spritesheet\n\t\t\treturn Short.MAX_VALUE+item.image();\n\t\t}\n\n\t\tstatic {\n\t\t\tGOLD.classes = new Class<?>[]{\n\t\t\t\t\tGold.class };\n\t\t\tGOLD.probs = new float[]{ 1 };\n\t\t\t\n\t\t\tPOTION.classes = new Class<?>[]{\n\t\t\t\t\tPotionOfStrength.class, //2 drop every chapter, see Dungeon.posNeeded()\n\t\t\t\t\tPotionOfHealing.class,\n\t\t\t\t\tPotionOfMindVision.class,\n\t\t\t\t\tPotionOfFrost.class,\n\t\t\t\t\tPotionOfLiquidFlame.class,\n\t\t\t\t\tPotionOfToxicGas.class,\n\t\t\t\t\tPotionOfHaste.class,\n\t\t\t\t\tPotionOfInvisibility.class,\n\t\t\t\t\tPotionOfLevitation.class,\n\t\t\t\t\tPotionOfParalyticGas.class,\n\t\t\t\t\tPotionOfPurity.class,\n\t\t\t\t\tPotionOfExperience.class};\n\t\t\tPOTION.defaultProbs = new float[]{ 0, 6, 4, 3, 3, 3, 2, 2, 2, 2, 2, 1 };\n\t\t\tPOTION.probs = POTION.defaultProbs.clone();\n\t\t\t\n\t\t\tSEED.classes = new Class<?>[]{\n\t\t\t\t\tRotberry.Seed.class, //quest item\n\t\t\t\t\tSungrass.Seed.class,\n\t\t\t\t\tFadeleaf.Seed.class,\n\t\t\t\t\tIcecap.Seed.class,\n\t\t\t\t\tFirebloom.Seed.class,\n\t\t\t\t\tSorrowmoss.Seed.class,\n\t\t\t\t\tSwiftthistle.Seed.class,\n\t\t\t\t\tBlindweed.Seed.class,\n\t\t\t\t\tStormvine.Seed.class,\n\t\t\t\t\tEarthroot.Seed.class,\n\t\t\t\t\tMageroyal.Seed.class,\n\t\t\t\t\tStarflower.Seed.class};\n\t\t\tSEED.defaultProbs = new float[]{ 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 2 };\n\t\t\tSEED.probs = SEED.defaultProbs.clone();\n\t\t\t\n\t\t\tSCROLL.classes = new Class<?>[]{\n\t\t\t\t\tScrollOfUpgrade.class, //3 drop every chapter, see Dungeon.souNeeded()\n\t\t\t\t\tScrollOfIdentify.class,\n\t\t\t\t\tScrollOfRemoveCurse.class,\n\t\t\t\t\tScrollOfMirrorImage.class,\n\t\t\t\t\tScrollOfRecharging.class,\n\t\t\t\t\tScrollOfTeleportation.class,\n\t\t\t\t\tScrollOfLullaby.class,\n\t\t\t\t\tScrollOfMagicMapping.class,\n\t\t\t\t\tScrollOfRage.class,\n\t\t\t\t\tScrollOfRetribution.class,\n\t\t\t\t\tScrollOfTerror.class,\n\t\t\t\t\tScrollOfTransmutation.class\n\t\t\t};\n\t\t\tSCROLL.defaultProbs = new float[]{ 0, 6, 4, 3, 3, 3, 2, 2, 2, 2, 2, 1 };\n\t\t\tSCROLL.probs = SCROLL.defaultProbs.clone();\n\t\t\t\n\t\t\tSTONE.classes = new Class<?>[]{\n\t\t\t\t\tStoneOfEnchantment.class, //1 is guaranteed to drop on floors 6-19\n\t\t\t\t\tStoneOfIntuition.class, //1 additional stone is also dropped on floors 1-3\n\t\t\t\t\tStoneOfDisarming.class,\n\t\t\t\t\tStoneOfFlock.class,\n\t\t\t\t\tStoneOfShock.class,\n\t\t\t\t\tStoneOfBlink.class,\n\t\t\t\t\tStoneOfDeepSleep.class,\n\t\t\t\t\tStoneOfClairvoyance.class,\n\t\t\t\t\tStoneOfAggression.class,\n\t\t\t\t\tStoneOfBlast.class,\n\t\t\t\t\tStoneOfFear.class,\n\t\t\t\t\tStoneOfAugmentation.class //1 is sold in each shop\n\t\t\t};\n\t\t\tSTONE.defaultProbs = new float[]{ 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0 };\n\t\t\tSTONE.probs = STONE.defaultProbs.clone();\n\n\t\t\tWAND.classes = new Class<?>[]{\n\t\t\t\t\tWandOfMagicMissile.class,\n\t\t\t\t\tWandOfLightning.class,\n\t\t\t\t\tWandOfDisintegration.class,\n\t\t\t\t\tWandOfFireblast.class,\n\t\t\t\t\tWandOfCorrosion.class,\n\t\t\t\t\tWandOfBlastWave.class,\n\t\t\t\t\tWandOfLivingEarth.class,\n\t\t\t\t\tWandOfFrost.class,\n\t\t\t\t\tWandOfPrismaticLight.class,\n\t\t\t\t\tWandOfWarding.class,\n\t\t\t\t\tWandOfTransfusion.class,\n\t\t\t\t\tWandOfCorruption.class,\n\t\t\t\t\tWandOfRegrowth.class };\n\t\t\tWAND.defaultProbs = new float[]{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };\n\t\t\tWAND.probs = WAND.defaultProbs.clone();\n\n\t\t\tSPELLBOOK.classes = new Class<?>[]{\n\t\t\t\t\tBookOfMagic.class,\n\t\t\t\t\tBookOfThunderBolt.class,\n\t\t\t\t\tBookOfDisintegration.class,\n\t\t\t\t\tBookOfFire.class,\n\t\t\t\t\tBookOfCorrosion.class,\n\t\t\t\t\tBookOfBlast.class,\n\t\t\t\t\tBookOfEarth.class,\n\t\t\t\t\tBookOfFrost.class,\n\t\t\t\t\tBookOfLight.class,\n\t\t\t\t\tBookOfWarding.class,\n\t\t\t\t\tBookOfTransfusion.class,\n\t\t\t\t\tBookOfCorruption.class,\n\t\t\t\t\tBookOfRegrowth.class };\n\t\t\tSPELLBOOK.defaultProbs = new float[]{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };\n\t\t\tSPELLBOOK.probs = SPELLBOOK.defaultProbs.clone();\n\t\t\t\n\t\t\t//see generator.randomWeapon\n\t\t\tWEAPON.classes = new Class<?>[]{};\n\t\t\tWEAPON.probs = new float[]{};\n\t\t\t\n\t\t\tWEP_T1.classes = new Class<?>[]{\n\t\t\t\t\tWornShortsword.class,\n\t\t\t\t\tMagesStaff.class,\n\t\t\t\t\tDagger.class,\n\t\t\t\t\tGloves.class,\n\t\t\t\t\tRapier.class,\n\t\t\t\t\tWornKatana.class,\n\t\t\t\t\tAR_T1.class\n\t\t\t};\n\t\t\tWEP_T1.defaultProbs = new float[]{ 2, 0, 2, 2, 2, 2, 2 };\n\t\t\tWEP_T1.probs = WEP_T1.defaultProbs.clone();\n\t\t\t\n\t\t\tWEP_T2.classes = new Class<?>[]{\n\t\t\t\t\tShortsword.class,\n\t\t\t\t\tHandAxe.class,\n\t\t\t\t\tSpear.class,\n\t\t\t\t\tQuarterstaff.class,\n\t\t\t\t\tDirk.class,\n\t\t\t\t\tSickle.class,\n\t\t\t\t\tNunchaku.class,\n\t\t\t\t\tDualDagger.class,\n\t\t\t\t\tKnife.class,\n\t\t\t\t\tShortKatana.class,\n\t\t\t\t\tAR_T2.class,\n\t\t\t\t\tHG_T2.class,\n\t\t\t\t\tSMG_T2.class\n\t\t\t};\n\t\t\tWEP_T2.defaultProbs = new float[]{ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };\n\t\t\tWEP_T2.probs = WEP_T2.defaultProbs.clone();\n\t\t\t\n\t\t\tWEP_T3.classes = new Class<?>[]{\n\t\t\t\t\tSword.class,\n\t\t\t\t\tMace.class,\n\t\t\t\t\tScimitar.class,\n\t\t\t\t\tRoundShield.class,\n\t\t\t\t\tSai.class,\n\t\t\t\t\tBible.class,\n\t\t\t\t\tNormalKatana.class,\n\t\t\t\t\tWhip.class,\n\t\t\t\t\tAR_T3.class,\n\t\t\t\t\tMG_T3.class,\n\t\t\t\t\tSG_T3.class,\n\t\t\t\t\tSR_T3.class\n\t\t\t};\n\t\t\tWEP_T3.defaultProbs = new float[]{ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };\n\t\t\tWEP_T3.probs = WEP_T1.defaultProbs.clone();\n\t\t\t\n\t\t\tWEP_T4.classes = new Class<?>[]{\n\t\t\t\t\tLongsword.class,\n\t\t\t\t\tBattleAxe.class,\n\t\t\t\t\tFlail.class,\n\t\t\t\t\tRunicBlade.class,\n\t\t\t\t\tAssassinsBlade.class,\n\t\t\t\t\tCrossbow.class,\n\t\t\t\t\tKatana.class,\n\t\t\t\t\tLongKatana.class,\n\t\t\t\t\tAR_T4.class\n\t\t\t};\n\t\t\tWEP_T4.defaultProbs = new float[]{ 2, 2, 2, 2, 2, 2, 2, 2, 2 };\n\t\t\tWEP_T4.probs = WEP_T4.defaultProbs.clone();\n\t\t\t\n\t\t\tWEP_T5.classes = new Class<?>[]{\n\t\t\t\t\tGreatsword.class,\n\t\t\t\t\tWarHammer.class,\n\t\t\t\t\tGlaive.class,\n\t\t\t\t\tGreataxe.class,\n\t\t\t\t\tGreatshield.class,\n\t\t\t\t\tGauntlet.class,\n\t\t\t\t\tWarScythe.class,\n\t\t\t\t\tLargeSword.class,\n\t\t\t\t\tLargeKatana.class,\n\t\t\t\t\tAR_T5.class,\n\t\t\t\t\tHG_T5.class,\n\t\t\t\t\tSMG_T5.class,\n\t\t\t\t\tMG_T5.class,\n\t\t\t\t\tSG_T5.class,\n\t\t\t\t\tSR_T5.class\n\t\t\t};\n\t\t\tWEP_T5.defaultProbs = new float[]{ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };\n\t\t\tWEP_T5.probs = WEP_T5.defaultProbs.clone();\n\n\t\t\tWEP_AL_T3.classes = new Class<?>[]{\n\t\t\t\t\tSpearNShield.class\n\t\t\t};\n\t\t\tWEP_AL_T3.defaultProbs = new float[]{ 0 };\n\t\t\tWEP_AL_T3.probs = WEP_AL_T3.defaultProbs.clone();\n\n\t\t\tWEP_AL_T4.classes = new Class<?>[]{\n\t\t\t\t\tUnholyBible.class\n\t\t\t};\n\t\t\tWEP_AL_T4.defaultProbs = new float[]{ 0 };\n\t\t\tWEP_AL_T4.probs = WEP_AL_T4.defaultProbs.clone();\n\n\t\t\tWEP_AL_T5.classes = new Class<?>[]{\n\t\t\t\t\tTrueRunicBlade.class,\n\t\t\t\t\tAssassinsSpear.class,\n\t\t\t\t\tChainWhip.class,\n\t\t\t\t\tUnformedBlade.class\n\t\t\t};\n\t\t\tWEP_AL_T5.defaultProbs = new float[]{ 0, 0, 0, 0 };\n\t\t\tWEP_AL_T5.probs = WEP_AL_T5.defaultProbs.clone();\n\n\t\t\tWEP_AL_T6.classes = new Class<?>[]{\n\t\t\t\t\tAR_T6.class,\n\t\t\t\t\tSR_T6.class,\n\t\t\t\t\tHG_T6.class,\n\t\t\t\t\tChainFlail.class,\n\t\t\t\t\tForceGlove.class,\n\t\t\t\t\tLance.class,\n\t\t\t\t\tObsidianShield.class,\n\t\t\t\t\tDualGreatSword.class,\n\t\t\t\t\tHugeSword.class,\n\t\t\t\t\tMeisterHammer.class,\n\t\t\t\t\tBeamSaber.class,\n\t\t\t\t\tSharpKatana.class\n\t\t\t};\n\t\t\tWEP_AL_T6.defaultProbs = new float[]{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };\n\t\t\tWEP_AL_T6.probs = WEP_AL_T6.defaultProbs.clone();\n\n\t\t\tWEP_AL_T7.classes = new Class<?>[]{\n\t\t\t\t\tLanceNShield.class,\n\t\t\t\t\tTacticalShield.class,\n\t\t\t\t\tHolySword.class\n\t\t\t};\n\t\t\tWEP_AL_T7.defaultProbs = new float[]{ 0, 0, 0 };\n\t\t\tWEP_AL_T7.probs = WEP_AL_T7.defaultProbs.clone();\n\t\t\t\n\t\t\t//see Generator.randomArmor\n\t\t\tARMOR.classes = new Class<?>[]{\n\t\t\t\t\tClothArmor.class,\n\t\t\t\t\tLeatherArmor.class,\n\t\t\t\t\tMailArmor.class,\n\t\t\t\t\tScaleArmor.class,\n\t\t\t\t\tPlateArmor.class,\n\t\t\t\t\tWarriorArmor.class,\n\t\t\t\t\tMageArmor.class,\n\t\t\t\t\tRogueArmor.class,\n\t\t\t\t\tHuntressArmor.class,\n\t\t\t\t\tDuelistArmor.class\n\t\t\t};\n\t\t\tARMOR.probs = new float[]{ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };\n\t\t\t\n\t\t\t//see Generator.randomMissile\n\t\t\tMISSILE.classes = new Class<?>[]{};\n\t\t\tMISSILE.probs = new float[]{};\n\t\t\t\n\t\t\tMIS_T1.classes = new Class<?>[]{\n\t\t\t\t\tThrowingStone.class,\n\t\t\t\t\tThrowingKnife.class,\n\t\t\t\t\tThrowingSpike.class\n\t\t\t};\n\t\t\tMIS_T1.defaultProbs = new float[]{ 3, 3, 3 };\n\t\t\tMIS_T1.probs = MIS_T1.defaultProbs.clone();\n\t\t\t\n\t\t\tMIS_T2.classes = new Class<?>[]{\n\t\t\t\t\tFishingSpear.class,\n\t\t\t\t\tThrowingClub.class,\n\t\t\t\t\tShuriken.class\n\t\t\t};\n\t\t\tMIS_T2.defaultProbs = new float[]{ 3, 3, 3 };\n\t\t\tMIS_T2.probs = MIS_T2.defaultProbs.clone();\n\t\t\t\n\t\t\tMIS_T3.classes = new Class<?>[]{\n\t\t\t\t\tThrowingSpear.class,\n\t\t\t\t\tKunai.class,\n\t\t\t\t\tBolas.class\n\t\t\t};\n\t\t\tMIS_T3.defaultProbs = new float[]{ 3, 3, 3 };\n\t\t\tMIS_T3.probs = MIS_T3.defaultProbs.clone();\n\t\t\t\n\t\t\tMIS_T4.classes = new Class<?>[]{\n\t\t\t\t\tJavelin.class,\n\t\t\t\t\tTomahawk.class,\n\t\t\t\t\tHeavyBoomerang.class\n\t\t\t};\n\t\t\tMIS_T4.defaultProbs = new float[]{ 3, 3, 3 };\n\t\t\tMIS_T4.probs = MIS_T4.defaultProbs.clone();\n\t\t\t\n\t\t\tMIS_T5.classes = new Class<?>[]{\n\t\t\t\t\tTrident.class,\n\t\t\t\t\tThrowingHammer.class,\n\t\t\t\t\tForceCube.class\n\t\t\t};\n\t\t\tMIS_T5.defaultProbs = new float[]{ 3, 3, 3 };\n\t\t\tMIS_T5.probs = MIS_T5.defaultProbs.clone();\n\t\t\t\n\t\t\tFOOD.classes = new Class<?>[]{\n\t\t\t\t\tFood.class,\n\t\t\t\t\tPasty.class,\n\t\t\t\t\tMysteryMeat.class };\n\t\t\tFOOD.defaultProbs = new float[]{ 4, 1, 0 };\n\t\t\tFOOD.probs = FOOD.defaultProbs.clone();\n\t\t\t\n\t\t\tRING.classes = new Class<?>[]{\n\t\t\t\t\tRingOfAccuracy.class,\n\t\t\t\t\tRingOfArcana.class,\n\t\t\t\t\tRingOfElements.class,\n\t\t\t\t\tRingOfEnergy.class,\n\t\t\t\t\tRingOfEvasion.class,\n\t\t\t\t\tRingOfForce.class,\n\t\t\t\t\tRingOfFuror.class,\n\t\t\t\t\tRingOfHaste.class,\n\t\t\t\t\tRingOfMight.class,\n\t\t\t\t\tRingOfSharpshooting.class,\n\t\t\t\t\tRingOfTenacity.class,\n\t\t\t\t\tRingOfWealth.class};\n\t\t\tRING.defaultProbs = new float[]{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };\n\t\t\tRING.probs = RING.defaultProbs.clone();\n\t\t\t\n\t\t\tARTIFACT.classes = new Class<?>[]{\n\t\t\t\t\tAlchemistsToolkit.class,\n\t\t\t\t\tChaliceOfBlood.class,\n\t\t\t\t\tCloakOfShadows.class,\n\t\t\t\t\tDriedRose.class,\n\t\t\t\t\tEtherealChains.class,\n\t\t\t\t\tHornOfPlenty.class,\n\t\t\t\t\tMasterThievesArmband.class,\n\t\t\t\t\tSandalsOfNature.class,\n\t\t\t\t\tTalismanOfForesight.class,\n\t\t\t\t\tTimekeepersHourglass.class,\n\t\t\t\t\tUnstableSpellbook.class\n\t\t\t};\n\t\t\tARTIFACT.defaultProbs = new float[]{ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 };\n\t\t\tARTIFACT.probs = ARTIFACT.defaultProbs.clone();\n\t\t}\n\t}\n\n\tprivate static final float[][] floorSetTierProbs = new float[][] {\n\t\t\t{0, 75, 20, 4, 1},\n\t\t\t{0, 25, 50, 20, 5},\n\t\t\t{0, 0, 40, 50, 10},\n\t\t\t{0, 0, 20, 40, 40},\n\t\t\t{0, 0, 0, 20, 80},\n\t\t\t{0, 0, 0, 0, 100}\n\t};\n\n\tprivate static boolean usingFirstDeck = false;\n\tprivate static HashMap<Category,Float> defaultCatProbs = new LinkedHashMap<>();\n\tprivate static HashMap<Category,Float> categoryProbs = new LinkedHashMap<>();\n\n\tpublic static void fullReset() {\n\t\tusingFirstDeck = Random.Int(2) == 0;\n\t\tgeneralReset();\n\t\tfor (Category cat : Category.values()) {\n\t\t\treset(cat);\n\t\t\tif (cat.defaultProbs != null) {\n\t\t\t\tcat.seed = Random.Long();\n\t\t\t\tcat.dropped = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void generalReset(){\n\t\tfor (Category cat : Category.values()) {\n\t\t\tcategoryProbs.put( cat, usingFirstDeck ? cat.firstProb : cat.secondProb );\n\t\t\tdefaultCatProbs.put( cat, cat.firstProb + cat.secondProb );\n\t\t}\n\t}\n\n\tpublic static void reset(Category cat){\n\t\tif (cat.defaultProbs != null) cat.probs = cat.defaultProbs.clone();\n\t}\n\n\t//reverts changes to drop chances generates by this item\n\t//equivalent of shuffling the card back into the deck, does not preserve order!\n\tpublic static void undoDrop(Item item){\n\t\tfor (Category cat : Category.values()){\n\t\t\tif (item.getClass().isAssignableFrom(cat.superClass)){\n\t\t\t\tif (cat.defaultProbs == null) continue;\n\t\t\t\tfor (int i = 0; i < cat.classes.length; i++){\n\t\t\t\t\tif (item.getClass() == cat.classes[i]){\n\t\t\t\t\t\tcat.probs[i]++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static Item random() {\n\t\tCategory cat = Random.chances( categoryProbs );\n\t\tif (cat == null){\n\t\t\tusingFirstDeck = !usingFirstDeck;\n\t\t\tgeneralReset();\n\t\t\tcat = Random.chances( categoryProbs );\n\t\t}\n\t\tcategoryProbs.put( cat, categoryProbs.get( cat ) - 1);\n\n\t\tif (cat == Category.SEED) {\n\t\t\t//We specifically use defaults for seeds here because, unlike other item categories\n\t\t\t// their predominant source of drops is grass, not levelgen. This way the majority\n\t\t\t// of seed drops still use a deck, but the few that are spawned by levelgen are consistent\n\t\t\treturn randomUsingDefaults(cat);\n\t\t} else {\n\t\t\treturn random(cat);\n\t\t}\n\t}\n\n\tpublic static Item randomUsingDefaults(){\n\t\treturn randomUsingDefaults(Random.chances( defaultCatProbs ));\n\t}\n\t\n\tpublic static Item random( Category cat ) {\n\t\tswitch (cat) {\n\t\t\tcase ARMOR:\n\t\t\t\treturn randomArmor();\n\t\t\tcase WEAPON:\n\t\t\t\treturn randomWeapon();\n\t\t\tcase MISSILE:\n\t\t\t\treturn randomMissile();\n\t\t\tcase ARTIFACT:\n\t\t\t\tItem item = randomArtifact();\n\t\t\t\t//if we're out of artifacts, return a ring instead.\n\t\t\t\treturn item != null ? item : random(Category.RING);\n\t\t\tdefault:\n\t\t\t\tif (cat.defaultProbs != null && cat.seed != null){\n\t\t\t\t\tRandom.pushGenerator(cat.seed);\n\t\t\t\t\tfor (int i = 0; i < cat.dropped; i++) Random.Long();\n\t\t\t\t}\n\n\t\t\t\tint i = Random.chances(cat.probs);\n\t\t\t\tif (i == -1) {\n\t\t\t\t\treset(cat);\n\t\t\t\t\ti = Random.chances(cat.probs);\n\t\t\t\t}\n\t\t\t\tif (cat.defaultProbs != null) cat.probs[i]--;\n\n\t\t\t\tif (cat.defaultProbs != null && cat.seed != null){\n\t\t\t\t\tRandom.popGenerator();\n\t\t\t\t\tcat.dropped++;\n\t\t\t\t}\n\n\t\t\t\treturn ((Item) Reflection.newInstance(cat.classes[i])).random();\n\t\t}\n\t}\n\n\t//overrides any deck systems and always uses default probs\n\t// except for artifacts, which must always use a deck\n\tpublic static Item randomUsingDefaults( Category cat ){\n\t\tif (cat == Category.WEAPON){\n\t\t\treturn randomWeapon(true);\n\t\t} else if (cat == Category.MISSILE){\n\t\t\treturn randomMissile(true);\n\t\t} else if (cat.defaultProbs == null || cat == Category.ARTIFACT) {\n\t\t\treturn random(cat);\n\t\t} else {\n\t\t\treturn ((Item) Reflection.newInstance(cat.classes[Random.chances(cat.defaultProbs)])).random();\n\t\t}\n\t}\n\t\n\tpublic static Item random( Class<? extends Item> cl ) {\n\t\treturn Reflection.newInstance(cl).random();\n\t}\n\n\tpublic static Armor randomArmor(){\n\t\treturn randomArmor(Dungeon.depth / 5);\n\t}\n\t\n\tpublic static Armor randomArmor(int floorSet) {\n\n\t\tfloorSet = (int)GameMath.gate(0, floorSet, floorSetTierProbs.length-1);\n\t\t\n\t\tArmor a = (Armor)Reflection.newInstance(Category.ARMOR.classes[Random.chances(floorSetTierProbs[floorSet])]);\n\t\ta.random();\n\t\treturn a;\n\t}\n\n\tpublic static final Category[] wepTiers = new Category[]{\n\t\t\tCategory.WEP_T1,\n\t\t\tCategory.WEP_T2,\n\t\t\tCategory.WEP_T3,\n\t\t\tCategory.WEP_T4,\n\t\t\tCategory.WEP_T5\n\t};\n\n\tpublic static MeleeWeapon randomWeapon(){\n\t\treturn randomWeapon(Dungeon.depth / 5);\n\t}\n\n\tpublic static MeleeWeapon randomWeapon(int floorSet) {\n\t\treturn randomWeapon(floorSet, false);\n\t}\n\n\tpublic static MeleeWeapon randomWeapon(boolean useDefaults) {\n\t\treturn randomWeapon(Dungeon.depth / 5, useDefaults);\n\t}\n\t\n\tpublic static MeleeWeapon randomWeapon(int floorSet, boolean useDefaults) {\n\n\t\tfloorSet = (int)GameMath.gate(0, floorSet, floorSetTierProbs.length-1);\n\n\t\tMeleeWeapon w;\n\t\tif (useDefaults){\n\t\t\tw = (MeleeWeapon) randomUsingDefaults(wepTiers[Random.chances(floorSetTierProbs[floorSet])]);\n\t\t} else {\n\t\t\tw = (MeleeWeapon) random(wepTiers[Random.chances(floorSetTierProbs[floorSet])]);\n\t\t}\n\t\treturn w;\n\t}\n\t\n\tpublic static final Category[] misTiers = new Category[]{\n\t\t\tCategory.MIS_T1,\n\t\t\tCategory.MIS_T2,\n\t\t\tCategory.MIS_T3,\n\t\t\tCategory.MIS_T4,\n\t\t\tCategory.MIS_T5\n\t};\n\t\n\tpublic static MissileWeapon randomMissile(){\n\t\treturn randomMissile(Dungeon.depth / 5);\n\t}\n\n\tpublic static MissileWeapon randomMissile(int floorSet) {\n\t\treturn randomMissile(floorSet, false);\n\t}\n\n\tpublic static MissileWeapon randomMissile(boolean useDefaults) {\n\t\treturn randomMissile(Dungeon.depth / 5, useDefaults);\n\t}\n\n\tpublic static MissileWeapon randomMissile(int floorSet, boolean useDefaults) {\n\t\t\n\t\tfloorSet = (int)GameMath.gate(0, floorSet, floorSetTierProbs.length-1);\n\n\t\tMissileWeapon w;\n\t\tif (useDefaults){\n\t\t\tw = (MissileWeapon)randomUsingDefaults(misTiers[Random.chances(floorSetTierProbs[floorSet])]);\n\t\t} else {\n\t\t\tw = (MissileWeapon)random(misTiers[Random.chances(floorSetTierProbs[floorSet])]);\n\t\t}\n\t\treturn w;\n\t}\n\n\t//enforces uniqueness of artifacts throughout a run.\n\tpublic static Artifact randomArtifact() {\n\n\t\tCategory cat = Category.ARTIFACT;\n\n\t\tif (cat.defaultProbs != null && cat.seed != null){\n\t\t\tRandom.pushGenerator(cat.seed);\n\t\t\tfor (int i = 0; i < cat.dropped; i++) Random.Long();\n\t\t}\n\n\t\tint i = Random.chances( cat.probs );\n\n\t\tif (cat.defaultProbs != null && cat.seed != null){\n\t\t\tRandom.popGenerator();\n\t\t\tcat.dropped++;\n\t\t}\n\n\t\t//if no artifacts are left, return null\n\t\tif (i == -1){\n\t\t\treturn null;\n\t\t}\n\n\t\tcat.probs[i]--;\n\t\treturn (Artifact) Reflection.newInstance((Class<? extends Artifact>) cat.classes[i]).random();\n\n\t}\n\n\tpublic static boolean removeArtifact(Class<?extends Artifact> artifact) {\n\t\tCategory cat = Category.ARTIFACT;\n\t\tfor (int i = 0; i < cat.classes.length; i++){\n\t\t\tif (cat.classes[i].equals(artifact) && cat.probs[i] > 0) {\n\t\t\t\tcat.probs[i] = 0;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate static final String FIRST_DECK = \"first_deck\";\n\tprivate static final String GENERAL_PROBS = \"general_probs\";\n\tprivate static final String CATEGORY_PROBS = \"_probs\";\n\tprivate static final String CATEGORY_SEED = \"_seed\";\n\tprivate static final String CATEGORY_DROPPED = \"_dropped\";\n\n\tpublic static void storeInBundle(Bundle bundle) {\n\t\tbundle.put(FIRST_DECK, usingFirstDeck);\n\n\t\tFloat[] genProbs = categoryProbs.values().toArray(new Float[0]);\n\t\tfloat[] storeProbs = new float[genProbs.length];\n\t\tfor (int i = 0; i < storeProbs.length; i++){\n\t\t\tstoreProbs[i] = genProbs[i];\n\t\t}\n\t\tbundle.put( GENERAL_PROBS, storeProbs);\n\n\t\tfor (Category cat : Category.values()){\n\t\t\tif (cat.defaultProbs == null) continue;\n\n\t\t\tbundle.put(cat.name().toLowerCase() + CATEGORY_PROBS, cat.probs);\n\t\t\tif (cat.seed != null) {\n\t\t\t\tbundle.put(cat.name().toLowerCase() + CATEGORY_SEED, cat.seed);\n\t\t\t\tbundle.put(cat.name().toLowerCase() + CATEGORY_DROPPED, cat.dropped);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void restoreFromBundle(Bundle bundle) {\n\t\tfullReset();\n\n\t\tusingFirstDeck = bundle.getBoolean(FIRST_DECK);\n\n\t\tif (bundle.contains(GENERAL_PROBS)){\n\t\t\tfloat[] probs = bundle.getFloatArray(GENERAL_PROBS);\n\t\t\tfor (int i = 0; i < probs.length; i++){\n\t\t\t\tcategoryProbs.put(Category.values()[i], probs[i]);\n\t\t\t}\n\t\t}\n\n\t\tfor (Category cat : Category.values()){\n\t\t\tif (bundle.contains(cat.name().toLowerCase() + CATEGORY_PROBS)){\n\t\t\t\tfloat[] probs = bundle.getFloatArray(cat.name().toLowerCase() + CATEGORY_PROBS);\n\t\t\t\tif (cat.defaultProbs != null && probs.length == cat.defaultProbs.length){\n\t\t\t\t\tcat.probs = probs;\n\t\t\t\t}\n\t\t\t\tif (bundle.contains(cat.name().toLowerCase() + CATEGORY_SEED)){\n\t\t\t\t\tcat.seed = bundle.getLong(cat.name().toLowerCase() + CATEGORY_SEED);\n\t\t\t\t\tcat.dropped = bundle.getInt(cat.name().toLowerCase() + CATEGORY_DROPPED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n}" }, { "identifier": "Honeypot", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/Honeypot.java", "snippet": "public class Honeypot extends Item {\n\t\n\tpublic static final String AC_SHATTER\t= \"SHATTER\";\n\t\n\t{\n\t\timage = ItemSpriteSheet.HONEYPOT;\n\n\t\tdefaultAction = AC_THROW;\n\t\tusesTargeting = true;\n\n\t\tstackable = true;\n\t}\n\t\n\t@Override\n\tpublic ArrayList<String> actions( Hero hero ) {\n\t\tArrayList<String> actions = super.actions( hero );\n\t\tactions.add( AC_SHATTER );\n\t\treturn actions;\n\t}\n\t\n\t@Override\n\tpublic void execute( final Hero hero, String action ) {\n\n\t\tsuper.execute( hero, action );\n\n\t\tif (action.equals( AC_SHATTER )) {\n\t\t\t\n\t\t\thero.sprite.zap( hero.pos );\n\t\t\t\n\t\t\tdetach( hero.belongings.backpack );\n\n\t\t\tItem item = shatter( hero, hero.pos );\n\t\t\tif (!item.collect()){\n\t\t\t\tDungeon.level.drop(item, hero.pos);\n\t\t\t\tif (item instanceof ShatteredPot){\n\t\t\t\t\t((ShatteredPot) item).dropPot(hero, hero.pos);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\thero.next();\n\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected void onThrow( int cell ) {\n\t\tif (Dungeon.level.pit[cell]) {\n\t\t\tsuper.onThrow( cell );\n\t\t} else {\n\t\t\tDungeon.level.drop(shatter( null, cell ), cell);\n\t\t}\n\t}\n\t\n\tpublic Item shatter( Char owner, int pos ) {\n\t\t\n\t\tif (Dungeon.level.heroFOV[pos]) {\n\t\t\tSample.INSTANCE.play( Assets.Sounds.SHATTER );\n\t\t\tSplash.at( pos, 0xffd500, 5 );\n\t\t}\n\t\t\n\t\tint newPos = pos;\n\t\tif (Actor.findChar( pos ) != null) {\n\t\t\tArrayList<Integer> candidates = new ArrayList<>();\n\t\t\t\n\t\t\tfor (int n : PathFinder.NEIGHBOURS4) {\n\t\t\t\tint c = pos + n;\n\t\t\t\tif (!Dungeon.level.solid[c] && Actor.findChar( c ) == null) {\n\t\t\t\t\tcandidates.add( c );\n\t\t\t\t}\n\t\t\t}\n\t\n\t\t\tnewPos = candidates.size() > 0 ? Random.element( candidates ) : -1;\n\t\t}\n\t\t\n\t\tif (newPos != -1) {\n\t\t\tBee bee = new Bee();\n\t\t\tbee.spawn( Dungeon.scalingDepth() );\n\t\t\tbee.setPotInfo( pos, owner );\n\t\t\tbee.HP = bee.HT;\n\t\t\tbee.pos = newPos;\n\t\t\t\n\t\t\tGameScene.add( bee );\n\t\t\tif (newPos != pos) Actor.add( new Pushing( bee, pos, newPos ) );\n\n\t\t\tbee.sprite.alpha( 0 );\n\t\t\tbee.sprite.parent.add( new AlphaTweener( bee.sprite, 1, 0.15f ) );\n\t\t\t\n\t\t\tSample.INSTANCE.play( Assets.Sounds.BEE );\n\t\t\treturn new ShatteredPot();\n\t\t} else {\n\t\t\treturn this;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic boolean isUpgradable() {\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic boolean isIdentified() {\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic int value() {\n\t\treturn 30 * quantity;\n\t}\n\n\t//The bee's broken 'home', all this item does is let its bee know where it is, and who owns it (if anyone).\n\tpublic static class ShatteredPot extends Item {\n\n\t\t{\n\t\t\timage = ItemSpriteSheet.SHATTPOT;\n\t\t\tstackable = true;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean doPickUp(Hero hero, int pos) {\n\t\t\tif ( super.doPickUp(hero, pos) ){\n\t\t\t\tpickupPot( hero );\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void doDrop(Hero hero) {\n\t\t\tsuper.doDrop(hero);\n\t\t\tdropPot(hero, hero.pos);\n\t\t}\n\n\t\t@Override\n\t\tprotected void onThrow(int cell) {\n\t\t\tsuper.onThrow(cell);\n\t\t\tdropPot(curUser, cell);\n\t\t}\n\n\t\tpublic void pickupPot(Char holder){\n\t\t\tfor (Bee bee : findBees(holder.pos)){\n\t\t\t\tupdateBee(bee, -1, holder);\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic void dropPot( Char holder, int dropPos ){\n\t\t\tfor (Bee bee : findBees(holder)){\n\t\t\t\tupdateBee(bee, dropPos, null);\n\t\t\t}\n\t\t}\n\n\t\tpublic void movePot( int oldpos, int movePos){\n\t\t\tfor (Bee bee : findBees(oldpos)){\n\t\t\t\tupdateBee(bee, movePos, null);\n\t\t\t}\n\t\t}\n\n\t\tpublic void destroyPot( int potPos ){\n\t\t\tfor (Bee bee : findBees(potPos)){\n\t\t\t\tupdateBee(bee, -1, null);\n\t\t\t}\n\t\t}\n\n\t\tprivate void updateBee( Bee bee, int cell, Char holder ){\n\t\t\tif (bee != null && bee.alignment == Char.Alignment.ENEMY)\n\t\t\t\tbee.setPotInfo( cell, holder );\n\t\t}\n\t\t\n\t\t//returns up to quantity bees which match the current pot Pos\n\t\tprivate ArrayList<Bee> findBees( int potPos ){\n\t\t\tArrayList<Bee> bees = new ArrayList<>();\n\t\t\tfor (Char c : Actor.chars()){\n\t\t\t\tif (c instanceof Bee && ((Bee) c).potPos() == potPos){\n\t\t\t\t\tbees.add((Bee) c);\n\t\t\t\t\tif (bees.size() >= quantity) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn bees;\n\t\t}\n\t\t\n\t\t//returns up to quantity bees which match the current pot holder\n\t\tprivate ArrayList<Bee> findBees( Char potHolder ){\n\t\t\tArrayList<Bee> bees = new ArrayList<>();\n\t\t\tfor (Char c : Actor.chars()){\n\t\t\t\tif (c instanceof Bee && ((Bee) c).potHolderID() == potHolder.id()){\n\t\t\t\t\tbees.add((Bee) c);\n\t\t\t\t\tif (bees.size() >= quantity) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn bees;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean isUpgradable() {\n\t\t\treturn false;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean isIdentified() {\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic int value() {\n\t\t\treturn 5 * quantity;\n\t\t}\n\t}\n}" }, { "identifier": "Item", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/Item.java", "snippet": "public class Item implements Bundlable {\n\n\tprotected static final String TXT_TO_STRING_LVL\t\t= \"%s %+d\";\n\tprotected static final String TXT_TO_STRING_X\t\t= \"%s x%d\";\n\t\n\tprotected static final float TIME_TO_THROW\t\t= 1.0f;\n\tprotected static final float TIME_TO_PICK_UP\t= 1.0f;\n\tprotected static final float TIME_TO_DROP\t\t= 1.0f;\n\t\n\tpublic static final String AC_DROP\t\t= \"DROP\";\n\tpublic static final String AC_THROW\t\t= \"THROW\";\n\t\n\tprotected String defaultAction;\n\tpublic boolean usesTargeting;\n\n\t//TODO should these be private and accessed through methods?\n\tpublic int image = 0;\n\tpublic int icon = -1; //used as an identifier for items with randomized images\n\t\n\tpublic boolean stackable = false;\n\tprotected int quantity = 1;\n\tpublic boolean dropsDownHeap = false;\n\t\n\tprivate int level = 0;\n\n\tpublic boolean levelKnown = false;\n\t\n\tpublic boolean cursed;\n\tpublic boolean cursedKnown;\n\t\n\t// Unique items persist through revival\n\tpublic boolean unique = false;\n\n\t// These items are preserved even if the hero's inventory is lost via unblessed ankh\n\t// this is largely set by the resurrection window, items can override this to always be kept\n\tpublic boolean keptThoughLostInvent = false;\n\n\t// whether an item can be included in heroes remains\n\tpublic boolean bones = false;\n\t\n\tpublic static final Comparator<Item> itemComparator = new Comparator<Item>() {\n\t\t@Override\n\t\tpublic int compare( Item lhs, Item rhs ) {\n\t\t\treturn Generator.Category.order( lhs ) - Generator.Category.order( rhs );\n\t\t}\n\t};\n\t\n\tpublic ArrayList<String> actions( Hero hero ) {\n\t\tArrayList<String> actions = new ArrayList<>();\n\t\tactions.add( AC_DROP );\n\t\tactions.add( AC_THROW );\n\t\treturn actions;\n\t}\n\n\tpublic String actionName(String action, Hero hero){\n\t\treturn Messages.get(this, \"ac_\" + action);\n\t}\n\n\tpublic final boolean doPickUp( Hero hero ) {\n\t\treturn doPickUp( hero, hero.pos );\n\t}\n\n\tpublic boolean doPickUp(Hero hero, int pos) {\n\t\tif (collect( hero.belongings.backpack )) {\n\t\t\t\n\t\t\tGameScene.pickUp( this, pos );\n\t\t\tSample.INSTANCE.play( Assets.Sounds.ITEM );\n\t\t\thero.spendAndNext( TIME_TO_PICK_UP );\n\t\t\treturn true;\n\t\t\t\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic void doDrop( Hero hero ) {\n\t\thero.spendAndNext(TIME_TO_DROP);\n\t\tint pos = hero.pos;\n\t\tDungeon.level.drop(detachAll(hero.belongings.backpack), pos).sprite.drop(pos);\n\t}\n\n\t//resets an item's properties, to ensure consistency between runs\n\tpublic void reset(){\n\t\tkeptThoughLostInvent = false;\n\t}\n\n\tpublic boolean keptThroughLostInventory(){\n\t\treturn keptThoughLostInvent;\n\t}\n\n\tpublic void doThrow( Hero hero ) {\n\t\tGameScene.selectCell(thrower);\n\t}\n\t\n\tpublic void execute( Hero hero, String action ) {\n\n\t\tGameScene.cancel();\n\t\tcurUser = hero;\n\t\tcurItem = this;\n\t\t\n\t\tif (action.equals( AC_DROP )) {\n\t\t\t\n\t\t\tif (hero.belongings.backpack.contains(this) || isEquipped(hero)) {\n\t\t\t\tdoDrop(hero);\n\t\t\t}\n\t\t\t\n\t\t} else if (action.equals( AC_THROW )) {\n\t\t\t\n\t\t\tif (hero.belongings.backpack.contains(this) || isEquipped(hero)) {\n\t\t\t\tdoThrow(hero);\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\n\t//can be overridden if default action is variable\n\tpublic String defaultAction(){\n\t\treturn defaultAction;\n\t}\n\t\n\tpublic void execute( Hero hero ) {\n\t\tString action = defaultAction();\n\t\tif (action != null) {\n\t\t\texecute(hero, defaultAction());\n\t\t}\n\t}\n\t\n\tprotected void onThrow( int cell ) {\n\t\tHeap heap = Dungeon.level.drop( this, cell );\n\t\tif (!heap.isEmpty()) {\n\t\t\theap.sprite.drop( cell );\n\t\t}\n\t}\n\t\n\t//takes two items and merges them (if possible)\n\tpublic Item merge( Item other ){\n\t\tif (isSimilar( other )){\n\t\t\tquantity += other.quantity;\n\t\t\tother.quantity = 0;\n\t\t}\n\t\treturn this;\n\t}\n\t\n\tpublic boolean collect( Bag container ) {\n\n\t\tif (quantity <= 0){\n\t\t\treturn true;\n\t\t}\n\n\t\tArrayList<Item> items = container.items;\n\n\t\tif (items.contains( this )) {\n\t\t\treturn true;\n\t\t}\n\n\t\tfor (Item item:items) {\n\t\t\tif (item instanceof Bag && ((Bag)item).canHold( this )) {\n\t\t\t\tif (collect( (Bag)item )){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!container.canHold(this)){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif (stackable) {\n\t\t\tfor (Item item:items) {\n\t\t\t\tif (isSimilar( item )) {\n\t\t\t\t\titem.merge( this );\n\t\t\t\t\titem.updateQuickslot();\n\t\t\t\t\tif (Dungeon.hero != null && Dungeon.hero.isAlive()) {\n\t\t\t\t\t\tBadges.validateItemLevelAquired( this );\n\t\t\t\t\t\tTalent.onItemCollected(Dungeon.hero, item);\n\t\t\t\t\t\tif (isIdentified()) Catalog.setSeen(getClass());\n\t\t\t\t\t}\n\t\t\t\t\tif (TippedDart.lostDarts > 0){\n\t\t\t\t\t\tDart d = new Dart();\n\t\t\t\t\t\td.quantity(TippedDart.lostDarts);\n\t\t\t\t\t\tTippedDart.lostDarts = 0;\n\t\t\t\t\t\tif (!d.collect()){\n\t\t\t\t\t\t\t//have to handle this in an actor as we can't manipulate the heap during pickup\n\t\t\t\t\t\t\tActor.add(new Actor() {\n\t\t\t\t\t\t\t\t{ actPriority = VFX_PRIO; }\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tprotected boolean act() {\n\t\t\t\t\t\t\t\t\tDungeon.level.drop(d, Dungeon.hero.pos).sprite.drop();\n\t\t\t\t\t\t\t\t\tActor.remove(this);\n\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.hero != null && Dungeon.hero.isAlive()) {\n\t\t\tBadges.validateItemLevelAquired( this );\n\t\t\tTalent.onItemCollected( Dungeon.hero, this );\n\t\t\tif (isIdentified()) Catalog.setSeen(getClass());\n\t\t}\n\n\t\titems.add( this );\n\t\tDungeon.quickslot.replacePlaceholder(this);\n\t\tCollections.sort( items, itemComparator );\n\t\tupdateQuickslot();\n\t\treturn true;\n\n\t}\n\t\n\tpublic boolean collect() {\n\t\treturn collect( Dungeon.hero.belongings.backpack );\n\t}\n\t\n\t//returns a new item if the split was sucessful and there are now 2 items, otherwise null\n\tpublic Item split( int amount ){\n\t\tif (amount <= 0 || amount >= quantity()) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\t//pssh, who needs copy constructors?\n\t\t\tItem split = Reflection.newInstance(getClass());\n\t\t\t\n\t\t\tif (split == null){\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t\n\t\t\tBundle copy = new Bundle();\n\t\t\tthis.storeInBundle(copy);\n\t\t\tsplit.restoreFromBundle(copy);\n\t\t\tsplit.quantity(amount);\n\t\t\tquantity -= amount;\n\t\t\t\n\t\t\treturn split;\n\t\t}\n\t}\n\t\n\tpublic final Item detach( Bag container ) {\n\t\t\n\t\tif (quantity <= 0) {\n\t\t\t\n\t\t\treturn null;\n\t\t\t\n\t\t} else\n\t\tif (quantity == 1) {\n\n\t\t\tif (stackable){\n\t\t\t\tDungeon.quickslot.convertToPlaceholder(this);\n\t\t\t}\n\n\t\t\treturn detachAll( container );\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tItem detached = split(1);\n\t\t\tupdateQuickslot();\n\t\t\tif (detached != null) detached.onDetach( );\n\t\t\treturn detached;\n\t\t\t\n\t\t}\n\t}\n\t\n\tpublic final Item detachAll( Bag container ) {\n\t\tDungeon.quickslot.clearItem( this );\n\n\t\tfor (Item item : container.items) {\n\t\t\tif (item == this) {\n\t\t\t\tcontainer.items.remove(this);\n\t\t\t\titem.onDetach();\n\t\t\t\tcontainer.grabItems(); //try to put more items into the bag as it now has free space\n\t\t\t\tupdateQuickslot();\n\t\t\t\treturn this;\n\t\t\t} else if (item instanceof Bag) {\n\t\t\t\tBag bag = (Bag)item;\n\t\t\t\tif (bag.contains( this )) {\n\t\t\t\t\treturn detachAll( bag );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdateQuickslot();\n\t\treturn this;\n\t}\n\t\n\tpublic boolean isSimilar( Item item ) {\n\t\treturn level == item.level && getClass() == item.getClass();\n\t}\n\n\tprotected void onDetach(){}\n\n\t//returns the true level of the item, ignoring all modifiers aside from upgrades\n\tpublic final int trueLevel(){\n\t\treturn level;\n\t}\n\n\t//returns the persistant level of the item, only affected by modifiers which are persistent (e.g. curse infusion)\n\tpublic int level(){\n\t\treturn level;\n\t}\n\t\n\t//returns the level of the item, after it may have been modified by temporary boosts/reductions\n\t//note that not all item properties should care about buffs/debuffs! (e.g. str requirement)\n\tpublic int buffedLvl(){\n\t\t//only the hero can be affected by Degradation\n\t\tif (Dungeon.hero.buff( Degrade.class ) != null\n\t\t\t&& (isEquipped( Dungeon.hero ) || Dungeon.hero.belongings.contains( this ))) {\n\t\t\treturn Degrade.reduceLevel(level());\n\t\t} else {\n\t\t\treturn level();\n\t\t}\n\t}\n\n\tpublic void level( int value ){\n\t\tlevel = value;\n\n\t\tupdateQuickslot();\n\t}\n\t\n\tpublic Item upgrade() {\n\t\t\n\t\tthis.level++;\n\n\t\tupdateQuickslot();\n\t\t\n\t\treturn this;\n\t}\n\t\n\tfinal public Item upgrade( int n ) {\n\t\tfor (int i=0; i < n; i++) {\n\t\t\tupgrade();\n\t\t}\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic Item degrade() {\n\t\t\n\t\tthis.level--;\n\t\t\n\t\treturn this;\n\t}\n\t\n\tfinal public Item degrade( int n ) {\n\t\tfor (int i=0; i < n; i++) {\n\t\t\tdegrade();\n\t\t}\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic int visiblyUpgraded() {\n\t\treturn levelKnown ? level() : 0;\n\t}\n\n\tpublic int buffedVisiblyUpgraded() {\n\t\treturn levelKnown ? buffedLvl() : 0;\n\t}\n\t\n\tpublic boolean visiblyCursed() {\n\t\treturn cursed && cursedKnown;\n\t}\n\t\n\tpublic boolean isUpgradable() {\n\t\treturn true;\n\t}\n\t\n\tpublic boolean isIdentified() {\n\t\treturn levelKnown && cursedKnown;\n\t}\n\t\n\tpublic boolean isEquipped( Hero hero ) {\n\t\treturn false;\n\t}\n\n\tpublic final Item identify(){\n\t\treturn identify(true);\n\t}\n\n\tpublic Item identify( boolean byHero ) {\n\n\t\tif (byHero && Dungeon.hero != null && Dungeon.hero.isAlive()){\n\t\t\tCatalog.setSeen(getClass());\n\t\t\tif (!isIdentified()) Talent.onItemIdentified(Dungeon.hero, this);\n\t\t}\n\n\t\tlevelKnown = true;\n\t\tcursedKnown = true;\n\t\tItem.updateQuickslot();\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic void onHeroGainExp( float levelPercent, Hero hero ){\n\t\t//do nothing by default\n\t}\n\t\n\tpublic static void evoke( Hero hero ) {\n\t\thero.sprite.emitter().burst( Speck.factory( Speck.EVOKE ), 5 );\n\t}\n\n\tpublic String title() {\n\n\t\tString name = name();\n\n\t\tif (visiblyUpgraded() != 0)\n\t\t\tname = Messages.format( TXT_TO_STRING_LVL, name, visiblyUpgraded() );\n\n\t\tif (quantity > 1)\n\t\t\tname = Messages.format( TXT_TO_STRING_X, name, quantity );\n\n\t\treturn name;\n\n\t}\n\t\n\tpublic String name() {\n\t\treturn trueName();\n\t}\n\t\n\tpublic final String trueName() {\n\t\treturn Messages.get(this, \"name\");\n\t}\n\t\n\tpublic int image() {\n\t\treturn image;\n\t}\n\t\n\tpublic ItemSprite.Glowing glowing() {\n\t\treturn null;\n\t}\n\n\tpublic Emitter emitter() { return null; }\n\t\n\tpublic String info() {\n\t\treturn desc();\n\t}\n\t\n\tpublic String desc() {\n\t\treturn Messages.get(this, \"desc\");\n\t}\n\t\n\tpublic int quantity() {\n\t\treturn quantity;\n\t}\n\t\n\tpublic Item quantity( int value ) {\n\t\tquantity = value;\n\t\treturn this;\n\t}\n\n\t//item's value in gold coins\n\tpublic int value() {\n\t\treturn 0;\n\t}\n\n\t//item's value in energy crystals\n\tpublic int energyVal() {\n\t\treturn 0;\n\t}\n\t\n\tpublic Item virtual(){\n\t\tItem item = Reflection.newInstance(getClass());\n\t\tif (item == null) return null;\n\t\t\n\t\titem.quantity = 0;\n\t\titem.level = level;\n\t\treturn item;\n\t}\n\t\n\tpublic Item random() {\n\t\treturn this;\n\t}\n\t\n\tpublic String status() {\n\t\treturn quantity != 1 ? Integer.toString( quantity ) : null;\n\t}\n\n\tpublic static void updateQuickslot() {\n\t\tGameScene.updateItemDisplays = true;\n\t}\n\t\n\tprivate static final String QUANTITY\t\t= \"quantity\";\n\tprivate static final String LEVEL\t\t\t= \"level\";\n\tprivate static final String LEVEL_KNOWN\t\t= \"levelKnown\";\n\tprivate static final String CURSED\t\t\t= \"cursed\";\n\tprivate static final String CURSED_KNOWN\t= \"cursedKnown\";\n\tprivate static final String QUICKSLOT\t\t= \"quickslotpos\";\n\tprivate static final String KEPT_LOST = \"kept_lost\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tbundle.put( QUANTITY, quantity );\n\t\tbundle.put( LEVEL, level );\n\t\tbundle.put( LEVEL_KNOWN, levelKnown );\n\t\tbundle.put( CURSED, cursed );\n\t\tbundle.put( CURSED_KNOWN, cursedKnown );\n\t\tif (Dungeon.quickslot.contains(this)) {\n\t\t\tbundle.put( QUICKSLOT, Dungeon.quickslot.getSlot(this) );\n\t\t}\n\t\tbundle.put( KEPT_LOST, keptThoughLostInvent );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tquantity\t= bundle.getInt( QUANTITY );\n\t\tlevelKnown\t= bundle.getBoolean( LEVEL_KNOWN );\n\t\tcursedKnown\t= bundle.getBoolean( CURSED_KNOWN );\n\t\t\n\t\tint level = bundle.getInt( LEVEL );\n\t\tif (level > 0) {\n\t\t\tupgrade( level );\n\t\t} else if (level < 0) {\n\t\t\tdegrade( -level );\n\t\t}\n\t\t\n\t\tcursed\t= bundle.getBoolean( CURSED );\n\n\t\t//only want to populate slot on first load.\n\t\tif (Dungeon.hero == null) {\n\t\t\tif (bundle.contains(QUICKSLOT)) {\n\t\t\t\tDungeon.quickslot.setSlot(bundle.getInt(QUICKSLOT), this);\n\t\t\t}\n\t\t}\n\n\t\tkeptThoughLostInvent = bundle.getBoolean( KEPT_LOST );\n\t}\n\n\tpublic int targetingPos( Hero user, int dst ){\n\t\treturn throwPos( user, dst );\n\t}\n\n\tpublic int throwPos( Hero user, int dst){\n\t\treturn new Ballistica( user.pos, dst, Ballistica.PROJECTILE ).collisionPos;\n\t}\n\n\tpublic void throwSound(){\n\t\tSample.INSTANCE.play(Assets.Sounds.MISS, 0.6f, 0.6f, 1.5f);\n\t}\n\t\n\tpublic void cast( final Hero user, final int dst ) {\n\t\t\n\t\tfinal int cell = throwPos( user, dst );\n\t\tuser.sprite.zap( cell );\n\t\tuser.busy();\n\n\t\tthrowSound();\n\n\t\tChar enemy = Actor.findChar( cell );\n\t\tQuickSlotButton.target(enemy);\n\t\t\n\t\tfinal float delay = castDelay(user, dst);\n\n\t\tif (enemy != null) {\n\t\t\t((MissileSprite) user.sprite.parent.recycle(MissileSprite.class)).\n\t\t\t\t\treset(user.sprite,\n\t\t\t\t\t\t\tenemy.sprite,\n\t\t\t\t\t\t\tthis,\n\t\t\t\t\t\t\tnew Callback() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\t\tcurUser = user;\n\t\t\t\t\t\t\tItem i = Item.this.detach(user.belongings.backpack);\n\t\t\t\t\t\t\tif (i != null) i.onThrow(cell);\n\t\t\t\t\t\t\tif (curUser.hasTalent(Talent.IMPROVISED_PROJECTILES)\n\t\t\t\t\t\t\t\t\t&& !(Item.this instanceof MissileWeapon)\n\t\t\t\t\t\t\t\t\t&& curUser.buff(Talent.ImprovisedProjectileCooldown.class) == null){\n\t\t\t\t\t\t\t\tif (enemy != null && enemy.alignment != curUser.alignment){\n\t\t\t\t\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT);\n\t\t\t\t\t\t\t\t\tBuff.affect(enemy, Blindness.class, 1f + curUser.pointsInTalent(Talent.IMPROVISED_PROJECTILES));\n\t\t\t\t\t\t\t\t\tBuff.affect(curUser, Talent.ImprovisedProjectileCooldown.class, 50f);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (user.buff(Talent.LethalMomentumTracker.class) != null){\n\t\t\t\t\t\t\t\tuser.buff(Talent.LethalMomentumTracker.class).detach();\n\t\t\t\t\t\t\t\tuser.next();\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tuser.spendAndNext(delay);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t} else {\n\t\t\t((MissileSprite) user.sprite.parent.recycle(MissileSprite.class)).\n\t\t\t\t\treset(user.sprite,\n\t\t\t\t\t\t\tcell,\n\t\t\t\t\t\t\tthis,\n\t\t\t\t\t\t\tnew Callback() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\t\tcurUser = user;\n\t\t\t\t\t\t\tItem i = Item.this.detach(user.belongings.backpack);\n\t\t\t\t\t\t\tif (i != null) i.onThrow(cell);\n\t\t\t\t\t\t\tuser.spendAndNext(delay);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t}\n\t}\n\t\n\tpublic float castDelay( Char user, int dst ){\n\t\treturn TIME_TO_THROW;\n\t}\n\t\n\tprotected static Hero curUser = null;\n\tprotected static Item curItem = null;\n\tprotected static CellSelector.Listener thrower = new CellSelector.Listener() {\n\t\t@Override\n\t\tpublic void onSelect( Integer target ) {\n\t\t\tif (target != null) {\n\t\t\t\tcurItem.cast( curUser, target );\n\t\t\t}\n\t\t}\n\t\t@Override\n\t\tpublic String prompt() {\n\t\t\treturn Messages.get(Item.class, \"prompt\");\n\t\t}\n\t};\n}" }, { "identifier": "PotionOfFrost", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/potions/PotionOfFrost.java", "snippet": "public class PotionOfFrost extends Potion {\n\n\t{\n\t\ticon = ItemSpriteSheet.Icons.POTION_FROST;\n\t}\n\t\n\t@Override\n\tpublic void shatter( int cell ) {\n\t\t\n\t\tif (Dungeon.level.heroFOV[cell]) {\n\t\t\tidentify();\n\t\t\t\n\t\t\tsplash( cell );\n\t\t\tSample.INSTANCE.play( Assets.Sounds.SHATTER );\n\t\t}\n\t\t\n\t\tfor (int offset : PathFinder.NEIGHBOURS9){\n\t\t\tif (!Dungeon.level.solid[cell+offset]) {\n\t\t\t\t\n\t\t\t\tGameScene.add(Blob.seed(cell + offset, 10, Freezing.class));\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\t@Override\n\tpublic int value() {\n\t\treturn isKnown() ? 30 * quantity : super.value();\n\t}\n}" }, { "identifier": "Level", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/Level.java", "snippet": "public abstract class Level implements Bundlable {\n\t\n\tpublic static enum Feeling {\n\t\tNONE,\n\t\tCHASM,\n\t\tWATER,\n\t\tGRASS,\n\t\tDARK,\n\t\tLARGE,\n\t\tTRAPS,\n\t\tSECRETS\n\t}\n\n\tprotected int width;\n\tprotected int height;\n\tprotected int length;\n\t\n\tprotected static final float TIME_TO_RESPAWN\t= 50;\n\n\tpublic int version;\n\t\n\tpublic int[] map;\n\tpublic boolean[] visited;\n\tpublic boolean[] mapped;\n\tpublic boolean[] discoverable;\n\n\tpublic int viewDistance = Dungeon.isChallenged( Challenges.DARKNESS ) ? 2 : 8;\n\t\n\tpublic boolean[] heroFOV;\n\t\n\tpublic boolean[] passable;\n\tpublic boolean[] losBlocking;\n\tpublic boolean[] flamable;\n\tpublic boolean[] secret;\n\tpublic boolean[] solid;\n\tpublic boolean[] avoid;\n\tpublic boolean[] water;\n\tpublic boolean[] pit;\n\n\tpublic boolean[] openSpace;\n\t\n\tpublic Feeling feeling = Feeling.NONE;\n\t\n\tpublic int entrance;\n\tpublic int exit;\n\n\tpublic ArrayList<LevelTransition> transitions;\n\n\t//when a boss level has become locked.\n\tpublic boolean locked = false;\n\t\n\tpublic HashSet<Mob> mobs;\n\tpublic SparseArray<Heap> heaps;\n\tpublic HashMap<Class<? extends Blob>,Blob> blobs;\n\tpublic SparseArray<Plant> plants;\n\tpublic SparseArray<Trap> traps;\n\tpublic HashSet<CustomTilemap> customTiles;\n\tpublic HashSet<CustomTilemap> customWalls;\n\t\n\tprotected ArrayList<Item> itemsToSpawn = new ArrayList<>();\n\n\tprotected Group visuals;\n\tprotected Group wallVisuals;\n\t\n\tpublic int color1 = 0x004400;\n\tpublic int color2 = 0x88CC44;\n\n\tprivate static final String VERSION = \"version\";\n\tprivate static final String WIDTH = \"width\";\n\tprivate static final String HEIGHT = \"height\";\n\tprivate static final String MAP\t\t\t= \"map\";\n\tprivate static final String VISITED\t\t= \"visited\";\n\tprivate static final String MAPPED\t\t= \"mapped\";\n\tprivate static final String TRANSITIONS\t= \"transitions\";\n\tprivate static final String LOCKED = \"locked\";\n\tprivate static final String HEAPS\t\t= \"heaps\";\n\tprivate static final String PLANTS\t\t= \"plants\";\n\tprivate static final String TRAPS = \"traps\";\n\tprivate static final String CUSTOM_TILES= \"customTiles\";\n\tprivate static final String CUSTOM_WALLS= \"customWalls\";\n\tprivate static final String MOBS\t\t= \"mobs\";\n\tprivate static final String BLOBS\t\t= \"blobs\";\n\tprivate static final String FEELING\t\t= \"feeling\";\n\n\tpublic void create() {\n\n\t\tRandom.pushGenerator( Dungeon.seedCurDepth() );\n\n\t\tif (!Dungeon.bossLevel() && Dungeon.branch == 2) {\n\t\t\taddItemToSpawn(Generator.random(Generator.Category.FOOD));\n\t\t}\n\n\t\t//TODO maybe just make this part of RegularLevel?\n\t\tif (!Dungeon.bossLevel() && Dungeon.branch == 0) {\n\n\t\t\taddItemToSpawn(Generator.random(Generator.Category.FOOD));\n\n\t\t\tif (Dungeon.posNeeded()) {\n\t\t\t\tDungeon.LimitedDrops.STRENGTH_POTIONS.count++;\n\t\t\t\taddItemToSpawn( new PotionOfStrength() );\n\t\t\t}\n\t\t\tif (Dungeon.souNeeded()) {\n\t\t\t\tDungeon.LimitedDrops.UPGRADE_SCROLLS.count++;\n\t\t\t\t//every 2nd scroll of upgrade is removed with forbidden runes challenge on\n\t\t\t\t//TODO while this does significantly reduce this challenge's levelgen impact, it doesn't quite remove it\n\t\t\t\t//for 0 levelgen impact, we need to do something like give the player all SOU, but nerf them\n\t\t\t\t//or give a random scroll (from a separate RNG) instead of every 2nd SOU\n\t\t\t\tif (!Dungeon.isChallenged(Challenges.NO_SCROLLS) || Dungeon.LimitedDrops.UPGRADE_SCROLLS.count%2 != 0){\n\t\t\t\t\taddItemToSpawn(new ScrollOfUpgrade());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (Dungeon.asNeeded()) {\n\t\t\t\tDungeon.LimitedDrops.ARCANE_STYLI.count++;\n\t\t\t\taddItemToSpawn( new Stylus() );\n\t\t\t}\n\t\t\t//one scroll of transmutation is guaranteed to spawn somewhere on chapter 2-4\n\t\t\tint enchChapter = (int)((Dungeon.seed / 10) % 3) + 1;\n\t\t\tif ( Dungeon.depth / 5 == enchChapter &&\n\t\t\t\t\tDungeon.seed % 4 + 1 == Dungeon.depth % 5){\n\t\t\t\taddItemToSpawn( new StoneOfEnchantment() );\n\t\t\t}\n\t\t\t\n\t\t\tif ( Dungeon.depth == ((Dungeon.seed % 3) + 1)){\n\t\t\t\taddItemToSpawn( new StoneOfIntuition() );\n\t\t\t}\n\t\t\t\n\t\t\tif (Dungeon.depth > 1) {\n\t\t\t\t//50% chance of getting a level feeling\n\t\t\t\t//~7.15% chance for each feeling\n\t\t\t\tswitch (Random.Int( 14 )) {\n\t\t\t\t\tcase 0:\n\t\t\t\t\t\tfeeling = Feeling.CHASM;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tfeeling = Feeling.WATER;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\tfeeling = Feeling.GRASS;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\tfeeling = Feeling.DARK;\n\t\t\t\t\t\taddItemToSpawn(new Torch());\n\t\t\t\t\t\tviewDistance = Math.round(viewDistance/2f);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 4:\n\t\t\t\t\t\tfeeling = Feeling.LARGE;\n\t\t\t\t\t\taddItemToSpawn(Generator.random(Generator.Category.FOOD));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 5:\n\t\t\t\t\t\tfeeling = Feeling.TRAPS;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 6:\n\t\t\t\t\t\tfeeling = Feeling.SECRETS;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tdo {\n\t\t\twidth = height = length = 0;\n\n\t\t\ttransitions = new ArrayList<>();\n\n\t\t\tmobs = new HashSet<>();\n\t\t\theaps = new SparseArray<>();\n\t\t\tblobs = new HashMap<>();\n\t\t\tplants = new SparseArray<>();\n\t\t\ttraps = new SparseArray<>();\n\t\t\tcustomTiles = new HashSet<>();\n\t\t\tcustomWalls = new HashSet<>();\n\t\t\t\n\t\t} while (!build());\n\t\t\n\t\tbuildFlagMaps();\n\t\tcleanWalls();\n\t\t\n\t\tcreateMobs();\n\t\tcreateItems();\n\n\t\tRandom.popGenerator();\n\t}\n\t\n\tpublic void setSize(int w, int h){\n\t\t\n\t\twidth = w;\n\t\theight = h;\n\t\tlength = w * h;\n\t\t\n\t\tmap = new int[length];\n\t\tArrays.fill( map, feeling == Level.Feeling.CHASM ? Terrain.CHASM : Terrain.WALL );\n\t\t\n\t\tvisited = new boolean[length];\n\t\tmapped = new boolean[length];\n\t\t\n\t\theroFOV = new boolean[length];\n\t\t\n\t\tpassable\t= new boolean[length];\n\t\tlosBlocking\t= new boolean[length];\n\t\tflamable\t= new boolean[length];\n\t\tsecret\t\t= new boolean[length];\n\t\tsolid\t\t= new boolean[length];\n\t\tavoid\t\t= new boolean[length];\n\t\twater\t\t= new boolean[length];\n\t\tpit\t\t\t= new boolean[length];\n\n\t\topenSpace = new boolean[length];\n\t\t\n\t\tPathFinder.setMapSize(w, h);\n\t}\n\t\n\tpublic void reset() {\n\t\t\n\t\tfor (Mob mob : mobs.toArray( new Mob[0] )) {\n\t\t\tif (!mob.reset()) {\n\t\t\t\tmobs.remove( mob );\n\t\t\t}\n\t\t}\n\t\tcreateMobs();\n\t}\n\n\tpublic void playLevelMusic(){\n\t\t//do nothing by default\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\n\t\tversion = bundle.getInt( VERSION );\n\t\t\n\t\t//saves from before v1.2.3 are not supported\n\t\tif (version < ShatteredPixelDungeon.v1_2_3){\n\t\t\tthrow new RuntimeException(\"old save\");\n\t\t}\n\n\t\tsetSize( bundle.getInt(WIDTH), bundle.getInt(HEIGHT));\n\t\t\n\t\tmobs = new HashSet<>();\n\t\theaps = new SparseArray<>();\n\t\tblobs = new HashMap<>();\n\t\tplants = new SparseArray<>();\n\t\ttraps = new SparseArray<>();\n\t\tcustomTiles = new HashSet<>();\n\t\tcustomWalls = new HashSet<>();\n\t\t\n\t\tmap\t\t= bundle.getIntArray( MAP );\n\n\t\tvisited\t= bundle.getBooleanArray( VISITED );\n\t\tmapped\t= bundle.getBooleanArray( MAPPED );\n\n\t\ttransitions = new ArrayList<>();\n\t\tif (bundle.contains(TRANSITIONS)){\n\t\t\tfor (Bundlable b : bundle.getCollection( TRANSITIONS )){\n\t\t\t\ttransitions.add((LevelTransition) b);\n\t\t\t}\n\t\t//pre-1.3.0 saves, converts old entrance/exit to new transitions\n\t\t} else {\n\t\t\tif (bundle.contains(\"entrance\")){\n\t\t\t\ttransitions.add(new LevelTransition(\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\tbundle.getInt(\"entrance\"),\n\t\t\t\t\t\tDungeon.depth == 1 ? LevelTransition.Type.SURFACE : LevelTransition.Type.REGULAR_ENTRANCE));\n\t\t\t}\n\t\t\tif (bundle.contains(\"exit\")){\n\t\t\t\ttransitions.add(new LevelTransition(this, bundle.getInt(\"exit\"), LevelTransition.Type.REGULAR_EXIT));\n\t\t\t}\n\t\t}\n\n\t\tlocked = bundle.getBoolean( LOCKED );\n\t\t\n\t\tCollection<Bundlable> collection = bundle.getCollection( HEAPS );\n\t\tfor (Bundlable h : collection) {\n\t\t\tHeap heap = (Heap)h;\n\t\t\tif (!heap.isEmpty())\n\t\t\t\theaps.put( heap.pos, heap );\n\t\t}\n\t\t\n\t\tcollection = bundle.getCollection( PLANTS );\n\t\tfor (Bundlable p : collection) {\n\t\t\tPlant plant = (Plant)p;\n\t\t\tplants.put( plant.pos, plant );\n\t\t}\n\n\t\tcollection = bundle.getCollection( TRAPS );\n\t\tfor (Bundlable p : collection) {\n\t\t\tTrap trap = (Trap)p;\n\t\t\ttraps.put( trap.pos, trap );\n\t\t}\n\n\t\tcollection = bundle.getCollection( CUSTOM_TILES );\n\t\tfor (Bundlable p : collection) {\n\t\t\tCustomTilemap vis = (CustomTilemap)p;\n\t\t\tcustomTiles.add(vis);\n\t\t}\n\n\t\tcollection = bundle.getCollection( CUSTOM_WALLS );\n\t\tfor (Bundlable p : collection) {\n\t\t\tCustomTilemap vis = (CustomTilemap)p;\n\t\t\tcustomWalls.add(vis);\n\t\t}\n\t\t\n\t\tcollection = bundle.getCollection( MOBS );\n\t\tfor (Bundlable m : collection) {\n\t\t\tMob mob = (Mob)m;\n\t\t\tif (mob != null) {\n\t\t\t\tmobs.add( mob );\n\t\t\t}\n\t\t}\n\t\t\n\t\tcollection = bundle.getCollection( BLOBS );\n\t\tfor (Bundlable b : collection) {\n\t\t\tBlob blob = (Blob)b;\n\t\t\tblobs.put( blob.getClass(), blob );\n\t\t}\n\n\t\tfeeling = bundle.getEnum( FEELING, Feeling.class );\n\t\tif (feeling == Feeling.DARK)\n\t\t\tviewDistance = Math.round(viewDistance/2f);\n\n\t\tif (bundle.contains( \"mobs_to_spawn\" )) {\n\t\t\tfor (Class<? extends Mob> mob : bundle.getClassArray(\"mobs_to_spawn\")) {\n\t\t\t\tif (mob != null) mobsToSpawn.add(mob);\n\t\t\t}\n\t\t}\n\n\t\tif (bundle.contains( \"respawner\" )){\n\t\t\trespawner = (Respawner) bundle.get(\"respawner\");\n\t\t}\n\n\t\tbuildFlagMaps();\n\t\tcleanWalls();\n\n\t}\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tbundle.put( VERSION, Game.versionCode );\n\t\tbundle.put( WIDTH, width );\n\t\tbundle.put( HEIGHT, height );\n\t\tbundle.put( MAP, map );\n\t\tbundle.put( VISITED, visited );\n\t\tbundle.put( MAPPED, mapped );\n\t\tbundle.put( TRANSITIONS, transitions );\n\t\tbundle.put( LOCKED, locked );\n\t\tbundle.put( HEAPS, heaps.valueList() );\n\t\tbundle.put( PLANTS, plants.valueList() );\n\t\tbundle.put( TRAPS, traps.valueList() );\n\t\tbundle.put( CUSTOM_TILES, customTiles );\n\t\tbundle.put( CUSTOM_WALLS, customWalls );\n\t\tbundle.put( MOBS, mobs );\n\t\tbundle.put( BLOBS, blobs.values() );\n\t\tbundle.put( FEELING, feeling );\n\t\tbundle.put( \"mobs_to_spawn\", mobsToSpawn.toArray(new Class[0]));\n\t\tbundle.put( \"respawner\", respawner );\n\t}\n\t\n\tpublic int tunnelTile() {\n\t\treturn feeling == Feeling.CHASM ? Terrain.EMPTY_SP : Terrain.EMPTY;\n\t}\n\n\tpublic int width() {\n\t\treturn width;\n\t}\n\n\tpublic int height() {\n\t\treturn height;\n\t}\n\n\tpublic int length() {\n\t\treturn length;\n\t}\n\t\n\tpublic String tilesTex() {\n\t\treturn null;\n\t}\n\t\n\tpublic String waterTex() {\n\t\treturn null;\n\t}\n\t\n\tabstract protected boolean build();\n\t\n\tprivate ArrayList<Class<?extends Mob>> mobsToSpawn = new ArrayList<>();\n\t\n\tpublic Mob createMob() {\n\t\tif (mobsToSpawn == null || mobsToSpawn.isEmpty()) {\n\t\t\tmobsToSpawn = Bestiary.getMobRotation(Dungeon.depth);\n\t\t}\n\n\t\tMob m = Reflection.newInstance(mobsToSpawn.remove(0));\n\t\tChampionEnemy.rollForChampion(m);\n\t\treturn m;\n\t}\n\n\tabstract protected void createMobs();\n\n\tabstract protected void createItems();\n\n\tpublic int entrance(){\n\t\tLevelTransition l = getTransition(null);\n\t\tif (l != null){\n\t\t\treturn l.cell();\n\t\t}\n\t\treturn 0;\n\t}\n\n\tpublic int exit(){\n\t\tLevelTransition l = getTransition(LevelTransition.Type.REGULAR_EXIT);\n\t\tif (l != null){\n\t\t\treturn l.cell();\n\t\t}\n\t\treturn 0;\n\t}\n\n\tpublic LevelTransition getTransition(LevelTransition.Type type){\n\t\tif (transitions.isEmpty()){\n\t\t\treturn null;\n\t\t}\n\t\tfor (LevelTransition transition : transitions){\n\t\t\t//if we don't specify a type, prefer to return any entrance\n\t\t\tif (type == null &&\n\t\t\t\t\t(transition.type == LevelTransition.Type.REGULAR_ENTRANCE || transition.type == LevelTransition.Type.SURFACE)){\n\t\t\t\treturn transition;\n\t\t\t} else if (transition.type == type){\n\t\t\t\treturn transition;\n\t\t\t}\n\t\t}\n\t\treturn type != null ? getTransition(null) : transitions.get(0);\n\t}\n\n\tpublic LevelTransition getTransition(int cell){\n\t\tfor (LevelTransition transition : transitions){\n\t\t\tif (transition.inside(cell)){\n\t\t\t\treturn transition;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t//returns true if we immediately transition, false otherwise\n\tpublic boolean activateTransition(Hero hero, LevelTransition transition){\n\t\tif (locked){\n\t\t\treturn false;\n\t\t}\n\n\t\tbeforeTransition();\n\t\tInterlevelScene.curTransition = transition;\n\t\tif (transition.type == LevelTransition.Type.REGULAR_EXIT\n\t\t\t\t|| transition.type == LevelTransition.Type.BRANCH_EXIT) {\n\t\t\tInterlevelScene.mode = InterlevelScene.Mode.DESCEND;\n\t\t} else {\n\t\t\tInterlevelScene.mode = InterlevelScene.Mode.ASCEND;\n\t\t}\n\t\tGame.switchScene(InterlevelScene.class);\n\t\treturn true;\n\t}\n\n\t//some buff effects have special logic or are cancelled from the hero before transitioning levels\n\tpublic static void beforeTransition(){\n\n\t\t//time freeze effects need to resolve their pressed cells before transitioning\n\t\tTimekeepersHourglass.timeFreeze timeFreeze = Dungeon.hero.buff(TimekeepersHourglass.timeFreeze.class);\n\t\tif (timeFreeze != null) timeFreeze.disarmPresses();\n\t\tSwiftthistle.TimeBubble timeBubble = Dungeon.hero.buff(Swiftthistle.TimeBubble.class);\n\t\tif (timeBubble != null) timeBubble.disarmPresses();\n\n\t\t//iron stomach does not persist through chasm falling\n\t\tTalent.WarriorFoodImmunity foodImmune = Dungeon.hero.buff(Talent.WarriorFoodImmunity.class);\n\t\tif (foodImmune != null) foodImmune.detach();\n\n\t\tTackle.SuperArmorTracker superArmorTracker = Dungeon.hero.buff(Tackle.SuperArmorTracker.class);\n\t\tif (superArmorTracker != null) superArmorTracker.detach();\n\n\t\t//spend the hero's partial turns, so the hero cannot take partial turns between floors\n\t\tDungeon.hero.spendToWhole();\n\t\tfor (Char ch : Actor.chars()){\n\t\t\t//also adjust any mobs that are now ahead of the hero due to this\n\t\t\tif (ch.cooldown() < Dungeon.hero.cooldown()){\n\t\t\t\tch.spendToWhole();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void seal(){\n\t\tif (!locked) {\n\t\t\tlocked = true;\n\t\t\tBuff.affect(Dungeon.hero, LockedFloor.class);\n\t\t}\n\t}\n\n\tpublic void unseal(){\n\t\tif (locked) {\n\t\t\tlocked = false;\n\t\t\tif (Dungeon.hero.buff(LockedFloor.class) != null){\n\t\t\t\tDungeon.hero.buff(LockedFloor.class).detach();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic ArrayList<Item> getItemsToPreserveFromSealedResurrect(){\n\t\tArrayList<Item> items = new ArrayList<>();\n\t\tfor (Heap h : heaps.valueList()){\n\t\t\tif (h.type == Heap.Type.HEAP) items.addAll(h.items);\n\t\t}\n\t\tfor (Mob m : mobs){\n\t\t\tfor (PinCushion b : m.buffs(PinCushion.class)){\n\t\t\t\titems.addAll(b.getStuckItems());\n\t\t\t}\n\t\t}\n\t\tfor (HeavyBoomerang.CircleBack b : Dungeon.hero.buffs(HeavyBoomerang.CircleBack.class)){\n\t\t\tif (b.activeDepth() == Dungeon.depth) items.add(b.cancel());\n\t\t}\n\t\treturn items;\n\t}\n\n\tpublic Group addVisuals() {\n\t\tif (visuals == null || visuals.parent == null){\n\t\t\tvisuals = new Group();\n\t\t} else {\n\t\t\tvisuals.clear();\n\t\t\tvisuals.camera = null;\n\t\t}\n\t\tfor (int i=0; i < length(); i++) {\n\t\t\tif (pit[i]) {\n\t\t\t\tvisuals.add( new WindParticle.Wind( i ) );\n\t\t\t\tif (i >= width() && water[i-width()]) {\n\t\t\t\t\tvisuals.add( new FlowParticle.Flow( i - width() ) );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn visuals;\n\t}\n\n\t//for visual effects that should render above wall overhang tiles\n\tpublic Group addWallVisuals(){\n\t\tif (wallVisuals == null || wallVisuals.parent == null){\n\t\t\twallVisuals = new Group();\n\t\t} else {\n\t\t\twallVisuals.clear();\n\t\t\twallVisuals.camera = null;\n\t\t}\n\t\treturn wallVisuals;\n\t}\n\n\t\n\tpublic int mobLimit() {\n\t\treturn 0;\n\t}\n\n\tpublic int mobCount(){\n\t\tfloat count = 0;\n\t\tfor (Mob mob : Dungeon.level.mobs.toArray(new Mob[0])){\n\t\t\tif (mob.alignment == Char.Alignment.ENEMY && !mob.properties().contains(Char.Property.MINIBOSS)) {\n\t\t\t\tcount += mob.spawningWeight();\n\t\t\t}\n\t\t}\n\t\treturn Math.round(count);\n\t}\n\n\tpublic Mob findMob( int pos ){\n\t\tfor (Mob mob : mobs){\n\t\t\tif (mob.pos == pos){\n\t\t\t\treturn mob;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate Respawner respawner;\n\n\tpublic Actor addRespawner() {\n\t\tif (respawner == null){\n\t\t\trespawner = new Respawner();\n\t\t\tActor.addDelayed(respawner, respawnCooldown());\n\t\t} else {\n\t\t\tActor.add(respawner);\n\t\t\tif (respawner.cooldown() > respawnCooldown()){\n\t\t\t\trespawner.resetCooldown();\n\t\t\t}\n\t\t}\n\t\treturn respawner;\n\t}\n\n\tpublic static class Respawner extends Actor {\n\t\t{\n\t\t\tactPriority = BUFF_PRIO; //as if it were a buff.\n\t\t}\n\n\t\t@Override\n\t\tprotected boolean act() {\n\n\t\t\tif (Dungeon.level.mobCount() < Dungeon.level.mobLimit()) {\n\n\t\t\t\tif (Dungeon.level.spawnMob(12)){\n\t\t\t\t\tspend(Dungeon.level.respawnCooldown());\n\t\t\t\t} else {\n\t\t\t\t\t//try again in 1 turn\n\t\t\t\t\tspend(TICK);\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tspend(Dungeon.level.respawnCooldown());\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\tprotected void resetCooldown(){\n\t\t\tspend(-cooldown());\n\t\t\tspend(Dungeon.level.respawnCooldown());\n\t\t}\n\t}\n\n\tpublic float respawnCooldown(){\n\t\tif (Statistics.amuletObtained){\n\t\t\tif (Dungeon.depth == 1){\n\t\t\t\t//very fast spawns on floor 1! 0/2/4/6/8/10/12, etc.\n\t\t\t\treturn (Dungeon.level.mobCount()) * (TIME_TO_RESPAWN / 25f);\n\t\t\t} else {\n\t\t\t\t//respawn time is 5/5/10/15/20/25/25, etc.\n\t\t\t\treturn Math.round(GameMath.gate( TIME_TO_RESPAWN/10f, Dungeon.level.mobCount() * (TIME_TO_RESPAWN / 10f), TIME_TO_RESPAWN / 2f));\n\t\t\t}\n\t\t} else if (Dungeon.level.feeling == Feeling.DARK){\n\t\t\treturn 2*TIME_TO_RESPAWN/3f;\n\t\t} else {\n\t\t\treturn TIME_TO_RESPAWN;\n\t\t}\n\t}\n\n\tpublic boolean spawnMob(int disLimit){\n\t\tPathFinder.buildDistanceMap(Dungeon.hero.pos, BArray.or(passable, avoid, null));\n\n\t\tMob mob = createMob();\n\t\tmob.state = mob.WANDERING;\n\t\tint tries = 30;\n\t\tdo {\n\t\t\tmob.pos = randomRespawnCell(mob);\n\t\t\ttries--;\n\t\t} while ((mob.pos == -1 || PathFinder.distance[mob.pos] < disLimit) && tries > 0);\n\n\t\tif (Dungeon.hero.isAlive() && mob.pos != -1 && PathFinder.distance[mob.pos] >= disLimit) {\n\t\t\tGameScene.add( mob );\n\t\t\tif (!mob.buffs(ChampionEnemy.class).isEmpty()){\n\t\t\t\tGLog.w(Messages.get(ChampionEnemy.class, \"warn\"));\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic int randomRespawnCell( Char ch ) {\n\t\tint cell;\n\t\tint count = 0;\n\t\tdo {\n\n\t\t\tif (++count > 30) {\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tcell = Random.Int( length() );\n\n\t\t} while ((Dungeon.level == this && heroFOV[cell])\n\t\t\t\t|| !passable[cell]\n\t\t\t\t|| (Char.hasProp(ch, Char.Property.LARGE) && !openSpace[cell])\n\t\t\t\t|| Actor.findChar( cell ) != null);\n\t\treturn cell;\n\t}\n\t\n\tpublic int randomDestination( Char ch ) {\n\t\tint cell;\n\t\tdo {\n\t\t\tcell = Random.Int( length() );\n\t\t} while (!passable[cell]\n\t\t\t\t|| (Char.hasProp(ch, Char.Property.LARGE) && !openSpace[cell]));\n\t\treturn cell;\n\t}\n\t\n\tpublic void addItemToSpawn( Item item ) {\n\t\tif (item != null) {\n\t\t\titemsToSpawn.add( item );\n\t\t}\n\t}\n\n\tpublic Item findPrizeItem(){ return findPrizeItem(null); }\n\n\tpublic Item findPrizeItem(Class<?extends Item> match){\n\t\tif (itemsToSpawn.size() == 0)\n\t\t\treturn null;\n\n\t\tif (match == null){\n\t\t\tItem item = Random.element(itemsToSpawn);\n\t\t\titemsToSpawn.remove(item);\n\t\t\treturn item;\n\t\t}\n\n\t\tfor (Item item : itemsToSpawn){\n\t\t\tif (match.isInstance(item)){\n\t\t\t\titemsToSpawn.remove( item );\n\t\t\t\treturn item;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic void buildFlagMaps() {\n\t\t\n\t\tfor (int i=0; i < length(); i++) {\n\t\t\tint flags = Terrain.flags[map[i]];\n\t\t\tpassable[i]\t\t= (flags & Terrain.PASSABLE) != 0;\n\t\t\tlosBlocking[i]\t= (flags & Terrain.LOS_BLOCKING) != 0;\n\t\t\tflamable[i]\t\t= (flags & Terrain.FLAMABLE) != 0;\n\t\t\tsecret[i]\t\t= (flags & Terrain.SECRET) != 0;\n\t\t\tsolid[i]\t\t= (flags & Terrain.SOLID) != 0;\n\t\t\tavoid[i]\t\t= (flags & Terrain.AVOID) != 0;\n\t\t\twater[i]\t\t= (flags & Terrain.LIQUID) != 0;\n\t\t\tpit[i]\t\t\t= (flags & Terrain.PIT) != 0;\n\t\t}\n\n\t\tfor (Blob b : blobs.values()){\n\t\t\tb.onBuildFlagMaps(this);\n\t\t}\n\t\t\n\t\tint lastRow = length() - width();\n\t\tfor (int i=0; i < width(); i++) {\n\t\t\tpassable[i] = avoid[i] = false;\n\t\t\tlosBlocking[i] = solid[i] = true;\n\t\t\tpassable[lastRow + i] = avoid[lastRow + i] = false;\n\t\t\tlosBlocking[lastRow + i] = solid[lastRow + i] = true;\n\t\t}\n\t\tfor (int i=width(); i < lastRow; i += width()) {\n\t\t\tpassable[i] = avoid[i] = false;\n\t\t\tlosBlocking[i] = solid[i] = true;\n\t\t\tpassable[i + width()-1] = avoid[i + width()-1] = false;\n\t\t\tlosBlocking[i + width()-1] = solid[i + width()-1] = true;\n\t\t}\n\n\t\t//an open space is large enough to fit large mobs. A space is open when it is not solid\n\t\t// and there is an open corner with both adjacent cells opens\n\t\tfor (int i=0; i < length(); i++) {\n\t\t\tif (solid[i]){\n\t\t\t\topenSpace[i] = false;\n\t\t\t} else {\n\t\t\t\tfor (int j = 1; j < PathFinder.CIRCLE8.length; j += 2){\n\t\t\t\t\tif (solid[i+PathFinder.CIRCLE8[j]]) {\n\t\t\t\t\t\topenSpace[i] = false;\n\t\t\t\t\t} else if (!solid[i+PathFinder.CIRCLE8[(j+1)%8]]\n\t\t\t\t\t\t\t&& !solid[i+PathFinder.CIRCLE8[(j+2)%8]]){\n\t\t\t\t\t\topenSpace[i] = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void destroy( int pos ) {\n\t\tItem prize = null;\n\t\tswitch (Random.Int(10)) {\n\t\t\tcase 0: prize = new ScrollOfTransmutation();\n\t\t\t\tbreak;\n\t\t\tcase 1: prize = Generator.random(Generator.Category.SPELLBOOK);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tprize = Generator.random(Generator.Category.SCROLL);\n\t\t\t\tbreak;\n\t\t}\n\t\t//if raw tile type is flammable or empty\n\t\tint terr = map[pos];\n\t\tif (terr == Terrain.EMPTY || terr == Terrain.EMPTY_DECO\n\t\t\t\t|| (Terrain.flags[map[pos]] & Terrain.FLAMABLE) != 0) {\n\t\t\tif (terr == Terrain.BOOKSHELF && Random.Float() < (1/20f)*RingOfWealth.dropChanceMultiplier( Dungeon.hero )) {\n\t\t\t\tif (prize == null) { //this will never be activated, but this is used to prevent a crash in unpredicted case\n\t\t\t\t\tprize = Generator.random(Generator.Category.SCROLL);\n\t\t\t\t}\n\t\t\t\tDungeon.level.drop(prize, pos).sprite.drop();\n\t\t\t} //generates prize for 5% chance when a bookshelf has destroyed\n\t\t\tset(pos, Terrain.EMBERS);\n\t\t}\n\t\tBlob web = blobs.get(Web.class);\n\t\tif (web != null){\n\t\t\tweb.clear(pos);\n\t\t}\n\t}\n\n\tpublic void cleanWalls() {\n\t\tif (discoverable == null || discoverable.length != length) {\n\t\t\tdiscoverable = new boolean[length()];\n\t\t}\n\n\t\tfor (int i=0; i < length(); i++) {\n\t\t\t\n\t\t\tboolean d = false;\n\t\t\t\n\t\t\tfor (int j=0; j < PathFinder.NEIGHBOURS9.length; j++) {\n\t\t\t\tint n = i + PathFinder.NEIGHBOURS9[j];\n\t\t\t\tif (n >= 0 && n < length() && map[n] != Terrain.WALL && map[n] != Terrain.WALL_DECO) {\n\t\t\t\t\td = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tdiscoverable[i] = d;\n\t\t}\n\t}\n\t\n\tpublic static void set( int cell, int terrain ){\n\t\tset( cell, terrain, Dungeon.level );\n\t}\n\t\n\tpublic static void set( int cell, int terrain, Level level ) {\n\t\tPainter.set( level, cell, terrain );\n\n\t\tif (terrain != Terrain.TRAP && terrain != Terrain.SECRET_TRAP && terrain != Terrain.INACTIVE_TRAP){\n\t\t\tlevel.traps.remove( cell );\n\t\t}\n\n\t\tint flags = Terrain.flags[terrain];\n\t\tlevel.passable[cell]\t\t= (flags & Terrain.PASSABLE) != 0;\n\t\tlevel.losBlocking[cell]\t = (flags & Terrain.LOS_BLOCKING) != 0;\n\t\tlevel.flamable[cell]\t\t= (flags & Terrain.FLAMABLE) != 0;\n\t\tlevel.secret[cell]\t\t = (flags & Terrain.SECRET) != 0;\n\t\tlevel.solid[cell]\t\t\t= (flags & Terrain.SOLID) != 0;\n\t\tlevel.avoid[cell]\t\t\t= (flags & Terrain.AVOID) != 0;\n\t\tlevel.pit[cell]\t\t\t = (flags & Terrain.PIT) != 0;\n\t\tlevel.water[cell]\t\t\t= terrain == Terrain.WATER;\n\n\t\tfor (int i : PathFinder.NEIGHBOURS9){\n\t\t\ti = cell + i;\n\t\t\tif (level.solid[i]){\n\t\t\t\tlevel.openSpace[i] = false;\n\t\t\t} else {\n\t\t\t\tfor (int j = 1; j < PathFinder.CIRCLE8.length; j += 2){\n\t\t\t\t\tif (level.solid[i+PathFinder.CIRCLE8[j]]) {\n\t\t\t\t\t\tlevel.openSpace[i] = false;\n\t\t\t\t\t} else if (!level.solid[i+PathFinder.CIRCLE8[(j+1)%8]]\n\t\t\t\t\t\t\t&& !level.solid[i+PathFinder.CIRCLE8[(j+2)%8]]){\n\t\t\t\t\t\tlevel.openSpace[i] = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic Heap drop( Item item, int cell ) {\n\n\t\tif (item == null || Challenges.isItemBlocked(item)){\n\n\t\t\t//create a dummy heap, give it a dummy sprite, don't add it to the game, and return it.\n\t\t\t//effectively nullifies whatever the logic calling this wants to do, including dropping items.\n\t\t\tHeap heap = new Heap();\n\t\t\tItemSprite sprite = heap.sprite = new ItemSprite();\n\t\t\tsprite.link(heap);\n\t\t\treturn heap;\n\n\t\t}\n\t\t\n\t\tHeap heap = heaps.get( cell );\n\t\tif (heap == null) {\n\t\t\t\n\t\t\theap = new Heap();\n\t\t\theap.seen = Dungeon.level == this && heroFOV[cell];\n\t\t\theap.pos = cell;\n\t\t\theap.drop(item);\n\t\t\tif (map[cell] == Terrain.CHASM || (Dungeon.level != null && pit[cell])) {\n\t\t\t\tDungeon.dropToChasm( item );\n\t\t\t\tGameScene.discard( heap );\n\t\t\t} else {\n\t\t\t\theaps.put( cell, heap );\n\t\t\t\tGameScene.add( heap );\n\t\t\t}\n\t\t\t\n\t\t} else if (heap.type == Heap.Type.LOCKED_CHEST || heap.type == Heap.Type.CRYSTAL_CHEST) {\n\t\t\t\n\t\t\tint n;\n\t\t\tdo {\n\t\t\t\tn = cell + PathFinder.NEIGHBOURS8[Random.Int( 8 )];\n\t\t\t} while (!passable[n] && !avoid[n]);\n\t\t\treturn drop( item, n );\n\t\t\t\n\t\t} else {\n\t\t\theap.drop(item);\n\t\t}\n\t\t\n\t\tif (Dungeon.level != null && ShatteredPixelDungeon.scene() instanceof GameScene) {\n\t\t\tpressCell( cell );\n\t\t}\n\t\t\n\t\treturn heap;\n\t}\n\t\n\tpublic Plant plant( Plant.Seed seed, int pos ) {\n\n\t\tPlant plant = plants.get( pos );\n\t\tif (plant != null) {\n\t\t\tplant.wither();\n\t\t}\n\n\t\tif (map[pos] == Terrain.HIGH_GRASS ||\n\t\t\t\tmap[pos] == Terrain.FURROWED_GRASS ||\n\t\t\t\tmap[pos] == Terrain.EMPTY ||\n\t\t\t\tmap[pos] == Terrain.EMBERS ||\n\t\t\t\tmap[pos] == Terrain.EMPTY_DECO) {\n\t\t\tset(pos, Terrain.GRASS, this);\n\t\t\tGameScene.updateMap(pos);\n\t\t}\n\n\t\t//we have to get this far as grass placement has RNG implications in levelgen\n\t\tif (Dungeon.isChallenged(Challenges.NO_HERBALISM)){\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tplant = seed.couch( pos, this );\n\t\tplants.put( pos, plant );\n\t\t\n\t\tGameScene.plantSeed( pos );\n\n\t\tfor (Char ch : Actor.chars()){\n\t\t\tif (ch instanceof WandOfRegrowth.Lotus\n\t\t\t\t\t&& ((WandOfRegrowth.Lotus) ch).inRange(pos)\n\t\t\t\t\t&& Actor.findChar(pos) != null){\n\t\t\t\tplant.trigger();\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn plant;\n\t}\n\t\n\tpublic void uproot( int pos ) {\n\t\tplants.remove(pos);\n\t\tGameScene.updateMap( pos );\n\t}\n\n\tpublic Trap setTrap( Trap trap, int pos ){\n\t\tTrap existingTrap = traps.get(pos);\n\t\tif (existingTrap != null){\n\t\t\ttraps.remove( pos );\n\t\t}\n\t\ttrap.set( pos );\n\t\ttraps.put( pos, trap );\n\t\tGameScene.updateMap( pos );\n\t\treturn trap;\n\t}\n\n\tpublic void disarmTrap( int pos ) {\n\t\tset(pos, Terrain.INACTIVE_TRAP);\n\t\tGameScene.updateMap(pos);\n\t}\n\n\tpublic void discover( int cell ) {\n\t\tset( cell, Terrain.discover( map[cell] ) );\n\t\tTrap trap = traps.get( cell );\n\t\tif (trap != null)\n\t\t\ttrap.reveal();\n\t\tGameScene.updateMap( cell );\n\t}\n\n\tpublic boolean setCellToWater( boolean includeTraps, int cell ){\n\t\tPoint p = cellToPoint(cell);\n\n\t\t//if a custom tilemap is over that cell, don't put water there\n\t\tfor (CustomTilemap cust : customTiles){\n\t\t\tPoint custPoint = new Point(p);\n\t\t\tcustPoint.x -= cust.tileX;\n\t\t\tcustPoint.y -= cust.tileY;\n\t\t\tif (custPoint.x >= 0 && custPoint.y >= 0\n\t\t\t\t\t&& custPoint.x < cust.tileW && custPoint.y < cust.tileH){\n\t\t\t\tif (cust.image(custPoint.x, custPoint.y) != null){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tint terr = map[cell];\n\t\tif (terr == Terrain.EMPTY || terr == Terrain.GRASS ||\n\t\t\t\tterr == Terrain.EMBERS || terr == Terrain.EMPTY_SP ||\n\t\t\t\tterr == Terrain.HIGH_GRASS || terr == Terrain.FURROWED_GRASS\n\t\t\t\t|| terr == Terrain.EMPTY_DECO){\n\t\t\tset(cell, Terrain.WATER);\n\t\t\tGameScene.updateMap(cell);\n\t\t\treturn true;\n\t\t} else if (includeTraps && (terr == Terrain.SECRET_TRAP ||\n\t\t\t\tterr == Terrain.TRAP || terr == Terrain.INACTIVE_TRAP)){\n\t\t\tset(cell, Terrain.WATER);\n\t\t\tDungeon.level.traps.remove(cell);\n\t\t\tGameScene.updateMap(cell);\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\t\n\tpublic int fallCell( boolean fallIntoPit ) {\n\t\tint result;\n\t\tdo {\n\t\t\tresult = randomRespawnCell( null );\n\t\t\tif (result == -1) return -1;\n\t\t} while (traps.get(result) != null\n\t\t\t\t|| findMob(result) != null);\n\t\treturn result;\n\t}\n\t\n\tpublic void occupyCell( Char ch ){\n\t\tif (!ch.isImmune(Web.class) && Blob.volumeAt(ch.pos, Web.class) > 0){\n\t\t\tblobs.get(Web.class).clear(ch.pos);\n\t\t\tWeb.affectChar( ch );\n\t\t}\n\n\t\tif (!ch.flying){\n\n\t\t\tif ( (map[ch.pos] == Terrain.GRASS || map[ch.pos] == Terrain.EMBERS)\n\t\t\t\t\t&& ch == Dungeon.hero && Dungeon.hero.hasTalent(Talent.REJUVENATING_STEPS)\n\t\t\t\t\t&& ch.buff(Talent.RejuvenatingStepsCooldown.class) == null){\n\n\t\t\t\tif (!Regeneration.regenOn()){\n\t\t\t\t\tset(ch.pos, Terrain.FURROWED_GRASS);\n\t\t\t\t} else if (ch.buff(Talent.RejuvenatingStepsFurrow.class) != null && ch.buff(Talent.RejuvenatingStepsFurrow.class).count() >= 200) {\n\t\t\t\t\tset(ch.pos, Terrain.FURROWED_GRASS);\n\t\t\t\t} else {\n\t\t\t\t\tset(ch.pos, Terrain.HIGH_GRASS);\n\t\t\t\t\tBuff.count(ch, Talent.RejuvenatingStepsFurrow.class, 3 - Dungeon.hero.pointsInTalent(Talent.REJUVENATING_STEPS));\n\t\t\t\t}\n\t\t\t\tGameScene.updateMap(ch.pos);\n\t\t\t\tBuff.affect(ch, Talent.RejuvenatingStepsCooldown.class, 15f - 5f*Dungeon.hero.pointsInTalent(Talent.REJUVENATING_STEPS));\n\t\t\t}\n\t\t\t\n\t\t\tif (pit[ch.pos]){\n\t\t\t\tif (ch == Dungeon.hero) {\n\t\t\t\t\tChasm.heroFall(ch.pos);\n\t\t\t\t} else if (ch instanceof Mob) {\n\t\t\t\t\tChasm.mobFall( (Mob)ch );\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t//characters which are not the hero or a sheep 'soft' press cells\n\t\t\tpressCell( ch.pos, ch instanceof Hero || ch instanceof Sheep);\n\t\t} else {\n\t\t\tif (map[ch.pos] == Terrain.DOOR){\n\t\t\t\tDoor.enter( ch.pos );\n\t\t\t}\n\t\t}\n\n\t\tif (ch.isAlive() && ch instanceof Piranha && !water[ch.pos]){\n\t\t\t((Piranha) ch).dieOnLand();\n\t\t}\n\t}\n\t\n\t//public method for forcing the hard press of a cell. e.g. when an item lands on it\n\tpublic void pressCell( int cell ){\n\t\tpressCell( cell, true );\n\t}\n\t\n\t//a 'soft' press ignores hidden traps\n\t//a 'hard' press triggers all things\n\tprivate void pressCell( int cell, boolean hard ) {\n\n\t\tTrap trap = null;\n\t\t\n\t\tswitch (map[cell]) {\n\t\t\n\t\tcase Terrain.SECRET_TRAP:\n\t\t\tif (hard) {\n\t\t\t\ttrap = traps.get( cell );\n\t\t\t\tGLog.i(Messages.get(Level.class, \"hidden_trap\", trap.name()));\n\t\t\t}\n\t\t\tbreak;\n\t\t\t\n\t\tcase Terrain.TRAP:\n\t\t\ttrap = traps.get( cell );\n\t\t\tbreak;\n\t\t\t\n\t\tcase Terrain.HIGH_GRASS:\n\t\tcase Terrain.FURROWED_GRASS:\n\t\t\tHighGrass.trample( this, cell);\n\t\t\tbreak;\n\t\t\t\n\t\tcase Terrain.WELL:\n\t\t\tWellWater.affectCell( cell );\n\t\t\tbreak;\n\t\t\t\n\t\tcase Terrain.DOOR:\n\t\t\tDoor.enter( cell );\n\t\t\tbreak;\n\t\t}\n\n\t\tTimekeepersHourglass.timeFreeze timeFreeze =\n\t\t\t\tDungeon.hero.buff(TimekeepersHourglass.timeFreeze.class);\n\n\t\tSwiftthistle.TimeBubble bubble =\n\t\t\t\tDungeon.hero.buff(Swiftthistle.TimeBubble.class);\n\n\t\tif (trap != null) {\n\t\t\tif (bubble != null){\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TRAP);\n\t\t\t\tdiscover(cell);\n\t\t\t\tbubble.setDelayedPress(cell);\n\t\t\t\t\n\t\t\t} else if (timeFreeze != null){\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TRAP);\n\t\t\t\tdiscover(cell);\n\t\t\t\ttimeFreeze.setDelayedPress(cell);\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tif (Dungeon.hero.pos == cell) {\n\t\t\t\t\tDungeon.hero.interrupt();\n\t\t\t\t}\n\t\t\t\ttrap.trigger();\n\n\t\t\t}\n\t\t}\n\t\t\n\t\tPlant plant = plants.get( cell );\n\t\tif (plant != null) {\n\t\t\tif (bubble != null){\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TRAMPLE, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t\tbubble.setDelayedPress(cell);\n\n\t\t\t} else if (timeFreeze != null){\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TRAMPLE, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t\ttimeFreeze.setDelayedPress(cell);\n\n\t\t\t} else {\n\t\t\t\tplant.trigger();\n\n\t\t\t}\n\t\t}\n\n\t\tif (hard && Blob.volumeAt(cell, Web.class) > 0){\n\t\t\tblobs.get(Web.class).clear(cell);\n\t\t}\n\t}\n\n\tprivate static boolean[] heroMindFov;\n\n\tprivate static boolean[] modifiableBlocking;\n\n\tpublic void updateFieldOfView( Char c, boolean[] fieldOfView ) {\n\n\t\tint cx = c.pos % width();\n\t\tint cy = c.pos / width();\n\t\t\n\t\tboolean sighted = c.buff( Blindness.class ) == null && c.buff( Shadows.class ) == null\n\t\t\t\t\t\t&& c.buff( TimekeepersHourglass.timeStasis.class ) == null && c.isAlive();\n\t\tif (sighted) {\n\t\t\tboolean[] blocking = null;\n\n\t\t\tif (modifiableBlocking == null || modifiableBlocking.length != Dungeon.level.losBlocking.length){\n\t\t\t\tmodifiableBlocking = new boolean[Dungeon.level.losBlocking.length];\n\t\t\t}\n\t\t\t\n\t\t\tif ((c instanceof Hero && ((Hero) c).subClass == HeroSubClass.WARDEN)\n\t\t\t\t|| c instanceof YogFist.SoiledFist) {\n\t\t\t\tif (blocking == null) {\n\t\t\t\t\tSystem.arraycopy(Dungeon.level.losBlocking, 0, modifiableBlocking, 0, modifiableBlocking.length);\n\t\t\t\t\tblocking = modifiableBlocking;\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < blocking.length; i++){\n\t\t\t\t\tif (blocking[i] && (Dungeon.level.map[i] == Terrain.HIGH_GRASS || Dungeon.level.map[i] == Terrain.FURROWED_GRASS)){\n\t\t\t\t\t\tblocking[i] = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (c.alignment != Char.Alignment.ALLY\n\t\t\t\t\t&& Dungeon.level.blobs.containsKey(SmokeScreen.class)\n\t\t\t\t\t&& Dungeon.level.blobs.get(SmokeScreen.class).volume > 0) {\n\t\t\t\tif (blocking == null) {\n\t\t\t\t\tSystem.arraycopy(Dungeon.level.losBlocking, 0, modifiableBlocking, 0, modifiableBlocking.length);\n\t\t\t\t\tblocking = modifiableBlocking;\n\t\t\t\t}\n\t\t\t\tBlob s = Dungeon.level.blobs.get(SmokeScreen.class);\n\t\t\t\tfor (int i = 0; i < blocking.length; i++){\n\t\t\t\t\tif (!blocking[i] && s.cur[i] > 0){\n\t\t\t\t\t\tblocking[i] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (blocking == null){\n\t\t\t\tblocking = Dungeon.level.losBlocking;\n\t\t\t}\n\t\t\t\n\t\t\tint viewDist = c.viewDistance;\n\t\t\tif (c instanceof Hero){\n\t\t\t\tviewDist *= 1f + 0.25f*((Hero) c).pointsInTalent(Talent.FARSIGHT);\n\t\t\t\tviewDist *= 1f + 0.25f*((Hero) c).pointsInTalent(Talent.TELESCOPE);\n\t\t\t}\n\t\t\t\n\t\t\tShadowCaster.castShadow( cx, cy, fieldOfView, blocking, viewDist );\n\t\t} else {\n\t\t\tBArray.setFalse(fieldOfView);\n\t\t}\n\t\t\n\t\tint sense = 1;\n\t\t//Currently only the hero can get mind vision\n\t\tif (c.isAlive() && c == Dungeon.hero) {\n\t\t\tfor (Buff b : c.buffs( MindVision.class )) {\n\t\t\t\tsense = Math.max( ((MindVision)b).distance, sense );\n\t\t\t}\n\t\t\tif (c.buff(MagicalSight.class) != null){\n\t\t\t\tsense = Math.max( MagicalSight.DISTANCE, sense );\n\t\t\t}\n\t\t}\n\t\t\n\t\t//uses rounding\n\t\tif (!sighted || sense > 1) {\n\t\t\t\n\t\t\tint[][] rounding = ShadowCaster.rounding;\n\t\t\t\n\t\t\tint left, right;\n\t\t\tint pos;\n\t\t\tfor (int y = Math.max(0, cy - sense); y <= Math.min(height()-1, cy + sense); y++) {\n\t\t\t\tif (rounding[sense][Math.abs(cy - y)] < Math.abs(cy - y)) {\n\t\t\t\t\tleft = cx - rounding[sense][Math.abs(cy - y)];\n\t\t\t\t} else {\n\t\t\t\t\tleft = sense;\n\t\t\t\t\twhile (rounding[sense][left] < rounding[sense][Math.abs(cy - y)]){\n\t\t\t\t\t\tleft--;\n\t\t\t\t\t}\n\t\t\t\t\tleft = cx - left;\n\t\t\t\t}\n\t\t\t\tright = Math.min(width()-1, cx + cx - left);\n\t\t\t\tleft = Math.max(0, left);\n\t\t\t\tpos = left + y * width();\n\t\t\t\tSystem.arraycopy(discoverable, pos, fieldOfView, pos, right - left + 1);\n\t\t\t}\n\t\t}\n\n\t\tif (c instanceof SpiritHawk.HawkAlly && Dungeon.hero.pointsInTalent(Talent.EAGLE_EYE) >= 3){\n\t\t\tint range = 1+(Dungeon.hero.pointsInTalent(Talent.EAGLE_EYE)-2);\n\t\t\tfor (Mob mob : mobs) {\n\t\t\t\tint p = mob.pos;\n\t\t\t\tif (!fieldOfView[p] && distance(c.pos, p) <= range) {\n\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\tfieldOfView[mob.pos + i] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//Currently only the hero can get mind vision or awareness\n\t\tif (c.isAlive() && c == Dungeon.hero) {\n\n\t\t\tif (heroMindFov == null || heroMindFov.length != length()){\n\t\t\t\theroMindFov = new boolean[length];\n\t\t\t} else {\n\t\t\t\tBArray.setFalse(heroMindFov);\n\t\t\t}\n\n\t\t\tDungeon.hero.mindVisionEnemies.clear();\n\t\t\tif (c.buff( MindVision.class ) != null) {\n\t\t\t\tfor (Mob mob : mobs) {\n\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\theroMindFov[mob.pos + i] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tHero h = (Hero) c;\n\t\t\t\tint range = 0;\n\t\t\t\tif (h.hasTalent(Talent.HEIGHTENED_SENSES)) {\n\t\t\t\t\trange += 1+h.pointsInTalent(Talent.HEIGHTENED_SENSES);\n\t\t\t\t}\n\t\t\t\tif (h.hasTalent(Talent.TACTICAL_SIGHT) && Dungeon.hero.buff(ReinforcedArmor.ReinforcedArmorTracker.class) != null) {\n\t\t\t\t\trange += 1+h.pointsInTalent(Talent.TACTICAL_SIGHT);\n\t\t\t\t}\n\t\t\t\tif (range > 0) {\n\t\t\t\t\tfor (Mob mob : mobs) {\n\t\t\t\t\t\tint p = mob.pos;\n\t\t\t\t\t\tif (!fieldOfView[p] && distance(c.pos, p) <= range) {\n\t\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\t\t\theroMindFov[mob.pos + i] = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (c.buff( Awareness.class ) != null) {\n\t\t\t\tfor (Heap heap : heaps.valueList()) {\n\t\t\t\t\tint p = heap.pos;\n\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) heroMindFov[p+i] = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (TalismanOfForesight.CharAwareness a : c.buffs(TalismanOfForesight.CharAwareness.class)){\n\t\t\t\tChar ch = (Char) Actor.findById(a.charID);\n\t\t\t\tif (ch == null || !ch.isAlive()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tint p = ch.pos;\n\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) heroMindFov[p+i] = true;\n\t\t\t}\n\n\t\t\tfor (TalismanOfForesight.HeapAwareness h : c.buffs(TalismanOfForesight.HeapAwareness.class)){\n\t\t\t\tif (Dungeon.depth != h.depth || Dungeon.branch != h.branch) continue;\n\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) heroMindFov[h.pos+i] = true;\n\t\t\t}\n\n\t\t\tfor (Mob m : mobs){\n\t\t\t\tif (m instanceof WandOfWarding.Ward\n\t\t\t\t\t\t|| m instanceof WandOfRegrowth.Lotus\n\t\t\t\t\t\t|| m instanceof SpiritHawk.HawkAlly){\n\t\t\t\t\tif (m.fieldOfView == null || m.fieldOfView.length != length()){\n\t\t\t\t\t\tm.fieldOfView = new boolean[length()];\n\t\t\t\t\t\tDungeon.level.updateFieldOfView( m, m.fieldOfView );\n\t\t\t\t\t}\n\t\t\t\t\tBArray.or(heroMindFov, m.fieldOfView, heroMindFov);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (RevealedArea a : c.buffs(RevealedArea.class)){\n\t\t\t\tif (Dungeon.depth != a.depth || Dungeon.branch != a.branch) continue;\n\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) heroMindFov[a.pos+i] = true;\n\t\t\t}\n\n\t\t\t//set mind vision chars\n\t\t\tfor (Mob mob : mobs) {\n\t\t\t\tif (heroMindFov[mob.pos] && !fieldOfView[mob.pos]){\n\t\t\t\t\tDungeon.hero.mindVisionEnemies.add(mob);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tBArray.or(heroMindFov, fieldOfView, fieldOfView);\n\n\t\t}\n\n\t\tif (c == Dungeon.hero) {\n\t\t\tfor (Heap heap : heaps.valueList())\n\t\t\t\tif (!heap.seen && fieldOfView[heap.pos])\n\t\t\t\t\theap.seen = true;\n\t\t}\n\n\t}\n\n\tpublic boolean isLevelExplored( int depth ){\n\t\treturn false;\n\t}\n\t\n\tpublic int distance( int a, int b ) {\n\t\tint ax = a % width();\n\t\tint ay = a / width();\n\t\tint bx = b % width();\n\t\tint by = b / width();\n\t\treturn Math.max( Math.abs( ax - bx ), Math.abs( ay - by ) );\n\t}\n\t\n\tpublic boolean adjacent( int a, int b ) {\n\t\treturn distance( a, b ) == 1;\n\t}\n\t\n\t//uses pythagorean theorum for true distance, as if there was no movement grid\n\tpublic float trueDistance(int a, int b){\n\t\tint ax = a % width();\n\t\tint ay = a / width();\n\t\tint bx = b % width();\n\t\tint by = b / width();\n\t\treturn (float)Math.sqrt(Math.pow(Math.abs( ax - bx ), 2) + Math.pow(Math.abs( ay - by ), 2));\n\t}\n\n\t//returns true if the input is a valid tile within the level\n\tpublic boolean insideMap( int tile ){\n\t\t\t\t//top and bottom row and beyond\n\t\treturn !((tile < width || tile >= length - width) ||\n\t\t\t\t//left and right column\n\t\t\t\t(tile % width == 0 || tile % width == width-1));\n\t}\n\n\tpublic Point cellToPoint( int cell ){\n\t\treturn new Point(cell % width(), cell / width());\n\t}\n\n\tpublic int pointToCell( Point p ){\n\t\treturn p.x + p.y*width();\n\t}\n\t\n\tpublic String tileName( int tile ) {\n\t\t\n\t\tswitch (tile) {\n\t\t\tcase Terrain.CHASM:\n\t\t\t\treturn Messages.get(Level.class, \"chasm_name\");\n\t\t\tcase Terrain.EMPTY:\n\t\t\tcase Terrain.EMPTY_SP:\n\t\t\tcase Terrain.EMPTY_DECO:\n\t\t\tcase Terrain.CUSTOM_DECO_EMPTY:\n\t\t\tcase Terrain.SECRET_TRAP:\n\t\t\t\treturn Messages.get(Level.class, \"floor_name\");\n\t\t\tcase Terrain.GRASS:\n\t\t\t\treturn Messages.get(Level.class, \"grass_name\");\n\t\t\tcase Terrain.WATER:\n\t\t\t\treturn Messages.get(Level.class, \"water_name\");\n\t\t\tcase Terrain.WALL:\n\t\t\tcase Terrain.WALL_DECO:\n\t\t\tcase Terrain.SECRET_DOOR:\n\t\t\t\treturn Messages.get(Level.class, \"wall_name\");\n\t\t\tcase Terrain.DOOR:\n\t\t\t\treturn Messages.get(Level.class, \"closed_door_name\");\n\t\t\tcase Terrain.OPEN_DOOR:\n\t\t\t\treturn Messages.get(Level.class, \"open_door_name\");\n\t\t\tcase Terrain.ENTRANCE:\n\t\t\t\treturn Messages.get(Level.class, \"entrace_name\");\n\t\t\tcase Terrain.EXIT:\n\t\t\t\treturn Messages.get(Level.class, \"exit_name\");\n\t\t\tcase Terrain.EMBERS:\n\t\t\t\treturn Messages.get(Level.class, \"embers_name\");\n\t\t\tcase Terrain.FURROWED_GRASS:\n\t\t\t\treturn Messages.get(Level.class, \"furrowed_grass_name\");\n\t\t\tcase Terrain.LOCKED_DOOR:\n\t\t\t\treturn Messages.get(Level.class, \"locked_door_name\");\n\t\t\tcase Terrain.CRYSTAL_DOOR:\n\t\t\t\treturn Messages.get(Level.class, \"crystal_door_name\");\n\t\t\tcase Terrain.PEDESTAL:\n\t\t\t\treturn Messages.get(Level.class, \"pedestal_name\");\n\t\t\tcase Terrain.BARRICADE:\n\t\t\t\treturn Messages.get(Level.class, \"barricade_name\");\n\t\t\tcase Terrain.HIGH_GRASS:\n\t\t\t\treturn Messages.get(Level.class, \"high_grass_name\");\n\t\t\tcase Terrain.LOCKED_EXIT:\n\t\t\t\treturn Messages.get(Level.class, \"locked_exit_name\");\n\t\t\tcase Terrain.UNLOCKED_EXIT:\n\t\t\t\treturn Messages.get(Level.class, \"unlocked_exit_name\");\n\t\t\tcase Terrain.WELL:\n\t\t\t\treturn Messages.get(Level.class, \"well_name\");\n\t\t\tcase Terrain.EMPTY_WELL:\n\t\t\t\treturn Messages.get(Level.class, \"empty_well_name\");\n\t\t\tcase Terrain.STATUE:\n\t\t\tcase Terrain.STATUE_SP:\n\t\t\t\treturn Messages.get(Level.class, \"statue_name\");\n\t\t\tcase Terrain.INACTIVE_TRAP:\n\t\t\t\treturn Messages.get(Level.class, \"inactive_trap_name\");\n\t\t\tcase Terrain.BOOKSHELF:\n\t\t\t\treturn Messages.get(Level.class, \"bookshelf_name\");\n\t\t\tcase Terrain.ALCHEMY:\n\t\t\t\treturn Messages.get(Level.class, \"alchemy_name\");\n\t\t\tdefault:\n\t\t\t\treturn Messages.get(Level.class, \"default_name\");\n\t\t}\n\t}\n\t\n\tpublic String tileDesc( int tile ) {\n\t\t\n\t\tswitch (tile) {\n\t\t\tcase Terrain.CHASM:\n\t\t\t\treturn Messages.get(Level.class, \"chasm_desc\");\n\t\t\tcase Terrain.WATER:\n\t\t\t\treturn Messages.get(Level.class, \"water_desc\");\n\t\t\tcase Terrain.ENTRANCE:\n\t\t\t\treturn Messages.get(Level.class, \"entrance_desc\");\n\t\t\tcase Terrain.EXIT:\n\t\t\tcase Terrain.UNLOCKED_EXIT:\n\t\t\t\treturn Messages.get(Level.class, \"exit_desc\");\n\t\t\tcase Terrain.EMBERS:\n\t\t\t\treturn Messages.get(Level.class, \"embers_desc\");\n\t\t\tcase Terrain.HIGH_GRASS:\n\t\t\tcase Terrain.FURROWED_GRASS:\n\t\t\t\treturn Messages.get(Level.class, \"high_grass_desc\");\n\t\t\tcase Terrain.LOCKED_DOOR:\n\t\t\t\treturn Messages.get(Level.class, \"locked_door_desc\");\n\t\t\tcase Terrain.CRYSTAL_DOOR:\n\t\t\t\treturn Messages.get(Level.class, \"crystal_door_desc\");\n\t\t\tcase Terrain.LOCKED_EXIT:\n\t\t\t\treturn Messages.get(Level.class, \"locked_exit_desc\");\n\t\t\tcase Terrain.BARRICADE:\n\t\t\t\treturn Messages.get(Level.class, \"barricade_desc\");\n\t\t\tcase Terrain.INACTIVE_TRAP:\n\t\t\t\treturn Messages.get(Level.class, \"inactive_trap_desc\");\n\t\t\tcase Terrain.STATUE:\n\t\t\tcase Terrain.STATUE_SP:\n\t\t\t\treturn Messages.get(Level.class, \"statue_desc\");\n\t\t\tcase Terrain.ALCHEMY:\n\t\t\t\treturn Messages.get(Level.class, \"alchemy_desc\");\n\t\t\tcase Terrain.EMPTY_WELL:\n\t\t\t\treturn Messages.get(Level.class, \"empty_well_desc\");\n\t\t\tdefault:\n\t\t\t\treturn \"\";\n\t\t}\n\t}\n}" }, { "identifier": "Terrain", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/Terrain.java", "snippet": "public class Terrain {\n\n\tpublic static final int CHASM\t\t\t= 0;\n\tpublic static final int EMPTY\t\t\t= 1;\n\tpublic static final int GRASS\t\t\t= 2;\n\tpublic static final int EMPTY_WELL\t\t= 3;\n\tpublic static final int WALL\t\t\t= 4;\n\tpublic static final int DOOR\t\t\t= 5;\n\tpublic static final int OPEN_DOOR\t\t= 6;\n\tpublic static final int ENTRANCE\t\t= 7;\n\tpublic static final int EXIT\t\t\t= 8;\n\tpublic static final int EMBERS\t\t\t= 9;\n\tpublic static final int LOCKED_DOOR\t\t= 10;\n\tpublic static final int CRYSTAL_DOOR\t= 31;\n\tpublic static final int PEDESTAL\t\t= 11;\n\tpublic static final int WALL_DECO\t\t= 12;\n\tpublic static final int BARRICADE\t\t= 13;\n\tpublic static final int EMPTY_SP\t\t= 14;\n\tpublic static final int HIGH_GRASS\t\t= 15;\n\tpublic static final int FURROWED_GRASS\t= 30;\n\n\tpublic static final int SECRET_DOOR\t = 16;\n\tpublic static final int SECRET_TRAP = 17;\n\tpublic static final int TRAP = 18;\n\tpublic static final int INACTIVE_TRAP = 19;\n\n\tpublic static final int EMPTY_DECO\t\t= 20;\n\tpublic static final int LOCKED_EXIT\t\t= 21;\n\tpublic static final int UNLOCKED_EXIT\t= 22;\n\tpublic static final int WELL\t\t\t= 24;\n\tpublic static final int BOOKSHELF\t\t= 27;\n\tpublic static final int ALCHEMY\t\t\t= 28;\n\n\tpublic static final int CUSTOM_DECO_EMPTY = 32; //regular empty tile that can't be overridden, used for custom visuals mainly\n\t//solid environment decorations\n\tpublic static final int CUSTOM_DECO\t = 23; //invisible decoration that will also be a custom visual, re-uses the old terrain ID for signs\n\tpublic static final int STATUE\t\t\t= 25;\n\tpublic static final int STATUE_SP\t\t= 26;\n\t//These decorations are environment-specific\n\t//33 and 34 are reserved for future statue-like decorations\n\tpublic static final int MINE_CRYSTAL = 35;\n\tpublic static final int MINE_BOULDER = 36;\n\n\tpublic static final int WATER\t\t = 29;\n\t\n\tpublic static final int PASSABLE\t\t= 0x01;\n\tpublic static final int LOS_BLOCKING\t= 0x02;\n\tpublic static final int FLAMABLE\t\t= 0x04;\n\tpublic static final int SECRET\t\t\t= 0x08;\n\tpublic static final int SOLID\t\t\t= 0x10;\n\tpublic static final int AVOID\t\t\t= 0x20;\n\tpublic static final int LIQUID\t\t\t= 0x40;\n\tpublic static final int PIT\t\t\t\t= 0x80;\n\t\n\tpublic static final int[] flags = new int[256];\n\tstatic {\n\t\tflags[CHASM]\t\t= AVOID\t| PIT;\n\t\tflags[EMPTY]\t\t= PASSABLE;\n\t\tflags[GRASS]\t\t= PASSABLE | FLAMABLE;\n\t\tflags[EMPTY_WELL]\t= PASSABLE;\n\t\tflags[WATER]\t\t= PASSABLE | LIQUID;\n\t\tflags[WALL]\t\t\t= LOS_BLOCKING | SOLID;\n\t\tflags[DOOR]\t\t\t= PASSABLE | LOS_BLOCKING | FLAMABLE | SOLID;\n\t\tflags[OPEN_DOOR]\t= PASSABLE | FLAMABLE;\n\t\tflags[ENTRANCE]\t\t= PASSABLE/* | SOLID*/;\n\t\tflags[EXIT]\t\t\t= PASSABLE;\n\t\tflags[EMBERS]\t\t= PASSABLE;\n\t\tflags[LOCKED_DOOR]\t= LOS_BLOCKING | SOLID;\n\t\tflags[CRYSTAL_DOOR]\t= SOLID;\n\t\tflags[PEDESTAL]\t\t= PASSABLE;\n\t\tflags[WALL_DECO]\t= flags[WALL];\n\t\tflags[BARRICADE]\t= FLAMABLE | SOLID | LOS_BLOCKING;\n\t\tflags[EMPTY_SP]\t\t= flags[EMPTY];\n\t\tflags[HIGH_GRASS]\t= PASSABLE | LOS_BLOCKING | FLAMABLE;\n\t\tflags[FURROWED_GRASS]= flags[HIGH_GRASS];\n\n\t\tflags[SECRET_DOOR] = flags[WALL] | SECRET;\n\t\tflags[SECRET_TRAP] = flags[EMPTY] | SECRET;\n\t\tflags[TRAP] = AVOID;\n\t\tflags[INACTIVE_TRAP]= flags[EMPTY];\n\n\t\tflags[EMPTY_DECO]\t= flags[EMPTY];\n\t\tflags[LOCKED_EXIT]\t= SOLID;\n\t\tflags[UNLOCKED_EXIT]= PASSABLE;\n\t\tflags[WELL]\t\t\t= AVOID;\n\t\tflags[BOOKSHELF]\t= flags[BARRICADE];\n\t\tflags[ALCHEMY]\t\t= SOLID;\n\n\t\tflags[CUSTOM_DECO_EMPTY] = flags[EMPTY];\n\t\tflags[CUSTOM_DECO] = SOLID;\n\t\tflags[STATUE] = SOLID;\n\t\tflags[STATUE_SP] = flags[STATUE];\n\n\t\tflags[MINE_CRYSTAL] = SOLID;\n\t\tflags[MINE_BOULDER] = SOLID;\n\n\t}\n\n\tpublic static int discover( int terr ) {\n\t\tswitch (terr) {\n\t\tcase SECRET_DOOR:\n\t\t\treturn DOOR;\n\t\tcase SECRET_TRAP:\n\t\t\treturn TRAP;\n\t\tdefault:\n\t\t\treturn terr;\n\t\t}\n\t}\n\n}" }, { "identifier": "Painter", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/painters/Painter.java", "snippet": "public abstract class Painter {\n\t\n\t//If painters require additional parameters, they should\n\t// request them in their constructor or other methods\n\t\n\t//Painters take a level and its collection of rooms, and paint all the specific tile values\n\tpublic abstract boolean paint(Level level, ArrayList<Room> rooms);\n\t\n\t// Static methods\n\n\tpublic static void set( Level level, int cell, int value ) {\n\t\tlevel.map[cell] = value;\n\t}\n\t\n\tpublic static void set( Level level, int x, int y, int value ) {\n\t\tset( level, x + y * level.width(), value );\n\t}\n\t\n\tpublic static void set( Level level, Point p, int value ) {\n\t\tset( level, p.x, p.y, value );\n\t}\n\t\n\tpublic static void fill( Level level, int x, int y, int w, int h, int value ) {\n\t\t\n\t\tint width = level.width();\n\t\t\n\t\tint pos = y * width + x;\n\t\tfor (int i=y; i < y + h; i++, pos += width) {\n\t\t\tArrays.fill( level.map, pos, pos + w, value );\n\t\t}\n\t}\n\t\n\tpublic static void fill( Level level, Rect rect, int value ) {\n\t\tfill( level, rect.left, rect.top, rect.width(), rect.height(), value );\n\t}\n\t\n\tpublic static void fill( Level level, Rect rect, int m, int value ) {\n\t\tfill( level, rect.left + m, rect.top + m, rect.width() - m*2, rect.height() - m*2, value );\n\t}\n\t\n\tpublic static void fill( Level level, Rect rect, int l, int t, int r, int b, int value ) {\n\t\tfill( level, rect.left + l, rect.top + t, rect.width() - (l + r), rect.height() - (t + b), value );\n\t}\n\t\n\tpublic static void drawLine( Level level, Point from, Point to, int value){\n\t\tfloat x = from.x;\n\t\tfloat y = from.y;\n\t\tfloat dx = to.x - from.x;\n\t\tfloat dy = to.y - from.y;\n\t\t\n\t\tboolean movingbyX = Math.abs(dx) >= Math.abs(dy);\n\t\t//normalize\n\t\tif (movingbyX){\n\t\t\tdy /= Math.abs(dx);\n\t\t\tdx /= Math.abs(dx);\n\t\t} else {\n\t\t\tdx /= Math.abs(dy);\n\t\t\tdy /= Math.abs(dy);\n\t\t}\n\t\t\n\t\tset(level, Math.round(x), Math.round(y), value);\n\t\twhile((movingbyX && to.x != x) || (!movingbyX && to.y != y)){\n\t\t\tx += dx;\n\t\t\ty += dy;\n\t\t\tset(level, Math.round(x), Math.round(y), value);\n\t\t}\n\t}\n\n\tpublic static void fillEllipse(Level level, Rect rect, int value ) {\n\t\tfillEllipse( level, rect.left, rect.top, rect.width(), rect.height(), value );\n\t}\n\n\tpublic static void fillEllipse(Level level, Rect rect, int m, int value ) {\n\t\tfillEllipse( level, rect.left + m, rect.top + m, rect.width() - m*2, rect.height() - m*2, value );\n\t}\n\t\n\tpublic static void fillEllipse(Level level, int x, int y, int w, int h, int value){\n\n\t\t//radii\n\t\tdouble radH = h/2f;\n\t\tdouble radW = w/2f;\n\n\t\t//fills each row of the ellipse from top to bottom\n\t\tfor( int i = 0; i < h; i++){\n\n\t\t\t//y coordinate of the row for determining ellipsis width\n\t\t\t//always want to test the middle of a tile, hence the 0.5 shift\n\t\t\tdouble rowY = -radH + 0.5 + i;\n\n\t\t\t//equation is derived from ellipsis formula: y^2/radH^2 + x^2/radW^2 = 1\n\t\t\t//solves for x and then doubles to get the width\n\t\t\tdouble rowW = 2.0 * Math.sqrt((radW * radW) * (1.0 - (rowY*rowY) / (radH * radH)));\n\n\t\t\t//need to round to nearest even or odd number, depending on width\n\t\t\tif ( w % 2 == 0 ){\n\t\t\t\trowW = Math.round(rowW / 2.0)*2.0;\n\n\t\t\t} else {\n\t\t\t\trowW = Math.floor(rowW / 2.0)*2.0;\n\t\t\t\trowW++;\n\t\t\t}\n\n\t\t\tint cell = x + (w - (int)rowW)/2 + ((y + i) * level.width());\n\t\t\tArrays.fill( level.map, cell, cell + (int)rowW, value );\n\n\t\t}\n\n\t}\n\n\tpublic static void fillDiamond(Level level, Rect rect, int value ) {\n\t\tfillDiamond( level, rect.left, rect.top, rect.width(), rect.height(), value );\n\t}\n\n\tpublic static void fillDiamond(Level level, Rect rect, int m, int value ) {\n\t\tfillDiamond( level, rect.left + m, rect.top + m, rect.width() - m*2, rect.height() - m*2, value );\n\t}\n\n\tpublic static void fillDiamond(Level level, int x, int y, int w, int h, int value){\n\n\t\t//we want the end width to be w, and the width will grow by a total of (h-2 - h%2)\n\t\tint diamondWidth = w - (h-2 - h%2);\n\t\t//but starting width cannot be smaller than 2 on even width, 3 on odd width.\n\t\tdiamondWidth = Math.max(diamondWidth, w%2 == 0 ? 2 : 3);\n\n\t\tfor (int i = 0; i <= h; i++){\n\t\t\tPainter.fill( level, x + (w - diamondWidth)/2, y+i, diamondWidth, h-2*i, value);\n\t\t\tdiamondWidth += 2;\n\t\t\tif (diamondWidth > w) break;\n\t\t}\n\n\t}\n\t\n\tpublic static Point drawInside( Level level, Room room, Point from, int n, int value ) {\n\t\t\n\t\tPoint step = new Point();\n\t\tif (from.x == room.left) {\n\t\t\tstep.set( +1, 0 );\n\t\t} else if (from.x == room.right) {\n\t\t\tstep.set( -1, 0 );\n\t\t} else if (from.y == room.top) {\n\t\t\tstep.set( 0, +1 );\n\t\t} else if (from.y == room.bottom) {\n\t\t\tstep.set( 0, -1 );\n\t\t}\n\t\t\n\t\tPoint p = new Point( from ).offset( step );\n\t\tfor (int i=0; i < n; i++) {\n\t\t\tif (value != -1) {\n\t\t\t\tset( level, p, value );\n\t\t\t}\n\t\t\tp.offset( step );\n\t\t}\n\t\t\n\t\treturn p;\n\t}\n}" }, { "identifier": "Room", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/rooms/Room.java", "snippet": "public abstract class Room extends Rect implements Graph.Node, Bundlable {\n\t\n\tpublic ArrayList<Room> neigbours = new ArrayList<>();\n\tpublic LinkedHashMap<Room, Door> connected = new LinkedHashMap<>();\n\t\n\tpublic int distance;\n\tpublic int price = 1;\n\t\n\tpublic Room(){\n\t\tsuper();\n\t}\n\t\n\tpublic Room( Rect other ){\n\t\tsuper(other);\n\t}\n\t\n\tpublic Room set( Room other ) {\n\t\tsuper.set( other );\n\t\tfor (Room r : other.neigbours){\n\t\t\tneigbours.add(r);\n\t\t\tr.neigbours.remove(other);\n\t\t\tr.neigbours.add(this);\n\t\t}\n\t\tfor (Room r : other.connected.keySet()){\n\t\t\tDoor d = other.connected.get(r);\n\t\t\tr.connected.remove(other);\n\t\t\tr.connected.put(this, d);\n\t\t\tconnected.put(r, d);\n\t\t}\n\t\treturn this;\n\t}\n\t\n\t// **** Spatial logic ****\n\t\n\t//Note: when overriding these YOU MUST store any randomly decided values.\n\t//With the same room and the same parameters these should always return\n\t//the same value over multiple calls, even if there's some randomness initially.\n\tpublic int minWidth(){\n\t\treturn -1;\n\t}\n\tpublic int maxWidth() { return -1; }\n\t\n\tpublic int minHeight() { return -1; }\n\tpublic int maxHeight() { return -1; }\n\t\n\tpublic boolean setSize(){\n\t\treturn setSize(minWidth(), maxWidth(), minHeight(), maxHeight());\n\t}\n\t\n\tpublic boolean forceSize( int w, int h ){\n\t\treturn setSize( w, w, h, h );\n\t}\n\t\n\tpublic boolean setSizeWithLimit( int w, int h ){\n\t\tif ( w < minWidth() || h < minHeight()) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\tsetSize();\n\t\t\t\n\t\t\tif (width() > w || height() > h){\n\t\t\t\tresize(Math.min(width(), w)-1, Math.min(height(), h)-1);\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\tprotected boolean setSize(int minW, int maxW, int minH, int maxH) {\n\t\tif (minW < minWidth()\n\t\t\t\t|| maxW > maxWidth()\n\t\t\t\t|| minH < minHeight()\n\t\t\t\t|| maxH > maxHeight()\n\t\t\t\t|| minW > maxW\n\t\t\t\t|| minH > maxH){\n\t\t\treturn false;\n\t\t} else {\n\t\t\t//subtract one because rooms are inclusive to their right and bottom sides\n\t\t\tresize(Random.NormalIntRange(minW, maxW) - 1,\n\t\t\t\t\tRandom.NormalIntRange(minH, maxH) - 1);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic Point pointInside(Point from, int n){\n\t\tPoint step = new Point(from);\n\t\tif (from.x == left) {\n\t\t\tstep.offset( +n, 0 );\n\t\t} else if (from.x == right) {\n\t\t\tstep.offset( -n, 0 );\n\t\t} else if (from.y == top) {\n\t\t\tstep.offset( 0, +n );\n\t\t} else if (from.y == bottom) {\n\t\t\tstep.offset( 0, -n );\n\t\t}\n\t\treturn step;\n\t}\n\t\n\t//Width and height are increased by 1 because rooms are inclusive to their right and bottom sides\n\t@Override\n\tpublic int width() {\n\t\treturn super.width()+1;\n\t}\n\t\n\t@Override\n\tpublic int height() {\n\t\treturn super.height()+1;\n\t}\n\t\n\tpublic Point random() {\n\t\treturn random( 1 );\n\t}\n\t\n\tpublic Point random( int m ) {\n\t\treturn new Point( Random.IntRange( left + m, right - m ),\n\t\t\t\tRandom.IntRange( top + m, bottom - m ));\n\t}\n\t\n\t//a point is only considered to be inside if it is within the 1 tile perimeter\n\tpublic boolean inside( Point p ) {\n\t\treturn p.x > left && p.y > top && p.x < right && p.y < bottom;\n\t}\n\t\n\tpublic Point center() {\n\t\treturn new Point(\n\t\t\t\t(left + right) / 2 + (((right - left) % 2) == 1 ? Random.Int( 2 ) : 0),\n\t\t\t\t(top + bottom) / 2 + (((bottom - top) % 2) == 1 ? Random.Int( 2 ) : 0) );\n\t}\n\t\n\t\n\t// **** Connection logic ****\n\t\n\tpublic static final int ALL = 0;\n\tpublic static final int LEFT = 1;\n\tpublic static final int TOP = 2;\n\tpublic static final int RIGHT = 3;\n\tpublic static final int BOTTOM = 4;\n\t\n\tpublic int minConnections(int direction){\n\t\tif (direction == ALL) return 1;\n\t\telse return 0;\n\t}\n\t\n\tpublic int curConnections(int direction){\n\t\tif (direction == ALL) {\n\t\t\treturn connected.size();\n\t\t\t\n\t\t} else {\n\t\t\tint total = 0;\n\t\t\tfor (Room r : connected.keySet()){\n\t\t\t\tRect i = intersect( r );\n\t\t\t\tif (direction == LEFT && i.width() == 0 && i.left == left) total++;\n\t\t\t\telse if (direction == TOP && i.height() == 0 && i.top == top) total++;\n\t\t\t\telse if (direction == RIGHT && i.width() == 0 && i.right == right) total++;\n\t\t\t\telse if (direction == BOTTOM && i.height() == 0 && i.bottom == bottom) total++;\n\t\t\t}\n\t\t\treturn total;\n\t\t}\n\t}\n\t\n\tpublic int remConnections(int direction){\n\t\tif (curConnections(ALL) >= maxConnections(ALL)) return 0;\n\t\telse return maxConnections(direction) - curConnections(direction);\n\t}\n\t\n\tpublic int maxConnections(int direction){\n\t\tif (direction == ALL) return 16;\n\t\telse return 4;\n\t}\n\t\n\t//only considers point-specific limits, not direction limits\n\tpublic boolean canConnect(Point p){\n\t\t//point must be along exactly one edge, no corners.\n\t\treturn (p.x == left || p.x == right) != (p.y == top || p.y == bottom);\n\t}\n\t\n\t//only considers direction limits, not point-specific limits\n\tpublic boolean canConnect(int direction){\n\t\treturn remConnections(direction) > 0;\n\t}\n\t\n\t//considers both direction and point limits\n\tpublic boolean canConnect( Room r ){\n\t\tRect i = intersect( r );\n\t\t\n\t\tboolean foundPoint = false;\n\t\tfor (Point p : i.getPoints()){\n\t\t\tif (canConnect(p) && r.canConnect(p)){\n\t\t\t\tfoundPoint = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!foundPoint) return false;\n\t\t\n\t\tif (i.width() == 0 && i.left == left)\n\t\t\treturn canConnect(LEFT) && r.canConnect(RIGHT);\n\t\telse if (i.height() == 0 && i.top == top)\n\t\t\treturn canConnect(TOP) && r.canConnect(BOTTOM);\n\t\telse if (i.width() == 0 && i.right == right)\n\t\t\treturn canConnect(RIGHT) && r.canConnect(LEFT);\n\t\telse if (i.height() == 0 && i.bottom == bottom)\n\t\t\treturn canConnect(BOTTOM) && r.canConnect(TOP);\n\t\telse\n\t\t\treturn false;\n\t}\n\n\tpublic boolean canMerge(Level l, Point p, int mergeTerrain){\n\t\treturn false;\n\t}\n\n\t//can be overriden for special merge logic between rooms\n\tpublic void merge(Level l, Room other, Rect merge, int mergeTerrain){\n\t\tPainter.fill(l, merge, mergeTerrain);\n\t}\n\t\n\tpublic boolean addNeigbour( Room other ) {\n\t\tif (neigbours.contains(other))\n\t\t\treturn true;\n\t\t\n\t\tRect i = intersect( other );\n\t\tif ((i.width() == 0 && i.height() >= 2) ||\n\t\t\t(i.height() == 0 && i.width() >= 2)) {\n\t\t\tneigbours.add( other );\n\t\t\tother.neigbours.add( this );\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic boolean connect( Room room ) {\n\t\tif ((neigbours.contains(room) || addNeigbour(room))\n\t\t\t\t&& !connected.containsKey( room ) && canConnect(room)) {\n\t\t\tconnected.put( room, null );\n\t\t\troom.connected.put( this, null );\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic void clearConnections(){\n\t\tfor (Room r : neigbours){\n\t\t\tr.neigbours.remove(this);\n\t\t}\n\t\tneigbours.clear();\n\t\tfor (Room r : connected.keySet()){\n\t\t\tr.connected.remove(this);\n\t\t}\n\t\tconnected.clear();\n\t}\n\t\n\t// **** Painter Logic ****\n\t\n\tpublic abstract void paint(Level level);\n\t\n\t//whether or not a painter can make its own modifications to a specific point\n\tpublic boolean canPlaceWater(Point p){\n\t\treturn true;\n\t}\n\t\n\tpublic final ArrayList<Point> waterPlaceablePoints(){\n\t\tArrayList<Point> points = new ArrayList<>();\n\t\tfor (int i = left; i <= right; i++) {\n\t\t\tfor (int j = top; j <= bottom; j++) {\n\t\t\t\tPoint p = new Point(i, j);\n\t\t\t\tif (canPlaceWater(p)) points.add(p);\n\t\t\t}\n\t\t}\n\t\treturn points;\n\t}\n\n\t//whether or not a painter can make place grass at a specific point\n\tpublic boolean canPlaceGrass(Point p){\n\t\treturn true;\n\t}\n\n\tpublic final ArrayList<Point> grassPlaceablePoints(){\n\t\tArrayList<Point> points = new ArrayList<>();\n\t\tfor (int i = left; i <= right; i++) {\n\t\t\tfor (int j = top; j <= bottom; j++) {\n\t\t\t\tPoint p = new Point(i, j);\n\t\t\t\tif (canPlaceGrass(p)) points.add(p);\n\t\t\t}\n\t\t}\n\t\treturn points;\n\t}\n\t\n\t//whether or not a painter can place a trap at a specific point\n\tpublic boolean canPlaceTrap(Point p){\n\t\treturn true;\n\t}\n\t\n\tpublic final ArrayList<Point> trapPlaceablePoints(){\n\t\tArrayList<Point> points = new ArrayList<>();\n\t\tfor (int i = left; i <= right; i++) {\n\t\t\tfor (int j = top; j <= bottom; j++) {\n\t\t\t\tPoint p = new Point(i, j);\n\t\t\t\tif (canPlaceTrap(p)) points.add(p);\n\t\t\t}\n\t\t}\n\t\treturn points;\n\t}\n\n\t//whether or not an item can be placed here (usually via randomDropCell)\n\tpublic boolean canPlaceItem(Point p, Level l){\n\t\treturn inside(p);\n\t}\n\n\tpublic final ArrayList<Point> itemPlaceablePoints(Level l){\n\t\tArrayList<Point> points = new ArrayList<>();\n\t\tfor (int i = left; i <= right; i++) {\n\t\t\tfor (int j = top; j <= bottom; j++) {\n\t\t\t\tPoint p = new Point(i, j);\n\t\t\t\tif (canPlaceItem(p, l)) points.add(p);\n\t\t\t}\n\t\t}\n\t\treturn points;\n\t}\n\t\n\t//whether or not a character can be placed here (usually via spawn, tele, or wander)\n\tpublic boolean canPlaceCharacter(Point p, Level l){\n\t\treturn inside(p);\n\t}\n\t\n\tpublic final ArrayList<Point> charPlaceablePoints(Level l){\n\t\tArrayList<Point> points = new ArrayList<>();\n\t\tfor (int i = left; i <= right; i++) {\n\t\t\tfor (int j = top; j <= bottom; j++) {\n\t\t\t\tPoint p = new Point(i, j);\n\t\t\t\tif (canPlaceCharacter(p, l)) points.add(p);\n\t\t\t}\n\t\t}\n\t\treturn points;\n\t}\n\n\t\n\t// **** Graph.Node interface ****\n\n\t@Override\n\tpublic int distance() {\n\t\treturn distance;\n\t}\n\n\t@Override\n\tpublic void distance( int value ) {\n\t\tdistance = value;\n\t}\n\t\n\t@Override\n\tpublic int price() {\n\t\treturn price;\n\t}\n\n\t@Override\n\tpublic void price( int value ) {\n\t\tprice = value;\n\t}\n\n\t@Override\n\tpublic Collection<Room> edges() {\n\t\tArrayList<Room> edges = new ArrayList<>();\n\t\tfor( Room r : connected.keySet()){\n\t\t\tDoor d = connected.get(r);\n\t\t\t//for the purposes of path building, ignore all doors that are locked, blocked, or hidden\n\t\t\tif (d.type == Door.Type.EMPTY || d.type == Door.Type.TUNNEL\n\t\t\t\t\t|| d.type == Door.Type.UNLOCKED || d.type == Door.Type.REGULAR){\n\t\t\t\tedges.add(r);\n\t\t\t}\n\t\t}\n\t\treturn edges;\n\t}\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tbundle.put( \"left\", left );\n\t\tbundle.put( \"top\", top );\n\t\tbundle.put( \"right\", right );\n\t\tbundle.put( \"bottom\", bottom );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tleft = bundle.getInt( \"left\" );\n\t\ttop = bundle.getInt( \"top\" );\n\t\tright = bundle.getInt( \"right\" );\n\t\tbottom = bundle.getInt( \"bottom\" );\n\t}\n\n\t//FIXME currently connections and neighbours are not preserved on load\n\tpublic void onLevelLoad( Level level ){\n\t\t//does nothing by default\n\t}\n\t\n\tpublic static class Door extends Point implements Bundlable {\n\t\t\n\t\tpublic enum Type {\n\t\t\tEMPTY, TUNNEL, WATER, REGULAR, UNLOCKED, HIDDEN, BARRICADE, LOCKED, CRYSTAL, WALL\n\t\t}\n\t\tpublic Type type = Type.EMPTY;\n\t\t\n\t\tpublic Door(){\n\t\t}\n\t\t\n\t\tpublic Door( Point p ){\n\t\t\tsuper(p);\n\t\t}\n\t\t\n\t\tpublic Door( int x, int y ) {\n\t\t\tsuper( x, y );\n\t\t}\n\n\t\tprivate boolean typeLocked = false;\n\n\t\tpublic void lockTypeChanges( boolean lock ){\n\t\t\ttypeLocked = lock;\n\t\t}\n\n\t\tpublic void set( Type type ) {\n\t\t\tif (!typeLocked && type.compareTo( this.type ) > 0) {\n\t\t\t\tthis.type = type;\n\t\t\t}\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void storeInBundle(Bundle bundle) {\n\t\t\tbundle.put(\"x\", x);\n\t\t\tbundle.put(\"y\", y);\n\t\t\tbundle.put(\"type\", type);\n\t\t\tbundle.put(\"type_locked\", typeLocked);\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void restoreFromBundle(Bundle bundle) {\n\t\t\tx = bundle.getInt(\"x\");\n\t\t\ty = bundle.getInt(\"y\");\n\t\t\ttype = bundle.getEnum(\"type\", Type.class);\n\t\t\ttypeLocked = bundle.getBoolean(\"type_locked\");\n\t\t}\n\t}\n}" }, { "identifier": "EmptyRoom", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/rooms/standard/EmptyRoom.java", "snippet": "public class EmptyRoom extends StandardRoom {\n\t\n\t@Override\n\tpublic void paint(Level level) {\n\t\tPainter.fill( level, this, Terrain.WALL );\n\t\tPainter.fill( level, this, 1 , Terrain.EMPTY );\n\t\t\n\t\tfor (Door door : connected.values()) {\n\t\t\tdoor.set( Door.Type.REGULAR );\n\t\t}\n\t}\n}" }, { "identifier": "Messages", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/messages/Messages.java", "snippet": "public class Messages {\n\n\tprivate static ArrayList<I18NBundle> bundles;\n\tprivate static Languages lang;\n\tprivate static Locale locale;\n\n\tpublic static final String NO_TEXT_FOUND = \"!!!NO TEXT FOUND!!!\";\n\n\tpublic static Languages lang(){\n\t\treturn lang;\n\t}\n\n\tpublic static Locale locale(){\n\t\treturn locale;\n\t}\n\n\t/**\n\t * Setup Methods\n\t */\n\n\tprivate static String[] prop_files = new String[]{\n\t\t\tAssets.Messages.ACTORS,\n\t\t\tAssets.Messages.ITEMS,\n\t\t\tAssets.Messages.JOURNAL,\n\t\t\tAssets.Messages.LEVELS,\n\t\t\tAssets.Messages.MISC,\n\t\t\tAssets.Messages.PLANTS,\n\t\t\tAssets.Messages.SCENES,\n\t\t\tAssets.Messages.UI,\n\t\t\tAssets.Messages.WINDOWS\n\t};\n\n\tstatic{\n\t\tsetup(SPDSettings.language());\n\t}\n\n\tpublic static void setup( Languages lang ){\n\t\t//seeing as missing keys are part of our process, this is faster than throwing an exception\n\t\tI18NBundle.setExceptionOnMissingKey(false);\n\n\t\t//store language and locale info for various string logic\n\t\tMessages.lang = lang;\n\t\tif (lang == Languages.ENGLISH){\n\t\t\tlocale = Locale.ENGLISH;\n\t\t} else {\n\t\t\tlocale = new Locale(lang.code());\n\t\t}\n\n\t\t//strictly match the language code when fetching bundles however\n\t\tbundles = new ArrayList<>();\n\t\tLocale bundleLocal = new Locale(lang.code());\n\t\tfor (String file : prop_files) {\n\t\t\tbundles.add(I18NBundle.createBundle(Gdx.files.internal(file), bundleLocal));\n\t\t}\n\t}\n\n\n\n\t/**\n\t * Resource grabbing methods\n\t */\n\n\tpublic static String get(String key, Object...args){\n\t\treturn get(null, key, args);\n\t}\n\n\tpublic static String get(Object o, String k, Object...args){\n\t\treturn get(o.getClass(), k, args);\n\t}\n\n\tpublic static String get(Class c, String k, Object...args){\n\t\tString key;\n\t\tif (c != null){\n\t\t\tkey = c.getName().replace(\"com.shatteredpixel.shatteredpixeldungeon.\", \"\");\n\t\t\tkey += \".\" + k;\n\t\t} else\n\t\t\tkey = k;\n\n\t\tString value = getFromBundle(key.toLowerCase(Locale.ENGLISH));\n\t\tif (value != null){\n\t\t\tif (args.length > 0) return format(value, args);\n\t\t\telse return value;\n\t\t} else {\n\t\t\t//this is so child classes can inherit properties from their parents.\n\t\t\t//in cases where text is commonly grabbed as a utility from classes that aren't mean to be instantiated\n\t\t\t//(e.g. flavourbuff.dispTurns()) using .class directly is probably smarter to prevent unnecessary recursive calls.\n\t\t\tif (c != null && c.getSuperclass() != null){\n\t\t\t\treturn get(c.getSuperclass(), k, args);\n\t\t\t} else {\n\t\t\t\treturn NO_TEXT_FOUND;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static String getFromBundle(String key){\n\t\tString result;\n\t\tfor (I18NBundle b : bundles){\n\t\t\tresult = b.get(key);\n\t\t\t//if it isn't the return string for no key found, return it\n\t\t\tif (result.length() != key.length()+6 || !result.contains(key)){\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\n\n\t/**\n\t * String Utility Methods\n\t */\n\n\tpublic static String format( String format, Object...args ) {\n\t\ttry {\n\t\t\treturn String.format(Locale.ENGLISH, format, args);\n\t\t} catch (IllegalFormatException e) {\n\t\t\tShatteredPixelDungeon.reportException( new Exception(\"formatting error for the string: \" + format, e) );\n\t\t\treturn format;\n\t\t}\n\t}\n\n\tprivate static HashMap<String, DecimalFormat> formatters = new HashMap<>();\n\n\tpublic static String decimalFormat( String format, double number ){\n\t\tif (!formatters.containsKey(format)){\n\t\t\tformatters.put(format, new DecimalFormat(format, DecimalFormatSymbols.getInstance(Locale.ENGLISH)));\n\t\t}\n\t\treturn formatters.get(format).format(number);\n\t}\n\n\tpublic static String capitalize( String str ){\n\t\tif (str.length() == 0) return str;\n\t\telse return str.substring( 0, 1 ).toUpperCase(locale) + str.substring( 1 );\n\t}\n\n\t//Words which should not be capitalized in title case, mostly prepositions which appear ingame\n\t//This list is not comprehensive!\n\tprivate static final HashSet<String> noCaps = new HashSet<>(\n\t\t\tArrays.asList(\"a\", \"an\", \"and\", \"of\", \"by\", \"to\", \"the\", \"x\", \"for\")\n\t);\n\n\tpublic static String titleCase( String str ){\n\t\t//English capitalizes every word except for a few exceptions\n\t\tif (lang == Languages.ENGLISH){\n\t\t\tString result = \"\";\n\t\t\t//split by any unicode space character\n\t\t\tfor (String word : str.split(\"(?<=\\\\p{Zs})\")){\n\t\t\t\tif (noCaps.contains(word.trim().toLowerCase(Locale.ENGLISH).replaceAll(\":|[0-9]\", \"\"))){\n\t\t\t\t\tresult += word;\n\t\t\t\t} else {\n\t\t\t\t\tresult += capitalize(word);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//first character is always capitalized.\n\t\t\treturn capitalize(result);\n\t\t}\n\n\t\t//Otherwise, use sentence case\n\t\treturn capitalize(str);\n\t}\n\n\tpublic static String upperCase( String str ){\n\t\treturn str.toUpperCase(locale);\n\t}\n\n\tpublic static String lowerCase( String str ){\n\t\treturn str.toLowerCase(locale);\n\t}\n}" }, { "identifier": "GameScene", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/scenes/GameScene.java", "snippet": "public class GameScene extends PixelScene {\n\n\tstatic GameScene scene;\n\n\tprivate SkinnedBlock water;\n\tprivate DungeonTerrainTilemap tiles;\n\tprivate GridTileMap visualGrid;\n\tprivate TerrainFeaturesTilemap terrainFeatures;\n\tprivate RaisedTerrainTilemap raisedTerrain;\n\tprivate DungeonWallsTilemap walls;\n\tprivate WallBlockingTilemap wallBlocking;\n\tprivate FogOfWar fog;\n\tprivate HeroSprite hero;\n\n\tprivate MenuPane menu;\n\tprivate StatusPane status;\n\n\tprivate BossHealthBar boss;\n\n\tprivate GameLog log;\n\t\n\tprivate static CellSelector cellSelector;\n\t\n\tprivate Group terrain;\n\tprivate Group customTiles;\n\tprivate Group levelVisuals;\n\tprivate Group levelWallVisuals;\n\tprivate Group customWalls;\n\tprivate Group ripples;\n\tprivate Group plants;\n\tprivate Group traps;\n\tprivate Group heaps;\n\tprivate Group mobs;\n\tprivate Group floorEmitters;\n\tprivate Group emitters;\n\tprivate Group effects;\n\tprivate Group gases;\n\tprivate Group spells;\n\tprivate Group statuses;\n\tprivate Group emoicons;\n\tprivate Group overFogEffects;\n\tprivate Group healthIndicators;\n\n\tprivate InventoryPane inventory;\n\tprivate static boolean invVisible = true;\n\n\tprivate Toolbar toolbar;\n\tprivate Toast prompt;\n\n\tprivate AttackIndicator attack;\n\tprivate LootIndicator loot;\n\tprivate ActionIndicator action;\n\tprivate ResumeIndicator resume;\n\n\t{\n\t\tinGameScene = true;\n\t}\n\t\n\t@Override\n\tpublic void create() {\n\t\t\n\t\tif (Dungeon.hero == null || Dungeon.level == null){\n\t\t\tShatteredPixelDungeon.switchNoFade(TitleScene.class);\n\t\t\treturn;\n\t\t}\n\n\t\tDungeon.level.playLevelMusic();\n\n\t\tSPDSettings.lastClass(Dungeon.hero.heroClass.ordinal());\n\t\t\n\t\tsuper.create();\n\t\tCamera.main.zoom( GameMath.gate(minZoom, defaultZoom + SPDSettings.zoom(), maxZoom));\n\t\tCamera.main.edgeScroll.set(1);\n\n\t\tswitch (SPDSettings.cameraFollow()) {\n\t\t\tcase 4: default: Camera.main.setFollowDeadzone(0); break;\n\t\t\tcase 3: Camera.main.setFollowDeadzone(0.2f); break;\n\t\t\tcase 2: Camera.main.setFollowDeadzone(0.5f); break;\n\t\t\tcase 1: Camera.main.setFollowDeadzone(0.9f); break;\n\t\t}\n\n\t\tscene = this;\n\n\t\tterrain = new Group();\n\t\tadd( terrain );\n\n\t\twater = new SkinnedBlock(\n\t\t\tDungeon.level.width() * DungeonTilemap.SIZE,\n\t\t\tDungeon.level.height() * DungeonTilemap.SIZE,\n\t\t\tDungeon.level.waterTex() ){\n\n\t\t\t@Override\n\t\t\tprotected NoosaScript script() {\n\t\t\t\treturn NoosaScriptNoLighting.get();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void draw() {\n\t\t\t\t//water has no alpha component, this improves performance\n\t\t\t\tBlending.disable();\n\t\t\t\tsuper.draw();\n\t\t\t\tBlending.enable();\n\t\t\t}\n\t\t};\n\t\twater.autoAdjust = true;\n\t\tterrain.add( water );\n\n\t\tripples = new Group();\n\t\tterrain.add( ripples );\n\n\t\tDungeonTileSheet.setupVariance(Dungeon.level.map.length, Dungeon.seedCurDepth());\n\t\t\n\t\ttiles = new DungeonTerrainTilemap();\n\t\tterrain.add( tiles );\n\n\t\tcustomTiles = new Group();\n\t\tterrain.add(customTiles);\n\n\t\tfor( CustomTilemap visual : Dungeon.level.customTiles){\n\t\t\taddCustomTile(visual);\n\t\t}\n\n\t\tvisualGrid = new GridTileMap();\n\t\tterrain.add( visualGrid );\n\n\t\tterrainFeatures = new TerrainFeaturesTilemap(Dungeon.level.plants, Dungeon.level.traps);\n\t\tterrain.add(terrainFeatures);\n\t\t\n\t\tlevelVisuals = Dungeon.level.addVisuals();\n\t\tadd(levelVisuals);\n\n\t\tfloorEmitters = new Group();\n\t\tadd(floorEmitters);\n\n\t\theaps = new Group();\n\t\tadd( heaps );\n\t\t\n\t\tfor ( Heap heap : Dungeon.level.heaps.valueList() ) {\n\t\t\taddHeapSprite( heap );\n\t\t}\n\n\t\temitters = new Group();\n\t\teffects = new Group();\n\t\thealthIndicators = new Group();\n\t\temoicons = new Group();\n\t\toverFogEffects = new Group();\n\t\t\n\t\tmobs = new Group();\n\t\tadd( mobs );\n\n\t\thero = new HeroSprite();\n\t\thero.place( Dungeon.hero.pos );\n\t\thero.updateArmor();\n\t\tmobs.add( hero );\n\t\t\n\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\taddMobSprite( mob );\n\t\t}\n\t\t\n\t\traisedTerrain = new RaisedTerrainTilemap();\n\t\tadd( raisedTerrain );\n\n\t\twalls = new DungeonWallsTilemap();\n\t\tadd(walls);\n\n\t\tcustomWalls = new Group();\n\t\tadd(customWalls);\n\n\t\tfor( CustomTilemap visual : Dungeon.level.customWalls){\n\t\t\taddCustomWall(visual);\n\t\t}\n\n\t\tlevelWallVisuals = Dungeon.level.addWallVisuals();\n\t\tadd( levelWallVisuals );\n\n\t\twallBlocking = new WallBlockingTilemap();\n\t\tadd (wallBlocking);\n\n\t\tadd( emitters );\n\t\tadd( effects );\n\n\t\tgases = new Group();\n\t\tadd( gases );\n\n\t\tfor (Blob blob : Dungeon.level.blobs.values()) {\n\t\t\tblob.emitter = null;\n\t\t\taddBlobSprite( blob );\n\t\t}\n\n\n\t\tfog = new FogOfWar( Dungeon.level.width(), Dungeon.level.height() );\n\t\tadd( fog );\n\n\t\tspells = new Group();\n\t\tadd( spells );\n\n\t\tadd(overFogEffects);\n\t\t\n\t\tstatuses = new Group();\n\t\tadd( statuses );\n\t\t\n\t\tadd( healthIndicators );\n\t\t//always appears ontop of other health indicators\n\t\tadd( new TargetHealthIndicator() );\n\t\t\n\t\tadd( emoicons );\n\t\t\n\t\tadd( cellSelector = new CellSelector( tiles ) );\n\n\t\tint uiSize = SPDSettings.interfaceSize();\n\n\t\tmenu = new MenuPane();\n\t\tmenu.camera = uiCamera;\n\t\tmenu.setPos( uiCamera.width-MenuPane.WIDTH, uiSize > 0 ? 0 : 1);\n\t\tadd(menu);\n\n\t\tstatus = new StatusPane( SPDSettings.interfaceSize() > 0 );\n\t\tstatus.camera = uiCamera;\n\t\tstatus.setRect(0, uiSize > 0 ? uiCamera.height-39 : 0, uiCamera.width, 0 );\n\t\tadd(status);\n\n\t\tboss = new BossHealthBar();\n\t\tboss.camera = uiCamera;\n\t\tboss.setPos( 6 + (uiCamera.width - boss.width())/2, 20);\n\t\tadd(boss);\n\n\t\tresume = new ResumeIndicator();\n\t\tresume.camera = uiCamera;\n\t\tadd( resume );\n\n\t\taction = new ActionIndicator();\n\t\taction.camera = uiCamera;\n\t\tadd( action );\n\n\t\tloot = new LootIndicator();\n\t\tloot.camera = uiCamera;\n\t\tadd( loot );\n\n\t\tattack = new AttackIndicator();\n\t\tattack.camera = uiCamera;\n\t\tadd( attack );\n\n\t\tlog = new GameLog();\n\t\tlog.camera = uiCamera;\n\t\tlog.newLine();\n\t\tadd( log );\n\n\t\tif (uiSize > 0){\n\t\t\tbringToFront(status);\n\t\t}\n\n\t\ttoolbar = new Toolbar();\n\t\ttoolbar.camera = uiCamera;\n\t\tadd( toolbar );\n\n\t\tif (uiSize == 2) {\n\t\t\tinventory = new InventoryPane();\n\t\t\tinventory.camera = uiCamera;\n\t\t\tinventory.setPos(uiCamera.width - inventory.width(), uiCamera.height - inventory.height());\n\t\t\tadd(inventory);\n\n\t\t\ttoolbar.setRect( 0, uiCamera.height - toolbar.height() - inventory.height(), uiCamera.width, toolbar.height() );\n\t\t} else {\n\t\t\ttoolbar.setRect( 0, uiCamera.height - toolbar.height(), uiCamera.width, toolbar.height() );\n\t\t}\n\n\t\tlayoutTags();\n\t\t\n\t\tswitch (InterlevelScene.mode) {\n\t\t\tcase RESURRECT:\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TELEPORT);\n\t\t\t\tScrollOfTeleportation.appearVFX( Dungeon.hero );\n\t\t\t\tSpellSprite.show(Dungeon.hero, SpellSprite.ANKH);\n\t\t\t\tnew Flare( 5, 16 ).color( 0xFFFF00, true ).show( hero, 4f ) ;\n\t\t\t\tbreak;\n\t\t\tcase RETURN:\n\t\t\t\tScrollOfTeleportation.appearVFX( Dungeon.hero );\n\t\t\t\tbreak;\n\t\t\tcase DESCEND:\n\t\t\tcase FALL:\n\t\t\t\tif (Dungeon.depth == Statistics.deepestFloor){\n\t\t\t\t\tswitch (Dungeon.depth) {\n\t\t\t\t\t\tcase 1: case 6: case 11: case 16: case 21:\n\t\t\t\t\t\t\tint region = (Dungeon.depth+4)/5;\n\t\t\t\t\t\t\tif (!Document.INTROS.isPageRead(region)) {\n\t\t\t\t\t\t\t\tadd(new WndStory(Document.INTROS.pageBody(region)).setDelays(0.6f, 1.4f));\n\t\t\t\t\t\t\t\tDocument.INTROS.readPage(region);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (Dungeon.hero.isAlive()) {\n\t\t\t\t\tBadges.validateNoKilling();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\n\t\tArrayList<Item> dropped = Dungeon.droppedItems.get( Dungeon.depth );\n\t\tif (dropped != null) {\n\t\t\tfor (Item item : dropped) {\n\t\t\t\tint pos = Dungeon.level.randomRespawnCell( null );\n\t\t\t\tif (pos == -1) pos = Dungeon.level.entrance();\n\t\t\t\tif (item instanceof Potion) {\n\t\t\t\t\t((Potion) item).shatter(pos);\n\t\t\t\t} else if (item instanceof Plant.Seed && !Dungeon.isChallenged(Challenges.NO_HERBALISM)) {\n\t\t\t\t\tDungeon.level.plant((Plant.Seed) item, pos);\n\t\t\t\t} else if (item instanceof Honeypot) {\n\t\t\t\t\tDungeon.level.drop(((Honeypot) item).shatter(null, pos), pos);\n\t\t\t\t} else {\n\t\t\t\t\tDungeon.level.drop(item, pos);\n\t\t\t\t}\n\t\t\t}\n\t\t\tDungeon.droppedItems.remove( Dungeon.depth );\n\t\t}\n\n\t\tDungeon.hero.next();\n\n\t\tswitch (InterlevelScene.mode){\n\t\t\tcase FALL: case DESCEND: case CONTINUE:\n\t\t\t\tCamera.main.snapTo(hero.center().x, hero.center().y - DungeonTilemap.SIZE * (defaultZoom/Camera.main.zoom));\n\t\t\t\tbreak;\n\t\t\tcase ASCEND:\n\t\t\t\tCamera.main.snapTo(hero.center().x, hero.center().y + DungeonTilemap.SIZE * (defaultZoom/Camera.main.zoom));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tCamera.main.snapTo(hero.center().x, hero.center().y);\n\t\t}\n\t\tCamera.main.panTo(hero.center(), 2.5f);\n\n\t\tif (InterlevelScene.mode != InterlevelScene.Mode.NONE) {\n\t\t\tif (Dungeon.depth == Statistics.deepestFloor\n\t\t\t\t\t&& (InterlevelScene.mode == InterlevelScene.Mode.DESCEND || InterlevelScene.mode == InterlevelScene.Mode.FALL)) {\n\t\t\t\tGLog.h(Messages.get(this, \"descend\"), Dungeon.depth);\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.DESCEND);\n\t\t\t\t\n\t\t\t\tfor (Char ch : Actor.chars()){\n\t\t\t\t\tif (ch instanceof DriedRose.GhostHero){\n\t\t\t\t\t\t((DriedRose.GhostHero) ch).sayAppeared();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tint spawnersAbove = Statistics.spawnersAlive;\n\t\t\t\tif (spawnersAbove > 0 && Dungeon.depth <= 25) {\n\t\t\t\t\tfor (Mob m : Dungeon.level.mobs) {\n\t\t\t\t\t\tif (m instanceof DemonSpawner && ((DemonSpawner) m).spawnRecorded) {\n\t\t\t\t\t\t\tspawnersAbove--;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (spawnersAbove > 0) {\n\t\t\t\t\t\tif (Dungeon.bossLevel()) {\n\t\t\t\t\t\t\tGLog.n(Messages.get(this, \"spawner_warn_final\"));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tGLog.n(Messages.get(this, \"spawner_warn\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t} else if (InterlevelScene.mode == InterlevelScene.Mode.RESET) {\n\t\t\t\tGLog.h(Messages.get(this, \"warp\"));\n\t\t\t} else if (InterlevelScene.mode == InterlevelScene.Mode.RESURRECT) {\n\t\t\t\tGLog.h(Messages.get(this, \"resurrect\"), Dungeon.depth);\n\t\t\t} else {\n\t\t\t\tGLog.h(Messages.get(this, \"return\"), Dungeon.depth);\n\t\t\t}\n\n\t\t\tif (Dungeon.hero.hasTalent(Talent.ROGUES_FORESIGHT)\n\t\t\t\t\t&& Dungeon.level instanceof RegularLevel && Dungeon.branch == 0){\n\t\t\t\tint reqSecrets = Dungeon.level.feeling == Level.Feeling.SECRETS ? 2 : 1;\n\t\t\t\tfor (Room r : ((RegularLevel) Dungeon.level).rooms()){\n\t\t\t\t\tif (r instanceof SecretRoom) reqSecrets--;\n\t\t\t\t}\n\n\t\t\t\t//50%/75% chance, use level's seed so that we get the same result for the same level\n\t\t\t\t//offset seed slightly to avoid output patterns\n\t\t\t\tRandom.pushGenerator(Dungeon.seedCurDepth()+1);\n\t\t\t\t\tif (reqSecrets <= 0 && Random.Int(4) <= Dungeon.hero.pointsInTalent(Talent.ROGUES_FORESIGHT)){\n\t\t\t\t\t\tGLog.p(Messages.get(this, \"secret_hint\"));\n\t\t\t\t\t}\n\t\t\t\tRandom.popGenerator();\n\t\t\t}\n\n\t\t\tboolean unspentTalents = false;\n\t\t\tfor (int i = 1; i <= Dungeon.hero.talents.size(); i++){\n\t\t\t\tif (Dungeon.hero.talentPointsAvailable(i) > 0){\n\t\t\t\t\tunspentTalents = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (unspentTalents){\n\t\t\t\tGLog.newLine();\n\t\t\t\tGLog.w( Messages.get(Dungeon.hero, \"unspent\") );\n\t\t\t\tStatusPane.talentBlink = 10f;\n\t\t\t\tWndHero.lastIdx = 1;\n\t\t\t}\n\n\t\t\tswitch (Dungeon.level.feeling) {\n\t\t\t\tcase CHASM: GLog.w(Messages.get(this, \"chasm\")); break;\n\t\t\t\tcase WATER: GLog.w(Messages.get(this, \"water\")); break;\n\t\t\t\tcase GRASS: GLog.w(Messages.get(this, \"grass\")); break;\n\t\t\t\tcase DARK: GLog.w(Messages.get(this, \"dark\")); break;\n\t\t\t\tcase LARGE: GLog.w(Messages.get(this, \"large\")); break;\n\t\t\t\tcase TRAPS: GLog.w(Messages.get(this, \"traps\")); break;\n\t\t\t\tcase SECRETS: GLog.w(Messages.get(this, \"secrets\")); break;\n\t\t\t}\n\n\t\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\t\tif (!mob.buffs(ChampionEnemy.class).isEmpty()) {\n\t\t\t\t\tGLog.w(Messages.get(ChampionEnemy.class, \"warn\"));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Dungeon.hero.buff(AscensionChallenge.class) != null){\n\t\t\t\tDungeon.hero.buff(AscensionChallenge.class).saySwitch();\n\t\t\t}\n\n\t\t\tif (Dungeon.hero.buff(OldAmulet.TempleCurse.class) != null) {\n\t\t\t\tDungeon.hero.buff(OldAmulet.TempleCurse.class).saySwitch();\n\t\t\t\tif (Dungeon.branch == 0) {\n\t\t\t\t\tfor (LevelTransition transition : Dungeon.level.transitions) {\n\t\t\t\t\t\tif (transition.type == LevelTransition.Type.BRANCH_EXIT && transition.destBranch == 2) {\n\t\t\t\t\t\t\tint cell = transition.cell();\n\t\t\t\t\t\t\tLevel.set(cell, Terrain.WALL);\n\t\t\t\t\t\t\tGameScene.updateMap(cell);\n\t\t\t\t\t\t\tif (Dungeon.level.heroFOV[ cell ]) {\n\t\t\t\t\t\t\t\tCellEmitter.get( cell - Dungeon.level.width() ).start(Speck.factory(Speck.ROCK), 0.07f, 10);\n\n\t\t\t\t\t\t\t\tPixelScene.shake(3, 0.7f);\n\t\t\t\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.ROCKS);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tint targetCell = cell+Dungeon.level.width();\n\t\t\t\t\t\t\tActor.add(new Pushing(Dungeon.hero, cell, targetCell, new Callback() {\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\t\t\t\tDungeon.hero.pos = targetCell;\n\t\t\t\t\t\t\t\t\tDungeon.hero.move(targetCell);\n\t\t\t\t\t\t\t\t\tDungeon.level.occupyCell(Dungeon.hero);\n\t\t\t\t\t\t\t\t\tDungeon.observe();\n\t\t\t\t\t\t\t\t\tGameScene.updateFog();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\tDungeon.level.transitions.remove(transition);\n\n\t\t\t\t\t\t\tDungeon.hero.busy();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tDungeon.hero.buff(OldAmulet.TempleCurse.class).detach();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tInterlevelScene.mode = InterlevelScene.Mode.NONE;\n\n\t\t\t\n\t\t}\n\n\t\t//Tutorial\n\t\tif (SPDSettings.intro()){\n\n\t\t\tif (Document.ADVENTURERS_GUIDE.isPageFound(Document.GUIDE_INTRO)){\n\t\t\t\tGLog.p(Messages.get(GameScene.class, \"tutorial_guidebook\"));\n\t\t\t\tflashForDocument(Document.ADVENTURERS_GUIDE, Document.GUIDE_INTRO);\n\t\t\t} else {\n\t\t\t\tif (ControllerHandler.isControllerConnected()) {\n\t\t\t\t\tGLog.p(Messages.get(GameScene.class, \"tutorial_move_controller\"));\n\t\t\t\t} else if (SPDSettings.interfaceSize() == 0) {\n\t\t\t\t\tGLog.p(Messages.get(GameScene.class, \"tutorial_move_mobile\"));\n\t\t\t\t} else {\n\t\t\t\t\tGLog.p(Messages.get(GameScene.class, \"tutorial_move_desktop\"));\n\t\t\t\t}\n\t\t\t}\n\t\t\ttoolbar.visible = toolbar.active = false;\n\t\t\tstatus.visible = status.active = false;\n\t\t\tif (inventory != null) inventory.visible = inventory.active = false;\n\t\t}\n\n\t\tif (!SPDSettings.intro() &&\n\t\t\t\tRankings.INSTANCE.totalNumber > 0 &&\n\t\t\t\t!Document.ADVENTURERS_GUIDE.isPageRead(Document.GUIDE_DIEING)){\n\t\t\tGLog.p(Messages.get(Guidebook.class, \"hint\"));\n\t\t\tGameScene.flashForDocument(Document.ADVENTURERS_GUIDE, Document.GUIDE_DIEING);\n\t\t}\n\n\t\tif (!invVisible) toggleInvPane();\n\t\tfadeIn();\n\n\t\t//re-show WndResurrect if needed\n\t\tif (!Dungeon.hero.isAlive()){\n\t\t\t//check if hero has an unblessed ankh\n\t\t\tAnkh ankh = null;\n\t\t\tfor (Ankh i : Dungeon.hero.belongings.getAllItems(Ankh.class)){\n\t\t\t\tif (!i.isBlessed()){\n\t\t\t\t\tankh = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ankh != null && GamesInProgress.gameExists(GamesInProgress.curSlot)) {\n\t\t\t\tadd(new WndResurrect(ankh));\n\t\t\t} else {\n\t\t\t\tgameOver();\n\t\t\t}\n\t\t}\n\n\t}\n\t\n\tpublic void destroy() {\n\t\t\n\t\t//tell the actor thread to finish, then wait for it to complete any actions it may be doing.\n\t\tif (!waitForActorThread( 4500, true )){\n\t\t\tThrowable t = new Throwable();\n\t\t\tt.setStackTrace(actorThread.getStackTrace());\n\t\t\tthrow new RuntimeException(\"timeout waiting for actor thread! \", t);\n\t\t}\n\n\t\tEmitter.freezeEmitters = false;\n\t\t\n\t\tscene = null;\n\t\tBadges.saveGlobal();\n\t\tJournal.saveGlobal();\n\t\t\n\t\tsuper.destroy();\n\t}\n\t\n\tpublic static void endActorThread(){\n\t\tif (actorThread != null && actorThread.isAlive()){\n\t\t\tActor.keepActorThreadAlive = false;\n\t\t\tactorThread.interrupt();\n\t\t}\n\t}\n\n\tpublic boolean waitForActorThread(int msToWait, boolean interrupt){\n\t\tif (actorThread == null || !actorThread.isAlive()) {\n\t\t\treturn true;\n\t\t}\n\t\tsynchronized (actorThread) {\n\t\t\tif (interrupt) actorThread.interrupt();\n\t\t\ttry {\n\t\t\t\tactorThread.wait(msToWait);\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t\t}\n\t\t\treturn !Actor.processing();\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic synchronized void onPause() {\n\t\ttry {\n\t\t\tDungeon.saveAll();\n\t\t\tBadges.saveGlobal();\n\t\t\tJournal.saveGlobal();\n\t\t} catch (IOException e) {\n\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t}\n\t}\n\n\tprivate static Thread actorThread;\n\t\n\t//sometimes UI changes can be prompted by the actor thread.\n\t// We queue any removed element destruction, rather than destroying them in the actor thread.\n\tprivate ArrayList<Gizmo> toDestroy = new ArrayList<>();\n\n\t//the actor thread processes at a maximum of 60 times a second\n\t//this caps the speed of resting for higher refresh rate displays\n\tprivate float notifyDelay = 1/60f;\n\n\tpublic static boolean updateItemDisplays = false;\n\n\tpublic static boolean tagDisappeared = false;\n\tpublic static boolean updateTags = false;\n\t\n\t@Override\n\tpublic synchronized void update() {\n\t\tlastOffset = null;\n\n\t\tif (updateItemDisplays){\n\t\t\tupdateItemDisplays = false;\n\t\t\tQuickSlotButton.refresh();\n\t\t\tInventoryPane.refresh();\n\t\t}\n\n\t\tif (Dungeon.hero == null || scene == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tsuper.update();\n\n\t\tif (notifyDelay > 0) notifyDelay -= Game.elapsed;\n\n\t\tif (!Emitter.freezeEmitters) water.offset( 0, -5 * Game.elapsed );\n\n\t\tif (!Actor.processing() && Dungeon.hero.isAlive()) {\n\t\t\tif (actorThread == null || !actorThread.isAlive()) {\n\t\t\t\t\n\t\t\t\tactorThread = new Thread() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\tActor.process();\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\t//if cpu cores are limited, game should prefer drawing the current frame\n\t\t\t\tif (Runtime.getRuntime().availableProcessors() == 1) {\n\t\t\t\t\tactorThread.setPriority(Thread.NORM_PRIORITY - 1);\n\t\t\t\t}\n\t\t\t\tactorThread.setName(\"SHPD Actor Thread\");\n\t\t\t\tThread.currentThread().setName(\"SHPD Render Thread\");\n\t\t\t\tActor.keepActorThreadAlive = true;\n\t\t\t\tactorThread.start();\n\t\t\t} else if (notifyDelay <= 0f) {\n\t\t\t\tnotifyDelay += 1/60f;\n\t\t\t\tsynchronized (actorThread) {\n\t\t\t\t\tactorThread.notify();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.hero.ready && Dungeon.hero.paralysed == 0) {\n\t\t\tlog.newLine();\n\t\t}\n\n\t\tif (updateTags){\n\t\t\ttagAttack = attack.active;\n\t\t\ttagLoot = loot.visible;\n\t\t\ttagAction = action.visible;\n\t\t\ttagResume = resume.visible;\n\n\t\t\tlayoutTags();\n\n\t\t} else if (tagAttack != attack.active ||\n\t\t\t\ttagLoot != loot.visible ||\n\t\t\t\ttagAction != action.visible ||\n\t\t\t\ttagResume != resume.visible) {\n\n\t\t\tboolean tagAppearing = (attack.active && !tagAttack) ||\n\t\t\t\t\t\t\t\t\t(loot.visible && !tagLoot) ||\n\t\t\t\t\t\t\t\t\t(action.visible && !tagAction) ||\n\t\t\t\t\t\t\t\t\t(resume.visible && !tagResume);\n\n\t\t\ttagAttack = attack.active;\n\t\t\ttagLoot = loot.visible;\n\t\t\ttagAction = action.visible;\n\t\t\ttagResume = resume.visible;\n\n\t\t\t//if a new tag appears, re-layout tags immediately\n\t\t\t//otherwise, wait until the hero acts, so as to not suddenly change their position\n\t\t\tif (tagAppearing) layoutTags();\n\t\t\telse tagDisappeared = true;\n\n\t\t}\n\n\t\tcellSelector.enable(Dungeon.hero.ready);\n\t\t\n\t\tfor (Gizmo g : toDestroy){\n\t\t\tg.destroy();\n\t\t}\n\t\ttoDestroy.clear();\n\t}\n\n\tprivate static Point lastOffset = null;\n\n\t@Override\n\tpublic synchronized Gizmo erase (Gizmo g) {\n\t\tGizmo result = super.erase(g);\n\t\tif (result instanceof Window){\n\t\t\tlastOffset = ((Window) result).getOffset();\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate boolean tagAttack = false;\n\tprivate boolean tagLoot = false;\n\tprivate boolean tagAction = false;\n\tprivate boolean tagResume = false;\n\n\tpublic static void layoutTags() {\n\n\t\tupdateTags = false;\n\n\t\tif (scene == null) return;\n\n\t\t//move the camera center up a bit if we're on full UI and it is taking up lots of space\n\t\tif (scene.inventory != null && scene.inventory.visible\n\t\t\t\t&& (uiCamera.width < 460 && uiCamera.height < 300)){\n\t\t\tCamera.main.setCenterOffset(0, Math.min(300-uiCamera.height, 460-uiCamera.width) / Camera.main.zoom);\n\t\t} else {\n\t\t\tCamera.main.setCenterOffset(0, 0);\n\t\t}\n\t\t//Camera.main.panTo(Dungeon.hero.sprite.center(), 5f);\n\n\t\t//primarily for phones displays with notches\n\t\t//TODO Android never draws into notch atm, perhaps allow it for center notches?\n\t\tRectF insets = DeviceCompat.getSafeInsets();\n\t\tinsets = insets.scale(1f / uiCamera.zoom);\n\n\t\tboolean tagsOnLeft = SPDSettings.flipTags();\n\t\tfloat tagWidth = Tag.SIZE + (tagsOnLeft ? insets.left : insets.right);\n\t\tfloat tagLeft = tagsOnLeft ? 0 : uiCamera.width - tagWidth;\n\n\t\tfloat y = SPDSettings.interfaceSize() == 0 ? scene.toolbar.top()-2 : scene.status.top()-2;\n\t\tif (SPDSettings.interfaceSize() == 0){\n\t\t\tif (tagsOnLeft) {\n\t\t\t\tscene.log.setRect(tagWidth, y, uiCamera.width - tagWidth - insets.right, 0);\n\t\t\t} else {\n\t\t\t\tscene.log.setRect(insets.left, y, uiCamera.width - tagWidth - insets.left, 0);\n\t\t\t}\n\t\t} else {\n\t\t\tif (tagsOnLeft) {\n\t\t\t\tscene.log.setRect(tagWidth, y, 160 - tagWidth, 0);\n\t\t\t} else {\n\t\t\t\tscene.log.setRect(insets.left, y, 160 - insets.left, 0);\n\t\t\t}\n\t\t}\n\n\t\tfloat pos = scene.toolbar.top();\n\t\tif (tagsOnLeft && SPDSettings.interfaceSize() > 0){\n\t\t\tpos = scene.status.top();\n\t\t}\n\n\t\tif (scene.tagAttack){\n\t\t\tscene.attack.setRect( tagLeft, pos - Tag.SIZE, tagWidth, Tag.SIZE );\n\t\t\tscene.attack.flip(tagsOnLeft);\n\t\t\tpos = scene.attack.top();\n\t\t}\n\n\t\tif (scene.tagLoot) {\n\t\t\tscene.loot.setRect( tagLeft, pos - Tag.SIZE, tagWidth, Tag.SIZE );\n\t\t\tscene.loot.flip(tagsOnLeft);\n\t\t\tpos = scene.loot.top();\n\t\t}\n\n\t\tif (scene.tagAction) {\n\t\t\tscene.action.setRect( tagLeft, pos - Tag.SIZE, tagWidth, Tag.SIZE );\n\t\t\tscene.action.flip(tagsOnLeft);\n\t\t\tpos = scene.action.top();\n\t\t}\n\n\t\tif (scene.tagResume) {\n\t\t\tscene.resume.setRect( tagLeft, pos - Tag.SIZE, tagWidth, Tag.SIZE );\n\t\t\tscene.resume.flip(tagsOnLeft);\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected void onBackPressed() {\n\t\tif (!cancel()) {\n\t\t\tadd( new WndGame() );\n\t\t}\n\t}\n\n\tpublic void addCustomTile( CustomTilemap visual){\n\t\tcustomTiles.add( visual.create() );\n\t}\n\n\tpublic void addCustomWall( CustomTilemap visual){\n\t\tcustomWalls.add( visual.create() );\n\t}\n\t\n\tprivate void addHeapSprite( Heap heap ) {\n\t\tItemSprite sprite = heap.sprite = (ItemSprite)heaps.recycle( ItemSprite.class );\n\t\tsprite.revive();\n\t\tsprite.link( heap );\n\t\theaps.add( sprite );\n\t}\n\t\n\tprivate void addDiscardedSprite( Heap heap ) {\n\t\theap.sprite = (DiscardedItemSprite)heaps.recycle( DiscardedItemSprite.class );\n\t\theap.sprite.revive();\n\t\theap.sprite.link( heap );\n\t\theaps.add( heap.sprite );\n\t}\n\t\n\tprivate void addPlantSprite( Plant plant ) {\n\n\t}\n\n\tprivate void addTrapSprite( Trap trap ) {\n\n\t}\n\t\n\tprivate void addBlobSprite( final Blob gas ) {\n\t\tif (gas.emitter == null) {\n\t\t\tgases.add( new BlobEmitter( gas ) );\n\t\t}\n\t}\n\t\n\tprivate synchronized void addMobSprite( Mob mob ) {\n\t\tCharSprite sprite = mob.sprite();\n\t\tsprite.visible = Dungeon.level.heroFOV[mob.pos];\n\t\tmobs.add( sprite );\n\t\tsprite.link( mob );\n\t\tsortMobSprites();\n\t}\n\n\t//ensures that mob sprites are drawn from top to bottom, in case of overlap\n\tpublic static void sortMobSprites(){\n\t\tif (scene != null){\n\t\t\tsynchronized (scene) {\n\t\t\t\tscene.mobs.sort(new Comparator() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic int compare(Object a, Object b) {\n\t\t\t\t\t\t//elements that aren't visual go to the end of the list\n\t\t\t\t\t\tif (a instanceof Visual && b instanceof Visual) {\n\t\t\t\t\t\t\treturn (int) Math.signum((((Visual) a).y + ((Visual) a).height())\n\t\t\t\t\t\t\t\t\t- (((Visual) b).y + ((Visual) b).height()));\n\t\t\t\t\t\t} else if (a instanceof Visual){\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t} else if (b instanceof Visual){\n\t\t\t\t\t\t\treturn 1;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate synchronized void prompt( String text ) {\n\t\t\n\t\tif (prompt != null) {\n\t\t\tprompt.killAndErase();\n\t\t\ttoDestroy.add(prompt);\n\t\t\tprompt = null;\n\t\t}\n\t\t\n\t\tif (text != null) {\n\t\t\tprompt = new Toast( text ) {\n\t\t\t\t@Override\n\t\t\t\tprotected void onClose() {\n\t\t\t\t\tcancel();\n\t\t\t\t}\n\t\t\t};\n\t\t\tprompt.camera = uiCamera;\n\t\t\tprompt.setPos( (uiCamera.width - prompt.width()) / 2, uiCamera.height - 60 );\n\n\t\t\tif (inventory != null && inventory.visible && prompt.right() > inventory.left() - 10){\n\t\t\t\tprompt.setPos(inventory.left() - prompt.width() - 10, prompt.top());\n\t\t\t}\n\n\t\t\tadd( prompt );\n\t\t}\n\t}\n\t\n\tprivate void showBanner( Banner banner ) {\n\t\tbanner.camera = uiCamera;\n\n\t\tfloat offset = Camera.main.centerOffset.y;\n\t\tbanner.x = align( uiCamera, (uiCamera.width - banner.width) / 2 );\n\t\tbanner.y = align( uiCamera, (uiCamera.height - banner.height) / 2 - banner.height/2 - 16 - offset );\n\n\t\taddToFront( banner );\n\t}\n\t\n\t// -------------------------------------------------------\n\n\tpublic static void add( Plant plant ) {\n\t\tif (scene != null) {\n\t\t\tscene.addPlantSprite( plant );\n\t\t}\n\t}\n\n\tpublic static void add( Trap trap ) {\n\t\tif (scene != null) {\n\t\t\tscene.addTrapSprite( trap );\n\t\t}\n\t}\n\t\n\tpublic static void add( Blob gas ) {\n\t\tActor.add( gas );\n\t\tif (scene != null) {\n\t\t\tscene.addBlobSprite( gas );\n\t\t}\n\t}\n\t\n\tpublic static void add( Heap heap ) {\n\t\tif (scene != null) {\n\t\t\t//heaps that aren't added as part of levelgen don't count for exploration bonus\n\t\t\theap.autoExplored = true;\n\t\t\tscene.addHeapSprite( heap );\n\t\t}\n\t}\n\t\n\tpublic static void discard( Heap heap ) {\n\t\tif (scene != null) {\n\t\t\tscene.addDiscardedSprite( heap );\n\t\t}\n\t}\n\t\n\tpublic static void add( Mob mob ) {\n\t\tDungeon.level.mobs.add( mob );\n\t\tif (scene != null) {\n\t\t\tscene.addMobSprite(mob);\n\t\t\tActor.add(mob);\n\t\t}\n\t}\n\n\tpublic static void addSprite( Mob mob ) {\n\t\tscene.addMobSprite( mob );\n\t}\n\t\n\tpublic static void add( Mob mob, float delay ) {\n\t\tDungeon.level.mobs.add( mob );\n\t\tscene.addMobSprite( mob );\n\t\tActor.addDelayed( mob, delay );\n\t}\n\t\n\tpublic static void add( EmoIcon icon ) {\n\t\tscene.emoicons.add( icon );\n\t}\n\t\n\tpublic static void add( CharHealthIndicator indicator ){\n\t\tif (scene != null) scene.healthIndicators.add(indicator);\n\t}\n\t\n\tpublic static void add( CustomTilemap t, boolean wall ){\n\t\tif (scene == null) return;\n\t\tif (wall){\n\t\t\tscene.addCustomWall(t);\n\t\t} else {\n\t\t\tscene.addCustomTile(t);\n\t\t}\n\t}\n\t\n\tpublic static void effect( Visual effect ) {\n\t\tif (scene != null) scene.effects.add( effect );\n\t}\n\n\tpublic static void effectOverFog( Visual effect ) {\n\t\tscene.overFogEffects.add( effect );\n\t}\n\t\n\tpublic static Ripple ripple( int pos ) {\n\t\tif (scene != null) {\n\t\t\tRipple ripple = (Ripple) scene.ripples.recycle(Ripple.class);\n\t\t\tripple.reset(pos);\n\t\t\treturn ripple;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\tpublic static SpellSprite spellSprite() {\n\t\treturn (SpellSprite)scene.spells.recycle( SpellSprite.class );\n\t}\n\t\n\tpublic static Emitter emitter() {\n\t\tif (scene != null) {\n\t\t\tEmitter emitter = (Emitter)scene.emitters.recycle( Emitter.class );\n\t\t\temitter.revive();\n\t\t\treturn emitter;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic static Emitter floorEmitter() {\n\t\tif (scene != null) {\n\t\t\tEmitter emitter = (Emitter)scene.floorEmitters.recycle( Emitter.class );\n\t\t\temitter.revive();\n\t\t\treturn emitter;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\tpublic static FloatingText status() {\n\t\treturn scene != null ? (FloatingText)scene.statuses.recycle( FloatingText.class ) : null;\n\t}\n\t\n\tpublic static void pickUp( Item item, int pos ) {\n\t\tif (scene != null) scene.toolbar.pickup( item, pos );\n\t}\n\n\tpublic static void pickUpJournal( Item item, int pos ) {\n\t\tif (scene != null) scene.menu.pickup( item, pos );\n\t}\n\n\tpublic static void flashForDocument( Document doc, String page ){\n\t\tif (scene != null) {\n\t\t\tscene.menu.flashForPage( doc, page );\n\t\t}\n\t}\n\n\tpublic static void endIntro(){\n\t\tif (scene != null){\n\t\t\tSPDSettings.intro(false);\n\t\t\tscene.add(new Tweener(scene, 2f){\n\t\t\t\t@Override\n\t\t\t\tprotected void updateValues(float progress) {\n\t\t\t\t\tif (progress <= 0.5f) {\n\t\t\t\t\t\tscene.status.alpha(2*progress);\n\t\t\t\t\t\tscene.status.visible = scene.status.active = true;\n\t\t\t\t\t\tscene.toolbar.visible = scene.toolbar.active = false;\n\t\t\t\t\t\tif (scene.inventory != null) scene.inventory.visible = scene.inventory.active = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tscene.status.alpha(1f);\n\t\t\t\t\t\tscene.status.visible = scene.status.active = true;\n\t\t\t\t\t\tscene.toolbar.alpha((progress - 0.5f)*2);\n\t\t\t\t\t\tscene.toolbar.visible = scene.toolbar.active = true;\n\t\t\t\t\t\tif (scene.inventory != null){\n\t\t\t\t\t\t\tscene.inventory.visible = scene.inventory.active = true;\n\t\t\t\t\t\t\tscene.inventory.alpha((progress - 0.5f)*2);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\tGameLog.wipe();\n\t\t\tif (SPDSettings.interfaceSize() == 0){\n\t\t\t\tGLog.p(Messages.get(GameScene.class, \"tutorial_ui_mobile\"));\n\t\t\t} else {\n\t\t\t\tGLog.p(Messages.get(GameScene.class, \"tutorial_ui_desktop\"));\n\t\t\t}\n\n\t\t\t//clear hidden doors, it's floor 1 so there are only the entrance ones\n\t\t\tfor (int i = 0; i < Dungeon.level.length(); i++){\n\t\t\t\tif (Dungeon.level.map[i] == Terrain.SECRET_DOOR){\n\t\t\t\t\tDungeon.level.discover(i);\n\t\t\t\t\tdiscoverTile(i, Terrain.SECRET_DOOR);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void updateKeyDisplay(){\n\t\tif (scene != null) scene.menu.updateKeys();\n\t}\n\n\tpublic static void showlevelUpStars(){\n\t\tif (scene != null) scene.status.showStarParticles();\n\t}\n\n\tpublic static void resetMap() {\n\t\tif (scene != null) {\n\t\t\tscene.tiles.map(Dungeon.level.map, Dungeon.level.width() );\n\t\t\tscene.visualGrid.map(Dungeon.level.map, Dungeon.level.width() );\n\t\t\tscene.terrainFeatures.map(Dungeon.level.map, Dungeon.level.width() );\n\t\t\tscene.raisedTerrain.map(Dungeon.level.map, Dungeon.level.width() );\n\t\t\tscene.walls.map(Dungeon.level.map, Dungeon.level.width() );\n\t\t}\n\t\tupdateFog();\n\t}\n\n\t//updates the whole map\n\tpublic static void updateMap() {\n\t\tif (scene != null) {\n\t\t\tscene.tiles.updateMap();\n\t\t\tscene.visualGrid.updateMap();\n\t\t\tscene.terrainFeatures.updateMap();\n\t\t\tscene.raisedTerrain.updateMap();\n\t\t\tscene.walls.updateMap();\n\t\t\tupdateFog();\n\t\t}\n\t}\n\t\n\tpublic static void updateMap( int cell ) {\n\t\tif (scene != null) {\n\t\t\tscene.tiles.updateMapCell( cell );\n\t\t\tscene.visualGrid.updateMapCell( cell );\n\t\t\tscene.terrainFeatures.updateMapCell( cell );\n\t\t\tscene.raisedTerrain.updateMapCell( cell );\n\t\t\tscene.walls.updateMapCell( cell );\n\t\t\t//update adjacent cells too\n\t\t\tupdateFog( cell, 1 );\n\t\t}\n\t}\n\n\tpublic static void plantSeed( int cell ) {\n\t\tif (scene != null) {\n\t\t\tscene.terrainFeatures.growPlant( cell );\n\t\t}\n\t}\n\t\n\tpublic static void discoverTile( int pos, int oldValue ) {\n\t\tif (scene != null) {\n\t\t\tscene.tiles.discover( pos, oldValue );\n\t\t}\n\t}\n\t\n\tpublic static void show( Window wnd ) {\n\t\tif (scene != null) {\n\t\t\tcancel();\n\n\t\t\t//If a window is already present (or was just present)\n\t\t\t// then inherit the offset it had\n\t\t\tif (scene.inventory != null && scene.inventory.visible){\n\t\t\t\tPoint offsetToInherit = null;\n\t\t\t\tfor (Gizmo g : scene.members){\n\t\t\t\t\tif (g instanceof Window) offsetToInherit = ((Window) g).getOffset();\n\t\t\t\t}\n\t\t\t\tif (lastOffset != null) {\n\t\t\t\t\toffsetToInherit = lastOffset;\n\t\t\t\t}\n\t\t\t\tif (offsetToInherit != null) {\n\t\t\t\t\twnd.offset(offsetToInherit);\n\t\t\t\t\twnd.boundOffsetWithMargin(3);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tscene.addToFront(wnd);\n\t\t}\n\t}\n\n\tpublic static boolean showingWindow(){\n\t\tif (scene == null) return false;\n\n\t\tfor (Gizmo g : scene.members){\n\t\t\tif (g instanceof Window) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic static boolean interfaceBlockingHero(){\n\t\tif (scene == null) return false;\n\n\t\tif (showingWindow()) return true;\n\n\t\tif (scene.inventory != null && scene.inventory.isSelecting()){\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic static void toggleInvPane(){\n\t\tif (scene != null && scene.inventory != null){\n\t\t\tif (scene.inventory.visible){\n\t\t\t\tscene.inventory.visible = scene.inventory.active = invVisible = false;\n\t\t\t\tscene.toolbar.setPos(scene.toolbar.left(), uiCamera.height-scene.toolbar.height());\n\t\t\t} else {\n\t\t\t\tscene.inventory.visible = scene.inventory.active = invVisible = true;\n\t\t\t\tscene.toolbar.setPos(scene.toolbar.left(), scene.inventory.top()-scene.toolbar.height());\n\t\t\t}\n\t\t\tlayoutTags();\n\t\t}\n\t}\n\n\tpublic static void centerNextWndOnInvPane(){\n\t\tif (scene != null && scene.inventory != null && scene.inventory.visible){\n\t\t\tlastOffset = new Point((int)scene.inventory.centerX() - uiCamera.width/2,\n\t\t\t\t\t(int)scene.inventory.centerY() - uiCamera.height/2);\n\t\t}\n\t}\n\n\tpublic static void updateFog(){\n\t\tif (scene != null) {\n\t\t\tscene.fog.updateFog();\n\t\t\tscene.wallBlocking.updateMap();\n\t\t}\n\t}\n\n\tpublic static void updateFog(int x, int y, int w, int h){\n\t\tif (scene != null) {\n\t\t\tscene.fog.updateFogArea(x, y, w, h);\n\t\t\tscene.wallBlocking.updateArea(x, y, w, h);\n\t\t}\n\t}\n\t\n\tpublic static void updateFog( int cell, int radius ){\n\t\tif (scene != null) {\n\t\t\tscene.fog.updateFog( cell, radius );\n\t\t\tscene.wallBlocking.updateArea( cell, radius );\n\t\t}\n\t}\n\t\n\tpublic static void afterObserve() {\n\t\tif (scene != null) {\n\t\t\tfor (Mob mob : Dungeon.level.mobs.toArray(new Mob[0])) {\n\t\t\t\tif (mob.sprite != null) mob.sprite.visible = Dungeon.level.heroFOV[mob.pos];\n\t\t\t\tif (mob instanceof Ghoul){\n\t\t\t\t\tfor (Ghoul.GhoulLifeLink link : mob.buffs(Ghoul.GhoulLifeLink.class)){\n\t\t\t\t\t\tlink.updateVisibility();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void flash( int color ) {\n\t\tflash( color, true);\n\t}\n\n\tpublic static void flash( int color, boolean lightmode ) {\n\t\tif (scene != null) {\n\t\t\t//greater than 0 to account for negative values (which have the first bit set to 1)\n\t\t\tif (color > 0 && color < 0x01000000) {\n\t\t\t\tscene.fadeIn(0xFF000000 | color, lightmode);\n\t\t\t} else {\n\t\t\t\tscene.fadeIn(color, lightmode);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void gameOver() {\n\t\tif (scene == null) return;\n\n\t\tBanner gameOver = new Banner( BannerSprites.get( BannerSprites.Type.GAME_OVER ) );\n\t\tgameOver.show( 0x000000, 2f );\n\t\tscene.showBanner( gameOver );\n\n\t\tStyledButton restart = new StyledButton(Chrome.Type.GREY_BUTTON_TR, Messages.get(StartScene.class, \"new\"), 9){\n\t\t\t@Override\n\t\t\tprotected void onClick() {\n\t\t\t\tGamesInProgress.selectedClass = Dungeon.hero.heroClass;\n\t\t\t\tGamesInProgress.curSlot = GamesInProgress.firstEmpty();\n\t\t\t\tShatteredPixelDungeon.switchScene(HeroSelectScene.class);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void update() {\n\t\t\t\talpha(gameOver.am);\n\t\t\t\tsuper.update();\n\t\t\t}\n\t\t};\n\t\trestart.icon(Icons.get(Icons.ENTER));\n\t\trestart.alpha(0);\n\t\trestart.camera = uiCamera;\n\t\tfloat offset = Camera.main.centerOffset.y;\n\t\trestart.setSize(Math.max(80, restart.reqWidth()), 20);\n\t\trestart.setPos(\n\t\t\t\talign(uiCamera, (restart.camera.width - restart.width()) / 2),\n\t\t\t\talign(uiCamera, (restart.camera.height - restart.height()) / 2 + restart.height()/2 + 16 - offset)\n\t\t);\n\t\tscene.add(restart);\n\n\t\tStyledButton menu = new StyledButton(Chrome.Type.GREY_BUTTON_TR, Messages.get(WndKeyBindings.class, \"menu\"), 9){\n\t\t\t@Override\n\t\t\tprotected void onClick() {\n\t\t\t\tGameScene.show(new WndGame());\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void update() {\n\t\t\t\talpha(gameOver.am);\n\t\t\t\tsuper.update();\n\t\t\t}\n\t\t};\n\t\tmenu.icon(Icons.get(Icons.PREFS));\n\t\tmenu.alpha(0);\n\t\tmenu.camera = uiCamera;\n\t\tmenu.setSize(Math.max(80, menu.reqWidth()), 20);\n\t\tmenu.setPos(\n\t\t\t\talign(uiCamera, (menu.camera.width - menu.width()) / 2),\n\t\t\t\trestart.bottom() + 2\n\t\t);\n\t\tscene.add(menu);\n\t}\n\t\n\tpublic static void bossSlain() {\n\t\tif (Dungeon.hero.isAlive()) {\n\t\t\tBanner bossSlain = new Banner( BannerSprites.get( BannerSprites.Type.BOSS_SLAIN ) );\n\t\t\tbossSlain.show( 0xFFFFFF, 0.3f, 5f );\n\t\t\tscene.showBanner( bossSlain );\n\t\t\t\n\t\t\tSample.INSTANCE.play( Assets.Sounds.BOSS );\n\t\t}\n\t}\n\t\n\tpublic static void handleCell( int cell ) {\n\t\tcellSelector.select( cell, PointerEvent.LEFT );\n\t}\n\t\n\tpublic static void selectCell( CellSelector.Listener listener ) {\n\t\tif (cellSelector.listener != null && cellSelector.listener != defaultCellListener){\n\t\t\tcellSelector.listener.onSelect(null);\n\t\t}\n\t\tcellSelector.listener = listener;\n\t\tcellSelector.enabled = Dungeon.hero.ready;\n\t\tif (scene != null) {\n\t\t\tscene.prompt(listener.prompt());\n\t\t}\n\t}\n\t\n\tpublic static boolean cancelCellSelector() {\n\t\tif (cellSelector.listener != null && cellSelector.listener != defaultCellListener) {\n\t\t\tcellSelector.resetKeyHold();\n\t\t\tcellSelector.cancel();\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic static WndBag selectItem( WndBag.ItemSelector listener ) {\n\t\tcancel();\n\n\t\tif (scene != null) {\n\t\t\t//TODO can the inventory pane work in these cases? bad to fallback to mobile window\n\t\t\tif (scene.inventory != null && scene.inventory.visible && !showingWindow()){\n\t\t\t\tscene.inventory.setSelector(listener);\n\t\t\t\treturn null;\n\t\t\t} else {\n\t\t\t\tWndBag wnd = WndBag.getBag( listener );\n\t\t\t\tshow(wnd);\n\t\t\t\treturn wnd;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic static boolean cancel() {\n\t\tcellSelector.resetKeyHold();\n\t\tif (Dungeon.hero != null && (Dungeon.hero.curAction != null || Dungeon.hero.resting)) {\n\t\t\t\n\t\t\tDungeon.hero.curAction = null;\n\t\t\tDungeon.hero.resting = false;\n\t\t\treturn true;\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\treturn cancelCellSelector();\n\t\t\t\n\t\t}\n\t}\n\t\n\tpublic static void ready() {\n\t\tselectCell( defaultCellListener );\n\t\tQuickSlotButton.cancel();\n\t\tInventoryPane.cancelTargeting();\n\t\tif (scene != null && scene.toolbar != null) scene.toolbar.examining = false;\n\t\tif (tagDisappeared) {\n\t\t\ttagDisappeared = false;\n\t\t\tupdateTags = true;\n\t\t}\n\t}\n\t\n\tpublic static void checkKeyHold(){\n\t\tcellSelector.processKeyHold();\n\t}\n\t\n\tpublic static void resetKeyHold(){\n\t\tcellSelector.resetKeyHold();\n\t}\n\n\tpublic static void examineCell( Integer cell ) {\n\t\tif (cell == null\n\t\t\t\t|| cell < 0\n\t\t\t\t|| cell > Dungeon.level.length()\n\t\t\t\t|| (!Dungeon.level.visited[cell] && !Dungeon.level.mapped[cell])) {\n\t\t\treturn;\n\t\t}\n\n\t\tArrayList<Object> objects = getObjectsAtCell(cell);\n\n\t\tif (objects.isEmpty()) {\n\t\t\tGameScene.show(new WndInfoCell(cell));\n\t\t} else if (objects.size() == 1){\n\t\t\texamineObject(objects.get(0));\n\t\t} else {\n\t\t\tString[] names = getObjectNames(objects).toArray(new String[0]);\n\n\t\t\tGameScene.show(new WndOptions(Icons.get(Icons.INFO),\n\t\t\t\t\tMessages.get(GameScene.class, \"choose_examine\"),\n\t\t\t\t\tMessages.get(GameScene.class, \"multiple_examine\"),\n\t\t\t\t\tnames){\n\t\t\t\t@Override\n\t\t\t\tprotected void onSelect(int index) {\n\t\t\t\t\texamineObject(objects.get(index));\n\t\t\t\t}\n\t\t\t});\n\n\t\t}\n\t}\n\n\tprivate static ArrayList<Object> getObjectsAtCell( int cell ){\n\t\tArrayList<Object> objects = new ArrayList<>();\n\n\t\tif (cell == Dungeon.hero.pos) {\n\t\t\tobjects.add(Dungeon.hero);\n\n\t\t} else if (Dungeon.level.heroFOV[cell]) {\n\t\t\tMob mob = (Mob) Actor.findChar(cell);\n\t\t\tif (mob != null) objects.add(mob);\n\t\t}\n\n\t\tHeap heap = Dungeon.level.heaps.get(cell);\n\t\tif (heap != null && heap.seen) objects.add(heap);\n\n\t\tPlant plant = Dungeon.level.plants.get( cell );\n\t\tif (plant != null) objects.add(plant);\n\n\t\tTrap trap = Dungeon.level.traps.get( cell );\n\t\tif (trap != null && trap.visible) objects.add(trap);\n\n\t\treturn objects;\n\t}\n\n\tprivate static ArrayList<String> getObjectNames( ArrayList<Object> objects ){\n\t\tArrayList<String> names = new ArrayList<>();\n\t\tfor (Object obj : objects){\n\t\t\tif (obj instanceof Hero) names.add(((Hero) obj).className().toUpperCase(Locale.ENGLISH));\n\t\t\telse if (obj instanceof Mob) names.add(Messages.titleCase( ((Mob)obj).name() ));\n\t\t\telse if (obj instanceof Heap) names.add(Messages.titleCase( ((Heap)obj).title() ));\n\t\t\telse if (obj instanceof Plant) names.add(Messages.titleCase( ((Plant) obj).name() ));\n\t\t\telse if (obj instanceof Trap) names.add(Messages.titleCase( ((Trap) obj).name() ));\n\t\t}\n\t\treturn names;\n\t}\n\n\tpublic static void examineObject(Object o){\n\t\tif (o == Dungeon.hero){\n\t\t\tGameScene.show( new WndHero() );\n\t\t} else if ( o instanceof Mob && ((Mob) o).isActive() ){\n\t\t\tGameScene.show(new WndInfoMob((Mob) o));\n\t\t\tif (o instanceof Snake && !Document.ADVENTURERS_GUIDE.isPageRead(Document.GUIDE_SURPRISE_ATKS)){\n\t\t\t\tGLog.p(Messages.get(Guidebook.class, \"hint\"));\n\t\t\t\tGameScene.flashForDocument(Document.ADVENTURERS_GUIDE, Document.GUIDE_SURPRISE_ATKS);\n\t\t\t}\n\t\t} else if ( o instanceof Heap && !((Heap) o).isEmpty() ){\n\t\t\tGameScene.show(new WndInfoItem((Heap)o));\n\t\t} else if ( o instanceof Plant ){\n\t\t\tGameScene.show( new WndInfoPlant((Plant) o) );\n\t\t} else if ( o instanceof Trap ){\n\t\t\tGameScene.show( new WndInfoTrap((Trap) o));\n\t\t} else {\n\t\t\tGameScene.show( new WndMessage( Messages.get(GameScene.class, \"dont_know\") ) ) ;\n\t\t}\n\t}\n\n\t\n\tprivate static final CellSelector.Listener defaultCellListener = new CellSelector.Listener() {\n\t\t@Override\n\t\tpublic void onSelect( Integer cell ) {\n\t\t\tif (Dungeon.hero.handle( cell )) {\n\t\t\t\tDungeon.hero.next();\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void onRightClick(Integer cell) {\n\t\t\tif (cell == null\n\t\t\t\t\t|| cell < 0\n\t\t\t\t\t|| cell > Dungeon.level.length()\n\t\t\t\t\t|| (!Dungeon.level.visited[cell] && !Dungeon.level.mapped[cell])) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tArrayList<Object> objects = getObjectsAtCell(cell);\n\t\t\tArrayList<String> textLines = getObjectNames(objects);\n\n\t\t\t//determine title and image\n\t\t\tString title = null;\n\t\t\tImage image = null;\n\t\t\tif (objects.isEmpty()) {\n\t\t\t\ttitle = WndInfoCell.cellName(cell);\n\t\t\t\timage = WndInfoCell.cellImage(cell);\n\t\t\t} else if (objects.size() > 1){\n\t\t\t\ttitle = Messages.get(GameScene.class, \"multiple\");\n\t\t\t\timage = Icons.get(Icons.INFO);\n\t\t\t} else if (objects.get(0) instanceof Hero) {\n\t\t\t\ttitle = textLines.remove(0);\n\t\t\t\timage = HeroSprite.avatar(((Hero) objects.get(0)).heroClass, ((Hero) objects.get(0)).tier());\n\t\t\t} else if (objects.get(0) instanceof Mob) {\n\t\t\t\ttitle = textLines.remove(0);\n\t\t\t\timage = ((Mob) objects.get(0)).sprite();\n\t\t\t} else if (objects.get(0) instanceof Heap) {\n\t\t\t\ttitle = textLines.remove(0);\n\t\t\t\timage = new ItemSprite((Heap) objects.get(0));\n\t\t\t} else if (objects.get(0) instanceof Plant) {\n\t\t\t\ttitle = textLines.remove(0);\n\t\t\t\timage = TerrainFeaturesTilemap.tile(cell, Dungeon.level.map[cell]);\n\t\t\t} else if (objects.get(0) instanceof Trap) {\n\t\t\t\ttitle = textLines.remove(0);\n\t\t\t\timage = TerrainFeaturesTilemap.tile(cell, Dungeon.level.map[cell]);\n\t\t\t}\n\n\t\t\t//determine first text line\n\t\t\tif (objects.isEmpty()) {\n\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"go_here\"));\n\t\t\t} else if (objects.get(0) instanceof Hero) {\n\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"go_here\"));\n\t\t\t} else if (objects.get(0) instanceof Mob) {\n\t\t\t\tif (((Mob) objects.get(0)).alignment != Char.Alignment.ENEMY) {\n\t\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"interact\"));\n\t\t\t\t} else {\n\t\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"attack\"));\n\t\t\t\t}\n\t\t\t} else if (objects.get(0) instanceof Heap) {\n\t\t\t\tswitch (((Heap) objects.get(0)).type) {\n\t\t\t\t\tcase HEAP:\n\t\t\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"pick_up\"));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase FOR_SALE:\n\t\t\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"purchase\"));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"interact\"));\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else if (objects.get(0) instanceof Plant) {\n\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"trample\"));\n\t\t\t} else if (objects.get(0) instanceof Trap) {\n\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"interact\"));\n\t\t\t}\n\n\t\t\t//final text formatting\n\t\t\tif (objects.size() > 1){\n\t\t\t\ttextLines.add(0, \"_\" + textLines.remove(0) + \":_ \" + textLines.get(0));\n\t\t\t\tfor (int i = 1; i < textLines.size(); i++){\n\t\t\t\t\ttextLines.add(i, \"_\" + Messages.get(GameScene.class, \"examine\") + \":_ \" + textLines.remove(i));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttextLines.add(0, \"_\" + textLines.remove(0) + \"_\");\n\t\t\t\ttextLines.add(1, \"_\" + Messages.get(GameScene.class, \"examine\") + \"_\");\n\t\t\t}\n\n\t\t\tRightClickMenu menu = new RightClickMenu(image,\n\t\t\t\t\ttitle,\n\t\t\t\t\ttextLines.toArray(new String[0])){\n\t\t\t\t@Override\n\t\t\t\tpublic void onSelect(int index) {\n\t\t\t\t\tif (index == 0){\n\t\t\t\t\t\thandleCell(cell);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (objects.size() == 0){\n\t\t\t\t\t\t\tGameScene.show(new WndInfoCell(cell));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\texamineObject(objects.get(index-1));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tscene.addToFront(menu);\n\t\t\tmenu.camera = PixelScene.uiCamera;\n\t\t\tPointF mousePos = PointerEvent.currentHoverPos();\n\t\t\tmousePos = menu.camera.screenToCamera((int)mousePos.x, (int)mousePos.y);\n\t\t\tmenu.setPos(mousePos.x-3, mousePos.y-3);\n\n\t\t}\n\n\t\t@Override\n\t\tpublic String prompt() {\n\t\t\treturn null;\n\t\t}\n\t};\n}" }, { "identifier": "PathFinder", "path": "SPD-classes/src/main/java/com/watabou/utils/PathFinder.java", "snippet": "public class PathFinder {\n\t\n\tpublic static int[] distance;\n\tprivate static int[] maxVal;\n\t\n\tprivate static boolean[] goals;\n\tprivate static int[] queue;\n\tprivate static boolean[] queued; //currently only used in getStepBack, other can piggyback on distance\n\t\n\tprivate static int size = 0;\n\tprivate static int width = 0;\n\n\tprivate static int[] dir;\n\tprivate static int[] dirLR;\n\n\t//performance-light shortcuts for some common pathfinder cases\n\t//they are in array-access order for increased memory performance\n\tpublic static int[] NEIGHBOURS4;\n\tpublic static int[] NEIGHBOURS8;\n\tpublic static int[] NEIGHBOURS9;\n\n\t//similar to their equivalent neighbour arrays, but the order is clockwise.\n\t//Useful for some logic functions, but is slower due to lack of array-access order.\n\tpublic static int[] CIRCLE4;\n\tpublic static int[] CIRCLE8;\n\t\n\tpublic static void setMapSize( int width, int height ) {\n\t\t\n\t\tPathFinder.width = width;\n\t\tPathFinder.size = width * height;\n\t\t\n\t\tdistance = new int[size];\n\t\tgoals = new boolean[size];\n\t\tqueue = new int[size];\n\t\tqueued = new boolean[size];\n\n\t\tmaxVal = new int[size];\n\t\tArrays.fill(maxVal, Integer.MAX_VALUE);\n\n\t\tdir = new int[]{-1, +1, -width, +width, -width-1, -width+1, +width-1, +width+1};\n\t\tdirLR = new int[]{-1-width, -1, -1+width, -width, +width, +1-width, +1, +1+width};\n\n\t\tNEIGHBOURS4 = new int[]{-width, -1, +1, +width};\n\t\tNEIGHBOURS8 = new int[]{-width-1, -width, -width+1, -1, +1, +width-1, +width, +width+1};\n\t\tNEIGHBOURS9 = new int[]{-width-1, -width, -width+1, -1, 0, +1, +width-1, +width, +width+1};\n\n\t\tCIRCLE4 = new int[]{-width, +1, +width, -1};\n\t\tCIRCLE8 = new int[]{-width-1, -width, -width+1, +1, +width+1, +width, +width-1, -1};\n\t}\n\n\tpublic static Path find( int from, int to, boolean[] passable ) {\n\n\t\tif (!buildDistanceMap( from, to, passable )) {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tPath result = new Path();\n\t\tint s = from;\n\n\t\t// From the starting position we are moving downwards,\n\t\t// until we reach the ending point\n\t\tdo {\n\t\t\tint minD = distance[s];\n\t\t\tint mins = s;\n\t\t\t\n\t\t\tfor (int i=0; i < dir.length; i++) {\n\t\t\t\t\n\t\t\t\tint n = s + dir[i];\n\t\t\t\t\n\t\t\t\tint thisD = distance[n];\n\t\t\t\tif (thisD < minD) {\n\t\t\t\t\tminD = thisD;\n\t\t\t\t\tmins = n;\n\t\t\t\t}\n\t\t\t}\n\t\t\ts = mins;\n\t\t\tresult.add( s );\n\t\t} while (s != to);\n\t\t\n\t\treturn result;\n\t}\n\t\n\tpublic static int getStep( int from, int to, boolean[] passable ) {\n\t\t\n\t\tif (!buildDistanceMap( from, to, passable )) {\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\t// From the starting position we are making one step downwards\n\t\tint minD = distance[from];\n\t\tint best = from;\n\t\t\n\t\tint step, stepD;\n\t\t\n\t\tfor (int i=0; i < dir.length; i++) {\n\n\t\t\tif ((stepD = distance[step = from + dir[i]]) < minD) {\n\t\t\t\tminD = stepD;\n\t\t\t\tbest = step;\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t}\n\t\n\tpublic static int getStepBack( int cur, int from, int lookahead, boolean[] passable, boolean canApproachFromPos ) {\n\n\t\tint d = buildEscapeDistanceMap( cur, from, lookahead, passable );\n\t\tif (d == 0) return -1;\n\n\t\tif (!canApproachFromPos) {\n\t\t\t//We can't approach the position we are retreating from\n\t\t\t//re-calculate based on this, and reduce the target distance if need-be\n\t\t\tint head = 0;\n\t\t\tint tail = 0;\n\n\t\t\tint newD = distance[cur];\n\t\t\tBArray.setFalse(queued);\n\n\t\t\tqueue[tail++] = cur;\n\t\t\tqueued[cur] = true;\n\n\t\t\twhile (head < tail) {\n\t\t\t\tint step = queue[head++];\n\n\t\t\t\tif (distance[step] > newD) {\n\t\t\t\t\tnewD = distance[step];\n\t\t\t\t}\n\n\t\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\t\tint end = ((step + 1) % width == 0 ? 3 : 0);\n\t\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\t\tint n = step + dirLR[i];\n\t\t\t\t\tif (n >= 0 && n < size && passable[n]) {\n\t\t\t\t\t\tif (distance[n] < distance[cur]) {\n\t\t\t\t\t\t\tpassable[n] = false;\n\t\t\t\t\t\t} else if (distance[n] >= distance[step] && !queued[n]) {\n\t\t\t\t\t\t\t// Add to queue\n\t\t\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\t\t\tqueued[n] = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\td = Math.min(newD, d);\n\t\t}\n\n\t\tfor (int i=0; i < size; i++) {\n\t\t\tgoals[i] = distance[i] == d;\n\t\t}\n\t\tif (!buildDistanceMap( cur, goals, passable )) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tint s = cur;\n\t\t\n\t\t// From the starting position we are making one step downwards\n\t\tint minD = distance[s];\n\t\tint mins = s;\n\t\t\n\t\tfor (int i=0; i < dir.length; i++) {\n\n\t\t\tint n = s + dir[i];\n\t\t\tint thisD = distance[n];\n\t\t\t\n\t\t\tif (thisD < minD) {\n\t\t\t\tminD = thisD;\n\t\t\t\tmins = n;\n\t\t\t}\n\t\t}\n\n\t\treturn mins;\n\t}\n\t\n\tprivate static boolean buildDistanceMap( int from, int to, boolean[] passable ) {\n\t\t\n\t\tif (from == to) {\n\t\t\treturn false;\n\t\t}\n\n\t\tSystem.arraycopy(maxVal, 0, distance, 0, maxVal.length);\n\t\t\n\t\tboolean pathFound = false;\n\t\t\n\t\tint head = 0;\n\t\tint tail = 0;\n\t\t\n\t\t// Add to queue\n\t\tqueue[tail++] = to;\n\t\tdistance[to] = 0;\n\t\t\n\t\twhile (head < tail) {\n\t\t\t\n\t\t\t// Remove from queue\n\t\t\tint step = queue[head++];\n\t\t\tif (step == from) {\n\t\t\t\tpathFound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tint nextDistance = distance[step] + 1;\n\t\t\t\n\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\tint end = ((step+1) % width == 0 ? 3 : 0);\n\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\tint n = step + dirLR[i];\n\t\t\t\tif (n == from || (n >= 0 && n < size && passable[n] && (distance[n] > nextDistance))) {\n\t\t\t\t\t// Add to queue\n\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\tdistance[n] = nextDistance;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn pathFound;\n\t}\n\t\n\tpublic static void buildDistanceMap( int to, boolean[] passable, int limit ) {\n\t\t\n\t\tSystem.arraycopy(maxVal, 0, distance, 0, maxVal.length);\n\t\t\n\t\tint head = 0;\n\t\tint tail = 0;\n\t\t\n\t\t// Add to queue\n\t\tqueue[tail++] = to;\n\t\tdistance[to] = 0;\n\t\t\n\t\twhile (head < tail) {\n\t\t\t\n\t\t\t// Remove from queue\n\t\t\tint step = queue[head++];\n\t\t\t\n\t\t\tint nextDistance = distance[step] + 1;\n\t\t\tif (nextDistance > limit) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\tint end = ((step+1) % width == 0 ? 3 : 0);\n\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\tint n = step + dirLR[i];\n\t\t\t\tif (n >= 0 && n < size && passable[n] && (distance[n] > nextDistance)) {\n\t\t\t\t\t// Add to queue\n\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\tdistance[n] = nextDistance;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate static boolean buildDistanceMap( int from, boolean[] to, boolean[] passable ) {\n\t\t\n\t\tif (to[from]) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tSystem.arraycopy(maxVal, 0, distance, 0, maxVal.length);\n\t\t\n\t\tboolean pathFound = false;\n\t\t\n\t\tint head = 0;\n\t\tint tail = 0;\n\t\t\n\t\t// Add to queue\n\t\tfor (int i=0; i < size; i++) {\n\t\t\tif (to[i]) {\n\t\t\t\tqueue[tail++] = i;\n\t\t\t\tdistance[i] = 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\twhile (head < tail) {\n\t\t\t\n\t\t\t// Remove from queue\n\t\t\tint step = queue[head++];\n\t\t\tif (step == from) {\n\t\t\t\tpathFound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tint nextDistance = distance[step] + 1;\n\t\t\t\n\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\tint end = ((step+1) % width == 0 ? 3 : 0);\n\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\tint n = step + dirLR[i];\n\t\t\t\tif (n == from || (n >= 0 && n < size && passable[n] && (distance[n] > nextDistance))) {\n\t\t\t\t\t// Add to queue\n\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\tdistance[n] = nextDistance;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn pathFound;\n\t}\n\n\t//the lookahead is the target number of cells to retreat toward from our current position's\n\t// distance from the position we are escaping from. Returns the highest found distance, up to the lookahead\n\tprivate static int buildEscapeDistanceMap( int cur, int from, int lookAhead, boolean[] passable ) {\n\t\t\n\t\tSystem.arraycopy(maxVal, 0, distance, 0, maxVal.length);\n\t\t\n\t\tint destDist = Integer.MAX_VALUE;\n\t\t\n\t\tint head = 0;\n\t\tint tail = 0;\n\t\t\n\t\t// Add to queue\n\t\tqueue[tail++] = from;\n\t\tdistance[from] = 0;\n\t\t\n\t\tint dist = 0;\n\t\t\n\t\twhile (head < tail) {\n\t\t\t\n\t\t\t// Remove from queue\n\t\t\tint step = queue[head++];\n\t\t\tdist = distance[step];\n\t\t\t\n\t\t\tif (dist > destDist) {\n\t\t\t\treturn destDist;\n\t\t\t}\n\t\t\t\n\t\t\tif (step == cur) {\n\t\t\t\tdestDist = dist + lookAhead;\n\t\t\t}\n\t\t\t\n\t\t\tint nextDistance = dist + 1;\n\t\t\t\n\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\tint end = ((step+1) % width == 0 ? 3 : 0);\n\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\tint n = step + dirLR[i];\n\t\t\t\tif (n >= 0 && n < size && passable[n] && distance[n] > nextDistance) {\n\t\t\t\t\t// Add to queue\n\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\tdistance[n] = nextDistance;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn dist;\n\t}\n\t\n\tpublic static void buildDistanceMap( int to, boolean[] passable ) {\n\t\t\n\t\tSystem.arraycopy(maxVal, 0, distance, 0, maxVal.length);\n\t\t\n\t\tint head = 0;\n\t\tint tail = 0;\n\t\t\n\t\t// Add to queue\n\t\tqueue[tail++] = to;\n\t\tdistance[to] = 0;\n\t\t\n\t\twhile (head < tail) {\n\t\t\t\n\t\t\t// Remove from queue\n\t\t\tint step = queue[head++];\n\t\t\tint nextDistance = distance[step] + 1;\n\t\t\t\n\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\tint end = ((step+1) % width == 0 ? 3 : 0);\n\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\tint n = step + dirLR[i];\n\t\t\t\tif (n >= 0 && n < size && passable[n] && (distance[n] > nextDistance)) {\n\t\t\t\t\t// Add to queue\n\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\tdistance[n] = nextDistance;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@SuppressWarnings(\"serial\")\n\tpublic static class Path extends LinkedList<Integer> {\n\t}\n}" }, { "identifier": "Point", "path": "SPD-classes/src/main/java/com/watabou/utils/Point.java", "snippet": "public class Point {\n\n\tpublic int x;\n\tpublic int y;\n\t\n\tpublic Point() {\n\t}\n\t\n\tpublic Point( int x, int y ) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\t\n\tpublic Point( Point p ) {\n\t\tthis.x = p.x;\n\t\tthis.y = p.y;\n\t}\n\t\n\tpublic Point set( int x, int y ) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\treturn this;\n\t}\n\t\n\tpublic Point set( Point p ) {\n\t\tx = p.x;\n\t\ty = p.y;\n\t\treturn this;\n\t}\n\t\n\tpublic Point clone() {\n\t\treturn new Point( this );\n\t}\n\t\n\tpublic Point scale( float f ) {\n\t\tthis.x *= f;\n\t\tthis.y *= f;\n\t\treturn this;\n\t}\n\t\n\tpublic Point offset( int dx, int dy ) {\n\t\tx += dx;\n\t\ty += dy;\n\t\treturn this;\n\t}\n\t\n\tpublic Point offset( Point d ) {\n\t\tx += d.x;\n\t\ty += d.y;\n\t\treturn this;\n\t}\n\n\tpublic boolean isZero(){\n\t\treturn x == 0 && y == 0;\n\t}\n\n\tpublic float length() {\n\t\treturn (float)Math.sqrt( x * x + y * y );\n\t}\n\n\tpublic static float distance( Point a, Point b ) {\n\t\tfloat dx = a.x - b.x;\n\t\tfloat dy = a.y - b.y;\n\t\treturn (float)Math.sqrt( dx * dx + dy * dy );\n\t}\n\t\n\t@Override\n\tpublic boolean equals( Object obj ) {\n\t\tif (obj instanceof Point) {\n\t\t\tPoint p = (Point)obj;\n\t\t\treturn p.x == x && p.y == y;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n}" }, { "identifier": "Random", "path": "SPD-classes/src/main/java/com/watabou/utils/Random.java", "snippet": "public class Random {\n\n\t//we store a stack of random number generators, which may be seeded deliberately or randomly.\n\t//top of the stack is what is currently being used to generate new numbers.\n\t//the base generator is always created with no seed, and cannot be popped.\n\tprivate static ArrayDeque<java.util.Random> generators;\n\tstatic {\n\t\tresetGenerators();\n\t}\n\n\tpublic static synchronized void resetGenerators(){\n\t\tgenerators = new ArrayDeque<>();\n\t\tgenerators.push(new java.util.Random());\n\t}\n\n\tpublic static synchronized void pushGenerator(){\n\t\tgenerators.push( new java.util.Random() );\n\t}\n\n\tpublic static synchronized void pushGenerator( long seed ){\n\t\tgenerators.push( new java.util.Random( scrambleSeed(seed) ) );\n\t}\n\n\t//scrambles a given seed, this helps eliminate patterns between the outputs of similar seeds\n\t//Algorithm used is MX3 by Jon Maiga (jonkagstrom.com), CC0 license.\n\tprivate static synchronized long scrambleSeed( long seed ){\n\t\tseed ^= seed >>> 32;\n\t\tseed *= 0xbea225f9eb34556dL;\n\t\tseed ^= seed >>> 29;\n\t\tseed *= 0xbea225f9eb34556dL;\n\t\tseed ^= seed >>> 32;\n\t\tseed *= 0xbea225f9eb34556dL;\n\t\tseed ^= seed >>> 29;\n\t\treturn seed;\n\t}\n\n\tpublic static synchronized void popGenerator(){\n\t\tif (generators.size() == 1){\n\t\t\tGame.reportException( new RuntimeException(\"tried to pop the last random number generator!\"));\n\t\t} else {\n\t\t\tgenerators.pop();\n\t\t}\n\t}\n\n\t//returns a uniformly distributed float in the range [0, 1)\n\tpublic static synchronized float Float() {\n\t\treturn generators.peek().nextFloat();\n\t}\n\n\t//returns a uniformly distributed float in the range [0, max)\n\tpublic static float Float( float max ) {\n\t\treturn Float() * max;\n\t}\n\n\t//returns a uniformly distributed float in the range [min, max)\n\tpublic static float Float( float min, float max ) {\n\t\treturn min + Float(max - min);\n\t}\n\t\n\t//returns a triangularly distributed float in the range [min, max)\n\tpublic static float NormalFloat( float min, float max ) {\n\t\treturn min + ((Float(max - min) + Float(max - min))/2f);\n\t}\n\n\t//returns a uniformly distributed int in the range [0, max)\n\tpublic static synchronized int Int( int max ) {\n\t\treturn max > 0 ? generators.peek().nextInt(max) : 0;\n\t}\n\n\t//returns a uniformly distributed int in the range [min, max)\n\tpublic static int Int( int min, int max ) {\n\t\treturn min + Int(max - min);\n\t}\n\n\t//returns a uniformly distributed int in the range [min, max]\n\tpublic static int IntRange( int min, int max ) {\n\t\treturn min + Int(max - min + 1);\n\t}\n\n\t//returns a triangularly distributed int in the range [min, max]\n\tpublic static int NormalIntRange( int min, int max ) {\n\t\treturn min + (int)((Float() + Float()) * (max - min + 1) / 2f);\n\t}\n\n\t//returns a uniformly distributed long in the range [-2^63, 2^63)\n\tpublic static synchronized long Long() {\n\t\treturn generators.peek().nextLong();\n\t}\n\n\t//returns a uniformly distributed long in the range [0, max)\n\tpublic static long Long( long max ) {\n\t\tlong result = Long();\n\t\tif (result < 0) result += Long.MAX_VALUE;\n\t\treturn result % max;\n\t}\n\n\t//returns an index from chances, the probability of each index is the weight values in changes\n\tpublic static int chances( float[] chances ) {\n\t\t\n\t\tint length = chances.length;\n\t\t\n\t\tfloat sum = 0;\n\t\tfor (int i=0; i < length; i++) {\n\t\t\tsum += chances[i];\n\t\t}\n\t\t\n\t\tfloat value = Float( sum );\n\t\tsum = 0;\n\t\tfor (int i=0; i < length; i++) {\n\t\t\tsum += chances[i];\n\t\t\tif (value < sum) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn -1;\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\t//returns a key element from chances, the probability of each key is the weight value it maps to\n\tpublic static <K> K chances( HashMap<K,Float> chances ) {\n\t\t\n\t\tint size = chances.size();\n\n\t\tObject[] values = chances.keySet().toArray();\n\t\tfloat[] probs = new float[size];\n\t\tfloat sum = 0;\n\t\tfor (int i=0; i < size; i++) {\n\t\t\tprobs[i] = chances.get( values[i] );\n\t\t\tsum += probs[i];\n\t\t}\n\t\t\n\t\tif (sum <= 0) {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tfloat value = Float( sum );\n\t\t\n\t\tsum = probs[0];\n\t\tfor (int i=0; i < size; i++) {\n\t\t\tif (value < sum) {\n\t\t\t\treturn (K)values[i];\n\t\t\t}\n\t\t\tsum += probs[i + 1];\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic static int index( Collection<?> collection ) {\n\t\treturn Int(collection.size());\n\t}\n\n\t@SafeVarargs\n\tpublic static<T> T oneOf(T... array ) {\n\t\treturn array[Int(array.length)];\n\t}\n\t\n\tpublic static<T> T element( T[] array ) {\n\t\treturn element( array, array.length );\n\t}\n\t\n\tpublic static<T> T element( T[] array, int max ) {\n\t\treturn array[Int(max)];\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static<T> T element( Collection<? extends T> collection ) {\n\t\tint size = collection.size();\n\t\treturn size > 0 ?\n\t\t\t(T)collection.toArray()[Int( size )] :\n\t\t\tnull;\n\t}\n\n\tpublic synchronized static<T> void shuffle( List<?extends T> list){\n\t\tCollections.shuffle(list, generators.peek());\n\t}\n\t\n\tpublic static<T> void shuffle( T[] array ) {\n\t\tfor (int i=0; i < array.length - 1; i++) {\n\t\t\tint j = Int( i, array.length );\n\t\t\tif (j != i) {\n\t\t\t\tT t = array[i];\n\t\t\t\tarray[i] = array[j];\n\t\t\t\tarray[j] = t;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static<U,V> void shuffle( U[] u, V[]v ) {\n\t\tfor (int i=0; i < u.length - 1; i++) {\n\t\t\tint j = Int( i, u.length );\n\t\t\tif (j != i) {\n\t\t\t\tU ut = u[i];\n\t\t\t\tu[i] = u[j];\n\t\t\t\tu[j] = ut;\n\t\t\t\t\n\t\t\t\tV vt = v[i];\n\t\t\t\tv[i] = v[j];\n\t\t\t\tv[j] = vt;\n\t\t\t}\n\t\t}\n\t}\n}" } ]
import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.actors.Actor; import com.shatteredpixel.shatteredpixeldungeon.actors.Char; import com.shatteredpixel.shatteredpixeldungeon.actors.blobs.Blizzard; import com.shatteredpixel.shatteredpixeldungeon.actors.blobs.Blob; import com.shatteredpixel.shatteredpixeldungeon.actors.blobs.Fire; import com.shatteredpixel.shatteredpixeldungeon.actors.blobs.Freezing; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Burning; import com.shatteredpixel.shatteredpixeldungeon.effects.BlobEmitter; import com.shatteredpixel.shatteredpixeldungeon.effects.particles.ElmoParticle; import com.shatteredpixel.shatteredpixeldungeon.items.Generator; import com.shatteredpixel.shatteredpixeldungeon.items.Honeypot; import com.shatteredpixel.shatteredpixeldungeon.items.Item; import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfFrost; import com.shatteredpixel.shatteredpixeldungeon.levels.Level; import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain; import com.shatteredpixel.shatteredpixeldungeon.levels.painters.Painter; import com.shatteredpixel.shatteredpixeldungeon.levels.rooms.Room; import com.shatteredpixel.shatteredpixeldungeon.levels.rooms.standard.EmptyRoom; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene; import com.watabou.utils.PathFinder; import com.watabou.utils.Point; import com.watabou.utils.Random;
84,478
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.levels.rooms.special; public class MagicalFireRoom extends SpecialRoom { @Override public int minWidth() { return 7; } public int minHeight() { return 7; } @Override public void paint(Level level) { Painter.fill( level, this, Terrain.WALL ); Painter.fill( level, this, 1, Terrain.EMPTY ); Door door = entrance(); door.set( Door.Type.REGULAR ); Point firePos = center(); Room behindFire = new EmptyRoom(); if (door.x == left || door.x == right){ firePos.y = top+1; while (firePos.y != bottom){
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.levels.rooms.special; public class MagicalFireRoom extends SpecialRoom { @Override public int minWidth() { return 7; } public int minHeight() { return 7; } @Override public void paint(Level level) { Painter.fill( level, this, Terrain.WALL ); Painter.fill( level, this, 1, Terrain.EMPTY ); Door door = entrance(); door.set( Door.Type.REGULAR ); Point firePos = center(); Room behindFire = new EmptyRoom(); if (door.x == left || door.x == right){ firePos.y = top+1; while (firePos.y != bottom){
Blob.seed(level.pointToCell(firePos), 1, EternalFire.class, level);
4
2023-11-27 05:56:58+00:00
128k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/tests/org/jfree/chart/renderer/xy/XYStepAreaRendererTest.java
[ { "identifier": "JFreeChart", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/JFreeChart.java", "snippet": "public class JFreeChart implements Drawable, TitleChangeListener,\r\n PlotChangeListener, Serializable, Cloneable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -3470703747817429120L;\r\n\r\n /** Information about the project. */\r\n public static final ProjectInfo INFO = new JFreeChartInfo();\r\n\r\n /** The default font for titles. */\r\n public static final Font DEFAULT_TITLE_FONT\r\n = new Font(\"SansSerif\", Font.BOLD, 18);\r\n\r\n /** The default background color. */\r\n public static final Paint DEFAULT_BACKGROUND_PAINT\r\n = UIManager.getColor(\"Panel.background\");\r\n\r\n /** The default background image. */\r\n public static final Image DEFAULT_BACKGROUND_IMAGE = null;\r\n\r\n /** The default background image alignment. */\r\n public static final int DEFAULT_BACKGROUND_IMAGE_ALIGNMENT = Align.FIT;\r\n\r\n /** The default background image alpha. */\r\n public static final float DEFAULT_BACKGROUND_IMAGE_ALPHA = 0.5f;\r\n\r\n /**\r\n * The key for a rendering hint that can suppress the generation of a \r\n * shadow effect when drawing the chart. The hint value must be a \r\n * Boolean.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static final RenderingHints.Key KEY_SUPPRESS_SHADOW_GENERATION\r\n = new RenderingHints.Key(0) {\r\n @Override\r\n public boolean isCompatibleValue(Object val) {\r\n return val instanceof Boolean;\r\n }\r\n };\r\n \r\n /**\r\n * Rendering hints that will be used for chart drawing. This should never\r\n * be <code>null</code>.\r\n */\r\n private transient RenderingHints renderingHints;\r\n\r\n /** A flag that controls whether or not the chart border is drawn. */\r\n private boolean borderVisible;\r\n\r\n /** The stroke used to draw the chart border (if visible). */\r\n private transient Stroke borderStroke;\r\n\r\n /** The paint used to draw the chart border (if visible). */\r\n private transient Paint borderPaint;\r\n\r\n /** The padding between the chart border and the chart drawing area. */\r\n private RectangleInsets padding;\r\n\r\n /** The chart title (optional). */\r\n private TextTitle title;\r\n\r\n /**\r\n * The chart subtitles (zero, one or many). This field should never be\r\n * <code>null</code>.\r\n */\r\n private List subtitles;\r\n\r\n /** Draws the visual representation of the data. */\r\n private Plot plot;\r\n\r\n /** Paint used to draw the background of the chart. */\r\n private transient Paint backgroundPaint;\r\n\r\n /** An optional background image for the chart. */\r\n private transient Image backgroundImage; // todo: not serialized yet\r\n\r\n /** The alignment for the background image. */\r\n private int backgroundImageAlignment = Align.FIT;\r\n\r\n /** The alpha transparency for the background image. */\r\n private float backgroundImageAlpha = 0.5f;\r\n\r\n /** Storage for registered change listeners. */\r\n private transient EventListenerList changeListeners;\r\n\r\n /** Storage for registered progress listeners. */\r\n private transient EventListenerList progressListeners;\r\n\r\n /**\r\n * A flag that can be used to enable/disable notification of chart change\r\n * events.\r\n */\r\n private boolean notify;\r\n\r\n /**\r\n * Creates a new chart based on the supplied plot. The chart will have\r\n * a legend added automatically, but no title (although you can easily add\r\n * one later).\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(Plot plot) {\r\n this(null, null, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. A default font\r\n * ({@link #DEFAULT_TITLE_FONT}) is used for the title, and the chart will\r\n * have a legend added automatically.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(String title, Plot plot) {\r\n this(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. The\r\n * <code>createLegend</code> argument specifies whether or not a legend\r\n * should be added to the chart.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param titleFont the font for displaying the chart title\r\n * (<code>null</code> permitted).\r\n * @param plot controller of the visual representation of the data\r\n * (<code>null</code> not permitted).\r\n * @param createLegend a flag indicating whether or not a legend should\r\n * be created for the chart.\r\n */\r\n public JFreeChart(String title, Font titleFont, Plot plot,\r\n boolean createLegend) {\r\n\r\n ParamChecks.nullNotPermitted(plot, \"plot\");\r\n\r\n // create storage for listeners...\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.notify = true; // default is to notify listeners when the\r\n // chart changes\r\n\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n // added the following hint because of \r\n // http://stackoverflow.com/questions/7785082/\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n this.borderVisible = false;\r\n this.borderStroke = new BasicStroke(1.0f);\r\n this.borderPaint = Color.black;\r\n\r\n this.padding = RectangleInsets.ZERO_INSETS;\r\n\r\n this.plot = plot;\r\n plot.addChangeListener(this);\r\n\r\n this.subtitles = new ArrayList();\r\n\r\n // create a legend, if requested...\r\n if (createLegend) {\r\n LegendTitle legend = new LegendTitle(this.plot);\r\n legend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));\r\n legend.setFrame(new LineBorder());\r\n legend.setBackgroundPaint(Color.white);\r\n legend.setPosition(RectangleEdge.BOTTOM);\r\n this.subtitles.add(legend);\r\n legend.addChangeListener(this);\r\n }\r\n\r\n // add the chart title, if one has been specified...\r\n if (title != null) {\r\n if (titleFont == null) {\r\n titleFont = DEFAULT_TITLE_FONT;\r\n }\r\n this.title = new TextTitle(title, titleFont);\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n this.backgroundPaint = DEFAULT_BACKGROUND_PAINT;\r\n\r\n this.backgroundImage = DEFAULT_BACKGROUND_IMAGE;\r\n this.backgroundImageAlignment = DEFAULT_BACKGROUND_IMAGE_ALIGNMENT;\r\n this.backgroundImageAlpha = DEFAULT_BACKGROUND_IMAGE_ALPHA;\r\n\r\n }\r\n\r\n /**\r\n * Returns the collection of rendering hints for the chart.\r\n *\r\n * @return The rendering hints for the chart (never <code>null</code>).\r\n *\r\n * @see #setRenderingHints(RenderingHints)\r\n */\r\n public RenderingHints getRenderingHints() {\r\n return this.renderingHints;\r\n }\r\n\r\n /**\r\n * Sets the rendering hints for the chart. These will be added (using the\r\n * {@code Graphics2D.addRenderingHints()} method) near the start of the\r\n * {@code JFreeChart.draw()} method.\r\n *\r\n * @param renderingHints the rendering hints ({@code null} not permitted).\r\n *\r\n * @see #getRenderingHints()\r\n */\r\n public void setRenderingHints(RenderingHints renderingHints) {\r\n ParamChecks.nullNotPermitted(renderingHints, \"renderingHints\");\r\n this.renderingHints = renderingHints;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setBorderVisible(boolean)\r\n */\r\n public boolean isBorderVisible() {\r\n return this.borderVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isBorderVisible()\r\n */\r\n public void setBorderVisible(boolean visible) {\r\n this.borderVisible = visible;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the chart border (if visible).\r\n *\r\n * @return The border stroke.\r\n *\r\n * @see #setBorderStroke(Stroke)\r\n */\r\n public Stroke getBorderStroke() {\r\n return this.borderStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the chart border (if visible).\r\n *\r\n * @param stroke the stroke.\r\n *\r\n * @see #getBorderStroke()\r\n */\r\n public void setBorderStroke(Stroke stroke) {\r\n this.borderStroke = stroke;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the chart border (if visible).\r\n *\r\n * @return The border paint.\r\n *\r\n * @see #setBorderPaint(Paint)\r\n */\r\n public Paint getBorderPaint() {\r\n return this.borderPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the chart border (if visible).\r\n *\r\n * @param paint the paint.\r\n *\r\n * @see #getBorderPaint()\r\n */\r\n public void setBorderPaint(Paint paint) {\r\n this.borderPaint = paint;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the padding between the chart border and the chart drawing area.\r\n *\r\n * @return The padding (never <code>null</code>).\r\n *\r\n * @see #setPadding(RectangleInsets)\r\n */\r\n public RectangleInsets getPadding() {\r\n return this.padding;\r\n }\r\n\r\n /**\r\n * Sets the padding between the chart border and the chart drawing area,\r\n * and sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param padding the padding (<code>null</code> not permitted).\r\n *\r\n * @see #getPadding()\r\n */\r\n public void setPadding(RectangleInsets padding) {\r\n ParamChecks.nullNotPermitted(padding, \"padding\");\r\n this.padding = padding;\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the main chart title. Very often a chart will have just one\r\n * title, so we make this case simple by providing accessor methods for\r\n * the main title. However, multiple titles are supported - see the\r\n * {@link #addSubtitle(Title)} method.\r\n *\r\n * @return The chart title (possibly <code>null</code>).\r\n *\r\n * @see #setTitle(TextTitle)\r\n */\r\n public TextTitle getTitle() {\r\n return this.title;\r\n }\r\n\r\n /**\r\n * Sets the main title for the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners. If you do not want a title for the\r\n * chart, set it to <code>null</code>. If you want more than one title on\r\n * a chart, use the {@link #addSubtitle(Title)} method.\r\n *\r\n * @param title the title (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(TextTitle title) {\r\n if (this.title != null) {\r\n this.title.removeChangeListener(this);\r\n }\r\n this.title = title;\r\n if (title != null) {\r\n title.addChangeListener(this);\r\n }\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Sets the chart title and sends a {@link ChartChangeEvent} to all\r\n * registered listeners. This is a convenience method that ends up calling\r\n * the {@link #setTitle(TextTitle)} method. If there is an existing title,\r\n * its text is updated, otherwise a new title using the default font is\r\n * added to the chart. If <code>text</code> is <code>null</code> the chart\r\n * title is set to <code>null</code>.\r\n *\r\n * @param text the title text (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(String text) {\r\n if (text != null) {\r\n if (this.title == null) {\r\n setTitle(new TextTitle(text, JFreeChart.DEFAULT_TITLE_FONT));\r\n }\r\n else {\r\n this.title.setText(text);\r\n }\r\n }\r\n else {\r\n setTitle((TextTitle) null);\r\n }\r\n }\r\n\r\n /**\r\n * Adds a legend to the plot and sends a {@link ChartChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param legend the legend (<code>null</code> not permitted).\r\n *\r\n * @see #removeLegend()\r\n */\r\n public void addLegend(LegendTitle legend) {\r\n addSubtitle(legend);\r\n }\r\n\r\n /**\r\n * Returns the legend for the chart, if there is one. Note that a chart\r\n * can have more than one legend - this method returns the first.\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #getLegend(int)\r\n */\r\n public LegendTitle getLegend() {\r\n return getLegend(0);\r\n }\r\n\r\n /**\r\n * Returns the nth legend for a chart, or <code>null</code>.\r\n *\r\n * @param index the legend index (zero-based).\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #addLegend(LegendTitle)\r\n */\r\n public LegendTitle getLegend(int index) {\r\n int seen = 0;\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title subtitle = (Title) iterator.next();\r\n if (subtitle instanceof LegendTitle) {\r\n if (seen == index) {\r\n return (LegendTitle) subtitle;\r\n }\r\n else {\r\n seen++;\r\n }\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Removes the first legend in the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @see #getLegend()\r\n */\r\n public void removeLegend() {\r\n removeSubtitle(getLegend());\r\n }\r\n\r\n /**\r\n * Returns the list of subtitles for the chart.\r\n *\r\n * @return The subtitle list (possibly empty, but never <code>null</code>).\r\n *\r\n * @see #setSubtitles(List)\r\n */\r\n public List getSubtitles() {\r\n return new ArrayList(this.subtitles);\r\n }\r\n\r\n /**\r\n * Sets the title list for the chart (completely replaces any existing\r\n * titles) and sends a {@link ChartChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param subtitles the new list of subtitles (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public void setSubtitles(List subtitles) {\r\n if (subtitles == null) {\r\n throw new NullPointerException(\"Null 'subtitles' argument.\");\r\n }\r\n setNotify(false);\r\n clearSubtitles();\r\n Iterator iterator = subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n if (t != null) {\r\n addSubtitle(t);\r\n }\r\n }\r\n setNotify(true); // this fires a ChartChangeEvent\r\n }\r\n\r\n /**\r\n * Returns the number of titles for the chart.\r\n *\r\n * @return The number of titles for the chart.\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public int getSubtitleCount() {\r\n return this.subtitles.size();\r\n }\r\n\r\n /**\r\n * Returns a chart subtitle.\r\n *\r\n * @param index the index of the chart subtitle (zero based).\r\n *\r\n * @return A chart subtitle.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public Title getSubtitle(int index) {\r\n if ((index < 0) || (index >= getSubtitleCount())) {\r\n throw new IllegalArgumentException(\"Index out of range.\");\r\n }\r\n return (Title) this.subtitles.get(index);\r\n }\r\n\r\n /**\r\n * Adds a chart subtitle, and notifies registered listeners that the chart\r\n * has been modified.\r\n *\r\n * @param subtitle the subtitle (<code>null</code> not permitted).\r\n *\r\n * @see #getSubtitle(int)\r\n */\r\n public void addSubtitle(Title subtitle) {\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Adds a subtitle at a particular position in the subtitle list, and sends\r\n * a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param index the index (in the range 0 to {@link #getSubtitleCount()}).\r\n * @param subtitle the subtitle to add (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.6\r\n */\r\n public void addSubtitle(int index, Title subtitle) {\r\n if (index < 0 || index > getSubtitleCount()) {\r\n throw new IllegalArgumentException(\r\n \"The 'index' argument is out of range.\");\r\n }\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(index, subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Clears all subtitles from the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void clearSubtitles() {\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n t.removeChangeListener(this);\r\n }\r\n this.subtitles.clear();\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Removes the specified subtitle and sends a {@link ChartChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param title the title.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void removeSubtitle(Title title) {\r\n this.subtitles.remove(title);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the plot for the chart. The plot is a class responsible for\r\n * coordinating the visual representation of the data, including the axes\r\n * (if any).\r\n *\r\n * @return The plot.\r\n */\r\n public Plot getPlot() {\r\n return this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as a {@link CategoryPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link CategoryPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public CategoryPlot getCategoryPlot() {\r\n return (CategoryPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as an {@link XYPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link XYPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public XYPlot getXYPlot() {\r\n return (XYPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns a flag that indicates whether or not anti-aliasing is used when\r\n * the chart is drawn.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAntiAlias(boolean)\r\n */\r\n public boolean getAntiAlias() {\r\n Object val = this.renderingHints.get(RenderingHints.KEY_ANTIALIASING);\r\n return RenderingHints.VALUE_ANTIALIAS_ON.equals(val);\r\n }\r\n\r\n /**\r\n * Sets a flag that indicates whether or not anti-aliasing is used when the\r\n * chart is drawn.\r\n * <P>\r\n * Anti-aliasing usually improves the appearance of charts, but is slower.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #getAntiAlias()\r\n */\r\n public void setAntiAlias(boolean flag) {\r\n Object hint = flag ? RenderingHints.VALUE_ANTIALIAS_ON \r\n : RenderingHints.VALUE_ANTIALIAS_OFF;\r\n this.renderingHints.put(RenderingHints.KEY_ANTIALIASING, hint);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the current value stored in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING}.\r\n *\r\n * @return The hint value (possibly <code>null</code>).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public Object getTextAntiAlias() {\r\n return this.renderingHints.get(RenderingHints.KEY_TEXT_ANTIALIASING);\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} to either\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_ON} or\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_OFF}, then sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public void setTextAntiAlias(boolean flag) {\r\n if (flag) {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\r\n }\r\n else {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);\r\n }\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param val the new value (<code>null</code> permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(boolean)\r\n */\r\n public void setTextAntiAlias(Object val) {\r\n this.renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, val);\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the paint used for the chart background.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundPaint(Paint)\r\n */\r\n public Paint getBackgroundPaint() {\r\n return this.backgroundPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to fill the chart background and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundPaint()\r\n */\r\n public void setBackgroundPaint(Paint paint) {\r\n\r\n if (this.backgroundPaint != null) {\r\n if (!this.backgroundPaint.equals(paint)) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (paint != null) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image for the chart, or <code>null</code> if\r\n * there is no image.\r\n *\r\n * @return The image (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundImage(Image)\r\n */\r\n public Image getBackgroundImage() {\r\n return this.backgroundImage;\r\n }\r\n\r\n /**\r\n * Sets the background image for the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param image the image (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundImage()\r\n */\r\n public void setBackgroundImage(Image image) {\r\n\r\n if (this.backgroundImage != null) {\r\n if (!this.backgroundImage.equals(image)) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (image != null) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image alignment. Alignment constants are defined\r\n * in the <code>org.jfree.ui.Align</code> class in the JCommon class\r\n * library.\r\n *\r\n * @return The alignment.\r\n *\r\n * @see #setBackgroundImageAlignment(int)\r\n */\r\n public int getBackgroundImageAlignment() {\r\n return this.backgroundImageAlignment;\r\n }\r\n\r\n /**\r\n * Sets the background alignment. Alignment options are defined by the\r\n * {@link org.jfree.ui.Align} class.\r\n *\r\n * @param alignment the alignment.\r\n *\r\n * @see #getBackgroundImageAlignment()\r\n */\r\n public void setBackgroundImageAlignment(int alignment) {\r\n if (this.backgroundImageAlignment != alignment) {\r\n this.backgroundImageAlignment = alignment;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha-transparency for the chart's background image.\r\n *\r\n * @return The alpha-transparency.\r\n *\r\n * @see #setBackgroundImageAlpha(float)\r\n */\r\n public float getBackgroundImageAlpha() {\r\n return this.backgroundImageAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha-transparency for the chart's background image.\r\n * Registered listeners are notified that the chart has been changed.\r\n *\r\n * @param alpha the alpha value.\r\n *\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void setBackgroundImageAlpha(float alpha) {\r\n\r\n if (this.backgroundImageAlpha != alpha) {\r\n this.backgroundImageAlpha = alpha;\r\n fireChartChanged();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not change events are sent to\r\n * registered listeners.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNotify(boolean)\r\n */\r\n public boolean isNotify() {\r\n return this.notify;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not listeners receive\r\n * {@link ChartChangeEvent} notifications.\r\n *\r\n * @param notify a boolean.\r\n *\r\n * @see #isNotify()\r\n */\r\n public void setNotify(boolean notify) {\r\n this.notify = notify;\r\n // if the flag is being set to true, there may be queued up changes...\r\n if (notify) {\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area) {\r\n draw(g2, area, null, null);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer). This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D area, ChartRenderingInfo info) {\r\n draw(g2, area, null, info);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param chartArea the area within which the chart should be drawn.\r\n * @param anchor the anchor point (in Java2D space) for the chart\r\n * (<code>null</code> permitted).\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D chartArea, Point2D anchor,\r\n ChartRenderingInfo info) {\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_STARTED, 0));\r\n \r\n EntityCollection entities = null;\r\n // record the chart area, if info is requested...\r\n if (info != null) {\r\n info.clear();\r\n info.setChartArea(chartArea);\r\n entities = info.getEntityCollection();\r\n }\r\n if (entities != null) {\r\n entities.add(new JFreeChartEntity((Rectangle2D) chartArea.clone(),\r\n this));\r\n }\r\n\r\n // ensure no drawing occurs outside chart area...\r\n Shape savedClip = g2.getClip();\r\n g2.clip(chartArea);\r\n\r\n g2.addRenderingHints(this.renderingHints);\r\n\r\n // draw the chart background...\r\n if (this.backgroundPaint != null) {\r\n g2.setPaint(this.backgroundPaint);\r\n g2.fill(chartArea);\r\n }\r\n\r\n if (this.backgroundImage != null) {\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundImageAlpha));\r\n Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,\r\n this.backgroundImage.getWidth(null),\r\n this.backgroundImage.getHeight(null));\r\n Align.align(dest, chartArea, this.backgroundImageAlignment);\r\n g2.drawImage(this.backgroundImage, (int) dest.getX(),\r\n (int) dest.getY(), (int) dest.getWidth(),\r\n (int) dest.getHeight(), null);\r\n g2.setComposite(originalComposite);\r\n }\r\n\r\n if (isBorderVisible()) {\r\n Paint paint = getBorderPaint();\r\n Stroke stroke = getBorderStroke();\r\n if (paint != null && stroke != null) {\r\n Rectangle2D borderArea = new Rectangle2D.Double(\r\n chartArea.getX(), chartArea.getY(),\r\n chartArea.getWidth() - 1.0, chartArea.getHeight()\r\n - 1.0);\r\n g2.setPaint(paint);\r\n g2.setStroke(stroke);\r\n g2.draw(borderArea);\r\n }\r\n }\r\n\r\n // draw the title and subtitles...\r\n Rectangle2D nonTitleArea = new Rectangle2D.Double();\r\n nonTitleArea.setRect(chartArea);\r\n this.padding.trim(nonTitleArea);\r\n\r\n if (this.title != null && this.title.isVisible()) {\r\n EntityCollection e = drawTitle(this.title, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title currentTitle = (Title) iterator.next();\r\n if (currentTitle.isVisible()) {\r\n EntityCollection e = drawTitle(currentTitle, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n }\r\n\r\n Rectangle2D plotArea = nonTitleArea;\r\n\r\n // draw the plot (axes and data visualisation)\r\n PlotRenderingInfo plotInfo = null;\r\n if (info != null) {\r\n plotInfo = info.getPlotInfo();\r\n }\r\n this.plot.draw(g2, plotArea, anchor, null, plotInfo);\r\n\r\n g2.setClip(savedClip);\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_FINISHED, 100));\r\n }\r\n\r\n /**\r\n * Creates a rectangle that is aligned to the frame.\r\n *\r\n * @param dimensions the dimensions for the rectangle.\r\n * @param frame the frame to align to.\r\n * @param hAlign the horizontal alignment.\r\n * @param vAlign the vertical alignment.\r\n *\r\n * @return A rectangle.\r\n */\r\n private Rectangle2D createAlignedRectangle2D(Size2D dimensions,\r\n Rectangle2D frame, HorizontalAlignment hAlign,\r\n VerticalAlignment vAlign) {\r\n double x = Double.NaN;\r\n double y = Double.NaN;\r\n if (hAlign == HorizontalAlignment.LEFT) {\r\n x = frame.getX();\r\n }\r\n else if (hAlign == HorizontalAlignment.CENTER) {\r\n x = frame.getCenterX() - (dimensions.width / 2.0);\r\n }\r\n else if (hAlign == HorizontalAlignment.RIGHT) {\r\n x = frame.getMaxX() - dimensions.width;\r\n }\r\n if (vAlign == VerticalAlignment.TOP) {\r\n y = frame.getY();\r\n }\r\n else if (vAlign == VerticalAlignment.CENTER) {\r\n y = frame.getCenterY() - (dimensions.height / 2.0);\r\n }\r\n else if (vAlign == VerticalAlignment.BOTTOM) {\r\n y = frame.getMaxY() - dimensions.height;\r\n }\r\n\r\n return new Rectangle2D.Double(x, y, dimensions.width,\r\n dimensions.height);\r\n }\r\n\r\n /**\r\n * Draws a title. The title should be drawn at the top, bottom, left or\r\n * right of the specified area, and the area should be updated to reflect\r\n * the amount of space used by the title.\r\n *\r\n * @param t the title (<code>null</code> not permitted).\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param area the chart area, excluding any existing titles\r\n * (<code>null</code> not permitted).\r\n * @param entities a flag that controls whether or not an entity\r\n * collection is returned for the title.\r\n *\r\n * @return An entity collection for the title (possibly <code>null</code>).\r\n */\r\n protected EntityCollection drawTitle(Title t, Graphics2D g2,\r\n Rectangle2D area, boolean entities) {\r\n\r\n ParamChecks.nullNotPermitted(t, \"t\");\r\n ParamChecks.nullNotPermitted(area, \"area\");\r\n Rectangle2D titleArea;\r\n RectangleEdge position = t.getPosition();\r\n double ww = area.getWidth();\r\n if (ww <= 0.0) {\r\n return null;\r\n }\r\n double hh = area.getHeight();\r\n if (hh <= 0.0) {\r\n return null;\r\n }\r\n RectangleConstraint constraint = new RectangleConstraint(ww,\r\n new Range(0.0, ww), LengthConstraintType.RANGE, hh,\r\n new Range(0.0, hh), LengthConstraintType.RANGE);\r\n Object retValue = null;\r\n BlockParams p = new BlockParams();\r\n p.setGenerateEntities(entities);\r\n if (position == RectangleEdge.TOP) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.TOP);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), Math.min(area.getY() + size.height,\r\n area.getMaxY()), area.getWidth(), Math.max(area.getHeight()\r\n - size.height, 0));\r\n }\r\n else if (position == RectangleEdge.BOTTOM) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.BOTTOM);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth(),\r\n area.getHeight() - size.height);\r\n }\r\n else if (position == RectangleEdge.RIGHT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.RIGHT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n\r\n else if (position == RectangleEdge.LEFT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.LEFT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX() + size.width, area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n else {\r\n throw new RuntimeException(\"Unrecognised title position.\");\r\n }\r\n EntityCollection result = null;\r\n if (retValue instanceof EntityBlockResult) {\r\n EntityBlockResult ebr = (EntityBlockResult) retValue;\r\n result = ebr.getEntityCollection();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height) {\r\n return createBufferedImage(width, height, null);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n ChartRenderingInfo info) {\r\n return createBufferedImage(width, height, BufferedImage.TYPE_INT_ARGB,\r\n info);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param imageType the image type.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n int imageType,\r\n ChartRenderingInfo info) {\r\n BufferedImage image = new BufferedImage(width, height, imageType);\r\n Graphics2D g2 = image.createGraphics();\r\n draw(g2, new Rectangle2D.Double(0, 0, width, height), null, info);\r\n g2.dispose();\r\n return image;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param imageWidth the image width.\r\n * @param imageHeight the image height.\r\n * @param drawWidth the width for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param drawHeight the height for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param info optional object for collection chart dimension and entity\r\n * information.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int imageWidth,\r\n int imageHeight,\r\n double drawWidth,\r\n double drawHeight,\r\n ChartRenderingInfo info) {\r\n\r\n BufferedImage image = new BufferedImage(imageWidth, imageHeight,\r\n BufferedImage.TYPE_INT_ARGB);\r\n Graphics2D g2 = image.createGraphics();\r\n double scaleX = imageWidth / drawWidth;\r\n double scaleY = imageHeight / drawHeight;\r\n AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);\r\n g2.transform(st);\r\n draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,\r\n info);\r\n g2.dispose();\r\n return image;\r\n\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the chart. JFreeChart is not a UI component, so\r\n * some other object (for example, {@link ChartPanel}) needs to capture\r\n * the click event and pass it onto the JFreeChart object.\r\n * If you are not using JFreeChart in a client application, then this\r\n * method is not required.\r\n *\r\n * @param x x-coordinate of the click (in Java2D space).\r\n * @param y y-coordinate of the click (in Java2D space).\r\n * @param info contains chart dimension and entity information\r\n * (<code>null</code> not permitted).\r\n */\r\n public void handleClick(int x, int y, ChartRenderingInfo info) {\r\n\r\n // pass the click on to the plot...\r\n // rely on the plot to post a plot change event and redraw the chart...\r\n this.plot.handleClick(x, y, info.getPlotInfo());\r\n\r\n }\r\n\r\n /**\r\n * Registers an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted).\r\n *\r\n * @see #removeChangeListener(ChartChangeListener)\r\n */\r\n public void addChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.add(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted)\r\n *\r\n * @see #addChangeListener(ChartChangeListener)\r\n */\r\n public void removeChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.remove(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a default {@link ChartChangeEvent} to all registered listeners.\r\n * <P>\r\n * This method is for convenience only.\r\n */\r\n public void fireChartChanged() {\r\n ChartChangeEvent event = new ChartChangeEvent(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartChangeEvent event) {\r\n if (this.notify) {\r\n Object[] listeners = this.changeListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartChangeListener.class) {\r\n ((ChartChangeListener) listeners[i + 1]).chartChanged(\r\n event);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Registers an object for notification of progress events relating to the\r\n * chart.\r\n *\r\n * @param listener the object being registered.\r\n *\r\n * @see #removeProgressListener(ChartProgressListener)\r\n */\r\n public void addProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.add(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the object being deregistered.\r\n *\r\n * @see #addProgressListener(ChartProgressListener)\r\n */\r\n public void removeProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.remove(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartProgressEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartProgressEvent event) {\r\n\r\n Object[] listeners = this.progressListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartProgressListener.class) {\r\n ((ChartProgressListener) listeners[i + 1]).chartProgress(event);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Receives notification that a chart title has changed, and passes this\r\n * on to registered listeners.\r\n *\r\n * @param event information about the chart title change.\r\n */\r\n @Override\r\n public void titleChanged(TitleChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Receives notification that the plot has changed, and passes this on to\r\n * registered listeners.\r\n *\r\n * @param event information about the plot change.\r\n */\r\n @Override\r\n public void plotChanged(PlotChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Tests this chart for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof JFreeChart)) {\r\n return false;\r\n }\r\n JFreeChart that = (JFreeChart) obj;\r\n if (!this.renderingHints.equals(that.renderingHints)) {\r\n return false;\r\n }\r\n if (this.borderVisible != that.borderVisible) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.borderStroke, that.borderStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.borderPaint, that.borderPaint)) {\r\n return false;\r\n }\r\n if (!this.padding.equals(that.padding)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.title, that.title)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.subtitles, that.subtitles)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.plot, that.plot)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(\r\n this.backgroundPaint, that.backgroundPaint\r\n )) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundImage,\r\n that.backgroundImage)) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlignment != that.backgroundImageAlignment) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlpha != that.backgroundImageAlpha) {\r\n return false;\r\n }\r\n if (this.notify != that.notify) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.borderStroke, stream);\r\n SerialUtilities.writePaint(this.borderPaint, stream);\r\n SerialUtilities.writePaint(this.backgroundPaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.borderStroke = SerialUtilities.readStroke(stream);\r\n this.borderPaint = SerialUtilities.readPaint(stream);\r\n this.backgroundPaint = SerialUtilities.readPaint(stream);\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n // register as a listener with sub-components...\r\n if (this.title != null) {\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n getSubtitle(i).addChangeListener(this);\r\n }\r\n this.plot.addChangeListener(this);\r\n }\r\n\r\n /**\r\n * Prints information about JFreeChart to standard output.\r\n *\r\n * @param args no arguments are honored.\r\n */\r\n public static void main(String[] args) {\r\n System.out.println(JFreeChart.INFO.toString());\r\n }\r\n\r\n /**\r\n * Clones the object, and takes care of listeners.\r\n * Note: caller shall register its own listeners on cloned graph.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the chart is not cloneable.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n JFreeChart chart = (JFreeChart) super.clone();\r\n\r\n chart.renderingHints = (RenderingHints) this.renderingHints.clone();\r\n // private boolean borderVisible;\r\n // private transient Stroke borderStroke;\r\n // private transient Paint borderPaint;\r\n\r\n if (this.title != null) {\r\n chart.title = (TextTitle) this.title.clone();\r\n chart.title.addChangeListener(chart);\r\n }\r\n\r\n chart.subtitles = new ArrayList();\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n Title subtitle = (Title) getSubtitle(i).clone();\r\n chart.subtitles.add(subtitle);\r\n subtitle.addChangeListener(chart);\r\n }\r\n\r\n if (this.plot != null) {\r\n chart.plot = (Plot) this.plot.clone();\r\n chart.plot.addChangeListener(chart);\r\n }\r\n\r\n chart.progressListeners = new EventListenerList();\r\n chart.changeListeners = new EventListenerList();\r\n return chart;\r\n }\r\n\r\n}\r" }, { "identifier": "TestUtilities", "path": "lib/jfreechart-1.0.19/tests/org/jfree/chart/TestUtilities.java", "snippet": "public class TestUtilities {\n\n /**\n * Returns <code>true</code> if the collections contains any object that\n * is an instance of the specified class, and <code>false</code> otherwise.\n *\n * @param collection the collection.\n * @param c the class.\n *\n * @return A boolean.\n */\n public static boolean containsInstanceOf(Collection collection, Class c) {\n Iterator iterator = collection.iterator();\n while (iterator.hasNext()) {\n Object obj = iterator.next();\n if (obj != null && obj.getClass().equals(c)) {\n return true;\n }\n }\n return false;\n }\n\n public static Object serialised(Object original) {\n Object result = null;\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n ObjectOutput out;\n try {\n out = new ObjectOutputStream(buffer);\n out.writeObject(original);\n out.close();\n ObjectInput in = new ObjectInputStream(\n new ByteArrayInputStream(buffer.toByteArray()));\n result = in.readObject();\n in.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n return result;\n }\n \n}" }, { "identifier": "NumberAxis", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/axis/NumberAxis.java", "snippet": "public class NumberAxis extends ValueAxis implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 2805933088476185789L;\r\n\r\n /** The default value for the autoRangeIncludesZero flag. */\r\n public static final boolean DEFAULT_AUTO_RANGE_INCLUDES_ZERO = true;\r\n\r\n /** The default value for the autoRangeStickyZero flag. */\r\n public static final boolean DEFAULT_AUTO_RANGE_STICKY_ZERO = true;\r\n\r\n /** The default tick unit. */\r\n public static final NumberTickUnit DEFAULT_TICK_UNIT = new NumberTickUnit(\r\n 1.0, new DecimalFormat(\"0\"));\r\n\r\n /** The default setting for the vertical tick labels flag. */\r\n public static final boolean DEFAULT_VERTICAL_TICK_LABELS = false;\r\n\r\n /**\r\n * The range type (can be used to force the axis to display only positive\r\n * values or only negative values).\r\n */\r\n private RangeType rangeType;\r\n\r\n /**\r\n * A flag that affects the axis range when the range is determined\r\n * automatically. If the auto range does NOT include zero and this flag\r\n * is TRUE, then the range is changed to include zero.\r\n */\r\n private boolean autoRangeIncludesZero;\r\n\r\n /**\r\n * A flag that affects the size of the margins added to the axis range when\r\n * the range is determined automatically. If the value 0 falls within the\r\n * margin and this flag is TRUE, then the margin is truncated at zero.\r\n */\r\n private boolean autoRangeStickyZero;\r\n\r\n /** The tick unit for the axis. */\r\n private NumberTickUnit tickUnit;\r\n\r\n /** The override number format. */\r\n private NumberFormat numberFormatOverride;\r\n\r\n /** An optional band for marking regions on the axis. */\r\n private MarkerAxisBand markerBand;\r\n\r\n /**\r\n * Default constructor.\r\n */\r\n public NumberAxis() {\r\n this(null);\r\n }\r\n\r\n /**\r\n * Constructs a number axis, using default values where necessary.\r\n *\r\n * @param label the axis label (<code>null</code> permitted).\r\n */\r\n public NumberAxis(String label) {\r\n super(label, NumberAxis.createStandardTickUnits());\r\n this.rangeType = RangeType.FULL;\r\n this.autoRangeIncludesZero = DEFAULT_AUTO_RANGE_INCLUDES_ZERO;\r\n this.autoRangeStickyZero = DEFAULT_AUTO_RANGE_STICKY_ZERO;\r\n this.tickUnit = DEFAULT_TICK_UNIT;\r\n this.numberFormatOverride = null;\r\n this.markerBand = null;\r\n }\r\n\r\n /**\r\n * Returns the axis range type.\r\n *\r\n * @return The axis range type (never <code>null</code>).\r\n *\r\n * @see #setRangeType(RangeType)\r\n */\r\n public RangeType getRangeType() {\r\n return this.rangeType;\r\n }\r\n\r\n /**\r\n * Sets the axis range type.\r\n *\r\n * @param rangeType the range type (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeType()\r\n */\r\n public void setRangeType(RangeType rangeType) {\r\n ParamChecks.nullNotPermitted(rangeType, \"rangeType\");\r\n this.rangeType = rangeType;\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the flag that indicates whether or not the automatic axis range\r\n * (if indeed it is determined automatically) is forced to include zero.\r\n *\r\n * @return The flag.\r\n */\r\n public boolean getAutoRangeIncludesZero() {\r\n return this.autoRangeIncludesZero;\r\n }\r\n\r\n /**\r\n * Sets the flag that indicates whether or not the axis range, if\r\n * automatically calculated, is forced to include zero.\r\n * <p>\r\n * If the flag is changed to <code>true</code>, the axis range is\r\n * recalculated.\r\n * <p>\r\n * Any change to the flag will trigger an {@link AxisChangeEvent}.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #getAutoRangeIncludesZero()\r\n */\r\n public void setAutoRangeIncludesZero(boolean flag) {\r\n if (this.autoRangeIncludesZero != flag) {\r\n this.autoRangeIncludesZero = flag;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag that affects the auto-range when zero falls outside the\r\n * data range but inside the margins defined for the axis.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAutoRangeStickyZero(boolean)\r\n */\r\n public boolean getAutoRangeStickyZero() {\r\n return this.autoRangeStickyZero;\r\n }\r\n\r\n /**\r\n * Sets a flag that affects the auto-range when zero falls outside the data\r\n * range but inside the margins defined for the axis.\r\n *\r\n * @param flag the new flag.\r\n *\r\n * @see #getAutoRangeStickyZero()\r\n */\r\n public void setAutoRangeStickyZero(boolean flag) {\r\n if (this.autoRangeStickyZero != flag) {\r\n this.autoRangeStickyZero = flag;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the tick unit for the axis.\r\n * <p>\r\n * Note: if the <code>autoTickUnitSelection</code> flag is\r\n * <code>true</code> the tick unit may be changed while the axis is being\r\n * drawn, so in that case the return value from this method may be\r\n * irrelevant if the method is called before the axis has been drawn.\r\n *\r\n * @return The tick unit for the axis.\r\n *\r\n * @see #setTickUnit(NumberTickUnit)\r\n * @see ValueAxis#isAutoTickUnitSelection()\r\n */\r\n public NumberTickUnit getTickUnit() {\r\n return this.tickUnit;\r\n }\r\n\r\n /**\r\n * Sets the tick unit for the axis and sends an {@link AxisChangeEvent} to\r\n * all registered listeners. A side effect of calling this method is that\r\n * the \"auto-select\" feature for tick units is switched off (you can\r\n * restore it using the {@link ValueAxis#setAutoTickUnitSelection(boolean)}\r\n * method).\r\n *\r\n * @param unit the new tick unit (<code>null</code> not permitted).\r\n *\r\n * @see #getTickUnit()\r\n * @see #setTickUnit(NumberTickUnit, boolean, boolean)\r\n */\r\n public void setTickUnit(NumberTickUnit unit) {\r\n // defer argument checking...\r\n setTickUnit(unit, true, true);\r\n }\r\n\r\n /**\r\n * Sets the tick unit for the axis and, if requested, sends an\r\n * {@link AxisChangeEvent} to all registered listeners. In addition, an\r\n * option is provided to turn off the \"auto-select\" feature for tick units\r\n * (you can restore it using the\r\n * {@link ValueAxis#setAutoTickUnitSelection(boolean)} method).\r\n *\r\n * @param unit the new tick unit (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n * @param turnOffAutoSelect turn off the auto-tick selection?\r\n */\r\n public void setTickUnit(NumberTickUnit unit, boolean notify,\r\n boolean turnOffAutoSelect) {\r\n\r\n ParamChecks.nullNotPermitted(unit, \"unit\");\r\n this.tickUnit = unit;\r\n if (turnOffAutoSelect) {\r\n setAutoTickUnitSelection(false, false);\r\n }\r\n if (notify) {\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the number format override. If this is non-null, then it will\r\n * be used to format the numbers on the axis.\r\n *\r\n * @return The number formatter (possibly <code>null</code>).\r\n *\r\n * @see #setNumberFormatOverride(NumberFormat)\r\n */\r\n public NumberFormat getNumberFormatOverride() {\r\n return this.numberFormatOverride;\r\n }\r\n\r\n /**\r\n * Sets the number format override. If this is non-null, then it will be\r\n * used to format the numbers on the axis.\r\n *\r\n * @param formatter the number formatter (<code>null</code> permitted).\r\n *\r\n * @see #getNumberFormatOverride()\r\n */\r\n public void setNumberFormatOverride(NumberFormat formatter) {\r\n this.numberFormatOverride = formatter;\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the (optional) marker band for the axis.\r\n *\r\n * @return The marker band (possibly <code>null</code>).\r\n *\r\n * @see #setMarkerBand(MarkerAxisBand)\r\n */\r\n public MarkerAxisBand getMarkerBand() {\r\n return this.markerBand;\r\n }\r\n\r\n /**\r\n * Sets the marker band for the axis.\r\n * <P>\r\n * The marker band is optional, leave it set to <code>null</code> if you\r\n * don't require it.\r\n *\r\n * @param band the new band (<code>null</code> permitted).\r\n *\r\n * @see #getMarkerBand()\r\n */\r\n public void setMarkerBand(MarkerAxisBand band) {\r\n this.markerBand = band;\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Configures the axis to work with the specified plot. If the axis has\r\n * auto-scaling, then sets the maximum and minimum values.\r\n */\r\n @Override\r\n public void configure() {\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n }\r\n\r\n /**\r\n * Rescales the axis to ensure that all data is visible.\r\n */\r\n @Override\r\n protected void autoAdjustRange() {\r\n\r\n Plot plot = getPlot();\r\n if (plot == null) {\r\n return; // no plot, no data\r\n }\r\n\r\n if (plot instanceof ValueAxisPlot) {\r\n ValueAxisPlot vap = (ValueAxisPlot) plot;\r\n\r\n Range r = vap.getDataRange(this);\r\n if (r == null) {\r\n r = getDefaultAutoRange();\r\n }\r\n\r\n double upper = r.getUpperBound();\r\n double lower = r.getLowerBound();\r\n if (this.rangeType == RangeType.POSITIVE) {\r\n lower = Math.max(0.0, lower);\r\n upper = Math.max(0.0, upper);\r\n }\r\n else if (this.rangeType == RangeType.NEGATIVE) {\r\n lower = Math.min(0.0, lower);\r\n upper = Math.min(0.0, upper);\r\n }\r\n\r\n if (getAutoRangeIncludesZero()) {\r\n lower = Math.min(lower, 0.0);\r\n upper = Math.max(upper, 0.0);\r\n }\r\n double range = upper - lower;\r\n\r\n // if fixed auto range, then derive lower bound...\r\n double fixedAutoRange = getFixedAutoRange();\r\n if (fixedAutoRange > 0.0) {\r\n lower = upper - fixedAutoRange;\r\n }\r\n else {\r\n // ensure the autorange is at least <minRange> in size...\r\n double minRange = getAutoRangeMinimumSize();\r\n if (range < minRange) {\r\n double expand = (minRange - range) / 2;\r\n upper = upper + expand;\r\n lower = lower - expand;\r\n if (lower == upper) { // see bug report 1549218\r\n double adjust = Math.abs(lower) / 10.0;\r\n lower = lower - adjust;\r\n upper = upper + adjust;\r\n }\r\n if (this.rangeType == RangeType.POSITIVE) {\r\n if (lower < 0.0) {\r\n upper = upper - lower;\r\n lower = 0.0;\r\n }\r\n }\r\n else if (this.rangeType == RangeType.NEGATIVE) {\r\n if (upper > 0.0) {\r\n lower = lower - upper;\r\n upper = 0.0;\r\n }\r\n }\r\n }\r\n\r\n if (getAutoRangeStickyZero()) {\r\n if (upper <= 0.0) {\r\n upper = Math.min(0.0, upper + getUpperMargin() * range);\r\n }\r\n else {\r\n upper = upper + getUpperMargin() * range;\r\n }\r\n if (lower >= 0.0) {\r\n lower = Math.max(0.0, lower - getLowerMargin() * range);\r\n }\r\n else {\r\n lower = lower - getLowerMargin() * range;\r\n }\r\n }\r\n else {\r\n upper = upper + getUpperMargin() * range;\r\n lower = lower - getLowerMargin() * range;\r\n }\r\n }\r\n\r\n setRange(new Range(lower, upper), false, false);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Converts a data value to a coordinate in Java2D space, assuming that the\r\n * axis runs along one edge of the specified dataArea.\r\n * <p>\r\n * Note that it is possible for the coordinate to fall outside the plotArea.\r\n *\r\n * @param value the data value.\r\n * @param area the area for plotting the data.\r\n * @param edge the axis location.\r\n *\r\n * @return The Java2D coordinate.\r\n *\r\n * @see #java2DToValue(double, Rectangle2D, RectangleEdge)\r\n */\r\n @Override\r\n public double valueToJava2D(double value, Rectangle2D area,\r\n RectangleEdge edge) {\r\n\r\n Range range = getRange();\r\n double axisMin = range.getLowerBound();\r\n double axisMax = range.getUpperBound();\r\n\r\n double min = 0.0;\r\n double max = 0.0;\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n min = area.getX();\r\n max = area.getMaxX();\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n max = area.getMinY();\r\n min = area.getMaxY();\r\n }\r\n if (isInverted()) {\r\n return max\r\n - ((value - axisMin) / (axisMax - axisMin)) * (max - min);\r\n }\r\n else {\r\n return min\r\n + ((value - axisMin) / (axisMax - axisMin)) * (max - min);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Converts a coordinate in Java2D space to the corresponding data value,\r\n * assuming that the axis runs along one edge of the specified dataArea.\r\n *\r\n * @param java2DValue the coordinate in Java2D space.\r\n * @param area the area in which the data is plotted.\r\n * @param edge the location.\r\n *\r\n * @return The data value.\r\n *\r\n * @see #valueToJava2D(double, Rectangle2D, RectangleEdge)\r\n */\r\n @Override\r\n public double java2DToValue(double java2DValue, Rectangle2D area,\r\n RectangleEdge edge) {\r\n\r\n Range range = getRange();\r\n double axisMin = range.getLowerBound();\r\n double axisMax = range.getUpperBound();\r\n\r\n double min = 0.0;\r\n double max = 0.0;\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n min = area.getX();\r\n max = area.getMaxX();\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n min = area.getMaxY();\r\n max = area.getY();\r\n }\r\n if (isInverted()) {\r\n return axisMax\r\n - (java2DValue - min) / (max - min) * (axisMax - axisMin);\r\n }\r\n else {\r\n return axisMin\r\n + (java2DValue - min) / (max - min) * (axisMax - axisMin);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Calculates the value of the lowest visible tick on the axis.\r\n *\r\n * @return The value of the lowest visible tick on the axis.\r\n *\r\n * @see #calculateHighestVisibleTickValue()\r\n */\r\n protected double calculateLowestVisibleTickValue() {\r\n double unit = getTickUnit().getSize();\r\n double index = Math.ceil(getRange().getLowerBound() / unit);\r\n return index * unit;\r\n }\r\n\r\n /**\r\n * Calculates the value of the highest visible tick on the axis.\r\n *\r\n * @return The value of the highest visible tick on the axis.\r\n *\r\n * @see #calculateLowestVisibleTickValue()\r\n */\r\n protected double calculateHighestVisibleTickValue() {\r\n double unit = getTickUnit().getSize();\r\n double index = Math.floor(getRange().getUpperBound() / unit);\r\n return index * unit;\r\n }\r\n\r\n /**\r\n * Calculates the number of visible ticks.\r\n *\r\n * @return The number of visible ticks on the axis.\r\n */\r\n protected int calculateVisibleTickCount() {\r\n double unit = getTickUnit().getSize();\r\n Range range = getRange();\r\n return (int) (Math.floor(range.getUpperBound() / unit)\r\n - Math.ceil(range.getLowerBound() / unit) + 1);\r\n }\r\n\r\n /**\r\n * Draws the axis on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param cursor the cursor location.\r\n * @param plotArea the area within which the axes and data should be drawn\r\n * (<code>null</code> not permitted).\r\n * @param dataArea the area within which the data should be drawn\r\n * (<code>null</code> not permitted).\r\n * @param edge the location of the axis (<code>null</code> not permitted).\r\n * @param plotState collects information about the plot\r\n * (<code>null</code> permitted).\r\n *\r\n * @return The axis state (never <code>null</code>).\r\n */\r\n @Override\r\n public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,\r\n Rectangle2D dataArea, RectangleEdge edge,\r\n PlotRenderingInfo plotState) {\r\n\r\n AxisState state;\r\n // if the axis is not visible, don't draw it...\r\n if (!isVisible()) {\r\n state = new AxisState(cursor);\r\n // even though the axis is not visible, we need ticks for the\r\n // gridlines...\r\n List ticks = refreshTicks(g2, state, dataArea, edge);\r\n state.setTicks(ticks);\r\n return state;\r\n }\r\n\r\n // draw the tick marks and labels...\r\n state = drawTickMarksAndLabels(g2, cursor, plotArea, dataArea, edge);\r\n\r\n if (getAttributedLabel() != null) {\r\n state = drawAttributedLabel(getAttributedLabel(), g2, plotArea, \r\n dataArea, edge, state);\r\n \r\n } else {\r\n state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);\r\n }\r\n createAndAddEntity(cursor, state, dataArea, edge, plotState);\r\n return state;\r\n\r\n }\r\n\r\n /**\r\n * Creates the standard tick units.\r\n * <P>\r\n * If you don't like these defaults, create your own instance of TickUnits\r\n * and then pass it to the setStandardTickUnits() method in the\r\n * NumberAxis class.\r\n *\r\n * @return The standard tick units.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n * @see #createIntegerTickUnits()\r\n */\r\n public static TickUnitSource createStandardTickUnits() {\r\n return new NumberTickUnitSource();\r\n }\r\n\r\n /**\r\n * Returns a collection of tick units for integer values.\r\n *\r\n * @return A collection of tick units for integer values.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n * @see #createStandardTickUnits()\r\n */\r\n public static TickUnitSource createIntegerTickUnits() {\r\n return new NumberTickUnitSource(true);\r\n }\r\n\r\n /**\r\n * Creates a collection of standard tick units. The supplied locale is\r\n * used to create the number formatter (a localised instance of\r\n * <code>NumberFormat</code>).\r\n * <P>\r\n * If you don't like these defaults, create your own instance of\r\n * {@link TickUnits} and then pass it to the\r\n * <code>setStandardTickUnits()</code> method.\r\n *\r\n * @param locale the locale.\r\n *\r\n * @return A tick unit collection.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n */\r\n public static TickUnitSource createStandardTickUnits(Locale locale) {\r\n NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);\r\n return new NumberTickUnitSource(false, numberFormat);\r\n }\r\n\r\n /**\r\n * Returns a collection of tick units for integer values.\r\n * Uses a given Locale to create the DecimalFormats.\r\n *\r\n * @param locale the locale to use to represent Numbers.\r\n *\r\n * @return A collection of tick units for integer values.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n */\r\n public static TickUnitSource createIntegerTickUnits(Locale locale) {\r\n NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);\r\n return new NumberTickUnitSource(true, numberFormat);\r\n }\r\n\r\n /**\r\n * Estimates the maximum tick label height.\r\n *\r\n * @param g2 the graphics device.\r\n *\r\n * @return The maximum height.\r\n */\r\n protected double estimateMaximumTickLabelHeight(Graphics2D g2) {\r\n RectangleInsets tickLabelInsets = getTickLabelInsets();\r\n double result = tickLabelInsets.getTop() + tickLabelInsets.getBottom();\r\n\r\n Font tickLabelFont = getTickLabelFont();\r\n FontRenderContext frc = g2.getFontRenderContext();\r\n result += tickLabelFont.getLineMetrics(\"123\", frc).getHeight();\r\n return result;\r\n }\r\n\r\n /**\r\n * Estimates the maximum width of the tick labels, assuming the specified\r\n * tick unit is used.\r\n * <P>\r\n * Rather than computing the string bounds of every tick on the axis, we\r\n * just look at two values: the lower bound and the upper bound for the\r\n * axis. These two values will usually be representative.\r\n *\r\n * @param g2 the graphics device.\r\n * @param unit the tick unit to use for calculation.\r\n *\r\n * @return The estimated maximum width of the tick labels.\r\n */\r\n protected double estimateMaximumTickLabelWidth(Graphics2D g2,\r\n TickUnit unit) {\r\n\r\n RectangleInsets tickLabelInsets = getTickLabelInsets();\r\n double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();\r\n\r\n if (isVerticalTickLabels()) {\r\n // all tick labels have the same width (equal to the height of the\r\n // font)...\r\n FontRenderContext frc = g2.getFontRenderContext();\r\n LineMetrics lm = getTickLabelFont().getLineMetrics(\"0\", frc);\r\n result += lm.getHeight();\r\n }\r\n else {\r\n // look at lower and upper bounds...\r\n FontMetrics fm = g2.getFontMetrics(getTickLabelFont());\r\n Range range = getRange();\r\n double lower = range.getLowerBound();\r\n double upper = range.getUpperBound();\r\n String lowerStr, upperStr;\r\n NumberFormat formatter = getNumberFormatOverride();\r\n if (formatter != null) {\r\n lowerStr = formatter.format(lower);\r\n upperStr = formatter.format(upper);\r\n }\r\n else {\r\n lowerStr = unit.valueToString(lower);\r\n upperStr = unit.valueToString(upper);\r\n }\r\n double w1 = fm.stringWidth(lowerStr);\r\n double w2 = fm.stringWidth(upperStr);\r\n result += Math.max(w1, w2);\r\n }\r\n\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Selects an appropriate tick value for the axis. The strategy is to\r\n * display as many ticks as possible (selected from an array of 'standard'\r\n * tick units) without the labels overlapping.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area defined by the axes.\r\n * @param edge the axis location.\r\n */\r\n protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea,\r\n RectangleEdge edge) {\r\n\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n selectHorizontalAutoTickUnit(g2, dataArea, edge);\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n selectVerticalAutoTickUnit(g2, dataArea, edge);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Selects an appropriate tick value for the axis. The strategy is to\r\n * display as many ticks as possible (selected from an array of 'standard'\r\n * tick units) without the labels overlapping.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area defined by the axes.\r\n * @param edge the axis location.\r\n */\r\n protected void selectHorizontalAutoTickUnit(Graphics2D g2,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n double tickLabelWidth = estimateMaximumTickLabelWidth(g2,\r\n getTickUnit());\r\n\r\n // start with the current tick unit...\r\n TickUnitSource tickUnits = getStandardTickUnits();\r\n TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());\r\n double unit1Width = lengthToJava2D(unit1.getSize(), dataArea, edge);\r\n\r\n // then extrapolate...\r\n double guess = (tickLabelWidth / unit1Width) * unit1.getSize();\r\n\r\n NumberTickUnit unit2 = (NumberTickUnit) tickUnits.getCeilingTickUnit(\r\n guess);\r\n double unit2Width = lengthToJava2D(unit2.getSize(), dataArea, edge);\r\n\r\n tickLabelWidth = estimateMaximumTickLabelWidth(g2, unit2);\r\n if (tickLabelWidth > unit2Width) {\r\n unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);\r\n }\r\n\r\n setTickUnit(unit2, false, false);\r\n\r\n }\r\n\r\n /**\r\n * Selects an appropriate tick value for the axis. The strategy is to\r\n * display as many ticks as possible (selected from an array of 'standard'\r\n * tick units) without the labels overlapping.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area in which the plot should be drawn.\r\n * @param edge the axis location.\r\n */\r\n protected void selectVerticalAutoTickUnit(Graphics2D g2, \r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n double tickLabelHeight = estimateMaximumTickLabelHeight(g2);\r\n\r\n // start with the current tick unit...\r\n TickUnitSource tickUnits = getStandardTickUnits();\r\n TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());\r\n double unitHeight = lengthToJava2D(unit1.getSize(), dataArea, edge);\r\n double guess = unit1.getSize();\r\n if (unitHeight > 0) {\r\n // then extrapolate...\r\n guess = (tickLabelHeight / unitHeight) * unit1.getSize();\r\n }\r\n NumberTickUnit unit2 = (NumberTickUnit) tickUnits.getCeilingTickUnit(\r\n guess);\r\n double unit2Height = lengthToJava2D(unit2.getSize(), dataArea, edge);\r\n\r\n tickLabelHeight = estimateMaximumTickLabelHeight(g2);\r\n if (tickLabelHeight > unit2Height) {\r\n unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);\r\n }\r\n\r\n setTickUnit(unit2, false, false);\r\n\r\n }\r\n\r\n /**\r\n * Calculates the positions of the tick labels for the axis, storing the\r\n * results in the tick label list (ready for drawing).\r\n *\r\n * @param g2 the graphics device.\r\n * @param state the axis state.\r\n * @param dataArea the area in which the plot should be drawn.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n @Override\r\n public List refreshTicks(Graphics2D g2, AxisState state, \r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List result = new java.util.ArrayList();\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n result = refreshTicksHorizontal(g2, dataArea, edge);\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n result = refreshTicksVertical(g2, dataArea, edge);\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the positions of the tick labels for the axis, storing the\r\n * results in the tick label list (ready for drawing).\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area in which the data should be drawn.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n protected List refreshTicksHorizontal(Graphics2D g2,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List result = new java.util.ArrayList();\r\n\r\n Font tickLabelFont = getTickLabelFont();\r\n g2.setFont(tickLabelFont);\r\n\r\n if (isAutoTickUnitSelection()) {\r\n selectAutoTickUnit(g2, dataArea, edge);\r\n }\r\n\r\n TickUnit tu = getTickUnit();\r\n double size = tu.getSize();\r\n int count = calculateVisibleTickCount();\r\n double lowestTickValue = calculateLowestVisibleTickValue();\r\n\r\n if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {\r\n int minorTickSpaces = getMinorTickCount();\r\n if (minorTickSpaces <= 0) {\r\n minorTickSpaces = tu.getMinorTickCount();\r\n }\r\n for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {\r\n double minorTickValue = lowestTickValue \r\n - size * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR, minorTickValue,\r\n \"\", TextAnchor.TOP_CENTER, TextAnchor.CENTER,\r\n 0.0));\r\n }\r\n }\r\n for (int i = 0; i < count; i++) {\r\n double currentTickValue = lowestTickValue + (i * size);\r\n String tickLabel;\r\n NumberFormat formatter = getNumberFormatOverride();\r\n if (formatter != null) {\r\n tickLabel = formatter.format(currentTickValue);\r\n }\r\n else {\r\n tickLabel = getTickUnit().valueToString(currentTickValue);\r\n }\r\n TextAnchor anchor, rotationAnchor;\r\n double angle = 0.0;\r\n if (isVerticalTickLabels()) {\r\n anchor = TextAnchor.CENTER_RIGHT;\r\n rotationAnchor = TextAnchor.CENTER_RIGHT;\r\n if (edge == RectangleEdge.TOP) {\r\n angle = Math.PI / 2.0;\r\n }\r\n else {\r\n angle = -Math.PI / 2.0;\r\n }\r\n }\r\n else {\r\n if (edge == RectangleEdge.TOP) {\r\n anchor = TextAnchor.BOTTOM_CENTER;\r\n rotationAnchor = TextAnchor.BOTTOM_CENTER;\r\n }\r\n else {\r\n anchor = TextAnchor.TOP_CENTER;\r\n rotationAnchor = TextAnchor.TOP_CENTER;\r\n }\r\n }\r\n\r\n Tick tick = new NumberTick(new Double(currentTickValue),\r\n tickLabel, anchor, rotationAnchor, angle);\r\n result.add(tick);\r\n double nextTickValue = lowestTickValue + ((i + 1) * size);\r\n for (int minorTick = 1; minorTick < minorTickSpaces;\r\n minorTick++) {\r\n double minorTickValue = currentTickValue\r\n + (nextTickValue - currentTickValue)\r\n * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR,\r\n minorTickValue, \"\", TextAnchor.TOP_CENTER,\r\n TextAnchor.CENTER, 0.0));\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the positions of the tick labels for the axis, storing the\r\n * results in the tick label list (ready for drawing).\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area in which the plot should be drawn.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n protected List refreshTicksVertical(Graphics2D g2,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List result = new java.util.ArrayList();\r\n result.clear();\r\n\r\n Font tickLabelFont = getTickLabelFont();\r\n g2.setFont(tickLabelFont);\r\n if (isAutoTickUnitSelection()) {\r\n selectAutoTickUnit(g2, dataArea, edge);\r\n }\r\n\r\n TickUnit tu = getTickUnit();\r\n double size = tu.getSize();\r\n int count = calculateVisibleTickCount();\r\n double lowestTickValue = calculateLowestVisibleTickValue();\r\n\r\n if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {\r\n int minorTickSpaces = getMinorTickCount();\r\n if (minorTickSpaces <= 0) {\r\n minorTickSpaces = tu.getMinorTickCount();\r\n }\r\n for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {\r\n double minorTickValue = lowestTickValue\r\n - size * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR, minorTickValue,\r\n \"\", TextAnchor.TOP_CENTER, TextAnchor.CENTER,\r\n 0.0));\r\n }\r\n }\r\n\r\n for (int i = 0; i < count; i++) {\r\n double currentTickValue = lowestTickValue + (i * size);\r\n String tickLabel;\r\n NumberFormat formatter = getNumberFormatOverride();\r\n if (formatter != null) {\r\n tickLabel = formatter.format(currentTickValue);\r\n }\r\n else {\r\n tickLabel = getTickUnit().valueToString(currentTickValue);\r\n }\r\n\r\n TextAnchor anchor;\r\n TextAnchor rotationAnchor;\r\n double angle = 0.0;\r\n if (isVerticalTickLabels()) {\r\n if (edge == RectangleEdge.LEFT) {\r\n anchor = TextAnchor.BOTTOM_CENTER;\r\n rotationAnchor = TextAnchor.BOTTOM_CENTER;\r\n angle = -Math.PI / 2.0;\r\n }\r\n else {\r\n anchor = TextAnchor.BOTTOM_CENTER;\r\n rotationAnchor = TextAnchor.BOTTOM_CENTER;\r\n angle = Math.PI / 2.0;\r\n }\r\n }\r\n else {\r\n if (edge == RectangleEdge.LEFT) {\r\n anchor = TextAnchor.CENTER_RIGHT;\r\n rotationAnchor = TextAnchor.CENTER_RIGHT;\r\n }\r\n else {\r\n anchor = TextAnchor.CENTER_LEFT;\r\n rotationAnchor = TextAnchor.CENTER_LEFT;\r\n }\r\n }\r\n\r\n Tick tick = new NumberTick(new Double(currentTickValue),\r\n tickLabel, anchor, rotationAnchor, angle);\r\n result.add(tick);\r\n\r\n double nextTickValue = lowestTickValue + ((i + 1) * size);\r\n for (int minorTick = 1; minorTick < minorTickSpaces;\r\n minorTick++) {\r\n double minorTickValue = currentTickValue\r\n + (nextTickValue - currentTickValue)\r\n * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR,\r\n minorTickValue, \"\", TextAnchor.TOP_CENTER,\r\n TextAnchor.CENTER, 0.0));\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Returns a clone of the axis.\r\n *\r\n * @return A clone\r\n *\r\n * @throws CloneNotSupportedException if some component of the axis does\r\n * not support cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n NumberAxis clone = (NumberAxis) super.clone();\r\n if (this.numberFormatOverride != null) {\r\n clone.numberFormatOverride\r\n = (NumberFormat) this.numberFormatOverride.clone();\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * Tests the axis for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof NumberAxis)) {\r\n return false;\r\n }\r\n NumberAxis that = (NumberAxis) obj;\r\n if (this.autoRangeIncludesZero != that.autoRangeIncludesZero) {\r\n return false;\r\n }\r\n if (this.autoRangeStickyZero != that.autoRangeStickyZero) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.tickUnit, that.tickUnit)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.numberFormatOverride,\r\n that.numberFormatOverride)) {\r\n return false;\r\n }\r\n if (!this.rangeType.equals(that.rangeType)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a hash code for this object.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n return super.hashCode();\r\n }\r\n\r\n}\r" }, { "identifier": "XYPlot", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/XYPlot.java", "snippet": "public class XYPlot extends Plot implements ValueAxisPlot, Pannable, Zoomable,\r\n RendererChangeListener, Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 7044148245716569264L;\r\n\r\n /** The default grid line stroke. */\r\n public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f,\r\n BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f,\r\n new float[] {2.0f, 2.0f}, 0.0f);\r\n\r\n /** The default grid line paint. */\r\n public static final Paint DEFAULT_GRIDLINE_PAINT = Color.lightGray;\r\n\r\n /** The default crosshair visibility. */\r\n public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false;\r\n\r\n /** The default crosshair stroke. */\r\n public static final Stroke DEFAULT_CROSSHAIR_STROKE\r\n = DEFAULT_GRIDLINE_STROKE;\r\n\r\n /** The default crosshair paint. */\r\n public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.blue;\r\n\r\n /** The resourceBundle for the localization. */\r\n protected static ResourceBundle localizationResources\r\n = ResourceBundleWrapper.getBundle(\r\n \"org.jfree.chart.plot.LocalizationBundle\");\r\n\r\n /** The plot orientation. */\r\n private PlotOrientation orientation;\r\n\r\n /** The offset between the data area and the axes. */\r\n private RectangleInsets axisOffset;\r\n\r\n /** The domain axis / axes (used for the x-values). */\r\n private Map<Integer, ValueAxis> domainAxes;\r\n\r\n /** The domain axis locations. */\r\n private Map<Integer, AxisLocation> domainAxisLocations;\r\n\r\n /** The range axis (used for the y-values). */\r\n private Map<Integer, ValueAxis> rangeAxes;\r\n\r\n /** The range axis location. */\r\n private Map<Integer, AxisLocation> rangeAxisLocations;\r\n\r\n /** Storage for the datasets. */\r\n private Map<Integer, XYDataset> datasets;\r\n\r\n /** Storage for the renderers. */\r\n private Map<Integer, XYItemRenderer> renderers;\r\n\r\n /**\r\n * Storage for the mapping between datasets/renderers and domain axes. The\r\n * keys in the map are Integer objects, corresponding to the dataset\r\n * index. The values in the map are List objects containing Integer\r\n * objects (corresponding to the axis indices). If the map contains no\r\n * entry for a dataset, it is assumed to map to the primary domain axis\r\n * (index = 0).\r\n */\r\n private Map<Integer, List<Integer>> datasetToDomainAxesMap;\r\n\r\n /**\r\n * Storage for the mapping between datasets/renderers and range axes. The\r\n * keys in the map are Integer objects, corresponding to the dataset\r\n * index. The values in the map are List objects containing Integer\r\n * objects (corresponding to the axis indices). If the map contains no\r\n * entry for a dataset, it is assumed to map to the primary domain axis\r\n * (index = 0).\r\n */\r\n private Map<Integer, List<Integer>> datasetToRangeAxesMap;\r\n\r\n /** The origin point for the quadrants (if drawn). */\r\n private transient Point2D quadrantOrigin = new Point2D.Double(0.0, 0.0);\r\n\r\n /** The paint used for each quadrant. */\r\n private transient Paint[] quadrantPaint\r\n = new Paint[] {null, null, null, null};\r\n\r\n /** A flag that controls whether the domain grid-lines are visible. */\r\n private boolean domainGridlinesVisible;\r\n\r\n /** The stroke used to draw the domain grid-lines. */\r\n private transient Stroke domainGridlineStroke;\r\n\r\n /** The paint used to draw the domain grid-lines. */\r\n private transient Paint domainGridlinePaint;\r\n\r\n /** A flag that controls whether the range grid-lines are visible. */\r\n private boolean rangeGridlinesVisible;\r\n\r\n /** The stroke used to draw the range grid-lines. */\r\n private transient Stroke rangeGridlineStroke;\r\n\r\n /** The paint used to draw the range grid-lines. */\r\n private transient Paint rangeGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether the domain minor grid-lines are visible.\r\n *\r\n * @since 1.0.12\r\n */\r\n private boolean domainMinorGridlinesVisible;\r\n\r\n /**\r\n * The stroke used to draw the domain minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Stroke domainMinorGridlineStroke;\r\n\r\n /**\r\n * The paint used to draw the domain minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Paint domainMinorGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether the range minor grid-lines are visible.\r\n *\r\n * @since 1.0.12\r\n */\r\n private boolean rangeMinorGridlinesVisible;\r\n\r\n /**\r\n * The stroke used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Stroke rangeMinorGridlineStroke;\r\n\r\n /**\r\n * The paint used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Paint rangeMinorGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not the zero baseline against the domain\r\n * axis is visible.\r\n *\r\n * @since 1.0.5\r\n */\r\n private boolean domainZeroBaselineVisible;\r\n\r\n /**\r\n * The stroke used for the zero baseline against the domain axis.\r\n *\r\n * @since 1.0.5\r\n */\r\n private transient Stroke domainZeroBaselineStroke;\r\n\r\n /**\r\n * The paint used for the zero baseline against the domain axis.\r\n *\r\n * @since 1.0.5\r\n */\r\n private transient Paint domainZeroBaselinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not the zero baseline against the range\r\n * axis is visible.\r\n */\r\n private boolean rangeZeroBaselineVisible;\r\n\r\n /** The stroke used for the zero baseline against the range axis. */\r\n private transient Stroke rangeZeroBaselineStroke;\r\n\r\n /** The paint used for the zero baseline against the range axis. */\r\n private transient Paint rangeZeroBaselinePaint;\r\n\r\n /** A flag that controls whether or not a domain crosshair is drawn..*/\r\n private boolean domainCrosshairVisible;\r\n\r\n /** The domain crosshair value. */\r\n private double domainCrosshairValue;\r\n\r\n /** The pen/brush used to draw the crosshair (if any). */\r\n private transient Stroke domainCrosshairStroke;\r\n\r\n /** The color used to draw the crosshair (if any). */\r\n private transient Paint domainCrosshairPaint;\r\n\r\n /**\r\n * A flag that controls whether or not the crosshair locks onto actual\r\n * data points.\r\n */\r\n private boolean domainCrosshairLockedOnData = true;\r\n\r\n /** A flag that controls whether or not a range crosshair is drawn..*/\r\n private boolean rangeCrosshairVisible;\r\n\r\n /** The range crosshair value. */\r\n private double rangeCrosshairValue;\r\n\r\n /** The pen/brush used to draw the crosshair (if any). */\r\n private transient Stroke rangeCrosshairStroke;\r\n\r\n /** The color used to draw the crosshair (if any). */\r\n private transient Paint rangeCrosshairPaint;\r\n\r\n /**\r\n * A flag that controls whether or not the crosshair locks onto actual\r\n * data points.\r\n */\r\n private boolean rangeCrosshairLockedOnData = true;\r\n\r\n /** A map of lists of foreground markers (optional) for the domain axes. */\r\n private Map foregroundDomainMarkers;\r\n\r\n /** A map of lists of background markers (optional) for the domain axes. */\r\n private Map backgroundDomainMarkers;\r\n\r\n /** A map of lists of foreground markers (optional) for the range axes. */\r\n private Map foregroundRangeMarkers;\r\n\r\n /** A map of lists of background markers (optional) for the range axes. */\r\n private Map backgroundRangeMarkers;\r\n\r\n /**\r\n * A (possibly empty) list of annotations for the plot. The list should\r\n * be initialised in the constructor and never allowed to be\r\n * <code>null</code>.\r\n */\r\n private List<XYAnnotation> annotations;\r\n\r\n /** The paint used for the domain tick bands (if any). */\r\n private transient Paint domainTickBandPaint;\r\n\r\n /** The paint used for the range tick bands (if any). */\r\n private transient Paint rangeTickBandPaint;\r\n\r\n /** The fixed domain axis space. */\r\n private AxisSpace fixedDomainAxisSpace;\r\n\r\n /** The fixed range axis space. */\r\n private AxisSpace fixedRangeAxisSpace;\r\n\r\n /**\r\n * The order of the dataset rendering (REVERSE draws the primary dataset\r\n * last so that it appears to be on top).\r\n */\r\n private DatasetRenderingOrder datasetRenderingOrder\r\n = DatasetRenderingOrder.REVERSE;\r\n\r\n /**\r\n * The order of the series rendering (REVERSE draws the primary series\r\n * last so that it appears to be on top).\r\n */\r\n private SeriesRenderingOrder seriesRenderingOrder\r\n = SeriesRenderingOrder.REVERSE;\r\n\r\n /**\r\n * The weight for this plot (only relevant if this is a subplot in a\r\n * combined plot).\r\n */\r\n private int weight;\r\n\r\n /**\r\n * An optional collection of legend items that can be returned by the\r\n * getLegendItems() method.\r\n */\r\n private LegendItemCollection fixedLegendItems;\r\n\r\n /**\r\n * A flag that controls whether or not panning is enabled for the domain\r\n * axis/axes.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean domainPannable;\r\n\r\n /**\r\n * A flag that controls whether or not panning is enabled for the range\r\n * axis/axes.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean rangePannable;\r\n\r\n /**\r\n * The shadow generator (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n private ShadowGenerator shadowGenerator;\r\n\r\n /**\r\n * Creates a new <code>XYPlot</code> instance with no dataset, no axes and\r\n * no renderer. You should specify these items before using the plot.\r\n */\r\n public XYPlot() {\r\n this(null, null, null, null);\r\n }\r\n\r\n /**\r\n * Creates a new plot with the specified dataset, axes and renderer. Any\r\n * of the arguments can be <code>null</code>, but in that case you should\r\n * take care to specify the value before using the plot (otherwise a\r\n * <code>NullPointerException</code> may be thrown).\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n * @param domainAxis the domain axis (<code>null</code> permitted).\r\n * @param rangeAxis the range axis (<code>null</code> permitted).\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n */\r\n public XYPlot(XYDataset dataset, ValueAxis domainAxis, ValueAxis rangeAxis,\r\n XYItemRenderer renderer) {\r\n super();\r\n this.orientation = PlotOrientation.VERTICAL;\r\n this.weight = 1; // only relevant when this is a subplot\r\n this.axisOffset = RectangleInsets.ZERO_INSETS;\r\n\r\n // allocate storage for datasets, axes and renderers (all optional)\r\n this.domainAxes = new HashMap<Integer, ValueAxis>();\r\n this.domainAxisLocations = new HashMap<Integer, AxisLocation>();\r\n this.foregroundDomainMarkers = new HashMap();\r\n this.backgroundDomainMarkers = new HashMap();\r\n\r\n this.rangeAxes = new HashMap<Integer, ValueAxis>();\r\n this.rangeAxisLocations = new HashMap<Integer, AxisLocation>();\r\n this.foregroundRangeMarkers = new HashMap();\r\n this.backgroundRangeMarkers = new HashMap();\r\n\r\n this.datasets = new HashMap<Integer, XYDataset>();\r\n this.renderers = new HashMap<Integer, XYItemRenderer>();\r\n\r\n this.datasetToDomainAxesMap = new TreeMap();\r\n this.datasetToRangeAxesMap = new TreeMap();\r\n\r\n this.annotations = new java.util.ArrayList();\r\n\r\n this.datasets.put(0, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n\r\n this.renderers.put(0, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n\r\n this.domainAxes.put(0, domainAxis);\r\n mapDatasetToDomainAxis(0, 0);\r\n if (domainAxis != null) {\r\n domainAxis.setPlot(this);\r\n domainAxis.addChangeListener(this);\r\n }\r\n this.domainAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT);\r\n\r\n this.rangeAxes.put(0, rangeAxis);\r\n mapDatasetToRangeAxis(0, 0);\r\n if (rangeAxis != null) {\r\n rangeAxis.setPlot(this);\r\n rangeAxis.addChangeListener(this);\r\n }\r\n this.rangeAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT);\r\n\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n\r\n this.domainGridlinesVisible = true;\r\n this.domainGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.domainGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.domainMinorGridlinesVisible = false;\r\n this.domainMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.domainMinorGridlinePaint = Color.white;\r\n\r\n this.domainZeroBaselineVisible = false;\r\n this.domainZeroBaselinePaint = Color.black;\r\n this.domainZeroBaselineStroke = new BasicStroke(0.5f);\r\n\r\n this.rangeGridlinesVisible = true;\r\n this.rangeGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.rangeMinorGridlinesVisible = false;\r\n this.rangeMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeMinorGridlinePaint = Color.white;\r\n\r\n this.rangeZeroBaselineVisible = false;\r\n this.rangeZeroBaselinePaint = Color.black;\r\n this.rangeZeroBaselineStroke = new BasicStroke(0.5f);\r\n\r\n this.domainCrosshairVisible = false;\r\n this.domainCrosshairValue = 0.0;\r\n this.domainCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.domainCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n\r\n this.rangeCrosshairVisible = false;\r\n this.rangeCrosshairValue = 0.0;\r\n this.rangeCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.rangeCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n this.shadowGenerator = null;\r\n }\r\n\r\n /**\r\n * Returns the plot type as a string.\r\n *\r\n * @return A short string describing the type of plot.\r\n */\r\n @Override\r\n public String getPlotType() {\r\n return localizationResources.getString(\"XY_Plot\");\r\n }\r\n\r\n /**\r\n * Returns the orientation of the plot.\r\n *\r\n * @return The orientation (never <code>null</code>).\r\n *\r\n * @see #setOrientation(PlotOrientation)\r\n */\r\n @Override\r\n public PlotOrientation getOrientation() {\r\n return this.orientation;\r\n }\r\n\r\n /**\r\n * Sets the orientation for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param orientation the orientation (<code>null</code> not allowed).\r\n *\r\n * @see #getOrientation()\r\n */\r\n public void setOrientation(PlotOrientation orientation) {\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n if (orientation != this.orientation) {\r\n this.orientation = orientation;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the axis offset.\r\n *\r\n * @return The axis offset (never <code>null</code>).\r\n *\r\n * @see #setAxisOffset(RectangleInsets)\r\n */\r\n public RectangleInsets getAxisOffset() {\r\n return this.axisOffset;\r\n }\r\n\r\n /**\r\n * Sets the axis offsets (gap between the data area and the axes) and sends\r\n * a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param offset the offset (<code>null</code> not permitted).\r\n *\r\n * @see #getAxisOffset()\r\n */\r\n public void setAxisOffset(RectangleInsets offset) {\r\n ParamChecks.nullNotPermitted(offset, \"offset\");\r\n this.axisOffset = offset;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the domain axis with index 0. If the domain axis for this plot\r\n * is <code>null</code>, then the method will return the parent plot's\r\n * domain axis (if there is a parent plot).\r\n *\r\n * @return The domain axis (possibly <code>null</code>).\r\n *\r\n * @see #getDomainAxis(int)\r\n * @see #setDomainAxis(ValueAxis)\r\n */\r\n public ValueAxis getDomainAxis() {\r\n return getDomainAxis(0);\r\n }\r\n\r\n /**\r\n * Returns the domain axis with the specified index, or {@code null} if \r\n * there is no axis with that index.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The axis ({@code null} possible).\r\n *\r\n * @see #setDomainAxis(int, ValueAxis)\r\n */\r\n public ValueAxis getDomainAxis(int index) {\r\n ValueAxis result = this.domainAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot xy = (XYPlot) parent;\r\n result = xy.getDomainAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the domain axis for the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axis the new axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis()\r\n * @see #setDomainAxis(int, ValueAxis)\r\n */\r\n public void setDomainAxis(ValueAxis axis) {\r\n setDomainAxis(0, axis);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis(int)\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public void setDomainAxis(int index, ValueAxis axis) {\r\n setDomainAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainAxis(int)\r\n */\r\n public void setDomainAxis(int index, ValueAxis axis, boolean notify) {\r\n ValueAxis existing = getDomainAxis(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.domainAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the domain axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setRangeAxes(ValueAxis[])\r\n */\r\n public void setDomainAxes(ValueAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setDomainAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the location of the primary domain axis.\r\n *\r\n * @return The location (never <code>null</code>).\r\n *\r\n * @see #setDomainAxisLocation(AxisLocation)\r\n */\r\n public AxisLocation getDomainAxisLocation() {\r\n return (AxisLocation) this.domainAxisLocations.get(0);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary domain axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainAxisLocation()\r\n */\r\n public void setDomainAxisLocation(AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainAxisLocation()\r\n */\r\n public void setDomainAxisLocation(AxisLocation location, boolean notify) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Returns the edge for the primary domain axis (taking into account the\r\n * plot's orientation).\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getDomainAxisLocation()\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getDomainAxisEdge() {\r\n return Plot.resolveDomainAxisLocation(getDomainAxisLocation(),\r\n this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the number of domain axes.\r\n *\r\n * @return The axis count.\r\n *\r\n * @see #getRangeAxisCount()\r\n */\r\n public int getDomainAxisCount() {\r\n return this.domainAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the domain axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #clearRangeAxes()\r\n */\r\n public void clearDomainAxes() {\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.removeChangeListener(this);\r\n }\r\n }\r\n this.domainAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the domain axes.\r\n */\r\n public void configureDomainAxes() {\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the location for a domain axis. If this hasn't been set\r\n * explicitly, the method returns the location that is opposite to the\r\n * primary domain axis location.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The location (never {@code null}).\r\n *\r\n * @see #setDomainAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getDomainAxisLocation(int index) {\r\n AxisLocation result = this.domainAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getDomainAxisLocation());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location for a domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> not permitted for index\r\n * 0).\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the axis location for a domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n * @param location the location (<code>null</code> not permitted for\r\n * index 0).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n * @see #setRangeAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.domainAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the edge for a domain axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getRangeAxisEdge(int)\r\n */\r\n public RectangleEdge getDomainAxisEdge(int index) {\r\n AxisLocation location = getDomainAxisLocation(index);\r\n return Plot.resolveDomainAxisLocation(location, this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the range axis for the plot. If the range axis for this plot is\r\n * <code>null</code>, then the method will return the parent plot's range\r\n * axis (if there is a parent plot).\r\n *\r\n * @return The range axis.\r\n *\r\n * @see #getRangeAxis(int)\r\n * @see #setRangeAxis(ValueAxis)\r\n */\r\n public ValueAxis getRangeAxis() {\r\n return getRangeAxis(0);\r\n }\r\n\r\n /**\r\n * Sets the range axis for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxis()\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public void setRangeAxis(ValueAxis axis) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n // plot is likely registered as a listener with the existing axis...\r\n ValueAxis existing = getRangeAxis();\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.rangeAxes.put(0, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the location of the primary range axis.\r\n *\r\n * @return The location (never <code>null</code>).\r\n *\r\n * @see #setRangeAxisLocation(AxisLocation)\r\n */\r\n public AxisLocation getRangeAxisLocation() {\r\n return (AxisLocation) this.rangeAxisLocations.get(0);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary range axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeAxisLocation()\r\n */\r\n public void setRangeAxisLocation(AxisLocation location) {\r\n // delegate...\r\n setRangeAxisLocation(0, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary range axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRangeAxisLocation()\r\n */\r\n public void setRangeAxisLocation(AxisLocation location, boolean notify) {\r\n // delegate...\r\n setRangeAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Returns the edge for the primary range axis.\r\n *\r\n * @return The range axis edge.\r\n *\r\n * @see #getRangeAxisLocation()\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getRangeAxisEdge() {\r\n return Plot.resolveRangeAxisLocation(getRangeAxisLocation(),\r\n this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the range axis with the specified index, or {@code null} if \r\n * there is no axis with that index.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The axis ({@code null} possible).\r\n *\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public ValueAxis getRangeAxis(int index) {\r\n ValueAxis result = this.rangeAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot xy = (XYPlot) parent;\r\n result = xy.getRangeAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets a range axis and sends a {@link PlotChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxis(int)\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis) {\r\n setRangeAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a range axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRangeAxis(int)\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis, boolean notify) {\r\n ValueAxis existing = getRangeAxis(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.rangeAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the range axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setDomainAxes(ValueAxis[])\r\n */\r\n public void setRangeAxes(ValueAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setRangeAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the number of range axes.\r\n *\r\n * @return The axis count.\r\n *\r\n * @see #getDomainAxisCount()\r\n */\r\n public int getRangeAxisCount() {\r\n return this.rangeAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the range axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #clearDomainAxes()\r\n */\r\n public void clearRangeAxes() {\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.removeChangeListener(this);\r\n }\r\n }\r\n this.rangeAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the range axes.\r\n *\r\n * @see #configureDomainAxes()\r\n */\r\n public void configureRangeAxes() {\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the location for a range axis. If this hasn't been set\r\n * explicitly, the method returns the location that is opposite to the\r\n * primary range axis location.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The location (never {@code null}).\r\n *\r\n * @see #setRangeAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getRangeAxisLocation(int index) {\r\n AxisLocation result = this.rangeAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getRangeAxisLocation());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location for a range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location) {\r\n // delegate...\r\n setRangeAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the axis location for a domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> not permitted for\r\n * index 0).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #setDomainAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.rangeAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the edge for a range axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getRangeAxisEdge(int index) {\r\n AxisLocation location = getRangeAxisLocation(index);\r\n return Plot.resolveRangeAxisLocation(location, this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the primary dataset for the plot.\r\n *\r\n * @return The primary dataset (possibly <code>null</code>).\r\n *\r\n * @see #getDataset(int)\r\n * @see #setDataset(XYDataset)\r\n */\r\n public XYDataset getDataset() {\r\n return getDataset(0);\r\n }\r\n\r\n /**\r\n * Returns the dataset with the specified index, or {@code null} if there\r\n * is no dataset with that index.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The dataset (possibly {@code null}).\r\n *\r\n * @see #setDataset(int, XYDataset)\r\n */\r\n public XYDataset getDataset(int index) {\r\n return (XYDataset) this.datasets.get(index);\r\n }\r\n\r\n /**\r\n * Sets the primary dataset for the plot, replacing the existing dataset if\r\n * there is one.\r\n *\r\n * @param dataset the dataset ({@code null} permitted).\r\n *\r\n * @see #getDataset()\r\n * @see #setDataset(int, XYDataset)\r\n */\r\n public void setDataset(XYDataset dataset) {\r\n setDataset(0, dataset);\r\n }\r\n\r\n /**\r\n * Sets a dataset for the plot and sends a change event to all registered\r\n * listeners.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n *\r\n * @see #getDataset(int)\r\n */\r\n public void setDataset(int index, XYDataset dataset) {\r\n XYDataset existing = getDataset(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.datasets.put(index, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n\r\n // send a dataset change event to self...\r\n DatasetChangeEvent event = new DatasetChangeEvent(this, dataset);\r\n datasetChanged(event);\r\n }\r\n\r\n /**\r\n * Returns the number of datasets.\r\n *\r\n * @return The number of datasets.\r\n */\r\n public int getDatasetCount() {\r\n return this.datasets.size();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified dataset, or {@code -1} if the\r\n * dataset does not belong to the plot.\r\n *\r\n * @param dataset the dataset ({@code null} not permitted).\r\n *\r\n * @return The index or -1.\r\n */\r\n public int indexOf(XYDataset dataset) {\r\n for (Map.Entry<Integer, XYDataset> entry: this.datasets.entrySet()) {\r\n if (dataset == entry.getValue()) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular domain axis. All data will be plotted\r\n * against axis zero by default, no mapping is required for this case.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index.\r\n *\r\n * @see #mapDatasetToRangeAxis(int, int)\r\n */\r\n public void mapDatasetToDomainAxis(int index, int axisIndex) {\r\n List axisIndices = new java.util.ArrayList(1);\r\n axisIndices.add(new Integer(axisIndex));\r\n mapDatasetToDomainAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToDomainAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n Integer key = new Integer(index);\r\n this.datasetToDomainAxesMap.put(key, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular range axis. All data will be plotted\r\n * against axis zero by default, no mapping is required for this case.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index.\r\n *\r\n * @see #mapDatasetToDomainAxis(int, int)\r\n */\r\n public void mapDatasetToRangeAxis(int index, int axisIndex) {\r\n List axisIndices = new java.util.ArrayList(1);\r\n axisIndices.add(new Integer(axisIndex));\r\n mapDatasetToRangeAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToRangeAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n Integer key = new Integer(index);\r\n this.datasetToRangeAxesMap.put(key, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * This method is used to perform argument checking on the list of\r\n * axis indices passed to mapDatasetToDomainAxes() and\r\n * mapDatasetToRangeAxes().\r\n *\r\n * @param indices the list of indices (<code>null</code> permitted).\r\n */\r\n private void checkAxisIndices(List<Integer> indices) {\r\n // axisIndices can be:\r\n // 1. null;\r\n // 2. non-empty, containing only Integer objects that are unique.\r\n if (indices == null) {\r\n return; // OK\r\n }\r\n int count = indices.size();\r\n if (count == 0) {\r\n throw new IllegalArgumentException(\"Empty list not permitted.\");\r\n }\r\n Set<Integer> set = new HashSet<Integer>();\r\n for (Integer item : indices) {\r\n if (set.contains(item)) {\r\n throw new IllegalArgumentException(\"Indices must be unique.\");\r\n }\r\n set.add(item);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the number of renderer slots for this plot.\r\n *\r\n * @return The number of renderer slots.\r\n *\r\n * @since 1.0.11\r\n */\r\n public int getRendererCount() {\r\n return this.renderers.size();\r\n }\r\n\r\n /**\r\n * Returns the renderer for the primary dataset.\r\n *\r\n * @return The item renderer (possibly <code>null</code>).\r\n *\r\n * @see #setRenderer(XYItemRenderer)\r\n */\r\n public XYItemRenderer getRenderer() {\r\n return getRenderer(0);\r\n }\r\n\r\n /**\r\n * Returns the renderer with the specified index, or {@code null}.\r\n *\r\n * @param index the renderer index (must be &gt;= 0).\r\n *\r\n * @return The renderer (possibly {@code null}).\r\n *\r\n * @see #setRenderer(int, XYItemRenderer)\r\n */\r\n public XYItemRenderer getRenderer(int index) {\r\n return (XYItemRenderer) this.renderers.get(index);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the primary dataset and sends a change event to \r\n * all registered listeners. If the renderer is set to <code>null</code>, \r\n * no data will be displayed.\r\n *\r\n * @param renderer the renderer ({@code null} permitted).\r\n *\r\n * @see #getRenderer()\r\n */\r\n public void setRenderer(XYItemRenderer renderer) {\r\n setRenderer(0, renderer);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the dataset with the specified index and sends a \r\n * change event to all registered listeners. Note that each dataset should \r\n * have its own renderer, you should not use one renderer for multiple \r\n * datasets.\r\n *\r\n * @param index the index (must be &gt;= 0).\r\n * @param renderer the renderer.\r\n *\r\n * @see #getRenderer(int)\r\n */\r\n public void setRenderer(int index, XYItemRenderer renderer) {\r\n setRenderer(index, renderer, true);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the dataset with the specified index and, if \r\n * requested, sends a change event to all registered listeners. Note that \r\n * each dataset should have its own renderer, you should not use one \r\n * renderer for multiple datasets.\r\n *\r\n * @param index the index (must be &gt;= 0).\r\n * @param renderer the renderer.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRenderer(int)\r\n */\r\n public void setRenderer(int index, XYItemRenderer renderer, \r\n boolean notify) {\r\n XYItemRenderer existing = getRenderer(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.renderers.put(index, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the renderers for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param renderers the renderers (<code>null</code> not permitted).\r\n */\r\n public void setRenderers(XYItemRenderer[] renderers) {\r\n for (int i = 0; i < renderers.length; i++) {\r\n setRenderer(i, renderers[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the dataset rendering order.\r\n *\r\n * @return The order (never <code>null</code>).\r\n *\r\n * @see #setDatasetRenderingOrder(DatasetRenderingOrder)\r\n */\r\n public DatasetRenderingOrder getDatasetRenderingOrder() {\r\n return this.datasetRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the rendering order and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. By default, the plot renders the primary dataset\r\n * last (so that the primary dataset overlays the secondary datasets).\r\n * You can reverse this if you want to.\r\n *\r\n * @param order the rendering order (<code>null</code> not permitted).\r\n *\r\n * @see #getDatasetRenderingOrder()\r\n */\r\n public void setDatasetRenderingOrder(DatasetRenderingOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.datasetRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the series rendering order.\r\n *\r\n * @return the order (never <code>null</code>).\r\n *\r\n * @see #setSeriesRenderingOrder(SeriesRenderingOrder)\r\n */\r\n public SeriesRenderingOrder getSeriesRenderingOrder() {\r\n return this.seriesRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the series order and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. By default, the plot renders the primary series\r\n * last (so that the primary series appears to be on top).\r\n * You can reverse this if you want to.\r\n *\r\n * @param order the rendering order (<code>null</code> not permitted).\r\n *\r\n * @see #getSeriesRenderingOrder()\r\n */\r\n public void setSeriesRenderingOrder(SeriesRenderingOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.seriesRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified renderer, or <code>-1</code> if the\r\n * renderer is not assigned to this plot.\r\n *\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n *\r\n * @return The renderer index.\r\n */\r\n public int getIndexOf(XYItemRenderer renderer) {\r\n for (Map.Entry<Integer, XYItemRenderer> entry \r\n : this.renderers.entrySet()) {\r\n if (entry.getValue() == renderer) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the renderer for the specified dataset (this is either the\r\n * renderer with the same index as the dataset or, if there isn't a \r\n * renderer with the same index, the default renderer). If the dataset\r\n * does not belong to the plot, this method will return {@code null}.\r\n *\r\n * @param dataset the dataset ({@code null} permitted).\r\n *\r\n * @return The renderer (possibly {@code null}).\r\n */\r\n public XYItemRenderer getRendererForDataset(XYDataset dataset) {\r\n int datasetIndex = indexOf(dataset);\r\n if (datasetIndex < 0) {\r\n return null;\r\n } \r\n XYItemRenderer result = this.renderers.get(datasetIndex);\r\n if (result == null) {\r\n result = getRenderer();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the weight for this plot when it is used as a subplot within a\r\n * combined plot.\r\n *\r\n * @return The weight.\r\n *\r\n * @see #setWeight(int)\r\n */\r\n public int getWeight() {\r\n return this.weight;\r\n }\r\n\r\n /**\r\n * Sets the weight for the plot and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param weight the weight.\r\n *\r\n * @see #getWeight()\r\n */\r\n public void setWeight(int weight) {\r\n this.weight = weight;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the domain gridlines are visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setDomainGridlinesVisible(boolean)\r\n */\r\n public boolean isDomainGridlinesVisible() {\r\n return this.domainGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the domain grid-lines are\r\n * visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isDomainGridlinesVisible()\r\n */\r\n public void setDomainGridlinesVisible(boolean visible) {\r\n if (this.domainGridlinesVisible != visible) {\r\n this.domainGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the domain minor gridlines are visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setDomainMinorGridlinesVisible(boolean)\r\n *\r\n * @since 1.0.12\r\n */\r\n public boolean isDomainMinorGridlinesVisible() {\r\n return this.domainMinorGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the domain minor grid-lines\r\n * are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isDomainMinorGridlinesVisible()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlinesVisible(boolean visible) {\r\n if (this.domainMinorGridlinesVisible != visible) {\r\n this.domainMinorGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the grid-lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlineStroke(Stroke)\r\n */\r\n public Stroke getDomainGridlineStroke() {\r\n return this.domainGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the grid lines plotted against the domain axis, and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>stroke</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainGridlineStroke()\r\n */\r\n public void setDomainGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke for the minor grid-lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainMinorGridlineStroke(Stroke)\r\n *\r\n * @since 1.0.12\r\n */\r\n\r\n public Stroke getDomainMinorGridlineStroke() {\r\n return this.domainMinorGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the minor grid lines plotted against the domain\r\n * axis, and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>stroke</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainMinorGridlineStroke()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainMinorGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the grid lines (if any) plotted against the domain\r\n * axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlinePaint(Paint)\r\n */\r\n public Paint getDomainGridlinePaint() {\r\n return this.domainGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the grid lines plotted against the domain axis, and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>paint</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainGridlinePaint()\r\n */\r\n public void setDomainGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the minor grid lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainMinorGridlinePaint(Paint)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Paint getDomainMinorGridlinePaint() {\r\n return this.domainMinorGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the minor grid lines plotted against the domain axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>paint</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainMinorGridlinePaint()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainMinorGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range axis grid is visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeGridlinesVisible(boolean)\r\n */\r\n public boolean isRangeGridlinesVisible() {\r\n return this.rangeGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the range axis grid lines\r\n * are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeGridlinesVisible()\r\n */\r\n public void setRangeGridlinesVisible(boolean visible) {\r\n if (this.rangeGridlinesVisible != visible) {\r\n this.rangeGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlineStroke(Stroke)\r\n */\r\n public Stroke getRangeGridlineStroke() {\r\n return this.rangeGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the grid lines plotted against the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlineStroke()\r\n */\r\n public void setRangeGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the grid lines (if any) plotted against the range\r\n * axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlinePaint(Paint)\r\n */\r\n public Paint getRangeGridlinePaint() {\r\n return this.rangeGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the grid lines plotted against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlinePaint()\r\n */\r\n public void setRangeGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range axis minor grid is visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeMinorGridlinesVisible(boolean)\r\n *\r\n * @since 1.0.12\r\n */\r\n public boolean isRangeMinorGridlinesVisible() {\r\n return this.rangeMinorGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the range axis minor grid\r\n * lines are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeMinorGridlinesVisible()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlinesVisible(boolean visible) {\r\n if (this.rangeMinorGridlinesVisible != visible) {\r\n this.rangeMinorGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlineStroke(Stroke)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Stroke getRangeMinorGridlineStroke() {\r\n return this.rangeMinorGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the minor grid lines plotted against the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlineStroke()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeMinorGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlinePaint(Paint)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Paint getRangeMinorGridlinePaint() {\r\n return this.rangeMinorGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the minor grid lines plotted against the range axis\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlinePaint()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeMinorGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a zero baseline is\r\n * displayed for the domain axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setDomainZeroBaselineVisible(boolean)\r\n */\r\n public boolean isDomainZeroBaselineVisible() {\r\n return this.domainZeroBaselineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the zero baseline is\r\n * displayed for the domain axis, and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #isDomainZeroBaselineVisible()\r\n */\r\n public void setDomainZeroBaselineVisible(boolean visible) {\r\n this.domainZeroBaselineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used for the zero baseline against the domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setDomainZeroBaselineStroke(Stroke)\r\n */\r\n public Stroke getDomainZeroBaselineStroke() {\r\n return this.domainZeroBaselineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the zero baseline for the domain axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getRangeZeroBaselineStroke()\r\n */\r\n public void setDomainZeroBaselineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainZeroBaselineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the zero baseline (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainZeroBaselinePaint(Paint)\r\n */\r\n public Paint getDomainZeroBaselinePaint() {\r\n return this.domainZeroBaselinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the zero baseline plotted against the domain axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getDomainZeroBaselinePaint()\r\n */\r\n public void setDomainZeroBaselinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainZeroBaselinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a zero baseline is\r\n * displayed for the range axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n */\r\n public boolean isRangeZeroBaselineVisible() {\r\n return this.rangeZeroBaselineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the zero baseline is\r\n * displayed for the range axis, and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isRangeZeroBaselineVisible()\r\n */\r\n public void setRangeZeroBaselineVisible(boolean visible) {\r\n this.rangeZeroBaselineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used for the zero baseline against the range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselineStroke(Stroke)\r\n */\r\n public Stroke getRangeZeroBaselineStroke() {\r\n return this.rangeZeroBaselineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the zero baseline for the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselineStroke()\r\n */\r\n public void setRangeZeroBaselineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeZeroBaselineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the zero baseline (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselinePaint(Paint)\r\n */\r\n public Paint getRangeZeroBaselinePaint() {\r\n return this.rangeZeroBaselinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the zero baseline plotted against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselinePaint()\r\n */\r\n public void setRangeZeroBaselinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeZeroBaselinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the domain tick bands. If this is\r\n * <code>null</code>, no tick bands will be drawn.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setDomainTickBandPaint(Paint)\r\n */\r\n public Paint getDomainTickBandPaint() {\r\n return this.domainTickBandPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the domain tick bands.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getDomainTickBandPaint()\r\n */\r\n public void setDomainTickBandPaint(Paint paint) {\r\n this.domainTickBandPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the range tick bands. If this is\r\n * <code>null</code>, no tick bands will be drawn.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setRangeTickBandPaint(Paint)\r\n */\r\n public Paint getRangeTickBandPaint() {\r\n return this.rangeTickBandPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the range tick bands.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getRangeTickBandPaint()\r\n */\r\n public void setRangeTickBandPaint(Paint paint) {\r\n this.rangeTickBandPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the origin for the quadrants that can be displayed on the plot.\r\n * This defaults to (0, 0).\r\n *\r\n * @return The origin point (never <code>null</code>).\r\n *\r\n * @see #setQuadrantOrigin(Point2D)\r\n */\r\n public Point2D getQuadrantOrigin() {\r\n return this.quadrantOrigin;\r\n }\r\n\r\n /**\r\n * Sets the quadrant origin and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param origin the origin (<code>null</code> not permitted).\r\n *\r\n * @see #getQuadrantOrigin()\r\n */\r\n public void setQuadrantOrigin(Point2D origin) {\r\n ParamChecks.nullNotPermitted(origin, \"origin\");\r\n this.quadrantOrigin = origin;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the specified quadrant.\r\n *\r\n * @param index the quadrant index (0-3).\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setQuadrantPaint(int, Paint)\r\n */\r\n public Paint getQuadrantPaint(int index) {\r\n if (index < 0 || index > 3) {\r\n throw new IllegalArgumentException(\"The index value (\" + index\r\n + \") should be in the range 0 to 3.\");\r\n }\r\n return this.quadrantPaint[index];\r\n }\r\n\r\n /**\r\n * Sets the paint used for the specified quadrant and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the quadrant index (0-3).\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getQuadrantPaint(int)\r\n */\r\n public void setQuadrantPaint(int index, Paint paint) {\r\n if (index < 0 || index > 3) {\r\n throw new IllegalArgumentException(\"The index value (\" + index\r\n + \") should be in the range 0 to 3.\");\r\n }\r\n this.quadrantPaint[index] = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #addDomainMarker(Marker, Layer)\r\n * @see #clearDomainMarkers()\r\n */\r\n public void addDomainMarker(Marker marker) {\r\n // defer argument checking...\r\n addDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for the domain axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void addDomainMarker(Marker marker, Layer layer) {\r\n addDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Clears all the (foreground and background) domain markers and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void clearDomainMarkers() {\r\n if (this.backgroundDomainMarkers != null) {\r\n Set<Integer> keys = this.backgroundDomainMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearDomainMarkers(key);\r\n }\r\n this.backgroundDomainMarkers.clear();\r\n }\r\n if (this.foregroundDomainMarkers != null) {\r\n Set<Integer> keys = this.foregroundDomainMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearDomainMarkers(key);\r\n }\r\n this.foregroundDomainMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Clears the (foreground and background) domain markers for a particular\r\n * renderer and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the renderer index.\r\n *\r\n * @see #clearRangeMarkers(int)\r\n */\r\n public void clearDomainMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundDomainMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis (that the renderer is mapped to), however this is\r\n * entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #clearDomainMarkers(int)\r\n * @see #addRangeMarker(int, Marker, Layer)\r\n */\r\n public void addDomainMarker(int index, Marker marker, Layer layer) {\r\n addDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis (that the renderer is mapped to), however this is\r\n * entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addDomainMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ParamChecks.nullNotPermitted(layer, \"layer\");\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker) {\r\n return removeDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker, Layer layer) {\r\n return removeDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer) {\r\n return removeDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and, if requested,\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ArrayList markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (ArrayList) this.foregroundDomainMarkers.get(\r\n new Integer(index));\r\n }\r\n else {\r\n markers = (ArrayList) this.backgroundDomainMarkers.get(\r\n new Integer(index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Adds a marker for the range axis and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #addRangeMarker(Marker, Layer)\r\n */\r\n public void addRangeMarker(Marker marker) {\r\n addRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for the range axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #addRangeMarker(int, Marker, Layer)\r\n */\r\n public void addRangeMarker(Marker marker, Layer layer) {\r\n addRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Clears all the range markers and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @see #clearRangeMarkers()\r\n */\r\n public void clearRangeMarkers() {\r\n if (this.backgroundRangeMarkers != null) {\r\n Set<Integer> keys = this.backgroundRangeMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearRangeMarkers(key);\r\n }\r\n this.backgroundRangeMarkers.clear();\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Set<Integer> keys = this.foregroundRangeMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearRangeMarkers(key);\r\n }\r\n this.foregroundRangeMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #clearRangeMarkers(int)\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer) {\r\n addRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Clears the (foreground and background) range markers for a particular\r\n * renderer.\r\n *\r\n * @param index the renderer index.\r\n */\r\n public void clearRangeMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(Marker marker) {\r\n return removeRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(Marker marker, Layer layer) {\r\n return removeRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer) {\r\n return removeRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background) (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ParamChecks.nullNotPermitted(layer, \"layer\");\r\n List markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (List) this.foregroundRangeMarkers.get(\r\n new Integer(index));\r\n }\r\n else {\r\n markers = (List) this.backgroundRangeMarkers.get(\r\n new Integer(index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @see #getAnnotations()\r\n * @see #removeAnnotation(XYAnnotation)\r\n */\r\n public void addAnnotation(XYAnnotation annotation) {\r\n addAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addAnnotation(XYAnnotation annotation, boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n this.annotations.add(annotation);\r\n annotation.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n * @see #getAnnotations()\r\n */\r\n public boolean removeAnnotation(XYAnnotation annotation) {\r\n return removeAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeAnnotation(XYAnnotation annotation, boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n boolean removed = this.annotations.remove(annotation);\r\n annotation.removeChangeListener(this);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Returns the list of annotations.\r\n *\r\n * @return The list of annotations.\r\n *\r\n * @since 1.0.1\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n */\r\n public List getAnnotations() {\r\n return new ArrayList(this.annotations);\r\n }\r\n\r\n /**\r\n * Clears all the annotations and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n */\r\n public void clearAnnotations() {\r\n for (XYAnnotation annotation : this.annotations) {\r\n annotation.removeChangeListener(this);\r\n }\r\n this.annotations.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the shadow generator for the plot, if any.\r\n *\r\n * @return The shadow generator (possibly <code>null</code>).\r\n *\r\n * @since 1.0.14\r\n */\r\n public ShadowGenerator getShadowGenerator() {\r\n return this.shadowGenerator;\r\n }\r\n\r\n /**\r\n * Sets the shadow generator for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setShadowGenerator(ShadowGenerator generator) {\r\n this.shadowGenerator = generator;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Calculates the space required for all the axes in the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateAxisSpace(Graphics2D g2,\r\n Rectangle2D plotArea) {\r\n AxisSpace space = new AxisSpace();\r\n space = calculateRangeAxisSpace(g2, plotArea, space);\r\n Rectangle2D revPlotArea = space.shrink(plotArea, null);\r\n space = calculateDomainAxisSpace(g2, revPlotArea, space);\r\n return space;\r\n }\r\n\r\n /**\r\n * Calculates the space required for the domain axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateDomainAxisSpace(Graphics2D g2, \r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the domain axis...\r\n if (this.fixedDomainAxisSpace != null) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getLeft(),\r\n RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n }\r\n else if (this.orientation == PlotOrientation.VERTICAL) {\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n }\r\n }\r\n else {\r\n // reserve space for the domain axes...\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n RectangleEdge edge = getDomainAxisEdge(\r\n findDomainAxisIndex(axis));\r\n space = axis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the space required for the range axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateRangeAxisSpace(Graphics2D g2, \r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the range axis...\r\n if (this.fixedRangeAxisSpace != null) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n }\r\n else if (this.orientation == PlotOrientation.VERTICAL) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getLeft(),\r\n RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n }\r\n }\r\n else {\r\n // reserve space for the range axes...\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n RectangleEdge edge = getRangeAxisEdge(\r\n findRangeAxisIndex(axis));\r\n space = axis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Trims a rectangle to integer coordinates.\r\n *\r\n * @param rect the incoming rectangle.\r\n *\r\n * @return A rectangle with integer coordinates.\r\n */\r\n private Rectangle integerise(Rectangle2D rect) {\r\n int x0 = (int) Math.ceil(rect.getMinX());\r\n int y0 = (int) Math.ceil(rect.getMinY());\r\n int x1 = (int) Math.floor(rect.getMaxX());\r\n int y1 = (int) Math.floor(rect.getMaxY());\r\n return new Rectangle(x0, y0, (x1 - x0), (y1 - y0));\r\n }\r\n\r\n /**\r\n * Draws the plot within the specified area on a graphics device.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the plot area (in Java2D space).\r\n * @param anchor an anchor point in Java2D space (<code>null</code>\r\n * permitted).\r\n * @param parentState the state from the parent plot, if there is one\r\n * (<code>null</code> permitted).\r\n * @param info collects chart drawing information (<code>null</code>\r\n * permitted).\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor,\r\n PlotState parentState, PlotRenderingInfo info) {\r\n\r\n // if the plot area is too small, just return...\r\n boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW);\r\n boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW);\r\n if (b1 || b2) {\r\n return;\r\n }\r\n\r\n // record the plot area...\r\n if (info != null) {\r\n info.setPlotArea(area);\r\n }\r\n\r\n // adjust the drawing area for the plot insets (if any)...\r\n RectangleInsets insets = getInsets();\r\n insets.trim(area);\r\n\r\n AxisSpace space = calculateAxisSpace(g2, area);\r\n Rectangle2D dataArea = space.shrink(area, null);\r\n this.axisOffset.trim(dataArea);\r\n\r\n dataArea = integerise(dataArea);\r\n if (dataArea.isEmpty()) {\r\n return;\r\n }\r\n createAndAddEntity((Rectangle2D) dataArea.clone(), info, null, null);\r\n if (info != null) {\r\n info.setDataArea(dataArea);\r\n }\r\n\r\n // draw the plot background and axes...\r\n drawBackground(g2, dataArea);\r\n Map axisStateMap = drawAxes(g2, area, dataArea, info);\r\n\r\n PlotOrientation orient = getOrientation();\r\n\r\n // the anchor point is typically the point where the mouse last\r\n // clicked - the crosshairs will be driven off this point...\r\n if (anchor != null && !dataArea.contains(anchor)) {\r\n anchor = null;\r\n }\r\n CrosshairState crosshairState = new CrosshairState();\r\n crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY);\r\n crosshairState.setAnchor(anchor);\r\n\r\n crosshairState.setAnchorX(Double.NaN);\r\n crosshairState.setAnchorY(Double.NaN);\r\n if (anchor != null) {\r\n ValueAxis domainAxis = getDomainAxis();\r\n if (domainAxis != null) {\r\n double x;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n x = domainAxis.java2DToValue(anchor.getX(), dataArea,\r\n getDomainAxisEdge());\r\n }\r\n else {\r\n x = domainAxis.java2DToValue(anchor.getY(), dataArea,\r\n getDomainAxisEdge());\r\n }\r\n crosshairState.setAnchorX(x);\r\n }\r\n ValueAxis rangeAxis = getRangeAxis();\r\n if (rangeAxis != null) {\r\n double y;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n y = rangeAxis.java2DToValue(anchor.getY(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n else {\r\n y = rangeAxis.java2DToValue(anchor.getX(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n crosshairState.setAnchorY(y);\r\n }\r\n }\r\n crosshairState.setCrosshairX(getDomainCrosshairValue());\r\n crosshairState.setCrosshairY(getRangeCrosshairValue());\r\n Shape originalClip = g2.getClip();\r\n Composite originalComposite = g2.getComposite();\r\n\r\n g2.clip(dataArea);\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n getForegroundAlpha()));\r\n\r\n AxisState domainAxisState = (AxisState) axisStateMap.get(\r\n getDomainAxis());\r\n if (domainAxisState == null) {\r\n if (parentState != null) {\r\n domainAxisState = (AxisState) parentState.getSharedAxisStates()\r\n .get(getDomainAxis());\r\n }\r\n }\r\n\r\n AxisState rangeAxisState = (AxisState) axisStateMap.get(getRangeAxis());\r\n if (rangeAxisState == null) {\r\n if (parentState != null) {\r\n rangeAxisState = (AxisState) parentState.getSharedAxisStates()\r\n .get(getRangeAxis());\r\n }\r\n }\r\n if (domainAxisState != null) {\r\n drawDomainTickBands(g2, dataArea, domainAxisState.getTicks());\r\n }\r\n if (rangeAxisState != null) {\r\n drawRangeTickBands(g2, dataArea, rangeAxisState.getTicks());\r\n }\r\n if (domainAxisState != null) {\r\n drawDomainGridlines(g2, dataArea, domainAxisState.getTicks());\r\n drawZeroDomainBaseline(g2, dataArea);\r\n }\r\n if (rangeAxisState != null) {\r\n drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks());\r\n drawZeroRangeBaseline(g2, dataArea);\r\n }\r\n\r\n Graphics2D savedG2 = g2;\r\n BufferedImage dataImage = null;\r\n boolean suppressShadow = Boolean.TRUE.equals(g2.getRenderingHint(\r\n JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION));\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n dataImage = new BufferedImage((int) dataArea.getWidth(),\r\n (int)dataArea.getHeight(), BufferedImage.TYPE_INT_ARGB);\r\n g2 = dataImage.createGraphics();\r\n g2.translate(-dataArea.getX(), -dataArea.getY());\r\n g2.setRenderingHints(savedG2.getRenderingHints());\r\n }\r\n\r\n // draw the markers that are associated with a specific dataset...\r\n for (XYDataset dataset: this.datasets.values()) {\r\n int datasetIndex = indexOf(dataset);\r\n drawDomainMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND);\r\n }\r\n for (XYDataset dataset: this.datasets.values()) {\r\n int datasetIndex = indexOf(dataset);\r\n drawRangeMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND);\r\n }\r\n\r\n // now draw annotations and render data items...\r\n boolean foundData = false;\r\n DatasetRenderingOrder order = getDatasetRenderingOrder();\r\n List<Integer> rendererIndices = getRendererIndices(order);\r\n List<Integer> datasetIndices = getDatasetIndices(order);\r\n // draw background annotations\r\n for (int i : rendererIndices) {\r\n XYItemRenderer renderer = getRenderer(i);\r\n if (renderer != null) {\r\n ValueAxis domainAxis = getDomainAxisForDataset(i);\r\n ValueAxis rangeAxis = getRangeAxisForDataset(i);\r\n renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, \r\n Layer.BACKGROUND, info);\r\n }\r\n }\r\n\r\n // render data items...\r\n for (int datasetIndex : datasetIndices) {\r\n XYDataset dataset = this.getDataset(datasetIndex);\r\n foundData = render(g2, dataArea, datasetIndex, info, \r\n crosshairState) || foundData;\r\n }\r\n\r\n // draw foreground annotations\r\n for (int i : rendererIndices) {\r\n XYItemRenderer renderer = getRenderer(i);\r\n if (renderer != null) {\r\n ValueAxis domainAxis = getDomainAxisForDataset(i);\r\n ValueAxis rangeAxis = getRangeAxisForDataset(i);\r\n renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, \r\n Layer.FOREGROUND, info);\r\n }\r\n }\r\n\r\n // draw domain crosshair if required...\r\n int datasetIndex = crosshairState.getDatasetIndex();\r\n ValueAxis xAxis = this.getDomainAxisForDataset(datasetIndex);\r\n RectangleEdge xAxisEdge = getDomainAxisEdge(getDomainAxisIndex(xAxis));\r\n if (!this.domainCrosshairLockedOnData && anchor != null) {\r\n double xx;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n xx = xAxis.java2DToValue(anchor.getX(), dataArea, xAxisEdge);\r\n }\r\n else {\r\n xx = xAxis.java2DToValue(anchor.getY(), dataArea, xAxisEdge);\r\n }\r\n crosshairState.setCrosshairX(xx);\r\n }\r\n setDomainCrosshairValue(crosshairState.getCrosshairX(), false);\r\n if (isDomainCrosshairVisible()) {\r\n double x = getDomainCrosshairValue();\r\n Paint paint = getDomainCrosshairPaint();\r\n Stroke stroke = getDomainCrosshairStroke();\r\n drawDomainCrosshair(g2, dataArea, orient, x, xAxis, stroke, paint);\r\n }\r\n\r\n // draw range crosshair if required...\r\n ValueAxis yAxis = getRangeAxisForDataset(datasetIndex);\r\n RectangleEdge yAxisEdge = getRangeAxisEdge(getRangeAxisIndex(yAxis));\r\n if (!this.rangeCrosshairLockedOnData && anchor != null) {\r\n double yy;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n yy = yAxis.java2DToValue(anchor.getY(), dataArea, yAxisEdge);\r\n } else {\r\n yy = yAxis.java2DToValue(anchor.getX(), dataArea, yAxisEdge);\r\n }\r\n crosshairState.setCrosshairY(yy);\r\n }\r\n setRangeCrosshairValue(crosshairState.getCrosshairY(), false);\r\n if (isRangeCrosshairVisible()) {\r\n double y = getRangeCrosshairValue();\r\n Paint paint = getRangeCrosshairPaint();\r\n Stroke stroke = getRangeCrosshairStroke();\r\n drawRangeCrosshair(g2, dataArea, orient, y, yAxis, stroke, paint);\r\n }\r\n\r\n if (!foundData) {\r\n drawNoDataMessage(g2, dataArea);\r\n }\r\n\r\n for (int i : rendererIndices) { \r\n drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n for (int i : rendererIndices) {\r\n drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n\r\n drawAnnotations(g2, dataArea, info);\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n BufferedImage shadowImage\r\n = this.shadowGenerator.createDropShadow(dataImage);\r\n g2 = savedG2;\r\n g2.drawImage(shadowImage, (int) dataArea.getX()\r\n + this.shadowGenerator.calculateOffsetX(),\r\n (int) dataArea.getY()\r\n + this.shadowGenerator.calculateOffsetY(), null);\r\n g2.drawImage(dataImage, (int) dataArea.getX(),\r\n (int) dataArea.getY(), null);\r\n }\r\n g2.setClip(originalClip);\r\n g2.setComposite(originalComposite);\r\n\r\n drawOutline(g2, dataArea);\r\n\r\n }\r\n\r\n /**\r\n * Returns the indices of the non-null datasets in the specified order.\r\n * \r\n * @param order the order (<code>null</code> not permitted).\r\n * \r\n * @return The list of indices. \r\n */\r\n private List<Integer> getDatasetIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result;\r\n }\r\n \r\n private List<Integer> getRendererIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Entry<Integer, XYItemRenderer> entry : this.renderers.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result; \r\n }\r\n \r\n /**\r\n * Draws the background for the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n */\r\n @Override\r\n public void drawBackground(Graphics2D g2, Rectangle2D area) {\r\n fillBackground(g2, area, this.orientation);\r\n drawQuadrants(g2, area);\r\n drawBackgroundImage(g2, area);\r\n }\r\n\r\n /**\r\n * Draws the quadrants.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n *\r\n * @see #setQuadrantOrigin(Point2D)\r\n * @see #setQuadrantPaint(int, Paint)\r\n */\r\n protected void drawQuadrants(Graphics2D g2, Rectangle2D area) {\r\n // 0 | 1\r\n // --+--\r\n // 2 | 3\r\n boolean somethingToDraw = false;\r\n\r\n ValueAxis xAxis = getDomainAxis();\r\n if (xAxis == null) { // we can't draw quadrants without a valid x-axis\r\n return;\r\n }\r\n double x = xAxis.getRange().constrain(this.quadrantOrigin.getX());\r\n double xx = xAxis.valueToJava2D(x, area, getDomainAxisEdge());\r\n\r\n ValueAxis yAxis = getRangeAxis();\r\n if (yAxis == null) { // we can't draw quadrants without a valid y-axis\r\n return;\r\n }\r\n double y = yAxis.getRange().constrain(this.quadrantOrigin.getY());\r\n double yy = yAxis.valueToJava2D(y, area, getRangeAxisEdge());\r\n\r\n double xmin = xAxis.getLowerBound();\r\n double xxmin = xAxis.valueToJava2D(xmin, area, getDomainAxisEdge());\r\n\r\n double xmax = xAxis.getUpperBound();\r\n double xxmax = xAxis.valueToJava2D(xmax, area, getDomainAxisEdge());\r\n\r\n double ymin = yAxis.getLowerBound();\r\n double yymin = yAxis.valueToJava2D(ymin, area, getRangeAxisEdge());\r\n\r\n double ymax = yAxis.getUpperBound();\r\n double yymax = yAxis.valueToJava2D(ymax, area, getRangeAxisEdge());\r\n\r\n Rectangle2D[] r = new Rectangle2D[] {null, null, null, null};\r\n if (this.quadrantPaint[0] != null) {\r\n if (x > xmin && y < ymax) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[0] = new Rectangle2D.Double(Math.min(yymax, yy),\r\n Math.min(xxmin, xx), Math.abs(yy - yymax),\r\n Math.abs(xx - xxmin));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[0] = new Rectangle2D.Double(Math.min(xxmin, xx),\r\n Math.min(yymax, yy), Math.abs(xx - xxmin),\r\n Math.abs(yy - yymax));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[1] != null) {\r\n if (x < xmax && y < ymax) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[1] = new Rectangle2D.Double(Math.min(yymax, yy),\r\n Math.min(xxmax, xx), Math.abs(yy - yymax),\r\n Math.abs(xx - xxmax));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[1] = new Rectangle2D.Double(Math.min(xx, xxmax),\r\n Math.min(yymax, yy), Math.abs(xx - xxmax),\r\n Math.abs(yy - yymax));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[2] != null) {\r\n if (x > xmin && y > ymin) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[2] = new Rectangle2D.Double(Math.min(yymin, yy),\r\n Math.min(xxmin, xx), Math.abs(yy - yymin),\r\n Math.abs(xx - xxmin));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[2] = new Rectangle2D.Double(Math.min(xxmin, xx),\r\n Math.min(yymin, yy), Math.abs(xx - xxmin),\r\n Math.abs(yy - yymin));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[3] != null) {\r\n if (x < xmax && y > ymin) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[3] = new Rectangle2D.Double(Math.min(yymin, yy),\r\n Math.min(xxmax, xx), Math.abs(yy - yymin),\r\n Math.abs(xx - xxmax));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[3] = new Rectangle2D.Double(Math.min(xx, xxmax),\r\n Math.min(yymin, yy), Math.abs(xx - xxmax),\r\n Math.abs(yy - yymin));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (somethingToDraw) {\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n getBackgroundAlpha()));\r\n for (int i = 0; i < 4; i++) {\r\n if (this.quadrantPaint[i] != null && r[i] != null) {\r\n g2.setPaint(this.quadrantPaint[i]);\r\n g2.fill(r[i]);\r\n }\r\n }\r\n g2.setComposite(originalComposite);\r\n }\r\n }\r\n\r\n /**\r\n * Draws the domain tick bands, if any.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #setDomainTickBandPaint(Paint)\r\n */\r\n public void drawDomainTickBands(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n Paint bandPaint = getDomainTickBandPaint();\r\n if (bandPaint != null) {\r\n boolean fillBand = false;\r\n ValueAxis xAxis = getDomainAxis();\r\n double previous = xAxis.getLowerBound();\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n double current = tick.getValue();\r\n if (fillBand) {\r\n getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea,\r\n previous, current);\r\n }\r\n previous = current;\r\n fillBand = !fillBand;\r\n }\r\n double end = xAxis.getUpperBound();\r\n if (fillBand) {\r\n getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea,\r\n previous, end);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws the range tick bands, if any.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #setRangeTickBandPaint(Paint)\r\n */\r\n public void drawRangeTickBands(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n Paint bandPaint = getRangeTickBandPaint();\r\n if (bandPaint != null) {\r\n boolean fillBand = false;\r\n ValueAxis axis = getRangeAxis();\r\n double previous = axis.getLowerBound();\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n double current = tick.getValue();\r\n if (fillBand) {\r\n getRenderer().fillRangeGridBand(g2, this, axis, dataArea,\r\n previous, current);\r\n }\r\n previous = current;\r\n fillBand = !fillBand;\r\n }\r\n double end = axis.getUpperBound();\r\n if (fillBand) {\r\n getRenderer().fillRangeGridBand(g2, this, axis, dataArea,\r\n previous, end);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * A utility method for drawing the axes.\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param plotArea the plot area (<code>null</code> not permitted).\r\n * @param dataArea the data area (<code>null</code> not permitted).\r\n * @param plotState collects information about the plot (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A map containing the state for each axis drawn.\r\n */\r\n protected Map<Axis, AxisState> drawAxes(Graphics2D g2, Rectangle2D plotArea,\r\n Rectangle2D dataArea, PlotRenderingInfo plotState) {\r\n\r\n AxisCollection axisCollection = new AxisCollection();\r\n\r\n // add domain axes to lists...\r\n for (ValueAxis axis : this.domainAxes.values()) {\r\n if (axis != null) {\r\n int axisIndex = findDomainAxisIndex(axis);\r\n axisCollection.add(axis, getDomainAxisEdge(axisIndex));\r\n }\r\n }\r\n\r\n // add range axes to lists...\r\n for (ValueAxis axis : this.rangeAxes.values()) {\r\n if (axis != null) {\r\n int axisIndex = findRangeAxisIndex(axis);\r\n axisCollection.add(axis, getRangeAxisEdge(axisIndex));\r\n }\r\n }\r\n\r\n Map axisStateMap = new HashMap();\r\n\r\n // draw the top axes\r\n double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset(\r\n dataArea.getHeight());\r\n Iterator iterator = axisCollection.getAxesAtTop().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.TOP, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the bottom axes\r\n cursor = dataArea.getMaxY()\r\n + this.axisOffset.calculateBottomOutset(dataArea.getHeight());\r\n iterator = axisCollection.getAxesAtBottom().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.BOTTOM, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the left axes\r\n cursor = dataArea.getMinX()\r\n - this.axisOffset.calculateLeftOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtLeft().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.LEFT, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the right axes\r\n cursor = dataArea.getMaxX()\r\n + this.axisOffset.calculateRightOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtRight().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.RIGHT, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n return axisStateMap;\r\n }\r\n\r\n /**\r\n * Draws a representation of the data within the dataArea region, using the\r\n * current renderer.\r\n * <P>\r\n * The <code>info</code> and <code>crosshairState</code> arguments may be\r\n * <code>null</code>.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the region in which the data is to be drawn.\r\n * @param index the dataset index.\r\n * @param info an optional object for collection dimension information.\r\n * @param crosshairState collects crosshair information\r\n * (<code>null</code> permitted).\r\n *\r\n * @return A flag that indicates whether any data was actually rendered.\r\n */\r\n public boolean render(Graphics2D g2, Rectangle2D dataArea, int index,\r\n PlotRenderingInfo info, CrosshairState crosshairState) {\r\n\r\n boolean foundData = false;\r\n XYDataset dataset = getDataset(index);\r\n if (!DatasetUtilities.isEmptyOrNull(dataset)) {\r\n foundData = true;\r\n ValueAxis xAxis = getDomainAxisForDataset(index);\r\n ValueAxis yAxis = getRangeAxisForDataset(index);\r\n if (xAxis == null || yAxis == null) {\r\n return foundData; // can't render anything without axes\r\n }\r\n XYItemRenderer renderer = getRenderer(index);\r\n if (renderer == null) {\r\n renderer = getRenderer();\r\n if (renderer == null) { // no default renderer available\r\n return foundData;\r\n }\r\n }\r\n\r\n XYItemRendererState state = renderer.initialise(g2, dataArea, this,\r\n dataset, info);\r\n int passCount = renderer.getPassCount();\r\n\r\n SeriesRenderingOrder seriesOrder = getSeriesRenderingOrder();\r\n if (seriesOrder == SeriesRenderingOrder.REVERSE) {\r\n //render series in reverse order\r\n for (int pass = 0; pass < passCount; pass++) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = seriesCount - 1; series >= 0; series--) {\r\n int firstItem = 0;\r\n int lastItem = dataset.getItemCount(series) - 1;\r\n if (lastItem == -1) {\r\n continue;\r\n }\r\n if (state.getProcessVisibleItemsOnly()) {\r\n int[] itemBounds = RendererUtilities.findLiveItems(\r\n dataset, series, xAxis.getLowerBound(),\r\n xAxis.getUpperBound());\r\n firstItem = Math.max(itemBounds[0] - 1, 0);\r\n lastItem = Math.min(itemBounds[1] + 1, lastItem);\r\n }\r\n state.startSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n for (int item = firstItem; item <= lastItem; item++) {\r\n renderer.drawItem(g2, state, dataArea, info,\r\n this, xAxis, yAxis, dataset, series, item,\r\n crosshairState, pass);\r\n }\r\n state.endSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n }\r\n }\r\n }\r\n else {\r\n //render series in forward order\r\n for (int pass = 0; pass < passCount; pass++) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n int firstItem = 0;\r\n int lastItem = dataset.getItemCount(series) - 1;\r\n if (state.getProcessVisibleItemsOnly()) {\r\n int[] itemBounds = RendererUtilities.findLiveItems(\r\n dataset, series, xAxis.getLowerBound(),\r\n xAxis.getUpperBound());\r\n firstItem = Math.max(itemBounds[0] - 1, 0);\r\n lastItem = Math.min(itemBounds[1] + 1, lastItem);\r\n }\r\n state.startSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n for (int item = firstItem; item <= lastItem; item++) {\r\n renderer.drawItem(g2, state, dataArea, info,\r\n this, xAxis, yAxis, dataset, series, item,\r\n crosshairState, pass);\r\n }\r\n state.endSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n }\r\n }\r\n }\r\n }\r\n return foundData;\r\n }\r\n\r\n /**\r\n * Returns the domain axis for a dataset.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The axis.\r\n */\r\n public ValueAxis getDomainAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n ValueAxis valueAxis;\r\n List axisIndices = (List) this.datasetToDomainAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n valueAxis = getDomainAxis(axisIndex.intValue());\r\n }\r\n else {\r\n valueAxis = getDomainAxis(0);\r\n }\r\n return valueAxis;\r\n }\r\n\r\n /**\r\n * Returns the range axis for a dataset.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The axis.\r\n */\r\n public ValueAxis getRangeAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n ValueAxis valueAxis;\r\n List axisIndices = (List) this.datasetToRangeAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n valueAxis = getRangeAxis(axisIndex.intValue());\r\n }\r\n else {\r\n valueAxis = getRangeAxis(0);\r\n }\r\n return valueAxis;\r\n }\r\n\r\n /**\r\n * Draws the gridlines for the plot, if they are visible.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #drawRangeGridlines(Graphics2D, Rectangle2D, List)\r\n */\r\n protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n\r\n // no renderer, no gridlines...\r\n if (getRenderer() == null) {\r\n return;\r\n }\r\n\r\n // draw the domain grid lines, if any...\r\n if (isDomainGridlinesVisible() || isDomainMinorGridlinesVisible()) {\r\n Stroke gridStroke = null;\r\n Paint gridPaint = null;\r\n Iterator iterator = ticks.iterator();\r\n boolean paintLine;\r\n while (iterator.hasNext()) {\r\n paintLine = false;\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if ((tick.getTickType() == TickType.MINOR)\r\n && isDomainMinorGridlinesVisible()) {\r\n gridStroke = getDomainMinorGridlineStroke();\r\n gridPaint = getDomainMinorGridlinePaint();\r\n paintLine = true;\r\n } else if ((tick.getTickType() == TickType.MAJOR)\r\n && isDomainGridlinesVisible()) {\r\n gridStroke = getDomainGridlineStroke();\r\n gridPaint = getDomainGridlinePaint();\r\n paintLine = true;\r\n }\r\n XYItemRenderer r = getRenderer();\r\n if ((r instanceof AbstractXYItemRenderer) && paintLine) {\r\n ((AbstractXYItemRenderer) r).drawDomainLine(g2, this,\r\n getDomainAxis(), dataArea, tick.getValue(),\r\n gridPaint, gridStroke);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws the gridlines for the plot's primary range axis, if they are\r\n * visible.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #drawDomainGridlines(Graphics2D, Rectangle2D, List)\r\n */\r\n protected void drawRangeGridlines(Graphics2D g2, Rectangle2D area,\r\n List ticks) {\r\n\r\n // no renderer, no gridlines...\r\n if (getRenderer() == null) {\r\n return;\r\n }\r\n\r\n // draw the range grid lines, if any...\r\n if (isRangeGridlinesVisible() || isRangeMinorGridlinesVisible()) {\r\n Stroke gridStroke = null;\r\n Paint gridPaint = null;\r\n ValueAxis axis = getRangeAxis();\r\n if (axis != null) {\r\n Iterator iterator = ticks.iterator();\r\n boolean paintLine;\r\n while (iterator.hasNext()) {\r\n paintLine = false;\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if ((tick.getTickType() == TickType.MINOR)\r\n && isRangeMinorGridlinesVisible()) {\r\n gridStroke = getRangeMinorGridlineStroke();\r\n gridPaint = getRangeMinorGridlinePaint();\r\n paintLine = true;\r\n } else if ((tick.getTickType() == TickType.MAJOR)\r\n && isRangeGridlinesVisible()) {\r\n gridStroke = getRangeGridlineStroke();\r\n gridPaint = getRangeGridlinePaint();\r\n paintLine = true;\r\n }\r\n if ((tick.getValue() != 0.0\r\n || !isRangeZeroBaselineVisible()) && paintLine) {\r\n getRenderer().drawRangeLine(g2, this, getRangeAxis(),\r\n area, tick.getValue(), gridPaint, gridStroke);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws a base line across the chart at value zero on the domain axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n *\r\n * @see #setDomainZeroBaselineVisible(boolean)\r\n *\r\n * @since 1.0.5\r\n */\r\n protected void drawZeroDomainBaseline(Graphics2D g2, Rectangle2D area) {\r\n if (isDomainZeroBaselineVisible()) {\r\n XYItemRenderer r = getRenderer();\r\n // FIXME: the renderer interface doesn't have the drawDomainLine()\r\n // method, so we have to rely on the renderer being a subclass of\r\n // AbstractXYItemRenderer (which is lame)\r\n if (r instanceof AbstractXYItemRenderer) {\r\n AbstractXYItemRenderer renderer = (AbstractXYItemRenderer) r;\r\n renderer.drawDomainLine(g2, this, getDomainAxis(), area, 0.0,\r\n this.domainZeroBaselinePaint,\r\n this.domainZeroBaselineStroke);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws a base line across the chart at value zero on the range axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n */\r\n protected void drawZeroRangeBaseline(Graphics2D g2, Rectangle2D area) {\r\n if (isRangeZeroBaselineVisible()) {\r\n getRenderer().drawRangeLine(g2, this, getRangeAxis(), area, 0.0,\r\n this.rangeZeroBaselinePaint, this.rangeZeroBaselineStroke);\r\n }\r\n }\r\n\r\n /**\r\n * Draws the annotations for the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param info the chart rendering info.\r\n */\r\n public void drawAnnotations(Graphics2D g2, Rectangle2D dataArea,\r\n PlotRenderingInfo info) {\r\n\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n ValueAxis xAxis = getDomainAxis();\r\n ValueAxis yAxis = getRangeAxis();\r\n annotation.draw(g2, this, dataArea, xAxis, yAxis, 0, info);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the domain markers (if any) for an axis and layer. This method is\r\n * typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the dataset/renderer index.\r\n * @param layer the layer (foreground or background).\r\n */\r\n protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n XYItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n // check that the renderer has a corresponding dataset (it doesn't\r\n // matter if the dataset is null)\r\n if (index >= getDatasetCount()) {\r\n return;\r\n }\r\n Collection markers = getDomainMarkers(index, layer);\r\n ValueAxis axis = getDomainAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker marker = (Marker) iterator.next();\r\n r.drawDomainMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the range markers (if any) for a renderer and layer. This method\r\n * is typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the renderer index.\r\n * @param layer the layer (foreground or background).\r\n */\r\n protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n XYItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n // check that the renderer has a corresponding dataset (it doesn't\r\n // matter if the dataset is null)\r\n if (index >= getDatasetCount()) {\r\n return;\r\n }\r\n Collection markers = getRangeMarkers(index, layer);\r\n ValueAxis axis = getRangeAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker marker = (Marker) iterator.next();\r\n r.drawRangeMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the list of domain markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of domain markers.\r\n *\r\n * @see #getRangeMarkers(Layer)\r\n */\r\n public Collection getDomainMarkers(Layer layer) {\r\n return getDomainMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns the list of range markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of range markers.\r\n *\r\n * @see #getDomainMarkers(Layer)\r\n */\r\n public Collection getRangeMarkers(Layer layer) {\r\n return getRangeMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns a collection of domain markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n *\r\n * @see #getRangeMarkers(int, Layer)\r\n */\r\n public Collection getDomainMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundDomainMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundDomainMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a collection of range markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n *\r\n * @see #getDomainMarkers(int, Layer)\r\n */\r\n public Collection getRangeMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundRangeMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundRangeMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Utility method for drawing a horizontal line across the data area of the\r\n * plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param value the coordinate, where to draw the line.\r\n * @param stroke the stroke to use.\r\n * @param paint the paint to use.\r\n */\r\n protected void drawHorizontalLine(Graphics2D g2, Rectangle2D dataArea,\r\n double value, Stroke stroke,\r\n Paint paint) {\r\n\r\n ValueAxis axis = getRangeAxis();\r\n if (getOrientation() == PlotOrientation.HORIZONTAL) {\r\n axis = getDomainAxis();\r\n }\r\n if (axis.getRange().contains(value)) {\r\n double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT);\r\n Line2D line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws a domain crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param value the crosshair value.\r\n * @param axis the axis against which the value is measured.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @since 1.0.4\r\n */\r\n protected void drawDomainCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, double value, ValueAxis axis,\r\n Stroke stroke, Paint paint) {\r\n\r\n if (!axis.getRange().contains(value)) {\r\n return;\r\n }\r\n Line2D line;\r\n if (orientation == PlotOrientation.VERTICAL) {\r\n double xx = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n } else {\r\n double yy = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n\r\n /**\r\n * Utility method for drawing a vertical line on the data area of the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param value the coordinate, where to draw the line.\r\n * @param stroke the stroke to use.\r\n * @param paint the paint to use.\r\n */\r\n protected void drawVerticalLine(Graphics2D g2, Rectangle2D dataArea,\r\n double value, Stroke stroke, Paint paint) {\r\n\r\n ValueAxis axis = getDomainAxis();\r\n if (getOrientation() == PlotOrientation.HORIZONTAL) {\r\n axis = getRangeAxis();\r\n }\r\n if (axis.getRange().contains(value)) {\r\n double xx = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.BOTTOM);\r\n Line2D line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws a range crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param value the crosshair value.\r\n * @param axis the axis against which the value is measured.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @since 1.0.4\r\n */\r\n protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, double value, ValueAxis axis,\r\n Stroke stroke, Paint paint) {\r\n\r\n if (!axis.getRange().contains(value)) {\r\n return;\r\n }\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n Line2D line;\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n double xx = axis.valueToJava2D(value, dataArea, \r\n RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n } else {\r\n double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the plot by updating the anchor values.\r\n *\r\n * @param x the x-coordinate, where the click occurred, in Java2D space.\r\n * @param y the y-coordinate, where the click occurred, in Java2D space.\r\n * @param info object containing information about the plot dimensions.\r\n */\r\n @Override\r\n public void handleClick(int x, int y, PlotRenderingInfo info) {\r\n\r\n Rectangle2D dataArea = info.getDataArea();\r\n if (dataArea.contains(x, y)) {\r\n // set the anchor value for the horizontal axis...\r\n ValueAxis xaxis = getDomainAxis();\r\n if (xaxis != null) {\r\n double hvalue = xaxis.java2DToValue(x, info.getDataArea(),\r\n getDomainAxisEdge());\r\n setDomainCrosshairValue(hvalue);\r\n }\r\n\r\n // set the anchor value for the vertical axis...\r\n ValueAxis yaxis = getRangeAxis();\r\n if (yaxis != null) {\r\n double vvalue = yaxis.java2DToValue(y, info.getDataArea(),\r\n getRangeAxisEdge());\r\n setRangeCrosshairValue(vvalue);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * A utility method that returns a list of datasets that are mapped to a\r\n * particular axis.\r\n *\r\n * @param axisIndex the axis index (<code>null</code> not permitted).\r\n *\r\n * @return A list of datasets.\r\n */\r\n private List<XYDataset> getDatasetsMappedToDomainAxis(Integer axisIndex) {\r\n ParamChecks.nullNotPermitted(axisIndex, \"axisIndex\");\r\n List<XYDataset> result = new ArrayList<XYDataset>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n int index = entry.getKey();\r\n List<Integer> mappedAxes = this.datasetToDomainAxesMap.get(index);\r\n if (mappedAxes == null) {\r\n if (axisIndex.equals(ZERO)) {\r\n result.add(entry.getValue());\r\n }\r\n } else {\r\n if (mappedAxes.contains(axisIndex)) {\r\n result.add(entry.getValue());\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * A utility method that returns a list of datasets that are mapped to a\r\n * particular axis.\r\n *\r\n * @param axisIndex the axis index (<code>null</code> not permitted).\r\n *\r\n * @return A list of datasets.\r\n */\r\n private List<XYDataset> getDatasetsMappedToRangeAxis(Integer axisIndex) {\r\n ParamChecks.nullNotPermitted(axisIndex, \"axisIndex\");\r\n List<XYDataset> result = new ArrayList<XYDataset>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n int index = entry.getKey();\r\n List<Integer> mappedAxes = this.datasetToRangeAxesMap.get(index);\r\n if (mappedAxes == null) {\r\n if (axisIndex.equals(ZERO)) {\r\n result.add(entry.getValue());\r\n }\r\n } else {\r\n if (mappedAxes.contains(axisIndex)) {\r\n result.add(entry.getValue());\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the index of the given domain axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getRangeAxisIndex(ValueAxis)\r\n */\r\n public int getDomainAxisIndex(ValueAxis axis) {\r\n int result = findDomainAxisIndex(axis);\r\n if (result < 0) {\r\n // try the parent plot\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot p = (XYPlot) parent;\r\n result = p.getDomainAxisIndex(axis);\r\n }\r\n }\r\n return result;\r\n }\r\n \r\n private int findDomainAxisIndex(ValueAxis axis) {\r\n for (Map.Entry<Integer, ValueAxis> entry : this.domainAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the index of the given range axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getDomainAxisIndex(ValueAxis)\r\n */\r\n public int getRangeAxisIndex(ValueAxis axis) {\r\n int result = findRangeAxisIndex(axis);\r\n if (result < 0) {\r\n // try the parent plot\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot p = (XYPlot) parent;\r\n result = p.getRangeAxisIndex(axis);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n private int findRangeAxisIndex(ValueAxis axis) {\r\n for (Map.Entry<Integer, ValueAxis> entry : this.rangeAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the range for the specified axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The range.\r\n */\r\n @Override\r\n public Range getDataRange(ValueAxis axis) {\r\n\r\n Range result = null;\r\n List<XYDataset> mappedDatasets = new ArrayList<XYDataset>();\r\n List<XYAnnotation> includedAnnotations = new ArrayList<XYAnnotation>();\r\n boolean isDomainAxis = true;\r\n\r\n // is it a domain axis?\r\n int domainIndex = getDomainAxisIndex(axis);\r\n if (domainIndex >= 0) {\r\n isDomainAxis = true;\r\n mappedDatasets.addAll(getDatasetsMappedToDomainAxis(domainIndex));\r\n if (domainIndex == 0) {\r\n // grab the plot's annotations\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n if (annotation instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(annotation);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // or is it a range axis?\r\n int rangeIndex = getRangeAxisIndex(axis);\r\n if (rangeIndex >= 0) {\r\n isDomainAxis = false;\r\n mappedDatasets.addAll(getDatasetsMappedToRangeAxis(rangeIndex));\r\n if (rangeIndex == 0) {\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n if (annotation instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(annotation);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // iterate through the datasets that map to the axis and get the union\r\n // of the ranges.\r\n for (XYDataset d : mappedDatasets) {\r\n if (d != null) {\r\n XYItemRenderer r = getRendererForDataset(d);\r\n if (isDomainAxis) {\r\n if (r != null) {\r\n result = Range.combine(result, r.findDomainBounds(d));\r\n }\r\n else {\r\n result = Range.combine(result,\r\n DatasetUtilities.findDomainBounds(d));\r\n }\r\n }\r\n else {\r\n if (r != null) {\r\n result = Range.combine(result, r.findRangeBounds(d));\r\n }\r\n else {\r\n result = Range.combine(result,\r\n DatasetUtilities.findRangeBounds(d));\r\n }\r\n }\r\n // FIXME: the XYItemRenderer interface doesn't specify the\r\n // getAnnotations() method but it should\r\n if (r instanceof AbstractXYItemRenderer) {\r\n AbstractXYItemRenderer rr = (AbstractXYItemRenderer) r;\r\n Collection c = rr.getAnnotations();\r\n Iterator i = c.iterator();\r\n while (i.hasNext()) {\r\n XYAnnotation a = (XYAnnotation) i.next();\r\n if (a instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(a);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n Iterator it = includedAnnotations.iterator();\r\n while (it.hasNext()) {\r\n XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next();\r\n if (xyabi.getIncludeInDataBounds()) {\r\n if (isDomainAxis) {\r\n result = Range.combine(result, xyabi.getXRange());\r\n }\r\n else {\r\n result = Range.combine(result, xyabi.getYRange());\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Receives notification of a change to an {@link Annotation} added to\r\n * this plot.\r\n *\r\n * @param event information about the event (not used here).\r\n *\r\n * @since 1.0.14\r\n */\r\n @Override\r\n public void annotationChanged(AnnotationChangeEvent event) {\r\n if (getParent() != null) {\r\n getParent().annotationChanged(event);\r\n }\r\n else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a change to the plot's dataset.\r\n * <P>\r\n * The axis ranges are updated if necessary.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void datasetChanged(DatasetChangeEvent event) {\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n if (getParent() != null) {\r\n getParent().datasetChanged(event);\r\n }\r\n else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n e.setType(ChartChangeEventType.DATASET_UPDATED);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a renderer change event.\r\n *\r\n * @param event the event.\r\n */\r\n @Override\r\n public void rendererChanged(RendererChangeEvent event) {\r\n // if the event was caused by a change to series visibility, then\r\n // the axis ranges might need updating...\r\n if (event.getSeriesVisibilityChanged()) {\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the domain crosshair is visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setDomainCrosshairVisible(boolean)\r\n */\r\n public boolean isDomainCrosshairVisible() {\r\n return this.domainCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the domain crosshair is visible\r\n * and, if the flag changes, sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isDomainCrosshairVisible()\r\n */\r\n public void setDomainCrosshairVisible(boolean flag) {\r\n if (this.domainCrosshairVisible != flag) {\r\n this.domainCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the crosshair should \"lock-on\"\r\n * to actual data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setDomainCrosshairLockedOnData(boolean)\r\n */\r\n public boolean isDomainCrosshairLockedOnData() {\r\n return this.domainCrosshairLockedOnData;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the domain crosshair should\r\n * \"lock-on\" to actual data values. If the flag value changes, this\r\n * method sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isDomainCrosshairLockedOnData()\r\n */\r\n public void setDomainCrosshairLockedOnData(boolean flag) {\r\n if (this.domainCrosshairLockedOnData != flag) {\r\n this.domainCrosshairLockedOnData = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the domain crosshair value.\r\n *\r\n * @return The value.\r\n *\r\n * @see #setDomainCrosshairValue(double)\r\n */\r\n public double getDomainCrosshairValue() {\r\n return this.domainCrosshairValue;\r\n }\r\n\r\n /**\r\n * Sets the domain crosshair value and sends a {@link PlotChangeEvent} to\r\n * all registered listeners (provided that the domain crosshair is visible).\r\n *\r\n * @param value the value.\r\n *\r\n * @see #getDomainCrosshairValue()\r\n */\r\n public void setDomainCrosshairValue(double value) {\r\n setDomainCrosshairValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the domain crosshair value and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners (provided that the\r\n * domain crosshair is visible).\r\n *\r\n * @param value the new value.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainCrosshairValue()\r\n */\r\n public void setDomainCrosshairValue(double value, boolean notify) {\r\n this.domainCrosshairValue = value;\r\n if (isDomainCrosshairVisible() && notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the {@link Stroke} used to draw the crosshair (if visible).\r\n *\r\n * @return The crosshair stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainCrosshairStroke(Stroke)\r\n * @see #isDomainCrosshairVisible()\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public Stroke getDomainCrosshairStroke() {\r\n return this.domainCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the Stroke used to draw the crosshairs (if visible) and notifies\r\n * registered listeners that the axis has been modified.\r\n *\r\n * @param stroke the new crosshair stroke (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public void setDomainCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainCrosshairStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the domain crosshair paint.\r\n *\r\n * @return The crosshair paint (never <code>null</code>).\r\n *\r\n * @see #setDomainCrosshairPaint(Paint)\r\n * @see #isDomainCrosshairVisible()\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public Paint getDomainCrosshairPaint() {\r\n return this.domainCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the new crosshair paint (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public void setDomainCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the range crosshair is visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairVisible(boolean)\r\n * @see #isDomainCrosshairVisible()\r\n */\r\n public boolean isRangeCrosshairVisible() {\r\n return this.rangeCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair is visible.\r\n * If the flag value changes, this method sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isRangeCrosshairVisible()\r\n */\r\n public void setRangeCrosshairVisible(boolean flag) {\r\n if (this.rangeCrosshairVisible != flag) {\r\n this.rangeCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the crosshair should \"lock-on\"\r\n * to actual data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairLockedOnData(boolean)\r\n */\r\n public boolean isRangeCrosshairLockedOnData() {\r\n return this.rangeCrosshairLockedOnData;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair should\r\n * \"lock-on\" to actual data values. If the flag value changes, this method\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isRangeCrosshairLockedOnData()\r\n */\r\n public void setRangeCrosshairLockedOnData(boolean flag) {\r\n if (this.rangeCrosshairLockedOnData != flag) {\r\n this.rangeCrosshairLockedOnData = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range crosshair value.\r\n *\r\n * @return The value.\r\n *\r\n * @see #setRangeCrosshairValue(double)\r\n */\r\n public double getRangeCrosshairValue() {\r\n return this.rangeCrosshairValue;\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value.\r\n * <P>\r\n * Registered listeners are notified that the plot has been modified, but\r\n * only if the crosshair is visible.\r\n *\r\n * @param value the new value.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value) {\r\n setRangeCrosshairValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value and sends a {@link PlotChangeEvent} to\r\n * all registered listeners, but only if the crosshair is visible.\r\n *\r\n * @param value the new value.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value, boolean notify) {\r\n this.rangeCrosshairValue = value;\r\n if (isRangeCrosshairVisible() && notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the crosshair (if visible).\r\n *\r\n * @return The crosshair stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairStroke(Stroke)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public Stroke getRangeCrosshairStroke() {\r\n return this.rangeCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the new crosshair stroke (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public void setRangeCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeCrosshairStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the range crosshair paint.\r\n *\r\n * @return The crosshair paint (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairPaint(Paint)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public Paint getRangeCrosshairPaint() {\r\n return this.rangeCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to color the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the new crosshair paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public void setRangeCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the fixed domain axis space.\r\n *\r\n * @return The fixed domain axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedDomainAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedDomainAxisSpace() {\r\n return this.fixedDomainAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space) {\r\n setFixedDomainAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n *\r\n * @since 1.0.9\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedDomainAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the fixed range axis space.\r\n *\r\n * @return The fixed range axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedRangeAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedRangeAxisSpace() {\r\n return this.fixedRangeAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space) {\r\n setFixedRangeAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n *\r\n * @since 1.0.9\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedRangeAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if panning is enabled for the domain axes,\r\n * and <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isDomainPannable() {\r\n return this.domainPannable;\r\n }\r\n\r\n /**\r\n * Sets the flag that enables or disables panning of the plot along the\r\n * domain axes.\r\n *\r\n * @param pannable the new flag value.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setDomainPannable(boolean pannable) {\r\n this.domainPannable = pannable;\r\n }\r\n\r\n /**\r\n * Returns {@code true} if panning is enabled for the range axis/axes,\r\n * and {@code false} otherwise. The default value is {@code false}.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isRangePannable() {\r\n return this.rangePannable;\r\n }\r\n\r\n /**\r\n * Sets the flag that enables or disables panning of the plot along\r\n * the range axis/axes.\r\n *\r\n * @param pannable the new flag value.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangePannable(boolean pannable) {\r\n this.rangePannable = pannable;\r\n }\r\n\r\n /**\r\n * Pans the domain axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panDomainAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n if (!isDomainPannable()) {\r\n return;\r\n }\r\n int domainAxisCount = getDomainAxisCount();\r\n for (int i = 0; i < domainAxisCount; i++) {\r\n ValueAxis axis = getDomainAxis(i);\r\n if (axis == null) {\r\n continue;\r\n }\r\n if (axis.isInverted()) {\r\n percent = -percent;\r\n }\r\n axis.pan(percent);\r\n }\r\n }\r\n\r\n /**\r\n * Pans the range axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panRangeAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n if (!isRangePannable()) {\r\n return;\r\n }\r\n int rangeAxisCount = getRangeAxisCount();\r\n for (int i = 0; i < rangeAxisCount; i++) {\r\n ValueAxis axis = getRangeAxis(i);\r\n if (axis == null) {\r\n continue;\r\n }\r\n if (axis.isInverted()) {\r\n percent = -percent;\r\n }\r\n axis.pan(percent);\r\n }\r\n }\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point (in Java2D space).\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo info,\r\n Point2D source) {\r\n // delegate to other method\r\n zoomDomainAxes(factor, info, source, false);\r\n }\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point (in Java2D space).\r\n * @param useAnchor use source point as zoom anchor?\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n\r\n // perform the zoom on each domain axis\r\n for (ValueAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis == null) {\r\n continue;\r\n }\r\n if (useAnchor) {\r\n // get the relevant source coordinate given the plot orientation\r\n double sourceX = source.getX();\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n sourceX = source.getY();\r\n }\r\n double anchorX = xAxis.java2DToValue(sourceX,\r\n info.getDataArea(), getDomainAxisEdge());\r\n xAxis.resizeRange2(factor, anchorX);\r\n } else {\r\n xAxis.resizeRange(factor);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the domain axis/axes. The new lower and upper bounds are\r\n * specified as percentages of the current axis range, where 0 percent is\r\n * the current lower bound and 100 percent is the current upper bound.\r\n *\r\n * @param lowerPercent a percentage that determines the new lower bound\r\n * for the axis (e.g. 0.20 is twenty percent).\r\n * @param upperPercent a percentage that determines the new upper bound\r\n * for the axis (e.g. 0.80 is eighty percent).\r\n * @param info the plot rendering info.\r\n * @param source the source point (ignored).\r\n *\r\n * @see #zoomRangeAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomDomainAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo info, Point2D source) {\r\n for (ValueAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n xAxis.zoomRange(lowerPercent, upperPercent);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo info,\r\n Point2D source) {\r\n // delegate to other method\r\n zoomRangeAxes(factor, info, source, false);\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n * @param useAnchor a flag that controls whether or not the source point\r\n * is used for the zoom anchor.\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n\r\n // perform the zoom on each range axis\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis == null) {\r\n continue;\r\n }\r\n if (useAnchor) {\r\n // get the relevant source coordinate given the plot orientation\r\n double sourceY = source.getY();\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n sourceY = source.getX();\r\n }\r\n double anchorY = yAxis.java2DToValue(sourceY,\r\n info.getDataArea(), getRangeAxisEdge());\r\n yAxis.resizeRange2(factor, anchorY);\r\n } else {\r\n yAxis.resizeRange(factor);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the range axes.\r\n *\r\n * @param lowerPercent the lower bound.\r\n * @param upperPercent the upper bound.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n *\r\n * @see #zoomDomainAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomRangeAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo info, Point2D source) {\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.zoomRange(lowerPercent, upperPercent);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code>, indicating that the domain axis/axes for this\r\n * plot are zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isRangeZoomable()\r\n */\r\n @Override\r\n public boolean isDomainZoomable() {\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code>, indicating that the range axis/axes for this\r\n * plot are zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isDomainZoomable()\r\n */\r\n @Override\r\n public boolean isRangeZoomable() {\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns the number of series in the primary dataset for this plot. If\r\n * the dataset is <code>null</code>, the method returns 0.\r\n *\r\n * @return The series count.\r\n */\r\n public int getSeriesCount() {\r\n int result = 0;\r\n XYDataset dataset = getDataset();\r\n if (dataset != null) {\r\n result = dataset.getSeriesCount();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the fixed legend items, if any.\r\n *\r\n * @return The legend items (possibly <code>null</code>).\r\n *\r\n * @see #setFixedLegendItems(LegendItemCollection)\r\n */\r\n public LegendItemCollection getFixedLegendItems() {\r\n return this.fixedLegendItems;\r\n }\r\n\r\n /**\r\n * Sets the fixed legend items for the plot. Leave this set to\r\n * <code>null</code> if you prefer the legend items to be created\r\n * automatically.\r\n *\r\n * @param items the legend items (<code>null</code> permitted).\r\n *\r\n * @see #getFixedLegendItems()\r\n */\r\n public void setFixedLegendItems(LegendItemCollection items) {\r\n this.fixedLegendItems = items;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the legend items for the plot. Each legend item is generated by\r\n * the plot's renderer, since the renderer is responsible for the visual\r\n * representation of the data.\r\n *\r\n * @return The legend items.\r\n */\r\n @Override\r\n public LegendItemCollection getLegendItems() {\r\n if (this.fixedLegendItems != null) {\r\n return this.fixedLegendItems;\r\n }\r\n LegendItemCollection result = new LegendItemCollection();\r\n for (XYDataset dataset : this.datasets.values()) {\r\n if (dataset == null) {\r\n continue;\r\n }\r\n int datasetIndex = indexOf(dataset);\r\n XYItemRenderer renderer = getRenderer(datasetIndex);\r\n if (renderer == null) {\r\n renderer = getRenderer(0);\r\n }\r\n if (renderer != null) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int i = 0; i < seriesCount; i++) {\r\n if (renderer.isSeriesVisible(i)\r\n && renderer.isSeriesVisibleInLegend(i)) {\r\n LegendItem item = renderer.getLegendItem(\r\n datasetIndex, i);\r\n if (item != null) {\r\n result.add(item);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Tests this plot for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof XYPlot)) {\r\n return false;\r\n }\r\n XYPlot that = (XYPlot) obj;\r\n if (this.weight != that.weight) {\r\n return false;\r\n }\r\n if (this.orientation != that.orientation) {\r\n return false;\r\n }\r\n if (!this.domainAxes.equals(that.domainAxes)) {\r\n return false;\r\n }\r\n if (!this.domainAxisLocations.equals(that.domainAxisLocations)) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairLockedOnData\r\n != that.rangeCrosshairLockedOnData) {\r\n return false;\r\n }\r\n if (this.domainGridlinesVisible != that.domainGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.rangeGridlinesVisible != that.rangeGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.domainMinorGridlinesVisible\r\n != that.domainMinorGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.rangeMinorGridlinesVisible\r\n != that.rangeMinorGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.domainZeroBaselineVisible != that.domainZeroBaselineVisible) {\r\n return false;\r\n }\r\n if (this.rangeZeroBaselineVisible != that.rangeZeroBaselineVisible) {\r\n return false;\r\n }\r\n if (this.domainCrosshairVisible != that.domainCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.domainCrosshairValue != that.domainCrosshairValue) {\r\n return false;\r\n }\r\n if (this.domainCrosshairLockedOnData\r\n != that.domainCrosshairLockedOnData) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairVisible != that.rangeCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairValue != that.rangeCrosshairValue) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.axisOffset, that.axisOffset)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.renderers, that.renderers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeAxes, that.rangeAxes)) {\r\n return false;\r\n }\r\n if (!this.rangeAxisLocations.equals(that.rangeAxisLocations)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToDomainAxesMap,\r\n that.datasetToDomainAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToRangeAxesMap,\r\n that.datasetToRangeAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainGridlineStroke,\r\n that.domainGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainGridlinePaint,\r\n that.domainGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeGridlineStroke,\r\n that.rangeGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeGridlinePaint,\r\n that.rangeGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainMinorGridlineStroke,\r\n that.domainMinorGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainMinorGridlinePaint,\r\n that.domainMinorGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeMinorGridlineStroke,\r\n that.rangeMinorGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeMinorGridlinePaint,\r\n that.rangeMinorGridlinePaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainZeroBaselinePaint,\r\n that.domainZeroBaselinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainZeroBaselineStroke,\r\n that.domainZeroBaselineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeZeroBaselinePaint,\r\n that.rangeZeroBaselinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeZeroBaselineStroke,\r\n that.rangeZeroBaselineStroke)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainCrosshairStroke,\r\n that.domainCrosshairStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainCrosshairPaint,\r\n that.domainCrosshairPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeCrosshairStroke,\r\n that.rangeCrosshairStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeCrosshairPaint,\r\n that.rangeCrosshairPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundDomainMarkers,\r\n that.foregroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundDomainMarkers,\r\n that.backgroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundRangeMarkers,\r\n that.foregroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundRangeMarkers,\r\n that.backgroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundDomainMarkers,\r\n that.foregroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundDomainMarkers,\r\n that.backgroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundRangeMarkers,\r\n that.foregroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundRangeMarkers,\r\n that.backgroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.annotations, that.annotations)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.fixedLegendItems,\r\n that.fixedLegendItems)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainTickBandPaint,\r\n that.domainTickBandPaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeTickBandPaint,\r\n that.rangeTickBandPaint)) {\r\n return false;\r\n }\r\n if (!this.quadrantOrigin.equals(that.quadrantOrigin)) {\r\n return false;\r\n }\r\n for (int i = 0; i < 4; i++) {\r\n if (!PaintUtilities.equal(this.quadrantPaint[i],\r\n that.quadrantPaint[i])) {\r\n return false;\r\n }\r\n }\r\n if (!ObjectUtilities.equal(this.shadowGenerator,\r\n that.shadowGenerator)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a clone of the plot.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException this can occur if some component of\r\n * the plot cannot be cloned.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n XYPlot clone = (XYPlot) super.clone();\r\n clone.domainAxes = CloneUtils.cloneMapValues(this.domainAxes);\r\n for (ValueAxis axis : clone.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n clone.rangeAxes = CloneUtils.cloneMapValues(this.rangeAxes);\r\n for (ValueAxis axis : clone.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n clone.domainAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.domainAxisLocations);\r\n clone.rangeAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.rangeAxisLocations);\r\n\r\n // the datasets are not cloned, but listeners need to be added...\r\n clone.datasets = new HashMap<Integer, XYDataset>(this.datasets);\r\n for (XYDataset dataset : clone.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(clone);\r\n }\r\n }\r\n\r\n clone.datasetToDomainAxesMap = new TreeMap();\r\n clone.datasetToDomainAxesMap.putAll(this.datasetToDomainAxesMap);\r\n clone.datasetToRangeAxesMap = new TreeMap();\r\n clone.datasetToRangeAxesMap.putAll(this.datasetToRangeAxesMap);\r\n\r\n clone.renderers = CloneUtils.cloneMapValues(this.renderers);\r\n for (XYItemRenderer renderer : clone.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.setPlot(clone);\r\n renderer.addChangeListener(clone);\r\n }\r\n }\r\n clone.foregroundDomainMarkers = (Map) ObjectUtilities.clone(\r\n this.foregroundDomainMarkers);\r\n clone.backgroundDomainMarkers = (Map) ObjectUtilities.clone(\r\n this.backgroundDomainMarkers);\r\n clone.foregroundRangeMarkers = (Map) ObjectUtilities.clone(\r\n this.foregroundRangeMarkers);\r\n clone.backgroundRangeMarkers = (Map) ObjectUtilities.clone(\r\n this.backgroundRangeMarkers);\r\n clone.annotations = (List) ObjectUtilities.deepClone(this.annotations);\r\n if (this.fixedDomainAxisSpace != null) {\r\n clone.fixedDomainAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedDomainAxisSpace);\r\n }\r\n if (this.fixedRangeAxisSpace != null) {\r\n clone.fixedRangeAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedRangeAxisSpace);\r\n }\r\n if (this.fixedLegendItems != null) {\r\n clone.fixedLegendItems\r\n = (LegendItemCollection) this.fixedLegendItems.clone();\r\n }\r\n clone.quadrantOrigin = (Point2D) ObjectUtilities.clone(\r\n this.quadrantOrigin);\r\n clone.quadrantPaint = this.quadrantPaint.clone();\r\n return clone;\r\n\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.domainGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.domainGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.domainMinorGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.domainMinorGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeMinorGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeMinorGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeZeroBaselineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeZeroBaselinePaint, stream);\r\n SerialUtilities.writeStroke(this.domainCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.domainCrosshairPaint, stream);\r\n SerialUtilities.writeStroke(this.rangeCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.rangeCrosshairPaint, stream);\r\n SerialUtilities.writePaint(this.domainTickBandPaint, stream);\r\n SerialUtilities.writePaint(this.rangeTickBandPaint, stream);\r\n SerialUtilities.writePoint2D(this.quadrantOrigin, stream);\r\n for (int i = 0; i < 4; i++) {\r\n SerialUtilities.writePaint(this.quadrantPaint[i], stream);\r\n }\r\n SerialUtilities.writeStroke(this.domainZeroBaselineStroke, stream);\r\n SerialUtilities.writePaint(this.domainZeroBaselinePaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n\r\n stream.defaultReadObject();\r\n this.domainGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.domainGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.domainMinorGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.domainMinorGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeMinorGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeMinorGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeZeroBaselineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeZeroBaselinePaint = SerialUtilities.readPaint(stream);\r\n this.domainCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.domainCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.rangeCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.rangeCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.domainTickBandPaint = SerialUtilities.readPaint(stream);\r\n this.rangeTickBandPaint = SerialUtilities.readPaint(stream);\r\n this.quadrantOrigin = SerialUtilities.readPoint2D(stream);\r\n this.quadrantPaint = new Paint[4];\r\n for (int i = 0; i < 4; i++) {\r\n this.quadrantPaint[i] = SerialUtilities.readPaint(stream);\r\n }\r\n\r\n this.domainZeroBaselineStroke = SerialUtilities.readStroke(stream);\r\n this.domainZeroBaselinePaint = SerialUtilities.readPaint(stream);\r\n\r\n // register the plot as a listener with its axes, datasets, and\r\n // renderers...\r\n for (ValueAxis axis : this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n axis.addChangeListener(this);\r\n }\r\n }\r\n for (ValueAxis axis : this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n axis.addChangeListener(this);\r\n }\r\n }\r\n for (XYDataset dataset : this.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n }\r\n for (XYItemRenderer renderer : this.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.addChangeListener(this);\r\n }\r\n }\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "DefaultTableXYDataset", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/xy/DefaultTableXYDataset.java", "snippet": "public class DefaultTableXYDataset extends AbstractIntervalXYDataset\r\n implements TableXYDataset, IntervalXYDataset, DomainInfo,\r\n PublicCloneable {\r\n\r\n /**\r\n * Storage for the data - this list will contain zero, one or many\r\n * XYSeries objects.\r\n */\r\n private List data = null;\r\n\r\n /** Storage for the x values. */\r\n private HashSet xPoints = null;\r\n\r\n /** A flag that controls whether or not events are propogated. */\r\n private boolean propagateEvents = true;\r\n\r\n /** A flag that controls auto pruning. */\r\n private boolean autoPrune = false;\r\n\r\n /** The delegate used to control the interval width. */\r\n private IntervalXYDelegate intervalDelegate;\r\n\r\n /**\r\n * Creates a new empty dataset.\r\n */\r\n public DefaultTableXYDataset() {\r\n this(false);\r\n }\r\n\r\n /**\r\n * Creates a new empty dataset.\r\n *\r\n * @param autoPrune a flag that controls whether or not x-values are\r\n * removed whenever the corresponding y-values are all\r\n * <code>null</code>.\r\n */\r\n public DefaultTableXYDataset(boolean autoPrune) {\r\n this.autoPrune = autoPrune;\r\n this.data = new ArrayList();\r\n this.xPoints = new HashSet();\r\n this.intervalDelegate = new IntervalXYDelegate(this, false);\r\n addChangeListener(this.intervalDelegate);\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not x-values are removed from\r\n * the dataset when the corresponding y-values are all <code>null</code>.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean isAutoPrune() {\r\n return this.autoPrune;\r\n }\r\n\r\n /**\r\n * Adds a series to the collection and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners. The series should be configured to NOT\r\n * allow duplicate x-values.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n */\r\n public void addSeries(XYSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n if (series.getAllowDuplicateXValues()) {\r\n throw new IllegalArgumentException(\r\n \"Cannot accept XYSeries that allow duplicate values. \"\r\n + \"Use XYSeries(seriesName, <sort>, false) constructor.\"\r\n );\r\n }\r\n updateXPoints(series);\r\n this.data.add(series);\r\n series.addChangeListener(this);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Adds any unique x-values from 'series' to the dataset, and also adds any\r\n * x-values that are in the dataset but not in 'series' to the series.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n */\r\n private void updateXPoints(XYSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n HashSet seriesXPoints = new HashSet();\r\n boolean savedState = this.propagateEvents;\r\n this.propagateEvents = false;\r\n for (int itemNo = 0; itemNo < series.getItemCount(); itemNo++) {\r\n Number xValue = series.getX(itemNo);\r\n seriesXPoints.add(xValue);\r\n if (!this.xPoints.contains(xValue)) {\r\n this.xPoints.add(xValue);\r\n int seriesCount = this.data.size();\r\n for (int seriesNo = 0; seriesNo < seriesCount; seriesNo++) {\r\n XYSeries dataSeries = (XYSeries) this.data.get(seriesNo);\r\n if (!dataSeries.equals(series)) {\r\n dataSeries.add(xValue, null);\r\n }\r\n }\r\n }\r\n }\r\n Iterator iterator = this.xPoints.iterator();\r\n while (iterator.hasNext()) {\r\n Number xPoint = (Number) iterator.next();\r\n if (!seriesXPoints.contains(xPoint)) {\r\n series.add(xPoint, null);\r\n }\r\n }\r\n this.propagateEvents = savedState;\r\n }\r\n\r\n /**\r\n * Updates the x-values for all the series in the dataset.\r\n */\r\n public void updateXPoints() {\r\n this.propagateEvents = false;\r\n for (int s = 0; s < this.data.size(); s++) {\r\n updateXPoints((XYSeries) this.data.get(s));\r\n }\r\n if (this.autoPrune) {\r\n prune();\r\n }\r\n this.propagateEvents = true;\r\n }\r\n\r\n /**\r\n * Returns the number of series in the collection.\r\n *\r\n * @return The series count.\r\n */\r\n @Override\r\n public int getSeriesCount() {\r\n return this.data.size();\r\n }\r\n\r\n /**\r\n * Returns the number of x values in the dataset.\r\n *\r\n * @return The number of x values in the dataset.\r\n */\r\n @Override\r\n public int getItemCount() {\r\n if (this.xPoints == null) {\r\n return 0;\r\n }\r\n else {\r\n return this.xPoints.size();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a series.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The series (never <code>null</code>).\r\n */\r\n public XYSeries getSeries(int series) {\r\n if ((series < 0) || (series >= getSeriesCount())) {\r\n throw new IllegalArgumentException(\"Index outside valid range.\");\r\n }\r\n return (XYSeries) this.data.get(series);\r\n }\r\n\r\n /**\r\n * Returns the key for a series.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The key for a series.\r\n */\r\n @Override\r\n public Comparable getSeriesKey(int series) {\r\n // check arguments...delegated\r\n return getSeries(series).getKey();\r\n }\r\n\r\n /**\r\n * Returns the number of items in the specified series.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The number of items in the specified series.\r\n */\r\n @Override\r\n public int getItemCount(int series) {\r\n // check arguments...delegated\r\n return getSeries(series).getItemCount();\r\n }\r\n\r\n /**\r\n * Returns the x-value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The x-value for the specified series and item.\r\n */\r\n @Override\r\n public Number getX(int series, int item) {\r\n XYSeries s = (XYSeries) this.data.get(series);\r\n return s.getX(item);\r\n\r\n }\r\n\r\n /**\r\n * Returns the starting X value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The starting X value.\r\n */\r\n @Override\r\n public Number getStartX(int series, int item) {\r\n return this.intervalDelegate.getStartX(series, item);\r\n }\r\n\r\n /**\r\n * Returns the ending X value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The ending X value.\r\n */\r\n @Override\r\n public Number getEndX(int series, int item) {\r\n return this.intervalDelegate.getEndX(series, item);\r\n }\r\n\r\n /**\r\n * Returns the y-value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param index the index of the item of interest (zero-based).\r\n *\r\n * @return The y-value for the specified series and item (possibly\r\n * <code>null</code>).\r\n */\r\n @Override\r\n public Number getY(int series, int index) {\r\n XYSeries s = (XYSeries) this.data.get(series);\r\n return s.getY(index);\r\n }\r\n\r\n /**\r\n * Returns the starting Y value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The starting Y value.\r\n */\r\n @Override\r\n public Number getStartY(int series, int item) {\r\n return getY(series, item);\r\n }\r\n\r\n /**\r\n * Returns the ending Y value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The ending Y value.\r\n */\r\n @Override\r\n public Number getEndY(int series, int item) {\r\n return getY(series, item);\r\n }\r\n\r\n /**\r\n * Removes all the series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n */\r\n public void removeAllSeries() {\r\n\r\n // Unregister the collection as a change listener to each series in\r\n // the collection.\r\n for (int i = 0; i < this.data.size(); i++) {\r\n XYSeries series = (XYSeries) this.data.get(i);\r\n series.removeChangeListener(this);\r\n }\r\n\r\n // Remove all the series from the collection and notify listeners.\r\n this.data.clear();\r\n this.xPoints.clear();\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes a series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n */\r\n public void removeSeries(XYSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n if (this.data.contains(series)) {\r\n series.removeChangeListener(this);\r\n this.data.remove(series);\r\n if (this.data.isEmpty()) {\r\n this.xPoints.clear();\r\n }\r\n fireDatasetChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Removes a series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series (zero based index).\r\n */\r\n public void removeSeries(int series) {\r\n\r\n // check arguments...\r\n if ((series < 0) || (series > getSeriesCount())) {\r\n throw new IllegalArgumentException(\"Index outside valid range.\");\r\n }\r\n\r\n // fetch the series, remove the change listener, then remove the series.\r\n XYSeries s = (XYSeries) this.data.get(series);\r\n s.removeChangeListener(this);\r\n this.data.remove(series);\r\n if (this.data.isEmpty()) {\r\n this.xPoints.clear();\r\n }\r\n else if (this.autoPrune) {\r\n prune();\r\n }\r\n fireDatasetChanged();\r\n\r\n }\r\n\r\n /**\r\n * Removes the items from all series for a given x value.\r\n *\r\n * @param x the x-value.\r\n */\r\n public void removeAllValuesForX(Number x) {\r\n ParamChecks.nullNotPermitted(x, \"x\");\r\n boolean savedState = this.propagateEvents;\r\n this.propagateEvents = false;\r\n for (int s = 0; s < this.data.size(); s++) {\r\n XYSeries series = (XYSeries) this.data.get(s);\r\n series.remove(x);\r\n }\r\n this.propagateEvents = savedState;\r\n this.xPoints.remove(x);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if all the y-values for the specified x-value\r\n * are <code>null</code> and <code>false</code> otherwise.\r\n *\r\n * @param x the x-value.\r\n *\r\n * @return A boolean.\r\n */\r\n protected boolean canPrune(Number x) {\r\n for (int s = 0; s < this.data.size(); s++) {\r\n XYSeries series = (XYSeries) this.data.get(s);\r\n if (series.getY(series.indexOf(x)) != null) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Removes all x-values for which all the y-values are <code>null</code>.\r\n */\r\n public void prune() {\r\n HashSet hs = (HashSet) this.xPoints.clone();\r\n Iterator iterator = hs.iterator();\r\n while (iterator.hasNext()) {\r\n Number x = (Number) iterator.next();\r\n if (canPrune(x)) {\r\n removeAllValuesForX(x);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * This method receives notification when a series belonging to the dataset\r\n * changes. It responds by updating the x-points for the entire dataset\r\n * and sending a {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param event information about the change.\r\n */\r\n @Override\r\n public void seriesChanged(SeriesChangeEvent event) {\r\n if (this.propagateEvents) {\r\n updateXPoints();\r\n fireDatasetChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Tests this collection for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof DefaultTableXYDataset)) {\r\n return false;\r\n }\r\n DefaultTableXYDataset that = (DefaultTableXYDataset) obj;\r\n if (this.autoPrune != that.autoPrune) {\r\n return false;\r\n }\r\n if (this.propagateEvents != that.propagateEvents) {\r\n return false;\r\n }\r\n if (!this.intervalDelegate.equals(that.intervalDelegate)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.data, that.data)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result;\r\n result = (this.data != null ? this.data.hashCode() : 0);\r\n result = 29 * result\r\n + (this.xPoints != null ? this.xPoints.hashCode() : 0);\r\n result = 29 * result + (this.propagateEvents ? 1 : 0);\r\n result = 29 * result + (this.autoPrune ? 1 : 0);\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns an independent copy of this dataset.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if there is some reason that cloning\r\n * cannot be performed.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n DefaultTableXYDataset clone = (DefaultTableXYDataset) super.clone();\r\n int seriesCount = this.data.size();\r\n clone.data = new java.util.ArrayList(seriesCount);\r\n for (int i = 0; i < seriesCount; i++) {\r\n XYSeries series = (XYSeries) this.data.get(i);\r\n clone.data.add(series.clone());\r\n }\r\n\r\n clone.intervalDelegate = new IntervalXYDelegate(clone);\r\n // need to configure the intervalDelegate to match the original\r\n clone.intervalDelegate.setFixedIntervalWidth(getIntervalWidth());\r\n clone.intervalDelegate.setAutoWidth(isAutoWidth());\r\n clone.intervalDelegate.setIntervalPositionFactor(\r\n getIntervalPositionFactor());\r\n clone.updateXPoints();\r\n return clone;\r\n }\r\n\r\n /**\r\n * Returns the minimum x-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The minimum value.\r\n */\r\n @Override\r\n public double getDomainLowerBound(boolean includeInterval) {\r\n return this.intervalDelegate.getDomainLowerBound(includeInterval);\r\n }\r\n\r\n /**\r\n * Returns the maximum x-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The maximum value.\r\n */\r\n @Override\r\n public double getDomainUpperBound(boolean includeInterval) {\r\n return this.intervalDelegate.getDomainUpperBound(includeInterval);\r\n }\r\n\r\n /**\r\n * Returns the range of the values in this dataset's domain.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The range.\r\n */\r\n @Override\r\n public Range getDomainBounds(boolean includeInterval) {\r\n if (includeInterval) {\r\n return this.intervalDelegate.getDomainBounds(includeInterval);\r\n }\r\n else {\r\n return DatasetUtilities.iterateDomainBounds(this, includeInterval);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the interval position factor.\r\n *\r\n * @return The interval position factor.\r\n */\r\n public double getIntervalPositionFactor() {\r\n return this.intervalDelegate.getIntervalPositionFactor();\r\n }\r\n\r\n /**\r\n * Sets the interval position factor. Must be between 0.0 and 1.0 inclusive.\r\n * If the factor is 0.5, the gap is in the middle of the x values. If it\r\n * is lesser than 0.5, the gap is farther to the left and if greater than\r\n * 0.5 it gets farther to the right.\r\n *\r\n * @param d the new interval position factor.\r\n */\r\n public void setIntervalPositionFactor(double d) {\r\n this.intervalDelegate.setIntervalPositionFactor(d);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * returns the full interval width.\r\n *\r\n * @return The interval width to use.\r\n */\r\n public double getIntervalWidth() {\r\n return this.intervalDelegate.getIntervalWidth();\r\n }\r\n\r\n /**\r\n * Sets the interval width to a fixed value, and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param d the new interval width (must be &gt; 0).\r\n */\r\n public void setIntervalWidth(double d) {\r\n this.intervalDelegate.setFixedIntervalWidth(d);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns whether the interval width is automatically calculated or not.\r\n *\r\n * @return A flag that determines whether or not the interval width is\r\n * automatically calculated.\r\n */\r\n public boolean isAutoWidth() {\r\n return this.intervalDelegate.isAutoWidth();\r\n }\r\n\r\n /**\r\n * Sets the flag that indicates whether the interval width is automatically\r\n * calculated or not.\r\n *\r\n * @param b a boolean.\r\n */\r\n public void setAutoWidth(boolean b) {\r\n this.intervalDelegate.setAutoWidth(b);\r\n fireDatasetChanged();\r\n }\r\n\r\n}\r" }, { "identifier": "XYSeries", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/xy/XYSeries.java", "snippet": "public class XYSeries extends Series implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n static final long serialVersionUID = -5908509288197150436L;\r\n\r\n // In version 0.9.12, in response to several developer requests, I changed\r\n // the 'data' attribute from 'private' to 'protected', so that others can\r\n // make subclasses that work directly with the underlying data structure.\r\n\r\n /** Storage for the data items in the series. */\r\n protected List data;\r\n\r\n /** The maximum number of items for the series. */\r\n private int maximumItemCount = Integer.MAX_VALUE;\r\n\r\n /**\r\n * A flag that controls whether the items are automatically sorted\r\n * (by x-value ascending).\r\n */\r\n private boolean autoSort;\r\n\r\n /** A flag that controls whether or not duplicate x-values are allowed. */\r\n private boolean allowDuplicateXValues;\r\n\r\n /** The lowest x-value in the series, excluding Double.NaN values. */\r\n private double minX;\r\n\r\n /** The highest x-value in the series, excluding Double.NaN values. */\r\n private double maxX;\r\n\r\n /** The lowest y-value in the series, excluding Double.NaN values. */\r\n private double minY;\r\n\r\n /** The highest y-value in the series, excluding Double.NaN values. */\r\n private double maxY;\r\n\r\n /**\r\n * Creates a new empty series. By default, items added to the series will\r\n * be sorted into ascending order by x-value, and duplicate x-values will\r\n * be allowed (these defaults can be modified with another constructor).\r\n *\r\n * @param key the series key (<code>null</code> not permitted).\r\n */\r\n public XYSeries(Comparable key) {\r\n this(key, true, true);\r\n }\r\n\r\n /**\r\n * Constructs a new empty series, with the auto-sort flag set as requested,\r\n * and duplicate values allowed.\r\n *\r\n * @param key the series key (<code>null</code> not permitted).\r\n * @param autoSort a flag that controls whether or not the items in the\r\n * series are sorted.\r\n */\r\n public XYSeries(Comparable key, boolean autoSort) {\r\n this(key, autoSort, true);\r\n }\r\n\r\n /**\r\n * Constructs a new xy-series that contains no data. You can specify\r\n * whether or not duplicate x-values are allowed for the series.\r\n *\r\n * @param key the series key (<code>null</code> not permitted).\r\n * @param autoSort a flag that controls whether or not the items in the\r\n * series are sorted.\r\n * @param allowDuplicateXValues a flag that controls whether duplicate\r\n * x-values are allowed.\r\n */\r\n public XYSeries(Comparable key, boolean autoSort,\r\n boolean allowDuplicateXValues) {\r\n super(key);\r\n this.data = new java.util.ArrayList();\r\n this.autoSort = autoSort;\r\n this.allowDuplicateXValues = allowDuplicateXValues;\r\n this.minX = Double.NaN;\r\n this.maxX = Double.NaN;\r\n this.minY = Double.NaN;\r\n this.maxY = Double.NaN;\r\n }\r\n\r\n /**\r\n * Returns the smallest x-value in the series, ignoring any Double.NaN\r\n * values. This method returns Double.NaN if there is no smallest x-value\r\n * (for example, when the series is empty).\r\n *\r\n * @return The smallest x-value.\r\n *\r\n * @see #getMaxX()\r\n *\r\n * @since 1.0.13\r\n */\r\n public double getMinX() {\r\n return this.minX;\r\n }\r\n\r\n /**\r\n * Returns the largest x-value in the series, ignoring any Double.NaN\r\n * values. This method returns Double.NaN if there is no largest x-value\r\n * (for example, when the series is empty).\r\n *\r\n * @return The largest x-value.\r\n *\r\n * @see #getMinX()\r\n *\r\n * @since 1.0.13\r\n */\r\n public double getMaxX() {\r\n return this.maxX;\r\n }\r\n\r\n /**\r\n * Returns the smallest y-value in the series, ignoring any null and\r\n * Double.NaN values. This method returns Double.NaN if there is no\r\n * smallest y-value (for example, when the series is empty).\r\n *\r\n * @return The smallest y-value.\r\n *\r\n * @see #getMaxY()\r\n *\r\n * @since 1.0.13\r\n */\r\n public double getMinY() {\r\n return this.minY;\r\n }\r\n\r\n /**\r\n * Returns the largest y-value in the series, ignoring any Double.NaN\r\n * values. This method returns Double.NaN if there is no largest y-value\r\n * (for example, when the series is empty).\r\n *\r\n * @return The largest y-value.\r\n *\r\n * @see #getMinY()\r\n *\r\n * @since 1.0.13\r\n */\r\n public double getMaxY() {\r\n return this.maxY;\r\n }\r\n\r\n /**\r\n * Updates the cached values for the minimum and maximum data values.\r\n *\r\n * @param item the item added (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.13\r\n */\r\n private void updateBoundsForAddedItem(XYDataItem item) {\r\n double x = item.getXValue();\r\n this.minX = minIgnoreNaN(this.minX, x);\r\n this.maxX = maxIgnoreNaN(this.maxX, x);\r\n if (item.getY() != null) {\r\n double y = item.getYValue();\r\n this.minY = minIgnoreNaN(this.minY, y);\r\n this.maxY = maxIgnoreNaN(this.maxY, y);\r\n }\r\n }\r\n\r\n /**\r\n * Updates the cached values for the minimum and maximum data values on\r\n * the basis that the specified item has just been removed.\r\n *\r\n * @param item the item added (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.13\r\n */\r\n private void updateBoundsForRemovedItem(XYDataItem item) {\r\n boolean itemContributesToXBounds = false;\r\n boolean itemContributesToYBounds = false;\r\n double x = item.getXValue();\r\n if (!Double.isNaN(x)) {\r\n if (x <= this.minX || x >= this.maxX) {\r\n itemContributesToXBounds = true;\r\n }\r\n }\r\n if (item.getY() != null) {\r\n double y = item.getYValue();\r\n if (!Double.isNaN(y)) {\r\n if (y <= this.minY || y >= this.maxY) {\r\n itemContributesToYBounds = true;\r\n }\r\n }\r\n }\r\n if (itemContributesToYBounds) {\r\n findBoundsByIteration();\r\n }\r\n else if (itemContributesToXBounds) {\r\n if (getAutoSort()) {\r\n this.minX = getX(0).doubleValue();\r\n this.maxX = getX(getItemCount() - 1).doubleValue();\r\n }\r\n else {\r\n findBoundsByIteration();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Finds the bounds of the x and y values for the series, by iterating\r\n * through all the data items.\r\n *\r\n * @since 1.0.13\r\n */\r\n private void findBoundsByIteration() {\r\n this.minX = Double.NaN;\r\n this.maxX = Double.NaN;\r\n this.minY = Double.NaN;\r\n this.maxY = Double.NaN;\r\n Iterator iterator = this.data.iterator();\r\n while (iterator.hasNext()) {\r\n XYDataItem item = (XYDataItem) iterator.next();\r\n updateBoundsForAddedItem(item);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether the items in the series are\r\n * automatically sorted. There is no setter for this flag, it must be\r\n * defined in the series constructor.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean getAutoSort() {\r\n return this.autoSort;\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether duplicate x-values are allowed.\r\n * This flag can only be set in the constructor.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean getAllowDuplicateXValues() {\r\n return this.allowDuplicateXValues;\r\n }\r\n\r\n /**\r\n * Returns the number of items in the series.\r\n *\r\n * @return The item count.\r\n *\r\n * @see #getItems()\r\n */\r\n @Override\r\n public int getItemCount() {\r\n return this.data.size();\r\n }\r\n\r\n /**\r\n * Returns the list of data items for the series (the list contains\r\n * {@link XYDataItem} objects and is unmodifiable).\r\n *\r\n * @return The list of data items.\r\n */\r\n public List getItems() {\r\n return Collections.unmodifiableList(this.data);\r\n }\r\n\r\n /**\r\n * Returns the maximum number of items that will be retained in the series.\r\n * The default value is <code>Integer.MAX_VALUE</code>.\r\n *\r\n * @return The maximum item count.\r\n *\r\n * @see #setMaximumItemCount(int)\r\n */\r\n public int getMaximumItemCount() {\r\n return this.maximumItemCount;\r\n }\r\n\r\n /**\r\n * Sets the maximum number of items that will be retained in the series.\r\n * If you add a new item to the series such that the number of items will\r\n * exceed the maximum item count, then the first element in the series is\r\n * automatically removed, ensuring that the maximum item count is not\r\n * exceeded.\r\n * <p>\r\n * Typically this value is set before the series is populated with data,\r\n * but if it is applied later, it may cause some items to be removed from\r\n * the series (in which case a {@link SeriesChangeEvent} will be sent to\r\n * all registered listeners).\r\n *\r\n * @param maximum the maximum number of items for the series.\r\n */\r\n public void setMaximumItemCount(int maximum) {\r\n this.maximumItemCount = maximum;\r\n int remove = this.data.size() - maximum;\r\n if (remove > 0) {\r\n this.data.subList(0, remove).clear();\r\n findBoundsByIteration();\r\n fireSeriesChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and sends a {@link SeriesChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param item the (x, y) item (<code>null</code> not permitted).\r\n */\r\n public void add(XYDataItem item) {\r\n // argument checking delegated...\r\n add(item, true);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and sends a {@link SeriesChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param x the x value.\r\n * @param y the y value.\r\n */\r\n public void add(double x, double y) {\r\n add(new Double(x), new Double(y), true);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and, if requested, sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param x the x value.\r\n * @param y the y value.\r\n * @param notify a flag that controls whether or not a\r\n * {@link SeriesChangeEvent} is sent to all registered\r\n * listeners.\r\n */\r\n public void add(double x, double y, boolean notify) {\r\n add(new Double(x), new Double(y), notify);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and sends a {@link SeriesChangeEvent} to\r\n * all registered listeners. The unusual pairing of parameter types is to\r\n * make it easier to add <code>null</code> y-values.\r\n *\r\n * @param x the x value.\r\n * @param y the y value (<code>null</code> permitted).\r\n */\r\n public void add(double x, Number y) {\r\n add(new Double(x), y);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and, if requested, sends a\r\n * {@link SeriesChangeEvent} to all registered listeners. The unusual\r\n * pairing of parameter types is to make it easier to add null y-values.\r\n *\r\n * @param x the x value.\r\n * @param y the y value (<code>null</code> permitted).\r\n * @param notify a flag that controls whether or not a\r\n * {@link SeriesChangeEvent} is sent to all registered\r\n * listeners.\r\n */\r\n public void add(double x, Number y, boolean notify) {\r\n add(new Double(x), y, notify);\r\n }\r\n\r\n /**\r\n * Adds a new data item to the series (in the correct position if the\r\n * <code>autoSort</code> flag is set for the series) and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n * <P>\r\n * Throws an exception if the x-value is a duplicate AND the\r\n * allowDuplicateXValues flag is false.\r\n *\r\n * @param x the x-value (<code>null</code> not permitted).\r\n * @param y the y-value (<code>null</code> permitted).\r\n *\r\n * @throws SeriesException if the x-value is a duplicate and the\r\n * <code>allowDuplicateXValues</code> flag is not set for this series.\r\n */\r\n public void add(Number x, Number y) {\r\n // argument checking delegated...\r\n add(x, y, true);\r\n }\r\n\r\n /**\r\n * Adds new data to the series and, if requested, sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n * <P>\r\n * Throws an exception if the x-value is a duplicate AND the\r\n * allowDuplicateXValues flag is false.\r\n *\r\n * @param x the x-value (<code>null</code> not permitted).\r\n * @param y the y-value (<code>null</code> permitted).\r\n * @param notify a flag the controls whether or not a\r\n * {@link SeriesChangeEvent} is sent to all registered\r\n * listeners.\r\n */\r\n public void add(Number x, Number y, boolean notify) {\r\n // delegate argument checking to XYDataItem...\r\n XYDataItem item = new XYDataItem(x, y);\r\n add(item, notify);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and, if requested, sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param item the (x, y) item (<code>null</code> not permitted).\r\n * @param notify a flag that controls whether or not a\r\n * {@link SeriesChangeEvent} is sent to all registered\r\n * listeners.\r\n */\r\n public void add(XYDataItem item, boolean notify) {\r\n ParamChecks.nullNotPermitted(item, \"item\");\r\n item = (XYDataItem) item.clone();\r\n if (this.autoSort) {\r\n int index = Collections.binarySearch(this.data, item);\r\n if (index < 0) {\r\n this.data.add(-index - 1, item);\r\n }\r\n else {\r\n if (this.allowDuplicateXValues) {\r\n // need to make sure we are adding *after* any duplicates\r\n int size = this.data.size();\r\n while (index < size && item.compareTo(\r\n this.data.get(index)) == 0) {\r\n index++;\r\n }\r\n if (index < this.data.size()) {\r\n this.data.add(index, item);\r\n }\r\n else {\r\n this.data.add(item);\r\n }\r\n }\r\n else {\r\n throw new SeriesException(\"X-value already exists.\");\r\n }\r\n }\r\n }\r\n else {\r\n if (!this.allowDuplicateXValues) {\r\n // can't allow duplicate values, so we need to check whether\r\n // there is an item with the given x-value already\r\n int index = indexOf(item.getX());\r\n if (index >= 0) {\r\n throw new SeriesException(\"X-value already exists.\");\r\n }\r\n }\r\n this.data.add(item);\r\n }\r\n updateBoundsForAddedItem(item);\r\n if (getItemCount() > this.maximumItemCount) {\r\n XYDataItem removed = (XYDataItem) this.data.remove(0);\r\n updateBoundsForRemovedItem(removed);\r\n }\r\n if (notify) {\r\n fireSeriesChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Deletes a range of items from the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param start the start index (zero-based).\r\n * @param end the end index (zero-based).\r\n */\r\n public void delete(int start, int end) {\r\n this.data.subList(start, end + 1).clear();\r\n findBoundsByIteration();\r\n fireSeriesChanged();\r\n }\r\n\r\n /**\r\n * Removes the item at the specified index and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param index the index.\r\n *\r\n * @return The item removed.\r\n */\r\n public XYDataItem remove(int index) {\r\n XYDataItem removed = (XYDataItem) this.data.remove(index);\r\n updateBoundsForRemovedItem(removed);\r\n fireSeriesChanged();\r\n return removed;\r\n }\r\n\r\n /**\r\n * Removes an item with the specified x-value and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners. Note that when\r\n * a series permits multiple items with the same x-value, this method\r\n * could remove any one of the items with that x-value.\r\n *\r\n * @param x the x-value.\r\n\r\n * @return The item removed.\r\n */\r\n public XYDataItem remove(Number x) {\r\n return remove(indexOf(x));\r\n }\r\n\r\n /**\r\n * Removes all data items from the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n */\r\n public void clear() {\r\n if (this.data.size() > 0) {\r\n this.data.clear();\r\n this.minX = Double.NaN;\r\n this.maxX = Double.NaN;\r\n this.minY = Double.NaN;\r\n this.maxY = Double.NaN;\r\n fireSeriesChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Return the data item with the specified index.\r\n *\r\n * @param index the index.\r\n *\r\n * @return The data item with the specified index.\r\n */\r\n public XYDataItem getDataItem(int index) {\r\n XYDataItem item = (XYDataItem) this.data.get(index);\r\n return (XYDataItem) item.clone();\r\n }\r\n\r\n /**\r\n * Return the data item with the specified index.\r\n *\r\n * @param index the index.\r\n *\r\n * @return The data item with the specified index.\r\n *\r\n * @since 1.0.14\r\n */\r\n XYDataItem getRawDataItem(int index) {\r\n return (XYDataItem) this.data.get(index);\r\n }\r\n\r\n /**\r\n * Returns the x-value at the specified index.\r\n *\r\n * @param index the index (zero-based).\r\n *\r\n * @return The x-value (never <code>null</code>).\r\n */\r\n public Number getX(int index) {\r\n return getRawDataItem(index).getX();\r\n }\r\n\r\n /**\r\n * Returns the y-value at the specified index.\r\n *\r\n * @param index the index (zero-based).\r\n *\r\n * @return The y-value (possibly <code>null</code>).\r\n */\r\n public Number getY(int index) {\r\n return getRawDataItem(index).getY();\r\n }\r\n\r\n /**\r\n * Updates the value of an item in the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param index the item (zero based index).\r\n * @param y the new value (<code>null</code> permitted).\r\n *\r\n * @deprecated Renamed {@link #updateByIndex(int, Number)} to avoid\r\n * confusion with the {@link #update(Number, Number)} method.\r\n */\r\n public void update(int index, Number y) {\r\n XYDataItem item = getRawDataItem(index);\r\n\r\n // figure out if we need to iterate through all the y-values\r\n boolean iterate = false;\r\n double oldY = item.getYValue();\r\n if (!Double.isNaN(oldY)) {\r\n iterate = oldY <= this.minY || oldY >= this.maxY;\r\n }\r\n item.setY(y);\r\n\r\n if (iterate) {\r\n findBoundsByIteration();\r\n }\r\n else if (y != null) {\r\n double yy = y.doubleValue();\r\n this.minY = minIgnoreNaN(this.minY, yy);\r\n this.maxY = maxIgnoreNaN(this.maxY, yy);\r\n }\r\n fireSeriesChanged();\r\n }\r\n\r\n /**\r\n * A function to find the minimum of two values, but ignoring any\r\n * Double.NaN values.\r\n *\r\n * @param a the first value.\r\n * @param b the second value.\r\n *\r\n * @return The minimum of the two values.\r\n */\r\n private double minIgnoreNaN(double a, double b) {\r\n if (Double.isNaN(a)) {\r\n return b;\r\n }\r\n if (Double.isNaN(b)) {\r\n return a;\r\n }\r\n return Math.min(a, b);\r\n }\r\n\r\n /**\r\n * A function to find the maximum of two values, but ignoring any\r\n * Double.NaN values.\r\n *\r\n * @param a the first value.\r\n * @param b the second value.\r\n *\r\n * @return The maximum of the two values.\r\n */\r\n private double maxIgnoreNaN(double a, double b) {\r\n if (Double.isNaN(a)) {\r\n return b;\r\n }\r\n if (Double.isNaN(b)) {\r\n return a;\r\n }\r\n return Math.max(a, b);\r\n }\r\n\r\n /**\r\n * Updates the value of an item in the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param index the item (zero based index).\r\n * @param y the new value (<code>null</code> permitted).\r\n *\r\n * @since 1.0.1\r\n */\r\n public void updateByIndex(int index, Number y) {\r\n update(index, y);\r\n }\r\n\r\n /**\r\n * Updates an item in the series.\r\n *\r\n * @param x the x-value (<code>null</code> not permitted).\r\n * @param y the y-value (<code>null</code> permitted).\r\n *\r\n * @throws SeriesException if there is no existing item with the specified\r\n * x-value.\r\n */\r\n public void update(Number x, Number y) {\r\n int index = indexOf(x);\r\n if (index < 0) {\r\n throw new SeriesException(\"No observation for x = \" + x);\r\n }\r\n updateByIndex(index, y);\r\n }\r\n\r\n /**\r\n * Adds or updates an item in the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param x the x-value.\r\n * @param y the y-value.\r\n *\r\n * @return The item that was overwritten, if any.\r\n *\r\n * @since 1.0.10\r\n */\r\n public XYDataItem addOrUpdate(double x, double y) {\r\n return addOrUpdate(new Double(x), new Double(y));\r\n }\r\n\r\n /**\r\n * Adds or updates an item in the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param x the x-value (<code>null</code> not permitted).\r\n * @param y the y-value (<code>null</code> permitted).\r\n *\r\n * @return A copy of the overwritten data item, or <code>null</code> if no\r\n * item was overwritten.\r\n */\r\n public XYDataItem addOrUpdate(Number x, Number y) {\r\n // defer argument checking\r\n return addOrUpdate(new XYDataItem(x, y));\r\n }\r\n\r\n /**\r\n * Adds or updates an item in the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param item the data item (<code>null</code> not permitted).\r\n *\r\n * @return A copy of the overwritten data item, or <code>null</code> if no\r\n * item was overwritten.\r\n *\r\n * @since 1.0.14\r\n */\r\n public XYDataItem addOrUpdate(XYDataItem item) {\r\n ParamChecks.nullNotPermitted(item, \"item\");\r\n if (this.allowDuplicateXValues) {\r\n add(item);\r\n return null;\r\n }\r\n\r\n // if we get to here, we know that duplicate X values are not permitted\r\n XYDataItem overwritten = null;\r\n int index = indexOf(item.getX());\r\n if (index >= 0) {\r\n XYDataItem existing = (XYDataItem) this.data.get(index);\r\n overwritten = (XYDataItem) existing.clone();\r\n // figure out if we need to iterate through all the y-values\r\n boolean iterate = false;\r\n double oldY = existing.getYValue();\r\n if (!Double.isNaN(oldY)) {\r\n iterate = oldY <= this.minY || oldY >= this.maxY;\r\n }\r\n existing.setY(item.getY());\r\n\r\n if (iterate) {\r\n findBoundsByIteration();\r\n }\r\n else if (item.getY() != null) {\r\n double yy = item.getY().doubleValue();\r\n this.minY = minIgnoreNaN(this.minY, yy);\r\n this.maxY = maxIgnoreNaN(this.maxY, yy);\r\n }\r\n }\r\n else {\r\n // if the series is sorted, the negative index is a result from\r\n // Collections.binarySearch() and tells us where to insert the\r\n // new item...otherwise it will be just -1 and we should just\r\n // append the value to the list...\r\n item = (XYDataItem) item.clone();\r\n if (this.autoSort) {\r\n this.data.add(-index - 1, item);\r\n }\r\n else {\r\n this.data.add(item);\r\n }\r\n updateBoundsForAddedItem(item);\r\n\r\n // check if this addition will exceed the maximum item count...\r\n if (getItemCount() > this.maximumItemCount) {\r\n XYDataItem removed = (XYDataItem) this.data.remove(0);\r\n updateBoundsForRemovedItem(removed);\r\n }\r\n }\r\n fireSeriesChanged();\r\n return overwritten;\r\n }\r\n\r\n /**\r\n * Returns the index of the item with the specified x-value, or a negative\r\n * index if the series does not contain an item with that x-value. Be\r\n * aware that for an unsorted series, the index is found by iterating\r\n * through all items in the series.\r\n *\r\n * @param x the x-value (<code>null</code> not permitted).\r\n *\r\n * @return The index.\r\n */\r\n public int indexOf(Number x) {\r\n if (this.autoSort) {\r\n return Collections.binarySearch(this.data, new XYDataItem(x, null));\r\n }\r\n else {\r\n for (int i = 0; i < this.data.size(); i++) {\r\n XYDataItem item = (XYDataItem) this.data.get(i);\r\n if (item.getX().equals(x)) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n }\r\n }\r\n\r\n /**\r\n * Returns a new array containing the x and y values from this series.\r\n *\r\n * @return A new array containing the x and y values from this series.\r\n *\r\n * @since 1.0.4\r\n */\r\n public double[][] toArray() {\r\n int itemCount = getItemCount();\r\n double[][] result = new double[2][itemCount];\r\n for (int i = 0; i < itemCount; i++) {\r\n result[0][i] = this.getX(i).doubleValue();\r\n Number y = getY(i);\r\n if (y != null) {\r\n result[1][i] = y.doubleValue();\r\n }\r\n else {\r\n result[1][i] = Double.NaN;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a clone of the series.\r\n *\r\n * @return A clone of the series.\r\n *\r\n * @throws CloneNotSupportedException if there is a cloning problem.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n XYSeries clone = (XYSeries) super.clone();\r\n clone.data = (List) ObjectUtilities.deepClone(this.data);\r\n return clone;\r\n }\r\n\r\n /**\r\n * Creates a new series by copying a subset of the data in this time series.\r\n *\r\n * @param start the index of the first item to copy.\r\n * @param end the index of the last item to copy.\r\n *\r\n * @return A series containing a copy of this series from start until end.\r\n *\r\n * @throws CloneNotSupportedException if there is a cloning problem.\r\n */\r\n public XYSeries createCopy(int start, int end)\r\n throws CloneNotSupportedException {\r\n\r\n XYSeries copy = (XYSeries) super.clone();\r\n copy.data = new java.util.ArrayList();\r\n if (this.data.size() > 0) {\r\n for (int index = start; index <= end; index++) {\r\n XYDataItem item = (XYDataItem) this.data.get(index);\r\n XYDataItem clone = (XYDataItem) item.clone();\r\n try {\r\n copy.add(clone);\r\n }\r\n catch (SeriesException e) {\r\n throw new RuntimeException(\r\n \"Unable to add cloned data item.\", e);\r\n }\r\n }\r\n }\r\n return copy;\r\n\r\n }\r\n\r\n /**\r\n * Tests this series for equality with an arbitrary object.\r\n *\r\n * @param obj the object to test against for equality\r\n * (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof XYSeries)) {\r\n return false;\r\n }\r\n if (!super.equals(obj)) {\r\n return false;\r\n }\r\n XYSeries that = (XYSeries) obj;\r\n if (this.maximumItemCount != that.maximumItemCount) {\r\n return false;\r\n }\r\n if (this.autoSort != that.autoSort) {\r\n return false;\r\n }\r\n if (this.allowDuplicateXValues != that.allowDuplicateXValues) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.data, that.data)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result = super.hashCode();\r\n // it is too slow to look at every data item, so let's just look at\r\n // the first, middle and last items...\r\n int count = getItemCount();\r\n if (count > 0) {\r\n XYDataItem item = getRawDataItem(0);\r\n result = 29 * result + item.hashCode();\r\n }\r\n if (count > 1) {\r\n XYDataItem item = getRawDataItem(count - 1);\r\n result = 29 * result + item.hashCode();\r\n }\r\n if (count > 2) {\r\n XYDataItem item = getRawDataItem(count / 2);\r\n result = 29 * result + item.hashCode();\r\n }\r\n result = 29 * result + this.maximumItemCount;\r\n result = 29 * result + (this.autoSort ? 1 : 0);\r\n result = 29 * result + (this.allowDuplicateXValues ? 1 : 0);\r\n return result;\r\n }\r\n\r\n}\r" } ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import org.jfree.chart.JFreeChart; import org.jfree.chart.TestUtilities; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.util.PublicCloneable; import org.junit.Test;
80,695
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * XYStepAreaRendererTest.java * --------------------------- * (C) Copyright 2003-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Matthias Rose; * * Changes * ------- * 25-Mar-2003 : Version 1 (DG); * 26-Sep-2003 : copied XYStepRendererTests.java and used for * testing XYStepAreaRenderer (MR); * 14-Feb-2007 : Extended testEquals() (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * 05-Dec-2013 : Add stepPoint to equals() test (DG); * */ package org.jfree.chart.renderer.xy; /** * Tests for the {@link XYStepAreaRenderer} class. */ public class XYStepAreaRendererTest { /** * Check that the equals() method distinguishes all fields. */ @Test public void testEquals() { XYStepAreaRenderer r1 = new XYStepAreaRenderer(); XYStepAreaRenderer r2 = new XYStepAreaRenderer(); assertEquals(r1, r2); r1.setOutline(true); assertFalse(r1.equals(r2)); r2.setOutline(true); assertTrue(r1.equals(r2)); r1.setShapesVisible(true); assertFalse(r1.equals(r2)); r2.setShapesVisible(true); assertTrue(r1.equals(r2)); r1.setShapesFilled(true); assertFalse(r1.equals(r2)); r2.setShapesFilled(true); assertTrue(r1.equals(r2)); r1.setPlotArea(false); assertFalse(r1.equals(r2)); r2.setPlotArea(false); assertTrue(r1.equals(r2)); r1.setRangeBase(-1.0); assertFalse(r1.equals(r2)); r2.setRangeBase(-1.0); assertTrue(r1.equals(r2)); r1.setStepPoint(0.33); assertFalse(r1.equals(r2)); r2.setStepPoint(0.33); assertTrue(r1.equals(r2)); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashcode() { XYStepAreaRenderer r1 = new XYStepAreaRenderer(); XYStepAreaRenderer r2 = new XYStepAreaRenderer(); assertTrue(r1.equals(r2)); int h1 = r1.hashCode(); int h2 = r2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { XYStepAreaRenderer r1 = new XYStepAreaRenderer(); XYStepAreaRenderer r2 = (XYStepAreaRenderer) r1.clone(); assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { XYStepAreaRenderer r1 = new XYStepAreaRenderer(); assertTrue(r1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { XYStepAreaRenderer r1 = new XYStepAreaRenderer(); XYStepAreaRenderer r2 = (XYStepAreaRenderer) TestUtilities.serialised(r1); assertEquals(r1, r2); } /** * Draws the chart with a <code>null</code> info object to make sure that * no exceptions are thrown (particularly by code in the renderer). */ @Test public void testDrawWithNullInfo() { try { DefaultTableXYDataset dataset = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(5.0, 5.0); s1.add(10.0, 15.5); s1.add(15.0, 9.5); s1.add(20.0, 7.5); dataset.addSeries(s1); XYSeries s2 = new XYSeries("Series 2", true, false); s2.add(5.0, 5.0); s2.add(10.0, 15.5); s2.add(15.0, 9.5); s2.add(20.0, 3.5); dataset.addSeries(s2); XYPlot plot = new XYPlot(dataset,
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * XYStepAreaRendererTest.java * --------------------------- * (C) Copyright 2003-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Matthias Rose; * * Changes * ------- * 25-Mar-2003 : Version 1 (DG); * 26-Sep-2003 : copied XYStepRendererTests.java and used for * testing XYStepAreaRenderer (MR); * 14-Feb-2007 : Extended testEquals() (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * 05-Dec-2013 : Add stepPoint to equals() test (DG); * */ package org.jfree.chart.renderer.xy; /** * Tests for the {@link XYStepAreaRenderer} class. */ public class XYStepAreaRendererTest { /** * Check that the equals() method distinguishes all fields. */ @Test public void testEquals() { XYStepAreaRenderer r1 = new XYStepAreaRenderer(); XYStepAreaRenderer r2 = new XYStepAreaRenderer(); assertEquals(r1, r2); r1.setOutline(true); assertFalse(r1.equals(r2)); r2.setOutline(true); assertTrue(r1.equals(r2)); r1.setShapesVisible(true); assertFalse(r1.equals(r2)); r2.setShapesVisible(true); assertTrue(r1.equals(r2)); r1.setShapesFilled(true); assertFalse(r1.equals(r2)); r2.setShapesFilled(true); assertTrue(r1.equals(r2)); r1.setPlotArea(false); assertFalse(r1.equals(r2)); r2.setPlotArea(false); assertTrue(r1.equals(r2)); r1.setRangeBase(-1.0); assertFalse(r1.equals(r2)); r2.setRangeBase(-1.0); assertTrue(r1.equals(r2)); r1.setStepPoint(0.33); assertFalse(r1.equals(r2)); r2.setStepPoint(0.33); assertTrue(r1.equals(r2)); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashcode() { XYStepAreaRenderer r1 = new XYStepAreaRenderer(); XYStepAreaRenderer r2 = new XYStepAreaRenderer(); assertTrue(r1.equals(r2)); int h1 = r1.hashCode(); int h2 = r2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { XYStepAreaRenderer r1 = new XYStepAreaRenderer(); XYStepAreaRenderer r2 = (XYStepAreaRenderer) r1.clone(); assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { XYStepAreaRenderer r1 = new XYStepAreaRenderer(); assertTrue(r1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { XYStepAreaRenderer r1 = new XYStepAreaRenderer(); XYStepAreaRenderer r2 = (XYStepAreaRenderer) TestUtilities.serialised(r1); assertEquals(r1, r2); } /** * Draws the chart with a <code>null</code> info object to make sure that * no exceptions are thrown (particularly by code in the renderer). */ @Test public void testDrawWithNullInfo() { try { DefaultTableXYDataset dataset = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(5.0, 5.0); s1.add(10.0, 15.5); s1.add(15.0, 9.5); s1.add(20.0, 7.5); dataset.addSeries(s1); XYSeries s2 = new XYSeries("Series 2", true, false); s2.add(5.0, 5.0); s2.add(10.0, 15.5); s2.add(15.0, 9.5); s2.add(20.0, 3.5); dataset.addSeries(s2); XYPlot plot = new XYPlot(dataset,
new NumberAxis("X"), new NumberAxis("Y"),
2
2023-12-24 12:36:47+00:00
128k
DrMango14/Create-Design-n-Decor
src/main/java/com/mangomilk/design_decor/registry/MmbBlocks.java
[ { "identifier": "DecorBuilderTransformer", "path": "src/main/java/com/mangomilk/design_decor/base/DecorBuilderTransformer.java", "snippet": "public class DecorBuilderTransformer {\n\n public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> connected(\n Supplier<CTSpriteShiftEntry> ct) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get()))\n .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> layeredConnected(\n Supplier<CTSpriteShiftEntry> ct, Supplier<CTSpriteShiftEntry> ct2) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get(), p.models()\n .cubeColumn(c.getName(), ct.get()\n .getOriginalResourceLocation(),\n ct2.get()\n .getOriginalResourceLocation())))\n .onRegister(connectedTextures(() -> new HorizontalCTBehaviour(ct.get(), ct2.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n public static <B extends OrnateGrateBlock> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> ornateconnected(\n Supplier<CTSpriteShiftEntry> ct) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get(), AssetLookup.standardModel(c, p)))\n .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n private static BlockBehaviour.Properties glassProperties(BlockBehaviour.Properties p) {\n return p.isValidSpawn(DecorBuilderTransformer::never)\n .isRedstoneConductor(DecorBuilderTransformer::never)\n .isSuffocating(DecorBuilderTransformer::never)\n .isViewBlocking(DecorBuilderTransformer::never)\n .noOcclusion();\n }\n\n public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(Supplier<ConnectedTextureBehaviour> behaviour) {\n return CreateMMBuilding.REGISTRATE.block(\"tinted_framed_glass\", ConnectedTintedGlassBlock::new)\n .onRegister(connectedTextures(behaviour))\n .addLayer(() -> RenderType::translucent)\n .initialProperties(() -> Blocks.TINTED_GLASS)\n .properties(DecorBuilderTransformer::glassProperties)\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get))\n .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, \"palettes/\", \"tinted_framed_glass\"))\n .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE)\n .lang(\"Tinted Framed Glass\")\n .item()\n .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS)\n .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()),\n p.modLoc(\"block/palettes/tinted_framed_glass\")))\n .build()\n .register();\n }\n\n public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(String type,String name, Supplier<ConnectedTextureBehaviour> behaviour) {\n return CreateMMBuilding.REGISTRATE.block(type + \"_tinted_framed_glass\", ConnectedTintedGlassBlock::new)\n .onRegister(connectedTextures(behaviour))\n .addLayer(() -> RenderType::translucent)\n .initialProperties(() -> Blocks.TINTED_GLASS)\n .properties(DecorBuilderTransformer::glassProperties)\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get))\n .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, \"palettes/\", type + \"_tinted_framed_glass\"))\n .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE)\n .lang(name + \" Tinted Framed Glass\")\n .item()\n .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS)\n .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()),\n p.modLoc(\"block/palettes/\" + type + \"_tinted_framed_glass\")))\n .build()\n .register();\n }\n\n\n\n\n public static BlockEntry<Block> CastelBricks(String id, String lang, MaterialColor color, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Brick Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_bricks\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_bricks\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Brick Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Brick Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_bricks\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Bricks\")\n .register();\n }\n\n public static BlockEntry<Block> CastelBricks(String id, String lang, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Brick Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_bricks\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_bricks\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Brick Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Brick Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_bricks\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Bricks\")\n .register();\n }\n public static BlockEntry<Block> CastelTiles(String id, String lang, MaterialColor color, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Tile Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_tiles\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_tiles\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Tile Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Tile Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_tiles\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Tiles\")\n .register();\n }\n public static BlockEntry<Block> CastelTiles(String id, String lang, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Tile Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_tiles\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_tiles\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Tile Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Tile Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_tiles\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Tiles\")\n .register();\n }\n private static boolean never(BlockState p_235436_0_, BlockGetter p_235436_1_, BlockPos p_235436_2_) {return false;}\n private static Boolean never(BlockState p_235427_0_, BlockGetter p_235427_1_, BlockPos p_235427_2_, EntityType<?> p_235427_3_) {return false;}\n private static String palettesDir() {return \"block/palettes/\";}\n}" }, { "identifier": "MmbSpriteShifts", "path": "src/main/java/com/mangomilk/design_decor/base/MmbSpriteShifts.java", "snippet": "@SuppressWarnings({\"unused\"})\npublic class MmbSpriteShifts {\n public static final Couple<CTSpriteShiftEntry>\n RED_CONTAINER_TOP = vault(\"red\",\"top\"),\n RED_CONTAINER_FRONT = vault(\"red\",\"front\"),\n RED_CONTAINER_SIDE = vault(\"red\",\"side\"),\n RED_CONTAINER_BOTTOM = vault(\"red\",\"bottom\");\n public static final Couple<CTSpriteShiftEntry>\n BLUE_CONTAINER_TOP = vault(\"blue\",\"top\"),\n BLUE_CONTAINER_FRONT = vault(\"blue\",\"front\"),\n BLUE_CONTAINER_SIDE = vault(\"blue\",\"side\"),\n BLUE_CONTAINER_BOTTOM = vault(\"blue\",\"bottom\");\n public static final Couple<CTSpriteShiftEntry>\n GREEN_CONTAINER_TOP = vault(\"green\",\"top\"),\n GREEN_CONTAINER_FRONT = vault(\"green\",\"front\"),\n GREEN_CONTAINER_SIDE = vault(\"green\",\"side\"),\n GREEN_CONTAINER_BOTTOM = vault(\"green\",\"bottom\");\n\n public static final CTSpriteShiftEntry\n ORNATE_GRATE = omni(\"ornate_grate\"),\n INDUSTRIAL_PLATING_BLOCK = omni(\"industrial_plating_block\"),\n INDUSTRIAL_PLATING_BLOCK_SIDE = omni(\"industrial_plating_block_side\"),\n TINTED_FRAMED_GLASS = omni(\"palettes/tinted_framed_glass\"),\n TINTED_HORIZONTAL_FRAMED_GLASS = omni(\"palettes/horizontal_tinted_framed_glass\"),\n TINTED_VERTICAL_FRAMED_GLASS = omni(\"palettes/vertical_tinted_framed_glass\");\n\n private static Couple<CTSpriteShiftEntry> vault(String color,String name) {\n final String prefixed = \"block/\"+color+\"_container/container_\" + name;\n return Couple.createWithContext(\n medium -> CTSpriteShifter.getCT(AllCTTypes.RECTANGLE, CreateMMBuilding.asResource(prefixed + \"_small\"),\n CreateMMBuilding.asResource(medium ? prefixed + \"_medium\" : prefixed + \"_large\")));\n }\n\n private static CTSpriteShiftEntry omni(String name) {\n return getCT(AllCTTypes.OMNIDIRECTIONAL, name);\n }\n\n private static CTSpriteShiftEntry horizontal(String name) {\n return getCT(AllCTTypes.HORIZONTAL, name);\n }\n\n private static CTSpriteShiftEntry vertical(String name) {\n return getCT(AllCTTypes.VERTICAL, name);\n }\n\n\n private static CTSpriteShiftEntry getCT(CTType type, String blockTextureName, String connectedTextureName) {\n return CTSpriteShifter.getCT(type, CreateMMBuilding.asResource(\"block/\" + blockTextureName),\n CreateMMBuilding.asResource(\"block/\" + connectedTextureName + \"_connected\"));\n }\n\n private static CTSpriteShiftEntry getCT(CTType type, String blockTextureName) {\n return getCT(type, blockTextureName, blockTextureName);\n }\n\n public static void init(){}\n\n}" }, { "identifier": "SignBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/SignBlock.java", "snippet": "public class SignBlock extends DirectionalBlock implements IWrenchable {\n\n public static final VoxelShape SHAPE_UP = Block.box(0.0D, 15.0D, 0.0D, 16.0D, 16.0D, 16.0D);\n public static final VoxelShape SHAPE_DOWN = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 1.0D, 16.0D);\n public static final VoxelShape SHAPE_NORTH = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 1.0D);\n public static final VoxelShape SHAPE_WEST = Block.box(0.0D, 0.0D, 0.0D, 1.0D, 16.0D, 16.0D);\n public static final VoxelShape SHAPE_EAST = Block.box(15.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D);\n public static final VoxelShape SHAPE_SOUTH = Block.box(0.0D, 0.0D, 15.0D, 16.0D, 16.0D, 16.0D);\n\n\n\n public static final VoxelShape SHAPE_UP_OUTLINE = Block.box(1.0D, 15.0D, 1.0D, 15.0D, 16.0D, 15.0D);\n public static final VoxelShape SHAPE_DOWN_OUTLINE = Block.box(1.0D, 0.0D, 1.0D, 15.0D, 1.0D, 15.0D);\n\n public static final VoxelShape SHAPE_WEST_OUTLINE = Block.box(0.0D, 1.0D, 1.0D, 1.0D, 15.0D, 15.0D);\n public static final VoxelShape SHAPE_EAST_OUTLINE = Block.box(15.0D, 1.0D, 1.0D, 16.0D, 15.0D, 15.0D);\n public static final VoxelShape SHAPE_SOUTH_OUTLINE = Block.box(1.0D, 1.0D, 15.0D, 15.0D, 15.0D, 16.0D);\n public static final VoxelShape SHAPE_NORTH_OUTLINE = Block.box(1.0D, 1.0D, 0.0D, 15.0D, 15.0D, 1.0D);\n public SignBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP));\n }\n\n public VoxelShape getShape(BlockState p_54561_, BlockGetter p_54562_, BlockPos p_54563_, CollisionContext p_54564_) {\n switch (p_54561_.getValue(FACING)) {\n case NORTH:\n return SHAPE_NORTH_OUTLINE;\n case SOUTH:\n return SHAPE_SOUTH_OUTLINE;\n case EAST:\n return SHAPE_EAST_OUTLINE;\n case WEST:\n return SHAPE_WEST_OUTLINE;\n case UP:\n return SHAPE_UP_OUTLINE;\n case DOWN:\n return SHAPE_DOWN_OUTLINE;\n default:\n return SHAPE_NORTH_OUTLINE;\n }\n }\n\n @Override\n public VoxelShape getBlockSupportShape(BlockState pState, BlockGetter pReader, BlockPos pPos) {\n switch (pState.getValue(FACING)) {\n case NORTH:\n return SHAPE_NORTH;\n case SOUTH:\n return SHAPE_SOUTH;\n case EAST:\n return SHAPE_EAST;\n case WEST:\n return SHAPE_WEST;\n case UP:\n return SHAPE_UP;\n case DOWN:\n return SHAPE_DOWN;\n default:\n return SHAPE_NORTH;\n }\n }\n\n public BlockState updateShape(BlockState p_57503_, Direction p_57504_, BlockState p_57505_, LevelAccessor p_57506_, BlockPos p_57507_, BlockPos p_57508_) {\n return !this.canSurvive(p_57503_, p_57506_, p_57507_) ? Blocks.AIR.defaultBlockState() : super.updateShape(p_57503_, p_57504_, p_57505_, p_57506_, p_57507_, p_57508_);\n }\n\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_55125_) {\n p_55125_.add(FACING);\n }\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_58126_) {\n BlockState blockstate = this.defaultBlockState();\n LevelReader levelreader = p_58126_.getLevel();\n BlockPos blockpos = p_58126_.getClickedPos();\n Direction[] adirection = p_58126_.getNearestLookingDirections();\n\n for(Direction direction : adirection) {\n blockstate = blockstate.setValue(FACING, direction);\n if (blockstate.canSurvive(levelreader, blockpos)) {\n return blockstate;\n }\n\n }\n\n return null;\n }\n public boolean canSurvive(BlockState p_58133_, LevelReader p_58134_, BlockPos p_58135_) {\n Direction direction = p_58133_.getValue(FACING);\n BlockPos blockpos = p_58135_.relative(direction);\n BlockState blockstate = p_58134_.getBlockState(blockpos);\n return !blockstate.isAir();\n }\n}" }, { "identifier": "LargeChain", "path": "src/main/java/com/mangomilk/design_decor/blocks/chain/LargeChain.java", "snippet": "@SuppressWarnings({\"unused\"})\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class LargeChain extends ChainBlock implements SimpleWaterloggedBlock, IWrenchable {\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n protected static final float AABB_MIN = 4;\n protected static final float AABB_MAX = 12;\n\n protected static final VoxelShape Y_AXIS_AABB = Block.box(4, 0, 4, 12, 16, 12);\n protected static final VoxelShape Z_AXIS_AABB = Block.box(4, 4, 0, 12, 12, 16);\n protected static final VoxelShape X_AXIS_AABB = Block.box(0, 4, 4, 16, 12, 12);\n\n public static final int placementHelperId = PlacementHelpers.register(new LargeChain.PlacementHelper());\n\n public LargeChain(Properties p_55926_) {\n super(p_55926_.noCollission().noOcclusion().isSuffocating(LargeChain::never).requiresCorrectToolForDrops().strength(5.0F, 6.0F)\n .sound(new ForgeSoundType(1f, .95f, () -> DecoSoundEvents.LARGE_CHAIN_BREAK.get(),\n () -> DecoSoundEvents.LARGE_CHAIN_STEP.get(), () -> DecoSoundEvents.LARGE_CHAIN_PLACE.get(),\n () -> DecoSoundEvents.LARGE_CHAIN_HIT.get(), () -> DecoSoundEvents.LARGE_CHAIN_FALL.get())));\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE).setValue(AXIS, Direction.Axis.Y));\n }\n\n @Override\n public VoxelShape getShape(BlockState p_51470_, BlockGetter p_51471_, BlockPos p_51472_, CollisionContext p_51473_) {\n switch ((Direction.Axis)p_51470_.getValue(AXIS)) {\n case X:\n default:\n return X_AXIS_AABB;\n case Z:\n return Z_AXIS_AABB;\n case Y:\n return Y_AXIS_AABB;\n }\n }\n\n @Override\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_51454_) {\n FluidState fluidstate = p_51454_.getLevel().getFluidState(p_51454_.getClickedPos());\n boolean flag = fluidstate.getType() == Fluids.WATER;\n return Objects.requireNonNull(super.getStateForPlacement(p_51454_)).setValue(WATERLOGGED, flag);\n }\n\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_51468_) {\n p_51468_.add(WATERLOGGED).add(AXIS);\n }\n\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n\n @Override\n public boolean isPathfindable(BlockState p_51456_, BlockGetter p_51457_, BlockPos p_51458_, PathComputationType p_51459_) {\n return false;\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction.Axis> {\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof LargeChain, state -> state.getValue(AXIS), AXIS);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof LargeChain;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof LargeChain;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectLargeChain(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n if (pPlayer == null)\n return InteractionResult.PASS;\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n public static BlockState pickCorrectLargeChain(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n private static boolean never(BlockState p_235436_0_, BlockGetter p_235436_1_, BlockPos p_235436_2_) {\n return false;\n }\n}" }, { "identifier": "TagDependentLargeChain", "path": "src/main/java/com/mangomilk/design_decor/blocks/chain/TagDependentLargeChain.java", "snippet": "@SuppressWarnings({\"unused\"})\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class TagDependentLargeChain extends ChainBlock implements SimpleWaterloggedBlock, IWrenchable {\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n protected static final float AABB_MIN = 4;\n protected static final float AABB_MAX = 12;\n\n protected static final VoxelShape Y_AXIS_AABB = Block.box(4, 0, 4, 12, 16, 12);\n protected static final VoxelShape Z_AXIS_AABB = Block.box(4, 4, 0, 12, 12, 16);\n protected static final VoxelShape X_AXIS_AABB = Block.box(0, 4, 4, 16, 12, 12);\n\n public static final int placementHelperId = PlacementHelpers.register(new TagDependentLargeChain.PlacementHelper());\n\n private TagKey<Item> tag;\n\n public TagDependentLargeChain(Properties p_55926_, TagKey<Item> itemTagKey) {\n super(p_55926_.noCollission().noOcclusion().isSuffocating(TagDependentLargeChain::never).requiresCorrectToolForDrops().strength(5.0F, 6.0F)\n .sound(new ForgeSoundType(1f, .95f, () -> DecoSoundEvents.LARGE_CHAIN_BREAK.get(),\n () -> DecoSoundEvents.LARGE_CHAIN_STEP.get(), () -> DecoSoundEvents.LARGE_CHAIN_PLACE.get(),\n () -> DecoSoundEvents.LARGE_CHAIN_HIT.get(), () -> DecoSoundEvents.LARGE_CHAIN_FALL.get())));\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE).setValue(AXIS, Direction.Axis.Y));\n this.tag = itemTagKey;\n }\n\n @Override\n public VoxelShape getShape(BlockState p_51470_, BlockGetter p_51471_, BlockPos p_51472_, CollisionContext p_51473_) {\n switch ((Direction.Axis)p_51470_.getValue(AXIS)) {\n case X:\n default:\n return X_AXIS_AABB;\n case Z:\n return Z_AXIS_AABB;\n case Y:\n return Y_AXIS_AABB;\n }\n }\n\n @Override\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_51454_) {\n FluidState fluidstate = p_51454_.getLevel().getFluidState(p_51454_.getClickedPos());\n boolean flag = fluidstate.getType() == Fluids.WATER;\n return Objects.requireNonNull(super.getStateForPlacement(p_51454_)).setValue(WATERLOGGED, flag);\n }\n\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_51468_) {\n p_51468_.add(WATERLOGGED).add(AXIS);\n }\n\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n\n @Override\n public boolean isPathfindable(BlockState p_51456_, BlockGetter p_51457_, BlockPos p_51458_, PathComputationType p_51459_) {\n return false;\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction.Axis> {\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof TagDependentLargeChain, state -> state.getValue(AXIS), AXIS);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof TagDependentLargeChain;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof TagDependentLargeChain;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectLargeChain(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n if (pPlayer == null)\n return InteractionResult.PASS;\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n public static BlockState pickCorrectLargeChain(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n private static boolean never(BlockState p_235436_0_, BlockGetter p_235436_1_, BlockPos p_235436_2_) {\n return false;\n }\n\n\n @Override\n public void fillItemCategory(CreativeModeTab tab, NonNullList<ItemStack> list) {\n if (!shouldHide())\n super.fillItemCategory(tab, list);\n }\n\n public boolean shouldHide() {\n ITagManager<Item> tagManager = ForgeRegistries.ITEMS.tags();\n return !tagManager.isKnownTagName(tag) || tagManager.getTag(tag).isEmpty();\n }\n}" }, { "identifier": "RedContainerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/red/RedContainerBlock.java", "snippet": "public class RedContainerBlock extends Block implements IWrenchable, IBE<RedContainerBlockEntity> {\n\n\tpublic static final Property<Axis> HORIZONTAL_AXIS = BlockStateProperties.HORIZONTAL_AXIS;\n\tpublic static final BooleanProperty LARGE = BooleanProperty.create(\"large\");\n\n\n\tpublic RedContainerBlock(Properties p_i48440_1_) {\n\t\tsuper(p_i48440_1_);\n\t\tregisterDefaultState(defaultBlockState().setValue(LARGE, false));\n\t}\n\n\t@Override\n\tprotected void createBlockStateDefinition(Builder<Block, BlockState> pBuilder) {\n\t\tpBuilder.add(HORIZONTAL_AXIS, LARGE);\n\t\tsuper.createBlockStateDefinition(pBuilder);\n\t}\n\n\t@Override\n\tpublic BlockState getStateForPlacement(BlockPlaceContext pContext) {\n\t\tif (pContext.getPlayer() == null || !pContext.getPlayer()\n\t\t\t.isSteppingCarefully()) {\n\t\t\tBlockState placedOn = pContext.getLevel()\n\t\t\t\t.getBlockState(pContext.getClickedPos()\n\t\t\t\t\t.relative(pContext.getClickedFace()\n\t\t\t\t\t\t.getOpposite()));\n\t\t\tAxis preferredAxis = getContainerBlockAxis(placedOn);\n\t\t\tif (preferredAxis != null)\n\t\t\t\treturn this.defaultBlockState()\n\t\t\t\t\t.setValue(HORIZONTAL_AXIS, preferredAxis);\n\t\t}\n\t\treturn this.defaultBlockState()\n\t\t\t.setValue(HORIZONTAL_AXIS, pContext.getHorizontalDirection()\n\t\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic void onPlace(BlockState pState, Level pLevel, BlockPos pPos, BlockState pOldState, boolean pIsMoving) {\n\t\tif (pOldState.getBlock() == pState.getBlock())\n\t\t\treturn;\n\t\tif (pIsMoving)\n\t\t\treturn;\n\t\twithBlockEntityDo(pLevel, pPos, RedContainerBlockEntity::updateConnectivity);\n\t}\n\n\t@Override\n\tpublic InteractionResult onWrenched(BlockState state, UseOnContext context) {\n\t\tif (context.getClickedFace()\n\t\t\t.getAxis()\n\t\t\t.isVertical()) {\n\t\t\tBlockEntity be = context.getLevel()\n\t\t\t\t.getBlockEntity(context.getClickedPos());\n\t\t\tif (be instanceof RedContainerBlockEntity) {\n\t\t\t\tRedContainerBlockEntity container = (RedContainerBlockEntity) be;\n\t\t\t\tConnectivityHandler.splitMulti(container);\n\t\t\t\tcontainer.removeController(true);\n\t\t\t}\n\t\t\tstate = state.setValue(LARGE, false);\n\t\t}\n\t\tInteractionResult onWrenched = IWrenchable.super.onWrenched(state, context);\n\t\treturn onWrenched;\n\t}\n\n\t@Override\n\tpublic void onRemove(BlockState state, Level world, BlockPos pos, BlockState newState, boolean pIsMoving) {\n\t\tif (state.hasBlockEntity() && (state.getBlock() != newState.getBlock() || !newState.hasBlockEntity())) {\n\t\t\tBlockEntity be = world.getBlockEntity(pos);\n\t\t\tif (!(be instanceof RedContainerBlockEntity))\n\t\t\t\treturn;\n\t\t\tRedContainerBlockEntity containerBE = (RedContainerBlockEntity) be;\n\t\t\tItemHelper.dropContents(world, pos, containerBE.inventory);\n\t\t\tworld.removeBlockEntity(pos);\n\t\t\tConnectivityHandler.splitMulti(containerBE);\n\t\t}\n\t}\n\n\tpublic static boolean isContainer(BlockState state) {\n\n\n\t\treturn MmbBlocks.RED_CONTAINER.has(state);\n\t}\n\n\t@Nullable\n\tpublic static Axis getContainerBlockAxis(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn null;\n\t\treturn state.getValue(HORIZONTAL_AXIS);\n\t}\n\n\tpublic static boolean isLarge(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn false;\n\t\treturn state.getValue(LARGE);\n\t}\n\n\t@Override\n\tpublic BlockState rotate(BlockState state, Rotation rot) {\n\t\tAxis axis = state.getValue(HORIZONTAL_AXIS);\n\t\treturn state.setValue(HORIZONTAL_AXIS, rot.rotate(Direction.fromAxisAndDirection(axis, AxisDirection.POSITIVE))\n\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic BlockState mirror(BlockState state, Mirror mirrorIn) {\n\t\treturn state;\n\t}\n\n\n\tpublic static final SoundType SILENCED_METAL =\n\t\tnew ForgeSoundType(0.1F, 1.5F, () -> SoundEvents.NETHERITE_BLOCK_BREAK, () -> SoundEvents.NETHERITE_BLOCK_STEP,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_PLACE, () -> SoundEvents.NETHERITE_BLOCK_HIT,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_FALL);\n\n\t@Override\n\tpublic SoundType getSoundType(BlockState state, LevelReader world, BlockPos pos, Entity entity) {\n\t\tSoundType soundType = super.getSoundType(state, world, pos, entity);\n\t\tif (entity != null && entity.getPersistentData()\n\t\t\t.contains(\"SilenceVaultSound\"))\n\t\t\treturn SILENCED_METAL;\n\t\treturn soundType;\n\t}\n\n\t@Override\n\tpublic boolean hasAnalogOutputSignal(BlockState p_149740_1_) {\n\t\treturn true;\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"removal\")\n\tpublic int getAnalogOutputSignal(BlockState pState, Level pLevel, BlockPos pPos) {\n\t\treturn getBlockEntityOptional(pLevel, pPos)\n\t\t\t.map(vte -> vte.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY))\n\t\t\t.map(lo -> lo.map(ItemHelper::calcRedstoneFromInventory)\n\t\t\t\t.orElse(0))\n\t\t\t.orElse(0);\n\t}\n\n\t@Override\n\tpublic BlockEntityType<? extends RedContainerBlockEntity> getBlockEntityType() {\n\t\treturn MmbBlockEntities.RED_CONTAINER.get();\n\t}\n\n\t@Override\n\tpublic Class<RedContainerBlockEntity> getBlockEntityClass() {\n\t\treturn RedContainerBlockEntity.class;\n\t}\n\n\n\n\n\n\n}" }, { "identifier": "RedContainerCTBehaviour", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/red/RedContainerCTBehaviour.java", "snippet": "public class RedContainerCTBehaviour extends ConnectedTextureBehaviour.Base {\n\n\t@Override\n\tpublic CTSpriteShiftEntry getShift(BlockState state, Direction direction, @Nullable TextureAtlasSprite sprite) {\n\t\tAxis containerBlockAxis = RedContainerBlock.getContainerBlockAxis(state);\n\t\tboolean small = !RedContainerBlock.isLarge(state);\n\t\tif (containerBlockAxis == null)\n\t\t\treturn null;\n\n\t\tif (direction.getAxis() == containerBlockAxis)\n\t\t\treturn MmbSpriteShifts.RED_CONTAINER_FRONT.get(small);\n\t\tif (direction == Direction.UP)\n\t\t\treturn MmbSpriteShifts.RED_CONTAINER_TOP.get(small);\n\t\tif (direction == Direction.DOWN)\n\t\t\treturn MmbSpriteShifts.RED_CONTAINER_BOTTOM.get(small);\n\n\t\treturn MmbSpriteShifts.RED_CONTAINER_SIDE.get(small);\n\t}\n\n\t@Override\n\tprotected Direction getUpDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = RedContainerBlock.getContainerBlockAxis(state);\n\t\tboolean alongX = containerBlockAxis == Axis.X;\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && alongX)\n\t\t\treturn super.getUpDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getUpDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(containerBlockAxis, alongX ? AxisDirection.POSITIVE : AxisDirection.NEGATIVE);\n\t}\n\n\t@Override\n\tprotected Direction getRightDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = RedContainerBlock.getContainerBlockAxis(state);\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && containerBlockAxis == Axis.X)\n\t\t\treturn super.getRightDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getRightDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(Axis.Y, face.getAxisDirection());\n\t}\n\n\tpublic boolean buildContextForOccludedDirections() {\n\t\treturn super.buildContextForOccludedDirections();\n\t}\n\n\t@Override\n\tpublic boolean connectsTo(BlockState state, BlockState other, BlockAndTintGetter reader, BlockPos pos,\n\t\tBlockPos otherPos, Direction face) {\n\t\treturn state == other && ConnectivityHandler.isConnected(reader, pos, otherPos); //ItemVaultConnectivityHandler.isConnected(reader, pos, otherPos);\n\t}\n\n}" }, { "identifier": "RedContainerItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/red/RedContainerItem.java", "snippet": "public class RedContainerItem extends BlockItem {\n\n\tpublic RedContainerItem(Block p_i48527_1_, Properties p_i48527_2_) {\n\t\tsuper(p_i48527_1_, p_i48527_2_);\n\t}\n\n\t@Override\n\tpublic InteractionResult place(BlockPlaceContext ctx) {\n\t\tInteractionResult initialResult = super.place(ctx);\n\t\tif (!initialResult.consumesAction())\n\t\t\treturn initialResult;\n\t\ttryMultiPlace(ctx);\n\t\treturn initialResult;\n\t}\n\n\t@Override\n\tprotected boolean updateCustomBlockEntityTag(BlockPos p_195943_1_, Level p_195943_2_, Player p_195943_3_,\n\t\tItemStack p_195943_4_, BlockState p_195943_5_) {\n\t\tMinecraftServer minecraftserver = p_195943_2_.getServer();\n\t\tif (minecraftserver == null)\n\t\t\treturn false;\n\t\tCompoundTag nbt = p_195943_4_.getTagElement(\"BlockEntityTag\");\n\t\tif (nbt != null) {\n\t\t\tnbt.remove(\"Length\");\n\t\t\tnbt.remove(\"Size\");\n\t\t\tnbt.remove(\"Controller\");\n\t\t\tnbt.remove(\"LastKnownPos\");\n\t\t}\n\t\treturn super.updateCustomBlockEntityTag(p_195943_1_, p_195943_2_, p_195943_3_, p_195943_4_, p_195943_5_);\n\t}\n\n\tpublic void tryMultiPlace(BlockPlaceContext ctx) {\n\t\tPlayer player = ctx.getPlayer();\n\t\tif (player == null)\n\t\t\treturn;\n\t\tif (player.isSteppingCarefully())\n\t\t\treturn;\n\t\tDirection face = ctx.getClickedFace();\n\t\tItemStack stack = ctx.getItemInHand();\n\t\tLevel world = ctx.getLevel();\n\t\tBlockPos pos = ctx.getClickedPos();\n\t\tBlockPos placedOnPos = pos.relative(face.getOpposite());\n\t\tBlockState placedOnState = world.getBlockState(placedOnPos);\n\n\t\tif (!RedContainerBlock.isContainer(placedOnState))\n\t\t\treturn;\n\t\tRedContainerBlockEntity tankAt = ConnectivityHandler.partAt(MmbBlockEntities.RED_CONTAINER.get(), world, placedOnPos);\n\t\tif (tankAt == null)\n\t\t\treturn;\n\t\tRedContainerBlockEntity controllerBE = tankAt.getControllerBE();\n\t\tif (controllerBE == null)\n\t\t\treturn;\n\n\t\tint width = controllerBE.radius;\n\t\tif (width == 1)\n\t\t\treturn;\n\n\t\tint tanksToPlace = 0;\n\t\tAxis vaultBlockAxis = RedContainerBlock.getContainerBlockAxis(placedOnState);\n\t\tif (vaultBlockAxis == null)\n\t\t\treturn;\n\t\tif (face.getAxis() != vaultBlockAxis)\n\t\t\treturn;\n\n\t\tDirection vaultFacing = Direction.fromAxisAndDirection(vaultBlockAxis, AxisDirection.POSITIVE);\n\t\tBlockPos startPos = face == vaultFacing.getOpposite() ? controllerBE.getBlockPos()\n\t\t\t.relative(vaultFacing.getOpposite())\n\t\t\t: controllerBE.getBlockPos()\n\t\t\t\t.relative(vaultFacing, controllerBE.length);\n\n\t\tif (VecHelper.getCoordinate(startPos, vaultBlockAxis) != VecHelper.getCoordinate(pos, vaultBlockAxis))\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\t\t\t\tif (RedContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!blockState.getMaterial()\n\t\t\t\t\t.isReplaceable())\n\t\t\t\t\treturn;\n\t\t\t\ttanksToPlace++;\n\t\t\t}\n\t\t}\n\n\t\tif (!player.isCreative() && stack.getCount() < tanksToPlace)\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\n\n\t\t\t\tif (RedContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\n\n\t\t\t\tBlockPlaceContext context = BlockPlaceContext.at(ctx, offsetPos, face);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.putBoolean(\"SilenceVaultSound\", true);\n\t\t\t\tsuper.place(context);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.remove(\"SilenceVaultSound\");\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "BlueContainerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/blue/BlueContainerBlock.java", "snippet": "public class BlueContainerBlock extends Block implements IWrenchable, IBE<BlueContainerBlockEntity> {\n\n\tpublic static final Property<Axis> HORIZONTAL_AXIS = BlockStateProperties.HORIZONTAL_AXIS;\n\tpublic static final BooleanProperty LARGE = BooleanProperty.create(\"large\");\n\n\n\tpublic BlueContainerBlock(Properties p_i48440_1_) {\n\t\tsuper(p_i48440_1_);\n\t\tregisterDefaultState(defaultBlockState().setValue(LARGE, false));\n\t}\n\n\t@Override\n\tprotected void createBlockStateDefinition(Builder<Block, BlockState> pBuilder) {\n\t\tpBuilder.add(HORIZONTAL_AXIS, LARGE);\n\t\tsuper.createBlockStateDefinition(pBuilder);\n\t}\n\n\t@Override\n\tpublic BlockState getStateForPlacement(BlockPlaceContext pContext) {\n\t\tif (pContext.getPlayer() == null || !pContext.getPlayer()\n\t\t\t.isSteppingCarefully()) {\n\t\t\tBlockState placedOn = pContext.getLevel()\n\t\t\t\t.getBlockState(pContext.getClickedPos()\n\t\t\t\t\t.relative(pContext.getClickedFace()\n\t\t\t\t\t\t.getOpposite()));\n\t\t\tAxis preferredAxis = getContainerBlockAxis(placedOn);\n\t\t\tif (preferredAxis != null)\n\t\t\t\treturn this.defaultBlockState()\n\t\t\t\t\t.setValue(HORIZONTAL_AXIS, preferredAxis);\n\t\t}\n\t\treturn this.defaultBlockState()\n\t\t\t.setValue(HORIZONTAL_AXIS, pContext.getHorizontalDirection()\n\t\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic void onPlace(BlockState pState, Level pLevel, BlockPos pPos, BlockState pOldState, boolean pIsMoving) {\n\t\tif (pOldState.getBlock() == pState.getBlock())\n\t\t\treturn;\n\t\tif (pIsMoving)\n\t\t\treturn;\n\t\twithBlockEntityDo(pLevel, pPos, BlueContainerBlockEntity::updateConnectivity);\n\t}\n\n\t@Override\n\tpublic InteractionResult onWrenched(BlockState state, UseOnContext context) {\n\t\tif (context.getClickedFace()\n\t\t\t.getAxis()\n\t\t\t.isVertical()) {\n\t\t\tBlockEntity be = context.getLevel()\n\t\t\t\t.getBlockEntity(context.getClickedPos());\n\t\t\tif (be instanceof BlueContainerBlockEntity) {\n\t\t\t\tBlueContainerBlockEntity container = (BlueContainerBlockEntity) be;\n\t\t\t\tConnectivityHandler.splitMulti(container);\n\t\t\t\tcontainer.removeController(true);\n\t\t\t}\n\t\t\tstate = state.setValue(LARGE, false);\n\t\t}\n\t\tInteractionResult onWrenched = IWrenchable.super.onWrenched(state, context);\n\t\treturn onWrenched;\n\t}\n\n\t@Override\n\tpublic void onRemove(BlockState state, Level world, BlockPos pos, BlockState newState, boolean pIsMoving) {\n\t\tif (state.hasBlockEntity() && (state.getBlock() != newState.getBlock() || !newState.hasBlockEntity())) {\n\t\t\tBlockEntity be = world.getBlockEntity(pos);\n\t\t\tif (!(be instanceof BlueContainerBlockEntity))\n\t\t\t\treturn;\n\t\t\tBlueContainerBlockEntity containerBE = (BlueContainerBlockEntity) be;\n\t\t\tItemHelper.dropContents(world, pos, containerBE.inventory);\n\t\t\tworld.removeBlockEntity(pos);\n\t\t\tConnectivityHandler.splitMulti(containerBE);\n\t\t}\n\t}\n\n\tpublic static boolean isContainer(BlockState state) {\n\n\n\t\treturn MmbBlocks.BLUE_CONTAINER.has(state);\n\t}\n\n\t@Nullable\n\tpublic static Axis getContainerBlockAxis(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn null;\n\t\treturn state.getValue(HORIZONTAL_AXIS);\n\t}\n\n\tpublic static boolean isLarge(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn false;\n\t\treturn state.getValue(LARGE);\n\t}\n\n\t@Override\n\tpublic BlockState rotate(BlockState state, Rotation rot) {\n\t\tAxis axis = state.getValue(HORIZONTAL_AXIS);\n\t\treturn state.setValue(HORIZONTAL_AXIS, rot.rotate(Direction.fromAxisAndDirection(axis, AxisDirection.POSITIVE))\n\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic BlockState mirror(BlockState state, Mirror mirrorIn) {\n\t\treturn state;\n\t}\n\n\n\tpublic static final SoundType SILENCED_METAL =\n\t\tnew ForgeSoundType(0.1F, 1.5F, () -> SoundEvents.NETHERITE_BLOCK_BREAK, () -> SoundEvents.NETHERITE_BLOCK_STEP,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_PLACE, () -> SoundEvents.NETHERITE_BLOCK_HIT,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_FALL);\n\n\t@Override\n\tpublic SoundType getSoundType(BlockState state, LevelReader world, BlockPos pos, Entity entity) {\n\t\tSoundType soundType = super.getSoundType(state, world, pos, entity);\n\t\tif (entity != null && entity.getPersistentData()\n\t\t\t.contains(\"SilenceVaultSound\"))\n\t\t\treturn SILENCED_METAL;\n\t\treturn soundType;\n\t}\n\n\t@Override\n\tpublic boolean hasAnalogOutputSignal(BlockState p_149740_1_) {\n\t\treturn true;\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"removal\")\n\tpublic int getAnalogOutputSignal(BlockState pState, Level pLevel, BlockPos pPos) {\n\t\treturn getBlockEntityOptional(pLevel, pPos)\n\t\t\t.map(vte -> vte.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY))\n\t\t\t.map(lo -> lo.map(ItemHelper::calcRedstoneFromInventory)\n\t\t\t\t.orElse(0))\n\t\t\t.orElse(0);\n\t}\n\n\t@Override\n\tpublic BlockEntityType<? extends BlueContainerBlockEntity> getBlockEntityType() {\n\t\treturn MmbBlockEntities.BLUE_CONTAINER.get();\n\t}\n\n\t@Override\n\tpublic Class<BlueContainerBlockEntity> getBlockEntityClass() {\n\t\treturn BlueContainerBlockEntity.class;\n\t}\n\n\n\n\n\n\n}" }, { "identifier": "BlueContainerCTBehaviour", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/blue/BlueContainerCTBehaviour.java", "snippet": "public class BlueContainerCTBehaviour extends ConnectedTextureBehaviour.Base {\n\n\t@Override\n\tpublic CTSpriteShiftEntry getShift(BlockState state, Direction direction, @Nullable TextureAtlasSprite sprite) {\n\t\tAxis containerBlockAxis = BlueContainerBlock.getContainerBlockAxis(state);\n\t\tboolean small = !BlueContainerBlock.isLarge(state);\n\t\tif (containerBlockAxis == null)\n\t\t\treturn null;\n\n\t\tif (direction.getAxis() == containerBlockAxis)\n\t\t\treturn MmbSpriteShifts.BLUE_CONTAINER_FRONT.get(small);\n\t\tif (direction == Direction.UP)\n\t\t\treturn MmbSpriteShifts.BLUE_CONTAINER_TOP.get(small);\n\t\tif (direction == Direction.DOWN)\n\t\t\treturn MmbSpriteShifts.BLUE_CONTAINER_BOTTOM.get(small);\n\n\t\treturn MmbSpriteShifts.BLUE_CONTAINER_SIDE.get(small);\n\t}\n\n\t@Override\n\tprotected Direction getUpDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = BlueContainerBlock.getContainerBlockAxis(state);\n\t\tboolean alongX = containerBlockAxis == Axis.X;\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && alongX)\n\t\t\treturn super.getUpDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getUpDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(containerBlockAxis, alongX ? AxisDirection.POSITIVE : AxisDirection.NEGATIVE);\n\t}\n\n\t@Override\n\tprotected Direction getRightDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = BlueContainerBlock.getContainerBlockAxis(state);\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && containerBlockAxis == Axis.X)\n\t\t\treturn super.getRightDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getRightDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(Axis.Y, face.getAxisDirection());\n\t}\n\n\tpublic boolean buildContextForOccludedDirections() {\n\t\treturn super.buildContextForOccludedDirections();\n\t}\n\n\t@Override\n\tpublic boolean connectsTo(BlockState state, BlockState other, BlockAndTintGetter reader, BlockPos pos,\n\t\tBlockPos otherPos, Direction face) {\n\t\treturn state == other && ConnectivityHandler.isConnected(reader, pos, otherPos); //ItemVaultConnectivityHandler.isConnected(reader, pos, otherPos);\n\t}\n\n}" }, { "identifier": "BlueContainerItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/blue/BlueContainerItem.java", "snippet": "public class BlueContainerItem extends BlockItem {\n\n\tpublic BlueContainerItem(Block p_i48527_1_, Properties p_i48527_2_) {\n\t\tsuper(p_i48527_1_, p_i48527_2_);\n\t}\n\n\t@Override\n\tpublic InteractionResult place(BlockPlaceContext ctx) {\n\t\tInteractionResult initialResult = super.place(ctx);\n\t\tif (!initialResult.consumesAction())\n\t\t\treturn initialResult;\n\t\ttryMultiPlace(ctx);\n\t\treturn initialResult;\n\t}\n\n\t@Override\n\tprotected boolean updateCustomBlockEntityTag(BlockPos p_195943_1_, Level p_195943_2_, Player p_195943_3_,\n\t\tItemStack p_195943_4_, BlockState p_195943_5_) {\n\t\tMinecraftServer minecraftserver = p_195943_2_.getServer();\n\t\tif (minecraftserver == null)\n\t\t\treturn false;\n\t\tCompoundTag nbt = p_195943_4_.getTagElement(\"BlockEntityTag\");\n\t\tif (nbt != null) {\n\t\t\tnbt.remove(\"Length\");\n\t\t\tnbt.remove(\"Size\");\n\t\t\tnbt.remove(\"Controller\");\n\t\t\tnbt.remove(\"LastKnownPos\");\n\t\t}\n\t\treturn super.updateCustomBlockEntityTag(p_195943_1_, p_195943_2_, p_195943_3_, p_195943_4_, p_195943_5_);\n\t}\n\n\tpublic void tryMultiPlace(BlockPlaceContext ctx) {\n\t\tPlayer player = ctx.getPlayer();\n\t\tif (player == null)\n\t\t\treturn;\n\t\tif (player.isSteppingCarefully())\n\t\t\treturn;\n\t\tDirection face = ctx.getClickedFace();\n\t\tItemStack stack = ctx.getItemInHand();\n\t\tLevel world = ctx.getLevel();\n\t\tBlockPos pos = ctx.getClickedPos();\n\t\tBlockPos placedOnPos = pos.relative(face.getOpposite());\n\t\tBlockState placedOnState = world.getBlockState(placedOnPos);\n\n\t\tif (!BlueContainerBlock.isContainer(placedOnState))\n\t\t\treturn;\n\t\tBlueContainerBlockEntity tankAt = ConnectivityHandler.partAt(MmbBlockEntities.BLUE_CONTAINER.get(), world, placedOnPos);\n\t\tif (tankAt == null)\n\t\t\treturn;\n\t\tBlueContainerBlockEntity controllerBE = tankAt.getControllerBE();\n\t\tif (controllerBE == null)\n\t\t\treturn;\n\n\t\tint width = controllerBE.radius;\n\t\tif (width == 1)\n\t\t\treturn;\n\n\t\tint tanksToPlace = 0;\n\t\tAxis vaultBlockAxis = BlueContainerBlock.getContainerBlockAxis(placedOnState);\n\t\tif (vaultBlockAxis == null)\n\t\t\treturn;\n\t\tif (face.getAxis() != vaultBlockAxis)\n\t\t\treturn;\n\n\t\tDirection vaultFacing = Direction.fromAxisAndDirection(vaultBlockAxis, AxisDirection.POSITIVE);\n\t\tBlockPos startPos = face == vaultFacing.getOpposite() ? controllerBE.getBlockPos()\n\t\t\t.relative(vaultFacing.getOpposite())\n\t\t\t: controllerBE.getBlockPos()\n\t\t\t\t.relative(vaultFacing, controllerBE.length);\n\n\t\tif (VecHelper.getCoordinate(startPos, vaultBlockAxis) != VecHelper.getCoordinate(pos, vaultBlockAxis))\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\t\t\t\tif (BlueContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!blockState.getMaterial()\n\t\t\t\t\t.isReplaceable())\n\t\t\t\t\treturn;\n\t\t\t\ttanksToPlace++;\n\t\t\t}\n\t\t}\n\n\t\tif (!player.isCreative() && stack.getCount() < tanksToPlace)\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\n\n\t\t\t\tif (BlueContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\n\n\t\t\t\tBlockPlaceContext context = BlockPlaceContext.at(ctx, offsetPos, face);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.putBoolean(\"SilenceVaultSound\", true);\n\t\t\t\tsuper.place(context);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.remove(\"SilenceVaultSound\");\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "GreenContainerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/green/GreenContainerBlock.java", "snippet": "public class GreenContainerBlock extends Block implements IWrenchable, IBE<GreenContainerBlockEntity> {\n\n\tpublic static final Property<Axis> HORIZONTAL_AXIS = BlockStateProperties.HORIZONTAL_AXIS;\n\tpublic static final BooleanProperty LARGE = BooleanProperty.create(\"large\");\n\n\n\tpublic GreenContainerBlock(Properties p_i48440_1_) {\n\t\tsuper(p_i48440_1_);\n\t\tregisterDefaultState(defaultBlockState().setValue(LARGE, false));\n\t}\n\n\t@Override\n\tprotected void createBlockStateDefinition(Builder<Block, BlockState> pBuilder) {\n\t\tpBuilder.add(HORIZONTAL_AXIS, LARGE);\n\t\tsuper.createBlockStateDefinition(pBuilder);\n\t}\n\n\t@Override\n\tpublic BlockState getStateForPlacement(BlockPlaceContext pContext) {\n\t\tif (pContext.getPlayer() == null || !pContext.getPlayer()\n\t\t\t.isSteppingCarefully()) {\n\t\t\tBlockState placedOn = pContext.getLevel()\n\t\t\t\t.getBlockState(pContext.getClickedPos()\n\t\t\t\t\t.relative(pContext.getClickedFace()\n\t\t\t\t\t\t.getOpposite()));\n\t\t\tAxis preferredAxis = getContainerBlockAxis(placedOn);\n\t\t\tif (preferredAxis != null)\n\t\t\t\treturn this.defaultBlockState()\n\t\t\t\t\t.setValue(HORIZONTAL_AXIS, preferredAxis);\n\t\t}\n\t\treturn this.defaultBlockState()\n\t\t\t.setValue(HORIZONTAL_AXIS, pContext.getHorizontalDirection()\n\t\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic void onPlace(BlockState pState, Level pLevel, BlockPos pPos, BlockState pOldState, boolean pIsMoving) {\n\t\tif (pOldState.getBlock() == pState.getBlock())\n\t\t\treturn;\n\t\tif (pIsMoving)\n\t\t\treturn;\n\t\twithBlockEntityDo(pLevel, pPos, GreenContainerBlockEntity::updateConnectivity);\n\t}\n\n\t@Override\n\tpublic InteractionResult onWrenched(BlockState state, UseOnContext context) {\n\t\tif (context.getClickedFace()\n\t\t\t.getAxis()\n\t\t\t.isVertical()) {\n\t\t\tBlockEntity be = context.getLevel()\n\t\t\t\t.getBlockEntity(context.getClickedPos());\n\t\t\tif (be instanceof GreenContainerBlockEntity) {\n\t\t\t\tGreenContainerBlockEntity container = (GreenContainerBlockEntity) be;\n\t\t\t\tConnectivityHandler.splitMulti(container);\n\t\t\t\tcontainer.removeController(true);\n\t\t\t}\n\t\t\tstate = state.setValue(LARGE, false);\n\t\t}\n\t\tInteractionResult onWrenched = IWrenchable.super.onWrenched(state, context);\n\t\treturn onWrenched;\n\t}\n\n\t@Override\n\tpublic void onRemove(BlockState state, Level world, BlockPos pos, BlockState newState, boolean pIsMoving) {\n\t\tif (state.hasBlockEntity() && (state.getBlock() != newState.getBlock() || !newState.hasBlockEntity())) {\n\t\t\tBlockEntity be = world.getBlockEntity(pos);\n\t\t\tif (!(be instanceof GreenContainerBlockEntity))\n\t\t\t\treturn;\n\t\t\tGreenContainerBlockEntity containerBE = (GreenContainerBlockEntity) be;\n\t\t\tItemHelper.dropContents(world, pos, containerBE.inventory);\n\t\t\tworld.removeBlockEntity(pos);\n\t\t\tConnectivityHandler.splitMulti(containerBE);\n\t\t}\n\t}\n\n\tpublic static boolean isContainer(BlockState state) {\n\n\n\t\treturn MmbBlocks.GREEN_CONTAINER.has(state);\n\t}\n\n\t@Nullable\n\tpublic static Axis getContainerBlockAxis(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn null;\n\t\treturn state.getValue(HORIZONTAL_AXIS);\n\t}\n\n\tpublic static boolean isLarge(BlockState state) {\n\t\tif (!isContainer(state))\n\t\t\treturn false;\n\t\treturn state.getValue(LARGE);\n\t}\n\n\t@Override\n\tpublic BlockState rotate(BlockState state, Rotation rot) {\n\t\tAxis axis = state.getValue(HORIZONTAL_AXIS);\n\t\treturn state.setValue(HORIZONTAL_AXIS, rot.rotate(Direction.fromAxisAndDirection(axis, AxisDirection.POSITIVE))\n\t\t\t.getAxis());\n\t}\n\n\t@Override\n\tpublic BlockState mirror(BlockState state, Mirror mirrorIn) {\n\t\treturn state;\n\t}\n\n\n\tpublic static final SoundType SILENCED_METAL =\n\t\tnew ForgeSoundType(0.1F, 1.5F, () -> SoundEvents.NETHERITE_BLOCK_BREAK, () -> SoundEvents.NETHERITE_BLOCK_STEP,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_PLACE, () -> SoundEvents.NETHERITE_BLOCK_HIT,\n\t\t\t() -> SoundEvents.NETHERITE_BLOCK_FALL);\n\n\t@Override\n\tpublic SoundType getSoundType(BlockState state, LevelReader world, BlockPos pos, Entity entity) {\n\t\tSoundType soundType = super.getSoundType(state, world, pos, entity);\n\t\tif (entity != null && entity.getPersistentData()\n\t\t\t.contains(\"SilenceVaultSound\"))\n\t\t\treturn SILENCED_METAL;\n\t\treturn soundType;\n\t}\n\n\t@Override\n\tpublic boolean hasAnalogOutputSignal(BlockState p_149740_1_) {\n\t\treturn true;\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"removal\")\n\tpublic int getAnalogOutputSignal(BlockState pState, Level pLevel, BlockPos pPos) {\n\t\treturn getBlockEntityOptional(pLevel, pPos)\n\t\t\t.map(vte -> vte.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY))\n\t\t\t.map(lo -> lo.map(ItemHelper::calcRedstoneFromInventory)\n\t\t\t\t.orElse(0))\n\t\t\t.orElse(0);\n\t}\n\n\t@Override\n\tpublic BlockEntityType<? extends GreenContainerBlockEntity> getBlockEntityType() {\n\t\treturn MmbBlockEntities.GREEN_CONTAINER.get();\n\t}\n\n\t@Override\n\tpublic Class<GreenContainerBlockEntity> getBlockEntityClass() {\n\t\treturn GreenContainerBlockEntity.class;\n\t}\n\n\n\n\n\n\n}" }, { "identifier": "GreenContainerCTBehaviour", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/green/GreenContainerCTBehaviour.java", "snippet": "public class GreenContainerCTBehaviour extends ConnectedTextureBehaviour.Base {\n\n\t@Override\n\tpublic CTSpriteShiftEntry getShift(BlockState state, Direction direction, @Nullable TextureAtlasSprite sprite) {\n\t\tAxis containerBlockAxis = GreenContainerBlock.getContainerBlockAxis(state);\n\t\tboolean small = !GreenContainerBlock.isLarge(state);\n\t\tif (containerBlockAxis == null)\n\t\t\treturn null;\n\n\t\tif (direction.getAxis() == containerBlockAxis)\n\t\t\treturn MmbSpriteShifts.GREEN_CONTAINER_FRONT.get(small);\n\t\tif (direction == Direction.UP)\n\t\t\treturn MmbSpriteShifts.GREEN_CONTAINER_TOP.get(small);\n\t\tif (direction == Direction.DOWN)\n\t\t\treturn MmbSpriteShifts.GREEN_CONTAINER_BOTTOM.get(small);\n\n\t\treturn MmbSpriteShifts.GREEN_CONTAINER_SIDE.get(small);\n\t}\n\n\t@Override\n\tprotected Direction getUpDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = GreenContainerBlock.getContainerBlockAxis(state);\n\t\tboolean alongX = containerBlockAxis == Axis.X;\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && alongX)\n\t\t\treturn super.getUpDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getUpDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(containerBlockAxis, alongX ? AxisDirection.POSITIVE : AxisDirection.NEGATIVE);\n\t}\n\n\t@Override\n\tprotected Direction getRightDirection(BlockAndTintGetter reader, BlockPos pos, BlockState state, Direction face) {\n\t\tAxis containerBlockAxis = GreenContainerBlock.getContainerBlockAxis(state);\n\t\tif (face.getAxis()\n\t\t\t.isVertical() && containerBlockAxis == Axis.X)\n\t\t\treturn super.getRightDirection(reader, pos, state, face).getClockWise();\n\t\tif (face.getAxis() == containerBlockAxis || face.getAxis()\n\t\t\t.isVertical())\n\t\t\treturn super.getRightDirection(reader, pos, state, face);\n\t\treturn Direction.fromAxisAndDirection(Axis.Y, face.getAxisDirection());\n\t}\n\n\tpublic boolean buildContextForOccludedDirections() {\n\t\treturn super.buildContextForOccludedDirections();\n\t}\n\n\t@Override\n\tpublic boolean connectsTo(BlockState state, BlockState other, BlockAndTintGetter reader, BlockPos pos,\n\t\tBlockPos otherPos, Direction face) {\n\t\treturn state == other && ConnectivityHandler.isConnected(reader, pos, otherPos); //ItemVaultConnectivityHandler.isConnected(reader, pos, otherPos);\n\t}\n\n}" }, { "identifier": "GreenContainerItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/green/GreenContainerItem.java", "snippet": "public class GreenContainerItem extends BlockItem {\n\n\tpublic GreenContainerItem(Block p_i48527_1_, Properties p_i48527_2_) {\n\t\tsuper(p_i48527_1_, p_i48527_2_);\n\t}\n\n\t@Override\n\tpublic InteractionResult place(BlockPlaceContext ctx) {\n\t\tInteractionResult initialResult = super.place(ctx);\n\t\tif (!initialResult.consumesAction())\n\t\t\treturn initialResult;\n\t\ttryMultiPlace(ctx);\n\t\treturn initialResult;\n\t}\n\n\t@Override\n\tprotected boolean updateCustomBlockEntityTag(BlockPos p_195943_1_, Level p_195943_2_, Player p_195943_3_,\n\t\tItemStack p_195943_4_, BlockState p_195943_5_) {\n\t\tMinecraftServer minecraftserver = p_195943_2_.getServer();\n\t\tif (minecraftserver == null)\n\t\t\treturn false;\n\t\tCompoundTag nbt = p_195943_4_.getTagElement(\"BlockEntityTag\");\n\t\tif (nbt != null) {\n\t\t\tnbt.remove(\"Length\");\n\t\t\tnbt.remove(\"Size\");\n\t\t\tnbt.remove(\"Controller\");\n\t\t\tnbt.remove(\"LastKnownPos\");\n\t\t}\n\t\treturn super.updateCustomBlockEntityTag(p_195943_1_, p_195943_2_, p_195943_3_, p_195943_4_, p_195943_5_);\n\t}\n\n\tpublic void tryMultiPlace(BlockPlaceContext ctx) {\n\t\tPlayer player = ctx.getPlayer();\n\t\tif (player == null)\n\t\t\treturn;\n\t\tif (player.isSteppingCarefully())\n\t\t\treturn;\n\t\tDirection face = ctx.getClickedFace();\n\t\tItemStack stack = ctx.getItemInHand();\n\t\tLevel world = ctx.getLevel();\n\t\tBlockPos pos = ctx.getClickedPos();\n\t\tBlockPos placedOnPos = pos.relative(face.getOpposite());\n\t\tBlockState placedOnState = world.getBlockState(placedOnPos);\n\n\t\tif (!GreenContainerBlock.isContainer(placedOnState))\n\t\t\treturn;\n\t\tGreenContainerBlockEntity tankAt = ConnectivityHandler.partAt(MmbBlockEntities.GREEN_CONTAINER.get(), world, placedOnPos);\n\t\tif (tankAt == null)\n\t\t\treturn;\n\t\tGreenContainerBlockEntity controllerBE = tankAt.getControllerBE();\n\t\tif (controllerBE == null)\n\t\t\treturn;\n\n\t\tint width = controllerBE.radius;\n\t\tif (width == 1)\n\t\t\treturn;\n\n\t\tint tanksToPlace = 0;\n\t\tAxis vaultBlockAxis = GreenContainerBlock.getContainerBlockAxis(placedOnState);\n\t\tif (vaultBlockAxis == null)\n\t\t\treturn;\n\t\tif (face.getAxis() != vaultBlockAxis)\n\t\t\treturn;\n\n\t\tDirection vaultFacing = Direction.fromAxisAndDirection(vaultBlockAxis, AxisDirection.POSITIVE);\n\t\tBlockPos startPos = face == vaultFacing.getOpposite() ? controllerBE.getBlockPos()\n\t\t\t.relative(vaultFacing.getOpposite())\n\t\t\t: controllerBE.getBlockPos()\n\t\t\t\t.relative(vaultFacing, controllerBE.length);\n\n\t\tif (VecHelper.getCoordinate(startPos, vaultBlockAxis) != VecHelper.getCoordinate(pos, vaultBlockAxis))\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\t\t\t\tif (GreenContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!blockState.getMaterial()\n\t\t\t\t\t.isReplaceable())\n\t\t\t\t\treturn;\n\t\t\t\ttanksToPlace++;\n\t\t\t}\n\t\t}\n\n\t\tif (!player.isCreative() && stack.getCount() < tanksToPlace)\n\t\t\treturn;\n\n\t\tfor (int xOffset = 0; xOffset < width; xOffset++) {\n\t\t\tfor (int zOffset = 0; zOffset < width; zOffset++) {\n\t\t\t\tBlockPos offsetPos = vaultBlockAxis == Axis.X ? startPos.offset(0, xOffset, zOffset)\n\t\t\t\t\t: startPos.offset(xOffset, zOffset, 0);\n\t\t\t\tBlockState blockState = world.getBlockState(offsetPos);\n\n\n\t\t\t\tif (GreenContainerBlock.isContainer(blockState))\n\t\t\t\t\tcontinue;\n\n\n\t\t\t\tBlockPlaceContext context = BlockPlaceContext.at(ctx, offsetPos, face);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.putBoolean(\"SilenceVaultSound\", true);\n\t\t\t\tsuper.place(context);\n\t\t\t\tplayer.getPersistentData()\n\t\t\t\t\t.remove(\"SilenceVaultSound\");\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "MmbCrushingWheelBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/crushing_wheels/MmbCrushingWheelBlock.java", "snippet": "public class MmbCrushingWheelBlock extends CrushingWheelBlock {\n\n\tpublic MmbCrushingWheelBlock(Properties properties) {\n\t\tsuper(properties);\n\t}\n\n\n\t@Override\n\tpublic void onRemove(BlockState state, Level worldIn, BlockPos pos, BlockState newState, boolean isMoving) {\n\t\tfor (Direction d : Iterate.directions) {\n\t\t\tif (d.getAxis() == state.getValue(AXIS))\n\t\t\t\tcontinue;\n\t\t\tif (MmbBlocks.MMB_CRUSHING_WHEEL_CONTROLLER.has(worldIn.getBlockState(pos.relative(d))))\n\t\t\t\tworldIn.removeBlock(pos.relative(d), isMoving);\n\t\t\tif (AllBlocks.CRUSHING_WHEEL_CONTROLLER.has(worldIn.getBlockState(pos.relative(d))))\n\t\t\t\tworldIn.removeBlock(pos.relative(d), isMoving);\n\t\t}\n\n\t\tsuper.onRemove(state, worldIn, pos, newState, isMoving);\n\t}\n\n\n\tpublic void updateControllers(BlockState state, Level world, BlockPos pos, Direction side) {\n\t\tif (side.getAxis() == state.getValue(AXIS))\n\t\t\treturn;\n\t\tif (world == null)\n\t\t\treturn;\n\n\t\tBlockPos controllerPos = pos.relative(side);\n\t\tBlockPos otherWheelPos = pos.relative(side, 2);\n\n\t\tboolean controllerExists =\n\t\t\t\tMmbBlocks.MMB_CRUSHING_WHEEL_CONTROLLER.has(world.getBlockState(controllerPos));\n\t\tboolean controllerIsValid = controllerExists && world.getBlockState(controllerPos)\n\t\t\t\t.getValue(VALID);\n\t\tDirection controllerOldDirection = controllerExists ? world.getBlockState(controllerPos)\n\t\t\t\t.getValue(CrushingWheelControllerBlock.FACING) : null;\n\n\t\tboolean controllerShouldExist = false;\n\t\tboolean controllerShouldBeValid = false;\n\t\tDirection controllerNewDirection = Direction.DOWN;\n\n\t\tBlockState otherState = world.getBlockState(otherWheelPos);\n\t\tif (\n\t\t\t\tAllBlocks.CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.GRANITE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.DIORITE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.LIMESTONE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.OCHRUM_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.SCORCHIA_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.SCORIA_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.TUFF_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.VERIDIUM_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.DRIPSTONE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.DEEPSLATE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.CRIMSITE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.CALCITE_CRUSHING_WHEEL.has(otherState)||\n\t\t\t\tMmbBlocks.ASURINE_CRUSHING_WHEEL.has(otherState)\n\n\t\t) {\n\t\t\tcontrollerShouldExist = true;\n\n\t\t\tCrushingWheelBlockEntity be = getBlockEntity(world, pos);\n\t\t\tCrushingWheelBlockEntity otherBE = getBlockEntity(world, otherWheelPos);\n\n\t\t\tif (be != null && otherBE != null && (be.getSpeed() > 0) != (otherBE.getSpeed() > 0)\n\t\t\t\t\t&& be.getSpeed() != 0) {\n\t\t\t\tAxis wheelAxis = state.getValue(AXIS);\n\t\t\t\tAxis sideAxis = side.getAxis();\n\t\t\t\tint controllerADO = Math.round(Math.signum(be.getSpeed())) * side.getAxisDirection()\n\t\t\t\t\t\t.getStep();\n\t\t\t\tVec3 controllerDirVec = new Vec3(wheelAxis == Axis.X ? 1 : 0, wheelAxis == Axis.Y ? 1 : 0,\n\t\t\t\t\t\twheelAxis == Axis.Z ? 1 : 0).cross(\n\t\t\t\t\t\tnew Vec3(sideAxis == Axis.X ? 1 : 0, sideAxis == Axis.Y ? 1 : 0, sideAxis == Axis.Z ? 1 : 0));\n\n\t\t\t\tcontrollerNewDirection = Direction.getNearest(controllerDirVec.x * controllerADO,\n\t\t\t\t\t\tcontrollerDirVec.y * controllerADO, controllerDirVec.z * controllerADO);\n\n\t\t\t\tcontrollerShouldBeValid = true;\n\t\t\t}\n\t\t\tif (otherState.getValue(AXIS) != state.getValue(AXIS))\n\t\t\t\tcontrollerShouldExist = false;\n\t\t}\n\n\t\tif (!controllerShouldExist) {\n\t\t\tif (controllerExists)\n\t\t\t\tworld.setBlockAndUpdate(controllerPos, Blocks.AIR.defaultBlockState());\n\t\t\treturn;\n\t\t}\n\n\t\tif (!controllerExists) {\n\t\t\tif (!world.getBlockState(controllerPos)\n\t\t\t\t\t.getMaterial()\n\t\t\t\t\t.isReplaceable())\n\t\t\t\treturn;\n\t\t\tworld.setBlockAndUpdate(controllerPos, MmbBlocks.MMB_CRUSHING_WHEEL_CONTROLLER.getDefaultState()\n\t\t\t\t\t.setValue(VALID, controllerShouldBeValid)\n\t\t\t\t\t.setValue(CrushingWheelControllerBlock.FACING, controllerNewDirection));\n\t\t} else if (controllerIsValid != controllerShouldBeValid || controllerOldDirection != controllerNewDirection) {\n\t\t\tworld.setBlockAndUpdate(controllerPos, world.getBlockState(controllerPos)\n\t\t\t\t\t.setValue(VALID, controllerShouldBeValid)\n\t\t\t\t\t.setValue(CrushingWheelControllerBlock.FACING, controllerNewDirection));\n\t\t}\n\n\t\t( MmbBlocks.MMB_CRUSHING_WHEEL_CONTROLLER.get())\n\t\t\t\t.updateSpeed(world.getBlockState(controllerPos), world, controllerPos);\n\n\t}\n\n\n\t@Override\n\tpublic boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) {\n\t\tfor (Direction direction : Iterate.directions) {\n\t\t\tBlockPos neighbourPos = pos.relative(direction);\n\t\t\tBlockState neighbourState = worldIn.getBlockState(neighbourPos);\n\t\t\tAxis stateAxis = state.getValue(AXIS);\n\t\t\tif (MmbBlocks.MMB_CRUSHING_WHEEL_CONTROLLER.has(neighbourState) && direction.getAxis() != stateAxis)\n\t\t\t\treturn false;\n\t\t\tif (AllBlocks.CRUSHING_WHEEL_CONTROLLER.has(neighbourState) && direction.getAxis() != stateAxis)\n\t\t\t\treturn false;\n\t\t\tif (!(worldIn.getBlockState(neighbourPos).getBlock() instanceof CrushingWheelBlock))\n\t\t\t\tcontinue;\n\t\t\tif (neighbourState.getValue(AXIS) != stateAxis || stateAxis != direction.getAxis())\n\t\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic Class<CrushingWheelBlockEntity> getBlockEntityClass() {\n\t\treturn CrushingWheelBlockEntity.class;\n\t}\n\t\n\t@Override\n\tpublic BlockEntityType<? extends CrushingWheelBlockEntity> getBlockEntityType() {\n\t\treturn MmbBlockEntities.MMB_CRUSHING_WHEEL.get();\n\t}\n\n}" }, { "identifier": "MmbCrushingWheelControllerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/crushing_wheels/MmbCrushingWheelControllerBlock.java", "snippet": "public class MmbCrushingWheelControllerBlock extends CrushingWheelControllerBlock {\n\n\tpublic MmbCrushingWheelControllerBlock(Properties p_i48440_1_) {\n\t\tsuper(p_i48440_1_);\n\t}\n\n\n\t@Override\n\tpublic boolean canBeReplaced(BlockState state, BlockPlaceContext useContext) {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean addRunningEffects(BlockState state, Level world, BlockPos pos, Entity entity) {\n\t\treturn true;\n\t}\n\n\t@Override\n\tprotected void createBlockStateDefinition(Builder<Block, BlockState> builder) {\n\t\tsuper.createBlockStateDefinition(builder);\n\t}\n\n\tpublic void entityInside(BlockState state, Level worldIn, BlockPos pos, Entity entityIn) {\n\t\tif (!state.getValue(VALID))\n\t\t\treturn;\n\n\t\tDirection facing = state.getValue(FACING);\n\t\tAxis axis = facing.getAxis();\n\n\t\tcheckEntityForProcessing(worldIn, pos, entityIn);\n\n\t\twithBlockEntityDo(worldIn, pos, be -> {\n\t\t\tif (be.processingEntity == entityIn)\n\n\t\t\t\tentityIn.makeStuckInBlock(state, new Vec3(axis == Axis.X ? (double) 0.05F : 0.25D,\n\t\t\t\t\taxis == Axis.Y ? (double) 0.05F : 0.25D, axis == Axis.Z ? (double) 0.05F : 0.25D));\n\t\t});\n\t}\n\n\tpublic void checkEntityForProcessing(Level worldIn, BlockPos pos, Entity entityIn) {\n\t\tCrushingWheelControllerBlockEntity be = getBlockEntity(worldIn, pos);\n\t\tif (be == null)\n\t\t\treturn;\n\t\tif (be.crushingspeed == 0)\n\t\t\treturn;\n//\t\tif (entityIn instanceof ItemEntity)\n//\t\t\t((ItemEntity) entityIn).setPickUpDelay(10);\n\t\tCompoundTag data = entityIn.getPersistentData();\n\t\tif (data.contains(\"BypassCrushingWheel\")) {\n\t\t\tif (pos.equals(NbtUtils.readBlockPos(data.getCompound(\"BypassCrushingWheel\"))))\n\t\t\t\treturn;\n\t\t}\n\t\tif (be.isOccupied())\n\t\t\treturn;\n\t\tboolean isPlayer = entityIn instanceof Player;\n\t\tif (isPlayer && ((Player) entityIn).isCreative())\n\t\t\treturn;\n\t\tif (isPlayer && entityIn.level.getDifficulty() == Difficulty.PEACEFUL)\n\t\t\treturn;\n\n\t\tbe.startCrushing(entityIn);\n\t}\n\n\t@Override\n\tpublic void updateEntityAfterFallOn(BlockGetter worldIn, Entity entityIn) {\n\t\tsuper.updateEntityAfterFallOn(worldIn, entityIn);\n\t\t// Moved to onEntityCollision to allow for omnidirectional input\n\t}\n\n\t@Override\n\tpublic void animateTick(BlockState stateIn, Level worldIn, BlockPos pos, RandomSource rand) {\n\t\tif (!stateIn.getValue(VALID))\n\t\t\treturn;\n\t\tif (rand.nextInt(1) != 0)\n\t\t\treturn;\n\t\tdouble d0 = (double) ((float) pos.getX() + rand.nextFloat());\n\t\tdouble d1 = (double) ((float) pos.getY() + rand.nextFloat());\n\t\tdouble d2 = (double) ((float) pos.getZ() + rand.nextFloat());\n\t\tworldIn.addParticle(ParticleTypes.CRIT, d0, d1, d2, 0.0D, 0.0D, 0.0D);\n\t}\n\n\t@Override\n\tpublic BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn,\n\t\tBlockPos currentPos, BlockPos facingPos) {\n\t\tupdateSpeed(stateIn, worldIn, currentPos);\n\t\treturn stateIn;\n\t}\n\n\tpublic void updateSpeed(BlockState state, LevelAccessor world, BlockPos pos) {\n\t\twithBlockEntityDo(world, pos, be -> {\n\t\t\tif (!state.getValue(VALID)) {\n\t\t\t\tif (be.crushingspeed != 0) {\n\t\t\t\t\tbe.crushingspeed = 0;\n\t\t\t\t\tbe.sendData();\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (Direction d : Iterate.directions) {\n\t\t\t\tBlockState neighbour = world.getBlockState(pos.relative(d));\n\t\t\t\tif (\n\t\t\t\t\t\t!MmbBlocks.GRANITE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t\t\t!MmbBlocks.DIORITE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t\t\t\t\t!AllBlocks.CRUSHING_WHEEL.has(neighbour)&&\n\n\t\t\t\t\t\t\t\t!MmbBlocks.LIMESTONE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.OCHRUM_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.SCORCHIA_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.SCORIA_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.TUFF_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.VERIDIUM_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.DRIPSTONE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.DEEPSLATE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.CRIMSITE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.CALCITE_CRUSHING_WHEEL.has(neighbour)&&\n\t\t\t\t!MmbBlocks.ASURINE_CRUSHING_WHEEL.has(neighbour))\n\t\t\t\t\tcontinue;\n\t\t\t\tif (neighbour.getValue(BlockStateProperties.AXIS) == d.getAxis())\n\t\t\t\t\tcontinue;\n\t\t\t\tBlockEntity adjBE = world.getBlockEntity(pos.relative(d));\n\t\t\t\tif (!(adjBE instanceof CrushingWheelBlockEntity cwbe))\n\t\t\t\t\tcontinue;\n\t\t\t\tbe.crushingspeed = Math.abs(cwbe.getSpeed() / 50f);\n\t\t\t\tbe.sendData();\n\n\t\t\t\tcwbe.award(AllAdvancements.CRUSHING_WHEEL);\n\t\t\t\tif (cwbe.getSpeed() > 255)\n\t\t\t\t\tcwbe.award(AllAdvancements.CRUSHER_MAXED);\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tpublic VoxelShape getCollisionShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) {\n\t\tVoxelShape standardShape = AllShapes.CRUSHING_WHEEL_CONTROLLER_COLLISION.get(state.getValue(FACING));\n\n\t\tif (!state.getValue(VALID))\n\t\t\treturn standardShape;\n\t\tif (!(context instanceof EntityCollisionContext))\n\t\t\treturn standardShape;\n\t\tEntity entity = ((EntityCollisionContext) context).getEntity();\n\t\tif (entity == null)\n\t\t\treturn standardShape;\n\n\t\tCompoundTag data = entity.getPersistentData();\n\t\tif (data.contains(\"BypassCrushingWheel\"))\n\t\t\tif (pos.equals(NbtUtils.readBlockPos(data.getCompound(\"BypassCrushingWheel\"))))\n\t\t\t\tif (state.getValue(FACING) != Direction.UP) // Allow output items to land on top of the block rather\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// than falling back through.\n\t\t\t\t\treturn Shapes.empty();\n\n\t\tCrushingWheelControllerBlockEntity be = getBlockEntity(worldIn, pos);\n\t\tif (be != null && be.processingEntity == entity)\n\t\t\treturn Shapes.empty();\n\n\t\treturn standardShape;\n\t}\n\n\t@Override\n\tpublic void onRemove(BlockState state, Level worldIn, BlockPos pos, BlockState newState, boolean isMoving) {\n\t\tif (!state.hasBlockEntity() || state.getBlock() == newState.getBlock())\n\t\t\treturn;\n\n\t\twithBlockEntityDo(worldIn, pos, be -> ItemHelper.dropContents(worldIn, pos, be.inventory));\n\t\tworldIn.removeBlockEntity(pos);\n\t}\n\n\t@Override\n\tpublic Class<CrushingWheelControllerBlockEntity> getBlockEntityClass() {\n\t\treturn CrushingWheelControllerBlockEntity.class;\n\t}\n\n\t@Override\n\tpublic BlockEntityType<? extends CrushingWheelControllerBlockEntity> getBlockEntityType() {\n\t\treturn MmbBlockEntities.MMB_CRUSHING_WHEEL_CONTROLLER.get();\n\t}\n\n\t@Override\n\tpublic boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) {\n\t\treturn false;\n\t}\n\n}" }, { "identifier": "DiagonalGirderBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/diagonal_girder/DiagonalGirderBlock.java", "snippet": "@SuppressWarnings({\"unused\",\"deprecation\"})\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class DiagonalGirderBlock extends DirectionalBlock implements SimpleWaterloggedBlock, IWrenchable {\n\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n public static final BooleanProperty FACING_UP = BooleanProperty.create(\"facing_up\");\n public DiagonalGirderBlock(Properties p_54120_) {\n super(p_54120_);\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE).setValue(FACING, Direction.NORTH).setValue(FACING_UP, false));\n }\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_55125_) {\n p_55125_.add(WATERLOGGED,FACING, FACING_UP);\n }\n\n public static final VoxelShape SHAPE_EAST = eShape();\n public static final VoxelShape SHAPE_WEST = wShape();\n public static final VoxelShape SHAPE_NORTH = nShape();\n public static final VoxelShape SHAPE_SOUTH = sShape();\n\n public static final VoxelShape SHAPE_UP_EAST = ueShape();\n public static final VoxelShape SHAPE_UP_WEST = uwShape();\n public static final VoxelShape SHAPE_UP_NORTH = unShape();\n public static final VoxelShape SHAPE_UP_SOUTH = usShape();\n\n public static VoxelShape nShape(){\n return Shapes.or(\n Block.box(3, 3, 0, 13, 13, 5),\n Block.box(3, 0, 3, 13, 5, 13),\n Block.box(4, 5, 5, 12, 12, 12)\n );\n }\n public static VoxelShape eShape(){\n return Shapes.or(\n Block.box(11, 3, 3, 16, 13, 13),\n Block.box(3, 0, 3, 13, 5, 13),\n Block.box(4, 5, 4, 11, 12, 12)\n );\n }\n\n public static VoxelShape sShape(){\n return Shapes.or(\n Block.box(3, 3, 11, 13, 13, 16),\n Block.box(3, 0, 3, 13, 5, 13),\n Block.box(4, 5, 4, 12, 12, 11)\n );\n }\n\n public static VoxelShape wShape(){\n return Shapes.or(\n Block.box(0, 3, 3, 5, 13, 13),\n Block.box(3, 0, 3, 13, 5, 13),\n Block.box(5, 5, 4, 12, 12, 12)\n );\n }\n\n public static VoxelShape unShape(){\n return Shapes.or(\n Block.box(3, 3, 0, 13, 13, 5),\n Block.box(3, 11, 3, 13, 16, 13),\n Block.box(4, 4, 5, 12, 11, 12)\n );\n }\n public static VoxelShape ueShape(){\n return Shapes.or(\n Block.box(11, 3, 3, 16, 13, 13),\n Block.box(3, 11, 3, 13, 16, 13),\n Block.box(4, 4, 4, 11, 11, 12)\n );\n }\n\n public static VoxelShape usShape(){\n return Shapes.or(\n Block.box(3, 3, 11, 13, 13, 16),\n Block.box(3, 11, 3, 13, 16, 13),\n Block.box(4, 4, 4, 12, 11, 11)\n );\n }\n\n public static VoxelShape uwShape(){\n return Shapes.or(\n Block.box(0, 3, 3, 5, 13, 13),\n Block.box(3, 11, 3, 13, 16, 13),\n Block.box(5, 4, 4, 12, 11, 12)\n );\n }\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n public VoxelShape getShape(BlockState p_54561_, BlockGetter p_54562_, BlockPos p_54563_, CollisionContext p_54564_) {\n if (!p_54561_.getValue(FACING_UP)) {\n return switch (p_54561_.getValue(FACING)) {\n case NORTH, UP, DOWN -> SHAPE_NORTH;\n case SOUTH -> SHAPE_SOUTH;\n case EAST -> SHAPE_EAST;\n case WEST -> SHAPE_WEST;\n };\n }\n if (p_54561_.getValue(FACING_UP)) {\n return switch (p_54561_.getValue(FACING)) {\n case NORTH, UP, DOWN -> SHAPE_UP_NORTH;\n case SOUTH -> SHAPE_UP_SOUTH;\n case EAST -> SHAPE_UP_EAST;\n case WEST -> SHAPE_UP_WEST;\n };\n }\n return SHAPE_NORTH;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n InteractionResult onWrenched = IWrenchable.super.onWrenched(state, context);\n if (!onWrenched.consumesAction())\n return onWrenched;\n\n context.getLevel().setBlock(context.getClickedPos(),state.setValue(FACING_UP,!state.getValue(FACING_UP)),2);\n\n playRotateSound(context.getLevel(), context.getClickedPos());\n return onWrenched;\n }\n\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n FluidState fluidstate = context.getLevel().getFluidState(context.getClickedPos());\n boolean flag = fluidstate.getType() == Fluids.WATER;\n Direction facing = Objects.requireNonNull(context.getPlayer()).getDirection();\n Direction clickedFace = context.getClickedFace();\n\n if (context.getPlayer() != null && context.getPlayer().isShiftKeyDown()) {\n if (clickedFace == Direction.DOWN)\n return defaultBlockState().setValue(FACING, facing.getOpposite()).setValue(FACING_UP,true).setValue(WATERLOGGED, flag);\n else\n return defaultBlockState().setValue(FACING, facing.getOpposite()).setValue(FACING_UP,false).setValue(WATERLOGGED, flag);\n }\n if (clickedFace == Direction.DOWN)\n return defaultBlockState().setValue(FACING, facing).setValue(FACING_UP,true).setValue(WATERLOGGED, flag);\n\n\n return defaultBlockState().setValue(FACING, facing).setValue(FACING_UP,false).setValue(WATERLOGGED, flag);\n }\n}" }, { "identifier": "DiagonalGirderGenerator", "path": "src/main/java/com/mangomilk/design_decor/blocks/diagonal_girder/DiagonalGirderGenerator.java", "snippet": "public class DiagonalGirderGenerator extends SpecialBlockStateGen {\n\n @Override\n protected int getXRotation(BlockState state) {\n return 0;\n }\n\n @Override\n protected int getYRotation(BlockState state) {\n return switch (state.getValue(DiagonalGirderBlock.FACING)) {\n case NORTH -> 270;\n case SOUTH -> 90;\n case WEST -> 180;\n case EAST -> 0;\n case DOWN -> 0;\n case UP -> 0;\n };\n }\n\n @Override\n public <T extends Block> ModelFile getModel(DataGenContext<Block, T> ctx, RegistrateBlockstateProvider prov,\n BlockState state) {\n // return AssetLookup.forPowered(ctx, prov)\n // .apply(state);\n\n return state.getValue(DiagonalGirderBlock.FACING_UP) ? partialBaseModel(ctx, prov, \"up\")\n : partialBaseModel(ctx, prov);\n }\n\n}" }, { "identifier": "FloodlightBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/floodlight/FloodlightBlock.java", "snippet": "@SuppressWarnings({\"unused\",\"deprecation\"})\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class FloodlightBlock extends DirectionalBlock implements SimpleWaterloggedBlock, IWrenchable {\n\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n public static final BooleanProperty TURNED_ON = BooleanProperty.create(\"turned_on\");\n public static final BooleanProperty WRENCHED = BooleanProperty.create(\"wrenched\");\n\n public static final VoxelShape SHAPE_DOWN = Block.box(3.0D, 8.0D, 3.0D, 13.0D, 16.0D, 13.0D);\n public static final VoxelShape SHAPE_UP = Block.box(3.0D, 0.0D, 3.0D, 13.0D, 8.0D, 13.0D);\n\n public static final VoxelShape SHAPE_EAST = Block.box(0.0D, 3.0D, 3.0D, 8.0D, 13.0D, 13.0D);\n public static final VoxelShape SHAPE_WEST = Block.box(8.0D, 3.0D, 3.0D, 16.0D, 13.0D, 13.0D);\n public static final VoxelShape SHAPE_NORTH = Block.box(3.0D, 3.0D, 8.0D, 13.0D, 13.0D, 16.0D);\n public static final VoxelShape SHAPE_SOUTH = Block.box(3.0D, 3.0D, 0.0D, 13.0D, 13.0D, 8.0D);\n public FloodlightBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE).setValue(FACING, Direction.UP).setValue(TURNED_ON, false).setValue(WRENCHED, false));\n }\n\n public VoxelShape getShape(BlockState p_54561_, BlockGetter p_54562_, BlockPos p_54563_, CollisionContext p_54564_) {\n return switch (p_54561_.getValue(FACING)) {\n case NORTH -> SHAPE_NORTH;\n case SOUTH -> SHAPE_SOUTH;\n case EAST -> SHAPE_EAST;\n case WEST -> SHAPE_WEST;\n case UP -> SHAPE_UP;\n case DOWN -> SHAPE_DOWN;\n default -> SHAPE_NORTH;\n };\n }\n\n @Override\n public void neighborChanged(BlockState pState, Level pLevel, BlockPos pPos, Block pBlock, BlockPos pFromPos,\n boolean pIsMoving) {\n if (pLevel.isClientSide)\n return;\n boolean beenWrenched = pState.getValue(WRENCHED);\n\n if (!beenWrenched && pLevel.hasNeighborSignal(pPos)) {\n pLevel.setBlock(pPos,pState.setValue(TURNED_ON,!pState.getValue(TURNED_ON)), 2);\n }\n }\n\n public void tick(BlockState p_221937_, ServerLevel p_221938_, BlockPos p_221939_, RandomSource p_221940_) {\n if (p_221937_.getValue(TURNED_ON) && p_221938_.hasNeighborSignal(p_221939_) != p_221937_.getValue(WRENCHED)) {\n p_221938_.setBlock(p_221939_, p_221937_.setValue(TURNED_ON, false), 2);\n }\n }\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n InteractionResult onWrenched = IWrenchable.super.onWrenched(state, context);\n if (!onWrenched.consumesAction())\n return onWrenched;\n boolean isOn = state.getValue(TURNED_ON);\n\n context.getLevel().setBlock(context.getClickedPos(),state.setValue(TURNED_ON,!state.getValue(TURNED_ON)).setValue(WRENCHED,!state.getValue(WRENCHED)),2);\n\n playRotateSound(context.getLevel(), context.getClickedPos());\n\n if (!isOn) {\n context.getLevel().playLocalSound(context.getClickedPos().getX(), context.getClickedPos().getY(), context.getClickedPos().getZ(),\n DecoSoundEvents.FLOODLIGHT_ON.get(), SoundSource.BLOCKS, 0.25F, Create.RANDOM.nextFloat() * 0.2F + 1.6F, false);\n }\n if (isOn) {\n context.getLevel().playLocalSound(context.getClickedPos().getX(), context.getClickedPos().getY(), context.getClickedPos().getZ(),\n DecoSoundEvents.FLOODLIGHT_OFF.get(), SoundSource.BLOCKS, 0.25F, Create.RANDOM.nextFloat() * 0.2F + 0.8F, false);\n }\n return onWrenched;\n }\n\n\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n\n @Override\n public boolean isPathfindable(BlockState p_51456_, BlockGetter p_51457_, BlockPos p_51458_, PathComputationType p_51459_) {\n return false;\n }\n\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_55125_) {\n p_55125_.add(WATERLOGGED,FACING,TURNED_ON,WRENCHED);\n }\n\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_58126_) {\n FluidState fluidstate = p_58126_.getLevel().getFluidState(p_58126_.getClickedPos());\n boolean flag = fluidstate.getType() == Fluids.WATER;\n\n BlockState blockstate = this.defaultBlockState();\n LevelReader levelreader = p_58126_.getLevel();\n BlockPos blockpos = p_58126_.getClickedPos();\n Direction[] adirection = p_58126_.getNearestLookingDirections();\n\n for(Direction direction : adirection) {\n Direction direction1 = direction.getOpposite();\n blockstate = blockstate.setValue(FACING, direction1).setValue(WATERLOGGED, flag);\n return blockstate;\n }\n\n return Objects.requireNonNull(super.getStateForPlacement(p_58126_)).setValue(WATERLOGGED, flag);\n }\n\n\n public void FloodlightSoundOff(Level p_49713_, BlockPos p_49714_, @Nullable Direction p_49715_) {\n this.FloodlightSoundOff((Entity) null, p_49713_, p_49714_, p_49715_);\n }\n\n public boolean FloodlightSoundOff(@Nullable Entity p_152189_, Level p_152190_, BlockPos p_152191_, @Nullable Direction p_152192_) {\n BlockEntity blockentity = p_152190_.getBlockEntity(p_152191_);\n if (!p_152190_.isClientSide) {\n\n p_152190_.playSound((Player)null, p_152191_, DecoSoundEvents.FLOODLIGHT_OFF.get(), SoundSource.BLOCKS, 0.25F, Create.RANDOM.nextFloat() * 0.2F + 0.8F);\n p_152190_.gameEvent(p_152189_, GameEvent.BLOCK_CHANGE, p_152191_);\n return true;\n } else {\n return false;\n }\n }\n\n public void FloodlightSoundOn(Level p_49713_, BlockPos p_49714_, @Nullable Direction p_49715_) {\n this.FloodlightSoundOn((Entity) null, p_49713_, p_49714_, p_49715_);\n }\n\n public boolean FloodlightSoundOn(@Nullable Entity p_152189_, Level p_152190_, BlockPos p_152191_, @Nullable Direction p_152192_) {\n BlockEntity blockentity = p_152190_.getBlockEntity(p_152191_);\n if (!p_152190_.isClientSide) {\n\n p_152190_.playSound((Player)null, p_152191_, DecoSoundEvents.FLOODLIGHT_ON.get(), SoundSource.BLOCKS, 0.25F, Create.RANDOM.nextFloat() * 0.2F + 1.6F);\n p_152190_.gameEvent(p_152189_, GameEvent.BLOCK_CHANGE, p_152191_);\n return true;\n } else {\n return false;\n }\n }\n}" }, { "identifier": "FloodlightGenerator", "path": "src/main/java/com/mangomilk/design_decor/blocks/floodlight/FloodlightGenerator.java", "snippet": "public class FloodlightGenerator extends SpecialBlockStateGen {\n public FloodlightGenerator() {\n }\n\n protected int getXRotation(BlockState state) {\n short value;\n switch ((Direction)state.getValue(FloodlightBlock.FACING)) {\n case NORTH:\n value = 0;\n break;\n case SOUTH:\n value = 0;\n break;\n case WEST:\n value = 0;\n break;\n case EAST:\n value = 0;\n break;\n case DOWN:\n value = 90;\n break;\n case UP:\n value = 270;\n break;\n default:\n throw new IncompatibleClassChangeError();\n }\n\n return value;\n }\n\n protected int getYRotation(BlockState state) {\n short value;\n switch ((Direction)state.getValue(FloodlightBlock.FACING)) {\n case NORTH:\n value = 0;\n break;\n case SOUTH:\n value = 180;\n break;\n case WEST:\n value = 270;\n break;\n case EAST:\n value = 90;\n break;\n case DOWN:\n value = 0;\n break;\n case UP:\n value = 0;\n break;\n default:\n throw new IncompatibleClassChangeError();\n }\n\n return value;\n }\n\n public <T extends Block> ModelFile getModel(DataGenContext<Block, T> ctx, RegistrateBlockstateProvider prov, BlockState state) {\n return (Boolean)state.getValue(FloodlightBlock.TURNED_ON) ? AssetLookup.partialBaseModel(ctx, prov, new String[]{\"on\"}) : AssetLookup.partialBaseModel(ctx, prov, new String[0]);\n }\n}" }, { "identifier": "GasTankBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/gas_tank/GasTankBlock.java", "snippet": "public class GasTankBlock extends Block implements SimpleWaterloggedBlock, IWrenchable, IBE<GasTankBlockEntity> {\n\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n\n public GasTankBlock(Properties p_49795_) {\n super(p_49795_);\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE));\n }\n\n public VoxelShape getShape(BlockState p_54561_, BlockGetter p_54562_, BlockPos p_54563_, CollisionContext p_54564_) {\n return Block.box(1, 0, 1, 15, 16, 15);\n }\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_55125_) {\n p_55125_.add(WATERLOGGED);\n }\n @Override\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_152019_) {\n LevelAccessor levelaccessor = p_152019_.getLevel();\n BlockPos blockpos = p_152019_.getClickedPos();\n return this.defaultBlockState().setValue(WATERLOGGED, levelaccessor.getFluidState(blockpos).getType() == Fluids.WATER);\n }\n\n @Override\n public Class<GasTankBlockEntity> getBlockEntityClass() {\n return GasTankBlockEntity.class;\n }\n\n @Override\n public BlockEntityType<? extends GasTankBlockEntity> getBlockEntityType() {\n return MmbBlockEntities.GAS_TANK.get();\n }\n}" }, { "identifier": "ConnectedTintedGlassBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/glass/ConnectedTintedGlassBlock.java", "snippet": "public class ConnectedTintedGlassBlock extends TintedGlassBlock {\n public ConnectedTintedGlassBlock(Properties p_154822_) {\n super(p_154822_);\n }\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public boolean skipRendering(BlockState state, BlockState adjacentBlockState, Direction side) {\n return adjacentBlockState.getBlock() instanceof ConnectedTintedGlassBlock || super.skipRendering(state, adjacentBlockState, side);\n }\n\n @Override\n public boolean shouldDisplayFluidOverlay(BlockState state, BlockAndTintGetter world, BlockPos pos, FluidState fluidState) {\n return true;\n }\n}" }, { "identifier": "IndustrialGearBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/industrial_gear/IndustrialGearBlock.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class IndustrialGearBlock extends ShaftBlock implements ICogWheel, EncasableBlock {\n boolean isLarge;\n\n VoxelShape largeY = Shapes.join(Block.box(-2, 2, -2, 18, 14, 18),\n Block.box(5, 0, 5, 11, 16, 11), BooleanOp.OR);\n VoxelShape smallY = Shapes.join(Block.box(1, 2, 1, 15, 14, 15),\n Block.box(5, 0, 5, 11, 16, 11), BooleanOp.OR);\n\n VoxelShape largeX = Shapes.join(Block.box(2, -2, -2, 14, 18, 18),\n Block.box(0, 5, 5, 16, 11, 11), BooleanOp.OR);\n VoxelShape smallX = Shapes.join(Block.box(2, 1, 1, 14, 15, 15),\n Block.box(0, 5, 5, 16, 11, 11), BooleanOp.OR);\n\n VoxelShape largeZ = Shapes.join(Block.box(-2, -2, 2, 18, 18, 14),\n Block.box(5, 5, 0, 11, 11, 16), BooleanOp.OR);\n VoxelShape smallZ = Shapes.join(Block.box(1, 1, 2, 15, 15, 14),\n Block.box(5, 5, 0, 11, 11, 16), BooleanOp.OR);\n\n protected IndustrialGearBlock(boolean large, Properties properties) {\n super(properties);\n isLarge = large;\n }\n\n public static IndustrialGearBlock small(Properties properties) {\n return new IndustrialGearBlock(false, properties);\n }\n\n public static IndustrialGearBlock large(Properties properties) {\n return new IndustrialGearBlock(true, properties);\n }\n\n @Override\n public boolean isLargeCog() {\n return isLarge;\n }\n\n @Override\n public boolean isSmallCog() {\n return !isLarge;\n }\n\n @Override\n public void fillItemCategory(CreativeModeTab pTab, NonNullList<ItemStack> pItems) {\n super.fillItemCategory(pTab, pItems);\n MmbBlocks.LARGE_COGWHEEL.is(this);\n }\n\n @Override\n public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) {\n if (state.getValue(AXIS) == Direction.Axis.X) {\n return (isLarge ? largeX : smallX);\n }\n if (state.getValue(AXIS) == Direction.Axis.Z) {\n return (isLarge ? largeZ : smallZ);\n }\n state.getValue(AXIS);\n return (isLarge ? largeY : smallY);\n }\n\n @Override\n public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) {\n return isValidCogwheelPosition(ICogWheel.isLargeCog(state), worldIn, pos, state.getValue(AXIS));\n }\n\n @Override\n public void setPlacedBy(Level worldIn, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {\n super.setPlacedBy(worldIn, pos, state, placer, stack);\n if (placer instanceof Player player)\n triggerShiftingGearsAdvancement(worldIn, pos, state, player);\n }\n\n protected void triggerShiftingGearsAdvancement(Level world, BlockPos pos, BlockState state, Player player) {\n if (world.isClientSide || player == null)\n return;\n\n Direction.Axis axis = state.getValue(IndustrialGearBlock.AXIS);\n for (Direction.Axis perpendicular1 : Iterate.axes) {\n if (perpendicular1 == axis)\n continue;\n\n Direction d1 = Direction.get(Direction.AxisDirection.POSITIVE, perpendicular1);\n for (Direction.Axis perpendicular2 : Iterate.axes) {\n if (perpendicular1 == perpendicular2)\n continue;\n if (axis == perpendicular2)\n continue;\n\n Direction d2 = Direction.get(Direction.AxisDirection.POSITIVE, perpendicular2);\n for (int offset1 : Iterate.positiveAndNegative) {\n for (int offset2 : Iterate.positiveAndNegative) {\n BlockPos connectedPos = pos.relative(d1, offset1)\n .relative(d2, offset2);\n BlockState blockState = world.getBlockState(connectedPos);\n if (!(blockState.getBlock() instanceof IndustrialGearBlock))\n continue;\n if (blockState.getValue(IndustrialGearBlock.AXIS) != axis)\n continue;\n if (ICogWheel.isLargeCog(blockState) == isLarge)\n continue;\n\n AllAdvancements.COGS.awardTo(player);\n }\n }\n }\n }\n }\n\n @Override\n public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand,\n BlockHitResult ray) {\n if (player.isShiftKeyDown() || !player.mayBuild())\n return InteractionResult.PASS;\n\n ItemStack heldItem = player.getItemInHand(hand);\n InteractionResult result = tryEncase(state, world, pos, heldItem, player, hand, ray);\n if (result.consumesAction())\n return result;\n\n return InteractionResult.PASS;\n }\n\n public static boolean isValidCogwheelPosition(boolean large, LevelReader worldIn, BlockPos pos, Direction.Axis cogAxis) {\n for (Direction facing : Iterate.directions) {\n if (facing.getAxis() == cogAxis)\n continue;\n\n BlockPos offsetPos = pos.relative(facing);\n BlockState blockState = worldIn.getBlockState(offsetPos);\n if (blockState.hasProperty(AXIS) && facing.getAxis() == blockState.getValue(AXIS))\n continue;\n\n if (ICogWheel.isLargeCog(blockState) || large && ICogWheel.isSmallCog(blockState))\n return false;\n }\n return true;\n }\n\n protected Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n if (context.getPlayer() != null && context.getPlayer()\n .isShiftKeyDown())\n return context.getClickedFace()\n .getAxis();\n\n Level world = context.getLevel();\n BlockState stateBelow = world.getBlockState(context.getClickedPos()\n .below());\n\n BlockPos placedOnPos = context.getClickedPos()\n .relative(context.getClickedFace()\n .getOpposite());\n BlockState placedAgainst = world.getBlockState(placedOnPos);\n\n Block block = placedAgainst.getBlock();\n if (ICogWheel.isSmallCog(placedAgainst))\n return ((IRotate) block).getRotationAxis(placedAgainst);\n\n Direction.Axis preferredAxis = getPreferredAxis(context);\n return preferredAxis != null ? preferredAxis\n : context.getClickedFace()\n .getAxis();\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n boolean shouldWaterlog = context.getLevel()\n .getFluidState(context.getClickedPos())\n .getType() == Fluids.WATER;\n return this.defaultBlockState()\n .setValue(AXIS, getAxisForPlacement(context))\n .setValue(BlockStateProperties.WATERLOGGED, shouldWaterlog);\n }\n\n @Override\n public float getParticleTargetRadius() {\n return isLargeCog() ? 1.125f : .65f;\n }\n\n @Override\n public float getParticleInitialRadius() {\n return isLargeCog() ? 1f : .75f;\n }\n\n @Override\n public boolean isDedicatedCogWheel() {\n return true;\n }\n\n}" }, { "identifier": "IndustrialGearBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/industrial_gear/IndustrialGearBlockItem.java", "snippet": "public class IndustrialGearBlockItem extends BlockItem {\n\n boolean large;\n\n private final int placementHelperId;\n private final int integratedCogHelperId;\n\n public IndustrialGearBlockItem(IndustrialGearBlock block, Properties builder) {\n super(block, builder);\n large = block.isLarge;\n\n placementHelperId = PlacementHelpers.register(large ? new IndustrialGearBlockItem.LargeCogHelper() : new IndustrialGearBlockItem.SmallCogHelper());\n integratedCogHelperId =\n PlacementHelpers.register(large ? new IndustrialGearBlockItem.IntegratedLargeCogHelper() : new IndustrialGearBlockItem.IntegratedSmallCogHelper());\n }\n\n @Override\n public InteractionResult onItemUseFirst(ItemStack stack, UseOnContext context) {\n Level world = context.getLevel();\n BlockPos pos = context.getClickedPos();\n BlockState state = world.getBlockState(pos);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n Player player = context.getPlayer();\n BlockHitResult ray = new BlockHitResult(context.getClickLocation(), context.getClickedFace(), pos, true);\n if (helper.matchesState(state) && player != null && !player.isShiftKeyDown()) {\n return helper.getOffset(player, world, state, pos, ray)\n .placeInWorld(world, this, player, context.getHand(), ray);\n }\n\n if (integratedCogHelperId != -1) {\n helper = PlacementHelpers.get(integratedCogHelperId);\n\n if (helper.matchesState(state) && player != null && !player.isShiftKeyDown()) {\n return helper.getOffset(player, world, state, pos, ray)\n .placeInWorld(world, this, player, context.getHand(), ray);\n }\n }\n\n return super.onItemUseFirst(stack, context);\n }\n\n @MethodsReturnNonnullByDefault\n private static class SmallCogHelper extends IndustrialGearBlockItem.DiagonalCogHelper {\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return ((Predicate<ItemStack>) ICogWheel::isSmallCogItem).and(ICogWheel::isDedicatedCogItem);\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n if (hitOnShaft(state, ray))\n return PlacementOffset.fail();\n\n if (!ICogWheel.isLargeCog(state)) {\n Direction.Axis axis = ((IRotate) state.getBlock()).getRotationAxis(state);\n List<Direction> directions = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), axis);\n\n for (Direction dir : directions) {\n BlockPos newPos = pos.relative(dir);\n\n if (!IndustrialGearBlock.isValidCogwheelPosition(false, world, newPos, axis))\n continue;\n\n if (!world.getBlockState(newPos)\n .getMaterial()\n .isReplaceable())\n continue;\n\n return PlacementOffset.success(newPos, s -> s.setValue(AXIS, axis));\n\n }\n\n return PlacementOffset.fail();\n }\n\n return super.getOffset(player, world, state, pos, ray);\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class LargeCogHelper extends IndustrialGearBlockItem.DiagonalCogHelper {\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return ((Predicate<ItemStack>) ICogWheel::isLargeCogItem).and(ICogWheel::isDedicatedCogItem);\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n if (hitOnShaft(state, ray))\n return PlacementOffset.fail();\n\n if (ICogWheel.isLargeCog(state)) {\n Direction.Axis axis = ((IRotate) state.getBlock()).getRotationAxis(state);\n Direction side = IPlacementHelper.orderedByDistanceOnlyAxis(pos, ray.getLocation(), axis)\n .get(0);\n List<Direction> directions = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), axis);\n for (Direction dir : directions) {\n BlockPos newPos = pos.relative(dir)\n .relative(side);\n\n if (!IndustrialGearBlock.isValidCogwheelPosition(true, world, newPos, dir.getAxis()))\n continue;\n\n if (!world.getBlockState(newPos)\n .getMaterial()\n .isReplaceable())\n continue;\n\n return PlacementOffset.success(newPos, s -> s.setValue(AXIS, dir.getAxis()));\n }\n\n return PlacementOffset.fail();\n }\n\n return super.getOffset(player, world, state, pos, ray);\n }\n }\n\n @MethodsReturnNonnullByDefault\n public abstract static class DiagonalCogHelper implements IPlacementHelper {\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> ICogWheel.isSmallCog(s) || ICogWheel.isLargeCog(s);\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n // diagonal gears of different size\n Direction.Axis axis = ((IRotate) state.getBlock()).getRotationAxis(state);\n Direction closest = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), axis)\n .get(0);\n List<Direction> directions = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), axis,\n d -> d.getAxis() != closest.getAxis());\n\n for (Direction dir : directions) {\n BlockPos newPos = pos.relative(dir)\n .relative(closest);\n if (!world.getBlockState(newPos)\n .getMaterial()\n .isReplaceable())\n continue;\n\n if (!IndustrialGearBlock.isValidCogwheelPosition(ICogWheel.isLargeCog(state), world, newPos, axis))\n continue;\n\n return PlacementOffset.success(newPos, s -> s.setValue(AXIS, axis));\n }\n\n return PlacementOffset.fail();\n }\n\n protected boolean hitOnShaft(BlockState state, BlockHitResult ray) {\n return AllShapes.SIX_VOXEL_POLE.get(((IRotate) state.getBlock()).getRotationAxis(state))\n .bounds()\n .inflate(0.001)\n .contains(ray.getLocation()\n .subtract(ray.getLocation()\n .align(Iterate.axisSet)));\n }\n }\n\n @MethodsReturnNonnullByDefault\n public static class IntegratedLargeCogHelper implements IPlacementHelper {\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return ((Predicate<ItemStack>) ICogWheel::isLargeCogItem).and(ICogWheel::isDedicatedCogItem);\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> !ICogWheel.isDedicatedCogWheel(s.getBlock()) && ICogWheel.isSmallCog(s);\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n Direction face = ray.getDirection();\n Direction.Axis newAxis;\n\n if (state.hasProperty(HorizontalKineticBlock.HORIZONTAL_FACING))\n newAxis = state.getValue(HorizontalKineticBlock.HORIZONTAL_FACING)\n .getAxis();\n else if (state.hasProperty(DirectionalKineticBlock.FACING))\n newAxis = state.getValue(DirectionalKineticBlock.FACING)\n .getAxis();\n else if (state.hasProperty(RotatedPillarKineticBlock.AXIS))\n newAxis = state.getValue(RotatedPillarKineticBlock.AXIS);\n else\n newAxis = Direction.Axis.Y;\n\n if (face.getAxis() == newAxis)\n return PlacementOffset.fail();\n\n List<Direction> directions =\n IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), face.getAxis(), newAxis);\n\n for (Direction d : directions) {\n BlockPos newPos = pos.relative(face)\n .relative(d);\n\n if (!world.getBlockState(newPos)\n .getMaterial()\n .isReplaceable())\n continue;\n\n if (!IndustrialGearBlock.isValidCogwheelPosition(false, world, newPos, newAxis))\n return PlacementOffset.fail();\n\n return PlacementOffset.success(newPos, s -> s.setValue(IndustrialGearBlock.AXIS, newAxis));\n }\n\n return PlacementOffset.fail();\n }\n\n }\n\n @MethodsReturnNonnullByDefault\n public static class IntegratedSmallCogHelper implements IPlacementHelper {\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return ((Predicate<ItemStack>) ICogWheel::isSmallCogItem).and(ICogWheel::isDedicatedCogItem);\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> !ICogWheel.isDedicatedCogWheel(s.getBlock()) && ICogWheel.isSmallCog(s);\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n Direction face = ray.getDirection();\n Direction.Axis newAxis;\n\n if (state.hasProperty(HorizontalKineticBlock.HORIZONTAL_FACING))\n newAxis = state.getValue(HorizontalKineticBlock.HORIZONTAL_FACING)\n .getAxis();\n else if (state.hasProperty(DirectionalKineticBlock.FACING))\n newAxis = state.getValue(DirectionalKineticBlock.FACING)\n .getAxis();\n else if (state.hasProperty(RotatedPillarKineticBlock.AXIS))\n newAxis = state.getValue(RotatedPillarKineticBlock.AXIS);\n else\n newAxis = Direction.Axis.Y;\n\n if (face.getAxis() == newAxis)\n return PlacementOffset.fail();\n\n List<Direction> directions = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), newAxis);\n\n for (Direction d : directions) {\n BlockPos newPos = pos.relative(d);\n\n if (!world.getBlockState(newPos)\n .getMaterial()\n .isReplaceable())\n continue;\n\n if (!IndustrialGearBlock.isValidCogwheelPosition(false, world, newPos, newAxis))\n return PlacementOffset.fail();\n\n return PlacementOffset.success()\n .at(newPos)\n .withTransform(s -> s.setValue(IndustrialGearBlock.AXIS, newAxis));\n }\n\n return PlacementOffset.fail();\n }\n\n }\n}" }, { "identifier": "AluminumBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/aluminum/AluminumBoilerStructure.java", "snippet": "public class AluminumBoilerStructure extends DirectionalBlock implements IWrenchable {\n public AluminumBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_ALUMINUM_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_ALUMINUM_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_ALUMINUM_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.ALUMINUM_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof AluminumLargeBoilerBlock\n && targetedState.getValue(AluminumLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n AluminumBoilerStructure waterWheelStructuralBlock = MmbBlocks.ALUMINUM_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(AluminumBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n AluminumBoilerStructure waterWheelStructuralBlock = MmbBlocks.ALUMINUM_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(AluminumBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "AluminumLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/aluminum/AluminumLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class AluminumLargeBoilerBlock extends TagDependentDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public AluminumLargeBoilerBlock(Properties properties, TagKey<Item> itemTagKey) {\n super(properties, itemTagKey);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.ALUMINUM_BOILER_STRUCTURAL.getDefaultState()\n .setValue(AluminumBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof AluminumLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof AluminumLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof AluminumLargeBoilerBlock || s.getBlock() instanceof AluminumLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n}" }, { "identifier": "AluminumLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/aluminum/AluminumLargeBoilerBlockItem.java", "snippet": "public class AluminumLargeBoilerBlockItem extends BlockItem {\n public AluminumLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((AluminumLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((AluminumLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "AndesiteBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/andesite/AndesiteBoilerStructure.java", "snippet": "public class AndesiteBoilerStructure extends DirectionalBlock implements IWrenchable {\n public AndesiteBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_ANDESITE_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_ANDESITE_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_ANDESITE_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.ANDESITE_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof AndesiteLargeBoilerBlock\n && targetedState.getValue(AndesiteLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n AndesiteBoilerStructure waterWheelStructuralBlock = MmbBlocks.ANDESITE_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(AndesiteBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n AndesiteBoilerStructure waterWheelStructuralBlock = MmbBlocks.ANDESITE_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(AndesiteBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "AndesiteLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/andesite/AndesiteLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class AndesiteLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public AndesiteLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.ANDESITE_BOILER_STRUCTURAL.getDefaultState()\n .setValue(AndesiteBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof AndesiteLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof AndesiteLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof AndesiteLargeBoilerBlock || s.getBlock() instanceof AndesiteLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "AndesiteLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/andesite/AndesiteLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class AndesiteLargeBoilerBlockItem extends BlockItem {\n\n public AndesiteLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((AndesiteLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((AndesiteLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "BrassBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/brass/BrassBoilerStructure.java", "snippet": "public class BrassBoilerStructure extends DirectionalBlock implements IWrenchable {\n public BrassBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_BRASS_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_BRASS_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_BRASS_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.BRASS_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof BrassLargeBoilerBlock\n && targetedState.getValue(BrassLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new BrassBoilerStructure.RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n BrassBoilerStructure waterWheelStructuralBlock = MmbBlocks.BRASS_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(BrassBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n BrassBoilerStructure waterWheelStructuralBlock = MmbBlocks.BRASS_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(BrassBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "BrassLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/brass/BrassLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class BrassLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public BrassLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.BRASS_BOILER_STRUCTURAL.getDefaultState()\n .setValue(BrassBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof BrassLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof BrassLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof BrassLargeBoilerBlock || s.getBlock() instanceof BrassLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "BrassLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/brass/BrassLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class BrassLargeBoilerBlockItem extends BlockItem {\n\n public BrassLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((BrassLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((BrassLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n\n}" }, { "identifier": "CapitalismBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/capitalism/CapitalismBoilerStructure.java", "snippet": "public class CapitalismBoilerStructure extends DirectionalBlock implements IWrenchable {\n public CapitalismBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_CAPITALISM_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_CAPITALISM_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_CAPITALISM_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.CAPITALISM_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof CapitalismLargeBoilerBlock\n && targetedState.getValue(CapitalismLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new CapitalismBoilerStructure.RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n CapitalismBoilerStructure waterWheelStructuralBlock = MmbBlocks.CAPITALISM_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(CapitalismBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n CapitalismBoilerStructure waterWheelStructuralBlock = MmbBlocks.CAPITALISM_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(CapitalismBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "CapitalismLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/capitalism/CapitalismLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CapitalismLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public CapitalismLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.CAPITALISM_BOILER_STRUCTURAL.getDefaultState()\n .setValue(CapitalismBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof CapitalismLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof CapitalismLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof CapitalismLargeBoilerBlock || s.getBlock() instanceof CapitalismLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "CapitalismLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/capitalism/CapitalismLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CapitalismLargeBoilerBlockItem extends BlockItem {\n\n public CapitalismLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((CapitalismLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((CapitalismLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "CastIronBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/cast_iron/CastIronBoilerStructure.java", "snippet": "public class CastIronBoilerStructure extends DirectionalBlock implements IWrenchable {\n public CastIronBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_CAST_IRON_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_CAST_IRON_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_CAST_IRON_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.CAST_IRON_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof CastIronLargeBoilerBlock\n && targetedState.getValue(CastIronLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new CastIronBoilerStructure.RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n CastIronBoilerStructure waterWheelStructuralBlock = MmbBlocks.CAST_IRON_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(CastIronBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n CastIronBoilerStructure waterWheelStructuralBlock = MmbBlocks.CAST_IRON_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(CastIronBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "CastIronLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/cast_iron/CastIronLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CastIronLargeBoilerBlock extends TagDependentDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public CastIronLargeBoilerBlock(Properties properties, TagKey<Item> itemTagKey) {\n super(properties, itemTagKey);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.CAST_IRON_BOILER_STRUCTURAL.getDefaultState()\n .setValue(CastIronBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof CastIronLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof CastIronLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof CastIronLargeBoilerBlock || s.getBlock() instanceof CastIronLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "CastIronLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/cast_iron/CastIronLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CastIronLargeBoilerBlockItem extends BlockItem {\n\n public CastIronLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((CastIronLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((CastIronLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n\n}" }, { "identifier": "CopperBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/copper/CopperBoilerStructure.java", "snippet": "public class CopperBoilerStructure extends DirectionalBlock implements IWrenchable {\n public CopperBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_COPPER_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_COPPER_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_COPPER_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.COPPER_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof CopperLargeBoilerBlock\n && targetedState.getValue(CopperLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n CopperBoilerStructure waterWheelStructuralBlock = MmbBlocks.COPPER_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(CopperBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n CopperBoilerStructure waterWheelStructuralBlock = MmbBlocks.COPPER_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(CopperBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "CopperLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/copper/CopperLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CopperLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public CopperLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.COPPER_BOILER_STRUCTURAL.getDefaultState()\n .setValue(CopperBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof CopperLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof CopperLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof CopperLargeBoilerBlock || s.getBlock() instanceof CopperLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "CopperLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/copper/CopperLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class CopperLargeBoilerBlockItem extends BlockItem {\n\n public CopperLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((CopperLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((CopperLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "GoldBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/gold/GoldBoilerStructure.java", "snippet": "public class GoldBoilerStructure extends DirectionalBlock implements IWrenchable {\n public GoldBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_GOLD_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_GOLD_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_GOLD_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.GOLD_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof GoldLargeBoilerBlock\n && targetedState.getValue(GoldLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n GoldBoilerStructure waterWheelStructuralBlock = MmbBlocks.GOLD_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(GoldBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n GoldBoilerStructure waterWheelStructuralBlock = MmbBlocks.GOLD_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(GoldBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "GoldLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/gold/GoldLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class GoldLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public GoldLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.GOLD_BOILER_STRUCTURAL.getDefaultState()\n .setValue(GoldBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof GoldLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof GoldLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof GoldLargeBoilerBlock || s.getBlock() instanceof GoldLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "GoldLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/gold/GoldLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class GoldLargeBoilerBlockItem extends BlockItem {\n\n public GoldLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((GoldLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((GoldLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "IndustrialIronBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/industrial_iron/IndustrialIronBoilerStructure.java", "snippet": "public class IndustrialIronBoilerStructure extends DirectionalBlock implements IWrenchable {\n public IndustrialIronBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_INDUSTRIAL_IRON_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_INDUSTRIAL_IRON_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_INDUSTRIAL_IRON_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.INDUSTRIAL_IRON_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof IndustrialIronLargeBoilerBlock\n && targetedState.getValue(IndustrialIronLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n IndustrialIronBoilerStructure waterWheelStructuralBlock = MmbBlocks.INDUSTRIAL_IRON_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(IndustrialIronBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n IndustrialIronBoilerStructure waterWheelStructuralBlock = MmbBlocks.INDUSTRIAL_IRON_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(IndustrialIronBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "IndustrialIronLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/industrial_iron/IndustrialIronLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class IndustrialIronLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public IndustrialIronLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.INDUSTRIAL_IRON_BOILER_STRUCTURAL.getDefaultState()\n .setValue(IndustrialIronBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof IndustrialIronLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof IndustrialIronLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof IndustrialIronLargeBoilerBlock || s.getBlock() instanceof IndustrialIronLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "IndustrialIronLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/industrial_iron/IndustrialIronLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class IndustrialIronLargeBoilerBlockItem extends BlockItem {\n\n public IndustrialIronLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((IndustrialIronLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((IndustrialIronLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n}" }, { "identifier": "ZincBoilerStructure", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/zinc/ZincBoilerStructure.java", "snippet": "public class ZincBoilerStructure extends DirectionalBlock implements IWrenchable {\n public ZincBoilerStructure(Properties p_52591_) {\n super(p_52591_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {\n super.createBlockStateDefinition(pBuilder.add(FACING));\n }\n\n @Override\n public RenderShape getRenderShape(BlockState pState) {\n return RenderShape.INVISIBLE;\n }\n\n @Override\n public PushReaction getPistonPushReaction(BlockState pState) {\n return PushReaction.BLOCK;\n }\n\n @Override\n public InteractionResult onWrenched(BlockState state, UseOnContext context) {\n return InteractionResult.PASS;\n }\n\n @Override\n public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) {\n return MmbBlocks.LARGE_ZINC_BOILER.asStack();\n }\n\n @Override\n public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {\n BlockPos clickedPos = context.getClickedPos();\n Level level = context.getLevel();\n\n if (stillValid(level, clickedPos, state, false)) {\n BlockPos masterPos = getMaster(level, clickedPos, state);\n context = new UseOnContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(),\n new BlockHitResult(context.getClickLocation(), context.getClickedFace(), masterPos,\n context.isInside()));\n state = level.getBlockState(masterPos);\n }\n\n return IWrenchable.super.onSneakWrenched(state, context);\n }\n\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n return InteractionResult.FAIL;\n }\n\n @Override\n public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) {\n if (stillValid(pLevel, pPos, pState, false))\n pLevel.destroyBlock(getMaster(pLevel, pPos, pState), true);\n }\n\n public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {\n if (stillValid(pLevel, pPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pPos, pState);\n pLevel.destroyBlockProgress(masterPos.hashCode(), masterPos, -1);\n if (!pLevel.isClientSide() && pPlayer.isCreative())\n pLevel.destroyBlock(masterPos, false);\n }\n super.playerWillDestroy(pLevel, pPos, pState, pPlayer);\n }\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel,\n BlockPos pCurrentPos, BlockPos pFacingPos) {\n if (stillValid(pLevel, pCurrentPos, pState, false)) {\n BlockPos masterPos = getMaster(pLevel, pCurrentPos, pState);\n if (!pLevel.getBlockTicks()\n .hasScheduledTick(masterPos, MmbBlocks.LARGE_ZINC_BOILER.get()))\n pLevel.scheduleTick(masterPos, MmbBlocks.LARGE_ZINC_BOILER.get(), 1);\n return pState;\n }\n if (!(pLevel instanceof Level level) || level.isClientSide())\n return pState;\n if (!level.getBlockTicks()\n .hasScheduledTick(pCurrentPos, this))\n level.scheduleTick(pCurrentPos, this, 1);\n return pState;\n }\n\n public static BlockPos getMaster(BlockGetter level, BlockPos pos, BlockState state) {\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n if (targetedState.is(MmbBlocks.ZINC_BOILER_STRUCTURAL.get()))\n return getMaster(level, targetedPos, targetedState);\n return targetedPos;\n }\n\n public boolean stillValid(BlockGetter level, BlockPos pos, BlockState state, boolean directlyAdjacent) {\n if (!state.is(this))\n return false;\n\n Direction direction = state.getValue(FACING);\n BlockPos targetedPos = pos.relative(direction);\n BlockState targetedState = level.getBlockState(targetedPos);\n\n if (!directlyAdjacent && stillValid(level, targetedPos, targetedState, true))\n return true;\n return targetedState.getBlock() instanceof ZincLargeBoilerBlock\n && targetedState.getValue(ZincLargeBoilerBlock.FACING).getAxis() != direction.getAxis();\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n if (!stillValid(pLevel, pPos, pState, false))\n pLevel.setBlockAndUpdate(pPos, Blocks.AIR.defaultBlockState());\n }\n\n @OnlyIn(Dist.CLIENT)\n public void initializeClient(Consumer<IClientBlockExtensions> consumer) {\n consumer.accept(new RenderProperties());\n }\n\n @Override\n public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,\n LivingEntity entity, int numberOfParticles) {\n return true;\n }\n\n public static class RenderProperties implements IClientBlockExtensions, MultiPosDestructionHandler {\n\n @Override\n public boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {\n return true;\n }\n\n @Override\n public boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {\n if (target instanceof BlockHitResult bhr) {\n BlockPos targetPos = bhr.getBlockPos();\n ZincBoilerStructure waterWheelStructuralBlock = MmbBlocks.ZINC_BOILER_STRUCTURAL.get();\n if (waterWheelStructuralBlock.stillValid(level, targetPos, state, false))\n manager.crack(ZincBoilerStructure.getMaster(level, targetPos, state), bhr.getDirection());\n return true;\n }\n return IClientBlockExtensions.super.addHitEffects(state, level, target, manager);\n }\n\n @Override\n @Nullable\n public Set<BlockPos> getExtraPositions(ClientLevel level, BlockPos pos, BlockState blockState, int progress) {\n ZincBoilerStructure waterWheelStructuralBlock = MmbBlocks.ZINC_BOILER_STRUCTURAL.get();\n if (!waterWheelStructuralBlock.stillValid(level, pos, blockState, false))\n return null;\n HashSet<BlockPos> set = new HashSet<>();\n set.add(ZincBoilerStructure.getMaster(level, pos, blockState));\n return set;\n }\n }\n}" }, { "identifier": "ZincLargeBoilerBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/zinc/ZincLargeBoilerBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class ZincLargeBoilerBlock extends WrenchableDirectionalBlock {\n\n public static final BooleanProperty EXTENSION = BooleanProperty.create(\"extension\");\n\n public static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());\n public ZincLargeBoilerBlock(Properties p_52591_) {\n super(p_52591_);\n this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.UP).setValue(EXTENSION, false));\n }\n\n public static final VoxelShape SHAPE = Block.box(-8.0D, -8.0D, -8.0D, 24.0D, 24.0D, 24.0D);\n\n @Override\n public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState,\n LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) {\n if (pDirection != Direction.fromAxisAndDirection(pState.getValue(FACING).getAxis(), Direction.AxisDirection.NEGATIVE))\n return pState;\n return pState.setValue(EXTENSION, pNeighborState.is(this));\n }\n\n public Direction.Axis getAxisForPlacement(BlockPlaceContext context) {\n return super.getStateForPlacement(context).getValue(FACING).getAxis();\n }\n @Override\n public VoxelShape getOcclusionShape(BlockState p_60578_, BlockGetter p_60579_, BlockPos p_60580_) {\n return SHAPE;\n }\n\n @Override\n public RenderShape getRenderShape(BlockState p_54559_) {\n return RenderShape.MODEL;\n }\n\n @Override\n public boolean useShapeForLightOcclusion(BlockState p_54582_) {\n return true;\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n super.createBlockStateDefinition(builder.add(EXTENSION));\n }\n\n @Override\n public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand,\n BlockHitResult pHit) {\n\n ItemStack itemInHand = pPlayer.getItemInHand(pHand);\n\n IPlacementHelper helper = PlacementHelpers.get(placementHelperId);\n if (helper.matchesItem(itemInHand))\n return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit)\n .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit);\n\n return InteractionResult.PASS;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n BlockState stateForPlacement = super.getStateForPlacement(context);\n BlockPos pos = context.getClickedPos();\n assert stateForPlacement != null;\n Direction.Axis axis = stateForPlacement.getValue(FACING).getAxis();\n\n for (int x = -1; x <= 1; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -1; z <= 1; z++) {\n if (axis.choose(x, y, z) != 0)\n continue;\n BlockPos offset = new BlockPos(x, y, z);\n if (offset.equals(BlockPos.ZERO))\n continue;\n BlockState occupiedState = context.getLevel()\n .getBlockState(pos.offset(offset));\n if (!occupiedState.getMaterial()\n .isReplaceable())\n return null;\n }\n }\n }\n\n if (context.getLevel()\n .getBlockState(pos.relative(Direction.fromAxisAndDirection(axis, Direction.AxisDirection.NEGATIVE)))\n .is(this))\n stateForPlacement = stateForPlacement.setValue(EXTENSION, true);\n\n return stateForPlacement;\n }\n\n @Override\n public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {\n super.onPlace(state, level, pos, oldState, isMoving);\n if (!level.getBlockTicks()\n .hasScheduledTick(pos, this))\n level.scheduleTick(pos, this, 1);\n }\n\n @Override\n public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, RandomSource pRandom) {\n Direction.Axis axis = pState.getValue(FACING).getAxis();\n for (Direction side : Iterate.directions) {\n if (side.getAxis() == axis)\n continue;\n for (boolean secondary : Iterate.falseAndTrue) {\n Direction targetSide = secondary ? side.getClockWise(axis) : side;\n BlockPos structurePos = (secondary ? pPos.relative(side) : pPos).relative(targetSide);\n BlockState occupiedState = pLevel.getBlockState(structurePos);\n BlockState requiredStructure = MmbBlocks.ZINC_BOILER_STRUCTURAL.getDefaultState()\n .setValue(ZincBoilerStructure.FACING, targetSide.getOpposite());\n if (occupiedState == requiredStructure)\n continue;\n if (!occupiedState.getMaterial()\n .isReplaceable()) {\n pLevel.destroyBlock(pPos, false);\n return;\n }\n pLevel.setBlockAndUpdate(structurePos, requiredStructure);\n }\n }\n }\n\n @MethodsReturnNonnullByDefault\n private static class PlacementHelper extends PoleHelper<Direction> {\n\n\n private PlacementHelper() {\n super(state -> state.getBlock() instanceof ZincLargeBoilerBlock, state -> state.getValue(FACING).getAxis(), FACING);\n }\n\n @Override\n public Predicate<ItemStack> getItemPredicate() {\n return i -> i.getItem() instanceof BlockItem\n && ((BlockItem) i.getItem()).getBlock() instanceof ZincLargeBoilerBlock;\n }\n\n @Override\n public Predicate<BlockState> getStatePredicate() {\n return s -> s.getBlock() instanceof ZincLargeBoilerBlock || s.getBlock() instanceof ZincLargeBoilerBlock;\n }\n\n @Override\n public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,\n BlockHitResult ray) {\n PlacementOffset offset = super.getOffset(player, world, state, pos, ray);\n if (offset.isSuccessful())\n offset.withTransform(offset.getTransform()\n .andThen(s -> pickCorrectBoiler(s, world, offset.getBlockPos())));\n return offset;\n }\n\n }\n\n @SuppressWarnings(\"unused\")\n public static BlockState pickCorrectBoiler(BlockState stateForPlacement, Level level, BlockPos pos) {\n return stateForPlacement;\n }\n\n\n}" }, { "identifier": "ZincLargeBoilerBlockItem", "path": "src/main/java/com/mangomilk/design_decor/blocks/large_boiler/zinc/ZincLargeBoilerBlockItem.java", "snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class ZincLargeBoilerBlockItem extends BlockItem {\n\n public ZincLargeBoilerBlockItem(Block p_40565_, Properties p_40566_) {\n super(p_40565_, p_40566_);\n }\n\n @Override\n public InteractionResult place(BlockPlaceContext ctx) {\n InteractionResult result = super.place(ctx);\n if (result != InteractionResult.FAIL)\n return result;\n Direction clickedFace = ctx.getClickedFace();\n if (clickedFace.getAxis() != ((ZincLargeBoilerBlock) getBlock()).getAxisForPlacement(ctx))\n result = super.place(BlockPlaceContext.at(ctx, ctx.getClickedPos()\n .relative(clickedFace), clickedFace));\n if (result == InteractionResult.FAIL && ctx.getLevel()\n .isClientSide())\n DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> showBounds(ctx));\n return result;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void showBounds(BlockPlaceContext context) {\n BlockPos pos = context.getClickedPos();\n Direction.Axis axis = ((ZincLargeBoilerBlock) getBlock()).getAxisForPlacement(context);\n Vec3 contract = Vec3.atLowerCornerOf(Direction.get(Direction.AxisDirection.POSITIVE, axis)\n .getNormal());\n if (!(context.getPlayer()instanceof LocalPlayer localPlayer))\n return;\n CreateClient.OUTLINER.showAABB(Pair.of(\"waterwheel\", pos), new AABB(pos).inflate(1)\n .deflate(contract.x, contract.y, contract.z))\n .colored(0xFF_ff5d6c);\n Lang.translate(\"large_water_wheel.not_enough_space\")\n .color(0xFF_ff5d6c)\n .sendStatus(localPlayer);\n }\n\n\n}" }, { "identifier": "REGISTRATE", "path": "src/main/java/com/mangomilk/design_decor/CreateMMBuilding.java", "snippet": "public static final CreateRegistrate REGISTRATE = CreateRegistrate.create(CreateMMBuilding.MOD_ID).creativeModeTab(()-> MmbCreativeModeTab.BUILDING);" }, { "identifier": "DecorBuilderTransformer", "path": "src/main/java/com/mangomilk/design_decor/base/DecorBuilderTransformer.java", "snippet": "public class DecorBuilderTransformer {\n\n public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> connected(\n Supplier<CTSpriteShiftEntry> ct) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get()))\n .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> layeredConnected(\n Supplier<CTSpriteShiftEntry> ct, Supplier<CTSpriteShiftEntry> ct2) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get(), p.models()\n .cubeColumn(c.getName(), ct.get()\n .getOriginalResourceLocation(),\n ct2.get()\n .getOriginalResourceLocation())))\n .onRegister(connectedTextures(() -> new HorizontalCTBehaviour(ct.get(), ct2.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n public static <B extends OrnateGrateBlock> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> ornateconnected(\n Supplier<CTSpriteShiftEntry> ct) {\n return b -> b.initialProperties(SharedProperties::stone)\n .blockstate((c, p) -> p.simpleBlock(c.get(), AssetLookup.standardModel(c, p)))\n .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get())))\n .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get())));\n }\n\n private static BlockBehaviour.Properties glassProperties(BlockBehaviour.Properties p) {\n return p.isValidSpawn(DecorBuilderTransformer::never)\n .isRedstoneConductor(DecorBuilderTransformer::never)\n .isSuffocating(DecorBuilderTransformer::never)\n .isViewBlocking(DecorBuilderTransformer::never)\n .noOcclusion();\n }\n\n public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(Supplier<ConnectedTextureBehaviour> behaviour) {\n return CreateMMBuilding.REGISTRATE.block(\"tinted_framed_glass\", ConnectedTintedGlassBlock::new)\n .onRegister(connectedTextures(behaviour))\n .addLayer(() -> RenderType::translucent)\n .initialProperties(() -> Blocks.TINTED_GLASS)\n .properties(DecorBuilderTransformer::glassProperties)\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get))\n .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, \"palettes/\", \"tinted_framed_glass\"))\n .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE)\n .lang(\"Tinted Framed Glass\")\n .item()\n .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS)\n .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()),\n p.modLoc(\"block/palettes/tinted_framed_glass\")))\n .build()\n .register();\n }\n\n public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(String type,String name, Supplier<ConnectedTextureBehaviour> behaviour) {\n return CreateMMBuilding.REGISTRATE.block(type + \"_tinted_framed_glass\", ConnectedTintedGlassBlock::new)\n .onRegister(connectedTextures(behaviour))\n .addLayer(() -> RenderType::translucent)\n .initialProperties(() -> Blocks.TINTED_GLASS)\n .properties(DecorBuilderTransformer::glassProperties)\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get))\n .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, \"palettes/\", type + \"_tinted_framed_glass\"))\n .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE)\n .lang(name + \" Tinted Framed Glass\")\n .item()\n .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS)\n .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()),\n p.modLoc(\"block/palettes/\" + type + \"_tinted_framed_glass\")))\n .build()\n .register();\n }\n\n\n\n\n public static BlockEntry<Block> CastelBricks(String id, String lang, MaterialColor color, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Brick Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_bricks\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_bricks\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Brick Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Brick Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_bricks\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Bricks\")\n .register();\n }\n\n public static BlockEntry<Block> CastelBricks(String id, String lang, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Brick Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_bricks\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_bricks\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Brick Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_brick_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_bricks\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Brick Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_bricks\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Bricks\")\n .register();\n }\n public static BlockEntry<Block> CastelTiles(String id, String lang, MaterialColor color, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Tile Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_tiles\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_tiles\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Tile Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Tile Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_tiles\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.color(color))\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Tiles\")\n .register();\n }\n public static BlockEntry<Block> CastelTiles(String id, String lang, Block block) {\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_stairs\", p -> new StairBlock(block.defaultBlockState(), p))\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"stairs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.stairsBlock(c.get(), CreateMMBuilding.asResource(\"block/stairs/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"stairs\"))\n .build()\n .lang(lang + \" Castel Tile Stairs\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_slab\", SlabBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"slabs\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 2))\n .blockstate((c, p) -> p.slabBlock(c.get(), CreateMMBuilding.asResource(\"block/slabs/\" + id + \"_castel_tiles\"), CreateMMBuilding.asResource(\"block/\" + id + \"_castel_tiles\")))\n .item()\n .tag(MCItemTag(\"slabs\"))\n .build()\n .lang(lang + \" Castel Tile Slab\")\n .register();\n\n CreateMMBuilding.REGISTRATE.block(id + \"_castel_tile_wall\", WallBlock::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .tag(MCBlockTag(\"walls\"))\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .blockstate((c, p) -> p.wallBlock(c.get(), CreateMMBuilding.asResource(\"block/walls/\" + id + \"_castel_tiles\")))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .tag(MCItemTag(\"walls\"))\n .build()\n .lang(lang + \" Castel Tile Wall\")\n .register();\n\n return CreateMMBuilding.REGISTRATE.block(id + \"_castel_tiles\", Block::new)\n .initialProperties(() -> block)\n .properties(p -> p.destroyTime(1.25f))\n .transform(pickaxeOnly())\n .recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag(\"stone_types/\" + id)), c::get, 1))\n .item()\n .tag(CreateItemTag(\"stone_types/\" + id))\n .build()\n .lang(lang + \" Castel Tiles\")\n .register();\n }\n private static boolean never(BlockState p_235436_0_, BlockGetter p_235436_1_, BlockPos p_235436_2_) {return false;}\n private static Boolean never(BlockState p_235427_0_, BlockGetter p_235427_1_, BlockPos p_235427_2_, EntityType<?> p_235427_3_) {return false;}\n private static String palettesDir() {return \"block/palettes/\";}\n}" } ]
import com.mangomilk.design_decor.base.DecorBuilderTransformer; import com.mangomilk.design_decor.base.MmbSpriteShifts; import com.mangomilk.design_decor.blocks.*; import com.mangomilk.design_decor.blocks.SignBlock; import com.mangomilk.design_decor.blocks.chain.LargeChain; import com.mangomilk.design_decor.blocks.chain.TagDependentLargeChain; import com.mangomilk.design_decor.blocks.containers.red.RedContainerBlock; import com.mangomilk.design_decor.blocks.containers.red.RedContainerCTBehaviour; import com.mangomilk.design_decor.blocks.containers.red.RedContainerItem; import com.mangomilk.design_decor.blocks.containers.blue.BlueContainerBlock; import com.mangomilk.design_decor.blocks.containers.blue.BlueContainerCTBehaviour; import com.mangomilk.design_decor.blocks.containers.blue.BlueContainerItem; import com.mangomilk.design_decor.blocks.containers.green.GreenContainerBlock; import com.mangomilk.design_decor.blocks.containers.green.GreenContainerCTBehaviour; import com.mangomilk.design_decor.blocks.containers.green.GreenContainerItem; import com.mangomilk.design_decor.blocks.crushing_wheels.MmbCrushingWheelBlock; import com.mangomilk.design_decor.blocks.crushing_wheels.MmbCrushingWheelControllerBlock; import com.mangomilk.design_decor.blocks.diagonal_girder.DiagonalGirderBlock; import com.mangomilk.design_decor.blocks.diagonal_girder.DiagonalGirderGenerator; import com.mangomilk.design_decor.blocks.floodlight.FloodlightBlock; import com.mangomilk.design_decor.blocks.floodlight.FloodlightGenerator; import com.mangomilk.design_decor.blocks.gas_tank.GasTankBlock; import com.mangomilk.design_decor.blocks.glass.ConnectedTintedGlassBlock; import com.mangomilk.design_decor.blocks.industrial_gear.IndustrialGearBlock; import com.mangomilk.design_decor.blocks.industrial_gear.IndustrialGearBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.aluminum.AluminumBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.aluminum.AluminumLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.aluminum.AluminumLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.andesite.AndesiteBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.andesite.AndesiteLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.andesite.AndesiteLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.brass.BrassBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.brass.BrassLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.brass.BrassLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.capitalism.CapitalismBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.capitalism.CapitalismLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.capitalism.CapitalismLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.cast_iron.CastIronBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.cast_iron.CastIronLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.cast_iron.CastIronLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.copper.CopperBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.copper.CopperLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.copper.CopperLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.gold.GoldBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.gold.GoldLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.gold.GoldLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.industrial_iron.IndustrialIronBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.industrial_iron.IndustrialIronLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.industrial_iron.IndustrialIronLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.large_boiler.zinc.ZincBoilerStructure; import com.mangomilk.design_decor.blocks.large_boiler.zinc.ZincLargeBoilerBlock; import com.mangomilk.design_decor.blocks.large_boiler.zinc.ZincLargeBoilerBlockItem; import com.mangomilk.design_decor.blocks.millstone.block.*; import com.simibubi.create.AllTags; import com.simibubi.create.content.kinetics.BlockStressDefaults; import com.simibubi.create.content.kinetics.simpleRelays.BracketedKineticBlockModel; import com.simibubi.create.foundation.block.connected.HorizontalCTBehaviour; import com.simibubi.create.foundation.block.connected.SimpleCTBehaviour; import com.simibubi.create.foundation.data.AssetLookup; import com.simibubi.create.foundation.data.BlockStateGen; import com.simibubi.create.foundation.data.CreateRegistrate; import com.simibubi.create.foundation.data.SharedProperties; import com.tterrag.registrate.util.entry.BlockEntry; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.client.renderer.RenderType; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.MaterialColor; import net.minecraftforge.client.model.generators.ConfiguredModel; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.IForgeRegistry; import javax.annotation.ParametersAreNonnullByDefault; import java.util.Collections; import static com.mangomilk.design_decor.CreateMMBuilding.REGISTRATE; import static com.mangomilk.design_decor.base.DecorBuilderTransformer.*; import static com.simibubi.create.foundation.data.CreateRegistrate.connectedTextures; import static com.simibubi.create.foundation.data.ModelGen.customItemModel; import static com.simibubi.create.foundation.data.TagGen.axeOrPickaxe; import static com.simibubi.create.foundation.data.TagGen.pickaxeOnly;
71,327
package com.mangomilk.design_decor.registry; @SuppressWarnings({"unused", "removal"}) @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class MmbBlocks { //LAMPS
package com.mangomilk.design_decor.registry; @SuppressWarnings({"unused", "removal"}) @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class MmbBlocks { //LAMPS
public static final BlockEntry<LampBlock> BRASS_LAMP = REGISTRATE.block("brass_lamp", LampBlock::new)
51
2023-10-14 21:51:49+00:00
128k
Hoto-Mocha/Re-ARranged-Pixel-Dungeon
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/traps/CursingTrap.java
[ { "identifier": "Assets", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/Assets.java", "snippet": "public class Assets {\n\n\tpublic static class Effects {\n\t\tpublic static final String EFFECTS = \"effects/effects.png\";\n\t\tpublic static final String FIREBALL = \"effects/fireball.png\";\n\t\tpublic static final String SPECKS = \"effects/specks.png\";\n\t\tpublic static final String SPELL_ICONS = \"effects/spell_icons.png\";\n\t}\n\n\tpublic static class Environment {\n\t\tpublic static final String TERRAIN_FEATURES = \"environment/terrain_features.png\";\n\n\t\tpublic static final String VISUAL_GRID = \"environment/visual_grid.png\";\n\t\tpublic static final String WALL_BLOCKING= \"environment/wall_blocking.png\";\n\n\t\tpublic static final String TILES_SEWERS = \"environment/tiles_sewers.png\";\n\t\tpublic static final String TILES_PRISON = \"environment/tiles_prison.png\";\n\t\tpublic static final String TILES_CAVES = \"environment/tiles_caves.png\";\n\t\tpublic static final String TILES_CITY = \"environment/tiles_city.png\";\n\t\tpublic static final String TILES_HALLS = \"environment/tiles_halls.png\";\n\t\tpublic static final String TILES_TEMPLE = \"environment/tiles_temple.png\";\n\t\tpublic static final String TILES_LABS\t= \"environment/tiles_labs.png\";\n\n\t\tpublic static final String WATER_SEWERS = \"environment/water0.png\";\n\t\tpublic static final String WATER_PRISON = \"environment/water1.png\";\n\t\tpublic static final String WATER_CAVES = \"environment/water2.png\";\n\t\tpublic static final String WATER_CITY = \"environment/water3.png\";\n\t\tpublic static final String WATER_HALLS = \"environment/water4.png\";\n\t\tpublic static final String WATER_TEMPLE = \"environment/water0_temple.png\";\n\t\tpublic static final String WATER_LABS\t= \"environment/water5.png\";\n\n\t\tpublic static final String WEAK_FLOOR = \"environment/custom_tiles/weak_floor.png\";\n\t\tpublic static final String SEWER_BOSS = \"environment/custom_tiles/sewer_boss.png\";\n\t\tpublic static final String PRISON_QUEST = \"environment/custom_tiles/prison_quest.png\";\n\t\tpublic static final String PRISON_EXIT = \"environment/custom_tiles/prison_exit.png\";\n\t\tpublic static final String CAVES_QUEST = \"environment/custom_tiles/caves_quest.png\";\n\t\tpublic static final String CAVES_BOSS = \"environment/custom_tiles/caves_boss.png\";\n\t\tpublic static final String CITY_BOSS = \"environment/custom_tiles/city_boss.png\";\n\t\tpublic static final String HALLS_SP = \"environment/custom_tiles/halls_special.png\";\n\t\tpublic static final String TEMPLE_SP = \"environment/custom_tiles/temple_special.png\";\n\t}\n\t\n\t//TODO include other font assets here? Some are platform specific though...\n\tpublic static class Fonts {\n\t\tpublic static final String PIXELFONT= \"fonts/pixel_font.png\";\n\t}\n\n\tpublic static class Interfaces {\n\t\tpublic static final String ARCS_BG = \"interfaces/arcs1.png\";\n\t\tpublic static final String ARCS_FG = \"interfaces/arcs2.png\";\n\n\t\tpublic static final String BANNERS = \"interfaces/banners.png\";\n\t\tpublic static final String BADGES = \"interfaces/badges.png\";\n\t\tpublic static final String LOCKED = \"interfaces/locked_badge.png\";\n\n\t\tpublic static final String CHROME = \"interfaces/chrome.png\";\n\t\tpublic static final String ICONS = \"interfaces/icons.png\";\n\t\tpublic static final String STATUS = \"interfaces/status_pane.png\";\n\t\tpublic static final String MENU = \"interfaces/menu_pane.png\";\n\t\tpublic static final String MENU_BTN = \"interfaces/menu_button.png\";\n\t\tpublic static final String TOOLBAR = \"interfaces/toolbar.png\";\n\t\tpublic static final String SHADOW = \"interfaces/shadow.png\";\n\t\tpublic static final String BOSSHP = \"interfaces/boss_hp.png\";\n\n\t\tpublic static final String SURFACE = \"interfaces/surface.png\";\n\n\t\tpublic static final String LOADING_SEWERS = \"interfaces/loading_sewers.png\";\n\t\tpublic static final String LOADING_PRISON = \"interfaces/loading_prison.png\";\n\t\tpublic static final String LOADING_CAVES = \"interfaces/loading_caves.png\";\n\t\tpublic static final String LOADING_CITY = \"interfaces/loading_city.png\";\n\t\tpublic static final String LOADING_HALLS = \"interfaces/loading_halls.png\";\n\n\t\tpublic static final String BUFFS_SMALL = \"interfaces/buffs.png\";\n\t\tpublic static final String BUFFS_LARGE = \"interfaces/large_buffs.png\";\n\n\t\tpublic static final String TALENT_ICONS = \"interfaces/talent_icons.png\";\n\t\tpublic static final String TALENT_BUTTON = \"interfaces/talent_button.png\";\n\n\t\tpublic static final String HERO_ICONS = \"interfaces/hero_icons.png\";\n\n\t\tpublic static final String RADIAL_MENU = \"interfaces/radial_menu.png\";\n\t}\n\n\t//these points to resource bundles, not raw asset files\n\tpublic static class Messages {\n\t\tpublic static final String ACTORS = \"messages/actors/actors\";\n\t\tpublic static final String ITEMS = \"messages/items/items\";\n\t\tpublic static final String JOURNAL = \"messages/journal/journal\";\n\t\tpublic static final String LEVELS = \"messages/levels/levels\";\n\t\tpublic static final String MISC = \"messages/misc/misc\";\n\t\tpublic static final String PLANTS = \"messages/plants/plants\";\n\t\tpublic static final String SCENES = \"messages/scenes/scenes\";\n\t\tpublic static final String UI = \"messages/ui/ui\";\n\t\tpublic static final String WINDOWS = \"messages/windows/windows\";\n\t}\n\n\tpublic static class Music {\n\t\tpublic static final String THEME_1 = \"music/theme_1.ogg\";\n\t\tpublic static final String THEME_2 = \"music/theme_2.ogg\";\n\t\tpublic static final String THEME_FINALE = \"music/theme_finale.ogg\";\n\n\t\tpublic static final String SEWERS_1 = \"music/sewers_1.ogg\";\n\t\tpublic static final String SEWERS_2 = \"music/sewers_2.ogg\";\n\t\tpublic static final String SEWERS_3 = \"music/sewers_3.ogg\";\n\t\tpublic static final String SEWERS_TENSE = \"music/sewers_tense.ogg\";\n\t\tpublic static final String SEWERS_BOSS = \"music/sewers_boss.ogg\";\n\n\t\tpublic static final String PRISON_1 = \"music/prison_1.ogg\";\n\t\tpublic static final String PRISON_2 = \"music/prison_2.ogg\";\n\t\tpublic static final String PRISON_3 = \"music/prison_3.ogg\";\n\t\tpublic static final String PRISON_TENSE = \"music/prison_tense.ogg\";\n\t\tpublic static final String PRISON_BOSS = \"music/prison_boss.ogg\";\n\n\t\tpublic static final String CAVES_1 = \"music/caves_1.ogg\";\n\t\tpublic static final String CAVES_2 = \"music/caves_2.ogg\";\n\t\tpublic static final String CAVES_3 = \"music/caves_3.ogg\";\n\t\tpublic static final String CAVES_TENSE = \"music/caves_tense.ogg\";\n\t\tpublic static final String CAVES_BOSS = \"music/caves_boss.ogg\";\n\t\tpublic static final String CAVES_BOSS_FINALE = \"music/caves_boss_finale.ogg\";\n\n\t\tpublic static final String CITY_1 = \"music/city_1.ogg\";\n\t\tpublic static final String CITY_2 = \"music/city_2.ogg\";\n\t\tpublic static final String CITY_3 = \"music/city_3.ogg\";\n\t\tpublic static final String CITY_TENSE = \"music/city_tense.ogg\";\n\t\tpublic static final String CITY_BOSS = \"music/city_boss.ogg\";\n\t\tpublic static final String CITY_BOSS_FINALE = \"music/city_boss_finale.ogg\";\n\n\t\tpublic static final String HALLS_1 = \"music/halls_1.ogg\";\n\t\tpublic static final String HALLS_2 = \"music/halls_2.ogg\";\n\t\tpublic static final String HALLS_3 = \"music/halls_3.ogg\";\n\t\tpublic static final String HALLS_TENSE = \"music/halls_tense.ogg\";\n\t\tpublic static final String HALLS_BOSS = \"music/halls_boss.ogg\";\n\t\tpublic static final String HALLS_BOSS_FINALE = \"music/halls_boss_finale.ogg\";\n\t}\n\n\tpublic static class Sounds {\n\t\tpublic static final String CLICK = \"sounds/click.mp3\";\n\t\tpublic static final String BADGE = \"sounds/badge.mp3\";\n\t\tpublic static final String GOLD = \"sounds/gold.mp3\";\n\n\t\tpublic static final String OPEN = \"sounds/door_open.mp3\";\n\t\tpublic static final String UNLOCK = \"sounds/unlock.mp3\";\n\t\tpublic static final String ITEM = \"sounds/item.mp3\";\n\t\tpublic static final String DEWDROP = \"sounds/dewdrop.mp3\";\n\t\tpublic static final String STEP = \"sounds/step.mp3\";\n\t\tpublic static final String WATER = \"sounds/water.mp3\";\n\t\tpublic static final String GRASS = \"sounds/grass.mp3\";\n\t\tpublic static final String TRAMPLE = \"sounds/trample.mp3\";\n\t\tpublic static final String STURDY = \"sounds/sturdy.mp3\";\n\n\t\tpublic static final String HIT = \"sounds/hit.mp3\";\n\t\tpublic static final String MISS = \"sounds/miss.mp3\";\n\t\tpublic static final String HIT_SLASH = \"sounds/hit_slash.mp3\";\n\t\tpublic static final String HIT_STAB = \"sounds/hit_stab.mp3\";\n\t\tpublic static final String HIT_CRUSH = \"sounds/hit_crush.mp3\";\n\t\tpublic static final String HIT_MAGIC = \"sounds/hit_magic.mp3\";\n\t\tpublic static final String HIT_STRONG = \"sounds/hit_strong.mp3\";\n\t\tpublic static final String HIT_PARRY = \"sounds/hit_parry.mp3\";\n\t\tpublic static final String HIT_ARROW = \"sounds/hit_arrow.mp3\";\n\t\tpublic static final String ATK_SPIRITBOW = \"sounds/atk_spiritbow.mp3\";\n\t\tpublic static final String ATK_CROSSBOW = \"sounds/atk_crossbow.mp3\";\n\t\tpublic static final String HEALTH_WARN = \"sounds/health_warn.mp3\";\n\t\tpublic static final String HEALTH_CRITICAL = \"sounds/health_critical.mp3\";\n\n\t\tpublic static final String DESCEND = \"sounds/descend.mp3\";\n\t\tpublic static final String EAT = \"sounds/eat.mp3\";\n\t\tpublic static final String READ = \"sounds/read.mp3\";\n\t\tpublic static final String LULLABY = \"sounds/lullaby.mp3\";\n\t\tpublic static final String DRINK = \"sounds/drink.mp3\";\n\t\tpublic static final String SHATTER = \"sounds/shatter.mp3\";\n\t\tpublic static final String ZAP = \"sounds/zap.mp3\";\n\t\tpublic static final String LIGHTNING= \"sounds/lightning.mp3\";\n\t\tpublic static final String LEVELUP = \"sounds/levelup.mp3\";\n\t\tpublic static final String DEATH = \"sounds/death.mp3\";\n\t\tpublic static final String CHALLENGE= \"sounds/challenge.mp3\";\n\t\tpublic static final String CURSED = \"sounds/cursed.mp3\";\n\t\tpublic static final String TRAP = \"sounds/trap.mp3\";\n\t\tpublic static final String EVOKE = \"sounds/evoke.mp3\";\n\t\tpublic static final String TOMB = \"sounds/tomb.mp3\";\n\t\tpublic static final String ALERT = \"sounds/alert.mp3\";\n\t\tpublic static final String MELD = \"sounds/meld.mp3\";\n\t\tpublic static final String BOSS = \"sounds/boss.mp3\";\n\t\tpublic static final String BLAST = \"sounds/blast.mp3\";\n\t\tpublic static final String PLANT = \"sounds/plant.mp3\";\n\t\tpublic static final String RAY = \"sounds/ray.mp3\";\n\t\tpublic static final String BEACON = \"sounds/beacon.mp3\";\n\t\tpublic static final String TELEPORT = \"sounds/teleport.mp3\";\n\t\tpublic static final String CHARMS = \"sounds/charms.mp3\";\n\t\tpublic static final String MASTERY = \"sounds/mastery.mp3\";\n\t\tpublic static final String PUFF = \"sounds/puff.mp3\";\n\t\tpublic static final String ROCKS = \"sounds/rocks.mp3\";\n\t\tpublic static final String BURNING = \"sounds/burning.mp3\";\n\t\tpublic static final String FALLING = \"sounds/falling.mp3\";\n\t\tpublic static final String GHOST = \"sounds/ghost.mp3\";\n\t\tpublic static final String SECRET = \"sounds/secret.mp3\";\n\t\tpublic static final String BONES = \"sounds/bones.mp3\";\n\t\tpublic static final String BEE = \"sounds/bee.mp3\";\n\t\tpublic static final String DEGRADE = \"sounds/degrade.mp3\";\n\t\tpublic static final String MIMIC = \"sounds/mimic.mp3\";\n\t\tpublic static final String DEBUFF = \"sounds/debuff.mp3\";\n\t\tpublic static final String CHARGEUP = \"sounds/chargeup.mp3\";\n\t\tpublic static final String GAS = \"sounds/gas.mp3\";\n\t\tpublic static final String CHAINS = \"sounds/chains.mp3\";\n\t\tpublic static final String SCAN = \"sounds/scan.mp3\";\n\t\tpublic static final String SHEEP = \"sounds/sheep.mp3\";\n\t\tpublic static final String MINE = \"sounds/mine.mp3\";\n\n\t\tpublic static final String[] all = new String[]{\n\t\t\t\tCLICK, BADGE, GOLD,\n\n\t\t\t\tOPEN, UNLOCK, ITEM, DEWDROP, STEP, WATER, GRASS, TRAMPLE, STURDY,\n\n\t\t\t\tHIT, MISS, HIT_SLASH, HIT_STAB, HIT_CRUSH, HIT_MAGIC, HIT_STRONG, HIT_PARRY,\n\t\t\t\tHIT_ARROW, ATK_SPIRITBOW, ATK_CROSSBOW, HEALTH_WARN, HEALTH_CRITICAL,\n\n\t\t\t\tDESCEND, EAT, READ, LULLABY, DRINK, SHATTER, ZAP, LIGHTNING, LEVELUP, DEATH,\n\t\t\t\tCHALLENGE, CURSED, TRAP, EVOKE, TOMB, ALERT, MELD, BOSS, BLAST, PLANT, RAY, BEACON,\n\t\t\t\tTELEPORT, CHARMS, MASTERY, PUFF, ROCKS, BURNING, FALLING, GHOST, SECRET, BONES,\n\t\t\t\tBEE, DEGRADE, MIMIC, DEBUFF, CHARGEUP, GAS, CHAINS, SCAN, SHEEP, MINE\n\t\t};\n\t}\n\n\tpublic static class Splashes {\n\t\tpublic static final String WARRIOR = \"splashes/warrior.jpg\";\n\t\tpublic static final String MAGE = \"splashes/mage.jpg\";\n\t\tpublic static final String ROGUE = \"splashes/rogue.jpg\";\n\t\tpublic static final String HUNTRESS = \"splashes/huntress.jpg\";\n\t\tpublic static final String DUELIST = \"splashes/duelist.jpg\";\n\t\tpublic static final String GUNNER\t= \"splashes/gunner.jpg\";\n\t\tpublic static final String SAMURAI = \"splashes/samurai.jpg\";\n\t\tpublic static final String PLANTER\t= \"splashes/planter.jpg\";\n\t\tpublic static final String KNIGHT\t= \"splashes/knight.jpg\";\n\t\tpublic static final String NURSE\t= \"splashes/nurse.jpg\";\n\t}\n\n\tpublic static class Sprites {\n\t\tpublic static final String ITEMS = \"sprites/items.png\";\n\t\tpublic static final String ITEM_ICONS = \"sprites/item_icons.png\";\n\n\t\tpublic static final String WARRIOR = \"sprites/warrior.png\";\n\t\tpublic static final String MAGE = \"sprites/mage.png\";\n\t\tpublic static final String ROGUE = \"sprites/rogue.png\";\n\t\tpublic static final String HUNTRESS = \"sprites/huntress.png\";\n\t\tpublic static final String DUELIST = \"sprites/duelist.png\";\n\t\tpublic static final String GUNNER\t= \"sprites/gunner.png\";\n\t\tpublic static final String SAMURAI\t= \"sprites/samurai.png\";\n\t\tpublic static final String PLANTER\t= \"sprites/planter.png\";\n\t\tpublic static final String KNIGHT\t= \"sprites/knight.png\";\n\t\tpublic static final String NURSE\t= \"sprites/nurse.png\";\n\t\tpublic static final String AVATARS = \"sprites/avatars.png\";\n\t\tpublic static final String PET = \"sprites/pet.png\";\n\t\tpublic static final String AMULET = \"sprites/amulet.png\";\n\n\t\tpublic static final String RAT = \"sprites/rat.png\";\n\t\tpublic static final String BRUTE = \"sprites/brute.png\";\n\t\tpublic static final String SPINNER = \"sprites/spinner.png\";\n\t\tpublic static final String DM300 = \"sprites/dm300.png\";\n\t\tpublic static final String WRAITH = \"sprites/wraith.png\";\n\t\tpublic static final String UNDEAD = \"sprites/undead.png\";\n\t\tpublic static final String KING = \"sprites/king.png\";\n\t\tpublic static final String PIRANHA = \"sprites/piranha.png\";\n\t\tpublic static final String EYE = \"sprites/eye.png\";\n\t\tpublic static final String GNOLL = \"sprites/gnoll.png\";\n\t\tpublic static final String CRAB = \"sprites/crab.png\";\n\t\tpublic static final String GOO = \"sprites/goo.png\";\n\t\tpublic static final String SWARM = \"sprites/swarm.png\";\n\t\tpublic static final String SKELETON = \"sprites/skeleton.png\";\n\t\tpublic static final String SHAMAN = \"sprites/shaman.png\";\n\t\tpublic static final String THIEF = \"sprites/thief.png\";\n\t\tpublic static final String TENGU = \"sprites/tengu.png\";\n\t\tpublic static final String SHEEP = \"sprites/sheep.png\";\n\t\tpublic static final String KEEPER = \"sprites/shopkeeper.png\";\n\t\tpublic static final String BAT = \"sprites/bat.png\";\n\t\tpublic static final String ELEMENTAL= \"sprites/elemental.png\";\n\t\tpublic static final String MONK = \"sprites/monk.png\";\n\t\tpublic static final String WARLOCK = \"sprites/warlock.png\";\n\t\tpublic static final String GOLEM = \"sprites/golem.png\";\n\t\tpublic static final String STATUE = \"sprites/statue.png\";\n\t\tpublic static final String SUCCUBUS = \"sprites/succubus.png\";\n\t\tpublic static final String SCORPIO = \"sprites/scorpio.png\";\n\t\tpublic static final String FISTS = \"sprites/yog_fists.png\";\n\t\tpublic static final String YOG = \"sprites/yog.png\";\n\t\tpublic static final String LARVA = \"sprites/larva.png\";\n\t\tpublic static final String GHOST = \"sprites/ghost.png\";\n\t\tpublic static final String MAKER = \"sprites/wandmaker.png\";\n\t\tpublic static final String TROLL = \"sprites/blacksmith.png\";\n\t\tpublic static final String IMP = \"sprites/demon.png\";\n\t\tpublic static final String RATKING = \"sprites/ratking.png\";\n\t\tpublic static final String BEE = \"sprites/bee.png\";\n\t\tpublic static final String MIMIC = \"sprites/mimic.png\";\n\t\tpublic static final String ROT_LASH = \"sprites/rot_lasher.png\";\n\t\tpublic static final String ROT_HEART= \"sprites/rot_heart.png\";\n\t\tpublic static final String GUARD = \"sprites/guard.png\";\n\t\tpublic static final String WARDS = \"sprites/wards.png\";\n\t\tpublic static final String GUARDIAN = \"sprites/guardian.png\";\n\t\tpublic static final String SLIME = \"sprites/slime.png\";\n\t\tpublic static final String SNAKE = \"sprites/snake.png\";\n\t\tpublic static final String NECRO = \"sprites/necromancer.png\";\n\t\tpublic static final String GHOUL = \"sprites/ghoul.png\";\n\t\tpublic static final String RIPPER = \"sprites/ripper.png\";\n\t\tpublic static final String SPAWNER = \"sprites/spawner.png\";\n\t\tpublic static final String DM100 = \"sprites/dm100.png\";\n\t\tpublic static final String PYLON = \"sprites/pylon.png\";\n\t\tpublic static final String DM200 = \"sprites/dm200.png\";\n\t\tpublic static final String LOTUS = \"sprites/lotus.png\";\n\t\tpublic static final String NINJA_LOG= \"sprites/ninja_log.png\";\n\t\tpublic static final String SPIRIT_HAWK= \"sprites/spirit_hawk.png\";\n\t\tpublic static final String RED_SENTRY= \"sprites/red_sentry.png\";\n\t\tpublic static final String NEW_SENTRY= \"sprites/new_sentry.png\";\n\t\tpublic static final String CRYSTAL_WISP= \"sprites/crystal_wisp.png\";\n\t\tpublic static final String CRYSTAL_GUARDIAN= \"sprites/crystal_guardian.png\";\n\t\tpublic static final String CRYSTAL_SPIRE= \"sprites/crystal_spire.png\";\n\t\tpublic static final String GNOLL_GUARD= \"sprites/gnoll_guard.png\";\n\n\t\tpublic static final String SOLDIER= \"sprites/soldier.png\";\n\t\tpublic static final String RESEARCHER= \"sprites/researcher.png\";\n\t\tpublic static final String TANK= \"sprites/tank.png\";\n\t\tpublic static final String SUPRESSION= \"sprites/supression.png\";\n\t\tpublic static final String MEDIC= \"sprites/medic.png\";\n\t\tpublic static final String REBEL= \"sprites/rebel.png\";\n\t}\n}" }, { "identifier": "Dungeon", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/Dungeon.java", "snippet": "public class Dungeon {\n\n\t//enum of items which have limited spawns, records how many have spawned\n\t//could all be their own separate numbers, but this allows iterating, much nicer for bundling/initializing.\n\tpublic static enum LimitedDrops {\n\t\t//limited world drops\n\t\tSTRENGTH_POTIONS,\n\t\tUPGRADE_SCROLLS,\n\t\tARCANE_STYLI,\n\n\t\t//Health potion sources\n\t\t//enemies\n\t\tSWARM_HP,\n\t\tNECRO_HP,\n\t\tBAT_HP,\n\t\tWARLOCK_HP,\n\t\t//Demon spawners are already limited in their spawnrate, no need to limit their health drops\n\t\t//alchemy\n\t\tCOOKING_HP,\n\t\tBLANDFRUIT_SEED,\n\n\t\t//Other limited enemy drops\n\t\tSLIME_WEP,\n\t\tSKELE_WEP,\n\t\tTHEIF_MISC,\n\t\tGUARD_ARM,\n\t\tSHAMAN_WAND,\n\t\tDM200_EQUIP,\n\t\tGOLEM_EQUIP,\n\t\tSOLDIER_WEP,\n\t\tMEDIC_HP,\n\n\t\t//containers\n\t\tVELVET_POUCH,\n\t\tSCROLL_HOLDER,\n\t\tPOTION_BANDOLIER,\n\t\tMAGICAL_HOLSTER,\n\n\t\t//lore documents\n\t\tLORE_SEWERS,\n\t\tLORE_PRISON,\n\t\tLORE_CAVES,\n\t\tLORE_CITY,\n\t\tLORE_HALLS,\n\t\tLORE_LABS;\n\n\t\tpublic int count = 0;\n\n\t\t//for items which can only be dropped once, should directly access count otherwise.\n\t\tpublic boolean dropped(){\n\t\t\treturn count != 0;\n\t\t}\n\t\tpublic void drop(){\n\t\t\tcount = 1;\n\t\t}\n\n\t\tpublic static void reset(){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tlim.count = 0;\n\t\t\t}\n\t\t}\n\n\t\tpublic static void store( Bundle bundle ){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tbundle.put(lim.name(), lim.count);\n\t\t\t}\n\t\t}\n\n\t\tpublic static void restore( Bundle bundle ){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tif (bundle.contains(lim.name())){\n\t\t\t\t\tlim.count = bundle.getInt(lim.name());\n\t\t\t\t} else {\n\t\t\t\t\tlim.count = 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\n\t\t\t//pre-v2.2.0 saves\n\t\t\tif (Dungeon.version < 750\n\t\t\t\t\t&& Dungeon.isChallenged(Challenges.NO_SCROLLS)\n\t\t\t\t\t&& UPGRADE_SCROLLS.count > 0){\n\t\t\t\t//we now count SOU fully, and just don't drop every 2nd one\n\t\t\t\tUPGRADE_SCROLLS.count += UPGRADE_SCROLLS.count-1;\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic static int challenges;\n\tpublic static int mobsToChampion;\n\n\tpublic static Hero hero;\n\tpublic static Level level;\n\n\tpublic static QuickSlot quickslot = new QuickSlot();\n\t\n\tpublic static int depth;\n\t//determines path the hero is on. Current uses:\n\t// 0 is the default path\n\t// 1 is for quest sub-floors\n\tpublic static int branch;\n\n\t//keeps track of what levels the game should try to load instead of creating fresh\n\tpublic static ArrayList<Integer> generatedLevels = new ArrayList<>();\n\n\tpublic static int gold;\n\tpublic static int energy;\n\tpublic static int bullet;\n\n\tpublic static HashSet<Integer> chapters;\n\n\tpublic static SparseArray<ArrayList<Item>> droppedItems;\n\n\t//first variable is only assigned when game is started, second is updated every time game is saved\n\tpublic static int initialVersion;\n\tpublic static int version;\n\n\tpublic static boolean daily;\n\tpublic static boolean dailyReplay;\n\tpublic static String customSeedText = \"\";\n\tpublic static long seed;\n\t\n\tpublic static void init() {\n\n\t\tinitialVersion = version = Game.versionCode;\n\t\tchallenges = SPDSettings.challenges();\n\t\tmobsToChampion = -1;\n\n\t\tif (daily) {\n\t\t\t//Ensures that daily seeds are not in the range of user-enterable seeds\n\t\t\tseed = SPDSettings.lastDaily() + DungeonSeed.TOTAL_SEEDS;\n\t\t\tDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ROOT);\n\t\t\tformat.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\t\t\tcustomSeedText = format.format(new Date(SPDSettings.lastDaily()));\n\t\t} else if (!SPDSettings.customSeed().isEmpty()){\n\t\t\tcustomSeedText = SPDSettings.customSeed();\n\t\t\tseed = DungeonSeed.convertFromText(customSeedText);\n\t\t} else {\n\t\t\tcustomSeedText = \"\";\n\t\t\tseed = DungeonSeed.randomSeed();\n\t\t}\n\n\t\tActor.clear();\n\t\tActor.resetNextID();\n\n\t\t//offset seed slightly to avoid output patterns\n\t\tRandom.pushGenerator( seed+1 );\n\n\t\t\tScroll.initLabels();\n\t\t\tPotion.initColors();\n\t\t\tRing.initGems();\n\n\t\t\tSpecialRoom.initForRun();\n\t\t\tSecretRoom.initForRun();\n\n\t\t\tGenerator.fullReset();\n\n\t\tRandom.resetGenerators();\n\t\t\n\t\tStatistics.reset();\n\t\tNotes.reset();\n\n\t\tquickslot.reset();\n\t\tQuickSlotButton.reset();\n\t\tToolbar.swappedQuickslots = false;\n\t\t\n\t\tdepth = 1;\n\t\tbranch = 0;\n\t\tgeneratedLevels.clear();\n\n\t\tgold = 0;\n\t\tenergy = 0;\n\t\tbullet = 0;\n\n\t\tdroppedItems = new SparseArray<>();\n\n\t\tLimitedDrops.reset();\n\t\t\n\t\tchapters = new HashSet<>();\n\t\t\n\t\tGhost.Quest.reset();\n\t\tWandmaker.Quest.reset();\n\t\tBlacksmith.Quest.reset();\n\t\tImp.Quest.reset();\n\n\t\thero = new Hero();\n\t\thero.live();\n\t\t\n\t\tBadges.reset();\n\t\t\n\t\tGamesInProgress.selectedClass.initHero( hero );\n\t}\n\n\tpublic static boolean isChallenged( int mask ) {\n\t\treturn (challenges & mask) != 0;\n\t}\n\n\tpublic static boolean levelHasBeenGenerated(int depth, int branch){\n\t\treturn generatedLevels.contains(depth + 1000*branch);\n\t}\n\t\n\tpublic static Level newLevel() {\n\t\t\n\t\tDungeon.level = null;\n\t\tActor.clear();\n\t\t\n\t\tLevel level;\n\t\tif (branch == 0) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 1:\n\t\t\t\tcase 2:\n\t\t\t\tcase 3:\n\t\t\t\tcase 4:\n\t\t\t\t\tlevel = new SewerLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\tlevel = new SewerBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 6:\n\t\t\t\tcase 7:\n\t\t\t\tcase 8:\n\t\t\t\tcase 9:\n\t\t\t\t\tlevel = new PrisonLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 10:\n\t\t\t\t\tlevel = new PrisonBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 11:\n\t\t\t\tcase 12:\n\t\t\t\tcase 13:\n\t\t\t\tcase 14:\n\t\t\t\t\tlevel = new CavesLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 15:\n\t\t\t\t\tlevel = new CavesBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 16:\n\t\t\t\tcase 17:\n\t\t\t\tcase 18:\n\t\t\t\tcase 19:\n\t\t\t\t\tlevel = new CityLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tlevel = new CityBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 21:\n\t\t\t\tcase 22:\n\t\t\t\tcase 23:\n\t\t\t\tcase 24:\n\t\t\t\t\tlevel = new HallsLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 25:\n\t\t\t\t\tlevel = new HallsBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 26:\n\t\t\t\tcase 27:\n\t\t\t\tcase 28:\n\t\t\t\tcase 29:\n\t\t\t\t\tlevel = new LabsLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 30:\n\t\t\t\t\tlevel = new LabsBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 31:\n\t\t\t\t\tlevel = new NewLastLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else if (branch == 1) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 11:\n\t\t\t\tcase 12:\n\t\t\t\tcase 13:\n\t\t\t\tcase 14:\n\t\t\t\t\tlevel = new MiningLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else if (branch == 2) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 16:\n\t\t\t\tcase 17:\n\t\t\t\tcase 18:\n\t\t\t\tcase 19:\n\t\t\t\t\tlevel = new TempleLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tlevel = new TempleLastLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else {\n\t\t\tlevel = new DeadEndLevel();\n\t\t}\n\n\t\t//dead end levels get cleared, don't count as generated\n\t\tif (!(level instanceof DeadEndLevel)){\n\t\t\t//this assumes that we will never have a depth value outside the range 0 to 999\n\t\t\t// or -500 to 499, etc.\n\t\t\tif (!generatedLevels.contains(depth + 1000*branch)) {\n\t\t\t\tgeneratedLevels.add(depth + 1000 * branch);\n\t\t\t}\n\n\t\t\tif (depth > Statistics.deepestFloor && branch == 0) {\n\t\t\t\tStatistics.deepestFloor = depth;\n\n\t\t\t\tif (Statistics.qualifiedForNoKilling) {\n\t\t\t\t\tStatistics.completedWithNoKilling = true;\n\t\t\t\t} else {\n\t\t\t\t\tStatistics.completedWithNoKilling = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tlevel.create();\n\t\t\n\t\tif (branch == 0) Statistics.qualifiedForNoKilling = !bossLevel();\n\t\tStatistics.qualifiedForBossChallengeBadge = false;\n\t\t\n\t\treturn level;\n\t}\n\t\n\tpublic static void resetLevel() {\n\t\t\n\t\tActor.clear();\n\t\t\n\t\tlevel.reset();\n\t\tswitchLevel( level, level.entrance() );\n\t}\n\n\tpublic static long seedCurDepth(){\n\t\treturn seedForDepth(depth, branch);\n\t}\n\n\tpublic static long seedForDepth(int depth, int branch){\n\t\tint lookAhead = depth;\n\t\tlookAhead += 30*branch; //Assumes depth is always 1-30, and branch is always 0 or higher\n\n\t\tRandom.pushGenerator( seed );\n\n\t\t\tfor (int i = 0; i < lookAhead; i ++) {\n\t\t\t\tRandom.Long(); //we don't care about these values, just need to go through them\n\t\t\t}\n\t\t\tlong result = Random.Long();\n\n\t\tRandom.popGenerator();\n\t\treturn result;\n\t}\n\t\n\tpublic static boolean shopOnLevel() {\n\t\treturn (depth == 6 || depth == 11 || depth == 16 || depth == 26) && branch == 0;\n\t}\n\t\n\tpublic static boolean bossLevel() {\n\t\treturn bossLevel( depth );\n\t}\n\t\n\tpublic static boolean bossLevel( int depth ) {\n\t\treturn depth == 5 || depth == 10 || depth == 15 || depth == 20 || depth == 25|| depth == 30;\n\t}\n\n\t//value used for scaling of damage values and other effects.\n\t//is usually the dungeon depth, but can be set to 26 when ascending\n\tpublic static int scalingDepth(){\n\t\tif (Dungeon.hero != null && Dungeon.hero.buff(AscensionChallenge.class) != null){\n\t\t\treturn 31;\n\t\t} else {\n\t\t\treturn depth;\n\t\t}\n\t}\n\n\tpublic static boolean interfloorTeleportAllowed(){\n\t\tif (Dungeon.level.locked\n\t\t\t\t|| (Dungeon.hero != null && Dungeon.hero.belongings.getItem(Amulet.class) != null)\n\t\t\t\t|| (Dungeon.hero != null && Dungeon.hero.buff(OldAmulet.TempleCurse.class) != null)){\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\n\tpublic static void switchLevel( final Level level, int pos ) {\n\n\t\t//Position of -2 specifically means trying to place the hero the exit\n\t\tif (pos == -2){\n\t\t\tLevelTransition t = level.getTransition(LevelTransition.Type.REGULAR_EXIT);\n\t\t\tif (t != null) pos = t.cell();\n\t\t}\n\n\t\t//Place hero at the entrance if they are out of the map (often used for pox = -1)\n\t\t// or if they are in solid terrain (except in the mining level, where that happens normally)\n\t\tif (pos < 0 || pos >= level.length()\n\t\t\t\t|| (!(level instanceof MiningLevel) && !level.passable[pos] && !level.avoid[pos])){\n\t\t\tpos = level.getTransition(null).cell();\n\t\t}\n\t\t\n\t\tPathFinder.setMapSize(level.width(), level.height());\n\t\t\n\t\tDungeon.level = level;\n\t\thero.pos = pos;\n\n\t\tif (hero.buff(AscensionChallenge.class) != null){\n\t\t\thero.buff(AscensionChallenge.class).onLevelSwitch();\n\t\t}\n\n\t\tif (hero.buff(OldAmulet.TempleCurse.class) != null){\n\t\t\thero.buff(OldAmulet.TempleCurse.class).onLevelSwitch();\n\t\t}\n\n\t\tMob.restoreAllies( level, pos );\n\n\t\tActor.init();\n\n\t\tlevel.addRespawner();\n\t\t\n\t\tfor(Mob m : level.mobs){\n\t\t\tif (m.pos == hero.pos && !Char.hasProp(m, Char.Property.IMMOVABLE)){\n\t\t\t\t//displace mob\n\t\t\t\tfor(int i : PathFinder.NEIGHBOURS8){\n\t\t\t\t\tif (Actor.findChar(m.pos+i) == null && level.passable[m.pos + i]){\n\t\t\t\t\t\tm.pos += i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tLight light = hero.buff( Light.class );\n\t\thero.viewDistance = light == null ? level.viewDistance : Math.max( Light.DISTANCE, level.viewDistance );\n\t\t\n\t\thero.curAction = hero.lastAction = null;\n\n\t\tobserve();\n\t\ttry {\n\t\t\tsaveAll();\n\t\t} catch (IOException e) {\n\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t\t/*This only catches IO errors. Yes, this means things can go wrong, and they can go wrong catastrophically.\n\t\t\tBut when they do the user will get a nice 'report this issue' dialogue, and I can fix the bug.*/\n\t\t}\n\t}\n\n\tpublic static void dropToChasm( Item item ) {\n\t\tint depth = Dungeon.depth + 1;\n\t\tArrayList<Item> dropped = Dungeon.droppedItems.get( depth );\n\t\tif (dropped == null) {\n\t\t\tDungeon.droppedItems.put( depth, dropped = new ArrayList<>() );\n\t\t}\n\t\tdropped.add( item );\n\t}\n\n\tpublic static boolean posNeeded() {\n\t\t//2 POS each floor set\n\t\tint posLeftThisSet = 2 - (LimitedDrops.STRENGTH_POTIONS.count - (depth / 5) * 2);\n\t\tif (posLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\n\t\t//pos drops every two floors, (numbers 1-2, and 3-4) with a 50% chance for the earlier one each time.\n\t\tint targetPOSLeft = 2 - floorThisSet/2;\n\t\tif (floorThisSet % 2 == 1 && Random.Int(2) == 0) targetPOSLeft --;\n\n\t\tif (targetPOSLeft < posLeftThisSet) return true;\n\t\telse return false;\n\n\t}\n\t\n\tpublic static boolean souNeeded() {\n\t\tint souLeftThisSet;\n\t\t//3 SOU each floor set\n\t\tsouLeftThisSet = 3 - (LimitedDrops.UPGRADE_SCROLLS.count - (depth / 5) * 3);\n\t\tif (souLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\t\t//chance is floors left / scrolls left\n\t\treturn Random.Int(5 - floorThisSet) < souLeftThisSet;\n\t}\n\t\n\tpublic static boolean asNeeded() {\n\t\t//1 AS each floor set\n\t\tint asLeftThisSet = 1 - (LimitedDrops.ARCANE_STYLI.count - (depth / 5));\n\t\tif (asLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\t\t//chance is floors left / scrolls left\n\t\treturn Random.Int(5 - floorThisSet) < asLeftThisSet;\n\t}\n\n\tprivate static final String INIT_VER\t= \"init_ver\";\n\tprivate static final String VERSION\t\t= \"version\";\n\tprivate static final String SEED\t\t= \"seed\";\n\tprivate static final String CUSTOM_SEED\t= \"custom_seed\";\n\tprivate static final String DAILY\t = \"daily\";\n\tprivate static final String DAILY_REPLAY= \"daily_replay\";\n\tprivate static final String CHALLENGES\t= \"challenges\";\n\tprivate static final String MOBS_TO_CHAMPION\t= \"mobs_to_champion\";\n\tprivate static final String HERO\t\t= \"hero\";\n\tprivate static final String DEPTH\t\t= \"depth\";\n\tprivate static final String BRANCH\t\t= \"branch\";\n\tprivate static final String GENERATED_LEVELS = \"generated_levels\";\n\tprivate static final String GOLD\t\t= \"gold\";\n\tprivate static final String ENERGY\t\t= \"energy\";\n\tprivate static final String BULLET\t\t= \"bullet\";\n\tprivate static final String DROPPED = \"dropped%d\";\n\tprivate static final String PORTED = \"ported%d\";\n\tprivate static final String LEVEL\t\t= \"level\";\n\tprivate static final String LIMDROPS = \"limited_drops\";\n\tprivate static final String CHAPTERS\t= \"chapters\";\n\tprivate static final String QUESTS\t\t= \"quests\";\n\tprivate static final String BADGES\t\t= \"badges\";\n\n\tpublic static void saveGame( int save ) {\n\t\ttry {\n\t\t\tBundle bundle = new Bundle();\n\n\t\t\tbundle.put( INIT_VER, initialVersion );\n\t\t\tbundle.put( VERSION, version = Game.versionCode );\n\t\t\tbundle.put( SEED, seed );\n\t\t\tbundle.put( CUSTOM_SEED, customSeedText );\n\t\t\tbundle.put( DAILY, daily );\n\t\t\tbundle.put( DAILY_REPLAY, dailyReplay );\n\t\t\tbundle.put( CHALLENGES, challenges );\n\t\t\tbundle.put( MOBS_TO_CHAMPION, mobsToChampion );\n\t\t\tbundle.put( HERO, hero );\n\t\t\tbundle.put( DEPTH, depth );\n\t\t\tbundle.put( BRANCH, branch );\n\n\t\t\tbundle.put( GOLD, gold );\n\t\t\tbundle.put( ENERGY, energy );\n\t\t\tbundle.put( BULLET, bullet );\n\n\t\t\tfor (int d : droppedItems.keyArray()) {\n\t\t\t\tbundle.put(Messages.format(DROPPED, d), droppedItems.get(d));\n\t\t\t}\n\n\t\t\tquickslot.storePlaceholders( bundle );\n\n\t\t\tBundle limDrops = new Bundle();\n\t\t\tLimitedDrops.store( limDrops );\n\t\t\tbundle.put ( LIMDROPS, limDrops );\n\t\t\t\n\t\t\tint count = 0;\n\t\t\tint ids[] = new int[chapters.size()];\n\t\t\tfor (Integer id : chapters) {\n\t\t\t\tids[count++] = id;\n\t\t\t}\n\t\t\tbundle.put( CHAPTERS, ids );\n\t\t\t\n\t\t\tBundle quests = new Bundle();\n\t\t\tGhost\t\t.Quest.storeInBundle( quests );\n\t\t\tWandmaker\t.Quest.storeInBundle( quests );\n\t\t\tBlacksmith\t.Quest.storeInBundle( quests );\n\t\t\tImp\t\t\t.Quest.storeInBundle( quests );\n\t\t\tbundle.put( QUESTS, quests );\n\t\t\t\n\t\t\tSpecialRoom.storeRoomsInBundle( bundle );\n\t\t\tSecretRoom.storeRoomsInBundle( bundle );\n\t\t\t\n\t\t\tStatistics.storeInBundle( bundle );\n\t\t\tNotes.storeInBundle( bundle );\n\t\t\tGenerator.storeInBundle( bundle );\n\n\t\t\tint[] bundleArr = new int[generatedLevels.size()];\n\t\t\tfor (int i = 0; i < generatedLevels.size(); i++){\n\t\t\t\tbundleArr[i] = generatedLevels.get(i);\n\t\t\t}\n\t\t\tbundle.put( GENERATED_LEVELS, bundleArr);\n\t\t\t\n\t\t\tScroll.save( bundle );\n\t\t\tPotion.save( bundle );\n\t\t\tRing.save( bundle );\n\n\t\t\tActor.storeNextID( bundle );\n\t\t\t\n\t\t\tBundle badges = new Bundle();\n\t\t\tBadges.saveLocal( badges );\n\t\t\tbundle.put( BADGES, badges );\n\t\t\t\n\t\t\tFileUtils.bundleToFile( GamesInProgress.gameFile(save), bundle);\n\t\t\t\n\t\t} catch (IOException e) {\n\t\t\tGamesInProgress.setUnknown( save );\n\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t}\n\t}\n\t\n\tpublic static void saveLevel( int save ) throws IOException {\n\t\tBundle bundle = new Bundle();\n\t\tbundle.put( LEVEL, level );\n\t\t\n\t\tFileUtils.bundleToFile(GamesInProgress.depthFile( save, depth, branch ), bundle);\n\t}\n\t\n\tpublic static void saveAll() throws IOException {\n\t\tif (hero != null && (hero.isAlive() || WndResurrect.instance != null)) {\n\t\t\t\n\t\t\tActor.fixTime();\n\t\t\tupdateLevelExplored();\n\t\t\tsaveGame( GamesInProgress.curSlot );\n\t\t\tsaveLevel( GamesInProgress.curSlot );\n\n\t\t\tGamesInProgress.set( GamesInProgress.curSlot );\n\n\t\t}\n\t}\n\t\n\tpublic static void loadGame( int save ) throws IOException {\n\t\tloadGame( save, true );\n\t}\n\t\n\tpublic static void loadGame( int save, boolean fullLoad ) throws IOException {\n\t\t\n\t\tBundle bundle = FileUtils.bundleFromFile( GamesInProgress.gameFile( save ) );\n\n\t\t//pre-1.3.0 saves\n\t\tif (bundle.contains(INIT_VER)){\n\t\t\tinitialVersion = bundle.getInt( INIT_VER );\n\t\t} else {\n\t\t\tinitialVersion = bundle.getInt( VERSION );\n\t\t}\n\n\t\tversion = bundle.getInt( VERSION );\n\n\t\tseed = bundle.contains( SEED ) ? bundle.getLong( SEED ) : DungeonSeed.randomSeed();\n\t\tcustomSeedText = bundle.getString( CUSTOM_SEED );\n\t\tdaily = bundle.getBoolean( DAILY );\n\t\tdailyReplay = bundle.getBoolean( DAILY_REPLAY );\n\n\t\tActor.clear();\n\t\tActor.restoreNextID( bundle );\n\n\t\tquickslot.reset();\n\t\tQuickSlotButton.reset();\n\t\tToolbar.swappedQuickslots = false;\n\n\t\tDungeon.challenges = bundle.getInt( CHALLENGES );\n\t\tDungeon.mobsToChampion = bundle.getInt( MOBS_TO_CHAMPION );\n\t\t\n\t\tDungeon.level = null;\n\t\tDungeon.depth = -1;\n\t\t\n\t\tScroll.restore( bundle );\n\t\tPotion.restore( bundle );\n\t\tRing.restore( bundle );\n\n\t\tquickslot.restorePlaceholders( bundle );\n\t\t\n\t\tif (fullLoad) {\n\t\t\t\n\t\t\tLimitedDrops.restore( bundle.getBundle(LIMDROPS) );\n\n\t\t\tchapters = new HashSet<>();\n\t\t\tint ids[] = bundle.getIntArray( CHAPTERS );\n\t\t\tif (ids != null) {\n\t\t\t\tfor (int id : ids) {\n\t\t\t\t\tchapters.add( id );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tBundle quests = bundle.getBundle( QUESTS );\n\t\t\tif (!quests.isNull()) {\n\t\t\t\tGhost.Quest.restoreFromBundle( quests );\n\t\t\t\tWandmaker.Quest.restoreFromBundle( quests );\n\t\t\t\tBlacksmith.Quest.restoreFromBundle( quests );\n\t\t\t\tImp.Quest.restoreFromBundle( quests );\n\t\t\t} else {\n\t\t\t\tGhost.Quest.reset();\n\t\t\t\tWandmaker.Quest.reset();\n\t\t\t\tBlacksmith.Quest.reset();\n\t\t\t\tImp.Quest.reset();\n\t\t\t}\n\t\t\t\n\t\t\tSpecialRoom.restoreRoomsFromBundle(bundle);\n\t\t\tSecretRoom.restoreRoomsFromBundle(bundle);\n\t\t}\n\t\t\n\t\tBundle badges = bundle.getBundle(BADGES);\n\t\tif (!badges.isNull()) {\n\t\t\tBadges.loadLocal( badges );\n\t\t} else {\n\t\t\tBadges.reset();\n\t\t}\n\t\t\n\t\tNotes.restoreFromBundle( bundle );\n\t\t\n\t\thero = null;\n\t\thero = (Hero)bundle.get( HERO );\n\t\t\n\t\tdepth = bundle.getInt( DEPTH );\n\t\tbranch = bundle.getInt( BRANCH );\n\n\t\tgold = bundle.getInt( GOLD );\n\t\tenergy = bundle.getInt( ENERGY );\n\t\tbullet = bundle.getInt( BULLET );\n\n\t\tStatistics.restoreFromBundle( bundle );\n\t\tGenerator.restoreFromBundle( bundle );\n\n\t\tgeneratedLevels.clear();\n\t\tif (bundle.contains(GENERATED_LEVELS)){\n\t\t\tfor (int i : bundle.getIntArray(GENERATED_LEVELS)){\n\t\t\t\tgeneratedLevels.add(i);\n\t\t\t}\n\t\t//pre-v2.1.1 saves\n\t\t} else {\n\t\t\tfor (int i = 1; i <= Statistics.deepestFloor; i++){\n\t\t\t\tgeneratedLevels.add(i);\n\t\t\t}\n\t\t}\n\n\t\tdroppedItems = new SparseArray<>();\n\t\tfor (int i=1; i <= 31; i++) {\n\t\t\t\n\t\t\t//dropped items\n\t\t\tArrayList<Item> items = new ArrayList<>();\n\t\t\tif (bundle.contains(Messages.format( DROPPED, i )))\n\t\t\t\tfor (Bundlable b : bundle.getCollection( Messages.format( DROPPED, i ) ) ) {\n\t\t\t\t\titems.add( (Item)b );\n\t\t\t\t}\n\t\t\tif (!items.isEmpty()) {\n\t\t\t\tdroppedItems.put( i, items );\n\t\t\t}\n\n\t\t}\n\t}\n\t\n\tpublic static Level loadLevel( int save ) throws IOException {\n\t\t\n\t\tDungeon.level = null;\n\t\tActor.clear();\n\n\t\tBundle bundle = FileUtils.bundleFromFile( GamesInProgress.depthFile( save, depth, branch ));\n\n\t\tLevel level = (Level)bundle.get( LEVEL );\n\n\t\tif (level == null){\n\t\t\tthrow new IOException();\n\t\t} else {\n\t\t\treturn level;\n\t\t}\n\t}\n\t\n\tpublic static void deleteGame( int save, boolean deleteLevels ) {\n\n\t\tif (deleteLevels) {\n\t\t\tString folder = GamesInProgress.gameFolder(save);\n\t\t\tfor (String file : FileUtils.filesInDir(folder)){\n\t\t\t\tif (file.contains(\"depth\")){\n\t\t\t\t\tFileUtils.deleteFile(folder + \"/\" + file);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tFileUtils.overwriteFile(GamesInProgress.gameFile(save), 1);\n\t\t\n\t\tGamesInProgress.delete( save );\n\t}\n\t\n\tpublic static void preview( GamesInProgress.Info info, Bundle bundle ) {\n\t\tinfo.depth = bundle.getInt( DEPTH );\n\t\tinfo.version = bundle.getInt( VERSION );\n\t\tinfo.challenges = bundle.getInt( CHALLENGES );\n\t\tinfo.seed = bundle.getLong( SEED );\n\t\tinfo.customSeed = bundle.getString( CUSTOM_SEED );\n\t\tinfo.daily = bundle.getBoolean( DAILY );\n\t\tinfo.dailyReplay = bundle.getBoolean( DAILY_REPLAY );\n\n\t\tHero.preview( info, bundle.getBundle( HERO ) );\n\t\tStatistics.preview( info, bundle );\n\t}\n\t\n\tpublic static void fail( Object cause ) {\n\t\tif (WndResurrect.instance == null) {\n\t\t\tupdateLevelExplored();\n\t\t\tStatistics.gameWon = false;\n\t\t\tRankings.INSTANCE.submit( false, cause );\n\t\t}\n\t}\n\t\n\tpublic static void win( Object cause ) {\n\n\t\tupdateLevelExplored();\n\t\tStatistics.gameWon = true;\n\n\t\thero.belongings.identify();\n\n\t\tRankings.INSTANCE.submit( true, cause );\n\t}\n\n\tpublic static void updateLevelExplored(){\n\t\tif (branch == 0 && level instanceof RegularLevel && !Dungeon.bossLevel()){\n\t\t\tStatistics.floorsExplored.put( depth, level.isLevelExplored(depth));\n\t\t}\n\t}\n\n\t//default to recomputing based on max hero vision, in case vision just shrank/grew\n\tpublic static void observe(){\n\t\tint dist = Math.max(Dungeon.hero.viewDistance, 8);\n\t\tdist *= 1f + 0.25f*Dungeon.hero.pointsInTalent(Talent.FARSIGHT);\n\t\tdist *= 1f + 0.25f*Dungeon.hero.pointsInTalent(Talent.TELESCOPE);\n\n\t\tif (Dungeon.hero.buff(MagicalSight.class) != null){\n\t\t\tdist = Math.max( dist, MagicalSight.DISTANCE );\n\t\t}\n\n\t\tobserve( dist+1 );\n\t}\n\t\n\tpublic static void observe( int dist ) {\n\n\t\tif (level == null) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlevel.updateFieldOfView(hero, level.heroFOV);\n\n\t\tint x = hero.pos % level.width();\n\t\tint y = hero.pos / level.width();\n\t\n\t\t//left, right, top, bottom\n\t\tint l = Math.max( 0, x - dist );\n\t\tint r = Math.min( x + dist, level.width() - 1 );\n\t\tint t = Math.max( 0, y - dist );\n\t\tint b = Math.min( y + dist, level.height() - 1 );\n\t\n\t\tint width = r - l + 1;\n\t\tint height = b - t + 1;\n\t\t\n\t\tint pos = l + t * level.width();\n\t\n\t\tfor (int i = t; i <= b; i++) {\n\t\t\tBArray.or( level.visited, level.heroFOV, pos, width, level.visited );\n\t\t\tpos+=level.width();\n\t\t}\n\t\n\t\tGameScene.updateFog(l, t, width, height);\n\n\t\tif (hero.buff(MindVision.class) != null){\n\t\t\tfor (Mob m : level.mobs.toArray(new Mob[0])){\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1 - level.width(), 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1, 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1 + level.width(), 3, level.visited );\n\t\t\t\t//updates adjacent cells too\n\t\t\t\tGameScene.updateFog(m.pos, 2);\n\t\t\t}\n\t\t}\n\n\t\tif (hero.buff(Awareness.class) != null){\n\t\t\tfor (Heap h : level.heaps.valueList()){\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 - level.width(), 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1, 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 + level.width(), 3, level.visited );\n\t\t\t\tGameScene.updateFog(h.pos, 2);\n\t\t\t}\n\t\t}\n\n\t\tfor (TalismanOfForesight.CharAwareness c : hero.buffs(TalismanOfForesight.CharAwareness.class)){\n\t\t\tChar ch = (Char) Actor.findById(c.charID);\n\t\t\tif (ch == null || !ch.isAlive()) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(ch.pos, 2);\n\t\t}\n\n\t\tfor (TalismanOfForesight.HeapAwareness h : hero.buffs(TalismanOfForesight.HeapAwareness.class)){\n\t\t\tif (Dungeon.depth != h.depth || Dungeon.branch != h.branch) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(h.pos, 2);\n\t\t}\n\n\t\tfor (RevealedArea a : hero.buffs(RevealedArea.class)){\n\t\t\tif (Dungeon.depth != a.depth || Dungeon.branch != a.branch) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(a.pos, 2);\n\t\t}\n\n\t\tfor (Char ch : Actor.chars()){\n\t\t\tif (ch instanceof WandOfWarding.Ward\n\t\t\t\t\t|| ch instanceof WandOfRegrowth.Lotus\n\t\t\t\t\t|| ch instanceof SpiritHawk.HawkAlly){\n\t\t\t\tx = ch.pos % level.width();\n\t\t\t\ty = ch.pos / level.width();\n\n\t\t\t\t//left, right, top, bottom\n\t\t\t\tdist = ch.viewDistance+1;\n\t\t\t\tl = Math.max( 0, x - dist );\n\t\t\t\tr = Math.min( x + dist, level.width() - 1 );\n\t\t\t\tt = Math.max( 0, y - dist );\n\t\t\t\tb = Math.min( y + dist, level.height() - 1 );\n\n\t\t\t\twidth = r - l + 1;\n\t\t\t\theight = b - t + 1;\n\n\t\t\t\tpos = l + t * level.width();\n\n\t\t\t\tfor (int i = t; i <= b; i++) {\n\t\t\t\t\tBArray.or( level.visited, level.heroFOV, pos, width, level.visited );\n\t\t\t\t\tpos+=level.width();\n\t\t\t\t}\n\t\t\t\tGameScene.updateFog(ch.pos, dist);\n\t\t\t}\n\t\t}\n\n\t\tGameScene.afterObserve();\n\t}\n\n\t//we store this to avoid having to re-allocate the array with each pathfind\n\tprivate static boolean[] passable;\n\n\tprivate static void setupPassable(){\n\t\tif (passable == null || passable.length != Dungeon.level.length())\n\t\t\tpassable = new boolean[Dungeon.level.length()];\n\t\telse\n\t\t\tBArray.setFalse(passable);\n\t}\n\n\tpublic static boolean[] findPassable(Char ch, boolean[] pass, boolean[] vis, boolean chars){\n\t\treturn findPassable(ch, pass, vis, chars, chars);\n\t}\n\n\tpublic static boolean[] findPassable(Char ch, boolean[] pass, boolean[] vis, boolean chars, boolean considerLarge){\n\t\tsetupPassable();\n\t\tif (ch.flying || ch.buff( Amok.class ) != null) {\n\t\t\tBArray.or( pass, Dungeon.level.avoid, passable );\n\t\t} else {\n\t\t\tSystem.arraycopy( pass, 0, passable, 0, Dungeon.level.length() );\n\t\t}\n\n\t\tif (considerLarge && Char.hasProp(ch, Char.Property.LARGE)){\n\t\t\tBArray.and( passable, Dungeon.level.openSpace, passable );\n\t\t}\n\n\t\tch.modifyPassable(passable);\n\n\t\tif (chars) {\n\t\t\tfor (Char c : Actor.chars()) {\n\t\t\t\tif (vis[c.pos]) {\n\t\t\t\t\tpassable[c.pos] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn passable;\n\t}\n\n\tpublic static PathFinder.Path findPath(Char ch, int to, boolean[] pass, boolean[] vis, boolean chars) {\n\n\t\treturn PathFinder.find( ch.pos, to, findPassable(ch, pass, vis, chars) );\n\n\t}\n\t\n\tpublic static int findStep(Char ch, int to, boolean[] pass, boolean[] visible, boolean chars ) {\n\n\t\tif (Dungeon.level.adjacent( ch.pos, to )) {\n\t\t\treturn Actor.findChar( to ) == null && pass[to] ? to : -1;\n\t\t}\n\n\t\treturn PathFinder.getStep( ch.pos, to, findPassable(ch, pass, visible, chars) );\n\n\t}\n\t\n\tpublic static int flee( Char ch, int from, boolean[] pass, boolean[] visible, boolean chars ) {\n\t\tboolean[] passable = findPassable(ch, pass, visible, false, true);\n\t\tpassable[ch.pos] = true;\n\n\t\t//only consider other chars impassable if our retreat step may collide with them\n\t\tif (chars) {\n\t\t\tfor (Char c : Actor.chars()) {\n\t\t\t\tif (c.pos == from || Dungeon.level.adjacent(c.pos, ch.pos)) {\n\t\t\t\t\tpassable[c.pos] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//chars affected by terror have a shorter lookahead and can't approach the fear source\n\t\tboolean canApproachFromPos = ch.buff(Terror.class) == null && ch.buff(Dread.class) == null;\n\t\treturn PathFinder.getStepBack( ch.pos, from, canApproachFromPos ? 8 : 4, passable, canApproachFromPos );\n\t\t\n\t}\n\n}" }, { "identifier": "Hero", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/hero/Hero.java", "snippet": "public class Hero extends Char {\n\n\t{\n\t\tactPriority = HERO_PRIO;\n\t\t\n\t\talignment = Alignment.ALLY;\n\t}\n\t\n\tpublic static final int MAX_LEVEL = 30;\n\n\tpublic static final int STARTING_STR = 10;\n\t\n\tprivate static final float TIME_TO_REST\t\t = 1f;\n\tprivate static final float TIME_TO_SEARCH\t = 2f;\n\tprivate static final float HUNGER_FOR_SEARCH\t= 6f;\n\t\n\tpublic HeroClass heroClass = HeroClass.ROGUE;\n\tpublic HeroSubClass subClass = HeroSubClass.NONE;\n\tpublic ArmorAbility armorAbility = null;\n\tpublic ArrayList<LinkedHashMap<Talent, Integer>> talents = new ArrayList<>();\n\tpublic LinkedHashMap<Talent, Talent> metamorphedTalents = new LinkedHashMap<>();\n\t\n\tprivate int attackSkill = 10;\n\tprivate int defenseSkill = 5;\n\n\tpublic boolean ready = false;\n\tpublic boolean damageInterrupt = true;\n\tpublic HeroAction curAction = null;\n\tpublic HeroAction lastAction = null;\n\n\tprivate Char enemy;\n\t\n\tpublic boolean resting = false;\n\t\n\tpublic Belongings belongings;\n\t\n\tpublic int STR;\n\t\n\tpublic float awareness;\n\t\n\tpublic int lvl = 1;\n\tpublic int exp = 0;\n\t\n\tpublic int HTBoost = 0;\n\t\n\tprivate ArrayList<Mob> visibleEnemies;\n\n\t//This list is maintained so that some logic checks can be skipped\n\t// for enemies we know we aren't seeing normally, resulting in better performance\n\tpublic ArrayList<Mob> mindVisionEnemies = new ArrayList<>();\n\n\tpublic Hero() {\n\t\tsuper();\n\n\t\tHP = HT = (Dungeon.isChallenged(Challenges.SUPERMAN)) ? 10 : 20;\n\t\tSTR = STARTING_STR;\n\t\t\n\t\tbelongings = new Belongings( this );\n\t\t\n\t\tvisibleEnemies = new ArrayList<>();\n\t}\n\t\n\tpublic void updateHT( boolean boostHP ){\n\t\tint curHT = HT;\n\n\t\tHT = (Dungeon.isChallenged(Challenges.SUPERMAN)) ? 10 : 20 + 5 * (lvl-1) + HTBoost;\n\t\tif (this.hasTalent(Talent.MAX_HEALTH)) {\n\t\t\tHT += 5*this.pointsInTalent(Talent.MAX_HEALTH);\n\t\t}\n\t\tfloat multiplier = RingOfMight.HTMultiplier(this);\n\t\tHT = Math.round(multiplier * HT);\n\t\t\n\t\tif (buff(ElixirOfMight.HTBoost.class) != null){\n\t\t\tHT += buff(ElixirOfMight.HTBoost.class).boost();\n\t\t}\n\n\t\tif (buff(ElixirOfTalent.ElixirOfTalentHTBoost.class) != null){\n\t\t\tHT += buff(ElixirOfTalent.ElixirOfTalentHTBoost.class).boost();\n\t\t}\n\t\t\n\t\tif (boostHP){\n\t\t\tHP += Math.max(HT - curHT, 0);\n\t\t}\n\t\tHP = Math.min(HP, HT);\n\t}\n\n\tpublic int STR() {\n\t\tint strBonus = 0;\n\n\t\tstrBonus += RingOfMight.strengthBonus( this );\n\t\t\n\t\tAdrenalineSurge buff = buff(AdrenalineSurge.class);\n\t\tif (buff != null){\n\t\t\tstrBonus += buff.boost();\n\t\t}\n\n\t\tif (hasTalent(Talent.STRONGMAN)){\n\t\t\tstrBonus += (int)Math.floor(STR * (0.03f + 0.05f*pointsInTalent(Talent.STRONGMAN)));\n\t\t}\n\n\t\treturn STR + strBonus;\n\t}\n\n\tpublic void onSTRGained() {\n\n\t}\n\n\tpublic void onSTRLost() {\n\n\t}\n\n\tprivate static final String CLASS = \"class\";\n\tprivate static final String SUBCLASS = \"subClass\";\n\tprivate static final String ABILITY = \"armorAbility\";\n\n\tprivate static final String ATTACK\t\t= \"attackSkill\";\n\tprivate static final String DEFENSE\t\t= \"defenseSkill\";\n\tprivate static final String STRENGTH\t= \"STR\";\n\tprivate static final String LEVEL\t\t= \"lvl\";\n\tprivate static final String EXPERIENCE\t= \"exp\";\n\tprivate static final String HTBOOST = \"htboost\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\n\t\tsuper.storeInBundle( bundle );\n\n\t\tbundle.put( CLASS, heroClass );\n\t\tbundle.put( SUBCLASS, subClass );\n\t\tbundle.put( ABILITY, armorAbility );\n\t\tTalent.storeTalentsInBundle( bundle, this );\n\t\t\n\t\tbundle.put( ATTACK, attackSkill );\n\t\tbundle.put( DEFENSE, defenseSkill );\n\t\t\n\t\tbundle.put( STRENGTH, STR );\n\t\t\n\t\tbundle.put( LEVEL, lvl );\n\t\tbundle.put( EXPERIENCE, exp );\n\t\t\n\t\tbundle.put( HTBOOST, HTBoost );\n\n\t\tbelongings.storeInBundle( bundle );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\n\t\tlvl = bundle.getInt( LEVEL );\n\t\texp = bundle.getInt( EXPERIENCE );\n\n\t\tHTBoost = bundle.getInt(HTBOOST);\n\n\t\tsuper.restoreFromBundle( bundle );\n\n\t\theroClass = bundle.getEnum( CLASS, HeroClass.class );\n\t\tsubClass = bundle.getEnum( SUBCLASS, HeroSubClass.class );\n\t\tarmorAbility = (ArmorAbility)bundle.get( ABILITY );\n\t\tTalent.restoreTalentsFromBundle( bundle, this );\n\t\t\n\t\tattackSkill = bundle.getInt( ATTACK );\n\t\tdefenseSkill = bundle.getInt( DEFENSE );\n\t\t\n\t\tSTR = bundle.getInt( STRENGTH );\n\n\t\tbelongings.restoreFromBundle( bundle );\n\t}\n\t\n\tpublic static void preview( GamesInProgress.Info info, Bundle bundle ) {\n\t\tinfo.level = bundle.getInt( LEVEL );\n\t\tinfo.str = bundle.getInt( STRENGTH );\n\t\tinfo.exp = bundle.getInt( EXPERIENCE );\n\t\tinfo.hp = bundle.getInt( Char.TAG_HP );\n\t\tinfo.ht = bundle.getInt( Char.TAG_HT );\n\t\tinfo.shld = bundle.getInt( Char.TAG_SHLD );\n\t\tinfo.heroClass = bundle.getEnum( CLASS, HeroClass.class );\n\t\tinfo.subClass = bundle.getEnum( SUBCLASS, HeroSubClass.class );\n\t\tBelongings.preview( info, bundle );\n\t}\n\n\tpublic boolean hasTalent( Talent talent ){\n\t\treturn pointsInTalent(talent) > 0;\n\t}\n\n\tpublic int pointsInTalent( Talent talent ){\n\t\tfor (LinkedHashMap<Talent, Integer> tier : talents){\n\t\t\tfor (Talent f : tier.keySet()){\n\t\t\t\tif (f == talent) return tier.get(f);\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\n\tpublic void upgradeTalent( Talent talent ){\n\t\tfor (LinkedHashMap<Talent, Integer> tier : talents){\n\t\t\tfor (Talent f : tier.keySet()){\n\t\t\t\tif (f == talent) tier.put(talent, tier.get(talent)+1);\n\t\t\t}\n\t\t}\n\t\tTalent.onTalentUpgraded(this, talent);\n\t}\n\n\tpublic int talentPointsSpent(int tier){\n\t\tint total = 0;\n\t\tfor (int i : talents.get(tier-1).values()){\n\t\t\ttotal += i;\n\t\t}\n\t\treturn total;\n\t}\n\n\tpublic int talentPointsAvailable(int tier){\n\t\tif (lvl < (Talent.tierLevelThresholds[tier] - 1)\n\t\t\t|| (tier == 3 && subClass == HeroSubClass.NONE)\n\t\t\t|| (tier == 4 && armorAbility == null)) {\n\t\t\treturn 0;\n\t\t} else if (lvl >= Talent.tierLevelThresholds[tier+1]){\n\t\t\treturn Talent.tierLevelThresholds[tier+1] - Talent.tierLevelThresholds[tier] - talentPointsSpent(tier) + bonusTalentPoints(tier);\n\t\t} else {\n\t\t\treturn 1 + lvl - Talent.tierLevelThresholds[tier] - talentPointsSpent(tier) + bonusTalentPoints(tier);\n\t\t}\n\t}\n\n\tpublic int bonusTalentPoints(int tier){\n\t\tint bonusPoints = 0;\n\t\tif (lvl < (Talent.tierLevelThresholds[tier]-1)\n\t\t\t\t|| (tier == 3 && subClass == HeroSubClass.NONE)\n\t\t\t\t|| (tier == 4 && armorAbility == null)) {\n\t\t\treturn 0;\n\t\t} else if (buff(PotionOfDivineInspiration.DivineInspirationTracker.class) != null\n\t\t\t\t\t&& buff(PotionOfDivineInspiration.DivineInspirationTracker.class).isBoosted(tier)) {\n\t\t\tbonusPoints += 2;\n\t\t}\n\t\tif (tier == 3 && buff(ElixirOfTalent.BonusTalentTracker.class) != null) {\n\t\t\tbonusPoints += 4;\n\t\t}\n\t\treturn bonusPoints;\n\t}\n\t\n\tpublic String className() {\n\t\treturn subClass == null || subClass == HeroSubClass.NONE ? heroClass.title() : subClass.title();\n\t}\n\n\t@Override\n\tpublic String name(){\n\t\treturn className();\n\t}\n\n\t@Override\n\tpublic void hitSound(float pitch) {\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\tbelongings.attackingWeapon().hitSound(pitch);\n\t\t} else if (RingOfForce.getBuffedBonus(this, RingOfForce.Force.class) > 0) {\n\t\t\t//pitch deepens by 2.5% (additive) per point of strength, down to 75%\n\t\t\tsuper.hitSound( pitch * GameMath.gate( 0.75f, 1.25f - 0.025f*STR(), 1f) );\n\t\t} else {\n\t\t\tsuper.hitSound(pitch * 1.1f);\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean blockSound(float pitch) {\n\t\tif ( belongings.weapon() != null && belongings.weapon().defenseFactor(this) >= 4 ){\n\t\t\tSample.INSTANCE.play( Assets.Sounds.HIT_PARRY, 1, pitch);\n\t\t\treturn true;\n\t\t}\n\t\treturn super.blockSound(pitch);\n\t}\n\n\tpublic void live() {\n\t\tfor (Buff b : buffs()){\n\t\t\tif (!b.revivePersists) b.detach();\n\t\t}\n\t\tBuff.affect( this, Regeneration.class );\n\t\tBuff.affect( this, Hunger.class );\n\t}\n\t\n\tpublic int tier() {\n\t\tArmor armor = belongings.armor();\n\t\tif (armor instanceof ClassArmor){\n\t\t\treturn 6;\n\t\t} else if (armor != null){\n\t\t\treturn armor.tier;\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tpublic boolean shoot( Char enemy, MissileWeapon wep ) {\n\n\t\tthis.enemy = enemy;\n\t\tboolean wasEnemy = enemy.alignment == Alignment.ENEMY\n\t\t\t\t|| (enemy instanceof Mimic && enemy.alignment == Alignment.NEUTRAL);\n\n\t\t//temporarily set the hero's weapon to the missile weapon being used\n\t\t//TODO improve this!\n\t\tbelongings.thrownWeapon = wep;\n\t\tboolean hit = attack( enemy );\n\t\tInvisibility.dispel();\n\t\tbelongings.thrownWeapon = null;\n\n\t\tif (hit && subClass == HeroSubClass.GLADIATOR && wasEnemy){\n\t\t\tBuff.affect( this, Combo.class ).hit( enemy );\n\t\t}\n\n\t\tif (hit && heroClass == HeroClass.DUELIST && wasEnemy){\n\t\t\tBuff.affect( this, Sai.ComboStrikeTracker.class).addHit();\n\t\t}\n\n\t\treturn hit;\n\t}\n\t\n\t@Override\n\tpublic int attackSkill( Char target ) {\n\t\tKindOfWeapon wep = belongings.attackingWeapon();\n\t\t\n\t\tfloat accuracy = 1;\n\t\taccuracy *= RingOfAccuracy.accuracyMultiplier( this );\n\n\t\tif (Dungeon.isChallenged(Challenges.SUPERMAN)) {\n\t\t\taccuracy *= 2;\n\t\t}\n\t\t\n\t\tif (wep instanceof MissileWeapon && !(wep instanceof Gun.Bullet)){ //총탄을 제외한 투척 무기의 정확성\n\t\t\tif (Dungeon.level.adjacent( pos, target.pos )) {\n\t\t\t\taccuracy *= (0.5f + 0.2f*pointsInTalent(Talent.POINT_BLANK));\n\t\t\t} else {\n\t\t\t\taccuracy *= 1.5f;\n\t\t\t}\n\t\t}\n\n\t\tif (wep instanceof Gun.Bullet) {\t//총탄의 정확성\n\t\t\tif (Dungeon.level.adjacent( pos, target.pos )) {\n\t\t\t\tif (wep instanceof SG.SGBullet) {\n\t\t\t\t\taccuracy *= 10f; //산탄총은 기본적으로 0.2배의 명중률 보정이 있으며, 이를 10배함으로써 2배의 명중률을 가짐\n\t\t\t\t} else {\n\t\t\t\t\taccuracy *= (0.5f + 0.2f*pointsInTalent(Talent.POINT_BLANK));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hero.hasTalent(Talent.INEVITABLE_DEATH) && hero.buff(RouletteOfDeath.class) != null && hero.buff(RouletteOfDeath.class).timeToDeath()) {\n\t\t\t\taccuracy *= 1 + hero.pointsInTalent(Talent.INEVITABLE_DEATH);\n\t\t\t}\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.GUNSLINGER && hero.justMoved && wep instanceof MissileWeapon) {\n\t\t\taccuracy *= 0.25f*(1+0.5f*hero.pointsInTalent(Talent.MOVING_SHOT));\n\t\t}\n\n\t\tif (buff(Scimitar.SwordDance.class) != null){\n\t\t\taccuracy *= 1.25f;\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.ACC_ENHANCE)) {\n\t\t\taccuracy *= 1 + 0.05f * hero.pointsInTalent(Talent.ACC_ENHANCE);\n\t\t}\n\n\t\tif (hero.buff(LargeSword.LargeSwordBuff.class) != null) {\n\t\t\taccuracy *= hero.buff(LargeSword.LargeSwordBuff.class).getAccuracyFactor();\n\t\t}\n\n\t\tif (hero.buff(UnholyBible.Demon.class) != null) {\n\t\t\taccuracy = INFINITE_ACCURACY;\n\t\t}\n\n\t\tif (hero.buff(MeleeWeapon.DashAttack.class) != null) {\n\t\t\taccuracy = INFINITE_ACCURACY;\n\t\t}\n\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\treturn (int)(attackSkill * accuracy * wep.accuracyFactor( this, target ));\n\t\t} else {\n\t\t\treturn (int)(attackSkill * accuracy);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic int defenseSkill( Char enemy ) {\n\n\t\tif (buff(Combo.ParryTracker.class) != null){\n\t\t\tif (canAttack(enemy) && !isCharmedBy(enemy)){\n\t\t\t\tBuff.affect(this, Combo.RiposteTracker.class).enemy = enemy;\n\t\t\t}\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\n\t\tif (buff(RoundShield.GuardTracker.class) != null){\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\n\t\tif (buff(Talent.ParryTracker.class) != null){\n\t\t\tif (canAttack(enemy) && !isCharmedBy(enemy)){\n\t\t\t\tBuff.affect(this, Talent.RiposteTracker.class).enemy = enemy;\n\t\t\t}\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\n\t\tif (buff(Nunchaku.ParryTracker.class) != null){\n\t\t\tif (canAttack(enemy) && !isCharmedBy(enemy)){\n\t\t\t\tBuff.affect(this, Nunchaku.RiposteTracker.class).enemy = enemy;\n\t\t\t}\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\t\t\n\t\tfloat evasion = defenseSkill;\n\t\t\n\t\tevasion *= RingOfEvasion.evasionMultiplier( this );\n\n\t\tif (hero.hasTalent(Talent.SWIFT_MOVEMENT)) {\n\t\t\tevasion += hero.STR()-10;\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.SUPERMAN)) {\n\t\t\tevasion *= 3;\n\t\t}\n\n\t\tif (buff(Talent.RestoredAgilityTracker.class) != null){\n\t\t\tif (pointsInTalent(Talent.LIQUID_AGILITY) == 1){\n\t\t\t\tevasion *= 4f;\n\t\t\t} else if (pointsInTalent(Talent.LIQUID_AGILITY) == 2){\n\t\t\t\treturn INFINITE_EVASION;\n\t\t\t}\n\t\t}\n\n\t\tif (buff(Quarterstaff.DefensiveStance.class) != null){\n\t\t\tevasion *= 3;\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.EVA_ENHANCE)) {\n\t\t\tevasion *= 1 + 0.05f * hero.pointsInTalent(Talent.EVA_ENHANCE);\n\t\t}\n\n\t\tif (hero.buff(UnholyBible.Demon.class) != null) {\n\t\t\tevasion /= 2;\n\t\t}\n\t\t\n\t\tif (paralysed > 0) {\n\t\t\tevasion /= 2;\n\t\t}\n\n\t\tif (belongings.armor() != null) {\n\t\t\tevasion = belongings.armor().evasionFactor(this, evasion);\n\t\t}\n\n\t\treturn Math.round(evasion);\n\t}\n\n\t@Override\n\tpublic String defenseVerb() {\n\t\tCombo.ParryTracker parry = buff(Combo.ParryTracker.class);\n\t\tif (parry != null){\n\t\t\tparry.parried = true;\n\t\t\tif (buff(Combo.class).getComboCount() < 9 || pointsInTalent(Talent.ENHANCED_COMBO) < 2){\n\t\t\t\tparry.detach();\n\t\t\t}\n\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t}\n\n\t\tif (buff(RoundShield.GuardTracker.class) != null){\n\t\t\tbuff(RoundShield.GuardTracker.class).detach();\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1, Random.Float(0.96f, 1.05f));\n\t\t\treturn Messages.get(RoundShield.GuardTracker.class, \"guarded\");\n\t\t}\n\n\t\tif (buff(MonkEnergy.MonkAbility.Focus.FocusActivation.class) != null){\n\t\t\tbuff(MonkEnergy.MonkAbility.Focus.FocusActivation.class).detach();\n\t\t\tif (sprite != null && sprite.visible) {\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1, Random.Float(0.96f, 1.05f));\n\t\t\t}\n\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t}\n\n\t\tTalent.ParryTracker parryTracker = buff(Talent.ParryTracker.class);\n\t\tif (hasTalent(Talent.PARRY)) {\n\t\t\tif (parryTracker != null) {\n\t\t\t\tparryTracker.detach();\n\t\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t\t}\n\t\t}\n\n\t\tNunchaku.ParryTracker nunchakuParry = buff(Nunchaku.ParryTracker.class);\n\t\tif (nunchakuParry != null){\n\t\t\tnunchakuParry.parried = true;\n\t\t\tif (sprite != null && sprite.visible) {\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1, Random.Float(0.96f, 1.05f));\n\t\t\t}\n\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t}\n\n\t\tRouletteOfDeath roulette = buff(RouletteOfDeath.class);\n\t\tif (hasTalent(Talent.HONORABLE_SHOT) && roulette != null && roulette.overHalf()) {\n\t\t\tBuff.prolong(hero, Talent.HonorableShotTracker.class, 1f);\n\t\t}\n\n\t\treturn super.defenseVerb();\n\t}\n\n\t@Override\n\tpublic int drRoll() {\n\t\tint dr = super.drRoll();\n\n\t\tif (belongings.armor() != null) {\n\t\t\tint armDr = Random.NormalIntRange( belongings.armor().DRMin(), belongings.armor().DRMax());\n\t\t\tif (STR() < belongings.armor().STRReq()){\n\t\t\t\tarmDr -= 2*(belongings.armor().STRReq() - STR());\n\t\t\t}\n\t\t\tif (armDr > 0) dr += armDr;\n\t\t}\n\t\tif (belongings.weapon() != null && !RingOfForce.fightingUnarmed(this)) {\n\t\t\tint wepDr = Random.NormalIntRange( 0 , belongings.weapon().defenseFactor( this ) );\n\t\t\tif (STR() < ((Weapon)belongings.weapon()).STRReq()){\n\t\t\t\twepDr -= 2*(((Weapon)belongings.weapon()).STRReq() - STR());\n\t\t\t}\n\t\t\tif (wepDr > 0) dr += wepDr;\n\t\t}\n\n\t\tif (buff(HoldFast.class) != null){\n\t\t\tdr += buff(HoldFast.class).armorBonus();\n\t\t}\n\n\t\tReinforcedArmor.ReinforcedArmorTracker rearmor = hero.buff(ReinforcedArmor.ReinforcedArmorTracker.class);\n\t\tif (rearmor != null) dr += rearmor.blockingRoll();\n\t\t\n\t\treturn dr;\n\t}\n\t\n\t@Override\n\tpublic int damageRoll() {\n\t\tKindOfWeapon wep = belongings.attackingWeapon();\n\t\tint dmg;\n\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\tdmg = wep.damageRoll( this );\n\n\t\t\tif (!(wep instanceof MissileWeapon)) dmg += RingOfForce.armedDamageBonus(this);\n\t\t} else {\n\t\t\tdmg = RingOfForce.damageRoll(this);\n\t\t\tif (RingOfForce.unarmedGetsWeaponAugment(this)){\n\t\t\t\tdmg = ((Weapon)belongings.attackingWeapon()).augment.damageFactor(dmg);\n\t\t\t}\n\t\t}\n\n\t\tPhysicalEmpower emp = buff(PhysicalEmpower.class);\n\t\tif (emp != null){\n\t\t\tdmg += emp.dmgBoost;\n\t\t\temp.left--;\n\t\t\tif (emp.left <= 0) {\n\t\t\t\temp.detach();\n\t\t\t}\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG, 0.75f, 1.2f);\n\t\t}\n\n\t\tif (heroClass != HeroClass.DUELIST\n\t\t\t\t&& hasTalent(Talent.WEAPON_RECHARGING)\n\t\t\t\t&& (buff(Recharging.class) != null || buff(ArtifactRecharge.class) != null)){\n\t\t\tdmg = Math.round(dmg * 1.025f + (.025f*pointsInTalent(Talent.WEAPON_RECHARGING)));\n\t\t}\n\n\t\tif (dmg < 0) dmg = 0;\n\t\treturn dmg;\n\t}\n\t\n\t@Override\n\tpublic float speed() {\n\n\t\tfloat speed = super.speed();\n\n\t\tspeed *= RingOfHaste.speedMultiplier(this);\n\t\t\n\t\tif (belongings.armor() != null) {\n\t\t\tspeed = belongings.armor().speedFactor(this, speed);\n\t\t}\n\t\t\n\t\tMomentum momentum = buff(Momentum.class);\n\t\tif (momentum != null){\n\t\t\t((HeroSprite)sprite).sprint( momentum.freerunning() ? 1.5f : 1f );\n\t\t\tspeed *= momentum.speedMultiplier();\n\t\t} else {\n\t\t\t((HeroSprite)sprite).sprint( 1f );\n\t\t}\n\n\t\tNaturesPower.naturesPowerTracker natStrength = buff(NaturesPower.naturesPowerTracker.class);\n\t\tif (natStrength != null){\n\t\t\tspeed *= (2f + 0.25f*pointsInTalent(Talent.GROWING_POWER));\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.MOVESPEED_ENHANCE)) {\n\t\t\tspeed *= 1 + 0.1*hero.pointsInTalent(Talent.MOVESPEED_ENHANCE);\n\t\t}\n\n\t\tif (subClass == HeroSubClass.MONK && buff(MonkEnergy.class) != null && buff(MonkEnergy.class).harmonized(this)) {\n\t\t\tspeed *= 1.5f;\n\t\t}\n\n\t\tif (hero.buff(ReinforcedArmor.ReinforcedArmorTracker.class) != null && hero.hasTalent(Talent.PLATE_ADD)) {\n\t\t\tspeed *= (1 - hero.pointsInTalent(Talent.PLATE_ADD)/8f);\n\t\t}\n\n\t\tif (hero.buff(Riot.RiotTracker.class) != null && hero.hasTalent(Talent.HASTE_MOVE)) {\n\t\t\tspeed *= 1f + 0.25f * hero.pointsInTalent(Talent.HASTE_MOVE);\n\t\t}\n\n\t\tspeed = AscensionChallenge.modifyHeroSpeed(speed);\n\t\t\n\t\treturn speed;\n\t\t\n\t}\n\n\t@Override\n\tpublic boolean canSurpriseAttack(){\n\t\tKindOfWeapon w = belongings.attackingWeapon();\n\t\tif (!(w instanceof Weapon)) return true;\n\t\tif (RingOfForce.fightingUnarmed(this)) return true;\n\t\tif (STR() < ((Weapon)w).STRReq()) return false;\n\t\tif (w instanceof Flail) return false;\n\t\tif (w instanceof ChainFlail) return false;\n\t\tif (w instanceof SG.SGBullet) return false;\n\n\t\treturn super.canSurpriseAttack();\n\t}\n\n\tpublic boolean canAttack(Char enemy){\n\t\tif (enemy == null || pos == enemy.pos || !Actor.chars().contains(enemy)) {\n\t\t\treturn false;\n\t\t}\n\n\t\t//can always attack adjacent enemies\n\t\tif (Dungeon.level.adjacent(pos, enemy.pos)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tKindOfWeapon wep = Dungeon.hero.belongings.attackingWeapon();\n\n\t\tif (wep != null){\n\t\t\treturn wep.canReach(this, enemy.pos);\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic float attackDelay() {\n\t\tif (buff(Talent.LethalMomentumTracker.class) != null){\n\t\t\tbuff(Talent.LethalMomentumTracker.class).detach();\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (buff(Talent.CounterAttackTracker.class) != null && hero.belongings.weapon == null) {\n\t\t\tbuff(Talent.CounterAttackTracker.class).detach();\n\t\t\treturn 0;\n\t\t}\n\n\t\tfloat delay = 1f;\n\n\t\tif ( buff(Adrenaline.class) != null) delay /= 1.5f;\n\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\t\n\t\t\treturn delay * belongings.attackingWeapon().delayFactor( this );\n\t\t\t\n\t\t} else {\n\t\t\t//Normally putting furor speed on unarmed attacks would be unnecessary\n\t\t\t//But there's going to be that one guy who gets a furor+force ring combo\n\t\t\t//This is for that one guy, you shall get your fists of fury!\n\t\t\tfloat speed = RingOfFuror.attackSpeedMultiplier(this);\n\n\t\t\tif (hero.hasTalent(Talent.LESS_RESIST)) {\n\t\t\t\tint aEnc = hero.belongings.armor.STRReq() - hero.STR();\n\t\t\t\tif (aEnc < 0) {\n\t\t\t\t\tspeed *= 1 + 0.05f * hero.pointsInTalent(Talent.LESS_RESIST) * (-aEnc);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.QUICK_FOLLOWUP) && hero.buff(Talent.QuickFollowupTracker.class) != null) {\n\t\t\t\tspeed *= 1+hero.pointsInTalent(Talent.QUICK_FOLLOWUP)/3f;\n\t\t\t}\n\n\t\t\tif (hero.subClass == HeroSubClass.MONK && hero.buff(MonkEnergy.class) != null && hero.buff(MonkEnergy.class).harmonized(hero)) {\n\t\t\t\tspeed *= 1.5f;\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.ATK_SPEED_ENHANCE)) {\n\t\t\t\tspeed *= 1 + 0.05f * hero.pointsInTalent(Talent.ATK_SPEED_ENHANCE);\n\t\t\t}\n\n\t\t\t//ditto for furor + sword dance!\n\t\t\tif (buff(Scimitar.SwordDance.class) != null){\n\t\t\t\tspeed += 0.6f;\n\t\t\t}\n\n\t\t\t//and augments + brawler's stance! My goodness, so many options now compared to 2014!\n\t\t\tif (RingOfForce.unarmedGetsWeaponAugment(this)){\n\t\t\t\tdelay = ((Weapon)belongings.weapon).augment.delayFactor(delay);\n\t\t\t}\n\n\t\t\treturn delay/speed;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void spend( float time ) {\n\t\tsuper.spend(time);\n\t}\n\n\t@Override\n\tpublic void spendConstant(float time) {\n\t\tjustMoved = false;\n\t\tsuper.spendConstant(time);\n\t}\n\n\tpublic void spendAndNextConstant(float time ) {\n\t\tbusy();\n\t\tspendConstant( time );\n\t\tnext();\n\t}\n\n\tpublic void spendAndNext( float time ) {\n\t\tbusy();\n\t\tspend( time );\n\t\tnext();\n\t}\n\t\n\t@Override\n\tpublic boolean act() {\n\t\t\n\t\t//calls to dungeon.observe will also update hero's local FOV.\n\t\tfieldOfView = Dungeon.level.heroFOV;\n\n\t\tif (buff(Endure.EndureTracker.class) != null){\n\t\t\tbuff(Endure.EndureTracker.class).endEnduring();\n\t\t}\n\t\t\n\t\tif (!ready) {\n\t\t\t//do a full observe (including fog update) if not resting.\n\t\t\tif (!resting || buff(MindVision.class) != null || buff(Awareness.class) != null) {\n\t\t\t\tDungeon.observe();\n\t\t\t} else {\n\t\t\t\t//otherwise just directly re-calculate FOV\n\t\t\t\tDungeon.level.updateFieldOfView(this, fieldOfView);\n\t\t\t}\n\t\t}\n\t\t\n\t\tcheckVisibleMobs();\n\t\tBuffIndicator.refreshHero();\n\t\tBuffIndicator.refreshBoss();\n\t\t\n\t\tif (paralysed > 0) {\n\t\t\t\n\t\t\tcurAction = null;\n\t\t\t\n\t\t\tspendAndNext( TICK );\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tboolean actResult;\n\t\tif (curAction == null) {\n\t\t\t\n\t\t\tif (resting) {\n\t\t\t\tspendConstant( TIME_TO_REST );\n\t\t\t\tnext();\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\t\t\t\n\t\t\tactResult = false;\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tresting = false;\n\t\t\t\n\t\t\tready = false;\n\t\t\t\n\t\t\tif (curAction instanceof HeroAction.Move) {\n\t\t\t\tactResult = actMove( (HeroAction.Move)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Interact) {\n\t\t\t\tactResult = actInteract( (HeroAction.Interact)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Buy) {\n\t\t\t\tactResult = actBuy( (HeroAction.Buy)curAction );\n\t\t\t\t\n\t\t\t}else if (curAction instanceof HeroAction.PickUp) {\n\t\t\t\tactResult = actPickUp( (HeroAction.PickUp)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.OpenChest) {\n\t\t\t\tactResult = actOpenChest( (HeroAction.OpenChest)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Unlock) {\n\t\t\t\tactResult = actUnlock((HeroAction.Unlock) curAction);\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Mine) {\n\t\t\t\tactResult = actMine( (HeroAction.Mine)curAction );\n\n\t\t\t}else if (curAction instanceof HeroAction.LvlTransition) {\n\t\t\t\tactResult = actTransition( (HeroAction.LvlTransition)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Attack) {\n\t\t\t\tactResult = actAttack( (HeroAction.Attack)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Alchemy) {\n\t\t\t\tactResult = actAlchemy( (HeroAction.Alchemy)curAction );\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tactResult = false;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(hasTalent(Talent.BARKSKIN) && Dungeon.level.map[pos] == Terrain.FURROWED_GRASS){\n\t\t\tBarkskin.conditionallyAppend(this, (lvl*pointsInTalent(Talent.BARKSKIN))/2, 1 );\n\t\t}\n\n\t\tif (hasTalent(Talent.PARRY) && buff(Talent.ParryCooldown.class) == null){\n\t\t\tBuff.affect(this, Talent.ParryTracker.class);\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.CURSED_DUNGEON) && hero.buff(GhostSpawner.class) == null) {\n\t\t\tBuff.affect(hero, GhostSpawner.class);\n\t\t}\n\t\t\n\t\treturn actResult;\n\t}\n\t\n\tpublic void busy() {\n\t\tready = false;\n\t}\n\t\n\tprivate void ready() {\n\t\tif (sprite.looping()) sprite.idle();\n\t\tcurAction = null;\n\t\tdamageInterrupt = true;\n\t\twaitOrPickup = false;\n\t\tready = true;\n\t\tcanSelfTrample = true;\n\n\t\tAttackIndicator.updateState();\n\t\t\n\t\tGameScene.ready();\n\t}\n\t\n\tpublic void interrupt() {\n\t\tif (isAlive() && curAction != null &&\n\t\t\t((curAction instanceof HeroAction.Move && curAction.dst != pos) ||\n\t\t\t(curAction instanceof HeroAction.LvlTransition))) {\n\t\t\tlastAction = curAction;\n\t\t}\n\t\tcurAction = null;\n\t\tGameScene.resetKeyHold();\n\t}\n\t\n\tpublic void resume() {\n\t\tcurAction = lastAction;\n\t\tlastAction = null;\n\t\tdamageInterrupt = false;\n\t\tnext();\n\t}\n\n\tprivate boolean canSelfTrample = false;\n\tpublic boolean canSelfTrample(){\n\t\treturn canSelfTrample && !rooted && !flying &&\n\t\t\t\t//standing in high grass\n\t\t\t\t(Dungeon.level.map[pos] == Terrain.HIGH_GRASS ||\n\t\t\t\t//standing in furrowed grass and not huntress\n\t\t\t\t((heroClass != HeroClass.HUNTRESS && hero.subClass != HeroSubClass.SPECIALIST) && Dungeon.level.map[pos] == Terrain.FURROWED_GRASS) ||\n\t\t\t\t//standing on a plant\n\t\t\t\tDungeon.level.plants.get(pos) != null);\n\t}\n\t\n\tprivate boolean actMove( HeroAction.Move action ) {\n\n\t\tif (getCloser( action.dst )) {\n\t\t\tcanSelfTrample = false;\n\t\t\treturn true;\n\n\t\t//Hero moves in place if there is grass to trample\n\t\t} else if (pos == action.dst && canSelfTrample()){\n\t\t\tcanSelfTrample = false;\n\t\t\tDungeon.level.pressCell(pos);\n\t\t\tspendAndNext( 1 / speed() );\n\t\t\treturn false;\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actInteract( HeroAction.Interact action ) {\n\t\t\n\t\tChar ch = action.ch;\n\n\t\tif (ch.isAlive() && ch.canInteract(this)) {\n\t\t\t\n\t\t\tready();\n\t\t\tsprite.turnTo( pos, ch.pos );\n\t\t\treturn ch.interact(this);\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tif (fieldOfView[ch.pos] && getCloser( ch.pos )) {\n\n\t\t\t\treturn true;\n\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\t\n\tprivate boolean actBuy( HeroAction.Buy action ) {\n\t\tint dst = action.dst;\n\t\tif (pos == dst) {\n\n\t\t\tready();\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( dst );\n\t\t\tif (heap != null && heap.type == Type.FOR_SALE && heap.size() == 1) {\n\t\t\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\tGameScene.show( new WndTradeItem( heap ) );\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate boolean actAlchemy( HeroAction.Alchemy action ) {\n\t\tint dst = action.dst;\n\t\tif (Dungeon.level.distance(dst, pos) <= 1) {\n\n\t\t\tready();\n\t\t\t\n\t\t\tAlchemistsToolkit.kitEnergy kit = buff(AlchemistsToolkit.kitEnergy.class);\n\t\t\tif (kit != null && kit.isCursed()){\n\t\t\t\tGLog.w( Messages.get(AlchemistsToolkit.class, \"cursed\"));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tAlchemyScene.clearToolkit();\n\t\t\tShatteredPixelDungeon.switchScene(AlchemyScene.class);\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t//used to keep track if the wait/pickup action was used\n\t// so that the hero spends a turn even if the fail to pick up an item\n\tpublic boolean waitOrPickup = false;\n\n\tprivate boolean actPickUp( HeroAction.PickUp action ) {\n\t\tint dst = action.dst;\n\t\tif (pos == dst) {\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( pos );\n\t\t\tif (heap != null) {\n\t\t\t\tItem item = heap.peek();\n\t\t\t\tif (item.doPickUp( this )) {\n\t\t\t\t\theap.pickUp();\n\n\t\t\t\t\tif (item instanceof Dewdrop\n\t\t\t\t\t\t\t|| item instanceof TimekeepersHourglass.sandBag\n\t\t\t\t\t\t\t|| item instanceof DriedRose.Petal\n\t\t\t\t\t\t\t|| item instanceof Key\n\t\t\t\t\t\t\t|| item instanceof Guidebook) {\n\t\t\t\t\t\t//Do Nothing\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t//TODO make all unique items important? or just POS / SOU?\n\t\t\t\t\t\tboolean important = item.unique && item.isIdentified() &&\n\t\t\t\t\t\t\t\t(item instanceof Scroll || item instanceof Potion);\n\t\t\t\t\t\tif (important) {\n\t\t\t\t\t\t\tGLog.p( Messages.capitalize(Messages.get(this, \"you_now_have\", item.name())) );\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tGLog.i( Messages.capitalize(Messages.get(this, \"you_now_have\", item.name())) );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tcurAction = null;\n\t\t\t\t} else {\n\n\t\t\t\t\tif (waitOrPickup) {\n\t\t\t\t\t\tspendAndNextConstant(TIME_TO_REST);\n\t\t\t\t\t}\n\n\t\t\t\t\t//allow the hero to move between levels even if they can't collect the item\n\t\t\t\t\tif (Dungeon.level.getTransition(pos) != null){\n\t\t\t\t\t\tthrowItems();\n\t\t\t\t\t} else {\n\t\t\t\t\t\theap.sprite.drop();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (item instanceof Dewdrop\n\t\t\t\t\t\t\t|| item instanceof TimekeepersHourglass.sandBag\n\t\t\t\t\t\t\t|| item instanceof DriedRose.Petal\n\t\t\t\t\t\t\t|| item instanceof Key) {\n\t\t\t\t\t\t//Do Nothing\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGLog.newLine();\n\t\t\t\t\t\tGLog.n(Messages.capitalize(Messages.get(this, \"you_cant_have\", item.name())));\n\t\t\t\t\t}\n\n\t\t\t\t\tready();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actOpenChest( HeroAction.OpenChest action ) {\n\t\tint dst = action.dst;\n\t\tif (Dungeon.level.adjacent( pos, dst ) || pos == dst) {\n\t\t\tpath = null;\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( dst );\n\t\t\tif (heap != null && (heap.type != Type.HEAP && heap.type != Type.FOR_SALE)) {\n\t\t\t\t\n\t\t\t\tif ((heap.type == Type.LOCKED_CHEST && Notes.keyCount(new GoldenKey(Dungeon.depth)) < 1)\n\t\t\t\t\t|| (heap.type == Type.CRYSTAL_CHEST && Notes.keyCount(new CrystalKey(Dungeon.depth)) < 1)){\n\n\t\t\t\t\t\tGLog.w( Messages.get(this, \"locked_chest\") );\n\t\t\t\t\t\tready();\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tswitch (heap.type) {\n\t\t\t\tcase TOMB:\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.TOMB );\n\t\t\t\t\tPixelScene.shake( 1, 0.5f );\n\t\t\t\t\tbreak;\n\t\t\t\tcase SKELETON:\n\t\t\t\tcase REMAINS:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.UNLOCK );\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tsprite.operate( dst );\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actUnlock( HeroAction.Unlock action ) {\n\t\tint doorCell = action.dst;\n\t\tif (Dungeon.level.adjacent( pos, doorCell )) {\n\t\t\tpath = null;\n\t\t\t\n\t\t\tboolean hasKey = false;\n\t\t\tint door = Dungeon.level.map[doorCell];\n\t\t\t\n\t\t\tif (door == Terrain.LOCKED_DOOR\n\t\t\t\t\t&& Notes.keyCount(new IronKey(Dungeon.depth)) > 0) {\n\t\t\t\t\n\t\t\t\thasKey = true;\n\t\t\t\t\n\t\t\t} else if (door == Terrain.CRYSTAL_DOOR\n\t\t\t\t\t&& Notes.keyCount(new CrystalKey(Dungeon.depth, Dungeon.branch)) > 0) {\n\n\t\t\t\thasKey = true;\n\n\t\t\t} else if (door == Terrain.LOCKED_EXIT\n\t\t\t\t\t&& Notes.keyCount(new SkeletonKey(Dungeon.depth)) > 0) {\n\n\t\t\t\thasKey = true;\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tif (hasKey) {\n\t\t\t\t\n\t\t\t\tsprite.operate( doorCell );\n\t\t\t\t\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.UNLOCK );\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tGLog.w( Messages.get(this, \"locked_door\") );\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( doorCell )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic boolean actMine(HeroAction.Mine action){\n\t\tif (Dungeon.level.adjacent(pos, action.dst)){\n\t\t\tpath = null;\n\t\t\tif ((Dungeon.level.map[action.dst] == Terrain.WALL\n\t\t\t\t\t|| Dungeon.level.map[action.dst] == Terrain.WALL_DECO\n\t\t\t\t\t|| Dungeon.level.map[action.dst] == Terrain.MINE_CRYSTAL\n\t\t\t\t\t|| Dungeon.level.map[action.dst] == Terrain.MINE_BOULDER)\n\t\t\t\t&& Dungeon.level.insideMap(action.dst)){\n\t\t\t\tsprite.attack(action.dst, new Callback() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void call() {\n\n\t\t\t\t\t\tboolean crystalAdjacent = false;\n\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS8) {\n\t\t\t\t\t\t\tif (Dungeon.level.map[action.dst + i] == Terrain.MINE_CRYSTAL){\n\t\t\t\t\t\t\t\tcrystalAdjacent = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//1 hunger spent total\n\t\t\t\t\t\tif (Dungeon.level.map[action.dst] == Terrain.WALL_DECO){\n\t\t\t\t\t\t\tDarkGold gold = new DarkGold();\n\t\t\t\t\t\t\tif (gold.doPickUp( Dungeon.hero )) {\n\t\t\t\t\t\t\t\tDarkGold existing = Dungeon.hero.belongings.getItem(DarkGold.class);\n\t\t\t\t\t\t\t\tif (existing != null && existing.quantity()%5 == 0){\n\t\t\t\t\t\t\t\t\tif (existing.quantity() >= 40) {\n\t\t\t\t\t\t\t\t\t\tGLog.p(Messages.get(DarkGold.class, \"you_now_have\", existing.quantity()));\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tGLog.i(Messages.get(DarkGold.class, \"you_now_have\", existing.quantity()));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tspend(-Actor.TICK); //picking up the gold doesn't spend a turn here\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tDungeon.level.drop( gold, pos ).sprite.drop();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tPixelScene.shake(0.5f, 0.5f);\n\t\t\t\t\t\t\tCellEmitter.center( action.dst ).burst( Speck.factory( Speck.STAR ), 7 );\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.EVOKE );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY_DECO );\n\n\t\t\t\t\t\t\t//mining gold doesn't break crystals\n\t\t\t\t\t\t\tcrystalAdjacent = false;\n\n\t\t\t\t\t\t//4 hunger spent total\n\t\t\t\t\t\t} else if (Dungeon.level.map[action.dst] == Terrain.WALL){\n\t\t\t\t\t\t\tbuff(Hunger.class).affectHunger(-3);\n\t\t\t\t\t\t\tPixelScene.shake(0.5f, 0.5f);\n\t\t\t\t\t\t\tCellEmitter.get( action.dst ).burst( Speck.factory( Speck.ROCK ), 2 );\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.MINE );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY_DECO );\n\n\t\t\t\t\t\t//1 hunger spent total\n\t\t\t\t\t\t} else if (Dungeon.level.map[action.dst] == Terrain.MINE_CRYSTAL){\n\t\t\t\t\t\t\tSplash.at(action.dst, 0xFFFFFF, 5);\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.SHATTER );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY );\n\n\t\t\t\t\t\t//1 hunger spent total\n\t\t\t\t\t\t} else if (Dungeon.level.map[action.dst] == Terrain.MINE_BOULDER){\n\t\t\t\t\t\t\tSplash.at(action.dst, ColorMath.random( 0x444444, 0x777766 ), 5);\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.MINE, 0.6f );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\t\tDungeon.level.discoverable[action.dst + i] = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\t\tGameScene.updateMap( action.dst+i );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (crystalAdjacent){\n\t\t\t\t\t\t\tsprite.parent.add(new Delayer(0.2f){\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tprotected void onComplete() {\n\t\t\t\t\t\t\t\t\tboolean broke = false;\n\t\t\t\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS8) {\n\t\t\t\t\t\t\t\t\t\tif (Dungeon.level.map[action.dst+i] == Terrain.MINE_CRYSTAL){\n\t\t\t\t\t\t\t\t\t\t\tSplash.at(action.dst+i, 0xFFFFFF, 5);\n\t\t\t\t\t\t\t\t\t\t\tLevel.set( action.dst+i, Terrain.EMPTY );\n\t\t\t\t\t\t\t\t\t\t\tbroke = true;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (broke){\n\t\t\t\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.SHATTER );\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\t\t\t\t\tGameScene.updateMap( action.dst+i );\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tspendAndNext(TICK);\n\t\t\t\t\t\t\t\t\tready();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tspendAndNext(TICK);\n\t\t\t\t\t\t\tready();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tDungeon.observe();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\t\t\treturn false;\n\t\t} else if (getCloser( action.dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actTransition(HeroAction.LvlTransition action ) {\n\t\tint stairs = action.dst;\n\t\tLevelTransition transition = Dungeon.level.getTransition(stairs);\n\n\t\tif (rooted) {\n\t\t\tPixelScene.shake(1, 1f);\n\t\t\tready();\n\t\t\treturn false;\n\n\t\t} else if (!Dungeon.level.locked && transition != null && transition.inside(pos)) {\n\n\t\t\tif (Dungeon.level.activateTransition(this, transition)){\n\t\t\t\tcurAction = null;\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( stairs )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actAttack( HeroAction.Attack action ) {\n\n\t\tenemy = action.target;\n\n\t\tif (enemy.isAlive() && canAttack( enemy ) && !isCharmedBy( enemy ) && enemy.invisible == 0) {\n\n\t\t\tif (heroClass != HeroClass.DUELIST\n\t\t\t\t\t&& hasTalent(Talent.AGGRESSIVE_BARRIER)\n\t\t\t\t\t&& buff(Talent.AggressiveBarrierCooldown.class) == null\n\t\t\t\t\t&& (HP / (float)HT) < 0.20f*(1+pointsInTalent(Talent.AGGRESSIVE_BARRIER))){\n\t\t\t\tBuff.affect(this, Barrier.class).setShield(3);\n\t\t\t\tBuff.affect(this, Talent.AggressiveBarrierCooldown.class, 50f);\n\t\t\t}\n\t\t\tsprite.attack( enemy.pos );\n\n\t\t\treturn false;\n\n\t\t} else {\n\n\t\t\tif (fieldOfView[enemy.pos] && getCloser( enemy.pos )) {\n\n\t\t\t\treturn true;\n\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t}\n\t}\n\n\tpublic Char enemy(){\n\t\treturn enemy;\n\t}\n\t\n\tpublic void rest( boolean fullRest ) {\n\t\tspendAndNextConstant( TIME_TO_REST );\n\t\tif (hasTalent(Talent.HOLD_FAST)){\n\t\t\tBuff.affect(this, HoldFast.class).pos = pos;\n\t\t}\n\t\tif (hasTalent(Talent.PATIENT_STRIKE)){\n\t\t\tBuff.affect(Dungeon.hero, Talent.PatientStrikeTracker.class).pos = Dungeon.hero.pos;\n\t\t}\n\t\tif (!fullRest) {\n\t\t\tif (sprite != null) {\n\t\t\t\tsprite.showStatus(CharSprite.DEFAULT, Messages.get(this, \"wait\"));\n\t\t\t}\n\n\t\t\tif (belongings.weapon instanceof LargeSword || belongings.secondWep instanceof LargeSword){\n\t\t\t\tBuff.affect(this, LargeSword.LargeSwordBuff.class).setDamageFactor(belongings.weapon.buffedLvl(), (belongings.secondWep instanceof LargeSword));\n\t\t\t\tif (hero.sprite != null) {\n\t\t\t\t\tEmitter e = hero.sprite.centerEmitter();\n\t\t\t\t\tif (e != null) e.burst(EnergyParticle.FACTORY, 15);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Dungeon.hero.subClass == HeroSubClass.CHASER\n\t\t\t\t\t&& hero.buff(Talent.ChaseCooldown.class) == null\n\t\t\t\t\t&& hero.buff(Invisibility.class) == null\n\t\t\t\t\t&& hero.buff(CloakOfShadows.cloakStealth.class) == null ) {\n\t\t\t\tif (hero.hasTalent(Talent.MASTER_OF_CLOAKING)) {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Invisibility.class, 6f);\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Invisibility.class, 5f);\n\t\t\t\t}\n\t\t\t\tif (hero.pointsInTalent(Talent.MASTER_OF_CLOAKING) > 1) {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.ChaseCooldown.class, 10f);\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.ChaseCooldown.class, 15f);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Dungeon.level.map[pos] == Terrain.FURROWED_GRASS && hero.subClass == HeroSubClass.SPECIALIST) {\n\t\t\t\tboolean adjacentMob = false;\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] )) {\n\t\t\t\t\tif (level.adjacent(hero.pos, mob.pos)) {\n\t\t\t\t\t\tadjacentMob = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (hero.pointsInTalent(Talent.STEALTH_MASTER) > 1) {\n\t\t\t\t\tadjacentMob = false;\n\t\t\t\t}\n\t\t\t\tif (!adjacentMob && hero.hasTalent(Talent.INTO_THE_SHADOW) && hero.buff(Talent.IntoTheShadowCooldown.class) == null) {\n\t\t\t\t\tBuff.affect(this, Invisibility.class, 3f*hero.pointsInTalent(Talent.INTO_THE_SHADOW));\n\t\t\t\t\tBuff.affect(this, Talent.IntoTheShadowCooldown.class, 15);\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(this, Cloaking.class);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresting = fullRest;\n\t}\n\t\n\t@Override\n\tpublic int attackProc( final Char enemy, int damage ) {\n\t\tdamage = super.attackProc( enemy, damage );\n\n\t\tKindOfWeapon wep;\n\t\tif (RingOfForce.fightingUnarmed(this) && !RingOfForce.unarmedGetsWeaponEnchantment(this)){\n\t\t\twep = null;\n\t\t} else {\n\t\t\twep = belongings.attackingWeapon();\n\t\t}\n\n\t\tif (hero.buff(MeleeWeapon.DashAttack.class) != null) {\n\t\t\tdamage *= hero.buff(MeleeWeapon.DashAttack.class).getDmgMulti();\n\t\t\thero.buff(MeleeWeapon.DashAttack.class).detach();\n\t\t}\n\n\t\tif (wep != null) damage = wep.proc( this, enemy, damage );\n\n\t\tdamage = Talent.onAttackProc( this, enemy, damage );\n\t\t\n\t\tswitch (subClass) {\n\t\t\tcase SNIPER:\n\t\t\t\tif (wep instanceof MissileWeapon && !(wep instanceof SpiritBow.SpiritArrow) && enemy != this) {\n\t\t\t\t\tActor.add(new Actor() {\n\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tactPriority = VFX_PRIO;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tprotected boolean act() {\n\t\t\t\t\t\t\tif (enemy.isAlive()) {\n\t\t\t\t\t\t\t\tint bonusTurns = hasTalent(Talent.SHARED_UPGRADES) ? wep.buffedLvl() : 0;\n\t\t\t\t\t\t\t\tBuff.prolong(Hero.this, SnipersMark.class, SnipersMark.DURATION + bonusTurns).set(enemy.id(), bonusTurns);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tActor.remove(this);\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (hero.hasTalent(Talent.KICK)\n\t\t\t\t\t\t&& enemy.buff(PinCushion.class) != null\n\t\t\t\t\t\t&& level.adjacent(hero.pos, enemy.pos)\n\t\t\t\t\t\t&& hero.buff(Talent.KickCooldown.class) == null) {\n\t\t\t\t\tItem item = enemy.buff(PinCushion.class).grabOne();\n\t\t\t\t\tif (item.doPickUp(hero, enemy.pos)){\n\t\t\t\t\t\thero.spend(-1); //attacking enemy already takes a turn\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGLog.w(Messages.get(this, \"cant_grab\"));\n\t\t\t\t\t\tDungeon.level.drop(item, enemy.pos).sprite.drop();\n\t\t\t\t\t}\n\t\t\t\t\tBallistica trajectory = new Ballistica(hero.pos, enemy.pos, Ballistica.STOP_TARGET);\n\t\t\t\t\ttrajectory = new Ballistica(trajectory.collisionPos, trajectory.path.get(trajectory.path.size() - 1), Ballistica.PROJECTILE);\n\t\t\t\t\tint dist = hero.pointsInTalent(Talent.KICK);\n\t\t\t\t\tWandOfBlastWave.throwChar(enemy, trajectory, dist, true, false ,hero.getClass());\n\t\t\t\t\tBuff.affect(hero, Talent.KickCooldown.class, 10f);\n\t\t\t\t}\n\t\t\t\tif (wep instanceof MissileWeapon\n\t\t\t\t\t\t&& hero.hasTalent(Talent.SHOOTING_EYES)\n\t\t\t\t\t\t&& enemy.buff(Talent.ShootingEyesTracker.class) == null) {\n\t\t\t\t\tif (Random.Float() < hero.pointsInTalent(Talent.SHOOTING_EYES)/3f) {\n\t\t\t\t\t\tBuff.affect(enemy, Blindness.class, 2f);\n\t\t\t\t\t}\n\t\t\t\t\tBuff.affect(enemy, Talent.ShootingEyesTracker.class);\n\t\t\t\t}\n\t\t\t\tif (wep instanceof MissileWeapon\n\t\t\t\t\t\t&& hero.hasTalent(Talent.TARGET_SPOTTING)\n\t\t\t\t\t\t&& hero.buff(SnipersMark.class) != null\n\t\t\t\t\t\t&& hero.buff(SnipersMark.class).object == enemy.id()) {\n\t\t\t\t\tdamage *= 1+0.1f*hero.pointsInTalent(Talent.TARGET_SPOTTING);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase FIGHTER:\n\t\t\t\tif (wep == null && Random.Int(3) < hero.pointsInTalent(Talent.QUICK_STEP)) {\n\t\t\t\t\tBuff.prolong(hero, Talent.QuickStep.class, 1.0001f);\n\t\t\t\t}\n\t\t\t\tif (wep == null && hero.hasTalent(Talent.RING_KNUCKLE) && hero.buff(RingOfForce.Force.class) == null) {\n\t\t\t\t\tBuff.prolong(hero, EnhancedRingsCombo.class, (Dungeon.hero.pointsInTalent(Talent.RING_KNUCKLE) >= 2) ? 2f : 1f).hit();\n\t\t\t\t\thero.updateHT(false);\n\t\t\t\t\tupdateQuickslot();\n\t\t\t\t}\n\t\t\t\tif (wep == null && Random.Float() < hero.pointsInTalent(Talent.MYSTICAL_PUNCH)/3f) {\n\t\t\t\t\tif (hero.belongings.ring != null) {\n\t\t\t\t\t\tdamage *= Ring.onHit(hero, enemy, damage, Ring.ringTypes.get(hero.belongings.ring.getClass()));\n\t\t\t\t\t}\n\t\t\t\t\tif (hero.belongings.misc instanceof Ring) {\n\t\t\t\t\t\tdamage *= Ring.onHit(hero, enemy, damage, Ring.ringTypes.get(hero.belongings.misc.getClass()));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CHAMPION:\n\t\t\t\tif (hero.belongings.weapon != null && hero.belongings.secondWep != null\n\t\t\t\t\t\t&& hero.pointsInTalent(Talent.TWIN_SWORD) > 1\n\t\t\t\t\t\t&& hero.belongings.weapon.getClass() == hero.belongings.secondWep.getClass()) {\n\t\t\t\t\tKindOfWeapon other = hero.belongings.secondWep;\n\t\t\t\t\tif (hero.belongings.secondWep == wep) {\n\t\t\t\t\t\tother = hero.belongings.weapon;\n\t\t\t\t\t}\n\t\t\t\t\tdamage = other.proc( this, enemy, damage );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase VETERAN:\n\t\t\t\tif (level.adjacent(enemy.pos, pos) && hero.buff(Tackle.TackleTracker.class) == null) {\n\t\t\t\t\tActor.add(new Actor() {\n\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tactPriority = VFX_PRIO;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tprotected boolean act() {\n\t\t\t\t\t\t\tif (enemy.isAlive()) {\n\t\t\t\t\t\t\t\tBuff.prolong(Hero.this, Tackle.class, 1).set(enemy.id());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tActor.remove(this);\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OUTLAW:\n\t\t\t\tif (wep instanceof Gun.Bullet) {\n\t\t\t\t\tif (hero.hasTalent(Talent.HEADSHOT) && Random.Float() < 0.01f*hero.pointsInTalent(Talent.HEADSHOT)) {\n\t\t\t\t\t\tif (!Char.hasProp(enemy, Property.BOSS) && !Char.hasProp(enemy, Property.MINIBOSS)) {\n\t\t\t\t\t\t\tdamage = enemy.HP;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdamage *= 1.2f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemy.sprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\t\t}\n\n\t\t\t\t\tif (hero.buff(Talent.HonorableShotTracker.class) != null\n\t\t\t\t\t\t\t&& (enemy.HP/(float)enemy.HT) <= 0.4f*hero.pointsInTalent(Talent.HONORABLE_SHOT)/3f) {\n\t\t\t\t\t\tif (!Char.hasProp(enemy, Property.BOSS) && !Char.hasProp(enemy, Property.MINIBOSS)) {\n\t\t\t\t\t\t\tdamage = enemy.HP;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdamage *= 1.2f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemy.sprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\t\t\thero.buff(Talent.HonorableShotTracker.class).detach();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (hero.buff(RouletteOfDeath.class) == null || !hero.buff(RouletteOfDeath.class).timeToDeath()) {\n\t\t\t\t\t\tBuff.affect(this, RouletteOfDeath.class).hit();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (!Char.hasProp(enemy, Property.BOSS) && !Char.hasProp(enemy, Property.MINIBOSS)) {\n\t\t\t\t\t\t\tdamage = enemy.HP;\n\t\t\t\t\t\t\tif (hero.belongings.weapon instanceof Gun) {\n\t\t\t\t\t\t\t\t((Gun)hero.belongings.weapon).quickReload();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (hero.hasTalent(Talent.BULLET_TIME)) {\n\t\t\t\t\t\t\t\tfor (Char ch : Actor.chars()) {\n\t\t\t\t\t\t\t\t\tif (level.heroFOV[ch.pos]) {\n\t\t\t\t\t\t\t\t\t\tBuff.affect(ch, Slow.class, 4*hero.pointsInTalent(Talent.BULLET_TIME));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdamage *= 1.2f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemy.sprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\t\t\thero.buff(RouletteOfDeath.class).detach();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.WATER_FRIENDLY) && Dungeon.level.map[hero.pos] == Terrain.WATER) {\n\t\t\tdamage += Random.NormalIntRange(1, hero.pointsInTalent(Talent.WATER_FRIENDLY));\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t}\n\n\t\tif (hero.buff(Talent.SkilledHandTracker.class) != null) {\n\t\t\tdamage += 1+hero.pointsInTalent(Talent.SKILLED_HAND);\n\t\t\thero.buff(Talent.SkilledHandTracker.class).detach();\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t}\n\n\t\tif (Random.Float() < hero.pointsInTalent(Talent.MADNESS)/10f) {\n\t\t\tBuff.prolong(enemy, Amok.class, 3f);\n\t\t}\n\n\t\tSpellBook.SpellBookCoolDown spellBookCoolDown = buff(SpellBook.SpellBookCoolDown.class);\n\t\tif (hero.hasTalent(Talent.BRIG_BOOST) && spellBookCoolDown != null) {\n\t\t\tspellBookCoolDown.hit(hero.pointsInTalent(Talent.BRIG_BOOST));\n\t\t}\n\n\t\tif (hero.buff(Bible.Angel.class) != null) {\n\t\t\thero.heal(Math.max(Math.round(0.2f*damage), 1));\n\t\t}\n\n\t\tif (hero.buff(UnholyBible.Demon.class) != null) {\n\t\t\tdamage *= 1.33f;\n\t\t}\n\n\t\tif (hero.buff(DualDagger.ReverseBlade.class) != null) {\n\t\t\tdamage *= 0.5f;\n\t\t\tBuff.affect(enemy, Bleeding.class).add(Random.NormalIntRange(1, 3));\n\t\t\tif (enemy.sprite.visible) {\n\t\t\t\tSplash.at( enemy.sprite.center(), -PointF.PI / 2, PointF.PI / 6,\n\t\t\t\t\t\tenemy.sprite.blood(), Math.min( 10 * Random.NormalIntRange(1, 3) / enemy.HT, 10 ) );\n\t\t\t}\n\t\t}\n\n\t\tif (enemy instanceof Mob && ((Mob) enemy).surprisedBy(hero)) {\n\t\t\tif (hero.hasTalent(Talent.POISONOUS_BLADE)) {\n\t\t\t\tBuff.affect(enemy, Poison.class).set(2+hero.pointsInTalent(Talent.POISONOUS_BLADE));\n\t\t\t}\n\t\t\tif (hero.hasTalent(Talent.SOUL_COLLECT) && damage >= enemy.HP) {\n\t\t\t\tint healAmt = 3*hero.pointsInTalent(Talent.SOUL_COLLECT);\n\t\t\t\thealAmt = Math.min( healAmt, hero.HT - hero.HP );\n\t\t\t\tif (healAmt > 0 && hero.isAlive()) {\n\t\t\t\t\thero.HP += healAmt;\n\t\t\t\t\thero.sprite.emitter().start( Speck.factory( Speck.HEALING ), 0.4f, 2 );\n\t\t\t\t\thero.sprite.showStatus( CharSprite.POSITIVE, Integer.toString( healAmt ) );\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hero.hasTalent(Talent.TRAIL_TRACKING) && damage >= enemy.HP) {\n\t\t\t\tBuff.affect(hero, MindVision.class, hero.pointsInTalent(Talent.TRAIL_TRACKING));\n\t\t\t}\n\n\t\t\tif (hero.pointsInTalent(Talent.MASTER_OF_CLOAKING) == 3) {\n\t\t\t\tif (hero.buff(Talent.ChaseCooldown.class) != null) {\n\t\t\t\t\thero.buff(Talent.ChaseCooldown.class).spendTime();\n\t\t\t\t}\n\t\t\t\tif (hero.buff(Talent.ChainCooldown.class) != null) {\n\t\t\t\t\thero.buff(Talent.ChainCooldown.class).spendTime();\n\t\t\t\t}\n\t\t\t\tif (hero.buff(Talent.LethalCooldown.class) != null) {\n\t\t\t\t\thero.buff(Talent.LethalCooldown.class).spendTime();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.BAYONET) && hero.buff(ReinforcedArmor.ReinforcedArmorTracker.class) != null){\n\t\t\tif (wep instanceof Gun) {\n\t\t\t\tBuff.affect( enemy, Bleeding.class ).set( 4 + hero.pointsInTalent(Talent.BAYONET));\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.SUPERMAN)) {\n\t\t\tdamage *= 3f;\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.PYRO)) {\n\t\t\tBuff.affect(enemy, Burning.class).reignite(enemy, 8f);\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.FATIGUE)) {\n\t\t\tBuff.affect(this, Fatigue.class).hit(true);\n\t\t}\n\t\t\n\t\treturn damage;\n\t}\n\t\n\t@Override\n\tpublic int defenseProc( Char enemy, int damage ) {\n\t\t\n\t\tif (damage > 0 && subClass == HeroSubClass.BERSERKER){\n\t\t\tBerserk berserk = Buff.affect(this, Berserk.class);\n\t\t\tberserk.damage(damage);\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.GLADIATOR && Random.Float() < hero.pointsInTalent(Talent.OFFENSIVE_DEFENSE)/3f) {\n\t\t\tCombo combo = Buff.affect(this, Combo.class);\n\t\t\tcombo.hit(enemy);\n\t\t}\n\t\t\n\t\tif (belongings.armor() != null) {\n\t\t\tdamage = belongings.armor().proc( enemy, this, damage );\n\t\t}\n\n\t\tWandOfLivingEarth.RockArmor rockArmor = buff(WandOfLivingEarth.RockArmor.class);\n\t\tif (rockArmor != null) {\n\t\t\tdamage = rockArmor.absorb(damage);\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.EMERGENCY_ESCAPE) && Random.Float() < hero.pointsInTalent(Talent.EMERGENCY_ESCAPE)/50f) {\n\t\t\tBuff.prolong(this, Invisibility.class, 3f);\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.OVERCOMING)) {\n\t\t\tMomentum momentum = buff(Momentum.class);\n\t\t\tif (momentum != null && momentum.freerunning()) {\n\t\t\t\tBuff.affect(this, Haste.class, 2f);\n\t\t\t\tif (hero.pointsInTalent(Talent.OVERCOMING) > 1) Buff.affect(this, Adrenaline.class, 2f);\n\t\t\t\tif (hero.pointsInTalent(Talent.OVERCOMING) > 2) Buff.affect(this, EvasiveMove.class, 2f);\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.FATIGUE)) {\n\t\t\tBuff.affect(this, Fatigue.class).hit(false);\n\t\t}\n\t\t\n\t\treturn super.defenseProc( enemy, damage );\n\t}\n\t\n\t@Override\n\tpublic void damage( int dmg, Object src ) {\n\t\tif (buff(TimekeepersHourglass.timeStasis.class) != null)\n\t\t\treturn;\n\n\t\t//regular damage interrupt, triggers on any damage except specific mild DOT effects\n\t\t// unless the player recently hit 'continue moving', in which case this is ignored\n\t\tif (!(src instanceof Hunger || src instanceof Viscosity.DeferedDamage) && damageInterrupt) {\n\t\t\tinterrupt();\n\t\t\tresting = false;\n\t\t}\n\n\t\tif (this.buff(Drowsy.class) != null){\n\t\t\tBuff.detach(this, Drowsy.class);\n\t\t\tGLog.w( Messages.get(this, \"pain_resist\") );\n\t\t}\n\n\t\tEndure.EndureTracker endure = buff(Endure.EndureTracker.class);\n\t\tif (!(src instanceof Char)){\n\t\t\t//reduce damage here if it isn't coming from a character (if it is we already reduced it)\n\t\t\tif (endure != null){\n\t\t\t\tdmg = Math.round(endure.adjustDamageTaken(dmg));\n\t\t\t}\n\t\t\t//the same also applies to challenge scroll damage reduction\n\t\t\tif (buff(ScrollOfChallenge.ChallengeArena.class) != null){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\t\t\t//and to monk meditate damage reduction\n\t\t\tif (buff(MonkEnergy.MonkAbility.Meditate.MeditateResistance.class) != null){\n\t\t\t\tdmg *= 0.2f;\n\t\t\t}\n\t\t}\n\n\t\tCapeOfThorns.Thorns thorns = buff( CapeOfThorns.Thorns.class );\n\t\tif (thorns != null) {\n\t\t\tdmg = thorns.proc(dmg, (src instanceof Char ? (Char)src : null), this);\n\t\t}\n\n\t\tdmg = (int)Math.ceil(dmg * RingOfTenacity.damageMultiplier( this ));\n\n\t\tLargeSword.LargeSwordBuff largeSwordBuff = hero.buff(LargeSword.LargeSwordBuff.class);\n\t\tif (largeSwordBuff != null) {\n\t\t\tdmg = (int)Math.ceil(dmg * largeSwordBuff.getDefenseFactor());\n\t\t}\n\n\t\t//TODO improve this when I have proper damage source logic\n\t\tif (belongings.armor() != null && belongings.armor().hasGlyph(AntiMagic.class, this)\n\t\t\t\t&& AntiMagic.RESISTS.contains(src.getClass())){\n\t\t\tdmg -= AntiMagic.drRoll(this, belongings.armor().buffedLvl());\n\t\t}\n\n\t\tif (buff(Talent.WarriorFoodImmunity.class) != null){\n\t\t\tif (pointsInTalent(Talent.IRON_STOMACH) == 1) dmg = Math.round(dmg*0.25f);\n\t\t\telse if (pointsInTalent(Talent.IRON_STOMACH) == 2) dmg = Math.round(dmg*0.00f);\n\t\t}\n\n\t\tif (buff(Tackle.SuperArmorTracker.class) != null) {\n\t\t\tswitch (pointsInTalent(Talent.SUPER_ARMOR)) {\n\t\t\t\tcase 1:\n\t\t\t\t\tdmg = Math.round(dmg*0.67f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tdmg = Math.round(dmg*0.33f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tdmg = Math.round(dmg*0.00f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0: default:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tint preHP = HP + shielding();\n\t\tif (src instanceof Hunger) preHP -= shielding();\n\t\tsuper.damage( dmg, src );\n\t\tint postHP = HP + shielding();\n\t\tif (src instanceof Hunger) postHP -= shielding();\n\t\tint effectiveDamage = preHP - postHP;\n\n\t\tif (effectiveDamage <= 0) return;\n\n\t\tif (buff(Challenge.DuelParticipant.class) != null){\n\t\t\tbuff(Challenge.DuelParticipant.class).addDamage(effectiveDamage);\n\t\t}\n\n\t\t//flash red when hit for serious damage.\n\t\tfloat percentDMG = effectiveDamage / (float)preHP; //percent of current HP that was taken\n\t\tfloat percentHP = 1 - ((HT - postHP) / (float)HT); //percent health after damage was taken\n\t\t// The flash intensity increases primarily based on damage taken and secondarily on missing HP.\n\t\tfloat flashIntensity = 0.25f * (percentDMG * percentDMG) / percentHP;\n\t\t//if the intensity is very low don't flash at all\n\t\tif (flashIntensity >= 0.05f){\n\t\t\tflashIntensity = Math.min(1/3f, flashIntensity); //cap intensity at 1/3\n\t\t\tGameScene.flash( (int)(0xFF*flashIntensity) << 16 );\n\t\t\tif (isAlive()) {\n\t\t\t\tif (flashIntensity >= 1/6f) {\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HEALTH_CRITICAL, 1/3f + flashIntensity * 2f);\n\t\t\t\t} else {\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HEALTH_WARN, 1/3f + flashIntensity * 4f);\n\t\t\t\t}\n\t\t\t\t//hero gets interrupted on taking serious damage, regardless of any other factor\n\t\t\t\tinterrupt();\n\t\t\t\tresting = false;\n\t\t\t\tdamageInterrupt = true;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void checkVisibleMobs() {\n\t\tArrayList<Mob> visible = new ArrayList<>();\n\n\t\tboolean newMob = false;\n\n\t\tMob target = null;\n\t\tfor (Mob m : Dungeon.level.mobs.toArray(new Mob[0])) {\n\t\t\tif (fieldOfView[ m.pos ] && m.alignment == Alignment.ENEMY) {\n\t\t\t\tvisible.add(m);\n\t\t\t\tif (!visibleEnemies.contains( m )) {\n\t\t\t\t\tnewMob = true;\n\t\t\t\t}\n\n\t\t\t\tif (!mindVisionEnemies.contains(m) && QuickSlotButton.autoAim(m) != -1){\n\t\t\t\t\tif (target == null){\n\t\t\t\t\t\ttarget = m;\n\t\t\t\t\t} else if (distance(target) > distance(m)) {\n\t\t\t\t\t\ttarget = m;\n\t\t\t\t\t}\n\t\t\t\t\tif (m instanceof Snake && Dungeon.level.distance(m.pos, pos) <= 4\n\t\t\t\t\t\t\t&& !Document.ADVENTURERS_GUIDE.isPageRead(Document.GUIDE_EXAMINING)){\n\t\t\t\t\t\tGLog.p(Messages.get(Guidebook.class, \"hint\"));\n\t\t\t\t\t\tGameScene.flashForDocument(Document.ADVENTURERS_GUIDE, Document.GUIDE_EXAMINING);\n\t\t\t\t\t\t//we set to read here to prevent this message popping up a bunch\n\t\t\t\t\t\tDocument.ADVENTURERS_GUIDE.readPage(Document.GUIDE_EXAMINING);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tChar lastTarget = QuickSlotButton.lastTarget;\n\t\tif (target != null && (lastTarget == null ||\n\t\t\t\t\t\t\t!lastTarget.isAlive() || !lastTarget.isActive() ||\n\t\t\t\t\t\t\tlastTarget.alignment == Alignment.ALLY ||\n\t\t\t\t\t\t\t!fieldOfView[lastTarget.pos])){\n\t\t\tQuickSlotButton.target(target);\n\t\t}\n\t\t\n\t\tif (newMob) {\n\t\t\tinterrupt();\n\t\t\tif (resting){\n\t\t\t\tDungeon.observe();\n\t\t\t\tresting = false;\n\t\t\t}\n\t\t}\n\n\t\tvisibleEnemies = visible;\n\t}\n\t\n\tpublic int visibleEnemies() {\n\t\treturn visibleEnemies.size();\n\t}\n\t\n\tpublic Mob visibleEnemy( int index ) {\n\t\treturn visibleEnemies.get(index % visibleEnemies.size());\n\t}\n\n\tpublic ArrayList<Mob> getVisibleEnemies(){\n\t\treturn new ArrayList<>(visibleEnemies);\n\t}\n\t\n\tprivate boolean walkingToVisibleTrapInFog = false;\n\t\n\t//FIXME this is a fairly crude way to track this, really it would be nice to have a short\n\t//history of hero actions\n\tpublic boolean justMoved = false;\n\t\n\tprivate boolean getCloser( final int target ) {\n\n\t\tif (target == pos)\n\t\t\treturn false;\n\n\t\tif (rooted) {\n\t\t\tPixelScene.shake( 1, 1f );\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tint step = -1;\n\t\t\n\t\tif (Dungeon.level.adjacent( pos, target )) {\n\n\t\t\tpath = null;\n\n\t\t\tif (Actor.findChar( target ) == null) {\n\t\t\t\tif (Dungeon.level.passable[target] || Dungeon.level.avoid[target]) {\n\t\t\t\t\tstep = target;\n\t\t\t\t}\n\t\t\t\tif (walkingToVisibleTrapInFog\n\t\t\t\t\t\t&& Dungeon.level.traps.get(target) != null\n\t\t\t\t\t\t&& Dungeon.level.traps.get(target).visible){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t} else {\n\n\t\t\tboolean newPath = false;\n\t\t\tif (path == null || path.isEmpty() || !Dungeon.level.adjacent(pos, path.getFirst()))\n\t\t\t\tnewPath = true;\n\t\t\telse if (path.getLast() != target)\n\t\t\t\tnewPath = true;\n\t\t\telse {\n\t\t\t\tif (!Dungeon.level.passable[path.get(0)] || Actor.findChar(path.get(0)) != null) {\n\t\t\t\t\tnewPath = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (newPath) {\n\n\t\t\t\tint len = Dungeon.level.length();\n\t\t\t\tboolean[] p = Dungeon.level.passable;\n\t\t\t\tboolean[] v = Dungeon.level.visited;\n\t\t\t\tboolean[] m = Dungeon.level.mapped;\n\t\t\t\tboolean[] passable = new boolean[len];\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\tpassable[i] = p[i] && (v[i] || m[i]);\n\t\t\t\t}\n\n\t\t\t\tPathFinder.Path newpath = Dungeon.findPath(this, target, passable, fieldOfView, true);\n\t\t\t\tif (newpath != null && path != null && newpath.size() > 2*path.size()){\n\t\t\t\t\tpath = null;\n\t\t\t\t} else {\n\t\t\t\t\tpath = newpath;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (path == null) return false;\n\t\t\tstep = path.removeFirst();\n\n\t\t}\n\n\t\tif (step != -1) {\n\n\t\t\tfloat delay = 1 / speed();\n\n\t\t\tif (Dungeon.level.pit[step] && !Dungeon.level.solid[step]\n\t\t\t\t\t&& (!flying || buff(Levitation.class) != null && buff(Levitation.class).detachesWithinDelay(delay))){\n\t\t\t\tif (!Chasm.jumpConfirmed){\n\t\t\t\t\tChasm.heroJump(this);\n\t\t\t\t\tinterrupt();\n\t\t\t\t} else {\n\t\t\t\t\tflying = false;\n\t\t\t\t\tremove(buff(Levitation.class)); //directly remove to prevent cell pressing\n\t\t\t\t\tChasm.heroFall(target);\n\t\t\t\t}\n\t\t\t\tcanSelfTrample = false;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif ((hero.belongings.weapon instanceof Lance ||\n\t\t\t\t\thero.belongings.secondWep instanceof Lance ||\n\t\t\t\t\t(hero.belongings.weapon instanceof LanceNShield && ((LanceNShield)hero.belongings.weapon).stance) ||\n\t\t\t\t\t(hero.belongings.secondWep instanceof LanceNShield && ((LanceNShield)hero.belongings.secondWep).stance))) {\n\t\t\t\tBuff.affect(this, Lance.LanceBuff.class).setDamageFactor(1 + (hero.speed()), hero.belongings.secondWep instanceof Lance || (hero.belongings.secondWep instanceof LanceNShield && ((LanceNShield) hero.belongings.secondWep).stance));\n\t\t\t}\n\n\t\t\tif (subClass == HeroSubClass.FREERUNNER){\n\t\t\t\tBuff.affect(this, Momentum.class).gainStack();\n\t\t\t}\n\n\t\t\tif (hero.buff(Talent.RollingTracker.class) != null && hero.belongings.weapon instanceof Gun && Dungeon.bullet > 1) {\n\t\t\t\tDungeon.bullet --;\n\t\t\t\t((Gun)hero.belongings.weapon).manualReload();\n\t\t\t\thero.buff(Talent.RollingTracker.class).detach();\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.QUICK_RELOAD) && hero.belongings.weapon instanceof Gun && Random.Float() < 0.03f * hero.pointsInTalent(Talent.QUICK_RELOAD) && Dungeon.bullet > 1) {\n\t\t\t\tDungeon.bullet --;\n\t\t\t\t((Gun)hero.belongings.weapon).manualReload();\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.MIND_VISION) && Random.Float() < 0.01f*hero.pointsInTalent(Talent.MIND_VISION)) {\n\t\t\t\tBuff.affect(this, MindVision.class, 1f);\n\t\t\t}\n\t\t\t\n\t\t\tsprite.move(pos, step);\n\t\t\tmove(step);\n\n\t\t\tif (buff(Talent.QuickStep.class) != null) {\n\t\t\t\tspend(-delay);\n\t\t\t\tbuff(Talent.QuickStep.class).detach();\n\t\t\t}\n\n\t\t\tspend( delay );\n\t\t\tjustMoved = true;\n\t\t\t\n\t\t\tsearch(false);\n\n\t\t\treturn true;\n\n\t\t} else {\n\n\t\t\treturn false;\n\t\t\t\n\t\t}\n\n\t}\n\t\n\tpublic boolean handle( int cell ) {\n\t\t\n\t\tif (cell == -1) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (fieldOfView == null || fieldOfView.length != Dungeon.level.length()){\n\t\t\tfieldOfView = new boolean[Dungeon.level.length()];\n\t\t\tDungeon.level.updateFieldOfView( this, fieldOfView );\n\t\t}\n\t\t\n\t\tChar ch = Actor.findChar( cell );\n\t\tHeap heap = Dungeon.level.heaps.get( cell );\n\n\t\tif (Dungeon.level.map[cell] == Terrain.ALCHEMY && cell != pos) {\n\t\t\t\n\t\t\tcurAction = new HeroAction.Alchemy( cell );\n\t\t\t\n\t\t} else if (fieldOfView[cell] && ch instanceof Mob) {\n\n\t\t\tif (ch.alignment != Alignment.ENEMY && ch.buff(Amok.class) == null) {\n\t\t\t\tcurAction = new HeroAction.Interact( ch );\n\t\t\t} else {\n\t\t\t\tcurAction = new HeroAction.Attack( ch );\n\t\t\t}\n\n\t\t//TODO perhaps only trigger this if hero is already adjacent? reducing mistaps\n\t\t} else if (Dungeon.level instanceof MiningLevel &&\n\t\t\t\t\tbelongings.getItem(Pickaxe.class) != null &&\n\t\t\t\t(Dungeon.level.map[cell] == Terrain.WALL\n\t\t\t\t\t\t|| Dungeon.level.map[cell] == Terrain.WALL_DECO\n\t\t\t\t\t\t|| Dungeon.level.map[cell] == Terrain.MINE_CRYSTAL\n\t\t\t\t\t\t|| Dungeon.level.map[cell] == Terrain.MINE_BOULDER)){\n\n\t\t\tcurAction = new HeroAction.Mine( cell );\n\n\t\t} else if (heap != null\n\t\t\t\t//moving to an item doesn't auto-pickup when enemies are near...\n\t\t\t\t&& (visibleEnemies.size() == 0 || cell == pos ||\n\t\t\t\t//...but only for standard heaps. Chests and similar open as normal.\n\t\t\t\t(heap.type != Type.HEAP && heap.type != Type.FOR_SALE))) {\n\n\t\t\tswitch (heap.type) {\n\t\t\tcase HEAP:\n\t\t\t\tcurAction = new HeroAction.PickUp( cell );\n\t\t\t\tbreak;\n\t\t\tcase FOR_SALE:\n\t\t\t\tcurAction = heap.size() == 1 && heap.peek().value() > 0 ?\n\t\t\t\t\tnew HeroAction.Buy( cell ) :\n\t\t\t\t\tnew HeroAction.PickUp( cell );\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tcurAction = new HeroAction.OpenChest( cell );\n\t\t\t}\n\t\t\t\n\t\t} else if (Dungeon.level.map[cell] == Terrain.LOCKED_DOOR || Dungeon.level.map[cell] == Terrain.CRYSTAL_DOOR || Dungeon.level.map[cell] == Terrain.LOCKED_EXIT) {\n\t\t\t\n\t\t\tcurAction = new HeroAction.Unlock( cell );\n\t\t\t\n\t\t} else if (Dungeon.level.getTransition(cell) != null\n\t\t\t\t//moving to a transition doesn't automatically trigger it when enemies are near\n\t\t\t\t&& (visibleEnemies.size() == 0 || cell == pos)\n\t\t\t\t&& !Dungeon.level.locked\n\t\t\t\t&& (Dungeon.depth < 31 || Dungeon.level.getTransition(cell).type == LevelTransition.Type.REGULAR_ENTRANCE) ) {\n\n\t\t\tcurAction = new HeroAction.LvlTransition( cell );\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tif (!Dungeon.level.visited[cell] && !Dungeon.level.mapped[cell]\n\t\t\t\t\t&& Dungeon.level.traps.get(cell) != null && Dungeon.level.traps.get(cell).visible) {\n\t\t\t\twalkingToVisibleTrapInFog = true;\n\t\t\t} else {\n\t\t\t\twalkingToVisibleTrapInFog = false;\n\t\t\t}\n\t\t\t\n\t\t\tcurAction = new HeroAction.Move( cell );\n\t\t\tlastAction = null;\n\t\t\t\n\t\t}\n\n\t\treturn true;\n\t}\n\t\n\tpublic void earnExp( int exp, Class source ) {\n\n\t\t//xp granted by ascension challenge is only for on-exp gain effects\n\t\tif (source != AscensionChallenge.class) {\n\t\t\tthis.exp += exp;\n\t\t}\n\t\tfloat percent = exp/(float)maxExp();\n\n\t\tEtherealChains.chainsRecharge chains = buff(EtherealChains.chainsRecharge.class);\n\t\tif (chains != null) chains.gainExp(percent);\n\n\t\tHornOfPlenty.hornRecharge horn = buff(HornOfPlenty.hornRecharge.class);\n\t\tif (horn != null) horn.gainCharge(percent);\n\t\t\n\t\tAlchemistsToolkit.kitEnergy kit = buff(AlchemistsToolkit.kitEnergy.class);\n\t\tif (kit != null) kit.gainCharge(percent);\n\n\t\tMasterThievesArmband.Thievery armband = buff(MasterThievesArmband.Thievery.class);\n\t\tif (armband != null) armband.gainCharge(percent);\n\t\t\n\t\tBerserk berserk = buff(Berserk.class);\n\t\tif (berserk != null) berserk.recover(percent);\n\t\t\n\t\tif (source != PotionOfExperience.class) {\n\t\t\tfor (Item i : belongings) {\n\t\t\t\ti.onHeroGainExp(percent, this);\n\t\t\t}\n\t\t\tif (buff(Talent.RejuvenatingStepsFurrow.class) != null){\n\t\t\t\tbuff(Talent.RejuvenatingStepsFurrow.class).countDown(percent*200f);\n\t\t\t\tif (buff(Talent.RejuvenatingStepsFurrow.class).count() <= 0){\n\t\t\t\t\tbuff(Talent.RejuvenatingStepsFurrow.class).detach();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (buff(ElementalStrike.ElementalStrikeFurrowCounter.class) != null){\n\t\t\t\tbuff(ElementalStrike.ElementalStrikeFurrowCounter.class).countDown(percent*20f);\n\t\t\t\tif (buff(ElementalStrike.ElementalStrikeFurrowCounter.class).count() <= 0){\n\t\t\t\t\tbuff(ElementalStrike.ElementalStrikeFurrowCounter.class).detach();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tboolean levelUp = false;\n\t\twhile (this.exp >= maxExp()) {\n\t\t\tthis.exp -= maxExp();\n\t\t\tif (lvl < MAX_LEVEL) {\n\t\t\t\tlvl++;\n\t\t\t\tlevelUp = true;\n\t\t\t\t\n\t\t\t\tif (buff(ElixirOfMight.HTBoost.class) != null){\n\t\t\t\t\tbuff(ElixirOfMight.HTBoost.class).onLevelUp();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tupdateHT( true );\n\t\t\t\tattackSkill++;\n\t\t\t\tdefenseSkill++;\n\n\t\t\t} else {\n\t\t\t\tBuff.prolong(this, Bless.class, Bless.DURATION);\n\t\t\t\tthis.exp = 0;\n\n\t\t\t\tGLog.newLine();\n\t\t\t\tGLog.p( Messages.get(this, \"level_cap\"));\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.LEVELUP );\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tif (levelUp) {\n\t\t\t\n\t\t\tif (sprite != null) {\n\t\t\t\tGLog.newLine();\n\t\t\t\tGLog.p( Messages.get(this, \"new_level\") );\n\t\t\t\tsprite.showStatus( CharSprite.POSITIVE, Messages.get(Hero.class, \"level_up\") );\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.LEVELUP );\n\t\t\t\tif (lvl < Talent.tierLevelThresholds[Talent.MAX_TALENT_TIERS+1]){\n\t\t\t\t\tGLog.newLine();\n\t\t\t\t\tGLog.p( Messages.get(this, \"new_talent\") );\n\t\t\t\t\tStatusPane.talentBlink = 10f;\n\t\t\t\t\tWndHero.lastIdx = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tItem.updateQuickslot();\n\t\t\t\n\t\t\tBadges.validateLevelReached();\n\t\t}\n\t}\n\t\n\tpublic int maxExp() {\n\t\treturn maxExp( lvl );\n\t}\n\t\n\tpublic static int maxExp( int lvl ){\n\t\treturn 5 + lvl * 5;\n\t}\n\t\n\tpublic boolean isStarving() {\n\t\treturn Buff.affect(this, Hunger.class).isStarving();\n\t}\n\t\n\t@Override\n\tpublic boolean add( Buff buff ) {\n\n\t\tif (buff(TimekeepersHourglass.timeStasis.class) != null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tboolean added = super.add( buff );\n\n\t\tif (sprite != null && added) {\n\t\t\tString msg = buff.heroMessage();\n\t\t\tif (msg != null){\n\t\t\t\tGLog.w(msg);\n\t\t\t}\n\n\t\t\tif (buff instanceof Paralysis || buff instanceof Vertigo) {\n\t\t\t\tinterrupt();\n\t\t\t}\n\n\t\t}\n\t\t\n\t\tBuffIndicator.refreshHero();\n\n\t\treturn added;\n\t}\n\t\n\t@Override\n\tpublic boolean remove( Buff buff ) {\n\t\tif (super.remove( buff )) {\n\t\t\tBuffIndicator.refreshHero();\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic float stealth() {\n\t\tfloat stealth = super.stealth();\n\t\t\n\t\tif (belongings.armor() != null){\n\t\t\tstealth = belongings.armor().stealthFactor(this, stealth);\n\t\t}\n\t\t\n\t\treturn stealth;\n\t}\n\t\n\t@Override\n\tpublic void die( Object cause ) {\n\n\t\tif (buff(Enduring.class) != null) {\n\t\t\tthis.HP = 1;\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tcurAction = null;\n\n\t\tAnkh ankh = null;\n\n\t\t//look for ankhs in player inventory, prioritize ones which are blessed.\n\t\tfor (Ankh i : belongings.getAllItems(Ankh.class)){\n\t\t\tif (ankh == null || i.isBlessed()) {\n\t\t\t\tankh = i;\n\t\t\t}\n\t\t}\n\n\t\tif (ankh != null) {\n\t\t\tinterrupt();\n\t\t\tresting = false;\n\n\t\t\tif (ankh.isBlessed()) {\n\t\t\t\tthis.HP = HT / 4;\n\n\t\t\t\tPotionOfHealing.cure(this);\n\t\t\t\tBuff.prolong(this, AnkhInvulnerability.class, AnkhInvulnerability.DURATION);\n\n\t\t\t\tSpellSprite.show(this, SpellSprite.ANKH);\n\t\t\t\tGameScene.flash(0x80FFFF40);\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TELEPORT);\n\t\t\t\tGLog.w(Messages.get(this, \"revive\"));\n\t\t\t\tStatistics.ankhsUsed++;\n\n\t\t\t\tankh.detach(belongings.backpack);\n\n\t\t\t\tfor (Char ch : Actor.chars()) {\n\t\t\t\t\tif (ch instanceof DriedRose.GhostHero) {\n\t\t\t\t\t\t((DriedRose.GhostHero) ch).sayAnhk();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\n\t\t\t\t//this is hacky, basically we want to declare that a wndResurrect exists before\n\t\t\t\t//it actually gets created. This is important so that the game knows to not\n\t\t\t\t//delete the run or submit it to rankings, because a WndResurrect is about to exist\n\t\t\t\t//this is needed because the actual creation of the window is delayed here\n\t\t\t\tWndResurrect.instance = new Object();\n\t\t\t\tAnkh finalAnkh = ankh;\n\t\t\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\tGameScene.show( new WndResurrect(finalAnkh) );\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (cause instanceof Hero.Doom) {\n\t\t\t\t\t((Hero.Doom)cause).onDeath();\n\t\t\t\t}\n\n\t\t\t\tSacrificialFire.Marked sacMark = buff(SacrificialFire.Marked.class);\n\t\t\t\tif (sacMark != null){\n\t\t\t\t\tsacMark.detach();\n\t\t\t\t}\n\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tActor.fixTime();\n\t\tsuper.die( cause );\n\t\treallyDie( cause );\n\t}\n\t\n\tpublic static void reallyDie( Object cause ) {\n\t\t\n\t\tint length = Dungeon.level.length();\n\t\tint[] map = Dungeon.level.map;\n\t\tboolean[] visited = Dungeon.level.visited;\n\t\tboolean[] discoverable = Dungeon.level.discoverable;\n\t\t\n\t\tfor (int i=0; i < length; i++) {\n\t\t\t\n\t\t\tint terr = map[i];\n\t\t\t\n\t\t\tif (discoverable[i]) {\n\t\t\t\t\n\t\t\t\tvisited[i] = true;\n\t\t\t\tif ((Terrain.flags[terr] & Terrain.SECRET) != 0) {\n\t\t\t\t\tDungeon.level.discover( i );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tBones.leave();\n\t\t\n\t\tDungeon.observe();\n\t\tGameScene.updateFog();\n\t\t\t\t\n\t\tDungeon.hero.belongings.identify();\n\n\t\tint pos = Dungeon.hero.pos;\n\n\t\tArrayList<Integer> passable = new ArrayList<>();\n\t\tfor (Integer ofs : PathFinder.NEIGHBOURS8) {\n\t\t\tint cell = pos + ofs;\n\t\t\tif ((Dungeon.level.passable[cell] || Dungeon.level.avoid[cell]) && Dungeon.level.heaps.get( cell ) == null) {\n\t\t\t\tpassable.add( cell );\n\t\t\t}\n\t\t}\n\t\tCollections.shuffle( passable );\n\n\t\tArrayList<Item> items = new ArrayList<>(Dungeon.hero.belongings.backpack.items);\n\t\tfor (Integer cell : passable) {\n\t\t\tif (items.isEmpty()) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tItem item = Random.element( items );\n\t\t\tDungeon.level.drop( item, cell ).sprite.drop( pos );\n\t\t\titems.remove( item );\n\t\t}\n\n\t\tfor (Char c : Actor.chars()){\n\t\t\tif (c instanceof DriedRose.GhostHero){\n\t\t\t\t((DriedRose.GhostHero) c).sayHeroKilled();\n\t\t\t}\n\t\t}\n\n\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t@Override\n\t\t\tpublic void call() {\n\t\t\t\tGameScene.gameOver();\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.DEATH );\n\t\t\t}\n\t\t});\n\n\t\tif (cause instanceof Hero.Doom) {\n\t\t\t((Hero.Doom)cause).onDeath();\n\t\t}\n\n\t\tDungeon.deleteGame( GamesInProgress.curSlot, true );\n\t}\n\n\t//effectively cache this buff to prevent having to call buff(...) a bunch.\n\t//This is relevant because we call isAlive during drawing, which has both performance\n\t//and thread coordination implications if that method calls buff(...) frequently\n\tprivate Berserk berserk;\n\n\t@Override\n\tpublic boolean isAlive() {\n\t\t\n\t\tif (HP <= 0){\n\t\t\tif (berserk == null) berserk = buff(Berserk.class);\n\t\t\treturn berserk != null && berserk.berserking();\n\t\t} else {\n\t\t\tberserk = null;\n\t\t\treturn super.isAlive();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void move(int step, boolean travelling) {\n\t\tboolean wasHighGrass = Dungeon.level.map[step] == Terrain.HIGH_GRASS;\n\n\t\tsuper.move( step, travelling);\n\t\t\n\t\tif (!flying && travelling) {\n\t\t\tif (Dungeon.level.water[pos]) {\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.WATER, 1, Random.Float( 0.8f, 1.25f ) );\n\t\t\t} else if (Dungeon.level.map[pos] == Terrain.EMPTY_SP) {\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.STURDY, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t} else if (Dungeon.level.map[pos] == Terrain.GRASS\n\t\t\t\t\t|| Dungeon.level.map[pos] == Terrain.EMBERS\n\t\t\t\t\t|| Dungeon.level.map[pos] == Terrain.FURROWED_GRASS){\n\t\t\t\tif (step == pos && wasHighGrass) {\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TRAMPLE, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t\t} else {\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.GRASS, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.STEP, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void onAttackComplete() {\n\n\t\tif (enemy == null){\n\t\t\tcurAction = null;\n\t\t\tsuper.onAttackComplete();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tAttackIndicator.target(enemy);\n\t\tboolean wasEnemy = enemy.alignment == Alignment.ENEMY\n\t\t\t\t|| (enemy instanceof Mimic && enemy.alignment == Alignment.NEUTRAL);\n\n\t\tboolean hit = attack( enemy );\n\t\t\n\t\tInvisibility.dispel();\n\t\tspend( attackDelay() );\n\n\t\tif (hit && subClass == HeroSubClass.GLADIATOR && wasEnemy){\n\t\t\tBuff.affect( this, Combo.class ).hit( enemy );\n\t\t}\n\n\t\tif (hit && subClass == HeroSubClass.BATTLEMAGE && hero.belongings.attackingWeapon() instanceof MagesStaff && hero.hasTalent(Talent.BATTLE_MAGIC) && wasEnemy) {\n\t\t\tBuff.affect( this, MagicalCombo.class).hit( enemy );\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.CHASER\n\t\t\t\t&& hero.hasTalent(Talent.CHAIN_CLOCK)\n\t\t\t\t&& ((Mob) enemy).surprisedBy(hero)\n\t\t\t\t&& hero.buff(Talent.ChainCooldown.class) == null){\n\t\t\tBuff.affect( this, Invisibility.class, 1f * hero.pointsInTalent(Talent.CHAIN_CLOCK));\n\t\t\tBuff.affect( this, Haste.class, 1f * hero.pointsInTalent(Talent.CHAIN_CLOCK));\n\t\t\tBuff.affect( this, Talent.ChainCooldown.class, 10f);\n\t\t\tSample.INSTANCE.play( Assets.Sounds.MELD );\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.CHASER\n\t\t\t\t&& hero.hasTalent(Talent.LETHAL_SURPRISE)\n\t\t\t\t&& ((Mob) enemy).surprisedBy(hero)\n\t\t\t\t&& !enemy.isAlive()\n\t\t\t\t&& hero.buff(Talent.LethalCooldown.class) == null) {\n\t\t\tif (hero.pointsInTalent(Talent.LETHAL_SURPRISE) >= 1) {\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] )) {\n\t\t\t\t\tif (mob.alignment != Char.Alignment.ALLY && Dungeon.level.heroFOV[mob.pos]) {\n\t\t\t\t\t\tBuff.affect( mob, Vulnerable.class, 1f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tBuff.affect(hero, Talent.LethalCooldown.class, 5f);\n\t\t\t}\n\t\t\tif (hero.pointsInTalent(Talent.LETHAL_SURPRISE) >= 2) {\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] )) {\n\t\t\t\t\tif (mob.alignment != Char.Alignment.ALLY && Dungeon.level.heroFOV[mob.pos]) {\n\t\t\t\t\t\tBuff.affect( mob, Paralysis.class, 1f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hero.pointsInTalent(Talent.LETHAL_SURPRISE) == 3) {\n\t\t\t\tBuff.affect(hero, Swiftthistle.TimeBubble.class).twoTurns();\n\t\t\t}\n\t\t}\n\n\t\tif (hit && heroClass == HeroClass.DUELIST && wasEnemy){\n\t\t\tBuff.affect( this, Sai.ComboStrikeTracker.class).addHit();\n\t\t}\n\n\t\tRingOfForce.BrawlersStance brawlStance = buff(RingOfForce.BrawlersStance.class);\n\t\tif (brawlStance != null && brawlStance.hitsLeft() > 0){\n\t\t\tMeleeWeapon.Charger charger = Buff.affect(this, MeleeWeapon.Charger.class);\n\t\t\tcharger.partialCharge -= RingOfForce.BrawlersStance.HIT_CHARGE_USE;\n\t\t\twhile (charger.partialCharge < 0) {\n\t\t\t\tcharger.charges--;\n\t\t\t\tcharger.partialCharge++;\n\t\t\t}\n\t\t\tBuffIndicator.refreshHero();\n\t\t\tItem.updateQuickslot();\n\t\t}\n\n\t\tif (!hit && hero.belongings.weapon == null && hero.subClass == HeroSubClass.FIGHTER && Random.Int(5) == 0 && hero.pointsInTalent(Talent.SWIFT_MOVEMENT) > 1) {\n\t\t\tBuff.prolong(hero, EvasiveMove.class, 0.9999f);\n\t\t}\n\n\t\tcurAction = null;\n\n\t\tsuper.onAttackComplete();\n\t}\n\t\n\t@Override\n\tpublic void onMotionComplete() {\n\t\tGameScene.checkKeyHold();\n\t}\n\t\n\t@Override\n\tpublic void onOperateComplete() {\n\t\t\n\t\tif (curAction instanceof HeroAction.Unlock) {\n\n\t\t\tint doorCell = ((HeroAction.Unlock)curAction).dst;\n\t\t\tint door = Dungeon.level.map[doorCell];\n\t\t\t\n\t\t\tif (Dungeon.level.distance(pos, doorCell) <= 1) {\n\t\t\t\tboolean hasKey = true;\n\t\t\t\tif (door == Terrain.LOCKED_DOOR) {\n\t\t\t\t\thasKey = Notes.remove(new IronKey(Dungeon.depth));\n\t\t\t\t\tif (hasKey) Level.set(doorCell, Terrain.DOOR);\n\t\t\t\t} else if (door == Terrain.CRYSTAL_DOOR) {\n\t\t\t\t\thasKey = Notes.remove(new CrystalKey(Dungeon.depth, Dungeon.branch));\n\t\t\t\t\tif (hasKey) {\n\t\t\t\t\t\tLevel.set(doorCell, Terrain.EMPTY);\n\t\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TELEPORT);\n\t\t\t\t\t\tCellEmitter.get( doorCell ).start( Speck.factory( Speck.DISCOVER ), 0.025f, 20 );\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\thasKey = Notes.remove(new SkeletonKey(Dungeon.depth));\n\t\t\t\t\tif (hasKey) Level.set(doorCell, Terrain.UNLOCKED_EXIT);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (hasKey) {\n\t\t\t\t\tGameScene.updateKeyDisplay();\n\t\t\t\t\tGameScene.updateMap(doorCell);\n\t\t\t\t\tspend(Key.TIME_TO_UNLOCK);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t} else if (curAction instanceof HeroAction.OpenChest) {\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( ((HeroAction.OpenChest)curAction).dst );\n\t\t\t\n\t\t\tif (Dungeon.level.distance(pos, heap.pos) <= 1){\n\t\t\t\tboolean hasKey = true;\n\t\t\t\tif (heap.type == Type.SKELETON || heap.type == Type.REMAINS) {\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.BONES );\n\t\t\t\t} else if (heap.type == Type.LOCKED_CHEST){\n\t\t\t\t\thasKey = Notes.remove(new GoldenKey(Dungeon.depth));\n\t\t\t\t} else if (heap.type == Type.CRYSTAL_CHEST){\n\t\t\t\t\thasKey = Notes.remove(new CrystalKey(Dungeon.depth));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (hasKey) {\n\t\t\t\t\tGameScene.updateKeyDisplay();\n\t\t\t\t\theap.open(this);\n\t\t\t\t\tspend(Key.TIME_TO_UNLOCK);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t\tcurAction = null;\n\n\t\tif (!ready) {\n\t\t\tsuper.onOperateComplete();\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean isImmune(Class effect) {\n\t\tif (effect == Burning.class\n\t\t\t\t&& belongings.armor() != null\n\t\t\t\t&& belongings.armor().hasGlyph(Brimstone.class, this)){\n\t\t\treturn true;\n\t\t}\n\t\treturn super.isImmune(effect);\n\t}\n\n\t@Override\n\tpublic boolean isInvulnerable(Class effect) {\n\t\treturn super.isInvulnerable(effect) || buff(AnkhInvulnerability.class) != null;\n\t}\n\n\tpublic boolean search( boolean intentional ) {\n\t\t\n\t\tif (!isAlive()) return false;\n\t\t\n\t\tboolean smthFound = false;\n\n\t\tboolean circular = pointsInTalent(Talent.WIDE_SEARCH) == 1;\n\t\tint distance = heroClass == HeroClass.ROGUE ? 2 : 1;\n\t\tif (hasTalent(Talent.WIDE_SEARCH)) distance++;\n\t\t\n\t\tboolean foresight = buff(Foresight.class) != null;\n\t\tboolean foresightScan = foresight && !Dungeon.level.mapped[pos];\n\n\t\tif (foresightScan){\n\t\t\tDungeon.level.mapped[pos] = true;\n\t\t}\n\n\t\tif (foresight) {\n\t\t\tdistance = Foresight.DISTANCE;\n\t\t\tcircular = true;\n\t\t}\n\n\t\tPoint c = Dungeon.level.cellToPoint(pos);\n\n\t\tTalismanOfForesight.Foresight talisman = buff( TalismanOfForesight.Foresight.class );\n\t\tboolean cursed = talisman != null && talisman.isCursed();\n\n\t\tint[] rounding = ShadowCaster.rounding[distance];\n\n\t\tint left, right;\n\t\tint curr;\n\t\tfor (int y = Math.max(0, c.y - distance); y <= Math.min(Dungeon.level.height()-1, c.y + distance); y++) {\n\t\t\tif (!circular){\n\t\t\t\tleft = c.x - distance;\n\t\t\t} else if (rounding[Math.abs(c.y - y)] < Math.abs(c.y - y)) {\n\t\t\t\tleft = c.x - rounding[Math.abs(c.y - y)];\n\t\t\t} else {\n\t\t\t\tleft = distance;\n\t\t\t\twhile (rounding[left] < rounding[Math.abs(c.y - y)]){\n\t\t\t\t\tleft--;\n\t\t\t\t}\n\t\t\t\tleft = c.x - left;\n\t\t\t}\n\t\t\tright = Math.min(Dungeon.level.width()-1, c.x + c.x - left);\n\t\t\tleft = Math.max(0, left);\n\t\t\tfor (curr = left + y * Dungeon.level.width(); curr <= right + y * Dungeon.level.width(); curr++){\n\n\t\t\t\tif ((foresight || fieldOfView[curr]) && curr != pos) {\n\n\t\t\t\t\tif ((foresight && (!Dungeon.level.mapped[curr] || foresightScan))){\n\t\t\t\t\t\tGameScene.effectOverFog(new CheckedCell(curr, foresightScan ? pos : curr));\n\t\t\t\t\t} else if (intentional) {\n\t\t\t\t\t\tGameScene.effectOverFog(new CheckedCell(curr, pos));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (foresight){\n\t\t\t\t\t\tDungeon.level.mapped[curr] = true;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (Dungeon.level.secret[curr]){\n\t\t\t\t\t\t\n\t\t\t\t\t\tTrap trap = Dungeon.level.traps.get( curr );\n\t\t\t\t\t\tfloat chance;\n\n\t\t\t\t\t\t//searches aided by foresight always succeed, even if trap isn't searchable\n\t\t\t\t\t\tif (foresight){\n\t\t\t\t\t\t\tchance = 1f;\n\n\t\t\t\t\t\t//otherwise if the trap isn't searchable, searching always fails\n\t\t\t\t\t\t} else if (trap != null && !trap.canBeSearched){\n\t\t\t\t\t\t\tchance = 0f;\n\n\t\t\t\t\t\t//intentional searches always succeed against regular traps and doors\n\t\t\t\t\t\t} else if (intentional){\n\t\t\t\t\t\t\tchance = 1f;\n\t\t\t\t\t\t\n\t\t\t\t\t\t//unintentional searches always fail with a cursed talisman\n\t\t\t\t\t\t} else if (cursed) {\n\t\t\t\t\t\t\tchance = 0f;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t//unintentional trap detection scales from 40% at floor 0 to 30% at floor 25\n\t\t\t\t\t\t} else if (Dungeon.level.map[curr] == Terrain.SECRET_TRAP) {\n\t\t\t\t\t\t\tchance = 0.4f - (Dungeon.depth / 250f);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t//unintentional door detection scales from 20% at floor 0 to 0% at floor 20\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tchance = 0.2f - (Dungeon.depth / 100f);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//don't want to let the player search though hidden doors in tutorial\n\t\t\t\t\t\tif (SPDSettings.intro()){\n\t\t\t\t\t\t\tchance = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (Random.Float() < chance) {\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tint oldValue = Dungeon.level.map[curr];\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tGameScene.discoverTile( curr, oldValue );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tDungeon.level.discover( curr );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tScrollOfMagicMapping.discover( curr );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (fieldOfView[curr]) smthFound = true;\n\t\n\t\t\t\t\t\t\tif (talisman != null){\n\t\t\t\t\t\t\t\tif (oldValue == Terrain.SECRET_TRAP){\n\t\t\t\t\t\t\t\t\ttalisman.charge(2);\n\t\t\t\t\t\t\t\t} else if (oldValue == Terrain.SECRET_DOOR){\n\t\t\t\t\t\t\t\t\ttalisman.charge(10);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (intentional) {\n\t\t\tsprite.showStatus( CharSprite.DEFAULT, Messages.get(this, \"search\") );\n\t\t\tsprite.operate( pos );\n\t\t\tif (!Dungeon.level.locked) {\n\t\t\t\tif (cursed) {\n\t\t\t\t\tGLog.n(Messages.get(this, \"search_distracted\"));\n\t\t\t\t\tBuff.affect(this, Hunger.class).affectHunger(TIME_TO_SEARCH - (2 * HUNGER_FOR_SEARCH));\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(this, Hunger.class).affectHunger(TIME_TO_SEARCH - HUNGER_FOR_SEARCH);\n\t\t\t\t}\n\t\t\t}\n\t\t\tspendAndNext(TIME_TO_SEARCH);\n\t\t\t\n\t\t}\n\t\t\n\t\tif (smthFound) {\n\t\t\tGLog.w( Messages.get(this, \"noticed_smth\") );\n\t\t\tSample.INSTANCE.play( Assets.Sounds.SECRET );\n\t\t\tinterrupt();\n\t\t}\n\n\t\tif (foresight){\n\t\t\tGameScene.updateFog(pos, Foresight.DISTANCE+1);\n\t\t}\n\t\t\n\t\treturn smthFound;\n\t}\n\t\n\tpublic void resurrect() {\n\t\tHP = HT;\n\t\tlive();\n\n\t\tMagicalHolster holster = belongings.getItem(MagicalHolster.class);\n\n\t\tBuff.affect(this, LostInventory.class);\n\t\tBuff.affect(this, Invisibility.class, 3f);\n\t\t//lost inventory is dropped in interlevelscene\n\n\t\t//activate items that persist after lost inventory\n\t\t//FIXME this is very messy, maybe it would be better to just have one buff that\n\t\t// handled all items that recharge over time?\n\t\tfor (Item i : belongings){\n\t\t\tif (i instanceof EquipableItem && i.isEquipped(this)){\n\t\t\t\t((EquipableItem) i).activate(this);\n\t\t\t} else if (i instanceof CloakOfShadows && i.keptThroughLostInventory() && hasTalent(Talent.LIGHT_CLOAK)){\n\t\t\t\t((CloakOfShadows) i).activate(this);\n\t\t\t} else if (i instanceof Wand && i.keptThroughLostInventory()){\n\t\t\t\tif (holster != null && holster.contains(i)){\n\t\t\t\t\t((Wand) i).charge(this, MagicalHolster.HOLSTER_SCALE_FACTOR);\n\t\t\t\t} else {\n\t\t\t\t\t((Wand) i).charge(this);\n\t\t\t\t}\n\t\t\t} else if (i instanceof MagesStaff && i.keptThroughLostInventory()){\n\t\t\t\t((MagesStaff) i).applyWandChargeBuff(this);\n\t\t\t}\n\t\t}\n\n\t\tupdateHT(false);\n\t}\n\n\t@Override\n\tpublic void next() {\n\t\tif (isAlive())\n\t\t\tsuper.next();\n\t}\n\n\tpublic static interface Doom {\n\t\tpublic void onDeath();\n\t}\n}" }, { "identifier": "CellEmitter", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/effects/CellEmitter.java", "snippet": "public class CellEmitter {\n\n\tpublic static Emitter floor( int cell ) {\n\n\t\tPointF p = DungeonTilemap.tileToWorld( cell );\n\n\t\tEmitter emitter = GameScene.floorEmitter();\n\t\temitter.pos( p.x, p.y, DungeonTilemap.SIZE, DungeonTilemap.SIZE );\n\n\t\treturn emitter;\n\t}\n\n\tpublic static Emitter get( int cell ) {\n\t\t\n\t\tPointF p = DungeonTilemap.tileToWorld( cell );\n\t\t\n\t\tEmitter emitter = GameScene.emitter();\n\t\temitter.pos( p.x, p.y, DungeonTilemap.SIZE, DungeonTilemap.SIZE );\n\t\t\n\t\treturn emitter;\n\t}\n\t\n\tpublic static Emitter center( int cell ) {\n\t\t\n\t\tPointF p = DungeonTilemap.tileToWorld( cell );\n\t\t\n\t\tEmitter emitter = GameScene.emitter();\n\t\temitter.pos( p.x + DungeonTilemap.SIZE / 2, p.y + DungeonTilemap.SIZE / 2 );\n\t\t\n\t\treturn emitter;\n\t}\n\t\n\tpublic static Emitter bottom( int cell ) {\n\t\t\n\t\tPointF p = DungeonTilemap.tileToWorld( cell );\n\t\t\n\t\tEmitter emitter = GameScene.emitter();\n\t\temitter.pos( p.x, p.y + DungeonTilemap.SIZE, DungeonTilemap.SIZE, 0 );\n\t\t\n\t\treturn emitter;\n\t}\n}" }, { "identifier": "ShadowParticle", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/effects/particles/ShadowParticle.java", "snippet": "public class ShadowParticle extends PixelParticle.Shrinking {\n\t\n\tpublic static final Emitter.Factory MISSILE = new Factory() {\n\t\t@Override\n\t\tpublic void emit( Emitter emitter, int index, float x, float y ) {\n\t\t\t((ShadowParticle)emitter.recycle( ShadowParticle.class )).reset( x, y );\n\t\t}\n\t};\n\t\n\tpublic static final Emitter.Factory CURSE = new Factory() {\n\t\t@Override\n\t\tpublic void emit( Emitter emitter, int index, float x, float y ) {\n\t\t\t((ShadowParticle)emitter.recycle( ShadowParticle.class )).resetCurse( x, y );\n\t\t}\n\t};\n\t\n\tpublic static final Emitter.Factory UP = new Factory() {\n\t\t@Override\n\t\tpublic void emit( Emitter emitter, int index, float x, float y ) {\n\t\t\t((ShadowParticle)emitter.recycle( ShadowParticle.class )).resetUp( x, y );\n\t\t}\n\t};\n\t\n\tpublic void reset( float x, float y ) {\n\t\trevive();\n\t\t\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\t\n\t\tspeed.set( Random.Float( -5, +5 ), Random.Float( -5, +5 ) );\n\t\t\n\t\tsize = 6;\n\t\tleft = lifespan = 0.5f;\n\t}\n\t\n\tpublic void resetCurse( float x, float y ) {\n\t\trevive();\n\t\t\n\t\tsize = 8;\n\t\tleft = lifespan = 0.5f;\n\t\t\n\t\tspeed.polar( Random.Float( PointF.PI2 ), Random.Float( 16, 32 ) );\n\t\tthis.x = x - speed.x * lifespan;\n\t\tthis.y = y - speed.y * lifespan;\n\t}\n\t\n\tpublic void resetUp( float x, float y ) {\n\t\trevive();\n\t\t\n\t\tspeed.set( Random.Float( -8, +8 ), Random.Float( -32, -48 ) );\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\t\n\t\tsize = 6;\n\t\tleft = lifespan = 1f;\n\t}\n\t\n\t@Override\n\tpublic void update() {\n\t\tsuper.update();\n\t\t\n\t\tfloat p = left / lifespan;\n\t\t// alpha: 0 -> 1 -> 0; size: 6 -> 0; color: 0x660044 -> 0x000000\n\t\tcolor( ColorMath.interpolate( 0x000000, 0x440044, p ) );\n\t\tam = p < 0.5f ? p * p * 4 : (1 - p) * 2;\n\t}\n}" }, { "identifier": "EquipableItem", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/EquipableItem.java", "snippet": "public abstract class EquipableItem extends Item {\n\n\tpublic static final String AC_EQUIP\t\t= \"EQUIP\";\n\tpublic static final String AC_UNEQUIP\t= \"UNEQUIP\";\n\n\t{\n\t\tbones = true;\n\t}\n\n\t@Override\n\tpublic ArrayList<String> actions(Hero hero ) {\n\t\tArrayList<String> actions = super.actions( hero );\n\t\tactions.add( isEquipped( hero ) ? AC_UNEQUIP : AC_EQUIP );\n\t\treturn actions;\n\t}\n\n\t@Override\n\tpublic boolean doPickUp(Hero hero, int pos) {\n\t\tif (super.doPickUp(hero, pos)){\n\t\t\tif (!isIdentified() && !Document.ADVENTURERS_GUIDE.isPageRead(Document.GUIDE_IDING)){\n\t\t\t\tGLog.p(Messages.get(Guidebook.class, \"hint\"));\n\t\t\t\tGameScene.flashForDocument(Document.ADVENTURERS_GUIDE, Document.GUIDE_IDING);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprotected static int slotOfUnequipped = -1;\n\n\t@Override\n\tpublic void execute( Hero hero, String action ) {\n\n\t\tsuper.execute( hero, action );\n\n\t\tif (action.equals( AC_EQUIP )) {\n\t\t\t//In addition to equipping itself, item reassigns itself to the quickslot\n\t\t\t//This is a special case as the item is being removed from inventory, but is staying with the hero.\n\t\t\tint slot = Dungeon.quickslot.getSlot( this );\n\t\t\tslotOfUnequipped = -1;\n\t\t\tdoEquip(hero);\n\t\t\tif (slot != -1) {\n\t\t\t\tDungeon.quickslot.setSlot( slot, this );\n\t\t\t\tupdateQuickslot();\n\t\t\t//if this item wasn't quickslotted, but the item it is replacing as equipped was\n\t\t\t//then also have the item occupy the unequipped item's quickslot\n\t\t\t} else if (slotOfUnequipped != -1 && defaultAction() != null) {\n\t\t\t\tDungeon.quickslot.setSlot( slotOfUnequipped, this );\n\t\t\t\tupdateQuickslot();\n\t\t\t}\n\t\t} else if (action.equals( AC_UNEQUIP )) {\n\t\t\tdoUnequip( hero, true );\n\t\t}\n\t}\n\n\t@Override\n\tpublic void doDrop( Hero hero ) {\n\t\tif (!isEquipped( hero ) || doUnequip( hero, false, false )) {\n\t\t\tsuper.doDrop( hero );\n\t\t}\n\t}\n\n\t@Override\n\tpublic void cast( final Hero user, int dst ) {\n\n\t\tif (isEquipped( user )) {\n\t\t\tif (quantity == 1 && !this.doUnequip( user, false, false )) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tsuper.cast( user, dst );\n\t}\n\n\tpublic static void equipCursed( Hero hero ) {\n\t\thero.sprite.emitter().burst( ShadowParticle.CURSE, 6 );\n\t\tSample.INSTANCE.play( Assets.Sounds.CURSED );\n\t}\n\n\tprotected float time2equip( Hero hero ) {\n\t\treturn 1;\n\t}\n\n\tpublic abstract boolean doEquip( Hero hero );\n\n\tpublic boolean doUnequip( Hero hero, boolean collect, boolean single ) {\n\n\t\tif (cursed\n\t\t\t\t&& hero.buff(MagicImmune.class) == null\n\t\t\t\t&& (hero.buff(LostInventory.class) == null || keptThroughLostInventory())) {\n\t\t\tGLog.w(Messages.get(EquipableItem.class, \"unequip_cursed\"));\n\t\t\treturn false;\n\t\t}\n\n\t\tif (single) {\n\t\t\thero.spendAndNext( time2equip( hero ) );\n\t\t} else {\n\t\t\thero.spend( time2equip( hero ) );\n\t\t}\n\n\t\tslotOfUnequipped = Dungeon.quickslot.getSlot(this);\n\n\t\t//temporarily keep this item so it can be collected\n\t\tboolean wasKept = keptThoughLostInvent;\n\t\tkeptThoughLostInvent = true;\n\t\tif (!collect || !collect( hero.belongings.backpack )) {\n\t\t\tonDetach();\n\t\t\tDungeon.quickslot.clearItem(this);\n\t\t\tupdateQuickslot();\n\t\t\tif (collect) Dungeon.level.drop( this, hero.pos ).sprite.drop();\n\t\t}\n\t\tkeptThoughLostInvent = wasKept;\n\n\t\treturn true;\n\t}\n\n\tfinal public boolean doUnequip( Hero hero, boolean collect ) {\n\t\treturn doUnequip( hero, collect, true );\n\t}\n\n\tpublic void activate( Char ch ){}\n}" }, { "identifier": "Heap", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/Heap.java", "snippet": "public class Heap implements Bundlable {\n\t\n\tpublic enum Type {\n\t\tHEAP,\n\t\tFOR_SALE,\n\t\tCHEST,\n\t\tLOCKED_CHEST,\n\t\tCRYSTAL_CHEST,\n\t\tTOMB,\n\t\tSKELETON,\n\t\tREMAINS,\n\t\tMIMIC,\n\t\tGOLDEN_MIMIC,\n\t\tCRYSTAL_MIMIC,\n\t\tSTATUE\n\t}\n\tpublic Type type = Type.HEAP;\n\t\n\tpublic int pos = 0;\n\t\n\tpublic ItemSprite sprite;\n\tpublic boolean seen = false;\n\tpublic boolean haunted = false;\n\tpublic boolean autoExplored = false; //used to determine if this heap should count for exploration bonus\n\t\n\tpublic LinkedList<Item> items = new LinkedList<>();\n\t\n\tpublic void open( Hero hero ) {\n\t\tswitch (type) {\n\t\tcase TOMB:\n\t\t\tWraith.spawnAround( hero.pos, true );\n\t\t\tbreak;\n\t\tcase REMAINS:\n\t\tcase SKELETON:\n\t\t\tCellEmitter.center( pos ).start(Speck.factory(Speck.RATTLE), 0.1f, 3);\n\t\t\tbreak;\n\t\tdefault:\n\t\t}\n\t\t\n\t\tif (haunted){\n\t\t\tif (Wraith.spawnAt( pos, true ) == null) {\n\t\t\t\thero.sprite.emitter().burst( ShadowParticle.CURSE, 6 );\n\t\t\t\thero.damage( hero.HP / 2, this );\n\t\t\t\tif (!hero.isAlive()){\n\t\t\t\t\tDungeon.fail(Wraith.class);\n\t\t\t\t\tGLog.n( Messages.capitalize(Messages.get(Char.class, \"kill\", Messages.get(Wraith.class, \"name\"))));\n\t\t\t\t}\n\t\t\t}\n\t\t\tSample.INSTANCE.play( Assets.Sounds.CURSED );\n\t\t}\n\n\t\ttype = Type.HEAP;\n\t\tArrayList<Item> bonus = RingOfWealth.tryForBonusDrop(hero, 1);\n\t\tif (bonus != null && !bonus.isEmpty()) {\n\t\t\titems.addAll(0, bonus);\n\t\t\tRingOfWealth.showFlareForBonusDrop(sprite);\n\t\t}\n\t\tsprite.link();\n\t\tsprite.drop();\n\t}\n\t\n\tpublic Heap setHauntedIfCursed(){\n\t\tfor (Item item : items) {\n\t\t\tif (item.cursed) {\n\t\t\t\thaunted = true;\n\t\t\t\titem.cursedKnown = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\t\n\tpublic int size() {\n\t\treturn items.size();\n\t}\n\t\n\tpublic Item pickUp() {\n\t\t\n\t\tif (items.isEmpty()){\n\t\t\tdestroy();\n\t\t\treturn null;\n\t\t}\n\t\tItem item = items.removeFirst();\n\t\tif (items.isEmpty()) {\n\t\t\tdestroy();\n\t\t} else if (sprite != null) {\n\t\t\tsprite.view(this).place( pos );\n\t\t}\n\t\t\n\t\treturn item;\n\t}\n\t\n\tpublic Item peek() {\n\t\treturn items.peek();\n\t}\n\t\n\tpublic void drop( Item item ) {\n\t\t\n\t\tif (item.stackable && type != Type.FOR_SALE) {\n\t\t\t\n\t\t\tfor (Item i : items) {\n\t\t\t\tif (i.isSimilar( item )) {\n\t\t\t\t\titem = i.merge( item );\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\titems.remove( item );\n\t\t\t\n\t\t}\n\n\t\t//lost backpack must always be on top of a heap\n\t\tif ((item.dropsDownHeap && type != Type.FOR_SALE) || peek() instanceof LostBackpack) {\n\t\t\titems.add( item );\n\t\t} else {\n\t\t\titems.addFirst( item );\n\t\t}\n\t\t\n\t\tif (sprite != null) {\n\t\t\tsprite.view(this).place( pos );\n\t\t}\n\n\t\tif (TippedDart.lostDarts > 0){\n\t\t\tDart d = new Dart();\n\t\t\td.quantity(TippedDart.lostDarts);\n\t\t\tTippedDart.lostDarts = 0;\n\t\t\tdrop(d);\n\t\t}\n\t}\n\t\n\tpublic void replace( Item a, Item b ) {\n\t\tint index = items.indexOf( a );\n\t\tif (index != -1) {\n\t\t\titems.remove( index );\n\t\t\tfor (Item i : items) {\n\t\t\t\tif (i.isSimilar( b )) {\n\t\t\t\t\ti.merge( b );\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\titems.add( index, b );\n\t\t}\n\t}\n\t\n\tpublic void remove( Item a ){\n\t\titems.remove(a);\n\t\tif (items.isEmpty()){\n\t\t\tdestroy();\n\t\t} else if (sprite != null) {\n\t\t\tsprite.view(this).place( pos );\n\t\t}\n\t}\n\t\n\tpublic void burn() {\n\n\t\tif (type != Type.HEAP) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tboolean burnt = false;\n\t\tboolean evaporated = false;\n\t\t\n\t\tfor (Item item : items.toArray( new Item[0] )) {\n\t\t\tif (item instanceof Scroll && !item.unique) {\n\t\t\t\titems.remove( item );\n\t\t\t\tburnt = true;\n\t\t\t} else if (item instanceof Dewdrop) {\n\t\t\t\titems.remove( item );\n\t\t\t\tevaporated = true;\n\t\t\t} else if (item instanceof MysteryMeat || item instanceof FrozenCarpaccio) {\n\t\t\t\treplace( item, ChargrilledMeat.cook( item.quantity ) );\n\t\t\t\tburnt = true;\n\t\t\t} else if (item instanceof Bomb) {\n\t\t\t\titems.remove( item );\n\t\t\t\t((Bomb) item).explode( pos );\n\t\t\t\tif (((Bomb) item).explodesDestructively()) {\n\t\t\t\t\t//stop processing the burning, it will be replaced by the explosion.\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tburnt = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (burnt || evaporated) {\n\t\t\t\n\t\t\tif (Dungeon.level.heroFOV[pos]) {\n\t\t\t\tif (burnt) {\n\t\t\t\t\tburnFX( pos );\n\t\t\t\t} else {\n\t\t\t\t\tevaporateFX( pos );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (isEmpty()) {\n\t\t\t\tdestroy();\n\t\t\t} else if (sprite != null) {\n\t\t\t\tsprite.view(this).place( pos );\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\n\t//Note: should not be called to initiate an explosion, but rather by an explosion that is happening.\n\tpublic void explode() {\n\n\t\t//breaks open most standard containers, mimics die.\n\t\tif (type == Type.CHEST || type == Type.SKELETON) {\n\t\t\ttype = Type.HEAP;\n\t\t\tsprite.link();\n\t\t\tsprite.drop();\n\t\t\treturn;\n\t\t}\n\n\t\tif (type != Type.HEAP) {\n\n\t\t\treturn;\n\n\t\t} else {\n\n\t\t\tfor (Item item : items.toArray( new Item[0] )) {\n\n\t\t\t\t//unique items aren't affect by explosions\n\t\t\t\tif (item.unique || (item instanceof Armor && ((Armor) item).checkSeal() != null)){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (item instanceof Potion) {\n\t\t\t\t\titems.remove(item);\n\t\t\t\t\t((Potion) item).shatter(pos);\n\n\t\t\t\t} else if (item instanceof Honeypot.ShatteredPot) {\n\t\t\t\t\titems.remove(item);\n\t\t\t\t\t((Honeypot.ShatteredPot) item).destroyPot(pos);\n\n\t\t\t\t} else if (item instanceof Bomb) {\n\t\t\t\t\titems.remove( item );\n\t\t\t\t\t((Bomb) item).explode(pos);\n\t\t\t\t\tif (((Bomb) item).explodesDestructively()) {\n\t\t\t\t\t\t//stop processing current explosion, it will be replaced by the new one.\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t//upgraded items can endure the blast\n\t\t\t\t} else if (item.level() <= 0) {\n\t\t\t\t\titems.remove( item );\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif (isEmpty()){\n\t\t\t\tdestroy();\n\t\t\t} else if (sprite != null) {\n\t\t\t\tsprite.view(this).place( pos );\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void freeze() {\n\n\t\tif (type != Type.HEAP) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tboolean frozen = false;\n\t\tfor (Item item : items.toArray( new Item[0] )) {\n\t\t\tif (item instanceof MysteryMeat) {\n\t\t\t\treplace( item, FrozenCarpaccio.cook( (MysteryMeat)item ) );\n\t\t\t\tfrozen = true;\n\t\t\t} else if (item instanceof Potion && !item.unique) {\n\t\t\t\titems.remove(item);\n\t\t\t\t((Potion) item).shatter(pos);\n\t\t\t\tfrozen = true;\n\t\t\t} else if (item instanceof Bomb && ((Bomb) item).fuse != null){\n\t\t\t\tfrozen = frozen || ((Bomb) item).fuse.freeze();\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (frozen) {\n\t\t\tif (isEmpty()) {\n\t\t\t\tdestroy();\n\t\t\t} else if (sprite != null) {\n\t\t\t\tsprite.view(this).place( pos );\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void burnFX( int pos ) {\n\t\tCellEmitter.get( pos ).burst( ElmoParticle.FACTORY, 6 );\n\t\tSample.INSTANCE.play( Assets.Sounds.BURNING );\n\t}\n\t\n\tpublic static void evaporateFX( int pos ) {\n\t\tCellEmitter.get( pos ).burst( Speck.factory( Speck.STEAM ), 5 );\n\t}\n\t\n\tpublic boolean isEmpty() {\n\t\treturn items == null || items.size() == 0;\n\t}\n\t\n\tpublic void destroy() {\n\t\tDungeon.level.heaps.remove( this.pos );\n\t\tif (sprite != null) {\n\t\t\tsprite.kill();\n\t\t}\n\t\titems.clear();\n\t}\n\n\tpublic String title(){\n\t\tswitch(type){\n\t\t\tcase FOR_SALE:\n\t\t\t\tItem i = peek();\n\t\t\t\tif (size() == 1) {\n\t\t\t\t\treturn Messages.get(this, \"for_sale\", Shopkeeper.sellPrice(i), i.title());\n\t\t\t\t} else {\n\t\t\t\t\treturn i.title();\n\t\t\t\t}\n\t\t\tcase CHEST:\n\t\t\t\treturn Messages.get(this, \"chest\");\n\t\t\tcase LOCKED_CHEST:\n\t\t\t\treturn Messages.get(this, \"locked_chest\");\n\t\t\tcase CRYSTAL_CHEST:\n\t\t\t\treturn Messages.get(this, \"crystal_chest\");\n\t\t\tcase TOMB:\n\t\t\t\treturn Messages.get(this, \"tomb\");\n\t\t\tcase SKELETON:\n\t\t\t\treturn Messages.get(this, \"skeleton\");\n\t\t\tcase REMAINS:\n\t\t\t\treturn Messages.get(this, \"remains\");\n\t\t\tdefault:\n\t\t\t\treturn peek().title();\n\t\t}\n\t}\n\n\tpublic String info(){\n\t\tswitch(type){\n\t\t\tcase CHEST:\n\t\t\t\treturn Messages.get(this, \"chest_desc\");\n\t\t\tcase LOCKED_CHEST:\n\t\t\t\treturn Messages.get(this, \"locked_chest_desc\");\n\t\t\tcase CRYSTAL_CHEST:\n\t\t\t\tif (peek() instanceof Artifact)\n\t\t\t\t\treturn Messages.get(this, \"crystal_chest_desc\", Messages.get(this, \"artifact\") );\n\t\t\t\telse if (peek() instanceof Wand)\n\t\t\t\t\treturn Messages.get(this, \"crystal_chest_desc\", Messages.get(this, \"wand\") );\n\t\t\t\telse\n\t\t\t\t\treturn Messages.get(this, \"crystal_chest_desc\", Messages.get(this, \"ring\") );\n\t\t\tcase TOMB:\n\t\t\t\treturn Messages.get(this, \"tomb_desc\");\n\t\t\tcase SKELETON:\n\t\t\t\treturn Messages.get(this, \"skeleton_desc\");\n\t\t\tcase REMAINS:\n\t\t\t\treturn Messages.get(this, \"remains_desc\");\n\t\t\tdefault:\n\t\t\t\treturn peek().info();\n\t\t}\n\t}\n\n\tprivate static final String POS\t\t= \"pos\";\n\tprivate static final String SEEN\t= \"seen\";\n\tprivate static final String TYPE\t= \"type\";\n\tprivate static final String ITEMS\t= \"items\";\n\tprivate static final String HAUNTED\t= \"haunted\";\n\tprivate static final String AUTO_EXPLORED\t= \"auto_explored\";\n\t\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tpos = bundle.getInt( POS );\n\t\tseen = bundle.getBoolean( SEEN );\n\t\ttype = Type.valueOf( bundle.getString( TYPE ) );\n\t\t\n\t\titems = new LinkedList<>((Collection<Item>) ((Collection<?>) bundle.getCollection(ITEMS)));\n\t\titems.removeAll(Collections.singleton(null));\n\t\t\n\t\t//remove any document pages that either don't exist anymore or that the player already has\n\t\tfor (Item item : items.toArray(new Item[0])){\n\t\t\tif (item instanceof DocumentPage\n\t\t\t\t\t&& ( !((DocumentPage) item).document().pageNames().contains(((DocumentPage) item).page())\n\t\t\t\t\t|| ((DocumentPage) item).document().isPageFound(((DocumentPage) item).page()))){\n\t\t\t\titems.remove(item);\n\t\t\t}\n\t\t\tif (item instanceof Guidebook && Document.ADVENTURERS_GUIDE.isPageRead(0)){\n\t\t\t\titems.remove(item);\n\t\t\t}\n\t\t}\n\t\t\n\t\thaunted = bundle.getBoolean( HAUNTED );\n\t\tautoExplored = bundle.getBoolean( AUTO_EXPLORED );\n\t}\n\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tbundle.put( POS, pos );\n\t\tbundle.put( SEEN, seen );\n\t\tbundle.put( TYPE, type );\n\t\tbundle.put( ITEMS, items );\n\t\tbundle.put( HAUNTED, haunted );\n\t\tbundle.put( AUTO_EXPLORED, autoExplored );\n\t}\n\t\n}" }, { "identifier": "Item", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/Item.java", "snippet": "public class Item implements Bundlable {\n\n\tprotected static final String TXT_TO_STRING_LVL\t\t= \"%s %+d\";\n\tprotected static final String TXT_TO_STRING_X\t\t= \"%s x%d\";\n\t\n\tprotected static final float TIME_TO_THROW\t\t= 1.0f;\n\tprotected static final float TIME_TO_PICK_UP\t= 1.0f;\n\tprotected static final float TIME_TO_DROP\t\t= 1.0f;\n\t\n\tpublic static final String AC_DROP\t\t= \"DROP\";\n\tpublic static final String AC_THROW\t\t= \"THROW\";\n\t\n\tprotected String defaultAction;\n\tpublic boolean usesTargeting;\n\n\t//TODO should these be private and accessed through methods?\n\tpublic int image = 0;\n\tpublic int icon = -1; //used as an identifier for items with randomized images\n\t\n\tpublic boolean stackable = false;\n\tprotected int quantity = 1;\n\tpublic boolean dropsDownHeap = false;\n\t\n\tprivate int level = 0;\n\n\tpublic boolean levelKnown = false;\n\t\n\tpublic boolean cursed;\n\tpublic boolean cursedKnown;\n\t\n\t// Unique items persist through revival\n\tpublic boolean unique = false;\n\n\t// These items are preserved even if the hero's inventory is lost via unblessed ankh\n\t// this is largely set by the resurrection window, items can override this to always be kept\n\tpublic boolean keptThoughLostInvent = false;\n\n\t// whether an item can be included in heroes remains\n\tpublic boolean bones = false;\n\t\n\tpublic static final Comparator<Item> itemComparator = new Comparator<Item>() {\n\t\t@Override\n\t\tpublic int compare( Item lhs, Item rhs ) {\n\t\t\treturn Generator.Category.order( lhs ) - Generator.Category.order( rhs );\n\t\t}\n\t};\n\t\n\tpublic ArrayList<String> actions( Hero hero ) {\n\t\tArrayList<String> actions = new ArrayList<>();\n\t\tactions.add( AC_DROP );\n\t\tactions.add( AC_THROW );\n\t\treturn actions;\n\t}\n\n\tpublic String actionName(String action, Hero hero){\n\t\treturn Messages.get(this, \"ac_\" + action);\n\t}\n\n\tpublic final boolean doPickUp( Hero hero ) {\n\t\treturn doPickUp( hero, hero.pos );\n\t}\n\n\tpublic boolean doPickUp(Hero hero, int pos) {\n\t\tif (collect( hero.belongings.backpack )) {\n\t\t\t\n\t\t\tGameScene.pickUp( this, pos );\n\t\t\tSample.INSTANCE.play( Assets.Sounds.ITEM );\n\t\t\thero.spendAndNext( TIME_TO_PICK_UP );\n\t\t\treturn true;\n\t\t\t\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic void doDrop( Hero hero ) {\n\t\thero.spendAndNext(TIME_TO_DROP);\n\t\tint pos = hero.pos;\n\t\tDungeon.level.drop(detachAll(hero.belongings.backpack), pos).sprite.drop(pos);\n\t}\n\n\t//resets an item's properties, to ensure consistency between runs\n\tpublic void reset(){\n\t\tkeptThoughLostInvent = false;\n\t}\n\n\tpublic boolean keptThroughLostInventory(){\n\t\treturn keptThoughLostInvent;\n\t}\n\n\tpublic void doThrow( Hero hero ) {\n\t\tGameScene.selectCell(thrower);\n\t}\n\t\n\tpublic void execute( Hero hero, String action ) {\n\n\t\tGameScene.cancel();\n\t\tcurUser = hero;\n\t\tcurItem = this;\n\t\t\n\t\tif (action.equals( AC_DROP )) {\n\t\t\t\n\t\t\tif (hero.belongings.backpack.contains(this) || isEquipped(hero)) {\n\t\t\t\tdoDrop(hero);\n\t\t\t}\n\t\t\t\n\t\t} else if (action.equals( AC_THROW )) {\n\t\t\t\n\t\t\tif (hero.belongings.backpack.contains(this) || isEquipped(hero)) {\n\t\t\t\tdoThrow(hero);\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\n\t//can be overridden if default action is variable\n\tpublic String defaultAction(){\n\t\treturn defaultAction;\n\t}\n\t\n\tpublic void execute( Hero hero ) {\n\t\tString action = defaultAction();\n\t\tif (action != null) {\n\t\t\texecute(hero, defaultAction());\n\t\t}\n\t}\n\t\n\tprotected void onThrow( int cell ) {\n\t\tHeap heap = Dungeon.level.drop( this, cell );\n\t\tif (!heap.isEmpty()) {\n\t\t\theap.sprite.drop( cell );\n\t\t}\n\t}\n\t\n\t//takes two items and merges them (if possible)\n\tpublic Item merge( Item other ){\n\t\tif (isSimilar( other )){\n\t\t\tquantity += other.quantity;\n\t\t\tother.quantity = 0;\n\t\t}\n\t\treturn this;\n\t}\n\t\n\tpublic boolean collect( Bag container ) {\n\n\t\tif (quantity <= 0){\n\t\t\treturn true;\n\t\t}\n\n\t\tArrayList<Item> items = container.items;\n\n\t\tif (items.contains( this )) {\n\t\t\treturn true;\n\t\t}\n\n\t\tfor (Item item:items) {\n\t\t\tif (item instanceof Bag && ((Bag)item).canHold( this )) {\n\t\t\t\tif (collect( (Bag)item )){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!container.canHold(this)){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif (stackable) {\n\t\t\tfor (Item item:items) {\n\t\t\t\tif (isSimilar( item )) {\n\t\t\t\t\titem.merge( this );\n\t\t\t\t\titem.updateQuickslot();\n\t\t\t\t\tif (Dungeon.hero != null && Dungeon.hero.isAlive()) {\n\t\t\t\t\t\tBadges.validateItemLevelAquired( this );\n\t\t\t\t\t\tTalent.onItemCollected(Dungeon.hero, item);\n\t\t\t\t\t\tif (isIdentified()) Catalog.setSeen(getClass());\n\t\t\t\t\t}\n\t\t\t\t\tif (TippedDart.lostDarts > 0){\n\t\t\t\t\t\tDart d = new Dart();\n\t\t\t\t\t\td.quantity(TippedDart.lostDarts);\n\t\t\t\t\t\tTippedDart.lostDarts = 0;\n\t\t\t\t\t\tif (!d.collect()){\n\t\t\t\t\t\t\t//have to handle this in an actor as we can't manipulate the heap during pickup\n\t\t\t\t\t\t\tActor.add(new Actor() {\n\t\t\t\t\t\t\t\t{ actPriority = VFX_PRIO; }\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tprotected boolean act() {\n\t\t\t\t\t\t\t\t\tDungeon.level.drop(d, Dungeon.hero.pos).sprite.drop();\n\t\t\t\t\t\t\t\t\tActor.remove(this);\n\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.hero != null && Dungeon.hero.isAlive()) {\n\t\t\tBadges.validateItemLevelAquired( this );\n\t\t\tTalent.onItemCollected( Dungeon.hero, this );\n\t\t\tif (isIdentified()) Catalog.setSeen(getClass());\n\t\t}\n\n\t\titems.add( this );\n\t\tDungeon.quickslot.replacePlaceholder(this);\n\t\tCollections.sort( items, itemComparator );\n\t\tupdateQuickslot();\n\t\treturn true;\n\n\t}\n\t\n\tpublic boolean collect() {\n\t\treturn collect( Dungeon.hero.belongings.backpack );\n\t}\n\t\n\t//returns a new item if the split was sucessful and there are now 2 items, otherwise null\n\tpublic Item split( int amount ){\n\t\tif (amount <= 0 || amount >= quantity()) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\t//pssh, who needs copy constructors?\n\t\t\tItem split = Reflection.newInstance(getClass());\n\t\t\t\n\t\t\tif (split == null){\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t\n\t\t\tBundle copy = new Bundle();\n\t\t\tthis.storeInBundle(copy);\n\t\t\tsplit.restoreFromBundle(copy);\n\t\t\tsplit.quantity(amount);\n\t\t\tquantity -= amount;\n\t\t\t\n\t\t\treturn split;\n\t\t}\n\t}\n\t\n\tpublic final Item detach( Bag container ) {\n\t\t\n\t\tif (quantity <= 0) {\n\t\t\t\n\t\t\treturn null;\n\t\t\t\n\t\t} else\n\t\tif (quantity == 1) {\n\n\t\t\tif (stackable){\n\t\t\t\tDungeon.quickslot.convertToPlaceholder(this);\n\t\t\t}\n\n\t\t\treturn detachAll( container );\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tItem detached = split(1);\n\t\t\tupdateQuickslot();\n\t\t\tif (detached != null) detached.onDetach( );\n\t\t\treturn detached;\n\t\t\t\n\t\t}\n\t}\n\t\n\tpublic final Item detachAll( Bag container ) {\n\t\tDungeon.quickslot.clearItem( this );\n\n\t\tfor (Item item : container.items) {\n\t\t\tif (item == this) {\n\t\t\t\tcontainer.items.remove(this);\n\t\t\t\titem.onDetach();\n\t\t\t\tcontainer.grabItems(); //try to put more items into the bag as it now has free space\n\t\t\t\tupdateQuickslot();\n\t\t\t\treturn this;\n\t\t\t} else if (item instanceof Bag) {\n\t\t\t\tBag bag = (Bag)item;\n\t\t\t\tif (bag.contains( this )) {\n\t\t\t\t\treturn detachAll( bag );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdateQuickslot();\n\t\treturn this;\n\t}\n\t\n\tpublic boolean isSimilar( Item item ) {\n\t\treturn level == item.level && getClass() == item.getClass();\n\t}\n\n\tprotected void onDetach(){}\n\n\t//returns the true level of the item, ignoring all modifiers aside from upgrades\n\tpublic final int trueLevel(){\n\t\treturn level;\n\t}\n\n\t//returns the persistant level of the item, only affected by modifiers which are persistent (e.g. curse infusion)\n\tpublic int level(){\n\t\treturn level;\n\t}\n\t\n\t//returns the level of the item, after it may have been modified by temporary boosts/reductions\n\t//note that not all item properties should care about buffs/debuffs! (e.g. str requirement)\n\tpublic int buffedLvl(){\n\t\t//only the hero can be affected by Degradation\n\t\tif (Dungeon.hero.buff( Degrade.class ) != null\n\t\t\t&& (isEquipped( Dungeon.hero ) || Dungeon.hero.belongings.contains( this ))) {\n\t\t\treturn Degrade.reduceLevel(level());\n\t\t} else {\n\t\t\treturn level();\n\t\t}\n\t}\n\n\tpublic void level( int value ){\n\t\tlevel = value;\n\n\t\tupdateQuickslot();\n\t}\n\t\n\tpublic Item upgrade() {\n\t\t\n\t\tthis.level++;\n\n\t\tupdateQuickslot();\n\t\t\n\t\treturn this;\n\t}\n\t\n\tfinal public Item upgrade( int n ) {\n\t\tfor (int i=0; i < n; i++) {\n\t\t\tupgrade();\n\t\t}\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic Item degrade() {\n\t\t\n\t\tthis.level--;\n\t\t\n\t\treturn this;\n\t}\n\t\n\tfinal public Item degrade( int n ) {\n\t\tfor (int i=0; i < n; i++) {\n\t\t\tdegrade();\n\t\t}\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic int visiblyUpgraded() {\n\t\treturn levelKnown ? level() : 0;\n\t}\n\n\tpublic int buffedVisiblyUpgraded() {\n\t\treturn levelKnown ? buffedLvl() : 0;\n\t}\n\t\n\tpublic boolean visiblyCursed() {\n\t\treturn cursed && cursedKnown;\n\t}\n\t\n\tpublic boolean isUpgradable() {\n\t\treturn true;\n\t}\n\t\n\tpublic boolean isIdentified() {\n\t\treturn levelKnown && cursedKnown;\n\t}\n\t\n\tpublic boolean isEquipped( Hero hero ) {\n\t\treturn false;\n\t}\n\n\tpublic final Item identify(){\n\t\treturn identify(true);\n\t}\n\n\tpublic Item identify( boolean byHero ) {\n\n\t\tif (byHero && Dungeon.hero != null && Dungeon.hero.isAlive()){\n\t\t\tCatalog.setSeen(getClass());\n\t\t\tif (!isIdentified()) Talent.onItemIdentified(Dungeon.hero, this);\n\t\t}\n\n\t\tlevelKnown = true;\n\t\tcursedKnown = true;\n\t\tItem.updateQuickslot();\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic void onHeroGainExp( float levelPercent, Hero hero ){\n\t\t//do nothing by default\n\t}\n\t\n\tpublic static void evoke( Hero hero ) {\n\t\thero.sprite.emitter().burst( Speck.factory( Speck.EVOKE ), 5 );\n\t}\n\n\tpublic String title() {\n\n\t\tString name = name();\n\n\t\tif (visiblyUpgraded() != 0)\n\t\t\tname = Messages.format( TXT_TO_STRING_LVL, name, visiblyUpgraded() );\n\n\t\tif (quantity > 1)\n\t\t\tname = Messages.format( TXT_TO_STRING_X, name, quantity );\n\n\t\treturn name;\n\n\t}\n\t\n\tpublic String name() {\n\t\treturn trueName();\n\t}\n\t\n\tpublic final String trueName() {\n\t\treturn Messages.get(this, \"name\");\n\t}\n\t\n\tpublic int image() {\n\t\treturn image;\n\t}\n\t\n\tpublic ItemSprite.Glowing glowing() {\n\t\treturn null;\n\t}\n\n\tpublic Emitter emitter() { return null; }\n\t\n\tpublic String info() {\n\t\treturn desc();\n\t}\n\t\n\tpublic String desc() {\n\t\treturn Messages.get(this, \"desc\");\n\t}\n\t\n\tpublic int quantity() {\n\t\treturn quantity;\n\t}\n\t\n\tpublic Item quantity( int value ) {\n\t\tquantity = value;\n\t\treturn this;\n\t}\n\n\t//item's value in gold coins\n\tpublic int value() {\n\t\treturn 0;\n\t}\n\n\t//item's value in energy crystals\n\tpublic int energyVal() {\n\t\treturn 0;\n\t}\n\t\n\tpublic Item virtual(){\n\t\tItem item = Reflection.newInstance(getClass());\n\t\tif (item == null) return null;\n\t\t\n\t\titem.quantity = 0;\n\t\titem.level = level;\n\t\treturn item;\n\t}\n\t\n\tpublic Item random() {\n\t\treturn this;\n\t}\n\t\n\tpublic String status() {\n\t\treturn quantity != 1 ? Integer.toString( quantity ) : null;\n\t}\n\n\tpublic static void updateQuickslot() {\n\t\tGameScene.updateItemDisplays = true;\n\t}\n\t\n\tprivate static final String QUANTITY\t\t= \"quantity\";\n\tprivate static final String LEVEL\t\t\t= \"level\";\n\tprivate static final String LEVEL_KNOWN\t\t= \"levelKnown\";\n\tprivate static final String CURSED\t\t\t= \"cursed\";\n\tprivate static final String CURSED_KNOWN\t= \"cursedKnown\";\n\tprivate static final String QUICKSLOT\t\t= \"quickslotpos\";\n\tprivate static final String KEPT_LOST = \"kept_lost\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tbundle.put( QUANTITY, quantity );\n\t\tbundle.put( LEVEL, level );\n\t\tbundle.put( LEVEL_KNOWN, levelKnown );\n\t\tbundle.put( CURSED, cursed );\n\t\tbundle.put( CURSED_KNOWN, cursedKnown );\n\t\tif (Dungeon.quickslot.contains(this)) {\n\t\t\tbundle.put( QUICKSLOT, Dungeon.quickslot.getSlot(this) );\n\t\t}\n\t\tbundle.put( KEPT_LOST, keptThoughLostInvent );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tquantity\t= bundle.getInt( QUANTITY );\n\t\tlevelKnown\t= bundle.getBoolean( LEVEL_KNOWN );\n\t\tcursedKnown\t= bundle.getBoolean( CURSED_KNOWN );\n\t\t\n\t\tint level = bundle.getInt( LEVEL );\n\t\tif (level > 0) {\n\t\t\tupgrade( level );\n\t\t} else if (level < 0) {\n\t\t\tdegrade( -level );\n\t\t}\n\t\t\n\t\tcursed\t= bundle.getBoolean( CURSED );\n\n\t\t//only want to populate slot on first load.\n\t\tif (Dungeon.hero == null) {\n\t\t\tif (bundle.contains(QUICKSLOT)) {\n\t\t\t\tDungeon.quickslot.setSlot(bundle.getInt(QUICKSLOT), this);\n\t\t\t}\n\t\t}\n\n\t\tkeptThoughLostInvent = bundle.getBoolean( KEPT_LOST );\n\t}\n\n\tpublic int targetingPos( Hero user, int dst ){\n\t\treturn throwPos( user, dst );\n\t}\n\n\tpublic int throwPos( Hero user, int dst){\n\t\treturn new Ballistica( user.pos, dst, Ballistica.PROJECTILE ).collisionPos;\n\t}\n\n\tpublic void throwSound(){\n\t\tSample.INSTANCE.play(Assets.Sounds.MISS, 0.6f, 0.6f, 1.5f);\n\t}\n\t\n\tpublic void cast( final Hero user, final int dst ) {\n\t\t\n\t\tfinal int cell = throwPos( user, dst );\n\t\tuser.sprite.zap( cell );\n\t\tuser.busy();\n\n\t\tthrowSound();\n\n\t\tChar enemy = Actor.findChar( cell );\n\t\tQuickSlotButton.target(enemy);\n\t\t\n\t\tfinal float delay = castDelay(user, dst);\n\n\t\tif (enemy != null) {\n\t\t\t((MissileSprite) user.sprite.parent.recycle(MissileSprite.class)).\n\t\t\t\t\treset(user.sprite,\n\t\t\t\t\t\t\tenemy.sprite,\n\t\t\t\t\t\t\tthis,\n\t\t\t\t\t\t\tnew Callback() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\t\tcurUser = user;\n\t\t\t\t\t\t\tItem i = Item.this.detach(user.belongings.backpack);\n\t\t\t\t\t\t\tif (i != null) i.onThrow(cell);\n\t\t\t\t\t\t\tif (curUser.hasTalent(Talent.IMPROVISED_PROJECTILES)\n\t\t\t\t\t\t\t\t\t&& !(Item.this instanceof MissileWeapon)\n\t\t\t\t\t\t\t\t\t&& curUser.buff(Talent.ImprovisedProjectileCooldown.class) == null){\n\t\t\t\t\t\t\t\tif (enemy != null && enemy.alignment != curUser.alignment){\n\t\t\t\t\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT);\n\t\t\t\t\t\t\t\t\tBuff.affect(enemy, Blindness.class, 1f + curUser.pointsInTalent(Talent.IMPROVISED_PROJECTILES));\n\t\t\t\t\t\t\t\t\tBuff.affect(curUser, Talent.ImprovisedProjectileCooldown.class, 50f);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (user.buff(Talent.LethalMomentumTracker.class) != null){\n\t\t\t\t\t\t\t\tuser.buff(Talent.LethalMomentumTracker.class).detach();\n\t\t\t\t\t\t\t\tuser.next();\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tuser.spendAndNext(delay);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t} else {\n\t\t\t((MissileSprite) user.sprite.parent.recycle(MissileSprite.class)).\n\t\t\t\t\treset(user.sprite,\n\t\t\t\t\t\t\tcell,\n\t\t\t\t\t\t\tthis,\n\t\t\t\t\t\t\tnew Callback() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\t\tcurUser = user;\n\t\t\t\t\t\t\tItem i = Item.this.detach(user.belongings.backpack);\n\t\t\t\t\t\t\tif (i != null) i.onThrow(cell);\n\t\t\t\t\t\t\tuser.spendAndNext(delay);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t}\n\t}\n\t\n\tpublic float castDelay( Char user, int dst ){\n\t\treturn TIME_TO_THROW;\n\t}\n\t\n\tprotected static Hero curUser = null;\n\tprotected static Item curItem = null;\n\tprotected static CellSelector.Listener thrower = new CellSelector.Listener() {\n\t\t@Override\n\t\tpublic void onSelect( Integer target ) {\n\t\t\tif (target != null) {\n\t\t\t\tcurItem.cast( curUser, target );\n\t\t\t}\n\t\t}\n\t\t@Override\n\t\tpublic String prompt() {\n\t\t\treturn Messages.get(Item.class, \"prompt\");\n\t\t}\n\t};\n}" }, { "identifier": "KindOfWeapon", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/KindOfWeapon.java", "snippet": "abstract public class KindOfWeapon extends EquipableItem {\n\t\n\tprotected static final float TIME_TO_EQUIP = 1f;\n\n\tprotected String hitSound = Assets.Sounds.HIT;\n\tprotected float hitSoundPitch = 1f;\n\t\n\t@Override\n\tpublic void execute(Hero hero, String action) {\n\t\tif (hero.subClass == HeroSubClass.CHAMPION && action.equals(AC_EQUIP)){\n\t\t\tusesTargeting = false;\n\t\t\tString primaryName = Messages.titleCase(hero.belongings.weapon != null ? hero.belongings.weapon.trueName() : Messages.get(KindOfWeapon.class, \"empty\"));\n\t\t\tString secondaryName = Messages.titleCase(hero.belongings.secondWep != null ? hero.belongings.secondWep.trueName() : Messages.get(KindOfWeapon.class, \"empty\"));\n\t\t\tif (primaryName.length() > 18) primaryName = primaryName.substring(0, 15) + \"...\";\n\t\t\tif (secondaryName.length() > 18) secondaryName = secondaryName.substring(0, 15) + \"...\";\n\t\t\tGameScene.show(new WndOptions(\n\t\t\t\t\tnew ItemSprite(this),\n\t\t\t\t\tMessages.titleCase(name()),\n\t\t\t\t\tMessages.get(KindOfWeapon.class, \"which_equip_msg\"),\n\t\t\t\t\tMessages.get(KindOfWeapon.class, \"which_equip_primary\", primaryName),\n\t\t\t\t\tMessages.get(KindOfWeapon.class, \"which_equip_secondary\", secondaryName)\n\t\t\t){\n\t\t\t\t@Override\n\t\t\t\tprotected void onSelect(int index) {\n\t\t\t\t\tsuper.onSelect(index);\n\t\t\t\t\tif (index == 0 || index == 1){\n\t\t\t\t\t\t//In addition to equipping itself, item reassigns itself to the quickslot\n\t\t\t\t\t\t//This is a special case as the item is being removed from inventory, but is staying with the hero.\n\t\t\t\t\t\tint slot = Dungeon.quickslot.getSlot( KindOfWeapon.this );\n\t\t\t\t\t\tslotOfUnequipped = -1;\n\t\t\t\t\t\tif (index == 0) {\n\t\t\t\t\t\t\tdoEquip(hero);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tequipSecondary(hero);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (slot != -1) {\n\t\t\t\t\t\t\tDungeon.quickslot.setSlot( slot, KindOfWeapon.this );\n\t\t\t\t\t\t\tupdateQuickslot();\n\t\t\t\t\t\t//if this item wasn't quickslotted, but the item it is replacing as equipped was\n\t\t\t\t\t\t//then also have the item occupy the unequipped item's quickslot\n\t\t\t\t\t\t} else if (slotOfUnequipped != -1 && defaultAction() != null) {\n\t\t\t\t\t\t\tDungeon.quickslot.setSlot( slotOfUnequipped, KindOfWeapon.this );\n\t\t\t\t\t\t\tupdateQuickslot();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\tsuper.execute(hero, action);\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean isEquipped( Hero hero ) {\n\t\treturn hero.belongings.weapon() == this || hero.belongings.secondWep() == this;\n\t}\n\t\n\t@Override\n\tpublic boolean doEquip( Hero hero ) {\n\t\tboolean wasInInv = hero.belongings.contains(this);\n\t\tdetachAll( hero.belongings.backpack );\n\t\t\n\t\tif (hero.belongings.weapon == null || hero.belongings.weapon.doUnequip( hero, true )) {\n\t\t\t\n\t\t\thero.belongings.weapon = this;\n\t\t\tactivate( hero );\n\t\t\tTalent.onItemEquipped(hero, this);\n\t\t\tBadges.validateDuelistUnlock();\n\t\t\tActionIndicator.refresh();\n\t\t\tupdateQuickslot();\n\n\t\t\tcursedKnown = true;\n\t\t\tif (cursed) {\n\t\t\t\tequipCursed( hero );\n\t\t\t\tGLog.n( Messages.get(KindOfWeapon.class, \"equip_cursed\") );\n\t\t\t}\n\n\t\t\tif (wasInInv && hero.hasTalent(Talent.SWIFT_EQUIP)) {\n\t\t\t\tif (hero.buff(Talent.SwiftEquipCooldown.class) == null){\n\t\t\t\t\thero.spendAndNext(-hero.cooldown());\n\t\t\t\t\tBuff.affect(hero, Talent.SwiftEquipCooldown.class, 19f)\n\t\t\t\t\t\t\t.secondUse = hero.pointsInTalent(Talent.SWIFT_EQUIP) == 2;\n\t\t\t\t\tGLog.i(Messages.get(this, \"swift_equip\"));\n\t\t\t\t} else if (hero.buff(Talent.SwiftEquipCooldown.class).hasSecondUse()) {\n\t\t\t\t\thero.spendAndNext(-hero.cooldown());\n\t\t\t\t\thero.buff(Talent.SwiftEquipCooldown.class).secondUse = false;\n\t\t\t\t\tGLog.i(Messages.get(this, \"swift_equip\"));\n\t\t\t\t} else {\n\t\t\t\t\thero.spendAndNext(TIME_TO_EQUIP);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thero.spendAndNext(TIME_TO_EQUIP);\n\t\t\t}\n\t\t\treturn true;\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tcollect( hero.belongings.backpack );\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic boolean equipSecondary( Hero hero ){\n\t\tboolean wasInInv = hero.belongings.contains(this);\n\t\tdetachAll( hero.belongings.backpack );\n\n\t\tif (hero.belongings.secondWep == null || hero.belongings.secondWep.doUnequip( hero, true )) {\n\n\t\t\thero.belongings.secondWep = this;\n\t\t\tactivate( hero );\n\t\t\tTalent.onItemEquipped(hero, this);\n\t\t\tBadges.validateDuelistUnlock();\n\t\t\tActionIndicator.refresh();\n\t\t\tupdateQuickslot();\n\n\t\t\tcursedKnown = true;\n\t\t\tif (cursed) {\n\t\t\t\tequipCursed( hero );\n\t\t\t\tGLog.n( Messages.get(KindOfWeapon.class, \"equip_cursed\") );\n\t\t\t}\n\n\t\t\tif (wasInInv && hero.hasTalent(Talent.SWIFT_EQUIP)) {\n\t\t\t\tif (hero.buff(Talent.SwiftEquipCooldown.class) == null){\n\t\t\t\t\thero.spendAndNext(-hero.cooldown());\n\t\t\t\t\tBuff.affect(hero, Talent.SwiftEquipCooldown.class, 19f)\n\t\t\t\t\t\t\t.secondUse = hero.pointsInTalent(Talent.SWIFT_EQUIP) == 2;\n\t\t\t\t\tGLog.i(Messages.get(this, \"swift_equip\"));\n\t\t\t\t} else if (hero.buff(Talent.SwiftEquipCooldown.class).hasSecondUse()) {\n\t\t\t\t\thero.spendAndNext(-hero.cooldown());\n\t\t\t\t\thero.buff(Talent.SwiftEquipCooldown.class).secondUse = false;\n\t\t\t\t\tGLog.i(Messages.get(this, \"swift_equip\"));\n\t\t\t\t} else {\n\t\t\t\t\thero.spendAndNext(TIME_TO_EQUIP);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thero.spendAndNext(TIME_TO_EQUIP);\n\t\t\t}\n\t\t\treturn true;\n\n\t\t} else {\n\n\t\t\tcollect( hero.belongings.backpack );\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean doUnequip( Hero hero, boolean collect, boolean single ) {\n\t\tboolean second = hero.belongings.secondWep == this;\n\n\t\tif (second){\n\t\t\t//do this first so that the item can go to a full inventory\n\t\t\thero.belongings.secondWep = null;\n\t\t}\n\n\t\tif (super.doUnequip( hero, collect, single )) {\n\n\t\t\tif (!second){\n\t\t\t\thero.belongings.weapon = null;\n\t\t\t}\n\t\t\treturn true;\n\n\t\t} else {\n\n\t\t\tif (second){\n\t\t\t\thero.belongings.secondWep = this;\n\t\t\t}\n\t\t\treturn false;\n\n\t\t}\n\t}\n\n\tpublic int min(){\n\t\treturn min(buffedLvl());\n\t}\n\n\tpublic int max(){\n\t\treturn max(buffedLvl());\n\t}\n\n\tabstract public int min(int lvl);\n\tabstract public int max(int lvl);\n\n\tpublic int damageRoll( Char owner ) {\n\t\treturn Random.NormalIntRange( min(), max() );\n\t}\n\t\n\tpublic float accuracyFactor( Char owner, Char target ) {\n\t\treturn 1f;\n\t}\n\t\n\tpublic float delayFactor( Char owner ) {\n\t\treturn 1f;\n\t}\n\n\tpublic int reachFactor( Char owner ){\n\t\treturn 1;\n\t}\n\t\n\tpublic boolean canReach( Char owner, int target){\n\t\tint reach = reachFactor(owner);\n\t\tBookOfDisintegration.ReachBuff buff = hero.buff(BookOfDisintegration.ReachBuff.class);\n\t\tif (buff != null) {\n\t\t\treach += 1+buff.getUpgrade();\n\t\t}\n\t\tif (Dungeon.level.distance( owner.pos, target ) > reach){\n\t\t\treturn false;\n\t\t} else {\n\t\t\tboolean[] passable = BArray.not(Dungeon.level.solid, null);\n\t\t\tfor (Char ch : Actor.chars()) {\n\t\t\t\tif (ch != owner) passable[ch.pos] = false;\n\t\t\t}\n\t\t\t\n\t\t\tPathFinder.buildDistanceMap(target, passable, reach);\n\t\t\t\n\t\t\treturn PathFinder.distance[owner.pos] <= reach;\n\t\t}\n\t}\n\n\tpublic int defenseFactor( Char owner ) {\n\t\treturn 0;\n\t}\n\t\n\tpublic int proc( Char attacker, Char defender, int damage ) {\n\t\treturn damage;\n\t}\n\n\tpublic void hitSound( float pitch ){\n\t\tSample.INSTANCE.play(hitSound, 1, pitch * hitSoundPitch);\n\t}\n\t\n}" }, { "identifier": "Armor", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/armor/Armor.java", "snippet": "public class Armor extends EquipableItem {\n\n\tprotected static final String AC_DETACH = \"DETACH\";\n\tprotected static final String AC_SCRAP \t\t = \"SCRAP\";\n\t\n\tpublic enum Augment {\n\t\tEVASION (2f , -1f),\n\t\tDEFENSE (-2f, 1f),\n\t\tNONE\t(0f , 0f);\n\t\t\n\t\tprivate float evasionFactor;\n\t\tprivate float defenceFactor;\n\t\t\n\t\tAugment(float eva, float df){\n\t\t\tevasionFactor = eva;\n\t\t\tdefenceFactor = df;\n\t\t}\n\t\t\n\t\tpublic int evasionFactor(int level){\n\t\t\treturn Math.round((2 + level) * evasionFactor);\n\t\t}\n\t\t\n\t\tpublic int defenseFactor(int level){\n\t\t\treturn Math.round((2 + level) * defenceFactor);\n\t\t}\n\t}\n\t\n\tpublic Augment augment = Augment.NONE;\n\t\n\tpublic Glyph glyph;\n\tpublic boolean glyphHardened = false;\n\tpublic boolean curseInfusionBonus = false;\n\tpublic boolean masteryPotionBonus = false;\n\t\n\tprotected BrokenSeal seal;\n\t\n\tpublic int tier;\n\t\n\tprivate static final int USES_TO_ID = 10;\n\tprivate float usesLeftToID = USES_TO_ID;\n\tprivate float availableUsesToID = USES_TO_ID/2f;\n\t\n\tpublic Armor( int tier ) {\n\t\tthis.tier = tier;\n\t}\n\t\n\tprivate static final String USES_LEFT_TO_ID = \"uses_left_to_id\";\n\tprivate static final String AVAILABLE_USES = \"available_uses\";\n\tprivate static final String GLYPH\t\t\t= \"glyph\";\n\tprivate static final String GLYPH_HARDENED\t= \"glyph_hardened\";\n\tprivate static final String CURSE_INFUSION_BONUS = \"curse_infusion_bonus\";\n\tprivate static final String MASTERY_POTION_BONUS = \"mastery_potion_bonus\";\n\tprivate static final String SEAL = \"seal\";\n\tprivate static final String AUGMENT\t\t\t= \"augment\";\n\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tsuper.storeInBundle( bundle );\n\t\tbundle.put( USES_LEFT_TO_ID, usesLeftToID );\n\t\tbundle.put( AVAILABLE_USES, availableUsesToID );\n\t\tbundle.put( GLYPH, glyph );\n\t\tbundle.put( GLYPH_HARDENED, glyphHardened );\n\t\tbundle.put( CURSE_INFUSION_BONUS, curseInfusionBonus );\n\t\tbundle.put( MASTERY_POTION_BONUS, masteryPotionBonus );\n\t\tbundle.put( SEAL, seal);\n\t\tbundle.put( AUGMENT, augment);\n\t}\n\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tsuper.restoreFromBundle(bundle);\n\t\tusesLeftToID = bundle.getInt( USES_LEFT_TO_ID );\n\t\tavailableUsesToID = bundle.getInt( AVAILABLE_USES );\n\t\tinscribe((Glyph) bundle.get(GLYPH));\n\t\tglyphHardened = bundle.getBoolean(GLYPH_HARDENED);\n\t\tcurseInfusionBonus = bundle.getBoolean( CURSE_INFUSION_BONUS );\n\t\tmasteryPotionBonus = bundle.getBoolean( MASTERY_POTION_BONUS );\n\t\tseal = (BrokenSeal)bundle.get(SEAL);\n\t\t\n\t\taugment = bundle.getEnum(AUGMENT, Augment.class);\n\t}\n\n\t@Override\n\tpublic void reset() {\n\t\tsuper.reset();\n\t\tusesLeftToID = USES_TO_ID;\n\t\tavailableUsesToID = USES_TO_ID/2f;\n\t\t//armor can be kept in bones between runs, the seal cannot.\n\t\tseal = null;\n\t}\n\n\t@Override\n\tpublic ArrayList<String> actions(Hero hero) {\n\t\tArrayList<String> actions = super.actions(hero);\n\t\tif (seal != null) actions.add(AC_DETACH);\n\t\tif (!isEquipped(hero) && isIdentified() && hero.heroClass == HeroClass.GUNNER) {\n\t\t\tactions.add(AC_SCRAP);\n\t\t}\n\t\treturn actions;\n\t}\n\n\t@Override\n\tpublic void execute(Hero hero, String action) {\n\n\t\tsuper.execute(hero, action);\n\n\t\tif (action.equals(AC_DETACH) && seal != null){\n\t\t\tBrokenSeal.WarriorShield sealBuff = hero.buff(BrokenSeal.WarriorShield.class);\n\t\t\tif (sealBuff != null) sealBuff.setArmor(null);\n\n\t\t\tBrokenSeal detaching = seal;\n\t\t\tseal = null;\n\n\t\t\tif (detaching.level() > 0){\n\t\t\t\tdegrade();\n\t\t\t}\n\t\t\tif (detaching.canTransferGlyph()){\n\t\t\t\tinscribe(null);\n\t\t\t} else {\n\t\t\t\tdetaching.setGlyph(null);\n\t\t\t}\n\t\t\tGLog.i( Messages.get(Armor.class, \"detach_seal\") );\n\t\t\thero.sprite.operate(hero.pos);\n\t\t\tif (!detaching.collect()){\n\t\t\t\tDungeon.level.drop(detaching, hero.pos);\n\t\t\t}\n\t\t\tupdateQuickslot();\n\t\t}\n\t\tif (action.equals(AC_SCRAP)) {\n\t\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t\t@Override\n\t\t\t\tpublic void call() {\n\t\t\t\t\tGameScene.show(\n\t\t\t\t\t\t\tnew WndOptions( new ItemSprite(Armor.this),\n\t\t\t\t\t\t\t\t\tMessages.get(MeleeWeapon.class, \"scrap_title\"),\n\t\t\t\t\t\t\t\t\tMessages.get(MeleeWeapon.class, \"scrap_desc\", Math.round(5 * (Armor.this.tier+1) * (float)Math.pow(2, Math.min(3, Armor.this.level())))),\n\t\t\t\t\t\t\t\t\tMessages.get(MeleeWeapon.class, \"scrap_yes\"),\n\t\t\t\t\t\t\t\t\tMessages.get(MeleeWeapon.class, \"scrap_no\") ) {\n\n\t\t\t\t\t\t\t\tprivate float elapsed = 0f;\n\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tpublic synchronized void update() {\n\t\t\t\t\t\t\t\t\tsuper.update();\n\t\t\t\t\t\t\t\t\telapsed += Game.elapsed;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tpublic void hide() {\n\t\t\t\t\t\t\t\t\tif (elapsed > 0.2f){\n\t\t\t\t\t\t\t\t\t\tsuper.hide();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tprotected void onSelect( int index ) {\n\t\t\t\t\t\t\t\t\tif (index == 0 && elapsed > 0.2f) {\n\t\t\t\t\t\t\t\t\t\tLiquidMetal metal = new LiquidMetal();\n\t\t\t\t\t\t\t\t\t\tint metalQuantity = Math.round(5 * (Armor.this.tier+1) * (float)Math.pow(2, Math.min(3, Armor.this.level())));\n\t\t\t\t\t\t\t\t\t\tif (Armor.this.cursed) {\n\t\t\t\t\t\t\t\t\t\t\tmetalQuantity /= 2;\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tmetal.quantity(metalQuantity);\n\t\t\t\t\t\t\t\t\t\tif (!metal.doPickUp(hero)) {\n\t\t\t\t\t\t\t\t\t\t\tDungeon.level.drop( metal, hero.pos ).sprite.drop();\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tEnergyCrystal crystal = new EnergyCrystal();\n\t\t\t\t\t\t\t\t\t\tcrystal.quantity(Random.IntRange(1, 2));\n\t\t\t\t\t\t\t\t\t\tcrystal.doPickUp(hero);\n\n\t\t\t\t\t\t\t\t\t\tArmor.this.detach(hero.belongings.backpack);\n\n\t\t\t\t\t\t\t\t\t\thero.sprite.operate(hero.pos);\n\t\t\t\t\t\t\t\t\t\tGLog.p(Messages.get(MeleeWeapon.class, \"scrap\", metalQuantity));\n\t\t\t\t\t\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.UNLOCK);\n\n\t\t\t\t\t\t\t\t\t\tupdateQuickslot();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean doEquip( Hero hero ) {\n\t\t\n\t\tdetach(hero.belongings.backpack);\n\n\t\tif (hero.belongings.armor == null || hero.belongings.armor.doUnequip( hero, true, false )) {\n\t\t\t\n\t\t\thero.belongings.armor = this;\n\t\t\t\n\t\t\tcursedKnown = true;\n\t\t\tif (cursed) {\n\t\t\t\tequipCursed( hero );\n\t\t\t\tGLog.n( Messages.get(Armor.class, \"equip_cursed\") );\n\t\t\t}\n\t\t\t\n\t\t\t((HeroSprite)hero.sprite).updateArmor();\n\t\t\tactivate(hero);\n\t\t\tTalent.onItemEquipped(hero, this);\n\t\t\thero.spendAndNext( time2equip( hero ) );\n\t\t\treturn true;\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tcollect( hero.belongings.backpack );\n\t\t\treturn false;\n\t\t\t\n\t\t}\n\t}\n\n\t@Override\n\tpublic void activate(Char ch) {\n\t\tif (seal != null) Buff.affect(ch, BrokenSeal.WarriorShield.class).setArmor(this);\n\t}\n\n\tpublic void affixSeal(BrokenSeal seal){\n\t\tthis.seal = seal;\n\t\tif (seal.level() > 0){\n\t\t\t//doesn't trigger upgrading logic such as affecting curses/glyphs\n\t\t\tint newLevel = trueLevel()+1;\n\t\t\tlevel(newLevel);\n\t\t\tBadges.validateItemLevelAquired(this);\n\t\t}\n\t\tif (seal.getGlyph() != null){\n\t\t\tinscribe(seal.getGlyph());\n\t\t}\n\t\tif (isEquipped(Dungeon.hero)){\n\t\t\tBuff.affect(Dungeon.hero, BrokenSeal.WarriorShield.class).setArmor(this);\n\t\t}\n\t}\n\n\tpublic BrokenSeal checkSeal(){\n\t\treturn seal;\n\t}\n\n\t@Override\n\tprotected float time2equip( Hero hero ) {\n\t\treturn 2 / hero.speed();\n\t}\n\n\t@Override\n\tpublic boolean doUnequip( Hero hero, boolean collect, boolean single ) {\n\t\tif (super.doUnequip( hero, collect, single )) {\n\n\t\t\thero.belongings.armor = null;\n\t\t\t((HeroSprite)hero.sprite).updateArmor();\n\n\t\t\tBrokenSeal.WarriorShield sealBuff = hero.buff(BrokenSeal.WarriorShield.class);\n\t\t\tif (sealBuff != null) sealBuff.setArmor(null);\n\n\t\t\treturn true;\n\n\t\t} else {\n\n\t\t\treturn false;\n\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic boolean isEquipped( Hero hero ) {\n\t\treturn hero.belongings.armor() == this;\n\t}\n\n\tpublic final int DRMax(){\n\t\treturn DRMax(buffedLvl());\n\t}\n\n\tpublic int DRMax(int lvl){\n\t\tif (Dungeon.isChallenged(Challenges.NO_ARMOR)){\n\t\t\treturn 1 + tier + lvl + augment.defenseFactor(lvl);\n\t\t}\n\n\t\tint max = tier * (2 + lvl) + augment.defenseFactor(lvl);\n\t\tif (lvl > max){\n\t\t\treturn ((lvl - max)+1)/2;\n\t\t} else {\n\t\t\treturn max;\n\t\t}\n\t}\n\n\tpublic final int DRMin(){\n\t\treturn DRMin(buffedLvl());\n\t}\n\n\tpublic int DRMin(int lvl){\n\t\tif (Dungeon.isChallenged(Challenges.NO_ARMOR)){\n\t\t\treturn 0;\n\t\t}\n\n\t\tint max = DRMax(lvl);\n\t\tif (lvl >= max){\n\t\t\treturn (lvl - max);\n\t\t} else {\n\t\t\treturn lvl;\n\t\t}\n\t}\n\t\n\tpublic float evasionFactor( Char owner, float evasion ){\n\t\t\n\t\tif (hasGlyph(Stone.class, owner) && !((Stone)glyph).testingEvasion()){\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (owner instanceof Hero){\n\t\t\tint aEnc = STRReq() - ((Hero) owner).STR();\n\t\t\tif (aEnc > 0) evasion /= Math.pow(1.5, aEnc);\n\t\t\t\n\t\t\tMomentum momentum = owner.buff(Momentum.class);\n\t\t\tif (momentum != null){\n\t\t\t\tevasion += momentum.evasionBonus(((Hero) owner).lvl, Math.max(0, -aEnc));\n\t\t\t}\n\n\t\t\tMeleeWeapon.Charger charger = owner.buff(MeleeWeapon.Charger.class);\n\t\t\tif (charger != null && hero.hasTalent(Talent.UNENCUMBERED_MOVEMENT) && ((Hero) owner).belongings.weapon instanceof MeleeWeapon) {\n\t\t\t\tint wEnc = ((MeleeWeapon)((Hero) owner).belongings.weapon).STRReq() - ((Hero) owner).STR();\n\t\t\t\tevasion += 0.5f*Math.max(0, -aEnc);\n\t\t\t\tevasion += 0.5f*Math.max(0, -wEnc);\n\t\t\t}\n\t\t}\n\n\t\t\n\t\treturn evasion + augment.evasionFactor(buffedLvl());\n\t}\n\t\n\tpublic float speedFactor( Char owner, float speed ){\n\t\t\n\t\tif (owner instanceof Hero) {\n\t\t\tint aEnc = STRReq() - ((Hero) owner).STR();\n\t\t\tif (aEnc > 0) speed /= Math.pow(1.2, aEnc);\n\n\t\t\tif (hero.hasTalent(Talent.LIGHT_MOVEMENT) && aEnc < 0) {\n\t\t\t\tfloat exceedSTR = -aEnc/(float)(4-hero.pointsInTalent(Talent.LIGHT_MOVEMENT));\n\t\t\t\tspeed *= Math.pow(1.05, Math.floor(exceedSTR));\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (hasGlyph(Swiftness.class, owner)) {\n\t\t\tboolean enemyNear = false;\n\t\t\tPathFinder.buildDistanceMap(owner.pos, Dungeon.level.passable, 2);\n\t\t\tfor (Char ch : Actor.chars()){\n\t\t\t\tif ( PathFinder.distance[ch.pos] != Integer.MAX_VALUE && owner.alignment != ch.alignment){\n\t\t\t\t\tenemyNear = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!enemyNear) speed *= (1.2f + 0.04f * buffedLvl()) * glyph.procChanceMultiplier(owner);\n\t\t} else if (hasGlyph(Flow.class, owner) && Dungeon.level.water[owner.pos]){\n\t\t\tspeed *= (2f + 0.5f*buffedLvl()) * glyph.procChanceMultiplier(owner);\n\t\t}\n\t\t\n\t\tif (hasGlyph(Bulk.class, owner) &&\n\t\t\t\t(Dungeon.level.map[owner.pos] == Terrain.DOOR\n\t\t\t\t\t\t|| Dungeon.level.map[owner.pos] == Terrain.OPEN_DOOR )) {\n\t\t\tspeed /= 3f * RingOfArcana.enchantPowerMultiplier(owner);\n\t\t}\n\t\t\n\t\treturn speed;\n\t\t\n\t}\n\t\n\tpublic float stealthFactor( Char owner, float stealth ){\n\t\t\n\t\tif (hasGlyph(Obfuscation.class, owner)){\n\t\t\tstealth += (1 + buffedLvl()/3f) * glyph.procChanceMultiplier(owner);\n\t\t}\n\n\t\tif (owner == Dungeon.hero) {\n\t\t\tstealth += hero.pointsInTalent(Talent.STEALTH);\n\n\t\t\tKindOfWeapon wep = ((Hero) owner).belongings.weapon;\n\t\t\tif (wep instanceof Gun) {\n\t\t\t\tswitch (((Gun) wep).attachMod) {\n\t\t\t\t\tcase NORMAL_ATTACH: default:\n\t\t\t\t\t\t//no effect\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LASER_ATTACH:\n\t\t\t\t\t\tstealth -= 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase FLASH_ATTACH:\n\t\t\t\t\t\tstealth -= 2;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn stealth;\n\t}\n\t\n\t@Override\n\tpublic int level() {\n\t\tint level = super.level();\n\t\t//TODO warrior's seal upgrade should probably be considered here too\n\t\t// instead of being part of true level\n\t\tif (curseInfusionBonus) level += 1 + level/6;\n\t\treturn level;\n\t}\n\t\n\t@Override\n\tpublic Item upgrade() {\n\t\treturn upgrade( false );\n\t}\n\t\n\tpublic Item upgrade( boolean inscribe ) {\n\n\t\tif (inscribe){\n\t\t\tif (glyph == null){\n\t\t\t\tinscribe( Glyph.random() );\n\t\t\t}\n\t\t} else if (glyph != null) {\n\t\t\t//chance to lose harden buff is 10/20/40/80/100% when upgrading from +6/7/8/9/10\n\t\t\tif (glyphHardened) {\n\t\t\t\tif (level() >= 6 && Random.Float(10) < Math.pow(2, level()-6)){\n\t\t\t\t\tglyphHardened = false;\n\t\t\t\t}\n\n\t\t\t//chance to remove curse is a static 33%\n\t\t\t} else if (hasCurseGlyph()){\n\t\t\t\tif (Random.Int(3) == 0) inscribe(null);\n\n\t\t\t//otherwise chance to lose glyph is 10/20/40/80/100% when upgrading from +4/5/6/7/8\n\t\t\t} else {\n\n\t\t\t\t//the chance from +4/5, and then +6 can be set to 0% with metamorphed runic transference\n\t\t\t\tint lossChanceStart = 4;\n\t\t\t\tif (Dungeon.hero != null && Dungeon.hero.heroClass != HeroClass.WARRIOR && Dungeon.hero.hasTalent(Talent.RUNIC_TRANSFERENCE)){\n\t\t\t\t\tlossChanceStart += 1+Dungeon.hero.pointsInTalent(Talent.RUNIC_TRANSFERENCE);\n\t\t\t\t}\n\n\t\t\t\tif (level() >= lossChanceStart && Random.Float(10) < Math.pow(2, level()-4)) {\n\t\t\t\t\tinscribe(null);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tcursed = false;\n\n\t\tif (seal != null && seal.level() == 0)\n\t\t\tseal.upgrade();\n\n\t\treturn super.upgrade();\n\t}\n\t\n\tpublic int proc( Char attacker, Char defender, int damage ) {\n\t\t\n\t\tif (glyph != null && defender.buff(MagicImmune.class) == null) {\n\t\t\tdamage = glyph.proc( this, attacker, defender, damage );\n\t\t}\n\t\t\n\t\tif (!levelKnown && defender == Dungeon.hero) {\n\t\t\tfloat uses = Math.min( availableUsesToID, Talent.itemIDSpeedFactor(Dungeon.hero, this) );\n\t\t\tavailableUsesToID -= uses;\n\t\t\tusesLeftToID -= uses;\n\t\t\tif (usesLeftToID <= 0) {\n\t\t\t\tidentify();\n\t\t\t\tGLog.p( Messages.get(Armor.class, \"identify\") );\n\t\t\t\tBadges.validateItemLevelAquired( this );\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn damage;\n\t}\n\t\n\t@Override\n\tpublic void onHeroGainExp(float levelPercent, Hero hero) {\n\t\tlevelPercent *= Talent.itemIDSpeedFactor(hero, this);\n\t\tif (!levelKnown && isEquipped(hero) && availableUsesToID <= USES_TO_ID/2f) {\n\t\t\t//gains enough uses to ID over 0.5 levels\n\t\t\tavailableUsesToID = Math.min(USES_TO_ID/2f, availableUsesToID + levelPercent * USES_TO_ID);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic String name() {\n\t\treturn glyph != null && (cursedKnown || !glyph.curse()) ? glyph.name( super.name() ) : super.name();\n\t}\n\t\n\t@Override\n\tpublic String info() {\n\t\tString info = desc();\n\t\t\n\t\tif (levelKnown) {\n\n\t\t\tinfo += \"\\n\\n\" + Messages.get(Armor.class, \"curr_absorb\", tier, DRMin(), DRMax(), STRReq());\n\t\t\t\n\t\t\tif (STRReq() > Dungeon.hero.STR()) {\n\t\t\t\tinfo += \" \" + Messages.get(Armor.class, \"too_heavy\");\n\t\t\t}\n\t\t} else {\n\t\t\tinfo += \"\\n\\n\" + Messages.get(Armor.class, \"avg_absorb\", tier, DRMin(0), DRMax(0), STRReq(0));\n\n\t\t\tif (STRReq(0) > Dungeon.hero.STR()) {\n\t\t\t\tinfo += \" \" + Messages.get(Armor.class, \"probably_too_heavy\");\n\t\t\t}\n\t\t}\n\n\t\tswitch (augment) {\n\t\t\tcase EVASION:\n\t\t\t\tinfo += \" \" + Messages.get(Armor.class, \"evasion\");\n\t\t\t\tbreak;\n\t\t\tcase DEFENSE:\n\t\t\t\tinfo += \" \" + Messages.get(Armor.class, \"defense\");\n\t\t\t\tbreak;\n\t\t\tcase NONE:\n\t\t}\n\t\t\n\t\tif (glyph != null && (cursedKnown || !glyph.curse())) {\n\t\t\tinfo += \"\\n\\n\" + Messages.capitalize(Messages.get(Armor.class, \"inscribed\", glyph.name()));\n\t\t\tif (glyphHardened) info += \" \" + Messages.get(Armor.class, \"glyph_hardened\");\n\t\t\tinfo += \" \" + glyph.desc();\n\t\t} else if (glyphHardened){\n\t\t\tinfo += \"\\n\\n\" + Messages.get(Armor.class, \"hardened_no_glyph\");\n\t\t}\n\t\t\n\t\tif (cursed && isEquipped( Dungeon.hero )) {\n\t\t\tinfo += \"\\n\\n\" + Messages.get(Armor.class, \"cursed_worn\");\n\t\t} else if (cursedKnown && cursed) {\n\t\t\tinfo += \"\\n\\n\" + Messages.get(Armor.class, \"cursed\");\n\t\t} else if (seal != null) {\n\t\t\tinfo += \"\\n\\n\" + Messages.get(Armor.class, \"seal_attached\", seal.maxShield(tier, level()));\n\t\t} else if (!isIdentified() && cursedKnown){\n\t\t\tif (glyph != null && glyph.curse()) {\n\t\t\t\tinfo += \"\\n\\n\" + Messages.get(Armor.class, \"weak_cursed\");\n\t\t\t} else {\n\t\t\t\tinfo += \"\\n\\n\" + Messages.get(Armor.class, \"not_cursed\");\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn info;\n\t}\n\n\t@Override\n\tpublic Emitter emitter() {\n\t\tif (seal == null) return super.emitter();\n\t\tEmitter emitter = new Emitter();\n\t\temitter.pos(ItemSpriteSheet.film.width(image)/2f + 2f, ItemSpriteSheet.film.height(image)/3f);\n\t\temitter.fillTarget = false;\n\t\temitter.pour(Speck.factory( Speck.RED_LIGHT ), 0.6f);\n\t\treturn emitter;\n\t}\n\n\t@Override\n\tpublic Item random() {\n\t\t//+0: 75% (3/4)\n\t\t//+1: 20% (4/20)\n\t\t//+2: 5% (1/20)\n\t\tint n = 0;\n\t\tif (Random.Int(4) == 0) {\n\t\t\tn++;\n\t\t\tif (Random.Int(5) == 0) {\n\t\t\t\tn++;\n\t\t\t}\n\t\t}\n\t\tlevel(n);\n\t\t\n\t\t//30% chance to be cursed\n\t\t//15% chance to be inscribed\n\t\tfloat effectRoll = Random.Float();\n\t\tif (effectRoll < 0.3f) {\n\t\t\tinscribe(Glyph.randomCurse());\n\t\t\tcursed = true;\n\t\t} else if (effectRoll >= 0.85f){\n\t\t\tinscribe();\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tpublic int STRReq(){\n\t\tint req = STRReq(level());\n\t\tif (masteryPotionBonus){\n\t\t\treq -= 2;\n\t\t}\n\t\treturn req;\n\t}\n\n\tpublic int STRReq(int lvl){\n\t\treturn STRReq(tier, lvl);\n\t}\n\n\tprotected static int STRReq(int tier, int lvl){\n\t\tlvl = Math.max(0, lvl);\n\n\t\t//strength req decreases at +1,+3,+6,+10,etc.\n\t\treturn (8 + Math.round(tier * 2)) - (int)(Math.sqrt(8 * lvl + 1) - 1)/2;\n\t}\n\t\n\t@Override\n\tpublic int value() {\n\t\tif (seal != null) return 0;\n\n\t\tint price = 20 * tier;\n\t\tif (hasGoodGlyph()) {\n\t\t\tprice *= 1.5;\n\t\t}\n\t\tif (cursedKnown && (cursed || hasCurseGlyph())) {\n\t\t\tprice /= 2;\n\t\t}\n\t\tif (levelKnown && level() > 0) {\n\t\t\tprice *= (level() + 1);\n\t\t}\n\t\tif (price < 1) {\n\t\t\tprice = 1;\n\t\t}\n\t\treturn price;\n\t}\n\n\tpublic Armor inscribe( Glyph glyph ) {\n\t\tif (glyph == null || !glyph.curse()) curseInfusionBonus = false;\n\t\tthis.glyph = glyph;\n\t\tupdateQuickslot();\n\t\t//the hero needs runic transference to actually transfer, but we still attach the glyph here\n\t\t// in case they take that talent in the future\n\t\tif (seal != null){\n\t\t\tseal.setGlyph(glyph);\n\t\t}\n\t\treturn this;\n\t}\n\n\tpublic Armor inscribe() {\n\n\t\tClass<? extends Glyph> oldGlyphClass = glyph != null ? glyph.getClass() : null;\n\t\tGlyph gl = Glyph.random( oldGlyphClass );\n\n\t\treturn inscribe( gl );\n\t}\n\n\tpublic boolean hasGlyph(Class<?extends Glyph> type, Char owner) {\n\t\treturn glyph != null && glyph.getClass() == type && owner.buff(MagicImmune.class) == null;\n\t}\n\n\t//these are not used to process specific glyph effects, so magic immune doesn't affect them\n\tpublic boolean hasGoodGlyph(){\n\t\treturn glyph != null && !glyph.curse();\n\t}\n\n\tpublic boolean hasCurseGlyph(){\n\t\treturn glyph != null && glyph.curse();\n\t}\n\t\n\t@Override\n\tpublic ItemSprite.Glowing glowing() {\n\t\treturn glyph != null && (cursedKnown || !glyph.curse()) ? glyph.glowing() : null;\n\t}\n\t\n\tpublic static abstract class Glyph implements Bundlable {\n\t\t\n\t\tpublic static final Class<?>[] common = new Class<?>[]{\n\t\t\t\tObfuscation.class, Swiftness.class, Viscosity.class, Potential.class };\n\n\t\tpublic static final Class<?>[] uncommon = new Class<?>[]{\n\t\t\t\tBrimstone.class, Stone.class, Entanglement.class,\n\t\t\t\tRepulsion.class, Camouflage.class, Flow.class };\n\n\t\tpublic static final Class<?>[] rare = new Class<?>[]{\n\t\t\t\tAffection.class, AntiMagic.class, Thorns.class };\n\n\t\tpublic static final float[] typeChances = new float[]{\n\t\t\t\t50, //12.5% each\n\t\t\t\t40, //6.67% each\n\t\t\t\t10 //3.33% each\n\t\t};\n\n\t\tprivate static final Class<?>[] curses = new Class<?>[]{\n\t\t\t\tAntiEntropy.class, Corrosion.class, Displacement.class, Metabolism.class,\n\t\t\t\tMultiplicity.class, Stench.class, Overgrowth.class, Bulk.class\n\t\t};\n\t\t\n\t\tpublic abstract int proc( Armor armor, Char attacker, Char defender, int damage );\n\n\t\tprotected float procChanceMultiplier( Char defender ){\n\t\t\treturn genericProcChanceMultiplier( defender );\n\t\t}\n\n\t\tpublic static float genericProcChanceMultiplier( Char defender ){\n\t\t\treturn RingOfArcana.enchantPowerMultiplier(defender);\n\t\t}\n\t\t\n\t\tpublic String name() {\n\t\t\tif (!curse())\n\t\t\t\treturn name( Messages.get(this, \"glyph\") );\n\t\t\telse\n\t\t\t\treturn name( Messages.get(Item.class, \"curse\"));\n\t\t}\n\t\t\n\t\tpublic String name( String armorName ) {\n\t\t\treturn Messages.get(this, \"name\", armorName);\n\t\t}\n\n\t\tpublic String desc() {\n\t\t\treturn Messages.get(this, \"desc\");\n\t\t}\n\n\t\tpublic boolean curse() {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\t}\n\n\t\t@Override\n\t\tpublic void storeInBundle( Bundle bundle ) {\n\t\t}\n\t\t\n\t\tpublic abstract ItemSprite.Glowing glowing();\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic static Glyph random( Class<? extends Glyph> ... toIgnore ) {\n\t\t\tswitch(Random.chances(typeChances)){\n\t\t\t\tcase 0: default:\n\t\t\t\t\treturn randomCommon( toIgnore );\n\t\t\t\tcase 1:\n\t\t\t\t\treturn randomUncommon( toIgnore );\n\t\t\t\tcase 2:\n\t\t\t\t\treturn randomRare( toIgnore );\n\t\t\t}\n\t\t}\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic static Glyph randomCommon( Class<? extends Glyph> ... toIgnore ){\n\t\t\tArrayList<Class<?>> glyphs = new ArrayList<>(Arrays.asList(common));\n\t\t\tglyphs.removeAll(Arrays.asList(toIgnore));\n\t\t\tif (glyphs.isEmpty()) {\n\t\t\t\treturn random();\n\t\t\t} else {\n\t\t\t\treturn (Glyph) Reflection.newInstance(Random.element(glyphs));\n\t\t\t}\n\t\t}\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic static Glyph randomUncommon( Class<? extends Glyph> ... toIgnore ){\n\t\t\tArrayList<Class<?>> glyphs = new ArrayList<>(Arrays.asList(uncommon));\n\t\t\tglyphs.removeAll(Arrays.asList(toIgnore));\n\t\t\tif (glyphs.isEmpty()) {\n\t\t\t\treturn random();\n\t\t\t} else {\n\t\t\t\treturn (Glyph) Reflection.newInstance(Random.element(glyphs));\n\t\t\t}\n\t\t}\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic static Glyph randomRare( Class<? extends Glyph> ... toIgnore ){\n\t\t\tArrayList<Class<?>> glyphs = new ArrayList<>(Arrays.asList(rare));\n\t\t\tglyphs.removeAll(Arrays.asList(toIgnore));\n\t\t\tif (glyphs.isEmpty()) {\n\t\t\t\treturn random();\n\t\t\t} else {\n\t\t\t\treturn (Glyph) Reflection.newInstance(Random.element(glyphs));\n\t\t\t}\n\t\t}\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic static Glyph randomCurse( Class<? extends Glyph> ... toIgnore ){\n\t\t\tArrayList<Class<?>> glyphs = new ArrayList<>(Arrays.asList(curses));\n\t\t\tglyphs.removeAll(Arrays.asList(toIgnore));\n\t\t\tif (glyphs.isEmpty()) {\n\t\t\t\treturn random();\n\t\t\t} else {\n\t\t\t\treturn (Glyph) Reflection.newInstance(Random.element(glyphs));\n\t\t\t}\n\t\t}\n\t\t\n\t}\n}" }, { "identifier": "Weapon", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/weapon/Weapon.java", "snippet": "abstract public class Weapon extends KindOfWeapon {\n\n\tpublic float ACC = 1f;\t// Accuracy modifier\n\tpublic float\tDLY\t= 1f;\t// Speed modifier\n\tpublic int RCH = 1; // Reach modifier (only applies to melee hits)\n\n\tpublic enum Augment {\n\t\tSPEED (0.7f, 2/3f),\n\t\tDAMAGE (1.5f, 5/3f),\n\t\tNONE\t(1.0f, 1f);\n\n\t\tprivate float damageFactor;\n\t\tprivate float delayFactor;\n\n\t\tAugment(float dmg, float dly){\n\t\t\tdamageFactor = dmg;\n\t\t\tdelayFactor = dly;\n\t\t}\n\n\t\tpublic int damageFactor(int dmg){\n\t\t\treturn Math.round(dmg * damageFactor);\n\t\t}\n\n\t\tpublic float delayFactor(float dly){\n\t\t\treturn dly * delayFactor;\n\t\t}\n\t}\n\t\n\tpublic Augment augment = Augment.NONE;\n\t\n\tprivate static final int USES_TO_ID = 20;\n\tprivate float usesLeftToID = USES_TO_ID;\n\tprivate float availableUsesToID = USES_TO_ID/2f;\n\t\n\tpublic Enchantment enchantment;\n\tpublic boolean enchantHardened = false;\n\tpublic boolean curseInfusionBonus = false;\n\tpublic boolean masteryPotionBonus = false;\n\t\n\t@Override\n\tpublic int proc( Char attacker, Char defender, int damage ) {\n\t\t\n\t\tif (enchantment != null && attacker.buff(MagicImmune.class) == null) {\n\t\t\tdamage = enchantment.proc( this, attacker, defender, damage );\n\t\t}\n\t\t\n\t\tif (!levelKnown && attacker == Dungeon.hero) {\n\t\t\tfloat uses = Math.min( availableUsesToID, Talent.itemIDSpeedFactor(Dungeon.hero, this) );\n\t\t\tavailableUsesToID -= uses;\n\t\t\tusesLeftToID -= uses;\n\t\t\tif (usesLeftToID <= 0) {\n\t\t\t\tidentify();\n\t\t\t\tGLog.p( Messages.get(Weapon.class, \"identify\") );\n\t\t\t\tBadges.validateItemLevelAquired( this );\n\t\t\t}\n\t\t}\n\n\t\treturn damage;\n\t}\n\t\n\tpublic void onHeroGainExp( float levelPercent, Hero hero ){\n\t\tlevelPercent *= Talent.itemIDSpeedFactor(hero, this);\n\t\tif (!levelKnown && isEquipped(hero) && availableUsesToID <= USES_TO_ID/2f) {\n\t\t\t//gains enough uses to ID over 0.5 levels\n\t\t\tavailableUsesToID = Math.min(USES_TO_ID/2f, availableUsesToID + levelPercent * USES_TO_ID);\n\t\t}\n\t}\n\t\n\tprivate static final String USES_LEFT_TO_ID = \"uses_left_to_id\";\n\tprivate static final String AVAILABLE_USES = \"available_uses\";\n\tprivate static final String ENCHANTMENT\t = \"enchantment\";\n\tprivate static final String ENCHANT_HARDENED = \"enchant_hardened\";\n\tprivate static final String CURSE_INFUSION_BONUS = \"curse_infusion_bonus\";\n\tprivate static final String MASTERY_POTION_BONUS = \"mastery_potion_bonus\";\n\tprivate static final String AUGMENT\t = \"augment\";\n\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tsuper.storeInBundle( bundle );\n\t\tbundle.put( USES_LEFT_TO_ID, usesLeftToID );\n\t\tbundle.put( AVAILABLE_USES, availableUsesToID );\n\t\tbundle.put( ENCHANTMENT, enchantment );\n\t\tbundle.put( ENCHANT_HARDENED, enchantHardened );\n\t\tbundle.put( CURSE_INFUSION_BONUS, curseInfusionBonus );\n\t\tbundle.put( MASTERY_POTION_BONUS, masteryPotionBonus );\n\t\tbundle.put( AUGMENT, augment );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tsuper.restoreFromBundle( bundle );\n\t\tusesLeftToID = bundle.getFloat( USES_LEFT_TO_ID );\n\t\tavailableUsesToID = bundle.getFloat( AVAILABLE_USES );\n\t\tenchantment = (Enchantment)bundle.get( ENCHANTMENT );\n\t\tenchantHardened = bundle.getBoolean( ENCHANT_HARDENED );\n\t\tcurseInfusionBonus = bundle.getBoolean( CURSE_INFUSION_BONUS );\n\t\tmasteryPotionBonus = bundle.getBoolean( MASTERY_POTION_BONUS );\n\n\t\taugment = bundle.getEnum(AUGMENT, Augment.class);\n\t}\n\t\n\t@Override\n\tpublic void reset() {\n\t\tsuper.reset();\n\t\tusesLeftToID = USES_TO_ID;\n\t\tavailableUsesToID = USES_TO_ID/2f;\n\t}\n\t\n\t@Override\n\tpublic float accuracyFactor(Char owner, Char target) {\n\t\t\n\t\tint encumbrance = 0;\n\t\t\n\t\tif( owner instanceof Hero ){\n\t\t\tencumbrance = STRReq() - ((Hero)owner).STR();\n\t\t}\n\n\t\tfloat ACC = this.ACC;\n\n\t\tif (owner.buff(Wayward.WaywardBuff.class) != null && enchantment instanceof Wayward){\n\t\t\tACC /= 5;\n\t\t}\n\n\t\treturn encumbrance > 0 ? (float)(ACC / Math.pow( 1.5, encumbrance )) : ACC;\n\t}\n\t\n\t@Override\n\tpublic float delayFactor( Char owner ) {\n\t\treturn baseDelay(owner) * (1f/speedMultiplier(owner));\n\t}\n\n\tprotected float baseDelay( Char owner ){\n\t\tfloat delay = augment.delayFactor(this.DLY);\n\t\tif (owner instanceof Hero) {\n\t\t\tint encumbrance = STRReq() - ((Hero)owner).STR();\n\t\t\tif (encumbrance > 0){\n\t\t\t\tdelay *= Math.pow( 1.2, encumbrance );\n\t\t\t}\n\t\t}\n\n\t\treturn delay;\n\t}\n\n\tprotected float speedMultiplier(Char owner ){\n\t\tfloat multi = RingOfFuror.attackSpeedMultiplier(owner);\n\n\t\tif (hero.hasTalent(Talent.LESS_RESIST)) {\n\t\t\tint aEnc = hero.belongings.armor.STRReq() - hero.STR();\n\t\t\tif (aEnc < 0) {\n\t\t\t\tmulti *= 1 + 0.05f * hero.pointsInTalent(Talent.LESS_RESIST) * (-aEnc);\n\t\t\t}\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.LIGHT_WEAPON) && hero.belongings.attackingWeapon() instanceof MeleeWeapon) {\n\t\t\tint aEnc = ((MeleeWeapon)hero.belongings.attackingWeapon()).STRReq() - hero.STR();\n\t\t\tif (aEnc < 0) {\n\t\t\t\tmulti *= 1 + 0.05f * hero.pointsInTalent(Talent.LIGHT_WEAPON) * (-aEnc);\n\t\t\t}\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.QUICK_FOLLOWUP) && hero.buff(Talent.QuickFollowupTracker.class) != null) {\n\t\t\tmulti *= 1+hero.pointsInTalent(Talent.QUICK_FOLLOWUP)/3f;\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.MONK && hero.buff(MonkEnergy.class) != null && hero.buff(MonkEnergy.class).harmonized(hero)) {\n\t\t\tmulti *= 1.5f;\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.ATK_SPEED_ENHANCE)) {\n\t\t\tmulti *= 1 + 0.05f * hero.pointsInTalent(Talent.ATK_SPEED_ENHANCE);\n\t\t}\n\n\t\tif (hero.belongings.weapon != null && hero.belongings.secondWep != null\n\t\t\t\t&& hero.pointsInTalent(Talent.TWIN_SWORD) > 2\n\t\t\t\t&& hero.belongings.weapon.getClass() == hero.belongings.secondWep.getClass()) {\n\t\t\tmulti *= 2;\n\t\t}\n\n\t\tif (owner.buff(Scimitar.SwordDance.class) != null){\n\t\t\tmulti += 0.6f;\n\t\t}\n\n\t\treturn multi;\n\t}\n\n\t@Override\n\tpublic int reachFactor(Char owner) {\n\t\tint reach = RCH;\n\t\tif (owner instanceof Hero && RingOfForce.fightingUnarmed((Hero) owner)){\n\t\t\treach = 1; //brawlers stance benefits from enchantments, but not innate reach\n\t\t\tif (!RingOfForce.unarmedGetsWeaponEnchantment((Hero) owner)){\n\t\t\t\treturn reach;\n\t\t\t}\n\t\t}\n\t\tif (hasEnchant(Projecting.class, owner)){\n\t\t\treturn reach + Math.round(enchantment.procChanceMultiplier(owner));\n\t\t} else {\n\t\t\treturn reach;\n\t\t}\n\t}\n\n\tpublic int STRReq(){\n\t\tint req = STRReq(level());\n\t\tif (masteryPotionBonus){\n\t\t\treq -= 2;\n\t\t}\n\t\treturn req;\n\t}\n\n\tpublic abstract int STRReq(int lvl);\n\n\tprotected static int STRReq(int tier, int lvl){\n\t\tlvl = Math.max(0, lvl);\n\n\t\t//strength req decreases at +1,+3,+6,+10,etc.\n\t\treturn (8 + tier * 2) - (int)(Math.sqrt(8 * lvl + 1) - 1)/2;\n\t}\n\n\t@Override\n\tpublic int level() {\n\t\tint level = super.level();\n\t\tif (curseInfusionBonus) level += 1 + level/6;\n\t\treturn level;\n\t}\n\n\t@Override\n\tpublic int buffedLvl() {\n\t\tint lvl;\n\t\tif (isEquipped(Dungeon.hero) || Dungeon.hero.belongings.contains(this)) {\n\t\t\tlvl = super.buffedLvl();\n\t\t} else {\n\t\t\tlvl = level();\n\t\t}\n\n\t\tUpgradeDust.WeaponEnhance weaponEmpower = hero.buff(UpgradeDust.WeaponEnhance.class);\n\t\tif (weaponEmpower != null && isEquipped(hero)) {\n\t\t\tlvl += weaponEmpower.getLvl();\n\t\t}\n\n\t\treturn lvl;\n\t}\n\t\n\t@Override\n\tpublic Item upgrade() {\n\t\treturn upgrade(false);\n\t}\n\t\n\tpublic Item upgrade(boolean enchant ) {\n\n\t\tif (enchant){\n\t\t\tif (enchantment == null){\n\t\t\t\tenchant(Enchantment.random());\n\t\t\t}\n\t\t} else if (enchantment != null) {\n\t\t\t//chance to lose harden buff is 10/20/40/80/100% when upgrading from +6/7/8/9/10\n\t\t\tif (enchantHardened){\n\t\t\t\tif (level() >= 6 && Random.Float(10) < Math.pow(2, level()-6)){\n\t\t\t\t\tenchantHardened = false;\n\t\t\t\t}\n\n\t\t\t//chance to remove curse is a static 33%\n\t\t\t} else if (hasCurseEnchant()) {\n\t\t\t\tif (Random.Int(3) == 0) enchant(null);\n\n\t\t\t//otherwise chance to lose enchant is 10/20/40/80/100% when upgrading from +4/5/6/7/8\n\t\t\t} else if (level() >= 4 && Random.Float(10) < Math.pow(2, level()-4)){\n\t\t\t\tenchant(null);\n\t\t\t}\n\t\t}\n\t\t\n\t\tcursed = false;\n\n\t\treturn super.upgrade();\n\t}\n\t\n\t@Override\n\tpublic String name() {\n\t\treturn enchantment != null && (cursedKnown || !enchantment.curse()) ? enchantment.name( super.name() ) : super.name();\n\t}\n\t\n\t@Override\n\tpublic Item random() {\n\t\t//+0: 75% (3/4)\n\t\t//+1: 20% (4/20)\n\t\t//+2: 5% (1/20)\n\t\tint n = 0;\n\t\tif (Random.Int(4) == 0) {\n\t\t\tn++;\n\t\t\tif (Random.Int(5) == 0) {\n\t\t\t\tn++;\n\t\t\t}\n\t\t}\n\t\tlevel(n);\n\t\t\n\t\t//30% chance to be cursed\n\t\t//10% chance to be enchanted\n\t\tfloat effectRoll = Random.Float();\n\t\tif (effectRoll < 0.3f) {\n\t\t\tenchant(Enchantment.randomCurse());\n\t\t\tcursed = true;\n\t\t} else if (effectRoll >= 0.9f){\n\t\t\tenchant();\n\t\t}\n\n\t\treturn this;\n\t}\n\t\n\tpublic Weapon enchant( Enchantment ench ) {\n\t\tif (ench == null || !ench.curse()) curseInfusionBonus = false;\n\t\tenchantment = ench;\n\t\tupdateQuickslot();\n\t\treturn this;\n\t}\n\n\tpublic Weapon enchant() {\n\n\t\tClass<? extends Enchantment> oldEnchantment = enchantment != null ? enchantment.getClass() : null;\n\t\tEnchantment ench = Enchantment.random( oldEnchantment );\n\n\t\treturn enchant( ench );\n\t}\n\n\tpublic boolean hasEnchant(Class<?extends Enchantment> type, Char owner) {\n\t\treturn enchantment != null && enchantment.getClass() == type && owner.buff(MagicImmune.class) == null;\n\t}\n\t\n\t//these are not used to process specific enchant effects, so magic immune doesn't affect them\n\tpublic boolean hasGoodEnchant(){\n\t\treturn enchantment != null && !enchantment.curse();\n\t}\n\n\tpublic boolean hasCurseEnchant(){\n\t\treturn enchantment != null && enchantment.curse();\n\t}\n\n\t@Override\n\tpublic ItemSprite.Glowing glowing() {\n\t\treturn enchantment != null && (cursedKnown || !enchantment.curse()) ? enchantment.glowing() : null;\n\t}\n\n\tpublic static abstract class Enchantment implements Bundlable {\n\t\t//TODO: 신규 인챈트 추가할 때 격투가 신비한 반지 특성 효과도 추가할 것\n\t\tpublic static final Class<?>[] common = new Class<?>[]{\n\t\t\t\tBlazing.class, Chilling.class, Kinetic.class, Shocking.class};\n\n\t\tpublic static final Class<?>[] uncommon = new Class<?>[]{\n\t\t\t\tBlocking.class, Blooming.class, Elastic.class,\n\t\t\t\tLucky.class, Projecting.class, Unstable.class};\n\n\t\tpublic static final Class<?>[] rare = new Class<?>[]{\n\t\t\t\tCorrupting.class, Grim.class, Vampiric.class};\n\n\t\tpublic static final float[] typeChances = new float[]{\n\t\t\t\t50, //12.5% each\n\t\t\t\t40, //6.67% each\n\t\t\t\t10 //3.33% each\n\t\t};\n\t\t\n\t\tprivate static final Class<?>[] curses = new Class<?>[]{\n\t\t\t\tAnnoying.class, Displacing.class, Dazzling.class, Explosive.class,\n\t\t\t\tSacrificial.class, Wayward.class, Polarized.class, Friendly.class\n\t\t};\n\t\t\n\t\t\t\n\t\tpublic abstract int proc( Weapon weapon, Char attacker, Char defender, int damage );\n\n\t\tprotected float procChanceMultiplier( Char attacker ){\n\t\t\treturn genericProcChanceMultiplier( attacker );\n\t\t}\n\n\t\tpublic static float genericProcChanceMultiplier( Char attacker ){\n\t\t\tfloat multi = RingOfArcana.enchantPowerMultiplier(attacker);\n\t\t\tBerserk rage = attacker.buff(Berserk.class);\n\t\t\tif (rage != null) {\n\t\t\t\tmulti = rage.enchantFactor(multi);\n\t\t\t}\n\n\t\t\tif (attacker.buff(RunicBlade.RunicSlashTracker.class) != null){\n\t\t\t\tmulti += 3f;\n\t\t\t\tattacker.buff(RunicBlade.RunicSlashTracker.class).detach();\n\t\t\t}\n\n\t\t\tif (attacker.buff(TrueRunicBlade.TrueRunicSlashTracker.class) != null){\n\t\t\t\tmulti += 3f;\n\t\t\t\tattacker.buff(TrueRunicBlade.TrueRunicSlashTracker.class).detach();\n\t\t\t}\n\n\t\t\tif (attacker.buff(ElementalStrike.DirectedPowerTracker.class) != null){\n\t\t\t\tmulti += attacker.buff(ElementalStrike.DirectedPowerTracker.class).enchBoost;\n\t\t\t\tattacker.buff(ElementalStrike.DirectedPowerTracker.class).detach();\n\t\t\t}\n\n\t\t\tif (attacker.buff(Talent.SpiritBladesTracker.class) != null\n\t\t\t\t\t&& ((Hero)attacker).pointsInTalent(Talent.SPIRIT_BLADES) == 4){\n\t\t\t\tmulti += 0.1f;\n\t\t\t}\n\t\t\tif (attacker.buff(Talent.StrikingWaveTracker.class) != null\n\t\t\t\t\t&& ((Hero)attacker).pointsInTalent(Talent.STRIKING_WAVE) == 4){\n\t\t\t\tmulti += 0.2f;\n\t\t\t}\n\n\t\t\tif (attacker instanceof Hero && ((Hero) attacker).belongings.attackingWeapon() instanceof Gun.Bullet) {\n\t\t\t\tmulti *= ((Gun.Bullet) ((Hero) attacker).belongings.attackingWeapon()).whatEnchant().enchantFactor();\n\t\t\t}\n\n\t\t\tif (attacker instanceof Hero && attacker.buff(Tackle.MysticalTackleTracker.class) != null) {\n\t\t\t\tmulti += 0.5f * Dungeon.hero.pointsInTalent(Talent.MYSTICAL_TACKLE);\n\t\t\t}\n\n\t\t\treturn multi;\n\t\t}\n\n\t\tpublic String name() {\n\t\t\tif (!curse())\n\t\t\t\treturn name( Messages.get(this, \"enchant\"));\n\t\t\telse\n\t\t\t\treturn name( Messages.get(Item.class, \"curse\"));\n\t\t}\n\n\t\tpublic String name( String weaponName ) {\n\t\t\treturn Messages.get(this, \"name\", weaponName);\n\t\t}\n\n\t\tpublic String desc() {\n\t\t\treturn Messages.get(this, \"desc\");\n\t\t}\n\n\t\tpublic boolean curse() {\n\t\t\treturn false;\n\t\t}\n\n\t\t@Override\n\t\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\t}\n\n\t\t@Override\n\t\tpublic void storeInBundle( Bundle bundle ) {\n\t\t}\n\t\t\n\t\tpublic abstract ItemSprite.Glowing glowing();\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic static Enchantment random( Class<? extends Enchantment> ... toIgnore ) {\n\t\t\tswitch(Random.chances(typeChances)){\n\t\t\t\tcase 0: default:\n\t\t\t\t\treturn randomCommon( toIgnore );\n\t\t\t\tcase 1:\n\t\t\t\t\treturn randomUncommon( toIgnore );\n\t\t\t\tcase 2:\n\t\t\t\t\treturn randomRare( toIgnore );\n\t\t\t}\n\t\t}\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic static Enchantment randomCommon( Class<? extends Enchantment> ... toIgnore ) {\n\t\t\tArrayList<Class<?>> enchants = new ArrayList<>(Arrays.asList(common));\n\t\t\tenchants.removeAll(Arrays.asList(toIgnore));\n\t\t\tif (enchants.isEmpty()) {\n\t\t\t\treturn random();\n\t\t\t} else {\n\t\t\t\treturn (Enchantment) Reflection.newInstance(Random.element(enchants));\n\t\t\t}\n\t\t}\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic static Enchantment randomUncommon( Class<? extends Enchantment> ... toIgnore ) {\n\t\t\tArrayList<Class<?>> enchants = new ArrayList<>(Arrays.asList(uncommon));\n\t\t\tenchants.removeAll(Arrays.asList(toIgnore));\n\t\t\tif (enchants.isEmpty()) {\n\t\t\t\treturn random();\n\t\t\t} else {\n\t\t\t\treturn (Enchantment) Reflection.newInstance(Random.element(enchants));\n\t\t\t}\n\t\t}\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic static Enchantment randomRare( Class<? extends Enchantment> ... toIgnore ) {\n\t\t\tArrayList<Class<?>> enchants = new ArrayList<>(Arrays.asList(rare));\n\t\t\tenchants.removeAll(Arrays.asList(toIgnore));\n\t\t\tif (enchants.isEmpty()) {\n\t\t\t\treturn random();\n\t\t\t} else {\n\t\t\t\treturn (Enchantment) Reflection.newInstance(Random.element(enchants));\n\t\t\t}\n\t\t}\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic static Enchantment randomCurse( Class<? extends Enchantment> ... toIgnore ){\n\t\t\tArrayList<Class<?>> enchants = new ArrayList<>(Arrays.asList(curses));\n\t\t\tenchants.removeAll(Arrays.asList(toIgnore));\n\t\t\tif (enchants.isEmpty()) {\n\t\t\t\treturn random();\n\t\t\t} else {\n\t\t\t\treturn (Enchantment) Reflection.newInstance(Random.element(enchants));\n\t\t\t}\n\t\t}\n\t\t\n\t}\n}" }, { "identifier": "MagesStaff", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/weapon/melee/MagesStaff.java", "snippet": "public class MagesStaff extends MeleeWeapon {\n\n\tprivate Wand wand;\n\n\tpublic static final String AC_IMBUE = \"IMBUE\";\n\tpublic static final String AC_ZAP\t= \"ZAP\";\n\n\tprivate static final float STAFF_SCALE_FACTOR = 0.75f;\n\n\t{\n\t\timage = ItemSpriteSheet.MAGES_STAFF;\n\t\thitSound = Assets.Sounds.HIT;\n\t\thitSoundPitch = 1.1f;\n\n\t\ttier = 1;\n\n\t\tdefaultAction = AC_ZAP;\n\t\tusesTargeting = true;\n\n\t\tunique = true;\n\t\tbones = false;\n\t}\n\n\tpublic MagesStaff() {\n\t\twand = null;\n\t}\n\n\t@Override\n\tpublic int max(int lvl) {\n\t\treturn Math.round(3f*(tier+1)) + //6 base damage, down from 10\n\t\t\t\tlvl*(tier+1); //scaling unaffected\n\t}\n\n\tpublic MagesStaff(Wand wand){\n\t\tthis();\n\t\twand.identify();\n\t\twand.cursed = false;\n\t\tthis.wand = wand;\n\t\tupdateWand(false);\n\t\twand.curCharges = wand.maxCharges;\n\t}\n\n\tpublic int getCurCharges() {\n\t\treturn wand.curCharges;\n\t}\n\n\t@Override\n\tpublic ArrayList<String> actions(Hero hero) {\n\t\tArrayList<String> actions = super.actions( hero );\n\t\tactions.add(AC_IMBUE);\n\t\tif (wand!= null && wand.curCharges > 0) {\n\t\t\tactions.add( AC_ZAP );\n\t\t}\n\t\treturn actions;\n\t}\n\n\t@Override\n\tpublic String defaultAction() {\n\t\treturn AC_ZAP;\n\t}\n\n\t@Override\n\tpublic void activate( Char ch ) {\n\t\tsuper.activate(ch);\n\t\tapplyWandChargeBuff(ch);\n\t}\n\n\t@Override\n\tpublic int targetingPos(Hero user, int dst) {\n\t\tif (wand != null) {\n\t\t\treturn wand.targetingPos(user, dst);\n\t\t} else {\n\t\t\treturn super.targetingPos(user, dst);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void execute(Hero hero, String action) {\n\n\t\tsuper.execute(hero, action);\n\n\t\tif (action.equals(AC_IMBUE)) {\n\n\t\t\tcurUser = hero;\n\t\t\tGameScene.selectItem(itemSelector);\n\n\t\t} else if (action.equals(AC_ZAP)){\n\n\t\t\tif (wand == null) {\n\t\t\t\tGameScene.show(new WndUseItem(null, this));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (cursed || hasCurseEnchant()) wand.cursed = true;\n\t\t\telse wand.cursed = false;\n\t\t\twand.execute(hero, AC_ZAP);\n\t\t}\n\t}\n\n\t@Override\n\tpublic int buffedVisiblyUpgraded() {\n\t\tif (wand != null){\n\t\t\treturn Math.max(super.buffedVisiblyUpgraded(), wand.buffedVisiblyUpgraded());\n\t\t} else {\n\t\t\treturn super.buffedVisiblyUpgraded();\n\t\t}\n\t}\n\n\t@Override\n\tpublic int proc(Char attacker, Char defender, int damage) {\n\t\tif (attacker instanceof Hero && ((Hero) attacker).hasTalent(Talent.MYSTICAL_CHARGE)){\n\t\t\tHero hero = (Hero) attacker;\n\t\t\tfor (Buff b : hero.buffs()){\n\t\t\t\tif (b instanceof Artifact.ArtifactBuff && !((Artifact.ArtifactBuff) b).isCursed() ) {\n\t\t\t\t\t((Artifact.ArtifactBuff) b).charge(hero, hero.pointsInTalent(Talent.MYSTICAL_CHARGE)/2f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tTalent.EmpoweredStrikeTracker empoweredStrike = attacker.buff(Talent.EmpoweredStrikeTracker.class);\n\t\tif (empoweredStrike != null){\n\t\t\tdamage = Math.round( damage * (1f + Dungeon.hero.pointsInTalent(Talent.EMPOWERED_STRIKE)/6f));\n\t\t}\n\n\t\tif (wand != null &&\n\t\t\t\tattacker instanceof Hero && ((Hero)attacker).subClass == HeroSubClass.BATTLEMAGE) {\n\t\t\tif (wand.curCharges < wand.maxCharges) wand.partialCharge += 0.5f;\n\t\t\tScrollOfRecharging.charge((Hero)attacker);\n\t\t\twand.onHit(this, attacker, defender, damage);\n\t\t}\n\n\t\tif (empoweredStrike != null){\n\t\t\tempoweredStrike.detach();\n\t\t\tif (!(defender instanceof Mob) || !((Mob) defender).surprisedBy(attacker)){\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG, 0.75f, 1.2f);\n\t\t\t}\n\t\t}\n\t\treturn super.proc(attacker, defender, damage);\n\t}\n\n\t@Override\n\tpublic int reachFactor(Char owner) {\n\t\tint reach = super.reachFactor(owner);\n\t\tif (owner instanceof Hero\n\t\t\t\t&& wand instanceof WandOfDisintegration\n\t\t\t\t&& ((Hero)owner).subClass == HeroSubClass.BATTLEMAGE){\n\t\t\treach += Math.round(Wand.procChanceMultiplier(owner));\n\t\t}\n\t\treturn reach;\n\t}\n\n\t@Override\n\tpublic boolean collect( Bag container ) {\n\t\tif (super.collect(container)) {\n\t\t\tif (container.owner != null) {\n\t\t\t\tapplyWandChargeBuff(container.owner);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onDetach( ) {\n\t\tif (wand != null) wand.stopCharging();\n\t}\n\n\tpublic Item imbueWand(Wand wand, Char owner){\n\n\t\tint oldStaffcharges = this.wand != null ? this.wand.curCharges : 0;\n\n\t\tif (owner == Dungeon.hero && Dungeon.hero.hasTalent(Talent.WAND_PRESERVATION)){\n\t\t\tTalent.WandPreservationCounter counter = Buff.affect(Dungeon.hero, Talent.WandPreservationCounter.class);\n\t\t\tif (counter.count() < 5 && Random.Float() < 0.34f + 0.33f*Dungeon.hero.pointsInTalent(Talent.WAND_PRESERVATION)){\n\t\t\t\tcounter.countUp(1);\n\t\t\t\tthis.wand.level(0);\n\t\t\t\tif (!this.wand.collect()) {\n\t\t\t\t\tDungeon.level.drop(this.wand, owner.pos);\n\t\t\t\t}\n\t\t\t\tGLog.newLine();\n\t\t\t\tGLog.p(Messages.get(this, \"preserved\"));\n\t\t\t} else {\n\t\t\t\tArcaneResin resin = new ArcaneResin();\n\t\t\t\tif (!resin.collect()) {\n\t\t\t\t\tDungeon.level.drop(resin, owner.pos);\n\t\t\t\t}\n\t\t\t\tGLog.newLine();\n\t\t\t\tGLog.p(Messages.get(this, \"preserved_resin\"));\n\t\t\t}\n\t\t}\n\n\t\tthis.wand = null;\n\n\t\twand.resinBonus = 0;\n\t\twand.updateLevel();\n\n\t\t//syncs the level of the two items.\n\t\tint targetLevel = Math.max(this.trueLevel(), wand.trueLevel());\n\n\t\t//if the staff's level is being overridden by the wand, preserve 1 upgrade\n\t\tif (wand.trueLevel() >= this.trueLevel() && this.trueLevel() > 0) targetLevel++;\n\t\t\n\t\tlevel(targetLevel);\n\t\tthis.wand = wand;\n\t\tupdateWand(false);\n\t\twand.curCharges = Math.min(wand.maxCharges, wand.curCharges+oldStaffcharges);\n\t\tif (owner != null){\n\t\t\tapplyWandChargeBuff(owner);\n \t\t} else if (Dungeon.hero.belongings.contains(this)){\n\t\t\tapplyWandChargeBuff(Dungeon.hero);\n\t\t}\n\n\t\t//This is necessary to reset any particles.\n\t\t//FIXME this is gross, should implement a better way to fully reset quickslot visuals\n\t\tint slot = Dungeon.quickslot.getSlot(this);\n\t\tif (slot != -1){\n\t\t\tDungeon.quickslot.clearSlot(slot);\n\t\t\tupdateQuickslot();\n\t\t\tDungeon.quickslot.setSlot( slot, this );\n\t\t\tupdateQuickslot();\n\t\t}\n\t\t\n\t\tBadges.validateItemLevelAquired(this);\n\n\t\treturn this;\n\t}\n\n\tpublic void gainCharge( float amt ){\n\t\tgainCharge(amt, false);\n\t}\n\n\tpublic void gainCharge( float amt, boolean overcharge ){\n\t\tif (wand != null){\n\t\t\twand.gainCharge(amt, overcharge);\n\t\t}\n\t}\n\n\tpublic void loseCharge() {\n\t\twand.loseCharge();\n\t}\n\n\tpublic void applyWandChargeBuff(Char owner){\n\t\tif (wand != null){\n\t\t\twand.charge(owner, STAFF_SCALE_FACTOR);\n\t\t}\n\t}\n\n\tpublic Class<?extends Wand> wandClass(){\n\t\treturn wand != null ? wand.getClass() : null;\n\t}\n\n\t@Override\n\tpublic Item upgrade(boolean enchant) {\n\t\tsuper.upgrade( enchant );\n\n\t\tupdateWand(true);\n\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic Item degrade() {\n\t\tsuper.degrade();\n\n\t\tupdateWand(false);\n\n\t\treturn this;\n\t}\n\t\n\tpublic void updateWand(boolean levelled){\n\t\tif (wand != null) {\n\t\t\tint curCharges = wand.curCharges;\n\t\t\twand.level(level());\n\t\t\t//gives the wand one additional max charge\n\t\t\twand.maxCharges = Math.min(wand.maxCharges + 1, 10);\n\t\t\twand.curCharges = Math.min(curCharges + (levelled ? 1 : 0), wand.maxCharges);\n\t\t\tupdateQuickslot();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String status() {\n\t\tif (wand == null) return super.status();\n\t\telse return wand.status();\n\t}\n\n\t@Override\n\tpublic String name() {\n\t\tif (wand == null) {\n\t\t\treturn super.name();\n\t\t} else {\n\t\t\tString name = Messages.get(wand, \"staff_name\");\n\t\t\treturn enchantment != null && (cursedKnown || !enchantment.curse()) ? enchantment.name( name ) : name;\n\t\t}\n\t}\n\n\t@Override\n\tpublic String info() {\n\t\tString info = super.info();\n\n\t\tif (wand != null){\n\t\t\tinfo += \"\\n\\n\" + Messages.get(this, \"has_wand\", Messages.get(wand, \"name\"));\n\t\t\tif ((!cursed && !hasCurseEnchant()) || !cursedKnown) info += \" \" + wand.statsDesc();\n\t\t\telse info += \" \" + Messages.get(this, \"cursed_wand\");\n\n\t\t\tif (Dungeon.hero.subClass == HeroSubClass.BATTLEMAGE){\n\t\t\t\tinfo += \"\\n\\n\" + Messages.get(wand, \"bmage_desc\");\n\t\t\t}\n\t\t}\n\n\t\treturn info;\n\t}\n\n\t@Override\n\tpublic Emitter emitter() {\n\t\tif (wand == null) return null;\n\t\tEmitter emitter = new Emitter();\n\t\temitter.pos(12.5f, 3);\n\t\temitter.fillTarget = false;\n\t\temitter.pour(StaffParticleFactory, 0.1f);\n\t\treturn emitter;\n\t}\n\n\tprivate static final String WAND = \"wand\";\n\n\t@Override\n\tpublic void storeInBundle(Bundle bundle) {\n\t\tsuper.storeInBundle(bundle);\n\t\tbundle.put(WAND, wand);\n\t}\n\n\t@Override\n\tpublic void restoreFromBundle(Bundle bundle) {\n\t\tsuper.restoreFromBundle(bundle);\n\t\twand = (Wand) bundle.get(WAND);\n\t\tif (wand != null) {\n\t\t\twand.maxCharges = Math.min(wand.maxCharges + 1, 10);\n\t\t}\n\t}\n\n\t@Override\n\tpublic int value() {\n\t\treturn 0;\n\t}\n\t\n\t@Override\n\tpublic Weapon enchant(Enchantment ench) {\n\t\tif (curseInfusionBonus && (ench == null || !ench.curse())){\n\t\t\tcurseInfusionBonus = false;\n\t\t\tupdateWand(false);\n\t\t}\n\t\treturn super.enchant(ench);\n\t}\n\t\n\tprivate final WndBag.ItemSelector itemSelector = new WndBag.ItemSelector() {\n\n\t\t@Override\n\t\tpublic String textPrompt() {\n\t\t\treturn Messages.get(MagesStaff.class, \"prompt\");\n\t\t}\n\n\t\t@Override\n\t\tpublic Class<?extends Bag> preferredBag(){\n\t\t\treturn MagicalHolster.class;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean itemSelectable(Item item) {\n\t\t\treturn item instanceof Wand;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onSelect( final Item item ) {\n\t\t\tif (item != null) {\n\n\t\t\t\tif (!item.isIdentified()) {\n\t\t\t\t\tGLog.w(Messages.get(MagesStaff.class, \"id_first\"));\n\t\t\t\t\treturn;\n\t\t\t\t} else if (item.cursed){\n\t\t\t\t\tGLog.w(Messages.get(MagesStaff.class, \"cursed\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (wand == null){\n\t\t\t\t\tapplyWand((Wand)item);\n\t\t\t\t} else {\n\t\t\t\t\tint newLevel;\n\t\t\t\t\tint itemLevel = item.trueLevel();\n\t\t\t\t\tif (itemLevel >= trueLevel()){\n\t\t\t\t\t\tif (trueLevel() > 0) newLevel = itemLevel + 1;\n\t\t\t\t\t\telse newLevel = itemLevel;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnewLevel = trueLevel();\n\t\t\t\t\t}\n\n\t\t\t\t\tString bodyText = Messages.get(MagesStaff.class, \"imbue_desc\", newLevel);\n\t\t\t\t\tint preservesLeft = Dungeon.hero.hasTalent(Talent.WAND_PRESERVATION) ? 5 : 0;\n\t\t\t\t\tif (Dungeon.hero.buff(Talent.WandPreservationCounter.class) != null){\n\t\t\t\t\t\tpreservesLeft -= Dungeon.hero.buff(Talent.WandPreservationCounter.class).count();\n\t\t\t\t\t}\n\t\t\t\t\tif (Dungeon.hero.hasTalent(Talent.WAND_PRESERVATION)){\n\t\t\t\t\t\tint preserveChance = Dungeon.hero.pointsInTalent(Talent.WAND_PRESERVATION) == 1 ? 67 : 100;\n\t\t\t\t\t\tbodyText += \"\\n\\n\" + Messages.get(MagesStaff.class, \"imbue_talent\", preserveChance, preservesLeft);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbodyText += \"\\n\\n\" + Messages.get(MagesStaff.class, \"imbue_lost\");\n\t\t\t\t\t}\n\n\t\t\t\t\tGameScene.show(\n\t\t\t\t\t\t\tnew WndOptions(new ItemSprite(item),\n\t\t\t\t\t\t\t\t\tMessages.titleCase(item.name()),\n\t\t\t\t\t\t\t\t\tbodyText,\n\t\t\t\t\t\t\t\t\tMessages.get(MagesStaff.class, \"yes\"),\n\t\t\t\t\t\t\t\t\tMessages.get(MagesStaff.class, \"no\")) {\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tprotected void onSelect(int index) {\n\t\t\t\t\t\t\t\t\tif (index == 0) {\n\t\t\t\t\t\t\t\t\t\tapplyWand((Wand)item);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprivate void applyWand(Wand wand){\n\t\t\tSample.INSTANCE.play(Assets.Sounds.BURNING);\n\t\t\tcurUser.sprite.emitter().burst( ElmoParticle.FACTORY, 12 );\n\t\t\tevoke(curUser);\n\n\t\t\tDungeon.quickslot.clearItem(wand);\n\n\t\t\twand.detach(curUser.belongings.backpack);\n\n\t\t\tGLog.p( Messages.get(MagesStaff.class, \"imbue\", wand.name()));\n\t\t\timbueWand( wand, curUser );\n\n\t\t\tupdateQuickslot();\n\t\t}\n\t};\n\n\tprivate final Emitter.Factory StaffParticleFactory = new Emitter.Factory() {\n\t\t@Override\n\t\t//reimplementing this is needed as instance creation of new staff particles must be within this class.\n\t\tpublic void emit( Emitter emitter, int index, float x, float y ) {\n\t\t\tStaffParticle c = (StaffParticle)emitter.getFirstAvailable(StaffParticle.class);\n\t\t\tif (c == null) {\n\t\t\t\tc = new StaffParticle();\n\t\t\t\temitter.add(c);\n\t\t\t}\n\t\t\tc.reset(x, y);\n\t\t}\n\n\t\t@Override\n\t\t//some particles need light mode, others don't\n\t\tpublic boolean lightMode() {\n\t\t\treturn !((wand instanceof WandOfDisintegration)\n\t\t\t\t\t|| (wand instanceof WandOfCorruption)\n\t\t\t\t\t|| (wand instanceof WandOfCorrosion)\n\t\t\t\t\t|| (wand instanceof WandOfRegrowth)\n\t\t\t\t\t|| (wand instanceof WandOfLivingEarth));\n\t\t}\n\t};\n\n\t//determines particle effects to use based on wand the staff owns.\n\tpublic class StaffParticle extends PixelParticle{\n\n\t\tprivate float minSize;\n\t\tprivate float maxSize;\n\t\tpublic float sizeJitter = 0;\n\n\t\tpublic StaffParticle(){\n\t\t\tsuper();\n\t\t}\n\n\t\tpublic void reset( float x, float y ) {\n\t\t\trevive();\n\n\t\t\tspeed.set(0);\n\n\t\t\tthis.x = x;\n\t\t\tthis.y = y;\n\n\t\t\tif (wand != null)\n\t\t\t\twand.staffFx( this );\n\n\t\t}\n\n\t\tpublic void setSize( float minSize, float maxSize ){\n\t\t\tthis.minSize = minSize;\n\t\t\tthis.maxSize = maxSize;\n\t\t}\n\n\t\tpublic void setLifespan( float life ){\n\t\t\tlifespan = left = life;\n\t\t}\n\n\t\tpublic void shuffleXY(float amt){\n\t\t\tx += Random.Float(-amt, amt);\n\t\t\ty += Random.Float(-amt, amt);\n\t\t}\n\n\t\tpublic void radiateXY(float amt){\n\t\t\tfloat hypot = (float)Math.hypot(speed.x, speed.y);\n\t\t\tthis.x += speed.x/hypot*amt;\n\t\t\tthis.y += speed.y/hypot*amt;\n\t\t}\n\n\t\t@Override\n\t\tpublic void update() {\n\t\t\tsuper.update();\n\t\t\tsize(minSize + (left / lifespan)*(maxSize-minSize) + Random.Float(sizeJitter));\n\t\t}\n\t}\n}" }, { "identifier": "MissileWeapon", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/weapon/missiles/MissileWeapon.java", "snippet": "abstract public class MissileWeapon extends Weapon {\n\n\t{\n\t\tstackable = true;\n\t\tlevelKnown = true;\n\t\t\n\t\tbones = true;\n\n\t\tdefaultAction = AC_THROW;\n\t\tusesTargeting = true;\n\t}\n\t\n\tprotected boolean sticky = true;\n\t\n\tpublic static final float MAX_DURABILITY = 100;\n\tprotected float durability = MAX_DURABILITY;\n\tprotected float baseUses = 10;\n\t\n\tpublic boolean holster;\n\t\n\t//used to reduce durability from the source weapon stack, rather than the one being thrown.\n\tprotected MissileWeapon parent;\n\t\n\tpublic int tier;\n\t\n\t@Override\n\tpublic int min() {\n\t\treturn Math.max(0, min( buffedLvl() + RingOfSharpshooting.levelDamageBonus(Dungeon.hero) ));\n\t}\n\t\n\t@Override\n\tpublic int min(int lvl) {\n\t\treturn 2 * tier + //base\n\t\t\t\t(tier == 1 ? lvl : 2*lvl); //level scaling\n\t}\n\t\n\t@Override\n\tpublic int max() {\n\t\treturn Math.max(0, max( buffedLvl() + RingOfSharpshooting.levelDamageBonus(Dungeon.hero) ));\n\t}\n\t\n\t@Override\n\tpublic int max(int lvl) {\n\t\treturn 5 * tier + //base\n\t\t\t\t(tier == 1 ? 2*lvl : tier*lvl); //level scaling\n\t}\n\t\n\tpublic int STRReq(int lvl){\n\t\treturn STRReq(tier, lvl) - 1; //1 less str than normal for their tier\n\t}\n\t\n\t@Override\n\t//FIXME some logic here assumes the items are in the player's inventory. Might need to adjust\n\tpublic Item upgrade() {\n\t\tif (!bundleRestoring) {\n\t\t\tdurability = MAX_DURABILITY;\n\t\t\tif (quantity > 1) {\n\t\t\t\tMissileWeapon upgraded = (MissileWeapon) split(1);\n\t\t\t\tupgraded.parent = null;\n\t\t\t\t\n\t\t\t\tupgraded = (MissileWeapon) upgraded.upgrade();\n\t\t\t\t\n\t\t\t\t//try to put the upgraded into inventory, if it didn't already merge\n\t\t\t\tif (upgraded.quantity() == 1 && !upgraded.collect()) {\n\t\t\t\t\tDungeon.level.drop(upgraded, Dungeon.hero.pos);\n\t\t\t\t}\n\t\t\t\tupdateQuickslot();\n\t\t\t\treturn upgraded;\n\t\t\t} else {\n\t\t\t\tsuper.upgrade();\n\t\t\t\t\n\t\t\t\tItem similar = Dungeon.hero.belongings.getSimilar(this);\n\t\t\t\tif (similar != null){\n\t\t\t\t\tdetach(Dungeon.hero.belongings.backpack);\n\t\t\t\t\tItem result = similar.merge(this);\n\t\t\t\t\tupdateQuickslot();\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\tupdateQuickslot();\n\t\t\t\treturn this;\n\t\t\t}\n\t\t\t\n\t\t} else {\n\t\t\treturn super.upgrade();\n\t\t}\n\t}\n\n\t@Override\n\tpublic ArrayList<String> actions( Hero hero ) {\n\t\tArrayList<String> actions = super.actions( hero );\n\t\tactions.remove( AC_EQUIP );\n\t\treturn actions;\n\t}\n\t\n\t@Override\n\tpublic boolean collect(Bag container) {\n\t\tif (container instanceof MagicalHolster) holster = true;\n\t\treturn super.collect(container);\n\t}\n\t\n\t@Override\n\tpublic int throwPos(Hero user, int dst) {\n\n\t\tboolean projecting = hasEnchant(Projecting.class, user);\n\t\tif (!projecting && Random.Int(3) < user.pointsInTalent(Talent.SHARED_ENCHANTMENT)){\n\t\t\tif (this instanceof Dart && ((Dart) this).crossbowHasEnchant(Dungeon.hero)){\n\t\t\t\t//do nothing\n\t\t\t} else {\n\t\t\t\tSpiritBow bow = Dungeon.hero.belongings.getItem(SpiritBow.class);\n\t\t\t\tif (bow != null && bow.hasEnchant(Projecting.class, user)) {\n\t\t\t\t\tprojecting = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif ((this instanceof Gun.Bullet && (Dungeon.level.passable[dst] || Dungeon.level.avoid[dst])\n\t\t\t\t&& Dungeon.level.distance(user.pos, dst) <= 1+Dungeon.hero.pointsInTalent(Talent.STREET_BATTLE))\n\t\t\t\t|| (projecting\n\t\t\t\t&& (Dungeon.level.passable[dst] || Dungeon.level.avoid[dst])\n\t\t\t\t&& Dungeon.level.distance(user.pos, dst) <= Math.round(4 * Enchantment.genericProcChanceMultiplier(user)))){\n\t\t\treturn dst;\n\t\t} else {\n\t\t\treturn super.throwPos(user, dst);\n\t\t}\n\t}\n\n\t@Override\n\tpublic float accuracyFactor(Char owner, Char target) {\n\t\tfloat accFactor = super.accuracyFactor(owner, target);\n\t\tif (owner instanceof Hero && owner.buff(Momentum.class) != null && owner.buff(Momentum.class).freerunning()){\n\t\t\taccFactor *= 1f + 0.2f*((Hero) owner).pointsInTalent(Talent.PROJECTILE_MOMENTUM);\n\t\t}\n\n\t\taccFactor *= adjacentAccFactor(owner, target);\n\n\t\treturn accFactor;\n\t}\n\n\tprotected float adjacentAccFactor(Char owner, Char target){\n\t\tif (Dungeon.level.adjacent( owner.pos, target.pos )) {\n\t\t\tif (owner instanceof Hero){\n\t\t\t\treturn (0.5f + 0.2f*((Hero) owner).pointsInTalent(Talent.POINT_BLANK));\n\t\t\t} else {\n\t\t\t\treturn 0.5f;\n\t\t\t}\n\t\t} else {\n\t\t\treturn 1.5f;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void doThrow(Hero hero) {\n\t\tparent = null; //reset parent before throwing, just incase\n\t\tsuper.doThrow(hero);\n\t}\n\n\t@Override\n\tprotected void onThrow( int cell ) {\n\t\tChar enemy = Actor.findChar( cell );\n\t\tif (enemy == null || enemy == curUser) {\n\t\t\tparent = null;\n\n\t\t\t//metamorphed seer shot logic\n\t\t\tif (curUser.hasTalent(Talent.SEER_SHOT)\n\t\t\t\t\t&& curUser.heroClass != HeroClass.HUNTRESS\n\t\t\t\t\t&& curUser.buff(Talent.SeerShotCooldown.class) == null){\n\t\t\t\tif (Actor.findChar(cell) == null) {\n\t\t\t\t\tRevealedArea a = Buff.affect(curUser, RevealedArea.class, 5 * curUser.pointsInTalent(Talent.SEER_SHOT));\n\t\t\t\t\ta.depth = Dungeon.depth;\n\t\t\t\t\ta.pos = cell;\n\t\t\t\t\tBuff.affect(curUser, Talent.SeerShotCooldown.class, 20f);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsuper.onThrow( cell );\n\t\t} else {\n\t\t\tif (!curUser.shoot( enemy, this )) {\n\t\t\t\trangedMiss( cell );\n\t\t\t} else {\n\t\t\t\t\n\t\t\t\trangedHit( enemy, cell );\n\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic int proc(Char attacker, Char defender, int damage) {\n\t\tif (attacker == Dungeon.hero && Random.Int(3) < Dungeon.hero.pointsInTalent(Talent.SHARED_ENCHANTMENT)){\n\t\t\tif (this instanceof Dart && ((Dart) this).crossbowHasEnchant(Dungeon.hero)){\n\t\t\t\t//do nothing\n\t\t\t} else {\n\t\t\t\tSpiritBow bow = Dungeon.hero.belongings.getItem(SpiritBow.class);\n\t\t\t\tif (bow != null && bow.enchantment != null && Dungeon.hero.buff(MagicImmune.class) == null) {\n\t\t\t\t\tdamage = bow.enchantment.proc(this, attacker, defender, damage);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn super.proc(attacker, defender, damage);\n\t}\n\n\t@Override\n\tpublic Item random() {\n\t\tif (!stackable) return this;\n\t\t\n\t\t//2: 66.67% (2/3)\n\t\t//3: 26.67% (4/15)\n\t\t//4: 6.67% (1/15)\n\t\tquantity = 2;\n\t\tif (Random.Int(3) == 0) {\n\t\t\tquantity++;\n\t\t\tif (Random.Int(5) == 0) {\n\t\t\t\tquantity++;\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\tpublic String status() {\n\t\t//show quantity even when it is 1\n\t\treturn Integer.toString( quantity );\n\t}\n\t\n\t@Override\n\tpublic float castDelay(Char user, int dst) {\n\t\tif (hero.subClass == HeroSubClass.GUNSLINGER) {\n\t\t\tif (user instanceof Hero && ((Hero) user).justMoved) return 0;\n\t\t\telse return delayFactor( user );\n\t\t} else {\n\t\t\treturn delayFactor( user );\n\t\t}\n\t}\n\t\n\tprotected void rangedHit( Char enemy, int cell ){\n\t\tdecrementDurability();\n\t\tif (durability > 0){\n\t\t\t//attempt to stick the missile weapon to the enemy, just drop it if we can't.\n\t\t\tif (sticky && enemy != null && enemy.isAlive() && enemy.alignment != Char.Alignment.ALLY){\n\t\t\t\tPinCushion p = Buff.affect(enemy, PinCushion.class);\n\t\t\t\tif (p.target == enemy){\n\t\t\t\t\tp.stick(this);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tDungeon.level.drop( this, cell ).sprite.drop();\n\t\t}\n\t}\n\t\n\tprotected void rangedMiss( int cell ) {\n\t\tparent = null;\n\t\tsuper.onThrow(cell);\n\t}\n\n\tpublic float durabilityLeft(){\n\t\treturn durability;\n\t}\n\n\tpublic void repair( float amount ){\n\t\tdurability += amount;\n\t\tdurability = Math.min(durability, MAX_DURABILITY);\n\t}\n\t\n\tpublic float durabilityPerUse(){\n\t\tfloat usages = baseUses * (float)(Math.pow(3, level()));\n\n\t\t//+50%/75% durability\n\t\tif (Dungeon.hero.hasTalent(Talent.DURABLE_PROJECTILES)){\n\t\t\tusages *= 1.25f + (0.25f*Dungeon.hero.pointsInTalent(Talent.DURABLE_PROJECTILES));\n\t\t}\n\t\tif (holster) {\n\t\t\tusages *= MagicalHolster.HOLSTER_DURABILITY_FACTOR;\n\t\t}\n\t\t\n\t\tusages *= RingOfSharpshooting.durabilityMultiplier( Dungeon.hero );\n\t\t\n\t\t//at 100 uses, items just last forever.\n\t\tif (usages >= 100f) return 0;\n\n\t\tusages = Math.round(usages);\n\t\t\n\t\t//add a tiny amount to account for rounding error for calculations like 1/3\n\t\treturn (MAX_DURABILITY/usages) + 0.001f;\n\t}\n\t\n\tprotected void decrementDurability(){\n\t\t//if this weapon was thrown from a source stack, degrade that stack.\n\t\t//unless a weapon is about to break, then break the one being thrown\n\t\tif (parent != null){\n\t\t\tif (parent.durability <= parent.durabilityPerUse()){\n\t\t\t\tdurability = 0;\n\t\t\t\tparent.durability = MAX_DURABILITY;\n\t\t\t} else {\n\t\t\t\tparent.durability -= parent.durabilityPerUse();\n\t\t\t\tif (parent.durability > 0 && parent.durability <= parent.durabilityPerUse()){\n\t\t\t\t\tif (level() <= 0)GLog.w(Messages.get(this, \"about_to_break\"));\n\t\t\t\t\telse GLog.n(Messages.get(this, \"about_to_break\"));\n\t\t\t\t}\n\t\t\t}\n\t\t\tparent = null;\n\t\t} else {\n\t\t\tdurability -= durabilityPerUse();\n\t\t\tif (durability > 0 && durability <= durabilityPerUse()){\n\t\t\t\tif (level() <= 0)GLog.w(Messages.get(this, \"about_to_break\"));\n\t\t\t\telse GLog.n(Messages.get(this, \"about_to_break\"));\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic int damageRoll(Char owner) {\n\t\tint damage = augment.damageFactor(super.damageRoll( owner ));\n\t\t\n\t\tif (owner instanceof Hero) {\n\t\t\tint exStr = ((Hero)owner).STR() - STRReq();\n\t\t\tif (exStr > 0) {\n\t\t\t\tdamage += Random.IntRange( 0, exStr );\n\t\t\t}\n\t\t\tif (owner.buff(Momentum.class) != null && owner.buff(Momentum.class).freerunning()) {\n\t\t\t\tdamage = Math.round(damage * (1f + 0.15f * ((Hero) owner).pointsInTalent(Talent.PROJECTILE_MOMENTUM)));\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn damage;\n\t}\n\t\n\t@Override\n\tpublic void reset() {\n\t\tsuper.reset();\n\t\tdurability = MAX_DURABILITY;\n\t}\n\t\n\t@Override\n\tpublic Item merge(Item other) {\n\t\tsuper.merge(other);\n\t\tif (isSimilar(other)) {\n\t\t\tdurability += ((MissileWeapon)other).durability;\n\t\t\tdurability -= MAX_DURABILITY;\n\t\t\twhile (durability <= 0){\n\t\t\t\tquantity -= 1;\n\t\t\t\tdurability += MAX_DURABILITY;\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic Item split(int amount) {\n\t\tbundleRestoring = true;\n\t\tItem split = super.split(amount);\n\t\tbundleRestoring = false;\n\t\t\n\t\t//unless the thrown weapon will break, split off a max durability item and\n\t\t//have it reduce the durability of the main stack. Cleaner to the player this way\n\t\tif (split != null){\n\t\t\tMissileWeapon m = (MissileWeapon)split;\n\t\t\tm.durability = MAX_DURABILITY;\n\t\t\tm.parent = this;\n\t\t}\n\t\t\n\t\treturn split;\n\t}\n\t\n\t@Override\n\tpublic boolean doPickUp(Hero hero, int pos) {\n\t\tparent = null;\n\t\treturn super.doPickUp(hero, pos);\n\t}\n\t\n\t@Override\n\tpublic boolean isIdentified() {\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic String info() {\n\n\t\tString info = desc();\n\t\t\n\t\tinfo += \"\\n\\n\" + Messages.get( MissileWeapon.class, \"stats\",\n\t\t\t\ttier,\n\t\t\t\tMath.round(augment.damageFactor(min())),\n\t\t\t\tMath.round(augment.damageFactor(max())),\n\t\t\t\tSTRReq());\n\n\t\tif (STRReq() > Dungeon.hero.STR()) {\n\t\t\tinfo += \" \" + Messages.get(Weapon.class, \"too_heavy\");\n\t\t} else if (Dungeon.hero.STR() > STRReq()){\n\t\t\tinfo += \" \" + Messages.get(Weapon.class, \"excess_str\", Dungeon.hero.STR() - STRReq());\n\t\t}\n\n\t\tif (enchantment != null && (cursedKnown || !enchantment.curse())){\n\t\t\tinfo += \"\\n\\n\" + Messages.get(Weapon.class, \"enchanted\", enchantment.name());\n\t\t\tinfo += \" \" + Messages.get(enchantment, \"desc\");\n\t\t}\n\n\t\tif (cursed && isEquipped( Dungeon.hero )) {\n\t\t\tinfo += \"\\n\\n\" + Messages.get(Weapon.class, \"cursed_worn\");\n\t\t} else if (cursedKnown && cursed) {\n\t\t\tinfo += \"\\n\\n\" + Messages.get(Weapon.class, \"cursed\");\n\t\t} else if (!isIdentified() && cursedKnown){\n\t\t\tinfo += \"\\n\\n\" + Messages.get(Weapon.class, \"not_cursed\");\n\t\t}\n\n\t\tinfo += \"\\n\\n\" + Messages.get(MissileWeapon.class, \"distance\");\n\t\t\n\t\tinfo += \"\\n\\n\" + Messages.get(this, \"durability\");\n\t\t\n\t\tif (durabilityPerUse() > 0){\n\t\t\tinfo += \" \" + Messages.get(this, \"uses_left\",\n\t\t\t\t\t(int)Math.ceil(durability/durabilityPerUse()),\n\t\t\t\t\t(int)Math.ceil(MAX_DURABILITY/durabilityPerUse()));\n\t\t} else {\n\t\t\tinfo += \" \" + Messages.get(this, \"unlimited_uses\");\n\t\t}\n\t\t\n\t\t\n\t\treturn info;\n\t}\n\t\n\t@Override\n\tpublic int value() {\n\t\treturn 6 * tier * quantity * (level() + 1);\n\t}\n\t\n\tprivate static final String DURABILITY = \"durability\";\n\t\n\t@Override\n\tpublic void storeInBundle(Bundle bundle) {\n\t\tsuper.storeInBundle(bundle);\n\t\tbundle.put(DURABILITY, durability);\n\t}\n\t\n\tprivate static boolean bundleRestoring = false;\n\t\n\t@Override\n\tpublic void restoreFromBundle(Bundle bundle) {\n\t\tbundleRestoring = true;\n\t\tsuper.restoreFromBundle(bundle);\n\t\tbundleRestoring = false;\n\t\tdurability = bundle.getFloat(DURABILITY);\n\t}\n\n\tpublic static class PlaceHolder extends MissileWeapon {\n\n\t\t{\n\t\t\timage = ItemSpriteSheet.MISSILE_HOLDER;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean isSimilar(Item item) {\n\t\t\treturn item instanceof MissileWeapon;\n\t\t}\n\n\t\t@Override\n\t\tpublic String info() {\n\t\t\treturn \"\";\n\t\t}\n\t}\n}" }, { "identifier": "Messages", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/messages/Messages.java", "snippet": "public class Messages {\n\n\tprivate static ArrayList<I18NBundle> bundles;\n\tprivate static Languages lang;\n\tprivate static Locale locale;\n\n\tpublic static final String NO_TEXT_FOUND = \"!!!NO TEXT FOUND!!!\";\n\n\tpublic static Languages lang(){\n\t\treturn lang;\n\t}\n\n\tpublic static Locale locale(){\n\t\treturn locale;\n\t}\n\n\t/**\n\t * Setup Methods\n\t */\n\n\tprivate static String[] prop_files = new String[]{\n\t\t\tAssets.Messages.ACTORS,\n\t\t\tAssets.Messages.ITEMS,\n\t\t\tAssets.Messages.JOURNAL,\n\t\t\tAssets.Messages.LEVELS,\n\t\t\tAssets.Messages.MISC,\n\t\t\tAssets.Messages.PLANTS,\n\t\t\tAssets.Messages.SCENES,\n\t\t\tAssets.Messages.UI,\n\t\t\tAssets.Messages.WINDOWS\n\t};\n\n\tstatic{\n\t\tsetup(SPDSettings.language());\n\t}\n\n\tpublic static void setup( Languages lang ){\n\t\t//seeing as missing keys are part of our process, this is faster than throwing an exception\n\t\tI18NBundle.setExceptionOnMissingKey(false);\n\n\t\t//store language and locale info for various string logic\n\t\tMessages.lang = lang;\n\t\tif (lang == Languages.ENGLISH){\n\t\t\tlocale = Locale.ENGLISH;\n\t\t} else {\n\t\t\tlocale = new Locale(lang.code());\n\t\t}\n\n\t\t//strictly match the language code when fetching bundles however\n\t\tbundles = new ArrayList<>();\n\t\tLocale bundleLocal = new Locale(lang.code());\n\t\tfor (String file : prop_files) {\n\t\t\tbundles.add(I18NBundle.createBundle(Gdx.files.internal(file), bundleLocal));\n\t\t}\n\t}\n\n\n\n\t/**\n\t * Resource grabbing methods\n\t */\n\n\tpublic static String get(String key, Object...args){\n\t\treturn get(null, key, args);\n\t}\n\n\tpublic static String get(Object o, String k, Object...args){\n\t\treturn get(o.getClass(), k, args);\n\t}\n\n\tpublic static String get(Class c, String k, Object...args){\n\t\tString key;\n\t\tif (c != null){\n\t\t\tkey = c.getName().replace(\"com.shatteredpixel.shatteredpixeldungeon.\", \"\");\n\t\t\tkey += \".\" + k;\n\t\t} else\n\t\t\tkey = k;\n\n\t\tString value = getFromBundle(key.toLowerCase(Locale.ENGLISH));\n\t\tif (value != null){\n\t\t\tif (args.length > 0) return format(value, args);\n\t\t\telse return value;\n\t\t} else {\n\t\t\t//this is so child classes can inherit properties from their parents.\n\t\t\t//in cases where text is commonly grabbed as a utility from classes that aren't mean to be instantiated\n\t\t\t//(e.g. flavourbuff.dispTurns()) using .class directly is probably smarter to prevent unnecessary recursive calls.\n\t\t\tif (c != null && c.getSuperclass() != null){\n\t\t\t\treturn get(c.getSuperclass(), k, args);\n\t\t\t} else {\n\t\t\t\treturn NO_TEXT_FOUND;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static String getFromBundle(String key){\n\t\tString result;\n\t\tfor (I18NBundle b : bundles){\n\t\t\tresult = b.get(key);\n\t\t\t//if it isn't the return string for no key found, return it\n\t\t\tif (result.length() != key.length()+6 || !result.contains(key)){\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\n\n\t/**\n\t * String Utility Methods\n\t */\n\n\tpublic static String format( String format, Object...args ) {\n\t\ttry {\n\t\t\treturn String.format(Locale.ENGLISH, format, args);\n\t\t} catch (IllegalFormatException e) {\n\t\t\tShatteredPixelDungeon.reportException( new Exception(\"formatting error for the string: \" + format, e) );\n\t\t\treturn format;\n\t\t}\n\t}\n\n\tprivate static HashMap<String, DecimalFormat> formatters = new HashMap<>();\n\n\tpublic static String decimalFormat( String format, double number ){\n\t\tif (!formatters.containsKey(format)){\n\t\t\tformatters.put(format, new DecimalFormat(format, DecimalFormatSymbols.getInstance(Locale.ENGLISH)));\n\t\t}\n\t\treturn formatters.get(format).format(number);\n\t}\n\n\tpublic static String capitalize( String str ){\n\t\tif (str.length() == 0) return str;\n\t\telse return str.substring( 0, 1 ).toUpperCase(locale) + str.substring( 1 );\n\t}\n\n\t//Words which should not be capitalized in title case, mostly prepositions which appear ingame\n\t//This list is not comprehensive!\n\tprivate static final HashSet<String> noCaps = new HashSet<>(\n\t\t\tArrays.asList(\"a\", \"an\", \"and\", \"of\", \"by\", \"to\", \"the\", \"x\", \"for\")\n\t);\n\n\tpublic static String titleCase( String str ){\n\t\t//English capitalizes every word except for a few exceptions\n\t\tif (lang == Languages.ENGLISH){\n\t\t\tString result = \"\";\n\t\t\t//split by any unicode space character\n\t\t\tfor (String word : str.split(\"(?<=\\\\p{Zs})\")){\n\t\t\t\tif (noCaps.contains(word.trim().toLowerCase(Locale.ENGLISH).replaceAll(\":|[0-9]\", \"\"))){\n\t\t\t\t\tresult += word;\n\t\t\t\t} else {\n\t\t\t\t\tresult += capitalize(word);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//first character is always capitalized.\n\t\t\treturn capitalize(result);\n\t\t}\n\n\t\t//Otherwise, use sentence case\n\t\treturn capitalize(str);\n\t}\n\n\tpublic static String upperCase( String str ){\n\t\treturn str.toUpperCase(locale);\n\t}\n\n\tpublic static String lowerCase( String str ){\n\t\treturn str.toLowerCase(locale);\n\t}\n}" }, { "identifier": "GLog", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/utils/GLog.java", "snippet": "public class GLog {\n\n\tpublic static final String TAG = \"GAME\";\n\t\n\tpublic static final String POSITIVE\t\t= \"++ \";\n\tpublic static final String NEGATIVE\t\t= \"-- \";\n\tpublic static final String WARNING\t\t= \"** \";\n\tpublic static final String HIGHLIGHT\t= \"@@ \";\n\n\tpublic static final String NEW_LINE\t = \"\\n\";\n\t\n\tpublic static Signal<String> update = new Signal<>();\n\n\tpublic static void newLine(){\n\t\tupdate.dispatch( NEW_LINE );\n\t}\n\t\n\tpublic static void i( String text, Object... args ) {\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttext = Messages.format( text, args );\n\t\t}\n\t\t\n\t\tDeviceCompat.log( TAG, text );\n\t\tupdate.dispatch( text );\n\t}\n\t\n\tpublic static void p( String text, Object... args ) {\n\t\ti( POSITIVE + text, args );\n\t}\n\t\n\tpublic static void n( String text, Object... args ) {\n\t\ti( NEGATIVE + text, args );\n\t}\n\t\n\tpublic static void w( String text, Object... args ) {\n\t\ti( WARNING + text, args );\n\t}\n\t\n\tpublic static void h( String text, Object... args ) {\n\t\ti( HIGHLIGHT + text, args );\n\t}\n}" }, { "identifier": "Sample", "path": "SPD-classes/src/main/java/com/watabou/noosa/audio/Sample.java", "snippet": "public enum Sample {\n\n\tINSTANCE;\n\n\tprotected HashMap<Object, Sound> ids = new HashMap<>();\n\n\tprivate boolean enabled = true;\n\tprivate float globalVolume = 1f;\n\n\tpublic synchronized void reset() {\n\n\t\tfor (Sound sound : ids.values()){\n\t\t\tsound.dispose();\n\t\t}\n\t\t\n\t\tids.clear();\n\t\tdelayedSFX.clear();\n\n\t}\n\n\tpublic synchronized void pause() {\n\t\tfor (Sound sound : ids.values()) {\n\t\t\tsound.pause();\n\t\t}\n\t}\n\n\tpublic synchronized void resume() {\n\t\tfor (Sound sound : ids.values()) {\n\t\t\tsound.resume();\n\t\t}\n\t}\n\n\tpublic synchronized void load( final String... assets ) {\n\n\t\tfinal ArrayList<String> toLoad = new ArrayList<>();\n\n\t\tfor (String asset : assets){\n\t\t\tif (!ids.containsKey(asset)){\n\t\t\t\ttoLoad.add(asset);\n\t\t\t}\n\t\t}\n\n\t\t//don't make a new thread of all assets are already loaded\n\t\tif (toLoad.isEmpty()) return;\n\n\t\t//load in a separate thread to prevent this blocking the UI\n\t\tnew Thread(){\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tfor (String asset : toLoad) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tSound newSound = Gdx.audio.newSound(Gdx.files.internal(asset));\n\t\t\t\t\t\tsynchronized (INSTANCE) {\n\t\t\t\t\t\t\tids.put(asset, newSound);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (Exception e){\n\t\t\t\t\t\tGame.reportException(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}.start();\n\t\t\n\t}\n\n\tpublic synchronized void unload( Object src ) {\n\t\tif (ids.containsKey( src )) {\n\t\t\tids.get( src ).dispose();\n\t\t\tids.remove( src );\n\t\t}\n\t}\n\n\tpublic long play( Object id ) {\n\t\treturn play( id, 1 );\n\t}\n\n\tpublic long play( Object id, float volume ) {\n\t\treturn play( id, volume, volume, 1 );\n\t}\n\t\n\tpublic long play( Object id, float volume, float pitch ) {\n\t\treturn play( id, volume, volume, pitch );\n\t}\n\t\n\tpublic synchronized long play( Object id, float leftVolume, float rightVolume, float pitch ) {\n\t\tfloat volume = Math.max(leftVolume, rightVolume);\n\t\tfloat pan = rightVolume - leftVolume;\n\t\tif (enabled && ids.containsKey( id )) {\n\t\t\treturn ids.get(id).play( globalVolume*volume, pitch, pan );\n\t\t} else {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tprivate class DelayedSoundEffect{\n\t\tObject id;\n\t\tfloat delay;\n\n\t\tfloat leftVol;\n\t\tfloat rightVol;\n\t\tfloat pitch;\n\t}\n\n\tprivate static final HashSet<DelayedSoundEffect> delayedSFX = new HashSet<>();\n\n\tpublic void playDelayed( Object id, float delay ){\n\t\tplayDelayed( id, delay, 1 );\n\t}\n\n\tpublic void playDelayed( Object id, float delay, float volume ) {\n\t\tplayDelayed( id, delay, volume, volume, 1 );\n\t}\n\n\tpublic void playDelayed( Object id, float delay, float volume, float pitch ) {\n\t\tplayDelayed( id, delay, volume, volume, pitch );\n\t}\n\n\tpublic void playDelayed( Object id, float delay, float leftVolume, float rightVolume, float pitch ) {\n\t\tif (delay <= 0) {\n\t\t\tplay(id, leftVolume, rightVolume, pitch);\n\t\t\treturn;\n\t\t}\n\t\tDelayedSoundEffect sfx = new DelayedSoundEffect();\n\t\tsfx.id = id;\n\t\tsfx.delay = delay;\n\t\tsfx.leftVol = leftVolume;\n\t\tsfx.rightVol = rightVolume;\n\t\tsfx.pitch = pitch;\n\t\tsynchronized (delayedSFX) {\n\t\t\tdelayedSFX.add(sfx);\n\t\t}\n\t}\n\n\tpublic void update(){\n\t\tsynchronized (delayedSFX) {\n\t\t\tif (delayedSFX.isEmpty()) return;\n\t\t\tfor (DelayedSoundEffect sfx : delayedSFX.toArray(new DelayedSoundEffect[0])) {\n\t\t\t\tsfx.delay -= Game.elapsed;\n\t\t\t\tif (sfx.delay <= 0) {\n\t\t\t\t\tdelayedSFX.remove(sfx);\n\t\t\t\t\tplay(sfx.id, sfx.leftVol, sfx.rightVol, sfx.pitch);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void enable( boolean value ) {\n\t\tenabled = value;\n\t}\n\n\tpublic void volume( float value ) {\n\t\tglobalVolume = value;\n\t}\n\n\tpublic boolean isEnabled() {\n\t\treturn enabled;\n\t}\n\t\n}" } ]
import com.shatteredpixel.shatteredpixeldungeon.items.armor.Armor; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.Weapon; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.MagesStaff; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.missiles.MissileWeapon; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.utils.GLog; import com.watabou.noosa.audio.Sample; import java.util.ArrayList; import java.util.Collections; import com.shatteredpixel.shatteredpixeldungeon.Assets; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero; import com.shatteredpixel.shatteredpixeldungeon.effects.CellEmitter; import com.shatteredpixel.shatteredpixeldungeon.effects.particles.ShadowParticle; import com.shatteredpixel.shatteredpixeldungeon.items.EquipableItem; import com.shatteredpixel.shatteredpixeldungeon.items.Heap; import com.shatteredpixel.shatteredpixeldungeon.items.Item; import com.shatteredpixel.shatteredpixeldungeon.items.KindOfWeapon;
76,820
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.levels.traps; public class CursingTrap extends Trap { { color = VIOLET; shape = WAVES; } @Override public void activate() { if (Dungeon.level.heroFOV[ pos ]) { CellEmitter.get(pos).burst(ShadowParticle.UP, 5); Sample.INSTANCE.play(Assets.Sounds.CURSED); } Heap heap = Dungeon.level.heaps.get( pos ); if (heap != null){ for (Item item : heap.items){ if (item.isUpgradable() && !(item instanceof MissileWeapon)) curse(item); } } if (Dungeon.hero.pos == pos && !Dungeon.hero.flying){ curse(Dungeon.hero); } } public static void curse(Hero hero){ //items the trap wants to curse because it will create a more negative effect ArrayList<Item> priorityCurse = new ArrayList<>(); //items the trap can curse if nothing else is available. ArrayList<Item> canCurse = new ArrayList<>();
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.levels.traps; public class CursingTrap extends Trap { { color = VIOLET; shape = WAVES; } @Override public void activate() { if (Dungeon.level.heroFOV[ pos ]) { CellEmitter.get(pos).burst(ShadowParticle.UP, 5); Sample.INSTANCE.play(Assets.Sounds.CURSED); } Heap heap = Dungeon.level.heaps.get( pos ); if (heap != null){ for (Item item : heap.items){ if (item.isUpgradable() && !(item instanceof MissileWeapon)) curse(item); } } if (Dungeon.hero.pos == pos && !Dungeon.hero.flying){ curse(Dungeon.hero); } } public static void curse(Hero hero){ //items the trap wants to curse because it will create a more negative effect ArrayList<Item> priorityCurse = new ArrayList<>(); //items the trap can curse if nothing else is available. ArrayList<Item> canCurse = new ArrayList<>();
KindOfWeapon weapon = hero.belongings.weapon();
8
2023-11-27 05:56:58+00:00
128k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/source/org/jfree/chart/annotations/XYTextAnnotation.java
[ { "identifier": "HashUtilities", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/HashUtilities.java", "snippet": "public class HashUtilities {\r\n \r\n /**\r\n * Returns a hash code for a <code>Paint</code> instance. If \r\n * <code>p</code> is <code>null</code>, this method returns zero.\r\n * \r\n * @param p the paint (<code>null</code> permitted).\r\n * \r\n * @return The hash code.\r\n */\r\n public static int hashCodeForPaint(Paint p) {\r\n if (p == null) {\r\n return 0;\r\n }\r\n int result;\r\n // handle GradientPaint as a special case\r\n if (p instanceof GradientPaint) {\r\n GradientPaint gp = (GradientPaint) p;\r\n result = 193;\r\n result = 37 * result + gp.getColor1().hashCode();\r\n result = 37 * result + gp.getPoint1().hashCode();\r\n result = 37 * result + gp.getColor2().hashCode();\r\n result = 37 * result + gp.getPoint2().hashCode();\r\n }\r\n else {\r\n // we assume that all other Paint instances implement equals() and\r\n // hashCode()...of course that might not be true, but what can we\r\n // do about it?\r\n result = p.hashCode();\r\n }\r\n return result;\r\n }\r\n \r\n /**\r\n * Returns a hash code for a <code>double[]</code> instance. If the array\r\n * is <code>null</code>, this method returns zero.\r\n * \r\n * @param a the array (<code>null</code> permitted).\r\n * \r\n * @return The hash code.\r\n */\r\n public static int hashCodeForDoubleArray(double[] a) {\r\n if (a == null) { \r\n return 0;\r\n }\r\n int result = 193;\r\n long temp;\r\n for (int i = 0; i < a.length; i++) {\r\n temp = Double.doubleToLongBits(a[i]);\r\n result = 29 * result + (int) (temp ^ (temp >>> 32));\r\n }\r\n return result;\r\n }\r\n \r\n /**\r\n * Returns a hash value based on a seed value and the value of a boolean\r\n * primitive.\r\n * \r\n * @param pre the seed value.\r\n * @param b the boolean value.\r\n * \r\n * @return A hash value.\r\n * \r\n * @since 1.0.7\r\n */\r\n public static int hashCode(int pre, boolean b) {\r\n return 37 * pre + (b ? 0 : 1);\r\n }\r\n \r\n /**\r\n * Returns a hash value based on a seed value and the value of an int\r\n * primitive.\r\n * \r\n * @param pre the seed value.\r\n * @param i the int value.\r\n * \r\n * @return A hash value.\r\n * \r\n * @since 1.0.8\r\n */\r\n public static int hashCode(int pre, int i) {\r\n return 37 * pre + i;\r\n }\r\n\r\n /**\r\n * Returns a hash value based on a seed value and the value of a double\r\n * primitive.\r\n * \r\n * @param pre the seed value.\r\n * @param d the double value.\r\n * \r\n * @return A hash value.\r\n * \r\n * @since 1.0.7\r\n */\r\n public static int hashCode(int pre, double d) {\r\n long l = Double.doubleToLongBits(d);\r\n return 37 * pre + (int) (l ^ (l >>> 32));\r\n }\r\n \r\n /**\r\n * Returns a hash value based on a seed value and a paint instance.\r\n * \r\n * @param pre the seed value.\r\n * @param p the paint (<code>null</code> permitted).\r\n * \r\n * @return A hash value.\r\n * \r\n * @since 1.0.7\r\n */\r\n public static int hashCode(int pre, Paint p) {\r\n return 37 * pre + hashCodeForPaint(p);\r\n }\r\n\r\n /**\r\n * Returns a hash value based on a seed value and a stroke instance.\r\n * \r\n * @param pre the seed value.\r\n * @param s the stroke (<code>null</code> permitted).\r\n * \r\n * @return A hash value.\r\n * \r\n * @since 1.0.7\r\n */\r\n public static int hashCode(int pre, Stroke s) {\r\n int h = (s != null ? s.hashCode() : 0);\r\n return 37 * pre + h;\r\n }\r\n\r\n /**\r\n * Returns a hash value based on a seed value and a string instance.\r\n * \r\n * @param pre the seed value.\r\n * @param s the string (<code>null</code> permitted).\r\n * \r\n * @return A hash value.\r\n * \r\n * @since 1.0.7\r\n */\r\n public static int hashCode(int pre, String s) {\r\n int h = (s != null ? s.hashCode() : 0);\r\n return 37 * pre + h;\r\n }\r\n\r\n /**\r\n * Returns a hash value based on a seed value and a <code>Comparable</code>\r\n * instance.\r\n * \r\n * @param pre the seed value.\r\n * @param c the comparable (<code>null</code> permitted).\r\n * \r\n * @return A hash value.\r\n * \r\n * @since 1.0.7\r\n */\r\n public static int hashCode(int pre, Comparable c) {\r\n int h = (c != null ? c.hashCode() : 0);\r\n return 37 * pre + h;\r\n }\r\n\r\n /**\r\n * Returns a hash value based on a seed value and an <code>Object</code>\r\n * instance.\r\n * \r\n * @param pre the seed value.\r\n * @param obj the object (<code>null</code> permitted).\r\n * \r\n * @return A hash value.\r\n * \r\n * @since 1.0.8\r\n */\r\n public static int hashCode(int pre, Object obj) {\r\n int h = (obj != null ? obj.hashCode() : 0);\r\n return 37 * pre + h;\r\n }\r\n \r\n /**\r\n * Computes a hash code for a {@link BooleanList}. In the latest version\r\n * of JCommon, the {@link BooleanList} class should implement the hashCode()\r\n * method correctly, but we compute it here anyway so that we can work with \r\n * older versions of JCommon (back to 1.0.0).\r\n * \r\n * @param pre the seed value.\r\n * @param list the list (<code>null</code> permitted).\r\n * \r\n * @return The hash code.\r\n * \r\n * @since 1.0.9\r\n */\r\n public static int hashCode(int pre, BooleanList list) {\r\n if (list == null) {\r\n return pre;\r\n }\r\n int result = 127;\r\n int size = list.size();\r\n result = HashUtilities.hashCode(result, size);\r\n \r\n // for efficiency, we just use the first, last and middle items to\r\n // compute a hashCode...\r\n if (size > 0) {\r\n result = HashUtilities.hashCode(result, list.getBoolean(0));\r\n if (size > 1) {\r\n result = HashUtilities.hashCode(result, \r\n list.getBoolean(size - 1));\r\n if (size > 2) {\r\n result = HashUtilities.hashCode(result, \r\n list.getBoolean(size / 2));\r\n }\r\n }\r\n }\r\n return 37 * pre + result;\r\n }\r\n\r\n /**\r\n * Computes a hash code for a {@link PaintList}. In the latest version\r\n * of JCommon, the {@link PaintList} class should implement the hashCode()\r\n * method correctly, but we compute it here anyway so that we can work with \r\n * older versions of JCommon (back to 1.0.0).\r\n * \r\n * @param pre the seed value.\r\n * @param list the list (<code>null</code> permitted).\r\n * \r\n * @return The hash code.\r\n * \r\n * @since 1.0.9\r\n */\r\n public static int hashCode(int pre, PaintList list) {\r\n if (list == null) {\r\n return pre;\r\n }\r\n int result = 127;\r\n int size = list.size();\r\n result = HashUtilities.hashCode(result, size);\r\n \r\n // for efficiency, we just use the first, last and middle items to\r\n // compute a hashCode...\r\n if (size > 0) {\r\n result = HashUtilities.hashCode(result, list.getPaint(0));\r\n if (size > 1) {\r\n result = HashUtilities.hashCode(result, \r\n list.getPaint(size - 1));\r\n if (size > 2) {\r\n result = HashUtilities.hashCode(result, \r\n list.getPaint(size / 2));\r\n }\r\n }\r\n }\r\n return 37 * pre + result;\r\n }\r\n\r\n /**\r\n * Computes a hash code for a {@link StrokeList}. In the latest version\r\n * of JCommon, the {@link StrokeList} class should implement the hashCode()\r\n * method correctly, but we compute it here anyway so that we can work with \r\n * older versions of JCommon (back to 1.0.0).\r\n * \r\n * @param pre the seed value.\r\n * @param list the list (<code>null</code> permitted).\r\n * \r\n * @return The hash code.\r\n * \r\n * @since 1.0.9\r\n */\r\n public static int hashCode(int pre, StrokeList list) {\r\n if (list == null) {\r\n return pre;\r\n }\r\n int result = 127;\r\n int size = list.size();\r\n result = HashUtilities.hashCode(result, size);\r\n \r\n // for efficiency, we just use the first, last and middle items to\r\n // compute a hashCode...\r\n if (size > 0) {\r\n result = HashUtilities.hashCode(result, list.getStroke(0));\r\n if (size > 1) {\r\n result = HashUtilities.hashCode(result, \r\n list.getStroke(size - 1));\r\n if (size > 2) {\r\n result = HashUtilities.hashCode(result, \r\n list.getStroke(size / 2));\r\n }\r\n }\r\n }\r\n return 37 * pre + result;\r\n }\r\n}\r" }, { "identifier": "ValueAxis", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/axis/ValueAxis.java", "snippet": "public abstract class ValueAxis extends Axis\r\n implements Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 3698345477322391456L;\r\n\r\n /** The default axis range. */\r\n public static final Range DEFAULT_RANGE = new Range(0.0, 1.0);\r\n\r\n /** The default auto-range value. */\r\n public static final boolean DEFAULT_AUTO_RANGE = true;\r\n\r\n /** The default inverted flag setting. */\r\n public static final boolean DEFAULT_INVERTED = false;\r\n\r\n /** The default minimum auto range. */\r\n public static final double DEFAULT_AUTO_RANGE_MINIMUM_SIZE = 0.00000001;\r\n\r\n /** The default value for the lower margin (0.05 = 5%). */\r\n public static final double DEFAULT_LOWER_MARGIN = 0.05;\r\n\r\n /** The default value for the upper margin (0.05 = 5%). */\r\n public static final double DEFAULT_UPPER_MARGIN = 0.05;\r\n\r\n /**\r\n * The default lower bound for the axis.\r\n *\r\n * @deprecated From 1.0.5 onwards, the axis defines a defaultRange\r\n * attribute (see {@link #getDefaultAutoRange()}).\r\n */\r\n public static final double DEFAULT_LOWER_BOUND = 0.0;\r\n\r\n /**\r\n * The default upper bound for the axis.\r\n *\r\n * @deprecated From 1.0.5 onwards, the axis defines a defaultRange\r\n * attribute (see {@link #getDefaultAutoRange()}).\r\n */\r\n public static final double DEFAULT_UPPER_BOUND = 1.0;\r\n\r\n /** The default auto-tick-unit-selection value. */\r\n public static final boolean DEFAULT_AUTO_TICK_UNIT_SELECTION = true;\r\n\r\n /** The maximum tick count. */\r\n public static final int MAXIMUM_TICK_COUNT = 500;\r\n\r\n /**\r\n * A flag that controls whether an arrow is drawn at the positive end of\r\n * the axis line.\r\n */\r\n private boolean positiveArrowVisible;\r\n\r\n /**\r\n * A flag that controls whether an arrow is drawn at the negative end of\r\n * the axis line.\r\n */\r\n private boolean negativeArrowVisible;\r\n\r\n /** The shape used for an up arrow. */\r\n private transient Shape upArrow;\r\n\r\n /** The shape used for a down arrow. */\r\n private transient Shape downArrow;\r\n\r\n /** The shape used for a left arrow. */\r\n private transient Shape leftArrow;\r\n\r\n /** The shape used for a right arrow. */\r\n private transient Shape rightArrow;\r\n\r\n /** A flag that affects the orientation of the values on the axis. */\r\n private boolean inverted;\r\n\r\n /** The axis range. */\r\n private Range range;\r\n\r\n /**\r\n * Flag that indicates whether the axis automatically scales to fit the\r\n * chart data.\r\n */\r\n private boolean autoRange;\r\n\r\n /** The minimum size for the 'auto' axis range (excluding margins). */\r\n private double autoRangeMinimumSize;\r\n\r\n /**\r\n * The default range is used when the dataset is empty and the axis needs\r\n * to determine the auto range.\r\n *\r\n * @since 1.0.5\r\n */\r\n private Range defaultAutoRange;\r\n\r\n /**\r\n * The upper margin percentage. This indicates the amount by which the\r\n * maximum axis value exceeds the maximum data value (as a percentage of\r\n * the range on the axis) when the axis range is determined automatically.\r\n */\r\n private double upperMargin;\r\n\r\n /**\r\n * The lower margin. This is a percentage that indicates the amount by\r\n * which the minimum axis value is \"less than\" the minimum data value when\r\n * the axis range is determined automatically.\r\n */\r\n private double lowerMargin;\r\n\r\n /**\r\n * If this value is positive, the amount is subtracted from the maximum\r\n * data value to determine the lower axis range. This can be used to\r\n * provide a fixed \"window\" on dynamic data.\r\n */\r\n private double fixedAutoRange;\r\n\r\n /**\r\n * Flag that indicates whether or not the tick unit is selected\r\n * automatically.\r\n */\r\n private boolean autoTickUnitSelection;\r\n\r\n /** The standard tick units for the axis. */\r\n private TickUnitSource standardTickUnits;\r\n\r\n /** An index into an array of standard tick values. */\r\n private int autoTickIndex;\r\n\r\n /**\r\n * The number of minor ticks per major tick unit. This is an override\r\n * field, if the value is &gt; 0 it is used, otherwise the axis refers to the\r\n * minorTickCount in the current tickUnit.\r\n */\r\n private int minorTickCount;\r\n\r\n /** A flag indicating whether or not tick labels are rotated to vertical. */\r\n private boolean verticalTickLabels;\r\n\r\n /**\r\n * Constructs a value axis.\r\n *\r\n * @param label the axis label (<code>null</code> permitted).\r\n * @param standardTickUnits the source for standard tick units\r\n * (<code>null</code> permitted).\r\n */\r\n protected ValueAxis(String label, TickUnitSource standardTickUnits) {\r\n\r\n super(label);\r\n\r\n this.positiveArrowVisible = false;\r\n this.negativeArrowVisible = false;\r\n\r\n this.range = DEFAULT_RANGE;\r\n this.autoRange = DEFAULT_AUTO_RANGE;\r\n this.defaultAutoRange = DEFAULT_RANGE;\r\n\r\n this.inverted = DEFAULT_INVERTED;\r\n this.autoRangeMinimumSize = DEFAULT_AUTO_RANGE_MINIMUM_SIZE;\r\n\r\n this.lowerMargin = DEFAULT_LOWER_MARGIN;\r\n this.upperMargin = DEFAULT_UPPER_MARGIN;\r\n\r\n this.fixedAutoRange = 0.0;\r\n\r\n this.autoTickUnitSelection = DEFAULT_AUTO_TICK_UNIT_SELECTION;\r\n this.standardTickUnits = standardTickUnits;\r\n\r\n Polygon p1 = new Polygon();\r\n p1.addPoint(0, 0);\r\n p1.addPoint(-2, 2);\r\n p1.addPoint(2, 2);\r\n\r\n this.upArrow = p1;\r\n\r\n Polygon p2 = new Polygon();\r\n p2.addPoint(0, 0);\r\n p2.addPoint(-2, -2);\r\n p2.addPoint(2, -2);\r\n\r\n this.downArrow = p2;\r\n\r\n Polygon p3 = new Polygon();\r\n p3.addPoint(0, 0);\r\n p3.addPoint(-2, -2);\r\n p3.addPoint(-2, 2);\r\n\r\n this.rightArrow = p3;\r\n\r\n Polygon p4 = new Polygon();\r\n p4.addPoint(0, 0);\r\n p4.addPoint(2, -2);\r\n p4.addPoint(2, 2);\r\n\r\n this.leftArrow = p4;\r\n\r\n this.verticalTickLabels = false;\r\n this.minorTickCount = 0;\r\n\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the tick labels should be rotated (to\r\n * vertical), and <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setVerticalTickLabels(boolean)\r\n */\r\n public boolean isVerticalTickLabels() {\r\n return this.verticalTickLabels;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether the tick labels are displayed\r\n * vertically (that is, rotated 90 degrees from horizontal). If the flag\r\n * is changed, an {@link AxisChangeEvent} is sent to all registered\r\n * listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isVerticalTickLabels()\r\n */\r\n public void setVerticalTickLabels(boolean flag) {\r\n if (this.verticalTickLabels != flag) {\r\n this.verticalTickLabels = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not the axis line has an arrow\r\n * drawn that points in the positive direction for the axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setPositiveArrowVisible(boolean)\r\n */\r\n public boolean isPositiveArrowVisible() {\r\n return this.positiveArrowVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not the axis lines has an arrow\r\n * drawn that points in the positive direction for the axis, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isPositiveArrowVisible()\r\n */\r\n public void setPositiveArrowVisible(boolean visible) {\r\n this.positiveArrowVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not the axis line has an arrow\r\n * drawn that points in the negative direction for the axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNegativeArrowVisible(boolean)\r\n */\r\n public boolean isNegativeArrowVisible() {\r\n return this.negativeArrowVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not the axis lines has an arrow\r\n * drawn that points in the negative direction for the axis, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #setNegativeArrowVisible(boolean)\r\n */\r\n public void setNegativeArrowVisible(boolean visible) {\r\n this.negativeArrowVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing upwards at\r\n * the end of an axis line.\r\n *\r\n * @return A shape (never <code>null</code>).\r\n *\r\n * @see #setUpArrow(Shape)\r\n */\r\n public Shape getUpArrow() {\r\n return this.upArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing upwards at\r\n * the end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (<code>null</code> not permitted).\r\n *\r\n * @see #getUpArrow()\r\n */\r\n public void setUpArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.upArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing downwards at\r\n * the end of an axis line.\r\n *\r\n * @return A shape (never <code>null</code>).\r\n *\r\n * @see #setDownArrow(Shape)\r\n */\r\n public Shape getDownArrow() {\r\n return this.downArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing downwards at\r\n * the end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (<code>null</code> not permitted).\r\n *\r\n * @see #getDownArrow()\r\n */\r\n public void setDownArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.downArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing left at the\r\n * end of an axis line.\r\n *\r\n * @return A shape (never <code>null</code>).\r\n *\r\n * @see #setLeftArrow(Shape)\r\n */\r\n public Shape getLeftArrow() {\r\n return this.leftArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing left at the\r\n * end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (<code>null</code> not permitted).\r\n *\r\n * @see #getLeftArrow()\r\n */\r\n public void setLeftArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.leftArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing right at the\r\n * end of an axis line.\r\n *\r\n * @return A shape (never <code>null</code>).\r\n *\r\n * @see #setRightArrow(Shape)\r\n */\r\n public Shape getRightArrow() {\r\n return this.rightArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing rightwards at\r\n * the end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (<code>null</code> not permitted).\r\n *\r\n * @see #getRightArrow()\r\n */\r\n public void setRightArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.rightArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Draws an axis line at the current cursor position and edge.\r\n *\r\n * @param g2 the graphics device ({@code null} not permitted).\r\n * @param cursor the cursor position.\r\n * @param dataArea the data area.\r\n * @param edge the edge.\r\n */\r\n @Override\r\n protected void drawAxisLine(Graphics2D g2, double cursor,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n Line2D axisLine = null;\r\n double c = cursor;\r\n if (edge == RectangleEdge.TOP) {\r\n axisLine = new Line2D.Double(dataArea.getX(), c, dataArea.getMaxX(),\r\n c);\r\n } else if (edge == RectangleEdge.BOTTOM) {\r\n axisLine = new Line2D.Double(dataArea.getX(), c, dataArea.getMaxX(),\r\n c);\r\n } else if (edge == RectangleEdge.LEFT) {\r\n axisLine = new Line2D.Double(c, dataArea.getY(), c, \r\n dataArea.getMaxY());\r\n } else if (edge == RectangleEdge.RIGHT) {\r\n axisLine = new Line2D.Double(c, dataArea.getY(), c,\r\n dataArea.getMaxY());\r\n }\r\n g2.setPaint(getAxisLinePaint());\r\n g2.setStroke(getAxisLineStroke());\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n g2.draw(axisLine);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n\r\n boolean drawUpOrRight = false;\r\n boolean drawDownOrLeft = false;\r\n if (this.positiveArrowVisible) {\r\n if (this.inverted) {\r\n drawDownOrLeft = true;\r\n }\r\n else {\r\n drawUpOrRight = true;\r\n }\r\n }\r\n if (this.negativeArrowVisible) {\r\n if (this.inverted) {\r\n drawUpOrRight = true;\r\n } else {\r\n drawDownOrLeft = true;\r\n }\r\n }\r\n if (drawUpOrRight) {\r\n double x = 0.0;\r\n double y = 0.0;\r\n Shape arrow = null;\r\n if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {\r\n x = dataArea.getMaxX();\r\n y = cursor;\r\n arrow = this.rightArrow;\r\n } else if (edge == RectangleEdge.LEFT\r\n || edge == RectangleEdge.RIGHT) {\r\n x = cursor;\r\n y = dataArea.getMinY();\r\n arrow = this.upArrow;\r\n }\r\n\r\n // draw the arrow...\r\n AffineTransform transformer = new AffineTransform();\r\n transformer.setToTranslation(x, y);\r\n Shape shape = transformer.createTransformedShape(arrow);\r\n g2.fill(shape);\r\n g2.draw(shape);\r\n }\r\n\r\n if (drawDownOrLeft) {\r\n double x = 0.0;\r\n double y = 0.0;\r\n Shape arrow = null;\r\n if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {\r\n x = dataArea.getMinX();\r\n y = cursor;\r\n arrow = this.leftArrow;\r\n } else if (edge == RectangleEdge.LEFT\r\n || edge == RectangleEdge.RIGHT) {\r\n x = cursor;\r\n y = dataArea.getMaxY();\r\n arrow = this.downArrow;\r\n }\r\n\r\n // draw the arrow...\r\n AffineTransform transformer = new AffineTransform();\r\n transformer.setToTranslation(x, y);\r\n Shape shape = transformer.createTransformedShape(arrow);\r\n g2.fill(shape);\r\n g2.draw(shape);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Calculates the anchor point for a tick label.\r\n *\r\n * @param tick the tick.\r\n * @param cursor the cursor.\r\n * @param dataArea the data area.\r\n * @param edge the edge on which the axis is drawn.\r\n *\r\n * @return The x and y coordinates of the anchor point.\r\n */\r\n protected float[] calculateAnchorPoint(ValueTick tick, double cursor,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n RectangleInsets insets = getTickLabelInsets();\r\n float[] result = new float[2];\r\n if (edge == RectangleEdge.TOP) {\r\n result[0] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n result[1] = (float) (cursor - insets.getBottom() - 2.0);\r\n }\r\n else if (edge == RectangleEdge.BOTTOM) {\r\n result[0] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n result[1] = (float) (cursor + insets.getTop() + 2.0);\r\n }\r\n else if (edge == RectangleEdge.LEFT) {\r\n result[0] = (float) (cursor - insets.getLeft() - 2.0);\r\n result[1] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n }\r\n else if (edge == RectangleEdge.RIGHT) {\r\n result[0] = (float) (cursor + insets.getRight() + 2.0);\r\n result[1] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Draws the axis line, tick marks and tick mark labels.\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param cursor the cursor.\r\n * @param plotArea the plot area (<code>null</code> not permitted).\r\n * @param dataArea the data area (<code>null</code> not permitted).\r\n * @param edge the edge that the axis is aligned with (<code>null</code> \r\n * not permitted).\r\n *\r\n * @return The width or height used to draw the axis.\r\n */\r\n protected AxisState drawTickMarksAndLabels(Graphics2D g2,\r\n double cursor, Rectangle2D plotArea, Rectangle2D dataArea,\r\n RectangleEdge edge) {\r\n\r\n AxisState state = new AxisState(cursor);\r\n if (isAxisLineVisible()) {\r\n drawAxisLine(g2, cursor, dataArea, edge);\r\n }\r\n List ticks = refreshTicks(g2, state, dataArea, edge);\r\n state.setTicks(ticks);\r\n g2.setFont(getTickLabelFont());\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if (isTickLabelsVisible()) {\r\n g2.setPaint(getTickLabelPaint());\r\n float[] anchorPoint = calculateAnchorPoint(tick, cursor,\r\n dataArea, edge);\r\n if (tick instanceof LogTick) {\r\n LogTick lt = (LogTick) tick;\r\n if (lt.getAttributedLabel() == null) {\r\n continue;\r\n }\r\n AttrStringUtils.drawRotatedString(lt.getAttributedLabel(), \r\n g2, anchorPoint[0], anchorPoint[1], \r\n tick.getTextAnchor(), tick.getAngle(), \r\n tick.getRotationAnchor());\r\n } else {\r\n if (tick.getText() == null) {\r\n continue;\r\n }\r\n TextUtilities.drawRotatedString(tick.getText(), g2,\r\n anchorPoint[0], anchorPoint[1], \r\n tick.getTextAnchor(), tick.getAngle(), \r\n tick.getRotationAnchor());\r\n }\r\n }\r\n\r\n if ((isTickMarksVisible() && tick.getTickType().equals(\r\n TickType.MAJOR)) || (isMinorTickMarksVisible()\r\n && tick.getTickType().equals(TickType.MINOR))) {\r\n\r\n double ol = (tick.getTickType().equals(TickType.MINOR)) \r\n ? getMinorTickMarkOutsideLength()\r\n : getTickMarkOutsideLength();\r\n\r\n double il = (tick.getTickType().equals(TickType.MINOR)) \r\n ? getMinorTickMarkInsideLength()\r\n : getTickMarkInsideLength();\r\n\r\n float xx = (float) valueToJava2D(tick.getValue(), dataArea,\r\n edge);\r\n Line2D mark = null;\r\n g2.setStroke(getTickMarkStroke());\r\n g2.setPaint(getTickMarkPaint());\r\n if (edge == RectangleEdge.LEFT) {\r\n mark = new Line2D.Double(cursor - ol, xx, cursor + il, xx);\r\n }\r\n else if (edge == RectangleEdge.RIGHT) {\r\n mark = new Line2D.Double(cursor + ol, xx, cursor - il, xx);\r\n }\r\n else if (edge == RectangleEdge.TOP) {\r\n mark = new Line2D.Double(xx, cursor - ol, xx, cursor + il);\r\n }\r\n else if (edge == RectangleEdge.BOTTOM) {\r\n mark = new Line2D.Double(xx, cursor + ol, xx, cursor - il);\r\n }\r\n g2.draw(mark);\r\n }\r\n }\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n \r\n // need to work out the space used by the tick labels...\r\n // so we can update the cursor...\r\n double used = 0.0;\r\n if (isTickLabelsVisible()) {\r\n if (edge == RectangleEdge.LEFT) {\r\n used += findMaximumTickLabelWidth(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorLeft(used);\r\n } else if (edge == RectangleEdge.RIGHT) {\r\n used = findMaximumTickLabelWidth(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorRight(used);\r\n } else if (edge == RectangleEdge.TOP) {\r\n used = findMaximumTickLabelHeight(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorUp(used);\r\n } else if (edge == RectangleEdge.BOTTOM) {\r\n used = findMaximumTickLabelHeight(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorDown(used);\r\n }\r\n }\r\n\r\n return state;\r\n }\r\n\r\n /**\r\n * Returns the space required to draw the axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plot the plot that the axis belongs to.\r\n * @param plotArea the area within which the plot should be drawn.\r\n * @param edge the axis location.\r\n * @param space the space already reserved (for other axes).\r\n *\r\n * @return The space required to draw the axis (including pre-reserved\r\n * space).\r\n */\r\n @Override\r\n public AxisSpace reserveSpace(Graphics2D g2, Plot plot, \r\n Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) {\r\n\r\n // create a new space object if one wasn't supplied...\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // if the axis is not visible, no additional space is required...\r\n if (!isVisible()) {\r\n return space;\r\n }\r\n\r\n // if the axis has a fixed dimension, return it...\r\n double dimension = getFixedDimension();\r\n if (dimension > 0.0) {\r\n space.add(dimension, edge);\r\n return space;\r\n }\r\n\r\n // calculate the max size of the tick labels (if visible)...\r\n double tickLabelHeight = 0.0;\r\n double tickLabelWidth = 0.0;\r\n if (isTickLabelsVisible()) {\r\n g2.setFont(getTickLabelFont());\r\n List ticks = refreshTicks(g2, new AxisState(), plotArea, edge);\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n tickLabelHeight = findMaximumTickLabelHeight(ticks, g2,\r\n plotArea, isVerticalTickLabels());\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n tickLabelWidth = findMaximumTickLabelWidth(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n }\r\n }\r\n\r\n // get the axis label size and update the space object...\r\n Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge);\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n double labelHeight = labelEnclosure.getHeight();\r\n space.add(labelHeight + tickLabelHeight, edge);\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n double labelWidth = labelEnclosure.getWidth();\r\n space.add(labelWidth + tickLabelWidth, edge);\r\n }\r\n\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * A utility method for determining the height of the tallest tick label.\r\n *\r\n * @param ticks the ticks.\r\n * @param g2 the graphics device.\r\n * @param drawArea the area within which the plot and axes should be drawn.\r\n * @param vertical a flag that indicates whether or not the tick labels\r\n * are 'vertical'.\r\n *\r\n * @return The height of the tallest tick label.\r\n */\r\n protected double findMaximumTickLabelHeight(List ticks, Graphics2D g2,\r\n Rectangle2D drawArea, boolean vertical) {\r\n\r\n RectangleInsets insets = getTickLabelInsets();\r\n Font font = getTickLabelFont();\r\n g2.setFont(font);\r\n double maxHeight = 0.0;\r\n if (vertical) {\r\n FontMetrics fm = g2.getFontMetrics(font);\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n Tick tick = (Tick) iterator.next();\r\n Rectangle2D labelBounds = null;\r\n if (tick instanceof LogTick) {\r\n LogTick lt = (LogTick) tick;\r\n if (lt.getAttributedLabel() != null) {\r\n labelBounds = AttrStringUtils.getTextBounds(\r\n lt.getAttributedLabel(), g2);\r\n }\r\n } else if (tick.getText() != null) {\r\n labelBounds = TextUtilities.getTextBounds(\r\n tick.getText(), g2, fm);\r\n }\r\n if (labelBounds != null && labelBounds.getWidth() \r\n + insets.getTop() + insets.getBottom() > maxHeight) {\r\n maxHeight = labelBounds.getWidth()\r\n + insets.getTop() + insets.getBottom();\r\n }\r\n }\r\n } else {\r\n LineMetrics metrics = font.getLineMetrics(\"ABCxyz\",\r\n g2.getFontRenderContext());\r\n maxHeight = metrics.getHeight()\r\n + insets.getTop() + insets.getBottom();\r\n }\r\n return maxHeight;\r\n\r\n }\r\n\r\n /**\r\n * A utility method for determining the width of the widest tick label.\r\n *\r\n * @param ticks the ticks.\r\n * @param g2 the graphics device.\r\n * @param drawArea the area within which the plot and axes should be drawn.\r\n * @param vertical a flag that indicates whether or not the tick labels\r\n * are 'vertical'.\r\n *\r\n * @return The width of the tallest tick label.\r\n */\r\n protected double findMaximumTickLabelWidth(List ticks, Graphics2D g2,\r\n Rectangle2D drawArea, boolean vertical) {\r\n\r\n RectangleInsets insets = getTickLabelInsets();\r\n Font font = getTickLabelFont();\r\n double maxWidth = 0.0;\r\n if (!vertical) {\r\n FontMetrics fm = g2.getFontMetrics(font);\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n Tick tick = (Tick) iterator.next();\r\n Rectangle2D labelBounds = null;\r\n if (tick instanceof LogTick) {\r\n LogTick lt = (LogTick) tick;\r\n if (lt.getAttributedLabel() != null) {\r\n labelBounds = AttrStringUtils.getTextBounds(\r\n lt.getAttributedLabel(), g2);\r\n }\r\n } else if (tick.getText() != null) {\r\n labelBounds = TextUtilities.getTextBounds(tick.getText(), \r\n g2, fm);\r\n }\r\n if (labelBounds != null \r\n && labelBounds.getWidth() + insets.getLeft()\r\n + insets.getRight() > maxWidth) {\r\n maxWidth = labelBounds.getWidth()\r\n + insets.getLeft() + insets.getRight();\r\n }\r\n }\r\n } else {\r\n LineMetrics metrics = font.getLineMetrics(\"ABCxyz\",\r\n g2.getFontRenderContext());\r\n maxWidth = metrics.getHeight()\r\n + insets.getTop() + insets.getBottom();\r\n }\r\n return maxWidth;\r\n\r\n }\r\n\r\n /**\r\n * Returns a flag that controls the direction of values on the axis.\r\n * <P>\r\n * For a regular axis, values increase from left to right (for a horizontal\r\n * axis) and bottom to top (for a vertical axis). When the axis is\r\n * 'inverted', the values increase in the opposite direction.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setInverted(boolean)\r\n */\r\n public boolean isInverted() {\r\n return this.inverted;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls the direction of values on the axis, and\r\n * notifies registered listeners that the axis has changed.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isInverted()\r\n */\r\n public void setInverted(boolean flag) {\r\n if (this.inverted != flag) {\r\n this.inverted = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the axis range is\r\n * automatically adjusted to fit the data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAutoRange(boolean)\r\n */\r\n public boolean isAutoRange() {\r\n return this.autoRange;\r\n }\r\n\r\n /**\r\n * Sets a flag that determines whether or not the axis range is\r\n * automatically adjusted to fit the data, and notifies registered\r\n * listeners that the axis has been modified.\r\n *\r\n * @param auto the new value of the flag.\r\n *\r\n * @see #isAutoRange()\r\n */\r\n public void setAutoRange(boolean auto) {\r\n setAutoRange(auto, true);\r\n }\r\n\r\n /**\r\n * Sets the auto range attribute. If the <code>notify</code> flag is set,\r\n * an {@link AxisChangeEvent} is sent to registered listeners.\r\n *\r\n * @param auto the flag.\r\n * @param notify notify listeners?\r\n *\r\n * @see #isAutoRange()\r\n */\r\n protected void setAutoRange(boolean auto, boolean notify) {\r\n if (this.autoRange != auto) {\r\n this.autoRange = auto;\r\n if (this.autoRange) {\r\n autoAdjustRange();\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the minimum size allowed for the axis range when it is\r\n * automatically calculated.\r\n *\r\n * @return The minimum range.\r\n *\r\n * @see #setAutoRangeMinimumSize(double)\r\n */\r\n public double getAutoRangeMinimumSize() {\r\n return this.autoRangeMinimumSize;\r\n }\r\n\r\n /**\r\n * Sets the auto range minimum size and sends an {@link AxisChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param size the size.\r\n *\r\n * @see #getAutoRangeMinimumSize()\r\n */\r\n public void setAutoRangeMinimumSize(double size) {\r\n setAutoRangeMinimumSize(size, true);\r\n }\r\n\r\n /**\r\n * Sets the minimum size allowed for the axis range when it is\r\n * automatically calculated.\r\n * <p>\r\n * If requested, an {@link AxisChangeEvent} is forwarded to all registered\r\n * listeners.\r\n *\r\n * @param size the new minimum.\r\n * @param notify notify listeners?\r\n */\r\n public void setAutoRangeMinimumSize(double size, boolean notify) {\r\n if (size <= 0.0) {\r\n throw new IllegalArgumentException(\r\n \"NumberAxis.setAutoRangeMinimumSize(double): must be > 0.0.\");\r\n }\r\n if (this.autoRangeMinimumSize != size) {\r\n this.autoRangeMinimumSize = size;\r\n if (this.autoRange) {\r\n autoAdjustRange();\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the default auto range.\r\n *\r\n * @return The default auto range (never <code>null</code>).\r\n *\r\n * @see #setDefaultAutoRange(Range)\r\n *\r\n * @since 1.0.5\r\n */\r\n public Range getDefaultAutoRange() {\r\n return this.defaultAutoRange;\r\n }\r\n\r\n /**\r\n * Sets the default auto range and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n *\r\n * @see #getDefaultAutoRange()\r\n *\r\n * @since 1.0.5\r\n */\r\n public void setDefaultAutoRange(Range range) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n this.defaultAutoRange = range;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the lower margin for the axis, expressed as a percentage of the\r\n * axis range. This controls the space added to the lower end of the axis\r\n * when the axis range is automatically calculated (it is ignored when the\r\n * axis range is set explicitly). The default value is 0.05 (five percent).\r\n *\r\n * @return The lower margin.\r\n *\r\n * @see #setLowerMargin(double)\r\n */\r\n public double getLowerMargin() {\r\n return this.lowerMargin;\r\n }\r\n\r\n /**\r\n * Sets the lower margin for the axis (as a percentage of the axis range)\r\n * and sends an {@link AxisChangeEvent} to all registered listeners. This\r\n * margin is added only when the axis range is auto-calculated - if you set\r\n * the axis range manually, the margin is ignored.\r\n *\r\n * @param margin the margin percentage (for example, 0.05 is five percent).\r\n *\r\n * @see #getLowerMargin()\r\n * @see #setUpperMargin(double)\r\n */\r\n public void setLowerMargin(double margin) {\r\n this.lowerMargin = margin;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the upper margin for the axis, expressed as a percentage of the\r\n * axis range. This controls the space added to the lower end of the axis\r\n * when the axis range is automatically calculated (it is ignored when the\r\n * axis range is set explicitly). The default value is 0.05 (five percent).\r\n *\r\n * @return The upper margin.\r\n *\r\n * @see #setUpperMargin(double)\r\n */\r\n public double getUpperMargin() {\r\n return this.upperMargin;\r\n }\r\n\r\n /**\r\n * Sets the upper margin for the axis (as a percentage of the axis range)\r\n * and sends an {@link AxisChangeEvent} to all registered listeners. This\r\n * margin is added only when the axis range is auto-calculated - if you set\r\n * the axis range manually, the margin is ignored.\r\n *\r\n * @param margin the margin percentage (for example, 0.05 is five percent).\r\n *\r\n * @see #getLowerMargin()\r\n * @see #setLowerMargin(double)\r\n */\r\n public void setUpperMargin(double margin) {\r\n this.upperMargin = margin;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the fixed auto range.\r\n *\r\n * @return The length.\r\n *\r\n * @see #setFixedAutoRange(double)\r\n */\r\n public double getFixedAutoRange() {\r\n return this.fixedAutoRange;\r\n }\r\n\r\n /**\r\n * Sets the fixed auto range for the axis.\r\n *\r\n * @param length the range length.\r\n *\r\n * @see #getFixedAutoRange()\r\n */\r\n public void setFixedAutoRange(double length) {\r\n this.fixedAutoRange = length;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the lower bound of the axis range.\r\n *\r\n * @return The lower bound.\r\n *\r\n * @see #setLowerBound(double)\r\n */\r\n public double getLowerBound() {\r\n return this.range.getLowerBound();\r\n }\r\n\r\n /**\r\n * Sets the lower bound for the axis range. An {@link AxisChangeEvent} is\r\n * sent to all registered listeners.\r\n *\r\n * @param min the new minimum.\r\n *\r\n * @see #getLowerBound()\r\n */\r\n public void setLowerBound(double min) {\r\n if (this.range.getUpperBound() > min) {\r\n setRange(new Range(min, this.range.getUpperBound()));\r\n }\r\n else {\r\n setRange(new Range(min, min + 1.0));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the upper bound for the axis range.\r\n *\r\n * @return The upper bound.\r\n *\r\n * @see #setUpperBound(double)\r\n */\r\n public double getUpperBound() {\r\n return this.range.getUpperBound();\r\n }\r\n\r\n /**\r\n * Sets the upper bound for the axis range, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param max the new maximum.\r\n *\r\n * @see #getUpperBound()\r\n */\r\n public void setUpperBound(double max) {\r\n if (this.range.getLowerBound() < max) {\r\n setRange(new Range(this.range.getLowerBound(), max));\r\n }\r\n else {\r\n setRange(max - 1.0, max);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range for the axis.\r\n *\r\n * @return The axis range (never <code>null</code>).\r\n *\r\n * @see #setRange(Range)\r\n */\r\n public Range getRange() {\r\n return this.range;\r\n }\r\n\r\n /**\r\n * Sets the range for the axis and sends a change event to all registered \r\n * listeners. As a side-effect, the auto-range flag is set to\r\n * <code>false</code>.\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n *\r\n * @see #getRange()\r\n */\r\n public void setRange(Range range) {\r\n // defer argument checking\r\n setRange(range, true, true);\r\n }\r\n\r\n /**\r\n * Sets the range for the axis and, if requested, sends a change event to \r\n * all registered listeners. Furthermore, if <code>turnOffAutoRange</code>\r\n * is <code>true</code>, the auto-range flag is set to <code>false</code> \r\n * (normally when setting the axis range manually the caller expects that\r\n * range to remain in force).\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n * @param turnOffAutoRange a flag that controls whether or not the auto\r\n * range is turned off.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n *\r\n * @see #getRange()\r\n */\r\n public void setRange(Range range, boolean turnOffAutoRange, \r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n if (range.getLength() <= 0.0) {\r\n throw new IllegalArgumentException(\r\n \"A positive range length is required: \" + range);\r\n }\r\n if (turnOffAutoRange) {\r\n this.autoRange = false;\r\n }\r\n this.range = range;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the range for the axis and sends a change event to all registered \r\n * listeners. As a side-effect, the auto-range flag is set to\r\n * <code>false</code>.\r\n *\r\n * @param lower the lower axis limit.\r\n * @param upper the upper axis limit.\r\n *\r\n * @see #getRange()\r\n * @see #setRange(Range)\r\n */\r\n public void setRange(double lower, double upper) {\r\n setRange(new Range(lower, upper));\r\n }\r\n\r\n /**\r\n * Sets the range for the axis (after first adding the current margins to\r\n * the specified range) and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n */\r\n public void setRangeWithMargins(Range range) {\r\n setRangeWithMargins(range, true, true);\r\n }\r\n\r\n /**\r\n * Sets the range for the axis after first adding the current margins to\r\n * the range and, if requested, sends an {@link AxisChangeEvent} to all\r\n * registered listeners. As a side-effect, the auto-range flag is set to\r\n * <code>false</code> (optional).\r\n *\r\n * @param range the range (excluding margins, <code>null</code> not\r\n * permitted).\r\n * @param turnOffAutoRange a flag that controls whether or not the auto\r\n * range is turned off.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n */\r\n public void setRangeWithMargins(Range range, boolean turnOffAutoRange,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n setRange(Range.expand(range, getLowerMargin(), getUpperMargin()),\r\n turnOffAutoRange, notify);\r\n }\r\n\r\n /**\r\n * Sets the axis range (after first adding the current margins to the\r\n * range) and sends an {@link AxisChangeEvent} to all registered listeners.\r\n * As a side-effect, the auto-range flag is set to <code>false</code>.\r\n *\r\n * @param lower the lower axis limit.\r\n * @param upper the upper axis limit.\r\n */\r\n public void setRangeWithMargins(double lower, double upper) {\r\n setRangeWithMargins(new Range(lower, upper));\r\n }\r\n\r\n /**\r\n * Sets the axis range, where the new range is 'size' in length, and\r\n * centered on 'value'.\r\n *\r\n * @param value the central value.\r\n * @param length the range length.\r\n */\r\n public void setRangeAboutValue(double value, double length) {\r\n setRange(new Range(value - length / 2, value + length / 2));\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the tick unit is automatically\r\n * selected from a range of standard tick units.\r\n *\r\n * @return A flag indicating whether or not the tick unit is automatically\r\n * selected.\r\n *\r\n * @see #setAutoTickUnitSelection(boolean)\r\n */\r\n public boolean isAutoTickUnitSelection() {\r\n return this.autoTickUnitSelection;\r\n }\r\n\r\n /**\r\n * Sets a flag indicating whether or not the tick unit is automatically\r\n * selected from a range of standard tick units. If the flag is changed,\r\n * registered listeners are notified that the chart has changed.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isAutoTickUnitSelection()\r\n */\r\n public void setAutoTickUnitSelection(boolean flag) {\r\n setAutoTickUnitSelection(flag, true);\r\n }\r\n\r\n /**\r\n * Sets a flag indicating whether or not the tick unit is automatically\r\n * selected from a range of standard tick units.\r\n *\r\n * @param flag the new value of the flag.\r\n * @param notify notify listeners?\r\n *\r\n * @see #isAutoTickUnitSelection()\r\n */\r\n public void setAutoTickUnitSelection(boolean flag, boolean notify) {\r\n\r\n if (this.autoTickUnitSelection != flag) {\r\n this.autoTickUnitSelection = flag;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the source for obtaining standard tick units for the axis.\r\n *\r\n * @return The source (possibly <code>null</code>).\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n */\r\n public TickUnitSource getStandardTickUnits() {\r\n return this.standardTickUnits;\r\n }\r\n\r\n /**\r\n * Sets the source for obtaining standard tick units for the axis and sends\r\n * an {@link AxisChangeEvent} to all registered listeners. The axis will\r\n * try to select the smallest tick unit from the source that does not cause\r\n * the tick labels to overlap (see also the\r\n * {@link #setAutoTickUnitSelection(boolean)} method.\r\n *\r\n * @param source the source for standard tick units (<code>null</code>\r\n * permitted).\r\n *\r\n * @see #getStandardTickUnits()\r\n */\r\n public void setStandardTickUnits(TickUnitSource source) {\r\n this.standardTickUnits = source;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the number of minor tick marks to display.\r\n *\r\n * @return The number of minor tick marks to display.\r\n *\r\n * @see #setMinorTickCount(int)\r\n *\r\n * @since 1.0.12\r\n */\r\n public int getMinorTickCount() {\r\n return this.minorTickCount;\r\n }\r\n\r\n /**\r\n * Sets the number of minor tick marks to display, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param count the count.\r\n *\r\n * @see #getMinorTickCount()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setMinorTickCount(int count) {\r\n this.minorTickCount = count;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Converts a data value to a coordinate in Java2D space, assuming that the\r\n * axis runs along one edge of the specified dataArea.\r\n * <p>\r\n * Note that it is possible for the coordinate to fall outside the area.\r\n *\r\n * @param value the data value.\r\n * @param area the area for plotting the data.\r\n * @param edge the edge along which the axis lies.\r\n *\r\n * @return The Java2D coordinate.\r\n *\r\n * @see #java2DToValue(double, Rectangle2D, RectangleEdge)\r\n */\r\n public abstract double valueToJava2D(double value, Rectangle2D area,\r\n RectangleEdge edge);\r\n\r\n /**\r\n * Converts a length in data coordinates into the corresponding length in\r\n * Java2D coordinates.\r\n *\r\n * @param length the length.\r\n * @param area the plot area.\r\n * @param edge the edge along which the axis lies.\r\n *\r\n * @return The length in Java2D coordinates.\r\n */\r\n public double lengthToJava2D(double length, Rectangle2D area,\r\n RectangleEdge edge) {\r\n double zero = valueToJava2D(0.0, area, edge);\r\n double l = valueToJava2D(length, area, edge);\r\n return Math.abs(l - zero);\r\n }\r\n\r\n /**\r\n * Converts a coordinate in Java2D space to the corresponding data value,\r\n * assuming that the axis runs along one edge of the specified dataArea.\r\n *\r\n * @param java2DValue the coordinate in Java2D space.\r\n * @param area the area in which the data is plotted.\r\n * @param edge the edge along which the axis lies.\r\n *\r\n * @return The data value.\r\n *\r\n * @see #valueToJava2D(double, Rectangle2D, RectangleEdge)\r\n */\r\n public abstract double java2DToValue(double java2DValue, Rectangle2D area, \r\n RectangleEdge edge);\r\n\r\n /**\r\n * Automatically sets the axis range to fit the range of values in the\r\n * dataset. Sometimes this can depend on the renderer used as well (for\r\n * example, the renderer may \"stack\" values, requiring an axis range\r\n * greater than otherwise necessary).\r\n */\r\n protected abstract void autoAdjustRange();\r\n\r\n /**\r\n * Centers the axis range about the specified value and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param value the center value.\r\n */\r\n public void centerRange(double value) {\r\n double central = this.range.getCentralValue();\r\n Range adjusted = new Range(this.range.getLowerBound() + value - central,\r\n this.range.getUpperBound() + value - central);\r\n setRange(adjusted);\r\n }\r\n\r\n /**\r\n * Increases or decreases the axis range by the specified percentage about\r\n * the central value and sends an {@link AxisChangeEvent} to all registered\r\n * listeners.\r\n * <P>\r\n * To double the length of the axis range, use 200% (2.0).\r\n * To halve the length of the axis range, use 50% (0.5).\r\n *\r\n * @param percent the resize factor.\r\n *\r\n * @see #resizeRange(double, double)\r\n */\r\n public void resizeRange(double percent) {\r\n resizeRange(percent, this.range.getCentralValue());\r\n }\r\n\r\n /**\r\n * Increases or decreases the axis range by the specified percentage about\r\n * the specified anchor value and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n * <P>\r\n * To double the length of the axis range, use 200% (2.0).\r\n * To halve the length of the axis range, use 50% (0.5).\r\n *\r\n * @param percent the resize factor.\r\n * @param anchorValue the new central value after the resize.\r\n *\r\n * @see #resizeRange(double)\r\n */\r\n public void resizeRange(double percent, double anchorValue) {\r\n if (percent > 0.0) {\r\n double halfLength = this.range.getLength() * percent / 2;\r\n Range adjusted = new Range(anchorValue - halfLength,\r\n anchorValue + halfLength);\r\n setRange(adjusted);\r\n }\r\n else {\r\n setAutoRange(true);\r\n }\r\n }\r\n\r\n /**\r\n * Increases or decreases the axis range by the specified percentage about\r\n * the specified anchor value and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n * <P>\r\n * To double the length of the axis range, use 200% (2.0).\r\n * To halve the length of the axis range, use 50% (0.5).\r\n *\r\n * @param percent the resize factor.\r\n * @param anchorValue the new central value after the resize.\r\n *\r\n * @see #resizeRange(double)\r\n *\r\n * @since 1.0.13\r\n */\r\n public void resizeRange2(double percent, double anchorValue) {\r\n if (percent > 0.0) {\r\n double left = anchorValue - getLowerBound();\r\n double right = getUpperBound() - anchorValue;\r\n Range adjusted = new Range(anchorValue - left * percent,\r\n anchorValue + right * percent);\r\n setRange(adjusted);\r\n }\r\n else {\r\n setAutoRange(true);\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the current range.\r\n *\r\n * @param lowerPercent the new lower bound.\r\n * @param upperPercent the new upper bound.\r\n */\r\n public void zoomRange(double lowerPercent, double upperPercent) {\r\n double start = this.range.getLowerBound();\r\n double length = this.range.getLength();\r\n double r0, r1;\r\n if (isInverted()) {\r\n r0 = start + (length * (1 - upperPercent));\r\n r1 = start + (length * (1 - lowerPercent));\r\n }\r\n else {\r\n r0 = start + length * lowerPercent;\r\n r1 = start + length * upperPercent;\r\n }\r\n if ((r1 > r0) && !Double.isInfinite(r1 - r0)) {\r\n setRange(new Range(r0, r1));\r\n }\r\n }\r\n\r\n /**\r\n * Slides the axis range by the specified percentage.\r\n *\r\n * @param percent the percentage.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void pan(double percent) {\r\n Range r = getRange();\r\n double length = range.getLength();\r\n double adj = length * percent;\r\n double lower = r.getLowerBound() + adj;\r\n double upper = r.getUpperBound() + adj;\r\n setRange(lower, upper);\r\n }\r\n\r\n /**\r\n * Returns the auto tick index.\r\n *\r\n * @return The auto tick index.\r\n *\r\n * @see #setAutoTickIndex(int)\r\n */\r\n protected int getAutoTickIndex() {\r\n return this.autoTickIndex;\r\n }\r\n\r\n /**\r\n * Sets the auto tick index.\r\n *\r\n * @param index the new value.\r\n *\r\n * @see #getAutoTickIndex()\r\n */\r\n protected void setAutoTickIndex(int index) {\r\n this.autoTickIndex = index;\r\n }\r\n\r\n /**\r\n * Tests the axis for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof ValueAxis)) {\r\n return false;\r\n }\r\n ValueAxis that = (ValueAxis) obj;\r\n if (this.positiveArrowVisible != that.positiveArrowVisible) {\r\n return false;\r\n }\r\n if (this.negativeArrowVisible != that.negativeArrowVisible) {\r\n return false;\r\n }\r\n if (this.inverted != that.inverted) {\r\n return false;\r\n }\r\n // if autoRange is true, then the current range is irrelevant\r\n if (!this.autoRange && !ObjectUtilities.equal(this.range, that.range)) {\r\n return false;\r\n }\r\n if (this.autoRange != that.autoRange) {\r\n return false;\r\n }\r\n if (this.autoRangeMinimumSize != that.autoRangeMinimumSize) {\r\n return false;\r\n }\r\n if (!this.defaultAutoRange.equals(that.defaultAutoRange)) {\r\n return false;\r\n }\r\n if (this.upperMargin != that.upperMargin) {\r\n return false;\r\n }\r\n if (this.lowerMargin != that.lowerMargin) {\r\n return false;\r\n }\r\n if (this.fixedAutoRange != that.fixedAutoRange) {\r\n return false;\r\n }\r\n if (this.autoTickUnitSelection != that.autoTickUnitSelection) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.standardTickUnits,\r\n that.standardTickUnits)) {\r\n return false;\r\n }\r\n if (this.verticalTickLabels != that.verticalTickLabels) {\r\n return false;\r\n }\r\n if (this.minorTickCount != that.minorTickCount) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a clone of the object.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if some component of the axis does\r\n * not support cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n ValueAxis clone = (ValueAxis) super.clone();\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeShape(this.upArrow, stream);\r\n SerialUtilities.writeShape(this.downArrow, stream);\r\n SerialUtilities.writeShape(this.leftArrow, stream);\r\n SerialUtilities.writeShape(this.rightArrow, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n\r\n stream.defaultReadObject();\r\n this.upArrow = SerialUtilities.readShape(stream);\r\n this.downArrow = SerialUtilities.readShape(stream);\r\n this.leftArrow = SerialUtilities.readShape(stream);\r\n this.rightArrow = SerialUtilities.readShape(stream);\r\n }\r\n\r\n}\r" }, { "identifier": "AnnotationChangeEvent", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/event/AnnotationChangeEvent.java", "snippet": "public class AnnotationChangeEvent extends ChartChangeEvent {\r\n\r\n /** The annotation that generated the event. */\r\n private Annotation annotation;\r\n\r\n /**\r\n * Creates a new <code>AnnotationChangeEvent</code> instance.\r\n *\r\n * @param source the event source.\r\n * @param annotation the annotation that triggered the event\r\n * (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n public AnnotationChangeEvent(Object source, Annotation annotation) {\r\n super(source);\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n this.annotation = annotation;\r\n }\r\n\r\n /**\r\n * Returns the annotation that triggered the event.\r\n *\r\n * @return The annotation that triggered the event (never <code>null</code>).\r\n *\r\n * @since 1.0.14\r\n */\r\n public Annotation getAnnotation() {\r\n return this.annotation;\r\n }\r\n\r\n}\r" }, { "identifier": "Plot", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/Plot.java", "snippet": "public abstract class Plot implements AxisChangeListener,\r\n DatasetChangeListener, AnnotationChangeListener, MarkerChangeListener,\r\n LegendItemSource, PublicCloneable, Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -8831571430103671324L;\r\n\r\n /** Useful constant representing zero. */\r\n public static final Number ZERO = new Integer(0);\r\n\r\n /** The default insets. */\r\n public static final RectangleInsets DEFAULT_INSETS\r\n = new RectangleInsets(4.0, 8.0, 4.0, 8.0);\r\n\r\n /** The default outline stroke. */\r\n public static final Stroke DEFAULT_OUTLINE_STROKE = new BasicStroke(0.5f,\r\n BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);\r\n\r\n /** The default outline color. */\r\n public static final Paint DEFAULT_OUTLINE_PAINT = Color.gray;\r\n\r\n /** The default foreground alpha transparency. */\r\n public static final float DEFAULT_FOREGROUND_ALPHA = 1.0f;\r\n\r\n /** The default background alpha transparency. */\r\n public static final float DEFAULT_BACKGROUND_ALPHA = 1.0f;\r\n\r\n /** The default background color. */\r\n public static final Paint DEFAULT_BACKGROUND_PAINT = Color.white;\r\n\r\n /** The minimum width at which the plot should be drawn. */\r\n public static final int MINIMUM_WIDTH_TO_DRAW = 10;\r\n\r\n /** The minimum height at which the plot should be drawn. */\r\n public static final int MINIMUM_HEIGHT_TO_DRAW = 10;\r\n\r\n /** A default box shape for legend items. */\r\n public static final Shape DEFAULT_LEGEND_ITEM_BOX\r\n = new Rectangle2D.Double(-4.0, -4.0, 8.0, 8.0);\r\n\r\n /** A default circle shape for legend items. */\r\n public static final Shape DEFAULT_LEGEND_ITEM_CIRCLE\r\n = new Ellipse2D.Double(-4.0, -4.0, 8.0, 8.0);\r\n\r\n /** The parent plot (<code>null</code> if this is the root plot). */\r\n private Plot parent;\r\n\r\n /** The dataset group (to be used for thread synchronisation). */\r\n private DatasetGroup datasetGroup;\r\n\r\n /** The message to display if no data is available. */\r\n private String noDataMessage;\r\n\r\n /** The font used to display the 'no data' message. */\r\n private Font noDataMessageFont;\r\n\r\n /** The paint used to draw the 'no data' message. */\r\n private transient Paint noDataMessagePaint;\r\n\r\n /** Amount of blank space around the plot area. */\r\n private RectangleInsets insets;\r\n\r\n /**\r\n * A flag that controls whether or not the plot outline is drawn.\r\n *\r\n * @since 1.0.6\r\n */\r\n private boolean outlineVisible;\r\n\r\n /** The Stroke used to draw an outline around the plot. */\r\n private transient Stroke outlineStroke;\r\n\r\n /** The Paint used to draw an outline around the plot. */\r\n private transient Paint outlinePaint;\r\n\r\n /** An optional color used to fill the plot background. */\r\n private transient Paint backgroundPaint;\r\n\r\n /** An optional image for the plot background. */\r\n private transient Image backgroundImage; // not currently serialized\r\n\r\n /** The alignment for the background image. */\r\n private int backgroundImageAlignment = Align.FIT;\r\n\r\n /** The alpha value used to draw the background image. */\r\n private float backgroundImageAlpha = 0.5f;\r\n\r\n /** The alpha-transparency for the plot. */\r\n private float foregroundAlpha;\r\n\r\n /** The alpha transparency for the background paint. */\r\n private float backgroundAlpha;\r\n\r\n /** The drawing supplier. */\r\n private DrawingSupplier drawingSupplier;\r\n\r\n /** Storage for registered change listeners. */\r\n private transient EventListenerList listenerList;\r\n\r\n /**\r\n * A flag that controls whether or not the plot will notify listeners\r\n * of changes (defaults to true, but sometimes it is useful to disable\r\n * this).\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean notify;\r\n\r\n /**\r\n * Creates a new plot.\r\n */\r\n protected Plot() {\r\n\r\n this.parent = null;\r\n this.insets = DEFAULT_INSETS;\r\n this.backgroundPaint = DEFAULT_BACKGROUND_PAINT;\r\n this.backgroundAlpha = DEFAULT_BACKGROUND_ALPHA;\r\n this.backgroundImage = null;\r\n this.outlineVisible = true;\r\n this.outlineStroke = DEFAULT_OUTLINE_STROKE;\r\n this.outlinePaint = DEFAULT_OUTLINE_PAINT;\r\n this.foregroundAlpha = DEFAULT_FOREGROUND_ALPHA;\r\n\r\n this.noDataMessage = null;\r\n this.noDataMessageFont = new Font(\"SansSerif\", Font.PLAIN, 12);\r\n this.noDataMessagePaint = Color.black;\r\n\r\n this.drawingSupplier = new DefaultDrawingSupplier();\r\n\r\n this.notify = true;\r\n this.listenerList = new EventListenerList();\r\n\r\n }\r\n\r\n /**\r\n * Returns the dataset group for the plot (not currently used).\r\n *\r\n * @return The dataset group.\r\n *\r\n * @see #setDatasetGroup(DatasetGroup)\r\n */\r\n public DatasetGroup getDatasetGroup() {\r\n return this.datasetGroup;\r\n }\r\n\r\n /**\r\n * Sets the dataset group (not currently used).\r\n *\r\n * @param group the dataset group (<code>null</code> permitted).\r\n *\r\n * @see #getDatasetGroup()\r\n */\r\n protected void setDatasetGroup(DatasetGroup group) {\r\n this.datasetGroup = group;\r\n }\r\n\r\n /**\r\n * Returns the string that is displayed when the dataset is empty or\r\n * <code>null</code>.\r\n *\r\n * @return The 'no data' message (<code>null</code> possible).\r\n *\r\n * @see #setNoDataMessage(String)\r\n * @see #getNoDataMessageFont()\r\n * @see #getNoDataMessagePaint()\r\n */\r\n public String getNoDataMessage() {\r\n return this.noDataMessage;\r\n }\r\n\r\n /**\r\n * Sets the message that is displayed when the dataset is empty or\r\n * <code>null</code>, and sends a {@link PlotChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param message the message (<code>null</code> permitted).\r\n *\r\n * @see #getNoDataMessage()\r\n */\r\n public void setNoDataMessage(String message) {\r\n this.noDataMessage = message;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the font used to display the 'no data' message.\r\n *\r\n * @return The font (never <code>null</code>).\r\n *\r\n * @see #setNoDataMessageFont(Font)\r\n * @see #getNoDataMessage()\r\n */\r\n public Font getNoDataMessageFont() {\r\n return this.noDataMessageFont;\r\n }\r\n\r\n /**\r\n * Sets the font used to display the 'no data' message and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param font the font (<code>null</code> not permitted).\r\n *\r\n * @see #getNoDataMessageFont()\r\n */\r\n public void setNoDataMessageFont(Font font) {\r\n ParamChecks.nullNotPermitted(font, \"font\");\r\n this.noDataMessageFont = font;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used to display the 'no data' message.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setNoDataMessagePaint(Paint)\r\n * @see #getNoDataMessage()\r\n */\r\n public Paint getNoDataMessagePaint() {\r\n return this.noDataMessagePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to display the 'no data' message and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getNoDataMessagePaint()\r\n */\r\n public void setNoDataMessagePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.noDataMessagePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a short string describing the plot type.\r\n * <P>\r\n * Note: this gets used in the chart property editing user interface,\r\n * but there needs to be a better mechanism for identifying the plot type.\r\n *\r\n * @return A short string describing the plot type (never\r\n * <code>null</code>).\r\n */\r\n public abstract String getPlotType();\r\n\r\n /**\r\n * Returns the parent plot (or <code>null</code> if this plot is not part\r\n * of a combined plot).\r\n *\r\n * @return The parent plot.\r\n *\r\n * @see #setParent(Plot)\r\n * @see #getRootPlot()\r\n */\r\n public Plot getParent() {\r\n return this.parent;\r\n }\r\n\r\n /**\r\n * Sets the parent plot. This method is intended for internal use, you\r\n * shouldn't need to call it directly.\r\n *\r\n * @param parent the parent plot (<code>null</code> permitted).\r\n *\r\n * @see #getParent()\r\n */\r\n public void setParent(Plot parent) {\r\n this.parent = parent;\r\n }\r\n\r\n /**\r\n * Returns the root plot.\r\n *\r\n * @return The root plot.\r\n *\r\n * @see #getParent()\r\n */\r\n public Plot getRootPlot() {\r\n\r\n Plot p = getParent();\r\n if (p == null) {\r\n return this;\r\n }\r\n return p.getRootPlot();\r\n\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this plot is part of a combined plot\r\n * structure (that is, {@link #getParent()} returns a non-<code>null</code>\r\n * value), and <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> if this plot is part of a combined plot\r\n * structure.\r\n *\r\n * @see #getParent()\r\n */\r\n public boolean isSubplot() {\r\n return (getParent() != null);\r\n }\r\n\r\n /**\r\n * Returns the insets for the plot area.\r\n *\r\n * @return The insets (never <code>null</code>).\r\n *\r\n * @see #setInsets(RectangleInsets)\r\n */\r\n public RectangleInsets getInsets() {\r\n return this.insets;\r\n }\r\n\r\n /**\r\n * Sets the insets for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param insets the new insets (<code>null</code> not permitted).\r\n *\r\n * @see #getInsets()\r\n * @see #setInsets(RectangleInsets, boolean)\r\n */\r\n public void setInsets(RectangleInsets insets) {\r\n setInsets(insets, true);\r\n }\r\n\r\n /**\r\n * Sets the insets for the plot and, if requested, and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param insets the new insets (<code>null</code> not permitted).\r\n * @param notify a flag that controls whether the registered listeners are\r\n * notified.\r\n *\r\n * @see #getInsets()\r\n * @see #setInsets(RectangleInsets)\r\n */\r\n public void setInsets(RectangleInsets insets, boolean notify) {\r\n ParamChecks.nullNotPermitted(insets, \"insets\");\r\n if (!this.insets.equals(insets)) {\r\n this.insets = insets;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background color of the plot area.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundPaint(Paint)\r\n */\r\n public Paint getBackgroundPaint() {\r\n return this.backgroundPaint;\r\n }\r\n\r\n /**\r\n * Sets the background color of the plot area and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundPaint()\r\n */\r\n public void setBackgroundPaint(Paint paint) {\r\n\r\n if (paint == null) {\r\n if (this.backgroundPaint != null) {\r\n this.backgroundPaint = null;\r\n fireChangeEvent();\r\n }\r\n }\r\n else {\r\n if (this.backgroundPaint != null) {\r\n if (this.backgroundPaint.equals(paint)) {\r\n return; // nothing to do\r\n }\r\n }\r\n this.backgroundPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the alpha transparency of the plot area background.\r\n *\r\n * @return The alpha transparency.\r\n *\r\n * @see #setBackgroundAlpha(float)\r\n */\r\n public float getBackgroundAlpha() {\r\n return this.backgroundAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha transparency of the plot area background, and notifies\r\n * registered listeners that the plot has been modified.\r\n *\r\n * @param alpha the new alpha value (in the range 0.0f to 1.0f).\r\n *\r\n * @see #getBackgroundAlpha()\r\n */\r\n public void setBackgroundAlpha(float alpha) {\r\n if (this.backgroundAlpha != alpha) {\r\n this.backgroundAlpha = alpha;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the drawing supplier for the plot.\r\n *\r\n * @return The drawing supplier (possibly <code>null</code>).\r\n *\r\n * @see #setDrawingSupplier(DrawingSupplier)\r\n */\r\n public DrawingSupplier getDrawingSupplier() {\r\n DrawingSupplier result;\r\n Plot p = getParent();\r\n if (p != null) {\r\n result = p.getDrawingSupplier();\r\n }\r\n else {\r\n result = this.drawingSupplier;\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the drawing supplier for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. The drawing\r\n * supplier is responsible for supplying a limitless (possibly repeating)\r\n * sequence of <code>Paint</code>, <code>Stroke</code> and\r\n * <code>Shape</code> objects that the plot's renderer(s) can use to\r\n * populate its (their) tables.\r\n *\r\n * @param supplier the new supplier.\r\n *\r\n * @see #getDrawingSupplier()\r\n */\r\n public void setDrawingSupplier(DrawingSupplier supplier) {\r\n this.drawingSupplier = supplier;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Sets the drawing supplier for the plot and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners. The drawing\r\n * supplier is responsible for supplying a limitless (possibly repeating)\r\n * sequence of <code>Paint</code>, <code>Stroke</code> and\r\n * <code>Shape</code> objects that the plot's renderer(s) can use to\r\n * populate its (their) tables.\r\n *\r\n * @param supplier the new supplier.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDrawingSupplier()\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setDrawingSupplier(DrawingSupplier supplier, boolean notify) {\r\n this.drawingSupplier = supplier;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the background image that is used to fill the plot's background\r\n * area.\r\n *\r\n * @return The image (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundImage(Image)\r\n */\r\n public Image getBackgroundImage() {\r\n return this.backgroundImage;\r\n }\r\n\r\n /**\r\n * Sets the background image for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param image the image (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundImage()\r\n */\r\n public void setBackgroundImage(Image image) {\r\n this.backgroundImage = image;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the background image alignment. Alignment constants are defined\r\n * in the <code>org.jfree.ui.Align</code> class in the JCommon class\r\n * library.\r\n *\r\n * @return The alignment.\r\n *\r\n * @see #setBackgroundImageAlignment(int)\r\n */\r\n public int getBackgroundImageAlignment() {\r\n return this.backgroundImageAlignment;\r\n }\r\n\r\n /**\r\n * Sets the alignment for the background image and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. Alignment options\r\n * are defined by the {@link org.jfree.ui.Align} class in the JCommon\r\n * class library.\r\n *\r\n * @param alignment the alignment.\r\n *\r\n * @see #getBackgroundImageAlignment()\r\n */\r\n public void setBackgroundImageAlignment(int alignment) {\r\n if (this.backgroundImageAlignment != alignment) {\r\n this.backgroundImageAlignment = alignment;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha transparency used to draw the background image. This\r\n * is a value in the range 0.0f to 1.0f, where 0.0f is fully transparent\r\n * and 1.0f is fully opaque.\r\n *\r\n * @return The alpha transparency.\r\n *\r\n * @see #setBackgroundImageAlpha(float)\r\n */\r\n public float getBackgroundImageAlpha() {\r\n return this.backgroundImageAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha transparency used when drawing the background image.\r\n *\r\n * @param alpha the alpha transparency (in the range 0.0f to 1.0f, where\r\n * 0.0f is fully transparent, and 1.0f is fully opaque).\r\n *\r\n * @throws IllegalArgumentException if <code>alpha</code> is not within\r\n * the specified range.\r\n *\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void setBackgroundImageAlpha(float alpha) {\r\n if (alpha < 0.0f || alpha > 1.0f) {\r\n throw new IllegalArgumentException(\r\n \"The 'alpha' value must be in the range 0.0f to 1.0f.\");\r\n }\r\n if (this.backgroundImageAlpha != alpha) {\r\n this.backgroundImageAlpha = alpha;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the plot outline is\r\n * drawn. The default value is <code>true</code>. Note that for\r\n * historical reasons, the plot's outline paint and stroke can take on\r\n * <code>null</code> values, in which case the outline will not be drawn\r\n * even if this flag is set to <code>true</code>.\r\n *\r\n * @return The outline visibility flag.\r\n *\r\n * @since 1.0.6\r\n *\r\n * @see #setOutlineVisible(boolean)\r\n */\r\n public boolean isOutlineVisible() {\r\n return this.outlineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the plot's outline is\r\n * drawn, and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the new flag value.\r\n *\r\n * @since 1.0.6\r\n *\r\n * @see #isOutlineVisible()\r\n */\r\n public void setOutlineVisible(boolean visible) {\r\n this.outlineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to outline the plot area.\r\n *\r\n * @return The stroke (possibly <code>null</code>).\r\n *\r\n * @see #setOutlineStroke(Stroke)\r\n */\r\n public Stroke getOutlineStroke() {\r\n return this.outlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to outline the plot area and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. If you set this\r\n * attribute to <code>null</code>, no outline will be drawn.\r\n *\r\n * @param stroke the stroke (<code>null</code> permitted).\r\n *\r\n * @see #getOutlineStroke()\r\n */\r\n public void setOutlineStroke(Stroke stroke) {\r\n if (stroke == null) {\r\n if (this.outlineStroke != null) {\r\n this.outlineStroke = null;\r\n fireChangeEvent();\r\n }\r\n }\r\n else {\r\n if (this.outlineStroke != null) {\r\n if (this.outlineStroke.equals(stroke)) {\r\n return; // nothing to do\r\n }\r\n }\r\n this.outlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the color used to draw the outline of the plot area.\r\n *\r\n * @return The color (possibly <code>null</code>).\r\n *\r\n * @see #setOutlinePaint(Paint)\r\n */\r\n public Paint getOutlinePaint() {\r\n return this.outlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the outline of the plot area and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. If you set this\r\n * attribute to <code>null</code>, no outline will be drawn.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getOutlinePaint()\r\n */\r\n public void setOutlinePaint(Paint paint) {\r\n if (paint == null) {\r\n if (this.outlinePaint != null) {\r\n this.outlinePaint = null;\r\n fireChangeEvent();\r\n }\r\n }\r\n else {\r\n if (this.outlinePaint != null) {\r\n if (this.outlinePaint.equals(paint)) {\r\n return; // nothing to do\r\n }\r\n }\r\n this.outlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha-transparency for the plot foreground.\r\n *\r\n * @return The alpha-transparency.\r\n *\r\n * @see #setForegroundAlpha(float)\r\n */\r\n public float getForegroundAlpha() {\r\n return this.foregroundAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha-transparency for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param alpha the new alpha transparency.\r\n *\r\n * @see #getForegroundAlpha()\r\n */\r\n public void setForegroundAlpha(float alpha) {\r\n if (this.foregroundAlpha != alpha) {\r\n this.foregroundAlpha = alpha;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the legend items for the plot. By default, this method returns\r\n * <code>null</code>. Subclasses should override to return a\r\n * {@link LegendItemCollection}.\r\n *\r\n * @return The legend items for the plot (possibly <code>null</code>).\r\n */\r\n @Override\r\n public LegendItemCollection getLegendItems() {\r\n return null;\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not change events are sent to\r\n * registered listeners.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNotify(boolean)\r\n *\r\n * @since 1.0.13\r\n */\r\n public boolean isNotify() {\r\n return this.notify;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not listeners receive\r\n * {@link PlotChangeEvent} notifications.\r\n *\r\n * @param notify a boolean.\r\n *\r\n * @see #isNotify()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setNotify(boolean notify) {\r\n this.notify = notify;\r\n // if the flag is being set to true, there may be queued up changes...\r\n if (notify) {\r\n notifyListeners(new PlotChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Registers an object for notification of changes to the plot.\r\n *\r\n * @param listener the object to be registered.\r\n *\r\n * @see #removeChangeListener(PlotChangeListener)\r\n */\r\n public void addChangeListener(PlotChangeListener listener) {\r\n this.listenerList.add(PlotChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Unregisters an object for notification of changes to the plot.\r\n *\r\n * @param listener the object to be unregistered.\r\n *\r\n * @see #addChangeListener(PlotChangeListener)\r\n */\r\n public void removeChangeListener(PlotChangeListener listener) {\r\n this.listenerList.remove(PlotChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Notifies all registered listeners that the plot has been modified.\r\n *\r\n * @param event information about the change event.\r\n */\r\n public void notifyListeners(PlotChangeEvent event) {\r\n // if the 'notify' flag has been switched to false, we don't notify\r\n // the listeners\r\n if (!this.notify) {\r\n return;\r\n }\r\n Object[] listeners = this.listenerList.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == PlotChangeListener.class) {\r\n ((PlotChangeListener) listeners[i + 1]).plotChanged(event);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @since 1.0.10\r\n */\r\n protected void fireChangeEvent() {\r\n notifyListeners(new PlotChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Draws the plot within the specified area. The anchor is a point on the\r\n * chart that is specified externally (for instance, it may be the last\r\n * point of the last mouse click performed by the user) - plots can use or\r\n * ignore this value as they see fit.\r\n * <br><br>\r\n * Subclasses need to provide an implementation of this method, obviously.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the plot area.\r\n * @param anchor the anchor point (<code>null</code> permitted).\r\n * @param parentState the parent state (if any).\r\n * @param info carries back plot rendering info.\r\n */\r\n public abstract void draw(Graphics2D g2,\r\n Rectangle2D area,\r\n Point2D anchor,\r\n PlotState parentState,\r\n PlotRenderingInfo info);\r\n\r\n /**\r\n * Draws the plot background (the background color and/or image).\r\n * <P>\r\n * This method will be called during the chart drawing process and is\r\n * declared public so that it can be accessed by the renderers used by\r\n * certain subclasses. You shouldn't need to call this method directly.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot should be drawn.\r\n */\r\n public void drawBackground(Graphics2D g2, Rectangle2D area) {\r\n // some subclasses override this method completely, so don't put\r\n // anything here that *must* be done\r\n fillBackground(g2, area);\r\n drawBackgroundImage(g2, area);\r\n }\r\n\r\n /**\r\n * Fills the specified area with the background paint.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n *\r\n * @see #getBackgroundPaint()\r\n * @see #getBackgroundAlpha()\r\n * @see #fillBackground(Graphics2D, Rectangle2D, PlotOrientation)\r\n */\r\n protected void fillBackground(Graphics2D g2, Rectangle2D area) {\r\n fillBackground(g2, area, PlotOrientation.VERTICAL);\r\n }\r\n\r\n /**\r\n * Fills the specified area with the background paint. If the background\r\n * paint is an instance of <code>GradientPaint</code>, the gradient will\r\n * run in the direction suggested by the plot's orientation.\r\n *\r\n * @param g2 the graphics target.\r\n * @param area the plot area.\r\n * @param orientation the plot orientation (<code>null</code> not\r\n * permitted).\r\n *\r\n * @since 1.0.6\r\n */\r\n protected void fillBackground(Graphics2D g2, Rectangle2D area,\r\n PlotOrientation orientation) {\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n if (this.backgroundPaint == null) {\r\n return;\r\n }\r\n Paint p = this.backgroundPaint;\r\n if (p instanceof GradientPaint) {\r\n GradientPaint gp = (GradientPaint) p;\r\n if (orientation == PlotOrientation.VERTICAL) {\r\n p = new GradientPaint((float) area.getCenterX(),\r\n (float) area.getMaxY(), gp.getColor1(),\r\n (float) area.getCenterX(), (float) area.getMinY(),\r\n gp.getColor2());\r\n }\r\n else if (orientation == PlotOrientation.HORIZONTAL) {\r\n p = new GradientPaint((float) area.getMinX(),\r\n (float) area.getCenterY(), gp.getColor1(),\r\n (float) area.getMaxX(), (float) area.getCenterY(),\r\n gp.getColor2());\r\n }\r\n }\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundAlpha));\r\n g2.setPaint(p);\r\n g2.fill(area);\r\n g2.setComposite(originalComposite);\r\n }\r\n\r\n /**\r\n * Draws the background image (if there is one) aligned within the\r\n * specified area.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n *\r\n * @see #getBackgroundImage()\r\n * @see #getBackgroundImageAlignment()\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void drawBackgroundImage(Graphics2D g2, Rectangle2D area) {\r\n if (this.backgroundImage == null) {\r\n return; // nothing to do\r\n }\r\n Composite savedComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundImageAlpha));\r\n Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,\r\n this.backgroundImage.getWidth(null),\r\n this.backgroundImage.getHeight(null));\r\n Align.align(dest, area, this.backgroundImageAlignment);\r\n Shape savedClip = g2.getClip();\r\n g2.clip(area);\r\n g2.drawImage(this.backgroundImage, (int) dest.getX(),\r\n (int) dest.getY(), (int) dest.getWidth() + 1,\r\n (int) dest.getHeight() + 1, null);\r\n g2.setClip(savedClip);\r\n g2.setComposite(savedComposite);\r\n }\r\n\r\n /**\r\n * Draws the plot outline. This method will be called during the chart\r\n * drawing process and is declared public so that it can be accessed by the\r\n * renderers used by certain subclasses. You shouldn't need to call this\r\n * method directly.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot should be drawn.\r\n */\r\n public void drawOutline(Graphics2D g2, Rectangle2D area) {\r\n if (!this.outlineVisible) {\r\n return;\r\n }\r\n if ((this.outlineStroke != null) && (this.outlinePaint != null)) {\r\n g2.setStroke(this.outlineStroke);\r\n g2.setPaint(this.outlinePaint);\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);\r\n g2.draw(area);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n }\r\n\r\n /**\r\n * Draws a message to state that there is no data to plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot should be drawn.\r\n */\r\n protected void drawNoDataMessage(Graphics2D g2, Rectangle2D area) {\r\n Shape savedClip = g2.getClip();\r\n g2.clip(area);\r\n String message = this.noDataMessage;\r\n if (message != null) {\r\n g2.setFont(this.noDataMessageFont);\r\n g2.setPaint(this.noDataMessagePaint);\r\n TextBlock block = TextUtilities.createTextBlock(\r\n this.noDataMessage, this.noDataMessageFont,\r\n this.noDataMessagePaint, 0.9f * (float) area.getWidth(),\r\n new G2TextMeasurer(g2));\r\n block.draw(g2, (float) area.getCenterX(),\r\n (float) area.getCenterY(), TextBlockAnchor.CENTER);\r\n }\r\n g2.setClip(savedClip);\r\n }\r\n\r\n /**\r\n * Creates a plot entity that contains a reference to the plot and the\r\n * data area as shape.\r\n *\r\n * @param dataArea the data area used as hot spot for the entity.\r\n * @param plotState the plot rendering info containing a reference to the\r\n * EntityCollection.\r\n * @param toolTip the tool tip (defined in the respective Plot\r\n * subclass) (<code>null</code> permitted).\r\n * @param urlText the url (defined in the respective Plot subclass)\r\n * (<code>null</code> permitted).\r\n *\r\n * @since 1.0.13\r\n */\r\n protected void createAndAddEntity(Rectangle2D dataArea,\r\n PlotRenderingInfo plotState, String toolTip, String urlText) {\r\n if (plotState != null && plotState.getOwner() != null) {\r\n EntityCollection e = plotState.getOwner().getEntityCollection();\r\n if (e != null) {\r\n e.add(new PlotEntity(dataArea, this, toolTip, urlText));\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the plot. Since the plot does not maintain any\r\n * information about where it has been drawn, the plot rendering info is\r\n * supplied as an argument so that the plot dimensions can be determined.\r\n *\r\n * @param x the x coordinate (in Java2D space).\r\n * @param y the y coordinate (in Java2D space).\r\n * @param info an object containing information about the dimensions of\r\n * the plot.\r\n */\r\n public void handleClick(int x, int y, PlotRenderingInfo info) {\r\n // provides a 'no action' default\r\n }\r\n\r\n /**\r\n * Performs a zoom on the plot. Subclasses should override if zooming is\r\n * appropriate for the type of plot.\r\n *\r\n * @param percent the zoom percentage.\r\n */\r\n public void zoom(double percent) {\r\n // do nothing by default.\r\n }\r\n\r\n /**\r\n * Receives notification of a change to an {@link Annotation} added to\r\n * this plot.\r\n *\r\n * @param event information about the event (not used here).\r\n *\r\n * @since 1.0.14\r\n */\r\n @Override\r\n public void annotationChanged(AnnotationChangeEvent event) {\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Receives notification of a change to one of the plot's axes.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void axisChanged(AxisChangeEvent event) {\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Receives notification of a change to the plot's dataset.\r\n * <P>\r\n * The plot reacts by passing on a plot change event to all registered\r\n * listeners.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void datasetChanged(DatasetChangeEvent event) {\r\n PlotChangeEvent newEvent = new PlotChangeEvent(this);\r\n newEvent.setType(ChartChangeEventType.DATASET_UPDATED);\r\n notifyListeners(newEvent);\r\n }\r\n\r\n /**\r\n * Receives notification of a change to a marker that is assigned to the\r\n * plot.\r\n *\r\n * @param event the event.\r\n *\r\n * @since 1.0.3\r\n */\r\n @Override\r\n public void markerChanged(MarkerChangeEvent event) {\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adjusts the supplied x-value.\r\n *\r\n * @param x the x-value.\r\n * @param w1 width 1.\r\n * @param w2 width 2.\r\n * @param edge the edge (left or right).\r\n *\r\n * @return The adjusted x-value.\r\n */\r\n protected double getRectX(double x, double w1, double w2,\r\n RectangleEdge edge) {\r\n\r\n double result = x;\r\n if (edge == RectangleEdge.LEFT) {\r\n result = result + w1;\r\n }\r\n else if (edge == RectangleEdge.RIGHT) {\r\n result = result + w2;\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Adjusts the supplied y-value.\r\n *\r\n * @param y the x-value.\r\n * @param h1 height 1.\r\n * @param h2 height 2.\r\n * @param edge the edge (top or bottom).\r\n *\r\n * @return The adjusted y-value.\r\n */\r\n protected double getRectY(double y, double h1, double h2,\r\n RectangleEdge edge) {\r\n\r\n double result = y;\r\n if (edge == RectangleEdge.TOP) {\r\n result = result + h1;\r\n }\r\n else if (edge == RectangleEdge.BOTTOM) {\r\n result = result + h2;\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Tests this plot for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof Plot)) {\r\n return false;\r\n }\r\n Plot that = (Plot) obj;\r\n if (!ObjectUtilities.equal(this.noDataMessage, that.noDataMessage)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(\r\n this.noDataMessageFont, that.noDataMessageFont\r\n )) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.noDataMessagePaint,\r\n that.noDataMessagePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.insets, that.insets)) {\r\n return false;\r\n }\r\n if (this.outlineVisible != that.outlineVisible) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.outlineStroke, that.outlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.backgroundPaint, that.backgroundPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundImage,\r\n that.backgroundImage)) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlignment != that.backgroundImageAlignment) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlpha != that.backgroundImageAlpha) {\r\n return false;\r\n }\r\n if (this.foregroundAlpha != that.foregroundAlpha) {\r\n return false;\r\n }\r\n if (this.backgroundAlpha != that.backgroundAlpha) {\r\n return false;\r\n }\r\n if (!this.drawingSupplier.equals(that.drawingSupplier)) {\r\n return false;\r\n }\r\n if (this.notify != that.notify) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Creates a clone of the plot.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if some component of the plot does not\r\n * support cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n\r\n Plot clone = (Plot) super.clone();\r\n // private Plot parent <-- don't clone the parent plot, but take care\r\n // childs in combined plots instead\r\n if (this.datasetGroup != null) {\r\n clone.datasetGroup\r\n = (DatasetGroup) ObjectUtilities.clone(this.datasetGroup);\r\n }\r\n clone.drawingSupplier\r\n = (DrawingSupplier) ObjectUtilities.clone(this.drawingSupplier);\r\n clone.listenerList = new EventListenerList();\r\n return clone;\r\n\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writePaint(this.noDataMessagePaint, stream);\r\n SerialUtilities.writeStroke(this.outlineStroke, stream);\r\n SerialUtilities.writePaint(this.outlinePaint, stream);\r\n // backgroundImage\r\n SerialUtilities.writePaint(this.backgroundPaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.noDataMessagePaint = SerialUtilities.readPaint(stream);\r\n this.outlineStroke = SerialUtilities.readStroke(stream);\r\n this.outlinePaint = SerialUtilities.readPaint(stream);\r\n // backgroundImage\r\n this.backgroundPaint = SerialUtilities.readPaint(stream);\r\n\r\n this.listenerList = new EventListenerList();\r\n\r\n }\r\n\r\n /**\r\n * Resolves a domain axis location for a given plot orientation.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param orientation the orientation (<code>null</code> not permitted).\r\n *\r\n * @return The edge (never <code>null</code>).\r\n */\r\n public static RectangleEdge resolveDomainAxisLocation(\r\n AxisLocation location, PlotOrientation orientation) {\r\n\r\n ParamChecks.nullNotPermitted(location, \"location\");\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n\r\n RectangleEdge result = null;\r\n if (location == AxisLocation.TOP_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n }\r\n else if (location == AxisLocation.TOP_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n }\r\n // the above should cover all the options...\r\n if (result == null) {\r\n throw new IllegalStateException(\"resolveDomainAxisLocation()\");\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Resolves a range axis location for a given plot orientation.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param orientation the orientation (<code>null</code> not permitted).\r\n *\r\n * @return The edge (never <code>null</code>).\r\n */\r\n public static RectangleEdge resolveRangeAxisLocation(\r\n AxisLocation location, PlotOrientation orientation) {\r\n\r\n ParamChecks.nullNotPermitted(location, \"location\");\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n\r\n RectangleEdge result = null;\r\n if (location == AxisLocation.TOP_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n }\r\n else if (location == AxisLocation.TOP_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n }\r\n\r\n // the above should cover all the options...\r\n if (result == null) {\r\n throw new IllegalStateException(\"resolveRangeAxisLocation()\");\r\n }\r\n return result;\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "PlotOrientation", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/PlotOrientation.java", "snippet": "public final class PlotOrientation implements Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -2508771828190337782L;\r\n\r\n /** For a plot where the range axis is horizontal. */\r\n public static final PlotOrientation HORIZONTAL\r\n = new PlotOrientation(\"PlotOrientation.HORIZONTAL\");\r\n\r\n /** For a plot where the range axis is vertical. */\r\n public static final PlotOrientation VERTICAL\r\n = new PlotOrientation(\"PlotOrientation.VERTICAL\");\r\n\r\n /** The name. */\r\n private String name;\r\n\r\n /**\r\n * Private constructor.\r\n *\r\n * @param name the name.\r\n */\r\n private PlotOrientation(String name) {\r\n this.name = name;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this orientation is <code>HORIZONTAL</code>,\r\n * and <code>false</code> otherwise. \r\n * \r\n * @return A boolean.\r\n * \r\n * @since 1.0.18\r\n */\r\n public boolean isHorizontal() {\r\n return this.equals(PlotOrientation.HORIZONTAL);\r\n }\r\n \r\n /**\r\n * Returns <code>true</code> if this orientation is <code>VERTICAL</code>,\r\n * and <code>false</code> otherwise.\r\n * \r\n * @return A boolean.\r\n * \r\n * @since 1.0.18\r\n */\r\n public boolean isVertical() {\r\n return this.equals(PlotOrientation.VERTICAL);\r\n }\r\n \r\n /**\r\n * Returns a string representing the object.\r\n *\r\n * @return The string.\r\n */\r\n @Override\r\n public String toString() {\r\n return this.name;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this object is equal to the specified\r\n * object, and <code>false</code> otherwise.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) {\r\n return true;\r\n }\r\n if (!(obj instanceof PlotOrientation)) {\r\n return false;\r\n }\r\n PlotOrientation orientation = (PlotOrientation) obj;\r\n if (!this.name.equals(orientation.toString())) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code for this instance.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n return this.name.hashCode();\r\n }\r\n\r\n /**\r\n * Ensures that serialization returns the unique instances.\r\n *\r\n * @return The object.\r\n *\r\n * @throws ObjectStreamException if there is a problem.\r\n */\r\n private Object readResolve() throws ObjectStreamException {\r\n Object result = null;\r\n if (this.equals(PlotOrientation.HORIZONTAL)) {\r\n result = PlotOrientation.HORIZONTAL;\r\n }\r\n else if (this.equals(PlotOrientation.VERTICAL)) {\r\n result = PlotOrientation.VERTICAL;\r\n }\r\n return result;\r\n }\r\n\r\n}\r" }, { "identifier": "PlotRenderingInfo", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/PlotRenderingInfo.java", "snippet": "public class PlotRenderingInfo implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 8446720134379617220L;\r\n\r\n /** The owner of this info. */\r\n private ChartRenderingInfo owner;\r\n\r\n /** The plot area. */\r\n private transient Rectangle2D plotArea;\r\n\r\n /** The data area. */\r\n private transient Rectangle2D dataArea;\r\n\r\n /**\r\n * Storage for the plot rendering info objects belonging to the subplots.\r\n */\r\n private List subplotInfo;\r\n\r\n /**\r\n * Creates a new instance.\r\n *\r\n * @param owner the owner (<code>null</code> permitted).\r\n */\r\n public PlotRenderingInfo(ChartRenderingInfo owner) {\r\n this.owner = owner;\r\n this.dataArea = new Rectangle2D.Double();\r\n this.subplotInfo = new java.util.ArrayList();\r\n }\r\n\r\n /**\r\n * Returns the owner (as specified in the constructor).\r\n *\r\n * @return The owner (possibly <code>null</code>).\r\n */\r\n public ChartRenderingInfo getOwner() {\r\n return this.owner;\r\n }\r\n\r\n /**\r\n * Returns the plot area (in Java2D space).\r\n *\r\n * @return The plot area (possibly <code>null</code>).\r\n *\r\n * @see #setPlotArea(Rectangle2D)\r\n */\r\n public Rectangle2D getPlotArea() {\r\n return this.plotArea;\r\n }\r\n\r\n /**\r\n * Sets the plot area.\r\n *\r\n * @param area the plot area (in Java2D space, <code>null</code>\r\n * permitted but discouraged)\r\n *\r\n * @see #getPlotArea()\r\n */\r\n public void setPlotArea(Rectangle2D area) {\r\n this.plotArea = area;\r\n }\r\n\r\n /**\r\n * Returns the plot's data area (in Java2D space).\r\n *\r\n * @return The data area (possibly <code>null</code>).\r\n *\r\n * @see #setDataArea(Rectangle2D)\r\n */\r\n public Rectangle2D getDataArea() {\r\n return this.dataArea;\r\n }\r\n\r\n /**\r\n * Sets the data area.\r\n *\r\n * @param area the data area (in Java2D space, <code>null</code> permitted\r\n * but discouraged).\r\n *\r\n * @see #getDataArea()\r\n */\r\n public void setDataArea(Rectangle2D area) {\r\n this.dataArea = area;\r\n }\r\n\r\n /**\r\n * Returns the number of subplots (possibly zero).\r\n *\r\n * @return The subplot count.\r\n */\r\n public int getSubplotCount() {\r\n return this.subplotInfo.size();\r\n }\r\n\r\n /**\r\n * Adds the info for a subplot.\r\n *\r\n * @param info the subplot info.\r\n *\r\n * @see #getSubplotInfo(int)\r\n */\r\n public void addSubplotInfo(PlotRenderingInfo info) {\r\n this.subplotInfo.add(info);\r\n }\r\n\r\n /**\r\n * Returns the info for a subplot.\r\n *\r\n * @param index the subplot index.\r\n *\r\n * @return The info.\r\n *\r\n * @see #addSubplotInfo(PlotRenderingInfo)\r\n */\r\n public PlotRenderingInfo getSubplotInfo(int index) {\r\n return (PlotRenderingInfo) this.subplotInfo.get(index);\r\n }\r\n\r\n /**\r\n * Returns the index of the subplot that contains the specified\r\n * (x, y) point (the \"source\" point). The source point will usually\r\n * come from a mouse click on a {@link org.jfree.chart.ChartPanel},\r\n * and this method is then used to determine the subplot that\r\n * contains the source point.\r\n *\r\n * @param source the source point (in Java2D space, <code>null</code> not\r\n * permitted).\r\n *\r\n * @return The subplot index (or -1 if no subplot contains\r\n * <code>source</code>).\r\n */\r\n public int getSubplotIndex(Point2D source) {\r\n ParamChecks.nullNotPermitted(source, \"source\");\r\n int subplotCount = getSubplotCount();\r\n for (int i = 0; i < subplotCount; i++) {\r\n PlotRenderingInfo info = getSubplotInfo(i);\r\n Rectangle2D area = info.getDataArea();\r\n if (area.contains(source)) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Tests this instance for equality against an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) {\r\n return true;\r\n }\r\n if (!(obj instanceof PlotRenderingInfo)) {\r\n return false;\r\n }\r\n PlotRenderingInfo that = (PlotRenderingInfo) obj;\r\n if (!ObjectUtilities.equal(this.dataArea, that.dataArea)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.plotArea, that.plotArea)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.subplotInfo, that.subplotInfo)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a clone of this object.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if there is a problem cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n PlotRenderingInfo clone = (PlotRenderingInfo) super.clone();\r\n if (this.plotArea != null) {\r\n clone.plotArea = (Rectangle2D) this.plotArea.clone();\r\n }\r\n if (this.dataArea != null) {\r\n clone.dataArea = (Rectangle2D) this.dataArea.clone();\r\n }\r\n clone.subplotInfo = new java.util.ArrayList(this.subplotInfo.size());\r\n for (int i = 0; i < this.subplotInfo.size(); i++) {\r\n PlotRenderingInfo info\r\n = (PlotRenderingInfo) this.subplotInfo.get(i);\r\n clone.subplotInfo.add(info.clone());\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeShape(this.dataArea, stream);\r\n SerialUtilities.writeShape(this.plotArea, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.dataArea = (Rectangle2D) SerialUtilities.readShape(stream);\r\n this.plotArea = (Rectangle2D) SerialUtilities.readShape(stream);\r\n }\r\n\r\n}\r" }, { "identifier": "XYPlot", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/XYPlot.java", "snippet": "public class XYPlot extends Plot implements ValueAxisPlot, Pannable, Zoomable,\r\n RendererChangeListener, Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 7044148245716569264L;\r\n\r\n /** The default grid line stroke. */\r\n public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f,\r\n BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f,\r\n new float[] {2.0f, 2.0f}, 0.0f);\r\n\r\n /** The default grid line paint. */\r\n public static final Paint DEFAULT_GRIDLINE_PAINT = Color.lightGray;\r\n\r\n /** The default crosshair visibility. */\r\n public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false;\r\n\r\n /** The default crosshair stroke. */\r\n public static final Stroke DEFAULT_CROSSHAIR_STROKE\r\n = DEFAULT_GRIDLINE_STROKE;\r\n\r\n /** The default crosshair paint. */\r\n public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.blue;\r\n\r\n /** The resourceBundle for the localization. */\r\n protected static ResourceBundle localizationResources\r\n = ResourceBundleWrapper.getBundle(\r\n \"org.jfree.chart.plot.LocalizationBundle\");\r\n\r\n /** The plot orientation. */\r\n private PlotOrientation orientation;\r\n\r\n /** The offset between the data area and the axes. */\r\n private RectangleInsets axisOffset;\r\n\r\n /** The domain axis / axes (used for the x-values). */\r\n private Map<Integer, ValueAxis> domainAxes;\r\n\r\n /** The domain axis locations. */\r\n private Map<Integer, AxisLocation> domainAxisLocations;\r\n\r\n /** The range axis (used for the y-values). */\r\n private Map<Integer, ValueAxis> rangeAxes;\r\n\r\n /** The range axis location. */\r\n private Map<Integer, AxisLocation> rangeAxisLocations;\r\n\r\n /** Storage for the datasets. */\r\n private Map<Integer, XYDataset> datasets;\r\n\r\n /** Storage for the renderers. */\r\n private Map<Integer, XYItemRenderer> renderers;\r\n\r\n /**\r\n * Storage for the mapping between datasets/renderers and domain axes. The\r\n * keys in the map are Integer objects, corresponding to the dataset\r\n * index. The values in the map are List objects containing Integer\r\n * objects (corresponding to the axis indices). If the map contains no\r\n * entry for a dataset, it is assumed to map to the primary domain axis\r\n * (index = 0).\r\n */\r\n private Map<Integer, List<Integer>> datasetToDomainAxesMap;\r\n\r\n /**\r\n * Storage for the mapping between datasets/renderers and range axes. The\r\n * keys in the map are Integer objects, corresponding to the dataset\r\n * index. The values in the map are List objects containing Integer\r\n * objects (corresponding to the axis indices). If the map contains no\r\n * entry for a dataset, it is assumed to map to the primary domain axis\r\n * (index = 0).\r\n */\r\n private Map<Integer, List<Integer>> datasetToRangeAxesMap;\r\n\r\n /** The origin point for the quadrants (if drawn). */\r\n private transient Point2D quadrantOrigin = new Point2D.Double(0.0, 0.0);\r\n\r\n /** The paint used for each quadrant. */\r\n private transient Paint[] quadrantPaint\r\n = new Paint[] {null, null, null, null};\r\n\r\n /** A flag that controls whether the domain grid-lines are visible. */\r\n private boolean domainGridlinesVisible;\r\n\r\n /** The stroke used to draw the domain grid-lines. */\r\n private transient Stroke domainGridlineStroke;\r\n\r\n /** The paint used to draw the domain grid-lines. */\r\n private transient Paint domainGridlinePaint;\r\n\r\n /** A flag that controls whether the range grid-lines are visible. */\r\n private boolean rangeGridlinesVisible;\r\n\r\n /** The stroke used to draw the range grid-lines. */\r\n private transient Stroke rangeGridlineStroke;\r\n\r\n /** The paint used to draw the range grid-lines. */\r\n private transient Paint rangeGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether the domain minor grid-lines are visible.\r\n *\r\n * @since 1.0.12\r\n */\r\n private boolean domainMinorGridlinesVisible;\r\n\r\n /**\r\n * The stroke used to draw the domain minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Stroke domainMinorGridlineStroke;\r\n\r\n /**\r\n * The paint used to draw the domain minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Paint domainMinorGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether the range minor grid-lines are visible.\r\n *\r\n * @since 1.0.12\r\n */\r\n private boolean rangeMinorGridlinesVisible;\r\n\r\n /**\r\n * The stroke used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Stroke rangeMinorGridlineStroke;\r\n\r\n /**\r\n * The paint used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Paint rangeMinorGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not the zero baseline against the domain\r\n * axis is visible.\r\n *\r\n * @since 1.0.5\r\n */\r\n private boolean domainZeroBaselineVisible;\r\n\r\n /**\r\n * The stroke used for the zero baseline against the domain axis.\r\n *\r\n * @since 1.0.5\r\n */\r\n private transient Stroke domainZeroBaselineStroke;\r\n\r\n /**\r\n * The paint used for the zero baseline against the domain axis.\r\n *\r\n * @since 1.0.5\r\n */\r\n private transient Paint domainZeroBaselinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not the zero baseline against the range\r\n * axis is visible.\r\n */\r\n private boolean rangeZeroBaselineVisible;\r\n\r\n /** The stroke used for the zero baseline against the range axis. */\r\n private transient Stroke rangeZeroBaselineStroke;\r\n\r\n /** The paint used for the zero baseline against the range axis. */\r\n private transient Paint rangeZeroBaselinePaint;\r\n\r\n /** A flag that controls whether or not a domain crosshair is drawn..*/\r\n private boolean domainCrosshairVisible;\r\n\r\n /** The domain crosshair value. */\r\n private double domainCrosshairValue;\r\n\r\n /** The pen/brush used to draw the crosshair (if any). */\r\n private transient Stroke domainCrosshairStroke;\r\n\r\n /** The color used to draw the crosshair (if any). */\r\n private transient Paint domainCrosshairPaint;\r\n\r\n /**\r\n * A flag that controls whether or not the crosshair locks onto actual\r\n * data points.\r\n */\r\n private boolean domainCrosshairLockedOnData = true;\r\n\r\n /** A flag that controls whether or not a range crosshair is drawn..*/\r\n private boolean rangeCrosshairVisible;\r\n\r\n /** The range crosshair value. */\r\n private double rangeCrosshairValue;\r\n\r\n /** The pen/brush used to draw the crosshair (if any). */\r\n private transient Stroke rangeCrosshairStroke;\r\n\r\n /** The color used to draw the crosshair (if any). */\r\n private transient Paint rangeCrosshairPaint;\r\n\r\n /**\r\n * A flag that controls whether or not the crosshair locks onto actual\r\n * data points.\r\n */\r\n private boolean rangeCrosshairLockedOnData = true;\r\n\r\n /** A map of lists of foreground markers (optional) for the domain axes. */\r\n private Map foregroundDomainMarkers;\r\n\r\n /** A map of lists of background markers (optional) for the domain axes. */\r\n private Map backgroundDomainMarkers;\r\n\r\n /** A map of lists of foreground markers (optional) for the range axes. */\r\n private Map foregroundRangeMarkers;\r\n\r\n /** A map of lists of background markers (optional) for the range axes. */\r\n private Map backgroundRangeMarkers;\r\n\r\n /**\r\n * A (possibly empty) list of annotations for the plot. The list should\r\n * be initialised in the constructor and never allowed to be\r\n * <code>null</code>.\r\n */\r\n private List<XYAnnotation> annotations;\r\n\r\n /** The paint used for the domain tick bands (if any). */\r\n private transient Paint domainTickBandPaint;\r\n\r\n /** The paint used for the range tick bands (if any). */\r\n private transient Paint rangeTickBandPaint;\r\n\r\n /** The fixed domain axis space. */\r\n private AxisSpace fixedDomainAxisSpace;\r\n\r\n /** The fixed range axis space. */\r\n private AxisSpace fixedRangeAxisSpace;\r\n\r\n /**\r\n * The order of the dataset rendering (REVERSE draws the primary dataset\r\n * last so that it appears to be on top).\r\n */\r\n private DatasetRenderingOrder datasetRenderingOrder\r\n = DatasetRenderingOrder.REVERSE;\r\n\r\n /**\r\n * The order of the series rendering (REVERSE draws the primary series\r\n * last so that it appears to be on top).\r\n */\r\n private SeriesRenderingOrder seriesRenderingOrder\r\n = SeriesRenderingOrder.REVERSE;\r\n\r\n /**\r\n * The weight for this plot (only relevant if this is a subplot in a\r\n * combined plot).\r\n */\r\n private int weight;\r\n\r\n /**\r\n * An optional collection of legend items that can be returned by the\r\n * getLegendItems() method.\r\n */\r\n private LegendItemCollection fixedLegendItems;\r\n\r\n /**\r\n * A flag that controls whether or not panning is enabled for the domain\r\n * axis/axes.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean domainPannable;\r\n\r\n /**\r\n * A flag that controls whether or not panning is enabled for the range\r\n * axis/axes.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean rangePannable;\r\n\r\n /**\r\n * The shadow generator (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n private ShadowGenerator shadowGenerator;\r\n\r\n /**\r\n * Creates a new <code>XYPlot</code> instance with no dataset, no axes and\r\n * no renderer. You should specify these items before using the plot.\r\n */\r\n public XYPlot() {\r\n this(null, null, null, null);\r\n }\r\n\r\n /**\r\n * Creates a new plot with the specified dataset, axes and renderer. Any\r\n * of the arguments can be <code>null</code>, but in that case you should\r\n * take care to specify the value before using the plot (otherwise a\r\n * <code>NullPointerException</code> may be thrown).\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n * @param domainAxis the domain axis (<code>null</code> permitted).\r\n * @param rangeAxis the range axis (<code>null</code> permitted).\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n */\r\n public XYPlot(XYDataset dataset, ValueAxis domainAxis, ValueAxis rangeAxis,\r\n XYItemRenderer renderer) {\r\n super();\r\n this.orientation = PlotOrientation.VERTICAL;\r\n this.weight = 1; // only relevant when this is a subplot\r\n this.axisOffset = RectangleInsets.ZERO_INSETS;\r\n\r\n // allocate storage for datasets, axes and renderers (all optional)\r\n this.domainAxes = new HashMap<Integer, ValueAxis>();\r\n this.domainAxisLocations = new HashMap<Integer, AxisLocation>();\r\n this.foregroundDomainMarkers = new HashMap();\r\n this.backgroundDomainMarkers = new HashMap();\r\n\r\n this.rangeAxes = new HashMap<Integer, ValueAxis>();\r\n this.rangeAxisLocations = new HashMap<Integer, AxisLocation>();\r\n this.foregroundRangeMarkers = new HashMap();\r\n this.backgroundRangeMarkers = new HashMap();\r\n\r\n this.datasets = new HashMap<Integer, XYDataset>();\r\n this.renderers = new HashMap<Integer, XYItemRenderer>();\r\n\r\n this.datasetToDomainAxesMap = new TreeMap();\r\n this.datasetToRangeAxesMap = new TreeMap();\r\n\r\n this.annotations = new java.util.ArrayList();\r\n\r\n this.datasets.put(0, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n\r\n this.renderers.put(0, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n\r\n this.domainAxes.put(0, domainAxis);\r\n mapDatasetToDomainAxis(0, 0);\r\n if (domainAxis != null) {\r\n domainAxis.setPlot(this);\r\n domainAxis.addChangeListener(this);\r\n }\r\n this.domainAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT);\r\n\r\n this.rangeAxes.put(0, rangeAxis);\r\n mapDatasetToRangeAxis(0, 0);\r\n if (rangeAxis != null) {\r\n rangeAxis.setPlot(this);\r\n rangeAxis.addChangeListener(this);\r\n }\r\n this.rangeAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT);\r\n\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n\r\n this.domainGridlinesVisible = true;\r\n this.domainGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.domainGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.domainMinorGridlinesVisible = false;\r\n this.domainMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.domainMinorGridlinePaint = Color.white;\r\n\r\n this.domainZeroBaselineVisible = false;\r\n this.domainZeroBaselinePaint = Color.black;\r\n this.domainZeroBaselineStroke = new BasicStroke(0.5f);\r\n\r\n this.rangeGridlinesVisible = true;\r\n this.rangeGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.rangeMinorGridlinesVisible = false;\r\n this.rangeMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeMinorGridlinePaint = Color.white;\r\n\r\n this.rangeZeroBaselineVisible = false;\r\n this.rangeZeroBaselinePaint = Color.black;\r\n this.rangeZeroBaselineStroke = new BasicStroke(0.5f);\r\n\r\n this.domainCrosshairVisible = false;\r\n this.domainCrosshairValue = 0.0;\r\n this.domainCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.domainCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n\r\n this.rangeCrosshairVisible = false;\r\n this.rangeCrosshairValue = 0.0;\r\n this.rangeCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.rangeCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n this.shadowGenerator = null;\r\n }\r\n\r\n /**\r\n * Returns the plot type as a string.\r\n *\r\n * @return A short string describing the type of plot.\r\n */\r\n @Override\r\n public String getPlotType() {\r\n return localizationResources.getString(\"XY_Plot\");\r\n }\r\n\r\n /**\r\n * Returns the orientation of the plot.\r\n *\r\n * @return The orientation (never <code>null</code>).\r\n *\r\n * @see #setOrientation(PlotOrientation)\r\n */\r\n @Override\r\n public PlotOrientation getOrientation() {\r\n return this.orientation;\r\n }\r\n\r\n /**\r\n * Sets the orientation for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param orientation the orientation (<code>null</code> not allowed).\r\n *\r\n * @see #getOrientation()\r\n */\r\n public void setOrientation(PlotOrientation orientation) {\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n if (orientation != this.orientation) {\r\n this.orientation = orientation;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the axis offset.\r\n *\r\n * @return The axis offset (never <code>null</code>).\r\n *\r\n * @see #setAxisOffset(RectangleInsets)\r\n */\r\n public RectangleInsets getAxisOffset() {\r\n return this.axisOffset;\r\n }\r\n\r\n /**\r\n * Sets the axis offsets (gap between the data area and the axes) and sends\r\n * a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param offset the offset (<code>null</code> not permitted).\r\n *\r\n * @see #getAxisOffset()\r\n */\r\n public void setAxisOffset(RectangleInsets offset) {\r\n ParamChecks.nullNotPermitted(offset, \"offset\");\r\n this.axisOffset = offset;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the domain axis with index 0. If the domain axis for this plot\r\n * is <code>null</code>, then the method will return the parent plot's\r\n * domain axis (if there is a parent plot).\r\n *\r\n * @return The domain axis (possibly <code>null</code>).\r\n *\r\n * @see #getDomainAxis(int)\r\n * @see #setDomainAxis(ValueAxis)\r\n */\r\n public ValueAxis getDomainAxis() {\r\n return getDomainAxis(0);\r\n }\r\n\r\n /**\r\n * Returns the domain axis with the specified index, or {@code null} if \r\n * there is no axis with that index.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The axis ({@code null} possible).\r\n *\r\n * @see #setDomainAxis(int, ValueAxis)\r\n */\r\n public ValueAxis getDomainAxis(int index) {\r\n ValueAxis result = this.domainAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot xy = (XYPlot) parent;\r\n result = xy.getDomainAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the domain axis for the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axis the new axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis()\r\n * @see #setDomainAxis(int, ValueAxis)\r\n */\r\n public void setDomainAxis(ValueAxis axis) {\r\n setDomainAxis(0, axis);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis(int)\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public void setDomainAxis(int index, ValueAxis axis) {\r\n setDomainAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainAxis(int)\r\n */\r\n public void setDomainAxis(int index, ValueAxis axis, boolean notify) {\r\n ValueAxis existing = getDomainAxis(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.domainAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the domain axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setRangeAxes(ValueAxis[])\r\n */\r\n public void setDomainAxes(ValueAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setDomainAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the location of the primary domain axis.\r\n *\r\n * @return The location (never <code>null</code>).\r\n *\r\n * @see #setDomainAxisLocation(AxisLocation)\r\n */\r\n public AxisLocation getDomainAxisLocation() {\r\n return (AxisLocation) this.domainAxisLocations.get(0);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary domain axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainAxisLocation()\r\n */\r\n public void setDomainAxisLocation(AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainAxisLocation()\r\n */\r\n public void setDomainAxisLocation(AxisLocation location, boolean notify) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Returns the edge for the primary domain axis (taking into account the\r\n * plot's orientation).\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getDomainAxisLocation()\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getDomainAxisEdge() {\r\n return Plot.resolveDomainAxisLocation(getDomainAxisLocation(),\r\n this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the number of domain axes.\r\n *\r\n * @return The axis count.\r\n *\r\n * @see #getRangeAxisCount()\r\n */\r\n public int getDomainAxisCount() {\r\n return this.domainAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the domain axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #clearRangeAxes()\r\n */\r\n public void clearDomainAxes() {\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.removeChangeListener(this);\r\n }\r\n }\r\n this.domainAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the domain axes.\r\n */\r\n public void configureDomainAxes() {\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the location for a domain axis. If this hasn't been set\r\n * explicitly, the method returns the location that is opposite to the\r\n * primary domain axis location.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The location (never {@code null}).\r\n *\r\n * @see #setDomainAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getDomainAxisLocation(int index) {\r\n AxisLocation result = this.domainAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getDomainAxisLocation());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location for a domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> not permitted for index\r\n * 0).\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the axis location for a domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n * @param location the location (<code>null</code> not permitted for\r\n * index 0).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n * @see #setRangeAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.domainAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the edge for a domain axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getRangeAxisEdge(int)\r\n */\r\n public RectangleEdge getDomainAxisEdge(int index) {\r\n AxisLocation location = getDomainAxisLocation(index);\r\n return Plot.resolveDomainAxisLocation(location, this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the range axis for the plot. If the range axis for this plot is\r\n * <code>null</code>, then the method will return the parent plot's range\r\n * axis (if there is a parent plot).\r\n *\r\n * @return The range axis.\r\n *\r\n * @see #getRangeAxis(int)\r\n * @see #setRangeAxis(ValueAxis)\r\n */\r\n public ValueAxis getRangeAxis() {\r\n return getRangeAxis(0);\r\n }\r\n\r\n /**\r\n * Sets the range axis for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxis()\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public void setRangeAxis(ValueAxis axis) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n // plot is likely registered as a listener with the existing axis...\r\n ValueAxis existing = getRangeAxis();\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.rangeAxes.put(0, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the location of the primary range axis.\r\n *\r\n * @return The location (never <code>null</code>).\r\n *\r\n * @see #setRangeAxisLocation(AxisLocation)\r\n */\r\n public AxisLocation getRangeAxisLocation() {\r\n return (AxisLocation) this.rangeAxisLocations.get(0);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary range axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeAxisLocation()\r\n */\r\n public void setRangeAxisLocation(AxisLocation location) {\r\n // delegate...\r\n setRangeAxisLocation(0, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary range axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRangeAxisLocation()\r\n */\r\n public void setRangeAxisLocation(AxisLocation location, boolean notify) {\r\n // delegate...\r\n setRangeAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Returns the edge for the primary range axis.\r\n *\r\n * @return The range axis edge.\r\n *\r\n * @see #getRangeAxisLocation()\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getRangeAxisEdge() {\r\n return Plot.resolveRangeAxisLocation(getRangeAxisLocation(),\r\n this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the range axis with the specified index, or {@code null} if \r\n * there is no axis with that index.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The axis ({@code null} possible).\r\n *\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public ValueAxis getRangeAxis(int index) {\r\n ValueAxis result = this.rangeAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot xy = (XYPlot) parent;\r\n result = xy.getRangeAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets a range axis and sends a {@link PlotChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxis(int)\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis) {\r\n setRangeAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a range axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRangeAxis(int)\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis, boolean notify) {\r\n ValueAxis existing = getRangeAxis(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.rangeAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the range axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setDomainAxes(ValueAxis[])\r\n */\r\n public void setRangeAxes(ValueAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setRangeAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the number of range axes.\r\n *\r\n * @return The axis count.\r\n *\r\n * @see #getDomainAxisCount()\r\n */\r\n public int getRangeAxisCount() {\r\n return this.rangeAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the range axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #clearDomainAxes()\r\n */\r\n public void clearRangeAxes() {\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.removeChangeListener(this);\r\n }\r\n }\r\n this.rangeAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the range axes.\r\n *\r\n * @see #configureDomainAxes()\r\n */\r\n public void configureRangeAxes() {\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the location for a range axis. If this hasn't been set\r\n * explicitly, the method returns the location that is opposite to the\r\n * primary range axis location.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The location (never {@code null}).\r\n *\r\n * @see #setRangeAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getRangeAxisLocation(int index) {\r\n AxisLocation result = this.rangeAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getRangeAxisLocation());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location for a range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location) {\r\n // delegate...\r\n setRangeAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the axis location for a domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> not permitted for\r\n * index 0).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #setDomainAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.rangeAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the edge for a range axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getRangeAxisEdge(int index) {\r\n AxisLocation location = getRangeAxisLocation(index);\r\n return Plot.resolveRangeAxisLocation(location, this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the primary dataset for the plot.\r\n *\r\n * @return The primary dataset (possibly <code>null</code>).\r\n *\r\n * @see #getDataset(int)\r\n * @see #setDataset(XYDataset)\r\n */\r\n public XYDataset getDataset() {\r\n return getDataset(0);\r\n }\r\n\r\n /**\r\n * Returns the dataset with the specified index, or {@code null} if there\r\n * is no dataset with that index.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The dataset (possibly {@code null}).\r\n *\r\n * @see #setDataset(int, XYDataset)\r\n */\r\n public XYDataset getDataset(int index) {\r\n return (XYDataset) this.datasets.get(index);\r\n }\r\n\r\n /**\r\n * Sets the primary dataset for the plot, replacing the existing dataset if\r\n * there is one.\r\n *\r\n * @param dataset the dataset ({@code null} permitted).\r\n *\r\n * @see #getDataset()\r\n * @see #setDataset(int, XYDataset)\r\n */\r\n public void setDataset(XYDataset dataset) {\r\n setDataset(0, dataset);\r\n }\r\n\r\n /**\r\n * Sets a dataset for the plot and sends a change event to all registered\r\n * listeners.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n *\r\n * @see #getDataset(int)\r\n */\r\n public void setDataset(int index, XYDataset dataset) {\r\n XYDataset existing = getDataset(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.datasets.put(index, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n\r\n // send a dataset change event to self...\r\n DatasetChangeEvent event = new DatasetChangeEvent(this, dataset);\r\n datasetChanged(event);\r\n }\r\n\r\n /**\r\n * Returns the number of datasets.\r\n *\r\n * @return The number of datasets.\r\n */\r\n public int getDatasetCount() {\r\n return this.datasets.size();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified dataset, or {@code -1} if the\r\n * dataset does not belong to the plot.\r\n *\r\n * @param dataset the dataset ({@code null} not permitted).\r\n *\r\n * @return The index or -1.\r\n */\r\n public int indexOf(XYDataset dataset) {\r\n for (Map.Entry<Integer, XYDataset> entry: this.datasets.entrySet()) {\r\n if (dataset == entry.getValue()) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular domain axis. All data will be plotted\r\n * against axis zero by default, no mapping is required for this case.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index.\r\n *\r\n * @see #mapDatasetToRangeAxis(int, int)\r\n */\r\n public void mapDatasetToDomainAxis(int index, int axisIndex) {\r\n List axisIndices = new java.util.ArrayList(1);\r\n axisIndices.add(new Integer(axisIndex));\r\n mapDatasetToDomainAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToDomainAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n Integer key = new Integer(index);\r\n this.datasetToDomainAxesMap.put(key, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular range axis. All data will be plotted\r\n * against axis zero by default, no mapping is required for this case.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index.\r\n *\r\n * @see #mapDatasetToDomainAxis(int, int)\r\n */\r\n public void mapDatasetToRangeAxis(int index, int axisIndex) {\r\n List axisIndices = new java.util.ArrayList(1);\r\n axisIndices.add(new Integer(axisIndex));\r\n mapDatasetToRangeAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToRangeAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n Integer key = new Integer(index);\r\n this.datasetToRangeAxesMap.put(key, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * This method is used to perform argument checking on the list of\r\n * axis indices passed to mapDatasetToDomainAxes() and\r\n * mapDatasetToRangeAxes().\r\n *\r\n * @param indices the list of indices (<code>null</code> permitted).\r\n */\r\n private void checkAxisIndices(List<Integer> indices) {\r\n // axisIndices can be:\r\n // 1. null;\r\n // 2. non-empty, containing only Integer objects that are unique.\r\n if (indices == null) {\r\n return; // OK\r\n }\r\n int count = indices.size();\r\n if (count == 0) {\r\n throw new IllegalArgumentException(\"Empty list not permitted.\");\r\n }\r\n Set<Integer> set = new HashSet<Integer>();\r\n for (Integer item : indices) {\r\n if (set.contains(item)) {\r\n throw new IllegalArgumentException(\"Indices must be unique.\");\r\n }\r\n set.add(item);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the number of renderer slots for this plot.\r\n *\r\n * @return The number of renderer slots.\r\n *\r\n * @since 1.0.11\r\n */\r\n public int getRendererCount() {\r\n return this.renderers.size();\r\n }\r\n\r\n /**\r\n * Returns the renderer for the primary dataset.\r\n *\r\n * @return The item renderer (possibly <code>null</code>).\r\n *\r\n * @see #setRenderer(XYItemRenderer)\r\n */\r\n public XYItemRenderer getRenderer() {\r\n return getRenderer(0);\r\n }\r\n\r\n /**\r\n * Returns the renderer with the specified index, or {@code null}.\r\n *\r\n * @param index the renderer index (must be &gt;= 0).\r\n *\r\n * @return The renderer (possibly {@code null}).\r\n *\r\n * @see #setRenderer(int, XYItemRenderer)\r\n */\r\n public XYItemRenderer getRenderer(int index) {\r\n return (XYItemRenderer) this.renderers.get(index);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the primary dataset and sends a change event to \r\n * all registered listeners. If the renderer is set to <code>null</code>, \r\n * no data will be displayed.\r\n *\r\n * @param renderer the renderer ({@code null} permitted).\r\n *\r\n * @see #getRenderer()\r\n */\r\n public void setRenderer(XYItemRenderer renderer) {\r\n setRenderer(0, renderer);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the dataset with the specified index and sends a \r\n * change event to all registered listeners. Note that each dataset should \r\n * have its own renderer, you should not use one renderer for multiple \r\n * datasets.\r\n *\r\n * @param index the index (must be &gt;= 0).\r\n * @param renderer the renderer.\r\n *\r\n * @see #getRenderer(int)\r\n */\r\n public void setRenderer(int index, XYItemRenderer renderer) {\r\n setRenderer(index, renderer, true);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the dataset with the specified index and, if \r\n * requested, sends a change event to all registered listeners. Note that \r\n * each dataset should have its own renderer, you should not use one \r\n * renderer for multiple datasets.\r\n *\r\n * @param index the index (must be &gt;= 0).\r\n * @param renderer the renderer.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRenderer(int)\r\n */\r\n public void setRenderer(int index, XYItemRenderer renderer, \r\n boolean notify) {\r\n XYItemRenderer existing = getRenderer(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.renderers.put(index, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the renderers for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param renderers the renderers (<code>null</code> not permitted).\r\n */\r\n public void setRenderers(XYItemRenderer[] renderers) {\r\n for (int i = 0; i < renderers.length; i++) {\r\n setRenderer(i, renderers[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the dataset rendering order.\r\n *\r\n * @return The order (never <code>null</code>).\r\n *\r\n * @see #setDatasetRenderingOrder(DatasetRenderingOrder)\r\n */\r\n public DatasetRenderingOrder getDatasetRenderingOrder() {\r\n return this.datasetRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the rendering order and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. By default, the plot renders the primary dataset\r\n * last (so that the primary dataset overlays the secondary datasets).\r\n * You can reverse this if you want to.\r\n *\r\n * @param order the rendering order (<code>null</code> not permitted).\r\n *\r\n * @see #getDatasetRenderingOrder()\r\n */\r\n public void setDatasetRenderingOrder(DatasetRenderingOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.datasetRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the series rendering order.\r\n *\r\n * @return the order (never <code>null</code>).\r\n *\r\n * @see #setSeriesRenderingOrder(SeriesRenderingOrder)\r\n */\r\n public SeriesRenderingOrder getSeriesRenderingOrder() {\r\n return this.seriesRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the series order and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. By default, the plot renders the primary series\r\n * last (so that the primary series appears to be on top).\r\n * You can reverse this if you want to.\r\n *\r\n * @param order the rendering order (<code>null</code> not permitted).\r\n *\r\n * @see #getSeriesRenderingOrder()\r\n */\r\n public void setSeriesRenderingOrder(SeriesRenderingOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.seriesRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified renderer, or <code>-1</code> if the\r\n * renderer is not assigned to this plot.\r\n *\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n *\r\n * @return The renderer index.\r\n */\r\n public int getIndexOf(XYItemRenderer renderer) {\r\n for (Map.Entry<Integer, XYItemRenderer> entry \r\n : this.renderers.entrySet()) {\r\n if (entry.getValue() == renderer) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the renderer for the specified dataset (this is either the\r\n * renderer with the same index as the dataset or, if there isn't a \r\n * renderer with the same index, the default renderer). If the dataset\r\n * does not belong to the plot, this method will return {@code null}.\r\n *\r\n * @param dataset the dataset ({@code null} permitted).\r\n *\r\n * @return The renderer (possibly {@code null}).\r\n */\r\n public XYItemRenderer getRendererForDataset(XYDataset dataset) {\r\n int datasetIndex = indexOf(dataset);\r\n if (datasetIndex < 0) {\r\n return null;\r\n } \r\n XYItemRenderer result = this.renderers.get(datasetIndex);\r\n if (result == null) {\r\n result = getRenderer();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the weight for this plot when it is used as a subplot within a\r\n * combined plot.\r\n *\r\n * @return The weight.\r\n *\r\n * @see #setWeight(int)\r\n */\r\n public int getWeight() {\r\n return this.weight;\r\n }\r\n\r\n /**\r\n * Sets the weight for the plot and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param weight the weight.\r\n *\r\n * @see #getWeight()\r\n */\r\n public void setWeight(int weight) {\r\n this.weight = weight;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the domain gridlines are visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setDomainGridlinesVisible(boolean)\r\n */\r\n public boolean isDomainGridlinesVisible() {\r\n return this.domainGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the domain grid-lines are\r\n * visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isDomainGridlinesVisible()\r\n */\r\n public void setDomainGridlinesVisible(boolean visible) {\r\n if (this.domainGridlinesVisible != visible) {\r\n this.domainGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the domain minor gridlines are visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setDomainMinorGridlinesVisible(boolean)\r\n *\r\n * @since 1.0.12\r\n */\r\n public boolean isDomainMinorGridlinesVisible() {\r\n return this.domainMinorGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the domain minor grid-lines\r\n * are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isDomainMinorGridlinesVisible()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlinesVisible(boolean visible) {\r\n if (this.domainMinorGridlinesVisible != visible) {\r\n this.domainMinorGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the grid-lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlineStroke(Stroke)\r\n */\r\n public Stroke getDomainGridlineStroke() {\r\n return this.domainGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the grid lines plotted against the domain axis, and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>stroke</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainGridlineStroke()\r\n */\r\n public void setDomainGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke for the minor grid-lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainMinorGridlineStroke(Stroke)\r\n *\r\n * @since 1.0.12\r\n */\r\n\r\n public Stroke getDomainMinorGridlineStroke() {\r\n return this.domainMinorGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the minor grid lines plotted against the domain\r\n * axis, and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>stroke</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainMinorGridlineStroke()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainMinorGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the grid lines (if any) plotted against the domain\r\n * axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlinePaint(Paint)\r\n */\r\n public Paint getDomainGridlinePaint() {\r\n return this.domainGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the grid lines plotted against the domain axis, and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>paint</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainGridlinePaint()\r\n */\r\n public void setDomainGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the minor grid lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainMinorGridlinePaint(Paint)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Paint getDomainMinorGridlinePaint() {\r\n return this.domainMinorGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the minor grid lines plotted against the domain axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>paint</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainMinorGridlinePaint()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainMinorGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range axis grid is visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeGridlinesVisible(boolean)\r\n */\r\n public boolean isRangeGridlinesVisible() {\r\n return this.rangeGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the range axis grid lines\r\n * are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeGridlinesVisible()\r\n */\r\n public void setRangeGridlinesVisible(boolean visible) {\r\n if (this.rangeGridlinesVisible != visible) {\r\n this.rangeGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlineStroke(Stroke)\r\n */\r\n public Stroke getRangeGridlineStroke() {\r\n return this.rangeGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the grid lines plotted against the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlineStroke()\r\n */\r\n public void setRangeGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the grid lines (if any) plotted against the range\r\n * axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlinePaint(Paint)\r\n */\r\n public Paint getRangeGridlinePaint() {\r\n return this.rangeGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the grid lines plotted against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlinePaint()\r\n */\r\n public void setRangeGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range axis minor grid is visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeMinorGridlinesVisible(boolean)\r\n *\r\n * @since 1.0.12\r\n */\r\n public boolean isRangeMinorGridlinesVisible() {\r\n return this.rangeMinorGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the range axis minor grid\r\n * lines are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeMinorGridlinesVisible()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlinesVisible(boolean visible) {\r\n if (this.rangeMinorGridlinesVisible != visible) {\r\n this.rangeMinorGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlineStroke(Stroke)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Stroke getRangeMinorGridlineStroke() {\r\n return this.rangeMinorGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the minor grid lines plotted against the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlineStroke()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeMinorGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlinePaint(Paint)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Paint getRangeMinorGridlinePaint() {\r\n return this.rangeMinorGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the minor grid lines plotted against the range axis\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlinePaint()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeMinorGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a zero baseline is\r\n * displayed for the domain axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setDomainZeroBaselineVisible(boolean)\r\n */\r\n public boolean isDomainZeroBaselineVisible() {\r\n return this.domainZeroBaselineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the zero baseline is\r\n * displayed for the domain axis, and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #isDomainZeroBaselineVisible()\r\n */\r\n public void setDomainZeroBaselineVisible(boolean visible) {\r\n this.domainZeroBaselineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used for the zero baseline against the domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setDomainZeroBaselineStroke(Stroke)\r\n */\r\n public Stroke getDomainZeroBaselineStroke() {\r\n return this.domainZeroBaselineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the zero baseline for the domain axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getRangeZeroBaselineStroke()\r\n */\r\n public void setDomainZeroBaselineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainZeroBaselineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the zero baseline (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainZeroBaselinePaint(Paint)\r\n */\r\n public Paint getDomainZeroBaselinePaint() {\r\n return this.domainZeroBaselinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the zero baseline plotted against the domain axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getDomainZeroBaselinePaint()\r\n */\r\n public void setDomainZeroBaselinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainZeroBaselinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a zero baseline is\r\n * displayed for the range axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n */\r\n public boolean isRangeZeroBaselineVisible() {\r\n return this.rangeZeroBaselineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the zero baseline is\r\n * displayed for the range axis, and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isRangeZeroBaselineVisible()\r\n */\r\n public void setRangeZeroBaselineVisible(boolean visible) {\r\n this.rangeZeroBaselineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used for the zero baseline against the range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselineStroke(Stroke)\r\n */\r\n public Stroke getRangeZeroBaselineStroke() {\r\n return this.rangeZeroBaselineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the zero baseline for the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselineStroke()\r\n */\r\n public void setRangeZeroBaselineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeZeroBaselineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the zero baseline (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselinePaint(Paint)\r\n */\r\n public Paint getRangeZeroBaselinePaint() {\r\n return this.rangeZeroBaselinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the zero baseline plotted against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselinePaint()\r\n */\r\n public void setRangeZeroBaselinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeZeroBaselinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the domain tick bands. If this is\r\n * <code>null</code>, no tick bands will be drawn.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setDomainTickBandPaint(Paint)\r\n */\r\n public Paint getDomainTickBandPaint() {\r\n return this.domainTickBandPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the domain tick bands.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getDomainTickBandPaint()\r\n */\r\n public void setDomainTickBandPaint(Paint paint) {\r\n this.domainTickBandPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the range tick bands. If this is\r\n * <code>null</code>, no tick bands will be drawn.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setRangeTickBandPaint(Paint)\r\n */\r\n public Paint getRangeTickBandPaint() {\r\n return this.rangeTickBandPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the range tick bands.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getRangeTickBandPaint()\r\n */\r\n public void setRangeTickBandPaint(Paint paint) {\r\n this.rangeTickBandPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the origin for the quadrants that can be displayed on the plot.\r\n * This defaults to (0, 0).\r\n *\r\n * @return The origin point (never <code>null</code>).\r\n *\r\n * @see #setQuadrantOrigin(Point2D)\r\n */\r\n public Point2D getQuadrantOrigin() {\r\n return this.quadrantOrigin;\r\n }\r\n\r\n /**\r\n * Sets the quadrant origin and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param origin the origin (<code>null</code> not permitted).\r\n *\r\n * @see #getQuadrantOrigin()\r\n */\r\n public void setQuadrantOrigin(Point2D origin) {\r\n ParamChecks.nullNotPermitted(origin, \"origin\");\r\n this.quadrantOrigin = origin;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the specified quadrant.\r\n *\r\n * @param index the quadrant index (0-3).\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setQuadrantPaint(int, Paint)\r\n */\r\n public Paint getQuadrantPaint(int index) {\r\n if (index < 0 || index > 3) {\r\n throw new IllegalArgumentException(\"The index value (\" + index\r\n + \") should be in the range 0 to 3.\");\r\n }\r\n return this.quadrantPaint[index];\r\n }\r\n\r\n /**\r\n * Sets the paint used for the specified quadrant and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the quadrant index (0-3).\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getQuadrantPaint(int)\r\n */\r\n public void setQuadrantPaint(int index, Paint paint) {\r\n if (index < 0 || index > 3) {\r\n throw new IllegalArgumentException(\"The index value (\" + index\r\n + \") should be in the range 0 to 3.\");\r\n }\r\n this.quadrantPaint[index] = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #addDomainMarker(Marker, Layer)\r\n * @see #clearDomainMarkers()\r\n */\r\n public void addDomainMarker(Marker marker) {\r\n // defer argument checking...\r\n addDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for the domain axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void addDomainMarker(Marker marker, Layer layer) {\r\n addDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Clears all the (foreground and background) domain markers and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void clearDomainMarkers() {\r\n if (this.backgroundDomainMarkers != null) {\r\n Set<Integer> keys = this.backgroundDomainMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearDomainMarkers(key);\r\n }\r\n this.backgroundDomainMarkers.clear();\r\n }\r\n if (this.foregroundDomainMarkers != null) {\r\n Set<Integer> keys = this.foregroundDomainMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearDomainMarkers(key);\r\n }\r\n this.foregroundDomainMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Clears the (foreground and background) domain markers for a particular\r\n * renderer and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the renderer index.\r\n *\r\n * @see #clearRangeMarkers(int)\r\n */\r\n public void clearDomainMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundDomainMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis (that the renderer is mapped to), however this is\r\n * entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #clearDomainMarkers(int)\r\n * @see #addRangeMarker(int, Marker, Layer)\r\n */\r\n public void addDomainMarker(int index, Marker marker, Layer layer) {\r\n addDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis (that the renderer is mapped to), however this is\r\n * entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addDomainMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ParamChecks.nullNotPermitted(layer, \"layer\");\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker) {\r\n return removeDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker, Layer layer) {\r\n return removeDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer) {\r\n return removeDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and, if requested,\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ArrayList markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (ArrayList) this.foregroundDomainMarkers.get(\r\n new Integer(index));\r\n }\r\n else {\r\n markers = (ArrayList) this.backgroundDomainMarkers.get(\r\n new Integer(index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Adds a marker for the range axis and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #addRangeMarker(Marker, Layer)\r\n */\r\n public void addRangeMarker(Marker marker) {\r\n addRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for the range axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #addRangeMarker(int, Marker, Layer)\r\n */\r\n public void addRangeMarker(Marker marker, Layer layer) {\r\n addRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Clears all the range markers and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @see #clearRangeMarkers()\r\n */\r\n public void clearRangeMarkers() {\r\n if (this.backgroundRangeMarkers != null) {\r\n Set<Integer> keys = this.backgroundRangeMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearRangeMarkers(key);\r\n }\r\n this.backgroundRangeMarkers.clear();\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Set<Integer> keys = this.foregroundRangeMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearRangeMarkers(key);\r\n }\r\n this.foregroundRangeMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #clearRangeMarkers(int)\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer) {\r\n addRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Clears the (foreground and background) range markers for a particular\r\n * renderer.\r\n *\r\n * @param index the renderer index.\r\n */\r\n public void clearRangeMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(Marker marker) {\r\n return removeRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(Marker marker, Layer layer) {\r\n return removeRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer) {\r\n return removeRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background) (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ParamChecks.nullNotPermitted(layer, \"layer\");\r\n List markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (List) this.foregroundRangeMarkers.get(\r\n new Integer(index));\r\n }\r\n else {\r\n markers = (List) this.backgroundRangeMarkers.get(\r\n new Integer(index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @see #getAnnotations()\r\n * @see #removeAnnotation(XYAnnotation)\r\n */\r\n public void addAnnotation(XYAnnotation annotation) {\r\n addAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addAnnotation(XYAnnotation annotation, boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n this.annotations.add(annotation);\r\n annotation.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n * @see #getAnnotations()\r\n */\r\n public boolean removeAnnotation(XYAnnotation annotation) {\r\n return removeAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeAnnotation(XYAnnotation annotation, boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n boolean removed = this.annotations.remove(annotation);\r\n annotation.removeChangeListener(this);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Returns the list of annotations.\r\n *\r\n * @return The list of annotations.\r\n *\r\n * @since 1.0.1\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n */\r\n public List getAnnotations() {\r\n return new ArrayList(this.annotations);\r\n }\r\n\r\n /**\r\n * Clears all the annotations and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n */\r\n public void clearAnnotations() {\r\n for (XYAnnotation annotation : this.annotations) {\r\n annotation.removeChangeListener(this);\r\n }\r\n this.annotations.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the shadow generator for the plot, if any.\r\n *\r\n * @return The shadow generator (possibly <code>null</code>).\r\n *\r\n * @since 1.0.14\r\n */\r\n public ShadowGenerator getShadowGenerator() {\r\n return this.shadowGenerator;\r\n }\r\n\r\n /**\r\n * Sets the shadow generator for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setShadowGenerator(ShadowGenerator generator) {\r\n this.shadowGenerator = generator;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Calculates the space required for all the axes in the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateAxisSpace(Graphics2D g2,\r\n Rectangle2D plotArea) {\r\n AxisSpace space = new AxisSpace();\r\n space = calculateRangeAxisSpace(g2, plotArea, space);\r\n Rectangle2D revPlotArea = space.shrink(plotArea, null);\r\n space = calculateDomainAxisSpace(g2, revPlotArea, space);\r\n return space;\r\n }\r\n\r\n /**\r\n * Calculates the space required for the domain axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateDomainAxisSpace(Graphics2D g2, \r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the domain axis...\r\n if (this.fixedDomainAxisSpace != null) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getLeft(),\r\n RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n }\r\n else if (this.orientation == PlotOrientation.VERTICAL) {\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n }\r\n }\r\n else {\r\n // reserve space for the domain axes...\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n RectangleEdge edge = getDomainAxisEdge(\r\n findDomainAxisIndex(axis));\r\n space = axis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the space required for the range axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateRangeAxisSpace(Graphics2D g2, \r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the range axis...\r\n if (this.fixedRangeAxisSpace != null) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n }\r\n else if (this.orientation == PlotOrientation.VERTICAL) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getLeft(),\r\n RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n }\r\n }\r\n else {\r\n // reserve space for the range axes...\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n RectangleEdge edge = getRangeAxisEdge(\r\n findRangeAxisIndex(axis));\r\n space = axis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Trims a rectangle to integer coordinates.\r\n *\r\n * @param rect the incoming rectangle.\r\n *\r\n * @return A rectangle with integer coordinates.\r\n */\r\n private Rectangle integerise(Rectangle2D rect) {\r\n int x0 = (int) Math.ceil(rect.getMinX());\r\n int y0 = (int) Math.ceil(rect.getMinY());\r\n int x1 = (int) Math.floor(rect.getMaxX());\r\n int y1 = (int) Math.floor(rect.getMaxY());\r\n return new Rectangle(x0, y0, (x1 - x0), (y1 - y0));\r\n }\r\n\r\n /**\r\n * Draws the plot within the specified area on a graphics device.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the plot area (in Java2D space).\r\n * @param anchor an anchor point in Java2D space (<code>null</code>\r\n * permitted).\r\n * @param parentState the state from the parent plot, if there is one\r\n * (<code>null</code> permitted).\r\n * @param info collects chart drawing information (<code>null</code>\r\n * permitted).\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor,\r\n PlotState parentState, PlotRenderingInfo info) {\r\n\r\n // if the plot area is too small, just return...\r\n boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW);\r\n boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW);\r\n if (b1 || b2) {\r\n return;\r\n }\r\n\r\n // record the plot area...\r\n if (info != null) {\r\n info.setPlotArea(area);\r\n }\r\n\r\n // adjust the drawing area for the plot insets (if any)...\r\n RectangleInsets insets = getInsets();\r\n insets.trim(area);\r\n\r\n AxisSpace space = calculateAxisSpace(g2, area);\r\n Rectangle2D dataArea = space.shrink(area, null);\r\n this.axisOffset.trim(dataArea);\r\n\r\n dataArea = integerise(dataArea);\r\n if (dataArea.isEmpty()) {\r\n return;\r\n }\r\n createAndAddEntity((Rectangle2D) dataArea.clone(), info, null, null);\r\n if (info != null) {\r\n info.setDataArea(dataArea);\r\n }\r\n\r\n // draw the plot background and axes...\r\n drawBackground(g2, dataArea);\r\n Map axisStateMap = drawAxes(g2, area, dataArea, info);\r\n\r\n PlotOrientation orient = getOrientation();\r\n\r\n // the anchor point is typically the point where the mouse last\r\n // clicked - the crosshairs will be driven off this point...\r\n if (anchor != null && !dataArea.contains(anchor)) {\r\n anchor = null;\r\n }\r\n CrosshairState crosshairState = new CrosshairState();\r\n crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY);\r\n crosshairState.setAnchor(anchor);\r\n\r\n crosshairState.setAnchorX(Double.NaN);\r\n crosshairState.setAnchorY(Double.NaN);\r\n if (anchor != null) {\r\n ValueAxis domainAxis = getDomainAxis();\r\n if (domainAxis != null) {\r\n double x;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n x = domainAxis.java2DToValue(anchor.getX(), dataArea,\r\n getDomainAxisEdge());\r\n }\r\n else {\r\n x = domainAxis.java2DToValue(anchor.getY(), dataArea,\r\n getDomainAxisEdge());\r\n }\r\n crosshairState.setAnchorX(x);\r\n }\r\n ValueAxis rangeAxis = getRangeAxis();\r\n if (rangeAxis != null) {\r\n double y;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n y = rangeAxis.java2DToValue(anchor.getY(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n else {\r\n y = rangeAxis.java2DToValue(anchor.getX(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n crosshairState.setAnchorY(y);\r\n }\r\n }\r\n crosshairState.setCrosshairX(getDomainCrosshairValue());\r\n crosshairState.setCrosshairY(getRangeCrosshairValue());\r\n Shape originalClip = g2.getClip();\r\n Composite originalComposite = g2.getComposite();\r\n\r\n g2.clip(dataArea);\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n getForegroundAlpha()));\r\n\r\n AxisState domainAxisState = (AxisState) axisStateMap.get(\r\n getDomainAxis());\r\n if (domainAxisState == null) {\r\n if (parentState != null) {\r\n domainAxisState = (AxisState) parentState.getSharedAxisStates()\r\n .get(getDomainAxis());\r\n }\r\n }\r\n\r\n AxisState rangeAxisState = (AxisState) axisStateMap.get(getRangeAxis());\r\n if (rangeAxisState == null) {\r\n if (parentState != null) {\r\n rangeAxisState = (AxisState) parentState.getSharedAxisStates()\r\n .get(getRangeAxis());\r\n }\r\n }\r\n if (domainAxisState != null) {\r\n drawDomainTickBands(g2, dataArea, domainAxisState.getTicks());\r\n }\r\n if (rangeAxisState != null) {\r\n drawRangeTickBands(g2, dataArea, rangeAxisState.getTicks());\r\n }\r\n if (domainAxisState != null) {\r\n drawDomainGridlines(g2, dataArea, domainAxisState.getTicks());\r\n drawZeroDomainBaseline(g2, dataArea);\r\n }\r\n if (rangeAxisState != null) {\r\n drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks());\r\n drawZeroRangeBaseline(g2, dataArea);\r\n }\r\n\r\n Graphics2D savedG2 = g2;\r\n BufferedImage dataImage = null;\r\n boolean suppressShadow = Boolean.TRUE.equals(g2.getRenderingHint(\r\n JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION));\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n dataImage = new BufferedImage((int) dataArea.getWidth(),\r\n (int)dataArea.getHeight(), BufferedImage.TYPE_INT_ARGB);\r\n g2 = dataImage.createGraphics();\r\n g2.translate(-dataArea.getX(), -dataArea.getY());\r\n g2.setRenderingHints(savedG2.getRenderingHints());\r\n }\r\n\r\n // draw the markers that are associated with a specific dataset...\r\n for (XYDataset dataset: this.datasets.values()) {\r\n int datasetIndex = indexOf(dataset);\r\n drawDomainMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND);\r\n }\r\n for (XYDataset dataset: this.datasets.values()) {\r\n int datasetIndex = indexOf(dataset);\r\n drawRangeMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND);\r\n }\r\n\r\n // now draw annotations and render data items...\r\n boolean foundData = false;\r\n DatasetRenderingOrder order = getDatasetRenderingOrder();\r\n List<Integer> rendererIndices = getRendererIndices(order);\r\n List<Integer> datasetIndices = getDatasetIndices(order);\r\n // draw background annotations\r\n for (int i : rendererIndices) {\r\n XYItemRenderer renderer = getRenderer(i);\r\n if (renderer != null) {\r\n ValueAxis domainAxis = getDomainAxisForDataset(i);\r\n ValueAxis rangeAxis = getRangeAxisForDataset(i);\r\n renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, \r\n Layer.BACKGROUND, info);\r\n }\r\n }\r\n\r\n // render data items...\r\n for (int datasetIndex : datasetIndices) {\r\n XYDataset dataset = this.getDataset(datasetIndex);\r\n foundData = render(g2, dataArea, datasetIndex, info, \r\n crosshairState) || foundData;\r\n }\r\n\r\n // draw foreground annotations\r\n for (int i : rendererIndices) {\r\n XYItemRenderer renderer = getRenderer(i);\r\n if (renderer != null) {\r\n ValueAxis domainAxis = getDomainAxisForDataset(i);\r\n ValueAxis rangeAxis = getRangeAxisForDataset(i);\r\n renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, \r\n Layer.FOREGROUND, info);\r\n }\r\n }\r\n\r\n // draw domain crosshair if required...\r\n int datasetIndex = crosshairState.getDatasetIndex();\r\n ValueAxis xAxis = this.getDomainAxisForDataset(datasetIndex);\r\n RectangleEdge xAxisEdge = getDomainAxisEdge(getDomainAxisIndex(xAxis));\r\n if (!this.domainCrosshairLockedOnData && anchor != null) {\r\n double xx;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n xx = xAxis.java2DToValue(anchor.getX(), dataArea, xAxisEdge);\r\n }\r\n else {\r\n xx = xAxis.java2DToValue(anchor.getY(), dataArea, xAxisEdge);\r\n }\r\n crosshairState.setCrosshairX(xx);\r\n }\r\n setDomainCrosshairValue(crosshairState.getCrosshairX(), false);\r\n if (isDomainCrosshairVisible()) {\r\n double x = getDomainCrosshairValue();\r\n Paint paint = getDomainCrosshairPaint();\r\n Stroke stroke = getDomainCrosshairStroke();\r\n drawDomainCrosshair(g2, dataArea, orient, x, xAxis, stroke, paint);\r\n }\r\n\r\n // draw range crosshair if required...\r\n ValueAxis yAxis = getRangeAxisForDataset(datasetIndex);\r\n RectangleEdge yAxisEdge = getRangeAxisEdge(getRangeAxisIndex(yAxis));\r\n if (!this.rangeCrosshairLockedOnData && anchor != null) {\r\n double yy;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n yy = yAxis.java2DToValue(anchor.getY(), dataArea, yAxisEdge);\r\n } else {\r\n yy = yAxis.java2DToValue(anchor.getX(), dataArea, yAxisEdge);\r\n }\r\n crosshairState.setCrosshairY(yy);\r\n }\r\n setRangeCrosshairValue(crosshairState.getCrosshairY(), false);\r\n if (isRangeCrosshairVisible()) {\r\n double y = getRangeCrosshairValue();\r\n Paint paint = getRangeCrosshairPaint();\r\n Stroke stroke = getRangeCrosshairStroke();\r\n drawRangeCrosshair(g2, dataArea, orient, y, yAxis, stroke, paint);\r\n }\r\n\r\n if (!foundData) {\r\n drawNoDataMessage(g2, dataArea);\r\n }\r\n\r\n for (int i : rendererIndices) { \r\n drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n for (int i : rendererIndices) {\r\n drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n\r\n drawAnnotations(g2, dataArea, info);\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n BufferedImage shadowImage\r\n = this.shadowGenerator.createDropShadow(dataImage);\r\n g2 = savedG2;\r\n g2.drawImage(shadowImage, (int) dataArea.getX()\r\n + this.shadowGenerator.calculateOffsetX(),\r\n (int) dataArea.getY()\r\n + this.shadowGenerator.calculateOffsetY(), null);\r\n g2.drawImage(dataImage, (int) dataArea.getX(),\r\n (int) dataArea.getY(), null);\r\n }\r\n g2.setClip(originalClip);\r\n g2.setComposite(originalComposite);\r\n\r\n drawOutline(g2, dataArea);\r\n\r\n }\r\n\r\n /**\r\n * Returns the indices of the non-null datasets in the specified order.\r\n * \r\n * @param order the order (<code>null</code> not permitted).\r\n * \r\n * @return The list of indices. \r\n */\r\n private List<Integer> getDatasetIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result;\r\n }\r\n \r\n private List<Integer> getRendererIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Entry<Integer, XYItemRenderer> entry : this.renderers.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result; \r\n }\r\n \r\n /**\r\n * Draws the background for the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n */\r\n @Override\r\n public void drawBackground(Graphics2D g2, Rectangle2D area) {\r\n fillBackground(g2, area, this.orientation);\r\n drawQuadrants(g2, area);\r\n drawBackgroundImage(g2, area);\r\n }\r\n\r\n /**\r\n * Draws the quadrants.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n *\r\n * @see #setQuadrantOrigin(Point2D)\r\n * @see #setQuadrantPaint(int, Paint)\r\n */\r\n protected void drawQuadrants(Graphics2D g2, Rectangle2D area) {\r\n // 0 | 1\r\n // --+--\r\n // 2 | 3\r\n boolean somethingToDraw = false;\r\n\r\n ValueAxis xAxis = getDomainAxis();\r\n if (xAxis == null) { // we can't draw quadrants without a valid x-axis\r\n return;\r\n }\r\n double x = xAxis.getRange().constrain(this.quadrantOrigin.getX());\r\n double xx = xAxis.valueToJava2D(x, area, getDomainAxisEdge());\r\n\r\n ValueAxis yAxis = getRangeAxis();\r\n if (yAxis == null) { // we can't draw quadrants without a valid y-axis\r\n return;\r\n }\r\n double y = yAxis.getRange().constrain(this.quadrantOrigin.getY());\r\n double yy = yAxis.valueToJava2D(y, area, getRangeAxisEdge());\r\n\r\n double xmin = xAxis.getLowerBound();\r\n double xxmin = xAxis.valueToJava2D(xmin, area, getDomainAxisEdge());\r\n\r\n double xmax = xAxis.getUpperBound();\r\n double xxmax = xAxis.valueToJava2D(xmax, area, getDomainAxisEdge());\r\n\r\n double ymin = yAxis.getLowerBound();\r\n double yymin = yAxis.valueToJava2D(ymin, area, getRangeAxisEdge());\r\n\r\n double ymax = yAxis.getUpperBound();\r\n double yymax = yAxis.valueToJava2D(ymax, area, getRangeAxisEdge());\r\n\r\n Rectangle2D[] r = new Rectangle2D[] {null, null, null, null};\r\n if (this.quadrantPaint[0] != null) {\r\n if (x > xmin && y < ymax) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[0] = new Rectangle2D.Double(Math.min(yymax, yy),\r\n Math.min(xxmin, xx), Math.abs(yy - yymax),\r\n Math.abs(xx - xxmin));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[0] = new Rectangle2D.Double(Math.min(xxmin, xx),\r\n Math.min(yymax, yy), Math.abs(xx - xxmin),\r\n Math.abs(yy - yymax));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[1] != null) {\r\n if (x < xmax && y < ymax) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[1] = new Rectangle2D.Double(Math.min(yymax, yy),\r\n Math.min(xxmax, xx), Math.abs(yy - yymax),\r\n Math.abs(xx - xxmax));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[1] = new Rectangle2D.Double(Math.min(xx, xxmax),\r\n Math.min(yymax, yy), Math.abs(xx - xxmax),\r\n Math.abs(yy - yymax));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[2] != null) {\r\n if (x > xmin && y > ymin) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[2] = new Rectangle2D.Double(Math.min(yymin, yy),\r\n Math.min(xxmin, xx), Math.abs(yy - yymin),\r\n Math.abs(xx - xxmin));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[2] = new Rectangle2D.Double(Math.min(xxmin, xx),\r\n Math.min(yymin, yy), Math.abs(xx - xxmin),\r\n Math.abs(yy - yymin));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[3] != null) {\r\n if (x < xmax && y > ymin) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[3] = new Rectangle2D.Double(Math.min(yymin, yy),\r\n Math.min(xxmax, xx), Math.abs(yy - yymin),\r\n Math.abs(xx - xxmax));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[3] = new Rectangle2D.Double(Math.min(xx, xxmax),\r\n Math.min(yymin, yy), Math.abs(xx - xxmax),\r\n Math.abs(yy - yymin));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (somethingToDraw) {\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n getBackgroundAlpha()));\r\n for (int i = 0; i < 4; i++) {\r\n if (this.quadrantPaint[i] != null && r[i] != null) {\r\n g2.setPaint(this.quadrantPaint[i]);\r\n g2.fill(r[i]);\r\n }\r\n }\r\n g2.setComposite(originalComposite);\r\n }\r\n }\r\n\r\n /**\r\n * Draws the domain tick bands, if any.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #setDomainTickBandPaint(Paint)\r\n */\r\n public void drawDomainTickBands(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n Paint bandPaint = getDomainTickBandPaint();\r\n if (bandPaint != null) {\r\n boolean fillBand = false;\r\n ValueAxis xAxis = getDomainAxis();\r\n double previous = xAxis.getLowerBound();\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n double current = tick.getValue();\r\n if (fillBand) {\r\n getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea,\r\n previous, current);\r\n }\r\n previous = current;\r\n fillBand = !fillBand;\r\n }\r\n double end = xAxis.getUpperBound();\r\n if (fillBand) {\r\n getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea,\r\n previous, end);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws the range tick bands, if any.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #setRangeTickBandPaint(Paint)\r\n */\r\n public void drawRangeTickBands(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n Paint bandPaint = getRangeTickBandPaint();\r\n if (bandPaint != null) {\r\n boolean fillBand = false;\r\n ValueAxis axis = getRangeAxis();\r\n double previous = axis.getLowerBound();\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n double current = tick.getValue();\r\n if (fillBand) {\r\n getRenderer().fillRangeGridBand(g2, this, axis, dataArea,\r\n previous, current);\r\n }\r\n previous = current;\r\n fillBand = !fillBand;\r\n }\r\n double end = axis.getUpperBound();\r\n if (fillBand) {\r\n getRenderer().fillRangeGridBand(g2, this, axis, dataArea,\r\n previous, end);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * A utility method for drawing the axes.\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param plotArea the plot area (<code>null</code> not permitted).\r\n * @param dataArea the data area (<code>null</code> not permitted).\r\n * @param plotState collects information about the plot (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A map containing the state for each axis drawn.\r\n */\r\n protected Map<Axis, AxisState> drawAxes(Graphics2D g2, Rectangle2D plotArea,\r\n Rectangle2D dataArea, PlotRenderingInfo plotState) {\r\n\r\n AxisCollection axisCollection = new AxisCollection();\r\n\r\n // add domain axes to lists...\r\n for (ValueAxis axis : this.domainAxes.values()) {\r\n if (axis != null) {\r\n int axisIndex = findDomainAxisIndex(axis);\r\n axisCollection.add(axis, getDomainAxisEdge(axisIndex));\r\n }\r\n }\r\n\r\n // add range axes to lists...\r\n for (ValueAxis axis : this.rangeAxes.values()) {\r\n if (axis != null) {\r\n int axisIndex = findRangeAxisIndex(axis);\r\n axisCollection.add(axis, getRangeAxisEdge(axisIndex));\r\n }\r\n }\r\n\r\n Map axisStateMap = new HashMap();\r\n\r\n // draw the top axes\r\n double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset(\r\n dataArea.getHeight());\r\n Iterator iterator = axisCollection.getAxesAtTop().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.TOP, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the bottom axes\r\n cursor = dataArea.getMaxY()\r\n + this.axisOffset.calculateBottomOutset(dataArea.getHeight());\r\n iterator = axisCollection.getAxesAtBottom().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.BOTTOM, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the left axes\r\n cursor = dataArea.getMinX()\r\n - this.axisOffset.calculateLeftOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtLeft().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.LEFT, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the right axes\r\n cursor = dataArea.getMaxX()\r\n + this.axisOffset.calculateRightOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtRight().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.RIGHT, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n return axisStateMap;\r\n }\r\n\r\n /**\r\n * Draws a representation of the data within the dataArea region, using the\r\n * current renderer.\r\n * <P>\r\n * The <code>info</code> and <code>crosshairState</code> arguments may be\r\n * <code>null</code>.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the region in which the data is to be drawn.\r\n * @param index the dataset index.\r\n * @param info an optional object for collection dimension information.\r\n * @param crosshairState collects crosshair information\r\n * (<code>null</code> permitted).\r\n *\r\n * @return A flag that indicates whether any data was actually rendered.\r\n */\r\n public boolean render(Graphics2D g2, Rectangle2D dataArea, int index,\r\n PlotRenderingInfo info, CrosshairState crosshairState) {\r\n\r\n boolean foundData = false;\r\n XYDataset dataset = getDataset(index);\r\n if (!DatasetUtilities.isEmptyOrNull(dataset)) {\r\n foundData = true;\r\n ValueAxis xAxis = getDomainAxisForDataset(index);\r\n ValueAxis yAxis = getRangeAxisForDataset(index);\r\n if (xAxis == null || yAxis == null) {\r\n return foundData; // can't render anything without axes\r\n }\r\n XYItemRenderer renderer = getRenderer(index);\r\n if (renderer == null) {\r\n renderer = getRenderer();\r\n if (renderer == null) { // no default renderer available\r\n return foundData;\r\n }\r\n }\r\n\r\n XYItemRendererState state = renderer.initialise(g2, dataArea, this,\r\n dataset, info);\r\n int passCount = renderer.getPassCount();\r\n\r\n SeriesRenderingOrder seriesOrder = getSeriesRenderingOrder();\r\n if (seriesOrder == SeriesRenderingOrder.REVERSE) {\r\n //render series in reverse order\r\n for (int pass = 0; pass < passCount; pass++) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = seriesCount - 1; series >= 0; series--) {\r\n int firstItem = 0;\r\n int lastItem = dataset.getItemCount(series) - 1;\r\n if (lastItem == -1) {\r\n continue;\r\n }\r\n if (state.getProcessVisibleItemsOnly()) {\r\n int[] itemBounds = RendererUtilities.findLiveItems(\r\n dataset, series, xAxis.getLowerBound(),\r\n xAxis.getUpperBound());\r\n firstItem = Math.max(itemBounds[0] - 1, 0);\r\n lastItem = Math.min(itemBounds[1] + 1, lastItem);\r\n }\r\n state.startSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n for (int item = firstItem; item <= lastItem; item++) {\r\n renderer.drawItem(g2, state, dataArea, info,\r\n this, xAxis, yAxis, dataset, series, item,\r\n crosshairState, pass);\r\n }\r\n state.endSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n }\r\n }\r\n }\r\n else {\r\n //render series in forward order\r\n for (int pass = 0; pass < passCount; pass++) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n int firstItem = 0;\r\n int lastItem = dataset.getItemCount(series) - 1;\r\n if (state.getProcessVisibleItemsOnly()) {\r\n int[] itemBounds = RendererUtilities.findLiveItems(\r\n dataset, series, xAxis.getLowerBound(),\r\n xAxis.getUpperBound());\r\n firstItem = Math.max(itemBounds[0] - 1, 0);\r\n lastItem = Math.min(itemBounds[1] + 1, lastItem);\r\n }\r\n state.startSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n for (int item = firstItem; item <= lastItem; item++) {\r\n renderer.drawItem(g2, state, dataArea, info,\r\n this, xAxis, yAxis, dataset, series, item,\r\n crosshairState, pass);\r\n }\r\n state.endSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n }\r\n }\r\n }\r\n }\r\n return foundData;\r\n }\r\n\r\n /**\r\n * Returns the domain axis for a dataset.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The axis.\r\n */\r\n public ValueAxis getDomainAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n ValueAxis valueAxis;\r\n List axisIndices = (List) this.datasetToDomainAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n valueAxis = getDomainAxis(axisIndex.intValue());\r\n }\r\n else {\r\n valueAxis = getDomainAxis(0);\r\n }\r\n return valueAxis;\r\n }\r\n\r\n /**\r\n * Returns the range axis for a dataset.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The axis.\r\n */\r\n public ValueAxis getRangeAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n ValueAxis valueAxis;\r\n List axisIndices = (List) this.datasetToRangeAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n valueAxis = getRangeAxis(axisIndex.intValue());\r\n }\r\n else {\r\n valueAxis = getRangeAxis(0);\r\n }\r\n return valueAxis;\r\n }\r\n\r\n /**\r\n * Draws the gridlines for the plot, if they are visible.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #drawRangeGridlines(Graphics2D, Rectangle2D, List)\r\n */\r\n protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n\r\n // no renderer, no gridlines...\r\n if (getRenderer() == null) {\r\n return;\r\n }\r\n\r\n // draw the domain grid lines, if any...\r\n if (isDomainGridlinesVisible() || isDomainMinorGridlinesVisible()) {\r\n Stroke gridStroke = null;\r\n Paint gridPaint = null;\r\n Iterator iterator = ticks.iterator();\r\n boolean paintLine;\r\n while (iterator.hasNext()) {\r\n paintLine = false;\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if ((tick.getTickType() == TickType.MINOR)\r\n && isDomainMinorGridlinesVisible()) {\r\n gridStroke = getDomainMinorGridlineStroke();\r\n gridPaint = getDomainMinorGridlinePaint();\r\n paintLine = true;\r\n } else if ((tick.getTickType() == TickType.MAJOR)\r\n && isDomainGridlinesVisible()) {\r\n gridStroke = getDomainGridlineStroke();\r\n gridPaint = getDomainGridlinePaint();\r\n paintLine = true;\r\n }\r\n XYItemRenderer r = getRenderer();\r\n if ((r instanceof AbstractXYItemRenderer) && paintLine) {\r\n ((AbstractXYItemRenderer) r).drawDomainLine(g2, this,\r\n getDomainAxis(), dataArea, tick.getValue(),\r\n gridPaint, gridStroke);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws the gridlines for the plot's primary range axis, if they are\r\n * visible.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #drawDomainGridlines(Graphics2D, Rectangle2D, List)\r\n */\r\n protected void drawRangeGridlines(Graphics2D g2, Rectangle2D area,\r\n List ticks) {\r\n\r\n // no renderer, no gridlines...\r\n if (getRenderer() == null) {\r\n return;\r\n }\r\n\r\n // draw the range grid lines, if any...\r\n if (isRangeGridlinesVisible() || isRangeMinorGridlinesVisible()) {\r\n Stroke gridStroke = null;\r\n Paint gridPaint = null;\r\n ValueAxis axis = getRangeAxis();\r\n if (axis != null) {\r\n Iterator iterator = ticks.iterator();\r\n boolean paintLine;\r\n while (iterator.hasNext()) {\r\n paintLine = false;\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if ((tick.getTickType() == TickType.MINOR)\r\n && isRangeMinorGridlinesVisible()) {\r\n gridStroke = getRangeMinorGridlineStroke();\r\n gridPaint = getRangeMinorGridlinePaint();\r\n paintLine = true;\r\n } else if ((tick.getTickType() == TickType.MAJOR)\r\n && isRangeGridlinesVisible()) {\r\n gridStroke = getRangeGridlineStroke();\r\n gridPaint = getRangeGridlinePaint();\r\n paintLine = true;\r\n }\r\n if ((tick.getValue() != 0.0\r\n || !isRangeZeroBaselineVisible()) && paintLine) {\r\n getRenderer().drawRangeLine(g2, this, getRangeAxis(),\r\n area, tick.getValue(), gridPaint, gridStroke);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws a base line across the chart at value zero on the domain axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n *\r\n * @see #setDomainZeroBaselineVisible(boolean)\r\n *\r\n * @since 1.0.5\r\n */\r\n protected void drawZeroDomainBaseline(Graphics2D g2, Rectangle2D area) {\r\n if (isDomainZeroBaselineVisible()) {\r\n XYItemRenderer r = getRenderer();\r\n // FIXME: the renderer interface doesn't have the drawDomainLine()\r\n // method, so we have to rely on the renderer being a subclass of\r\n // AbstractXYItemRenderer (which is lame)\r\n if (r instanceof AbstractXYItemRenderer) {\r\n AbstractXYItemRenderer renderer = (AbstractXYItemRenderer) r;\r\n renderer.drawDomainLine(g2, this, getDomainAxis(), area, 0.0,\r\n this.domainZeroBaselinePaint,\r\n this.domainZeroBaselineStroke);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws a base line across the chart at value zero on the range axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n */\r\n protected void drawZeroRangeBaseline(Graphics2D g2, Rectangle2D area) {\r\n if (isRangeZeroBaselineVisible()) {\r\n getRenderer().drawRangeLine(g2, this, getRangeAxis(), area, 0.0,\r\n this.rangeZeroBaselinePaint, this.rangeZeroBaselineStroke);\r\n }\r\n }\r\n\r\n /**\r\n * Draws the annotations for the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param info the chart rendering info.\r\n */\r\n public void drawAnnotations(Graphics2D g2, Rectangle2D dataArea,\r\n PlotRenderingInfo info) {\r\n\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n ValueAxis xAxis = getDomainAxis();\r\n ValueAxis yAxis = getRangeAxis();\r\n annotation.draw(g2, this, dataArea, xAxis, yAxis, 0, info);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the domain markers (if any) for an axis and layer. This method is\r\n * typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the dataset/renderer index.\r\n * @param layer the layer (foreground or background).\r\n */\r\n protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n XYItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n // check that the renderer has a corresponding dataset (it doesn't\r\n // matter if the dataset is null)\r\n if (index >= getDatasetCount()) {\r\n return;\r\n }\r\n Collection markers = getDomainMarkers(index, layer);\r\n ValueAxis axis = getDomainAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker marker = (Marker) iterator.next();\r\n r.drawDomainMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the range markers (if any) for a renderer and layer. This method\r\n * is typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the renderer index.\r\n * @param layer the layer (foreground or background).\r\n */\r\n protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n XYItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n // check that the renderer has a corresponding dataset (it doesn't\r\n // matter if the dataset is null)\r\n if (index >= getDatasetCount()) {\r\n return;\r\n }\r\n Collection markers = getRangeMarkers(index, layer);\r\n ValueAxis axis = getRangeAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker marker = (Marker) iterator.next();\r\n r.drawRangeMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the list of domain markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of domain markers.\r\n *\r\n * @see #getRangeMarkers(Layer)\r\n */\r\n public Collection getDomainMarkers(Layer layer) {\r\n return getDomainMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns the list of range markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of range markers.\r\n *\r\n * @see #getDomainMarkers(Layer)\r\n */\r\n public Collection getRangeMarkers(Layer layer) {\r\n return getRangeMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns a collection of domain markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n *\r\n * @see #getRangeMarkers(int, Layer)\r\n */\r\n public Collection getDomainMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundDomainMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundDomainMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a collection of range markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n *\r\n * @see #getDomainMarkers(int, Layer)\r\n */\r\n public Collection getRangeMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundRangeMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundRangeMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Utility method for drawing a horizontal line across the data area of the\r\n * plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param value the coordinate, where to draw the line.\r\n * @param stroke the stroke to use.\r\n * @param paint the paint to use.\r\n */\r\n protected void drawHorizontalLine(Graphics2D g2, Rectangle2D dataArea,\r\n double value, Stroke stroke,\r\n Paint paint) {\r\n\r\n ValueAxis axis = getRangeAxis();\r\n if (getOrientation() == PlotOrientation.HORIZONTAL) {\r\n axis = getDomainAxis();\r\n }\r\n if (axis.getRange().contains(value)) {\r\n double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT);\r\n Line2D line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws a domain crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param value the crosshair value.\r\n * @param axis the axis against which the value is measured.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @since 1.0.4\r\n */\r\n protected void drawDomainCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, double value, ValueAxis axis,\r\n Stroke stroke, Paint paint) {\r\n\r\n if (!axis.getRange().contains(value)) {\r\n return;\r\n }\r\n Line2D line;\r\n if (orientation == PlotOrientation.VERTICAL) {\r\n double xx = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n } else {\r\n double yy = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n\r\n /**\r\n * Utility method for drawing a vertical line on the data area of the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param value the coordinate, where to draw the line.\r\n * @param stroke the stroke to use.\r\n * @param paint the paint to use.\r\n */\r\n protected void drawVerticalLine(Graphics2D g2, Rectangle2D dataArea,\r\n double value, Stroke stroke, Paint paint) {\r\n\r\n ValueAxis axis = getDomainAxis();\r\n if (getOrientation() == PlotOrientation.HORIZONTAL) {\r\n axis = getRangeAxis();\r\n }\r\n if (axis.getRange().contains(value)) {\r\n double xx = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.BOTTOM);\r\n Line2D line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws a range crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param value the crosshair value.\r\n * @param axis the axis against which the value is measured.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @since 1.0.4\r\n */\r\n protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, double value, ValueAxis axis,\r\n Stroke stroke, Paint paint) {\r\n\r\n if (!axis.getRange().contains(value)) {\r\n return;\r\n }\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n Line2D line;\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n double xx = axis.valueToJava2D(value, dataArea, \r\n RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n } else {\r\n double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the plot by updating the anchor values.\r\n *\r\n * @param x the x-coordinate, where the click occurred, in Java2D space.\r\n * @param y the y-coordinate, where the click occurred, in Java2D space.\r\n * @param info object containing information about the plot dimensions.\r\n */\r\n @Override\r\n public void handleClick(int x, int y, PlotRenderingInfo info) {\r\n\r\n Rectangle2D dataArea = info.getDataArea();\r\n if (dataArea.contains(x, y)) {\r\n // set the anchor value for the horizontal axis...\r\n ValueAxis xaxis = getDomainAxis();\r\n if (xaxis != null) {\r\n double hvalue = xaxis.java2DToValue(x, info.getDataArea(),\r\n getDomainAxisEdge());\r\n setDomainCrosshairValue(hvalue);\r\n }\r\n\r\n // set the anchor value for the vertical axis...\r\n ValueAxis yaxis = getRangeAxis();\r\n if (yaxis != null) {\r\n double vvalue = yaxis.java2DToValue(y, info.getDataArea(),\r\n getRangeAxisEdge());\r\n setRangeCrosshairValue(vvalue);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * A utility method that returns a list of datasets that are mapped to a\r\n * particular axis.\r\n *\r\n * @param axisIndex the axis index (<code>null</code> not permitted).\r\n *\r\n * @return A list of datasets.\r\n */\r\n private List<XYDataset> getDatasetsMappedToDomainAxis(Integer axisIndex) {\r\n ParamChecks.nullNotPermitted(axisIndex, \"axisIndex\");\r\n List<XYDataset> result = new ArrayList<XYDataset>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n int index = entry.getKey();\r\n List<Integer> mappedAxes = this.datasetToDomainAxesMap.get(index);\r\n if (mappedAxes == null) {\r\n if (axisIndex.equals(ZERO)) {\r\n result.add(entry.getValue());\r\n }\r\n } else {\r\n if (mappedAxes.contains(axisIndex)) {\r\n result.add(entry.getValue());\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * A utility method that returns a list of datasets that are mapped to a\r\n * particular axis.\r\n *\r\n * @param axisIndex the axis index (<code>null</code> not permitted).\r\n *\r\n * @return A list of datasets.\r\n */\r\n private List<XYDataset> getDatasetsMappedToRangeAxis(Integer axisIndex) {\r\n ParamChecks.nullNotPermitted(axisIndex, \"axisIndex\");\r\n List<XYDataset> result = new ArrayList<XYDataset>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n int index = entry.getKey();\r\n List<Integer> mappedAxes = this.datasetToRangeAxesMap.get(index);\r\n if (mappedAxes == null) {\r\n if (axisIndex.equals(ZERO)) {\r\n result.add(entry.getValue());\r\n }\r\n } else {\r\n if (mappedAxes.contains(axisIndex)) {\r\n result.add(entry.getValue());\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the index of the given domain axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getRangeAxisIndex(ValueAxis)\r\n */\r\n public int getDomainAxisIndex(ValueAxis axis) {\r\n int result = findDomainAxisIndex(axis);\r\n if (result < 0) {\r\n // try the parent plot\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot p = (XYPlot) parent;\r\n result = p.getDomainAxisIndex(axis);\r\n }\r\n }\r\n return result;\r\n }\r\n \r\n private int findDomainAxisIndex(ValueAxis axis) {\r\n for (Map.Entry<Integer, ValueAxis> entry : this.domainAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the index of the given range axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getDomainAxisIndex(ValueAxis)\r\n */\r\n public int getRangeAxisIndex(ValueAxis axis) {\r\n int result = findRangeAxisIndex(axis);\r\n if (result < 0) {\r\n // try the parent plot\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot p = (XYPlot) parent;\r\n result = p.getRangeAxisIndex(axis);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n private int findRangeAxisIndex(ValueAxis axis) {\r\n for (Map.Entry<Integer, ValueAxis> entry : this.rangeAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the range for the specified axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The range.\r\n */\r\n @Override\r\n public Range getDataRange(ValueAxis axis) {\r\n\r\n Range result = null;\r\n List<XYDataset> mappedDatasets = new ArrayList<XYDataset>();\r\n List<XYAnnotation> includedAnnotations = new ArrayList<XYAnnotation>();\r\n boolean isDomainAxis = true;\r\n\r\n // is it a domain axis?\r\n int domainIndex = getDomainAxisIndex(axis);\r\n if (domainIndex >= 0) {\r\n isDomainAxis = true;\r\n mappedDatasets.addAll(getDatasetsMappedToDomainAxis(domainIndex));\r\n if (domainIndex == 0) {\r\n // grab the plot's annotations\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n if (annotation instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(annotation);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // or is it a range axis?\r\n int rangeIndex = getRangeAxisIndex(axis);\r\n if (rangeIndex >= 0) {\r\n isDomainAxis = false;\r\n mappedDatasets.addAll(getDatasetsMappedToRangeAxis(rangeIndex));\r\n if (rangeIndex == 0) {\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n if (annotation instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(annotation);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // iterate through the datasets that map to the axis and get the union\r\n // of the ranges.\r\n for (XYDataset d : mappedDatasets) {\r\n if (d != null) {\r\n XYItemRenderer r = getRendererForDataset(d);\r\n if (isDomainAxis) {\r\n if (r != null) {\r\n result = Range.combine(result, r.findDomainBounds(d));\r\n }\r\n else {\r\n result = Range.combine(result,\r\n DatasetUtilities.findDomainBounds(d));\r\n }\r\n }\r\n else {\r\n if (r != null) {\r\n result = Range.combine(result, r.findRangeBounds(d));\r\n }\r\n else {\r\n result = Range.combine(result,\r\n DatasetUtilities.findRangeBounds(d));\r\n }\r\n }\r\n // FIXME: the XYItemRenderer interface doesn't specify the\r\n // getAnnotations() method but it should\r\n if (r instanceof AbstractXYItemRenderer) {\r\n AbstractXYItemRenderer rr = (AbstractXYItemRenderer) r;\r\n Collection c = rr.getAnnotations();\r\n Iterator i = c.iterator();\r\n while (i.hasNext()) {\r\n XYAnnotation a = (XYAnnotation) i.next();\r\n if (a instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(a);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n Iterator it = includedAnnotations.iterator();\r\n while (it.hasNext()) {\r\n XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next();\r\n if (xyabi.getIncludeInDataBounds()) {\r\n if (isDomainAxis) {\r\n result = Range.combine(result, xyabi.getXRange());\r\n }\r\n else {\r\n result = Range.combine(result, xyabi.getYRange());\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Receives notification of a change to an {@link Annotation} added to\r\n * this plot.\r\n *\r\n * @param event information about the event (not used here).\r\n *\r\n * @since 1.0.14\r\n */\r\n @Override\r\n public void annotationChanged(AnnotationChangeEvent event) {\r\n if (getParent() != null) {\r\n getParent().annotationChanged(event);\r\n }\r\n else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a change to the plot's dataset.\r\n * <P>\r\n * The axis ranges are updated if necessary.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void datasetChanged(DatasetChangeEvent event) {\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n if (getParent() != null) {\r\n getParent().datasetChanged(event);\r\n }\r\n else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n e.setType(ChartChangeEventType.DATASET_UPDATED);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a renderer change event.\r\n *\r\n * @param event the event.\r\n */\r\n @Override\r\n public void rendererChanged(RendererChangeEvent event) {\r\n // if the event was caused by a change to series visibility, then\r\n // the axis ranges might need updating...\r\n if (event.getSeriesVisibilityChanged()) {\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the domain crosshair is visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setDomainCrosshairVisible(boolean)\r\n */\r\n public boolean isDomainCrosshairVisible() {\r\n return this.domainCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the domain crosshair is visible\r\n * and, if the flag changes, sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isDomainCrosshairVisible()\r\n */\r\n public void setDomainCrosshairVisible(boolean flag) {\r\n if (this.domainCrosshairVisible != flag) {\r\n this.domainCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the crosshair should \"lock-on\"\r\n * to actual data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setDomainCrosshairLockedOnData(boolean)\r\n */\r\n public boolean isDomainCrosshairLockedOnData() {\r\n return this.domainCrosshairLockedOnData;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the domain crosshair should\r\n * \"lock-on\" to actual data values. If the flag value changes, this\r\n * method sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isDomainCrosshairLockedOnData()\r\n */\r\n public void setDomainCrosshairLockedOnData(boolean flag) {\r\n if (this.domainCrosshairLockedOnData != flag) {\r\n this.domainCrosshairLockedOnData = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the domain crosshair value.\r\n *\r\n * @return The value.\r\n *\r\n * @see #setDomainCrosshairValue(double)\r\n */\r\n public double getDomainCrosshairValue() {\r\n return this.domainCrosshairValue;\r\n }\r\n\r\n /**\r\n * Sets the domain crosshair value and sends a {@link PlotChangeEvent} to\r\n * all registered listeners (provided that the domain crosshair is visible).\r\n *\r\n * @param value the value.\r\n *\r\n * @see #getDomainCrosshairValue()\r\n */\r\n public void setDomainCrosshairValue(double value) {\r\n setDomainCrosshairValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the domain crosshair value and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners (provided that the\r\n * domain crosshair is visible).\r\n *\r\n * @param value the new value.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainCrosshairValue()\r\n */\r\n public void setDomainCrosshairValue(double value, boolean notify) {\r\n this.domainCrosshairValue = value;\r\n if (isDomainCrosshairVisible() && notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the {@link Stroke} used to draw the crosshair (if visible).\r\n *\r\n * @return The crosshair stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainCrosshairStroke(Stroke)\r\n * @see #isDomainCrosshairVisible()\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public Stroke getDomainCrosshairStroke() {\r\n return this.domainCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the Stroke used to draw the crosshairs (if visible) and notifies\r\n * registered listeners that the axis has been modified.\r\n *\r\n * @param stroke the new crosshair stroke (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public void setDomainCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainCrosshairStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the domain crosshair paint.\r\n *\r\n * @return The crosshair paint (never <code>null</code>).\r\n *\r\n * @see #setDomainCrosshairPaint(Paint)\r\n * @see #isDomainCrosshairVisible()\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public Paint getDomainCrosshairPaint() {\r\n return this.domainCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the new crosshair paint (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public void setDomainCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the range crosshair is visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairVisible(boolean)\r\n * @see #isDomainCrosshairVisible()\r\n */\r\n public boolean isRangeCrosshairVisible() {\r\n return this.rangeCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair is visible.\r\n * If the flag value changes, this method sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isRangeCrosshairVisible()\r\n */\r\n public void setRangeCrosshairVisible(boolean flag) {\r\n if (this.rangeCrosshairVisible != flag) {\r\n this.rangeCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the crosshair should \"lock-on\"\r\n * to actual data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairLockedOnData(boolean)\r\n */\r\n public boolean isRangeCrosshairLockedOnData() {\r\n return this.rangeCrosshairLockedOnData;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair should\r\n * \"lock-on\" to actual data values. If the flag value changes, this method\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isRangeCrosshairLockedOnData()\r\n */\r\n public void setRangeCrosshairLockedOnData(boolean flag) {\r\n if (this.rangeCrosshairLockedOnData != flag) {\r\n this.rangeCrosshairLockedOnData = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range crosshair value.\r\n *\r\n * @return The value.\r\n *\r\n * @see #setRangeCrosshairValue(double)\r\n */\r\n public double getRangeCrosshairValue() {\r\n return this.rangeCrosshairValue;\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value.\r\n * <P>\r\n * Registered listeners are notified that the plot has been modified, but\r\n * only if the crosshair is visible.\r\n *\r\n * @param value the new value.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value) {\r\n setRangeCrosshairValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value and sends a {@link PlotChangeEvent} to\r\n * all registered listeners, but only if the crosshair is visible.\r\n *\r\n * @param value the new value.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value, boolean notify) {\r\n this.rangeCrosshairValue = value;\r\n if (isRangeCrosshairVisible() && notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the crosshair (if visible).\r\n *\r\n * @return The crosshair stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairStroke(Stroke)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public Stroke getRangeCrosshairStroke() {\r\n return this.rangeCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the new crosshair stroke (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public void setRangeCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeCrosshairStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the range crosshair paint.\r\n *\r\n * @return The crosshair paint (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairPaint(Paint)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public Paint getRangeCrosshairPaint() {\r\n return this.rangeCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to color the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the new crosshair paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public void setRangeCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the fixed domain axis space.\r\n *\r\n * @return The fixed domain axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedDomainAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedDomainAxisSpace() {\r\n return this.fixedDomainAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space) {\r\n setFixedDomainAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n *\r\n * @since 1.0.9\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedDomainAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the fixed range axis space.\r\n *\r\n * @return The fixed range axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedRangeAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedRangeAxisSpace() {\r\n return this.fixedRangeAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space) {\r\n setFixedRangeAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n *\r\n * @since 1.0.9\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedRangeAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if panning is enabled for the domain axes,\r\n * and <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isDomainPannable() {\r\n return this.domainPannable;\r\n }\r\n\r\n /**\r\n * Sets the flag that enables or disables panning of the plot along the\r\n * domain axes.\r\n *\r\n * @param pannable the new flag value.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setDomainPannable(boolean pannable) {\r\n this.domainPannable = pannable;\r\n }\r\n\r\n /**\r\n * Returns {@code true} if panning is enabled for the range axis/axes,\r\n * and {@code false} otherwise. The default value is {@code false}.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isRangePannable() {\r\n return this.rangePannable;\r\n }\r\n\r\n /**\r\n * Sets the flag that enables or disables panning of the plot along\r\n * the range axis/axes.\r\n *\r\n * @param pannable the new flag value.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangePannable(boolean pannable) {\r\n this.rangePannable = pannable;\r\n }\r\n\r\n /**\r\n * Pans the domain axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panDomainAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n if (!isDomainPannable()) {\r\n return;\r\n }\r\n int domainAxisCount = getDomainAxisCount();\r\n for (int i = 0; i < domainAxisCount; i++) {\r\n ValueAxis axis = getDomainAxis(i);\r\n if (axis == null) {\r\n continue;\r\n }\r\n if (axis.isInverted()) {\r\n percent = -percent;\r\n }\r\n axis.pan(percent);\r\n }\r\n }\r\n\r\n /**\r\n * Pans the range axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panRangeAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n if (!isRangePannable()) {\r\n return;\r\n }\r\n int rangeAxisCount = getRangeAxisCount();\r\n for (int i = 0; i < rangeAxisCount; i++) {\r\n ValueAxis axis = getRangeAxis(i);\r\n if (axis == null) {\r\n continue;\r\n }\r\n if (axis.isInverted()) {\r\n percent = -percent;\r\n }\r\n axis.pan(percent);\r\n }\r\n }\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point (in Java2D space).\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo info,\r\n Point2D source) {\r\n // delegate to other method\r\n zoomDomainAxes(factor, info, source, false);\r\n }\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point (in Java2D space).\r\n * @param useAnchor use source point as zoom anchor?\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n\r\n // perform the zoom on each domain axis\r\n for (ValueAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis == null) {\r\n continue;\r\n }\r\n if (useAnchor) {\r\n // get the relevant source coordinate given the plot orientation\r\n double sourceX = source.getX();\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n sourceX = source.getY();\r\n }\r\n double anchorX = xAxis.java2DToValue(sourceX,\r\n info.getDataArea(), getDomainAxisEdge());\r\n xAxis.resizeRange2(factor, anchorX);\r\n } else {\r\n xAxis.resizeRange(factor);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the domain axis/axes. The new lower and upper bounds are\r\n * specified as percentages of the current axis range, where 0 percent is\r\n * the current lower bound and 100 percent is the current upper bound.\r\n *\r\n * @param lowerPercent a percentage that determines the new lower bound\r\n * for the axis (e.g. 0.20 is twenty percent).\r\n * @param upperPercent a percentage that determines the new upper bound\r\n * for the axis (e.g. 0.80 is eighty percent).\r\n * @param info the plot rendering info.\r\n * @param source the source point (ignored).\r\n *\r\n * @see #zoomRangeAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomDomainAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo info, Point2D source) {\r\n for (ValueAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n xAxis.zoomRange(lowerPercent, upperPercent);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo info,\r\n Point2D source) {\r\n // delegate to other method\r\n zoomRangeAxes(factor, info, source, false);\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n * @param useAnchor a flag that controls whether or not the source point\r\n * is used for the zoom anchor.\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n\r\n // perform the zoom on each range axis\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis == null) {\r\n continue;\r\n }\r\n if (useAnchor) {\r\n // get the relevant source coordinate given the plot orientation\r\n double sourceY = source.getY();\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n sourceY = source.getX();\r\n }\r\n double anchorY = yAxis.java2DToValue(sourceY,\r\n info.getDataArea(), getRangeAxisEdge());\r\n yAxis.resizeRange2(factor, anchorY);\r\n } else {\r\n yAxis.resizeRange(factor);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the range axes.\r\n *\r\n * @param lowerPercent the lower bound.\r\n * @param upperPercent the upper bound.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n *\r\n * @see #zoomDomainAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomRangeAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo info, Point2D source) {\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.zoomRange(lowerPercent, upperPercent);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code>, indicating that the domain axis/axes for this\r\n * plot are zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isRangeZoomable()\r\n */\r\n @Override\r\n public boolean isDomainZoomable() {\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code>, indicating that the range axis/axes for this\r\n * plot are zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isDomainZoomable()\r\n */\r\n @Override\r\n public boolean isRangeZoomable() {\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns the number of series in the primary dataset for this plot. If\r\n * the dataset is <code>null</code>, the method returns 0.\r\n *\r\n * @return The series count.\r\n */\r\n public int getSeriesCount() {\r\n int result = 0;\r\n XYDataset dataset = getDataset();\r\n if (dataset != null) {\r\n result = dataset.getSeriesCount();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the fixed legend items, if any.\r\n *\r\n * @return The legend items (possibly <code>null</code>).\r\n *\r\n * @see #setFixedLegendItems(LegendItemCollection)\r\n */\r\n public LegendItemCollection getFixedLegendItems() {\r\n return this.fixedLegendItems;\r\n }\r\n\r\n /**\r\n * Sets the fixed legend items for the plot. Leave this set to\r\n * <code>null</code> if you prefer the legend items to be created\r\n * automatically.\r\n *\r\n * @param items the legend items (<code>null</code> permitted).\r\n *\r\n * @see #getFixedLegendItems()\r\n */\r\n public void setFixedLegendItems(LegendItemCollection items) {\r\n this.fixedLegendItems = items;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the legend items for the plot. Each legend item is generated by\r\n * the plot's renderer, since the renderer is responsible for the visual\r\n * representation of the data.\r\n *\r\n * @return The legend items.\r\n */\r\n @Override\r\n public LegendItemCollection getLegendItems() {\r\n if (this.fixedLegendItems != null) {\r\n return this.fixedLegendItems;\r\n }\r\n LegendItemCollection result = new LegendItemCollection();\r\n for (XYDataset dataset : this.datasets.values()) {\r\n if (dataset == null) {\r\n continue;\r\n }\r\n int datasetIndex = indexOf(dataset);\r\n XYItemRenderer renderer = getRenderer(datasetIndex);\r\n if (renderer == null) {\r\n renderer = getRenderer(0);\r\n }\r\n if (renderer != null) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int i = 0; i < seriesCount; i++) {\r\n if (renderer.isSeriesVisible(i)\r\n && renderer.isSeriesVisibleInLegend(i)) {\r\n LegendItem item = renderer.getLegendItem(\r\n datasetIndex, i);\r\n if (item != null) {\r\n result.add(item);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Tests this plot for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof XYPlot)) {\r\n return false;\r\n }\r\n XYPlot that = (XYPlot) obj;\r\n if (this.weight != that.weight) {\r\n return false;\r\n }\r\n if (this.orientation != that.orientation) {\r\n return false;\r\n }\r\n if (!this.domainAxes.equals(that.domainAxes)) {\r\n return false;\r\n }\r\n if (!this.domainAxisLocations.equals(that.domainAxisLocations)) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairLockedOnData\r\n != that.rangeCrosshairLockedOnData) {\r\n return false;\r\n }\r\n if (this.domainGridlinesVisible != that.domainGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.rangeGridlinesVisible != that.rangeGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.domainMinorGridlinesVisible\r\n != that.domainMinorGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.rangeMinorGridlinesVisible\r\n != that.rangeMinorGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.domainZeroBaselineVisible != that.domainZeroBaselineVisible) {\r\n return false;\r\n }\r\n if (this.rangeZeroBaselineVisible != that.rangeZeroBaselineVisible) {\r\n return false;\r\n }\r\n if (this.domainCrosshairVisible != that.domainCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.domainCrosshairValue != that.domainCrosshairValue) {\r\n return false;\r\n }\r\n if (this.domainCrosshairLockedOnData\r\n != that.domainCrosshairLockedOnData) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairVisible != that.rangeCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairValue != that.rangeCrosshairValue) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.axisOffset, that.axisOffset)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.renderers, that.renderers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeAxes, that.rangeAxes)) {\r\n return false;\r\n }\r\n if (!this.rangeAxisLocations.equals(that.rangeAxisLocations)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToDomainAxesMap,\r\n that.datasetToDomainAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToRangeAxesMap,\r\n that.datasetToRangeAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainGridlineStroke,\r\n that.domainGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainGridlinePaint,\r\n that.domainGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeGridlineStroke,\r\n that.rangeGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeGridlinePaint,\r\n that.rangeGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainMinorGridlineStroke,\r\n that.domainMinorGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainMinorGridlinePaint,\r\n that.domainMinorGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeMinorGridlineStroke,\r\n that.rangeMinorGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeMinorGridlinePaint,\r\n that.rangeMinorGridlinePaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainZeroBaselinePaint,\r\n that.domainZeroBaselinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainZeroBaselineStroke,\r\n that.domainZeroBaselineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeZeroBaselinePaint,\r\n that.rangeZeroBaselinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeZeroBaselineStroke,\r\n that.rangeZeroBaselineStroke)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainCrosshairStroke,\r\n that.domainCrosshairStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainCrosshairPaint,\r\n that.domainCrosshairPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeCrosshairStroke,\r\n that.rangeCrosshairStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeCrosshairPaint,\r\n that.rangeCrosshairPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundDomainMarkers,\r\n that.foregroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundDomainMarkers,\r\n that.backgroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundRangeMarkers,\r\n that.foregroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundRangeMarkers,\r\n that.backgroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundDomainMarkers,\r\n that.foregroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundDomainMarkers,\r\n that.backgroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundRangeMarkers,\r\n that.foregroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundRangeMarkers,\r\n that.backgroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.annotations, that.annotations)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.fixedLegendItems,\r\n that.fixedLegendItems)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainTickBandPaint,\r\n that.domainTickBandPaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeTickBandPaint,\r\n that.rangeTickBandPaint)) {\r\n return false;\r\n }\r\n if (!this.quadrantOrigin.equals(that.quadrantOrigin)) {\r\n return false;\r\n }\r\n for (int i = 0; i < 4; i++) {\r\n if (!PaintUtilities.equal(this.quadrantPaint[i],\r\n that.quadrantPaint[i])) {\r\n return false;\r\n }\r\n }\r\n if (!ObjectUtilities.equal(this.shadowGenerator,\r\n that.shadowGenerator)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a clone of the plot.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException this can occur if some component of\r\n * the plot cannot be cloned.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n XYPlot clone = (XYPlot) super.clone();\r\n clone.domainAxes = CloneUtils.cloneMapValues(this.domainAxes);\r\n for (ValueAxis axis : clone.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n clone.rangeAxes = CloneUtils.cloneMapValues(this.rangeAxes);\r\n for (ValueAxis axis : clone.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n clone.domainAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.domainAxisLocations);\r\n clone.rangeAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.rangeAxisLocations);\r\n\r\n // the datasets are not cloned, but listeners need to be added...\r\n clone.datasets = new HashMap<Integer, XYDataset>(this.datasets);\r\n for (XYDataset dataset : clone.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(clone);\r\n }\r\n }\r\n\r\n clone.datasetToDomainAxesMap = new TreeMap();\r\n clone.datasetToDomainAxesMap.putAll(this.datasetToDomainAxesMap);\r\n clone.datasetToRangeAxesMap = new TreeMap();\r\n clone.datasetToRangeAxesMap.putAll(this.datasetToRangeAxesMap);\r\n\r\n clone.renderers = CloneUtils.cloneMapValues(this.renderers);\r\n for (XYItemRenderer renderer : clone.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.setPlot(clone);\r\n renderer.addChangeListener(clone);\r\n }\r\n }\r\n clone.foregroundDomainMarkers = (Map) ObjectUtilities.clone(\r\n this.foregroundDomainMarkers);\r\n clone.backgroundDomainMarkers = (Map) ObjectUtilities.clone(\r\n this.backgroundDomainMarkers);\r\n clone.foregroundRangeMarkers = (Map) ObjectUtilities.clone(\r\n this.foregroundRangeMarkers);\r\n clone.backgroundRangeMarkers = (Map) ObjectUtilities.clone(\r\n this.backgroundRangeMarkers);\r\n clone.annotations = (List) ObjectUtilities.deepClone(this.annotations);\r\n if (this.fixedDomainAxisSpace != null) {\r\n clone.fixedDomainAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedDomainAxisSpace);\r\n }\r\n if (this.fixedRangeAxisSpace != null) {\r\n clone.fixedRangeAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedRangeAxisSpace);\r\n }\r\n if (this.fixedLegendItems != null) {\r\n clone.fixedLegendItems\r\n = (LegendItemCollection) this.fixedLegendItems.clone();\r\n }\r\n clone.quadrantOrigin = (Point2D) ObjectUtilities.clone(\r\n this.quadrantOrigin);\r\n clone.quadrantPaint = this.quadrantPaint.clone();\r\n return clone;\r\n\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.domainGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.domainGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.domainMinorGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.domainMinorGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeMinorGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeMinorGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeZeroBaselineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeZeroBaselinePaint, stream);\r\n SerialUtilities.writeStroke(this.domainCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.domainCrosshairPaint, stream);\r\n SerialUtilities.writeStroke(this.rangeCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.rangeCrosshairPaint, stream);\r\n SerialUtilities.writePaint(this.domainTickBandPaint, stream);\r\n SerialUtilities.writePaint(this.rangeTickBandPaint, stream);\r\n SerialUtilities.writePoint2D(this.quadrantOrigin, stream);\r\n for (int i = 0; i < 4; i++) {\r\n SerialUtilities.writePaint(this.quadrantPaint[i], stream);\r\n }\r\n SerialUtilities.writeStroke(this.domainZeroBaselineStroke, stream);\r\n SerialUtilities.writePaint(this.domainZeroBaselinePaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n\r\n stream.defaultReadObject();\r\n this.domainGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.domainGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.domainMinorGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.domainMinorGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeMinorGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeMinorGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeZeroBaselineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeZeroBaselinePaint = SerialUtilities.readPaint(stream);\r\n this.domainCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.domainCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.rangeCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.rangeCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.domainTickBandPaint = SerialUtilities.readPaint(stream);\r\n this.rangeTickBandPaint = SerialUtilities.readPaint(stream);\r\n this.quadrantOrigin = SerialUtilities.readPoint2D(stream);\r\n this.quadrantPaint = new Paint[4];\r\n for (int i = 0; i < 4; i++) {\r\n this.quadrantPaint[i] = SerialUtilities.readPaint(stream);\r\n }\r\n\r\n this.domainZeroBaselineStroke = SerialUtilities.readStroke(stream);\r\n this.domainZeroBaselinePaint = SerialUtilities.readPaint(stream);\r\n\r\n // register the plot as a listener with its axes, datasets, and\r\n // renderers...\r\n for (ValueAxis axis : this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n axis.addChangeListener(this);\r\n }\r\n }\r\n for (ValueAxis axis : this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n axis.addChangeListener(this);\r\n }\r\n }\r\n for (XYDataset dataset : this.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n }\r\n for (XYItemRenderer renderer : this.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.addChangeListener(this);\r\n }\r\n }\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "ParamChecks", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/util/ParamChecks.java", "snippet": "public class ParamChecks {\r\n\r\n /**\r\n * Throws an <code>IllegalArgumentException</code> if the supplied \r\n * <code>param</code> is <code>null</code>.\r\n *\r\n * @param param the parameter to check (<code>null</code> permitted).\r\n * @param name the name of the parameter (to use in the exception message\r\n * if <code>param</code> is <code>null</code>).\r\n *\r\n * @throws IllegalArgumentException if <code>param</code> is \r\n * <code>null</code>.\r\n *\r\n * @since 1.0.14\r\n */\r\n public static void nullNotPermitted(Object param, String name) {\r\n if (param == null) {\r\n throw new IllegalArgumentException(\"Null '\" + name + \"' argument.\");\r\n }\r\n }\r\n \r\n /**\r\n * Throws an {@code IllegalArgumentException} if {@code value} is negative.\r\n * \r\n * @param value the value.\r\n * @param name the parameter name (for use in the exception message).\r\n * \r\n * @since 1.0.18\r\n */\r\n public static void requireNonNegative(int value, String name) {\r\n if (value < 0) {\r\n throw new IllegalArgumentException(\"Require '\" + name + \"' (\" \r\n + value + \") to be non-negative.\");\r\n }\r\n }\r\n}\r" } ]
import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.HashUtilities; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.event.AnnotationChangeEvent; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.util.ParamChecks; import org.jfree.io.SerialUtilities; import org.jfree.text.TextUtilities; import org.jfree.ui.RectangleEdge; import org.jfree.ui.TextAnchor; import org.jfree.util.PaintUtilities; import org.jfree.util.PublicCloneable;
77,360
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------- * XYTextAnnotation.java * --------------------- * (C) Copyright 2002-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Peter Kolb (patch 2809117); * * Changes: * -------- * 28-Aug-2002 : Version 1 (DG); * 07-Nov-2002 : Fixed errors reported by Checkstyle (DG); * 13-Jan-2003 : Reviewed Javadocs (DG); * 26-Mar-2003 : Implemented Serializable (DG); * 02-Jul-2003 : Added new text alignment and rotation options (DG); * 19-Aug-2003 : Implemented Cloneable (DG); * 17-Jan-2003 : Added fix for bug 878706, where the annotation is placed * incorrectly for a plot with horizontal orientation (thanks to * Ed Yu for the fix) (DG); * 21-Jan-2004 : Update for renamed method in ValueAxis (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 26-Jan-2006 : Fixed equals() method (bug 1415480) (DG); * 06-Mar-2007 : Added argument checks, re-implemented hashCode() method (DG); * 12-Feb-2009 : Added background paint and outline paint/stroke (DG); * 01-Apr-2009 : Fixed bug in hotspot calculation (DG); * 24-Jun-2009 : Fire change events (see patch 2809117) (DG); * */ package org.jfree.chart.annotations; /** * A text annotation that can be placed at a particular (x, y) location on an * {@link XYPlot}. */ public class XYTextAnnotation extends AbstractXYAnnotation implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -2946063342782506328L; /** The default font. */ public static final Font DEFAULT_FONT = new Font("SansSerif", Font.PLAIN, 10); /** The default paint. */ public static final Paint DEFAULT_PAINT = Color.black; /** The default text anchor. */ public static final TextAnchor DEFAULT_TEXT_ANCHOR = TextAnchor.CENTER; /** The default rotation anchor. */ public static final TextAnchor DEFAULT_ROTATION_ANCHOR = TextAnchor.CENTER; /** The default rotation angle. */ public static final double DEFAULT_ROTATION_ANGLE = 0.0; /** The text. */ private String text; /** The font. */ private Font font; /** The paint. */ private transient Paint paint; /** The x-coordinate. */ private double x; /** The y-coordinate. */ private double y; /** The text anchor (to be aligned with (x, y)). */ private TextAnchor textAnchor; /** The rotation anchor. */ private TextAnchor rotationAnchor; /** The rotation angle. */ private double rotationAngle; /** * The background paint (possibly null). * * @since 1.0.13 */ private transient Paint backgroundPaint; /** * The flag that controls the visibility of the outline. * * @since 1.0.13 */ private boolean outlineVisible; /** * The outline paint (never null). * * @since 1.0.13 */ private transient Paint outlinePaint; /** * The outline stroke (never null). * * @since 1.0.13 */ private transient Stroke outlineStroke; /** * Creates a new annotation to be displayed at the given coordinates. The * coordinates are specified in data space (they will be converted to * Java2D space for display). * * @param text the text (<code>null</code> not permitted). * @param x the x-coordinate (in data space). * @param y the y-coordinate (in data space). */ public XYTextAnnotation(String text, double x, double y) { super();
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------- * XYTextAnnotation.java * --------------------- * (C) Copyright 2002-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Peter Kolb (patch 2809117); * * Changes: * -------- * 28-Aug-2002 : Version 1 (DG); * 07-Nov-2002 : Fixed errors reported by Checkstyle (DG); * 13-Jan-2003 : Reviewed Javadocs (DG); * 26-Mar-2003 : Implemented Serializable (DG); * 02-Jul-2003 : Added new text alignment and rotation options (DG); * 19-Aug-2003 : Implemented Cloneable (DG); * 17-Jan-2003 : Added fix for bug 878706, where the annotation is placed * incorrectly for a plot with horizontal orientation (thanks to * Ed Yu for the fix) (DG); * 21-Jan-2004 : Update for renamed method in ValueAxis (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 26-Jan-2006 : Fixed equals() method (bug 1415480) (DG); * 06-Mar-2007 : Added argument checks, re-implemented hashCode() method (DG); * 12-Feb-2009 : Added background paint and outline paint/stroke (DG); * 01-Apr-2009 : Fixed bug in hotspot calculation (DG); * 24-Jun-2009 : Fire change events (see patch 2809117) (DG); * */ package org.jfree.chart.annotations; /** * A text annotation that can be placed at a particular (x, y) location on an * {@link XYPlot}. */ public class XYTextAnnotation extends AbstractXYAnnotation implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -2946063342782506328L; /** The default font. */ public static final Font DEFAULT_FONT = new Font("SansSerif", Font.PLAIN, 10); /** The default paint. */ public static final Paint DEFAULT_PAINT = Color.black; /** The default text anchor. */ public static final TextAnchor DEFAULT_TEXT_ANCHOR = TextAnchor.CENTER; /** The default rotation anchor. */ public static final TextAnchor DEFAULT_ROTATION_ANCHOR = TextAnchor.CENTER; /** The default rotation angle. */ public static final double DEFAULT_ROTATION_ANGLE = 0.0; /** The text. */ private String text; /** The font. */ private Font font; /** The paint. */ private transient Paint paint; /** The x-coordinate. */ private double x; /** The y-coordinate. */ private double y; /** The text anchor (to be aligned with (x, y)). */ private TextAnchor textAnchor; /** The rotation anchor. */ private TextAnchor rotationAnchor; /** The rotation angle. */ private double rotationAngle; /** * The background paint (possibly null). * * @since 1.0.13 */ private transient Paint backgroundPaint; /** * The flag that controls the visibility of the outline. * * @since 1.0.13 */ private boolean outlineVisible; /** * The outline paint (never null). * * @since 1.0.13 */ private transient Paint outlinePaint; /** * The outline stroke (never null). * * @since 1.0.13 */ private transient Stroke outlineStroke; /** * Creates a new annotation to be displayed at the given coordinates. The * coordinates are specified in data space (they will be converted to * Java2D space for display). * * @param text the text (<code>null</code> not permitted). * @param x the x-coordinate (in data space). * @param y the y-coordinate (in data space). */ public XYTextAnnotation(String text, double x, double y) { super();
ParamChecks.nullNotPermitted(text, "text");
7
2023-12-24 12:36:47+00:00
128k
Hoto-Mocha/Re-ARranged-Pixel-Dungeon
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/scrolls/ScrollOfRage.java
[ { "identifier": "Assets", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/Assets.java", "snippet": "public class Assets {\n\n\tpublic static class Effects {\n\t\tpublic static final String EFFECTS = \"effects/effects.png\";\n\t\tpublic static final String FIREBALL = \"effects/fireball.png\";\n\t\tpublic static final String SPECKS = \"effects/specks.png\";\n\t\tpublic static final String SPELL_ICONS = \"effects/spell_icons.png\";\n\t}\n\n\tpublic static class Environment {\n\t\tpublic static final String TERRAIN_FEATURES = \"environment/terrain_features.png\";\n\n\t\tpublic static final String VISUAL_GRID = \"environment/visual_grid.png\";\n\t\tpublic static final String WALL_BLOCKING= \"environment/wall_blocking.png\";\n\n\t\tpublic static final String TILES_SEWERS = \"environment/tiles_sewers.png\";\n\t\tpublic static final String TILES_PRISON = \"environment/tiles_prison.png\";\n\t\tpublic static final String TILES_CAVES = \"environment/tiles_caves.png\";\n\t\tpublic static final String TILES_CITY = \"environment/tiles_city.png\";\n\t\tpublic static final String TILES_HALLS = \"environment/tiles_halls.png\";\n\t\tpublic static final String TILES_TEMPLE = \"environment/tiles_temple.png\";\n\t\tpublic static final String TILES_LABS\t= \"environment/tiles_labs.png\";\n\n\t\tpublic static final String WATER_SEWERS = \"environment/water0.png\";\n\t\tpublic static final String WATER_PRISON = \"environment/water1.png\";\n\t\tpublic static final String WATER_CAVES = \"environment/water2.png\";\n\t\tpublic static final String WATER_CITY = \"environment/water3.png\";\n\t\tpublic static final String WATER_HALLS = \"environment/water4.png\";\n\t\tpublic static final String WATER_TEMPLE = \"environment/water0_temple.png\";\n\t\tpublic static final String WATER_LABS\t= \"environment/water5.png\";\n\n\t\tpublic static final String WEAK_FLOOR = \"environment/custom_tiles/weak_floor.png\";\n\t\tpublic static final String SEWER_BOSS = \"environment/custom_tiles/sewer_boss.png\";\n\t\tpublic static final String PRISON_QUEST = \"environment/custom_tiles/prison_quest.png\";\n\t\tpublic static final String PRISON_EXIT = \"environment/custom_tiles/prison_exit.png\";\n\t\tpublic static final String CAVES_QUEST = \"environment/custom_tiles/caves_quest.png\";\n\t\tpublic static final String CAVES_BOSS = \"environment/custom_tiles/caves_boss.png\";\n\t\tpublic static final String CITY_BOSS = \"environment/custom_tiles/city_boss.png\";\n\t\tpublic static final String HALLS_SP = \"environment/custom_tiles/halls_special.png\";\n\t\tpublic static final String TEMPLE_SP = \"environment/custom_tiles/temple_special.png\";\n\t}\n\t\n\t//TODO include other font assets here? Some are platform specific though...\n\tpublic static class Fonts {\n\t\tpublic static final String PIXELFONT= \"fonts/pixel_font.png\";\n\t}\n\n\tpublic static class Interfaces {\n\t\tpublic static final String ARCS_BG = \"interfaces/arcs1.png\";\n\t\tpublic static final String ARCS_FG = \"interfaces/arcs2.png\";\n\n\t\tpublic static final String BANNERS = \"interfaces/banners.png\";\n\t\tpublic static final String BADGES = \"interfaces/badges.png\";\n\t\tpublic static final String LOCKED = \"interfaces/locked_badge.png\";\n\n\t\tpublic static final String CHROME = \"interfaces/chrome.png\";\n\t\tpublic static final String ICONS = \"interfaces/icons.png\";\n\t\tpublic static final String STATUS = \"interfaces/status_pane.png\";\n\t\tpublic static final String MENU = \"interfaces/menu_pane.png\";\n\t\tpublic static final String MENU_BTN = \"interfaces/menu_button.png\";\n\t\tpublic static final String TOOLBAR = \"interfaces/toolbar.png\";\n\t\tpublic static final String SHADOW = \"interfaces/shadow.png\";\n\t\tpublic static final String BOSSHP = \"interfaces/boss_hp.png\";\n\n\t\tpublic static final String SURFACE = \"interfaces/surface.png\";\n\n\t\tpublic static final String LOADING_SEWERS = \"interfaces/loading_sewers.png\";\n\t\tpublic static final String LOADING_PRISON = \"interfaces/loading_prison.png\";\n\t\tpublic static final String LOADING_CAVES = \"interfaces/loading_caves.png\";\n\t\tpublic static final String LOADING_CITY = \"interfaces/loading_city.png\";\n\t\tpublic static final String LOADING_HALLS = \"interfaces/loading_halls.png\";\n\n\t\tpublic static final String BUFFS_SMALL = \"interfaces/buffs.png\";\n\t\tpublic static final String BUFFS_LARGE = \"interfaces/large_buffs.png\";\n\n\t\tpublic static final String TALENT_ICONS = \"interfaces/talent_icons.png\";\n\t\tpublic static final String TALENT_BUTTON = \"interfaces/talent_button.png\";\n\n\t\tpublic static final String HERO_ICONS = \"interfaces/hero_icons.png\";\n\n\t\tpublic static final String RADIAL_MENU = \"interfaces/radial_menu.png\";\n\t}\n\n\t//these points to resource bundles, not raw asset files\n\tpublic static class Messages {\n\t\tpublic static final String ACTORS = \"messages/actors/actors\";\n\t\tpublic static final String ITEMS = \"messages/items/items\";\n\t\tpublic static final String JOURNAL = \"messages/journal/journal\";\n\t\tpublic static final String LEVELS = \"messages/levels/levels\";\n\t\tpublic static final String MISC = \"messages/misc/misc\";\n\t\tpublic static final String PLANTS = \"messages/plants/plants\";\n\t\tpublic static final String SCENES = \"messages/scenes/scenes\";\n\t\tpublic static final String UI = \"messages/ui/ui\";\n\t\tpublic static final String WINDOWS = \"messages/windows/windows\";\n\t}\n\n\tpublic static class Music {\n\t\tpublic static final String THEME_1 = \"music/theme_1.ogg\";\n\t\tpublic static final String THEME_2 = \"music/theme_2.ogg\";\n\t\tpublic static final String THEME_FINALE = \"music/theme_finale.ogg\";\n\n\t\tpublic static final String SEWERS_1 = \"music/sewers_1.ogg\";\n\t\tpublic static final String SEWERS_2 = \"music/sewers_2.ogg\";\n\t\tpublic static final String SEWERS_3 = \"music/sewers_3.ogg\";\n\t\tpublic static final String SEWERS_TENSE = \"music/sewers_tense.ogg\";\n\t\tpublic static final String SEWERS_BOSS = \"music/sewers_boss.ogg\";\n\n\t\tpublic static final String PRISON_1 = \"music/prison_1.ogg\";\n\t\tpublic static final String PRISON_2 = \"music/prison_2.ogg\";\n\t\tpublic static final String PRISON_3 = \"music/prison_3.ogg\";\n\t\tpublic static final String PRISON_TENSE = \"music/prison_tense.ogg\";\n\t\tpublic static final String PRISON_BOSS = \"music/prison_boss.ogg\";\n\n\t\tpublic static final String CAVES_1 = \"music/caves_1.ogg\";\n\t\tpublic static final String CAVES_2 = \"music/caves_2.ogg\";\n\t\tpublic static final String CAVES_3 = \"music/caves_3.ogg\";\n\t\tpublic static final String CAVES_TENSE = \"music/caves_tense.ogg\";\n\t\tpublic static final String CAVES_BOSS = \"music/caves_boss.ogg\";\n\t\tpublic static final String CAVES_BOSS_FINALE = \"music/caves_boss_finale.ogg\";\n\n\t\tpublic static final String CITY_1 = \"music/city_1.ogg\";\n\t\tpublic static final String CITY_2 = \"music/city_2.ogg\";\n\t\tpublic static final String CITY_3 = \"music/city_3.ogg\";\n\t\tpublic static final String CITY_TENSE = \"music/city_tense.ogg\";\n\t\tpublic static final String CITY_BOSS = \"music/city_boss.ogg\";\n\t\tpublic static final String CITY_BOSS_FINALE = \"music/city_boss_finale.ogg\";\n\n\t\tpublic static final String HALLS_1 = \"music/halls_1.ogg\";\n\t\tpublic static final String HALLS_2 = \"music/halls_2.ogg\";\n\t\tpublic static final String HALLS_3 = \"music/halls_3.ogg\";\n\t\tpublic static final String HALLS_TENSE = \"music/halls_tense.ogg\";\n\t\tpublic static final String HALLS_BOSS = \"music/halls_boss.ogg\";\n\t\tpublic static final String HALLS_BOSS_FINALE = \"music/halls_boss_finale.ogg\";\n\t}\n\n\tpublic static class Sounds {\n\t\tpublic static final String CLICK = \"sounds/click.mp3\";\n\t\tpublic static final String BADGE = \"sounds/badge.mp3\";\n\t\tpublic static final String GOLD = \"sounds/gold.mp3\";\n\n\t\tpublic static final String OPEN = \"sounds/door_open.mp3\";\n\t\tpublic static final String UNLOCK = \"sounds/unlock.mp3\";\n\t\tpublic static final String ITEM = \"sounds/item.mp3\";\n\t\tpublic static final String DEWDROP = \"sounds/dewdrop.mp3\";\n\t\tpublic static final String STEP = \"sounds/step.mp3\";\n\t\tpublic static final String WATER = \"sounds/water.mp3\";\n\t\tpublic static final String GRASS = \"sounds/grass.mp3\";\n\t\tpublic static final String TRAMPLE = \"sounds/trample.mp3\";\n\t\tpublic static final String STURDY = \"sounds/sturdy.mp3\";\n\n\t\tpublic static final String HIT = \"sounds/hit.mp3\";\n\t\tpublic static final String MISS = \"sounds/miss.mp3\";\n\t\tpublic static final String HIT_SLASH = \"sounds/hit_slash.mp3\";\n\t\tpublic static final String HIT_STAB = \"sounds/hit_stab.mp3\";\n\t\tpublic static final String HIT_CRUSH = \"sounds/hit_crush.mp3\";\n\t\tpublic static final String HIT_MAGIC = \"sounds/hit_magic.mp3\";\n\t\tpublic static final String HIT_STRONG = \"sounds/hit_strong.mp3\";\n\t\tpublic static final String HIT_PARRY = \"sounds/hit_parry.mp3\";\n\t\tpublic static final String HIT_ARROW = \"sounds/hit_arrow.mp3\";\n\t\tpublic static final String ATK_SPIRITBOW = \"sounds/atk_spiritbow.mp3\";\n\t\tpublic static final String ATK_CROSSBOW = \"sounds/atk_crossbow.mp3\";\n\t\tpublic static final String HEALTH_WARN = \"sounds/health_warn.mp3\";\n\t\tpublic static final String HEALTH_CRITICAL = \"sounds/health_critical.mp3\";\n\n\t\tpublic static final String DESCEND = \"sounds/descend.mp3\";\n\t\tpublic static final String EAT = \"sounds/eat.mp3\";\n\t\tpublic static final String READ = \"sounds/read.mp3\";\n\t\tpublic static final String LULLABY = \"sounds/lullaby.mp3\";\n\t\tpublic static final String DRINK = \"sounds/drink.mp3\";\n\t\tpublic static final String SHATTER = \"sounds/shatter.mp3\";\n\t\tpublic static final String ZAP = \"sounds/zap.mp3\";\n\t\tpublic static final String LIGHTNING= \"sounds/lightning.mp3\";\n\t\tpublic static final String LEVELUP = \"sounds/levelup.mp3\";\n\t\tpublic static final String DEATH = \"sounds/death.mp3\";\n\t\tpublic static final String CHALLENGE= \"sounds/challenge.mp3\";\n\t\tpublic static final String CURSED = \"sounds/cursed.mp3\";\n\t\tpublic static final String TRAP = \"sounds/trap.mp3\";\n\t\tpublic static final String EVOKE = \"sounds/evoke.mp3\";\n\t\tpublic static final String TOMB = \"sounds/tomb.mp3\";\n\t\tpublic static final String ALERT = \"sounds/alert.mp3\";\n\t\tpublic static final String MELD = \"sounds/meld.mp3\";\n\t\tpublic static final String BOSS = \"sounds/boss.mp3\";\n\t\tpublic static final String BLAST = \"sounds/blast.mp3\";\n\t\tpublic static final String PLANT = \"sounds/plant.mp3\";\n\t\tpublic static final String RAY = \"sounds/ray.mp3\";\n\t\tpublic static final String BEACON = \"sounds/beacon.mp3\";\n\t\tpublic static final String TELEPORT = \"sounds/teleport.mp3\";\n\t\tpublic static final String CHARMS = \"sounds/charms.mp3\";\n\t\tpublic static final String MASTERY = \"sounds/mastery.mp3\";\n\t\tpublic static final String PUFF = \"sounds/puff.mp3\";\n\t\tpublic static final String ROCKS = \"sounds/rocks.mp3\";\n\t\tpublic static final String BURNING = \"sounds/burning.mp3\";\n\t\tpublic static final String FALLING = \"sounds/falling.mp3\";\n\t\tpublic static final String GHOST = \"sounds/ghost.mp3\";\n\t\tpublic static final String SECRET = \"sounds/secret.mp3\";\n\t\tpublic static final String BONES = \"sounds/bones.mp3\";\n\t\tpublic static final String BEE = \"sounds/bee.mp3\";\n\t\tpublic static final String DEGRADE = \"sounds/degrade.mp3\";\n\t\tpublic static final String MIMIC = \"sounds/mimic.mp3\";\n\t\tpublic static final String DEBUFF = \"sounds/debuff.mp3\";\n\t\tpublic static final String CHARGEUP = \"sounds/chargeup.mp3\";\n\t\tpublic static final String GAS = \"sounds/gas.mp3\";\n\t\tpublic static final String CHAINS = \"sounds/chains.mp3\";\n\t\tpublic static final String SCAN = \"sounds/scan.mp3\";\n\t\tpublic static final String SHEEP = \"sounds/sheep.mp3\";\n\t\tpublic static final String MINE = \"sounds/mine.mp3\";\n\n\t\tpublic static final String[] all = new String[]{\n\t\t\t\tCLICK, BADGE, GOLD,\n\n\t\t\t\tOPEN, UNLOCK, ITEM, DEWDROP, STEP, WATER, GRASS, TRAMPLE, STURDY,\n\n\t\t\t\tHIT, MISS, HIT_SLASH, HIT_STAB, HIT_CRUSH, HIT_MAGIC, HIT_STRONG, HIT_PARRY,\n\t\t\t\tHIT_ARROW, ATK_SPIRITBOW, ATK_CROSSBOW, HEALTH_WARN, HEALTH_CRITICAL,\n\n\t\t\t\tDESCEND, EAT, READ, LULLABY, DRINK, SHATTER, ZAP, LIGHTNING, LEVELUP, DEATH,\n\t\t\t\tCHALLENGE, CURSED, TRAP, EVOKE, TOMB, ALERT, MELD, BOSS, BLAST, PLANT, RAY, BEACON,\n\t\t\t\tTELEPORT, CHARMS, MASTERY, PUFF, ROCKS, BURNING, FALLING, GHOST, SECRET, BONES,\n\t\t\t\tBEE, DEGRADE, MIMIC, DEBUFF, CHARGEUP, GAS, CHAINS, SCAN, SHEEP, MINE\n\t\t};\n\t}\n\n\tpublic static class Splashes {\n\t\tpublic static final String WARRIOR = \"splashes/warrior.jpg\";\n\t\tpublic static final String MAGE = \"splashes/mage.jpg\";\n\t\tpublic static final String ROGUE = \"splashes/rogue.jpg\";\n\t\tpublic static final String HUNTRESS = \"splashes/huntress.jpg\";\n\t\tpublic static final String DUELIST = \"splashes/duelist.jpg\";\n\t\tpublic static final String GUNNER\t= \"splashes/gunner.jpg\";\n\t\tpublic static final String SAMURAI = \"splashes/samurai.jpg\";\n\t\tpublic static final String PLANTER\t= \"splashes/planter.jpg\";\n\t\tpublic static final String KNIGHT\t= \"splashes/knight.jpg\";\n\t\tpublic static final String NURSE\t= \"splashes/nurse.jpg\";\n\t}\n\n\tpublic static class Sprites {\n\t\tpublic static final String ITEMS = \"sprites/items.png\";\n\t\tpublic static final String ITEM_ICONS = \"sprites/item_icons.png\";\n\n\t\tpublic static final String WARRIOR = \"sprites/warrior.png\";\n\t\tpublic static final String MAGE = \"sprites/mage.png\";\n\t\tpublic static final String ROGUE = \"sprites/rogue.png\";\n\t\tpublic static final String HUNTRESS = \"sprites/huntress.png\";\n\t\tpublic static final String DUELIST = \"sprites/duelist.png\";\n\t\tpublic static final String GUNNER\t= \"sprites/gunner.png\";\n\t\tpublic static final String SAMURAI\t= \"sprites/samurai.png\";\n\t\tpublic static final String PLANTER\t= \"sprites/planter.png\";\n\t\tpublic static final String KNIGHT\t= \"sprites/knight.png\";\n\t\tpublic static final String NURSE\t= \"sprites/nurse.png\";\n\t\tpublic static final String AVATARS = \"sprites/avatars.png\";\n\t\tpublic static final String PET = \"sprites/pet.png\";\n\t\tpublic static final String AMULET = \"sprites/amulet.png\";\n\n\t\tpublic static final String RAT = \"sprites/rat.png\";\n\t\tpublic static final String BRUTE = \"sprites/brute.png\";\n\t\tpublic static final String SPINNER = \"sprites/spinner.png\";\n\t\tpublic static final String DM300 = \"sprites/dm300.png\";\n\t\tpublic static final String WRAITH = \"sprites/wraith.png\";\n\t\tpublic static final String UNDEAD = \"sprites/undead.png\";\n\t\tpublic static final String KING = \"sprites/king.png\";\n\t\tpublic static final String PIRANHA = \"sprites/piranha.png\";\n\t\tpublic static final String EYE = \"sprites/eye.png\";\n\t\tpublic static final String GNOLL = \"sprites/gnoll.png\";\n\t\tpublic static final String CRAB = \"sprites/crab.png\";\n\t\tpublic static final String GOO = \"sprites/goo.png\";\n\t\tpublic static final String SWARM = \"sprites/swarm.png\";\n\t\tpublic static final String SKELETON = \"sprites/skeleton.png\";\n\t\tpublic static final String SHAMAN = \"sprites/shaman.png\";\n\t\tpublic static final String THIEF = \"sprites/thief.png\";\n\t\tpublic static final String TENGU = \"sprites/tengu.png\";\n\t\tpublic static final String SHEEP = \"sprites/sheep.png\";\n\t\tpublic static final String KEEPER = \"sprites/shopkeeper.png\";\n\t\tpublic static final String BAT = \"sprites/bat.png\";\n\t\tpublic static final String ELEMENTAL= \"sprites/elemental.png\";\n\t\tpublic static final String MONK = \"sprites/monk.png\";\n\t\tpublic static final String WARLOCK = \"sprites/warlock.png\";\n\t\tpublic static final String GOLEM = \"sprites/golem.png\";\n\t\tpublic static final String STATUE = \"sprites/statue.png\";\n\t\tpublic static final String SUCCUBUS = \"sprites/succubus.png\";\n\t\tpublic static final String SCORPIO = \"sprites/scorpio.png\";\n\t\tpublic static final String FISTS = \"sprites/yog_fists.png\";\n\t\tpublic static final String YOG = \"sprites/yog.png\";\n\t\tpublic static final String LARVA = \"sprites/larva.png\";\n\t\tpublic static final String GHOST = \"sprites/ghost.png\";\n\t\tpublic static final String MAKER = \"sprites/wandmaker.png\";\n\t\tpublic static final String TROLL = \"sprites/blacksmith.png\";\n\t\tpublic static final String IMP = \"sprites/demon.png\";\n\t\tpublic static final String RATKING = \"sprites/ratking.png\";\n\t\tpublic static final String BEE = \"sprites/bee.png\";\n\t\tpublic static final String MIMIC = \"sprites/mimic.png\";\n\t\tpublic static final String ROT_LASH = \"sprites/rot_lasher.png\";\n\t\tpublic static final String ROT_HEART= \"sprites/rot_heart.png\";\n\t\tpublic static final String GUARD = \"sprites/guard.png\";\n\t\tpublic static final String WARDS = \"sprites/wards.png\";\n\t\tpublic static final String GUARDIAN = \"sprites/guardian.png\";\n\t\tpublic static final String SLIME = \"sprites/slime.png\";\n\t\tpublic static final String SNAKE = \"sprites/snake.png\";\n\t\tpublic static final String NECRO = \"sprites/necromancer.png\";\n\t\tpublic static final String GHOUL = \"sprites/ghoul.png\";\n\t\tpublic static final String RIPPER = \"sprites/ripper.png\";\n\t\tpublic static final String SPAWNER = \"sprites/spawner.png\";\n\t\tpublic static final String DM100 = \"sprites/dm100.png\";\n\t\tpublic static final String PYLON = \"sprites/pylon.png\";\n\t\tpublic static final String DM200 = \"sprites/dm200.png\";\n\t\tpublic static final String LOTUS = \"sprites/lotus.png\";\n\t\tpublic static final String NINJA_LOG= \"sprites/ninja_log.png\";\n\t\tpublic static final String SPIRIT_HAWK= \"sprites/spirit_hawk.png\";\n\t\tpublic static final String RED_SENTRY= \"sprites/red_sentry.png\";\n\t\tpublic static final String NEW_SENTRY= \"sprites/new_sentry.png\";\n\t\tpublic static final String CRYSTAL_WISP= \"sprites/crystal_wisp.png\";\n\t\tpublic static final String CRYSTAL_GUARDIAN= \"sprites/crystal_guardian.png\";\n\t\tpublic static final String CRYSTAL_SPIRE= \"sprites/crystal_spire.png\";\n\t\tpublic static final String GNOLL_GUARD= \"sprites/gnoll_guard.png\";\n\n\t\tpublic static final String SOLDIER= \"sprites/soldier.png\";\n\t\tpublic static final String RESEARCHER= \"sprites/researcher.png\";\n\t\tpublic static final String TANK= \"sprites/tank.png\";\n\t\tpublic static final String SUPRESSION= \"sprites/supression.png\";\n\t\tpublic static final String MEDIC= \"sprites/medic.png\";\n\t\tpublic static final String REBEL= \"sprites/rebel.png\";\n\t}\n}" }, { "identifier": "Dungeon", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/Dungeon.java", "snippet": "public class Dungeon {\n\n\t//enum of items which have limited spawns, records how many have spawned\n\t//could all be their own separate numbers, but this allows iterating, much nicer for bundling/initializing.\n\tpublic static enum LimitedDrops {\n\t\t//limited world drops\n\t\tSTRENGTH_POTIONS,\n\t\tUPGRADE_SCROLLS,\n\t\tARCANE_STYLI,\n\n\t\t//Health potion sources\n\t\t//enemies\n\t\tSWARM_HP,\n\t\tNECRO_HP,\n\t\tBAT_HP,\n\t\tWARLOCK_HP,\n\t\t//Demon spawners are already limited in their spawnrate, no need to limit their health drops\n\t\t//alchemy\n\t\tCOOKING_HP,\n\t\tBLANDFRUIT_SEED,\n\n\t\t//Other limited enemy drops\n\t\tSLIME_WEP,\n\t\tSKELE_WEP,\n\t\tTHEIF_MISC,\n\t\tGUARD_ARM,\n\t\tSHAMAN_WAND,\n\t\tDM200_EQUIP,\n\t\tGOLEM_EQUIP,\n\t\tSOLDIER_WEP,\n\t\tMEDIC_HP,\n\n\t\t//containers\n\t\tVELVET_POUCH,\n\t\tSCROLL_HOLDER,\n\t\tPOTION_BANDOLIER,\n\t\tMAGICAL_HOLSTER,\n\n\t\t//lore documents\n\t\tLORE_SEWERS,\n\t\tLORE_PRISON,\n\t\tLORE_CAVES,\n\t\tLORE_CITY,\n\t\tLORE_HALLS,\n\t\tLORE_LABS;\n\n\t\tpublic int count = 0;\n\n\t\t//for items which can only be dropped once, should directly access count otherwise.\n\t\tpublic boolean dropped(){\n\t\t\treturn count != 0;\n\t\t}\n\t\tpublic void drop(){\n\t\t\tcount = 1;\n\t\t}\n\n\t\tpublic static void reset(){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tlim.count = 0;\n\t\t\t}\n\t\t}\n\n\t\tpublic static void store( Bundle bundle ){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tbundle.put(lim.name(), lim.count);\n\t\t\t}\n\t\t}\n\n\t\tpublic static void restore( Bundle bundle ){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tif (bundle.contains(lim.name())){\n\t\t\t\t\tlim.count = bundle.getInt(lim.name());\n\t\t\t\t} else {\n\t\t\t\t\tlim.count = 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\n\t\t\t//pre-v2.2.0 saves\n\t\t\tif (Dungeon.version < 750\n\t\t\t\t\t&& Dungeon.isChallenged(Challenges.NO_SCROLLS)\n\t\t\t\t\t&& UPGRADE_SCROLLS.count > 0){\n\t\t\t\t//we now count SOU fully, and just don't drop every 2nd one\n\t\t\t\tUPGRADE_SCROLLS.count += UPGRADE_SCROLLS.count-1;\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic static int challenges;\n\tpublic static int mobsToChampion;\n\n\tpublic static Hero hero;\n\tpublic static Level level;\n\n\tpublic static QuickSlot quickslot = new QuickSlot();\n\t\n\tpublic static int depth;\n\t//determines path the hero is on. Current uses:\n\t// 0 is the default path\n\t// 1 is for quest sub-floors\n\tpublic static int branch;\n\n\t//keeps track of what levels the game should try to load instead of creating fresh\n\tpublic static ArrayList<Integer> generatedLevels = new ArrayList<>();\n\n\tpublic static int gold;\n\tpublic static int energy;\n\tpublic static int bullet;\n\n\tpublic static HashSet<Integer> chapters;\n\n\tpublic static SparseArray<ArrayList<Item>> droppedItems;\n\n\t//first variable is only assigned when game is started, second is updated every time game is saved\n\tpublic static int initialVersion;\n\tpublic static int version;\n\n\tpublic static boolean daily;\n\tpublic static boolean dailyReplay;\n\tpublic static String customSeedText = \"\";\n\tpublic static long seed;\n\t\n\tpublic static void init() {\n\n\t\tinitialVersion = version = Game.versionCode;\n\t\tchallenges = SPDSettings.challenges();\n\t\tmobsToChampion = -1;\n\n\t\tif (daily) {\n\t\t\t//Ensures that daily seeds are not in the range of user-enterable seeds\n\t\t\tseed = SPDSettings.lastDaily() + DungeonSeed.TOTAL_SEEDS;\n\t\t\tDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ROOT);\n\t\t\tformat.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\t\t\tcustomSeedText = format.format(new Date(SPDSettings.lastDaily()));\n\t\t} else if (!SPDSettings.customSeed().isEmpty()){\n\t\t\tcustomSeedText = SPDSettings.customSeed();\n\t\t\tseed = DungeonSeed.convertFromText(customSeedText);\n\t\t} else {\n\t\t\tcustomSeedText = \"\";\n\t\t\tseed = DungeonSeed.randomSeed();\n\t\t}\n\n\t\tActor.clear();\n\t\tActor.resetNextID();\n\n\t\t//offset seed slightly to avoid output patterns\n\t\tRandom.pushGenerator( seed+1 );\n\n\t\t\tScroll.initLabels();\n\t\t\tPotion.initColors();\n\t\t\tRing.initGems();\n\n\t\t\tSpecialRoom.initForRun();\n\t\t\tSecretRoom.initForRun();\n\n\t\t\tGenerator.fullReset();\n\n\t\tRandom.resetGenerators();\n\t\t\n\t\tStatistics.reset();\n\t\tNotes.reset();\n\n\t\tquickslot.reset();\n\t\tQuickSlotButton.reset();\n\t\tToolbar.swappedQuickslots = false;\n\t\t\n\t\tdepth = 1;\n\t\tbranch = 0;\n\t\tgeneratedLevels.clear();\n\n\t\tgold = 0;\n\t\tenergy = 0;\n\t\tbullet = 0;\n\n\t\tdroppedItems = new SparseArray<>();\n\n\t\tLimitedDrops.reset();\n\t\t\n\t\tchapters = new HashSet<>();\n\t\t\n\t\tGhost.Quest.reset();\n\t\tWandmaker.Quest.reset();\n\t\tBlacksmith.Quest.reset();\n\t\tImp.Quest.reset();\n\n\t\thero = new Hero();\n\t\thero.live();\n\t\t\n\t\tBadges.reset();\n\t\t\n\t\tGamesInProgress.selectedClass.initHero( hero );\n\t}\n\n\tpublic static boolean isChallenged( int mask ) {\n\t\treturn (challenges & mask) != 0;\n\t}\n\n\tpublic static boolean levelHasBeenGenerated(int depth, int branch){\n\t\treturn generatedLevels.contains(depth + 1000*branch);\n\t}\n\t\n\tpublic static Level newLevel() {\n\t\t\n\t\tDungeon.level = null;\n\t\tActor.clear();\n\t\t\n\t\tLevel level;\n\t\tif (branch == 0) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 1:\n\t\t\t\tcase 2:\n\t\t\t\tcase 3:\n\t\t\t\tcase 4:\n\t\t\t\t\tlevel = new SewerLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\tlevel = new SewerBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 6:\n\t\t\t\tcase 7:\n\t\t\t\tcase 8:\n\t\t\t\tcase 9:\n\t\t\t\t\tlevel = new PrisonLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 10:\n\t\t\t\t\tlevel = new PrisonBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 11:\n\t\t\t\tcase 12:\n\t\t\t\tcase 13:\n\t\t\t\tcase 14:\n\t\t\t\t\tlevel = new CavesLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 15:\n\t\t\t\t\tlevel = new CavesBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 16:\n\t\t\t\tcase 17:\n\t\t\t\tcase 18:\n\t\t\t\tcase 19:\n\t\t\t\t\tlevel = new CityLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tlevel = new CityBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 21:\n\t\t\t\tcase 22:\n\t\t\t\tcase 23:\n\t\t\t\tcase 24:\n\t\t\t\t\tlevel = new HallsLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 25:\n\t\t\t\t\tlevel = new HallsBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 26:\n\t\t\t\tcase 27:\n\t\t\t\tcase 28:\n\t\t\t\tcase 29:\n\t\t\t\t\tlevel = new LabsLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 30:\n\t\t\t\t\tlevel = new LabsBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 31:\n\t\t\t\t\tlevel = new NewLastLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else if (branch == 1) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 11:\n\t\t\t\tcase 12:\n\t\t\t\tcase 13:\n\t\t\t\tcase 14:\n\t\t\t\t\tlevel = new MiningLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else if (branch == 2) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 16:\n\t\t\t\tcase 17:\n\t\t\t\tcase 18:\n\t\t\t\tcase 19:\n\t\t\t\t\tlevel = new TempleLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tlevel = new TempleLastLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else {\n\t\t\tlevel = new DeadEndLevel();\n\t\t}\n\n\t\t//dead end levels get cleared, don't count as generated\n\t\tif (!(level instanceof DeadEndLevel)){\n\t\t\t//this assumes that we will never have a depth value outside the range 0 to 999\n\t\t\t// or -500 to 499, etc.\n\t\t\tif (!generatedLevels.contains(depth + 1000*branch)) {\n\t\t\t\tgeneratedLevels.add(depth + 1000 * branch);\n\t\t\t}\n\n\t\t\tif (depth > Statistics.deepestFloor && branch == 0) {\n\t\t\t\tStatistics.deepestFloor = depth;\n\n\t\t\t\tif (Statistics.qualifiedForNoKilling) {\n\t\t\t\t\tStatistics.completedWithNoKilling = true;\n\t\t\t\t} else {\n\t\t\t\t\tStatistics.completedWithNoKilling = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tlevel.create();\n\t\t\n\t\tif (branch == 0) Statistics.qualifiedForNoKilling = !bossLevel();\n\t\tStatistics.qualifiedForBossChallengeBadge = false;\n\t\t\n\t\treturn level;\n\t}\n\t\n\tpublic static void resetLevel() {\n\t\t\n\t\tActor.clear();\n\t\t\n\t\tlevel.reset();\n\t\tswitchLevel( level, level.entrance() );\n\t}\n\n\tpublic static long seedCurDepth(){\n\t\treturn seedForDepth(depth, branch);\n\t}\n\n\tpublic static long seedForDepth(int depth, int branch){\n\t\tint lookAhead = depth;\n\t\tlookAhead += 30*branch; //Assumes depth is always 1-30, and branch is always 0 or higher\n\n\t\tRandom.pushGenerator( seed );\n\n\t\t\tfor (int i = 0; i < lookAhead; i ++) {\n\t\t\t\tRandom.Long(); //we don't care about these values, just need to go through them\n\t\t\t}\n\t\t\tlong result = Random.Long();\n\n\t\tRandom.popGenerator();\n\t\treturn result;\n\t}\n\t\n\tpublic static boolean shopOnLevel() {\n\t\treturn (depth == 6 || depth == 11 || depth == 16 || depth == 26) && branch == 0;\n\t}\n\t\n\tpublic static boolean bossLevel() {\n\t\treturn bossLevel( depth );\n\t}\n\t\n\tpublic static boolean bossLevel( int depth ) {\n\t\treturn depth == 5 || depth == 10 || depth == 15 || depth == 20 || depth == 25|| depth == 30;\n\t}\n\n\t//value used for scaling of damage values and other effects.\n\t//is usually the dungeon depth, but can be set to 26 when ascending\n\tpublic static int scalingDepth(){\n\t\tif (Dungeon.hero != null && Dungeon.hero.buff(AscensionChallenge.class) != null){\n\t\t\treturn 31;\n\t\t} else {\n\t\t\treturn depth;\n\t\t}\n\t}\n\n\tpublic static boolean interfloorTeleportAllowed(){\n\t\tif (Dungeon.level.locked\n\t\t\t\t|| (Dungeon.hero != null && Dungeon.hero.belongings.getItem(Amulet.class) != null)\n\t\t\t\t|| (Dungeon.hero != null && Dungeon.hero.buff(OldAmulet.TempleCurse.class) != null)){\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\n\tpublic static void switchLevel( final Level level, int pos ) {\n\n\t\t//Position of -2 specifically means trying to place the hero the exit\n\t\tif (pos == -2){\n\t\t\tLevelTransition t = level.getTransition(LevelTransition.Type.REGULAR_EXIT);\n\t\t\tif (t != null) pos = t.cell();\n\t\t}\n\n\t\t//Place hero at the entrance if they are out of the map (often used for pox = -1)\n\t\t// or if they are in solid terrain (except in the mining level, where that happens normally)\n\t\tif (pos < 0 || pos >= level.length()\n\t\t\t\t|| (!(level instanceof MiningLevel) && !level.passable[pos] && !level.avoid[pos])){\n\t\t\tpos = level.getTransition(null).cell();\n\t\t}\n\t\t\n\t\tPathFinder.setMapSize(level.width(), level.height());\n\t\t\n\t\tDungeon.level = level;\n\t\thero.pos = pos;\n\n\t\tif (hero.buff(AscensionChallenge.class) != null){\n\t\t\thero.buff(AscensionChallenge.class).onLevelSwitch();\n\t\t}\n\n\t\tif (hero.buff(OldAmulet.TempleCurse.class) != null){\n\t\t\thero.buff(OldAmulet.TempleCurse.class).onLevelSwitch();\n\t\t}\n\n\t\tMob.restoreAllies( level, pos );\n\n\t\tActor.init();\n\n\t\tlevel.addRespawner();\n\t\t\n\t\tfor(Mob m : level.mobs){\n\t\t\tif (m.pos == hero.pos && !Char.hasProp(m, Char.Property.IMMOVABLE)){\n\t\t\t\t//displace mob\n\t\t\t\tfor(int i : PathFinder.NEIGHBOURS8){\n\t\t\t\t\tif (Actor.findChar(m.pos+i) == null && level.passable[m.pos + i]){\n\t\t\t\t\t\tm.pos += i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tLight light = hero.buff( Light.class );\n\t\thero.viewDistance = light == null ? level.viewDistance : Math.max( Light.DISTANCE, level.viewDistance );\n\t\t\n\t\thero.curAction = hero.lastAction = null;\n\n\t\tobserve();\n\t\ttry {\n\t\t\tsaveAll();\n\t\t} catch (IOException e) {\n\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t\t/*This only catches IO errors. Yes, this means things can go wrong, and they can go wrong catastrophically.\n\t\t\tBut when they do the user will get a nice 'report this issue' dialogue, and I can fix the bug.*/\n\t\t}\n\t}\n\n\tpublic static void dropToChasm( Item item ) {\n\t\tint depth = Dungeon.depth + 1;\n\t\tArrayList<Item> dropped = Dungeon.droppedItems.get( depth );\n\t\tif (dropped == null) {\n\t\t\tDungeon.droppedItems.put( depth, dropped = new ArrayList<>() );\n\t\t}\n\t\tdropped.add( item );\n\t}\n\n\tpublic static boolean posNeeded() {\n\t\t//2 POS each floor set\n\t\tint posLeftThisSet = 2 - (LimitedDrops.STRENGTH_POTIONS.count - (depth / 5) * 2);\n\t\tif (posLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\n\t\t//pos drops every two floors, (numbers 1-2, and 3-4) with a 50% chance for the earlier one each time.\n\t\tint targetPOSLeft = 2 - floorThisSet/2;\n\t\tif (floorThisSet % 2 == 1 && Random.Int(2) == 0) targetPOSLeft --;\n\n\t\tif (targetPOSLeft < posLeftThisSet) return true;\n\t\telse return false;\n\n\t}\n\t\n\tpublic static boolean souNeeded() {\n\t\tint souLeftThisSet;\n\t\t//3 SOU each floor set\n\t\tsouLeftThisSet = 3 - (LimitedDrops.UPGRADE_SCROLLS.count - (depth / 5) * 3);\n\t\tif (souLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\t\t//chance is floors left / scrolls left\n\t\treturn Random.Int(5 - floorThisSet) < souLeftThisSet;\n\t}\n\t\n\tpublic static boolean asNeeded() {\n\t\t//1 AS each floor set\n\t\tint asLeftThisSet = 1 - (LimitedDrops.ARCANE_STYLI.count - (depth / 5));\n\t\tif (asLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\t\t//chance is floors left / scrolls left\n\t\treturn Random.Int(5 - floorThisSet) < asLeftThisSet;\n\t}\n\n\tprivate static final String INIT_VER\t= \"init_ver\";\n\tprivate static final String VERSION\t\t= \"version\";\n\tprivate static final String SEED\t\t= \"seed\";\n\tprivate static final String CUSTOM_SEED\t= \"custom_seed\";\n\tprivate static final String DAILY\t = \"daily\";\n\tprivate static final String DAILY_REPLAY= \"daily_replay\";\n\tprivate static final String CHALLENGES\t= \"challenges\";\n\tprivate static final String MOBS_TO_CHAMPION\t= \"mobs_to_champion\";\n\tprivate static final String HERO\t\t= \"hero\";\n\tprivate static final String DEPTH\t\t= \"depth\";\n\tprivate static final String BRANCH\t\t= \"branch\";\n\tprivate static final String GENERATED_LEVELS = \"generated_levels\";\n\tprivate static final String GOLD\t\t= \"gold\";\n\tprivate static final String ENERGY\t\t= \"energy\";\n\tprivate static final String BULLET\t\t= \"bullet\";\n\tprivate static final String DROPPED = \"dropped%d\";\n\tprivate static final String PORTED = \"ported%d\";\n\tprivate static final String LEVEL\t\t= \"level\";\n\tprivate static final String LIMDROPS = \"limited_drops\";\n\tprivate static final String CHAPTERS\t= \"chapters\";\n\tprivate static final String QUESTS\t\t= \"quests\";\n\tprivate static final String BADGES\t\t= \"badges\";\n\n\tpublic static void saveGame( int save ) {\n\t\ttry {\n\t\t\tBundle bundle = new Bundle();\n\n\t\t\tbundle.put( INIT_VER, initialVersion );\n\t\t\tbundle.put( VERSION, version = Game.versionCode );\n\t\t\tbundle.put( SEED, seed );\n\t\t\tbundle.put( CUSTOM_SEED, customSeedText );\n\t\t\tbundle.put( DAILY, daily );\n\t\t\tbundle.put( DAILY_REPLAY, dailyReplay );\n\t\t\tbundle.put( CHALLENGES, challenges );\n\t\t\tbundle.put( MOBS_TO_CHAMPION, mobsToChampion );\n\t\t\tbundle.put( HERO, hero );\n\t\t\tbundle.put( DEPTH, depth );\n\t\t\tbundle.put( BRANCH, branch );\n\n\t\t\tbundle.put( GOLD, gold );\n\t\t\tbundle.put( ENERGY, energy );\n\t\t\tbundle.put( BULLET, bullet );\n\n\t\t\tfor (int d : droppedItems.keyArray()) {\n\t\t\t\tbundle.put(Messages.format(DROPPED, d), droppedItems.get(d));\n\t\t\t}\n\n\t\t\tquickslot.storePlaceholders( bundle );\n\n\t\t\tBundle limDrops = new Bundle();\n\t\t\tLimitedDrops.store( limDrops );\n\t\t\tbundle.put ( LIMDROPS, limDrops );\n\t\t\t\n\t\t\tint count = 0;\n\t\t\tint ids[] = new int[chapters.size()];\n\t\t\tfor (Integer id : chapters) {\n\t\t\t\tids[count++] = id;\n\t\t\t}\n\t\t\tbundle.put( CHAPTERS, ids );\n\t\t\t\n\t\t\tBundle quests = new Bundle();\n\t\t\tGhost\t\t.Quest.storeInBundle( quests );\n\t\t\tWandmaker\t.Quest.storeInBundle( quests );\n\t\t\tBlacksmith\t.Quest.storeInBundle( quests );\n\t\t\tImp\t\t\t.Quest.storeInBundle( quests );\n\t\t\tbundle.put( QUESTS, quests );\n\t\t\t\n\t\t\tSpecialRoom.storeRoomsInBundle( bundle );\n\t\t\tSecretRoom.storeRoomsInBundle( bundle );\n\t\t\t\n\t\t\tStatistics.storeInBundle( bundle );\n\t\t\tNotes.storeInBundle( bundle );\n\t\t\tGenerator.storeInBundle( bundle );\n\n\t\t\tint[] bundleArr = new int[generatedLevels.size()];\n\t\t\tfor (int i = 0; i < generatedLevels.size(); i++){\n\t\t\t\tbundleArr[i] = generatedLevels.get(i);\n\t\t\t}\n\t\t\tbundle.put( GENERATED_LEVELS, bundleArr);\n\t\t\t\n\t\t\tScroll.save( bundle );\n\t\t\tPotion.save( bundle );\n\t\t\tRing.save( bundle );\n\n\t\t\tActor.storeNextID( bundle );\n\t\t\t\n\t\t\tBundle badges = new Bundle();\n\t\t\tBadges.saveLocal( badges );\n\t\t\tbundle.put( BADGES, badges );\n\t\t\t\n\t\t\tFileUtils.bundleToFile( GamesInProgress.gameFile(save), bundle);\n\t\t\t\n\t\t} catch (IOException e) {\n\t\t\tGamesInProgress.setUnknown( save );\n\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t}\n\t}\n\t\n\tpublic static void saveLevel( int save ) throws IOException {\n\t\tBundle bundle = new Bundle();\n\t\tbundle.put( LEVEL, level );\n\t\t\n\t\tFileUtils.bundleToFile(GamesInProgress.depthFile( save, depth, branch ), bundle);\n\t}\n\t\n\tpublic static void saveAll() throws IOException {\n\t\tif (hero != null && (hero.isAlive() || WndResurrect.instance != null)) {\n\t\t\t\n\t\t\tActor.fixTime();\n\t\t\tupdateLevelExplored();\n\t\t\tsaveGame( GamesInProgress.curSlot );\n\t\t\tsaveLevel( GamesInProgress.curSlot );\n\n\t\t\tGamesInProgress.set( GamesInProgress.curSlot );\n\n\t\t}\n\t}\n\t\n\tpublic static void loadGame( int save ) throws IOException {\n\t\tloadGame( save, true );\n\t}\n\t\n\tpublic static void loadGame( int save, boolean fullLoad ) throws IOException {\n\t\t\n\t\tBundle bundle = FileUtils.bundleFromFile( GamesInProgress.gameFile( save ) );\n\n\t\t//pre-1.3.0 saves\n\t\tif (bundle.contains(INIT_VER)){\n\t\t\tinitialVersion = bundle.getInt( INIT_VER );\n\t\t} else {\n\t\t\tinitialVersion = bundle.getInt( VERSION );\n\t\t}\n\n\t\tversion = bundle.getInt( VERSION );\n\n\t\tseed = bundle.contains( SEED ) ? bundle.getLong( SEED ) : DungeonSeed.randomSeed();\n\t\tcustomSeedText = bundle.getString( CUSTOM_SEED );\n\t\tdaily = bundle.getBoolean( DAILY );\n\t\tdailyReplay = bundle.getBoolean( DAILY_REPLAY );\n\n\t\tActor.clear();\n\t\tActor.restoreNextID( bundle );\n\n\t\tquickslot.reset();\n\t\tQuickSlotButton.reset();\n\t\tToolbar.swappedQuickslots = false;\n\n\t\tDungeon.challenges = bundle.getInt( CHALLENGES );\n\t\tDungeon.mobsToChampion = bundle.getInt( MOBS_TO_CHAMPION );\n\t\t\n\t\tDungeon.level = null;\n\t\tDungeon.depth = -1;\n\t\t\n\t\tScroll.restore( bundle );\n\t\tPotion.restore( bundle );\n\t\tRing.restore( bundle );\n\n\t\tquickslot.restorePlaceholders( bundle );\n\t\t\n\t\tif (fullLoad) {\n\t\t\t\n\t\t\tLimitedDrops.restore( bundle.getBundle(LIMDROPS) );\n\n\t\t\tchapters = new HashSet<>();\n\t\t\tint ids[] = bundle.getIntArray( CHAPTERS );\n\t\t\tif (ids != null) {\n\t\t\t\tfor (int id : ids) {\n\t\t\t\t\tchapters.add( id );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tBundle quests = bundle.getBundle( QUESTS );\n\t\t\tif (!quests.isNull()) {\n\t\t\t\tGhost.Quest.restoreFromBundle( quests );\n\t\t\t\tWandmaker.Quest.restoreFromBundle( quests );\n\t\t\t\tBlacksmith.Quest.restoreFromBundle( quests );\n\t\t\t\tImp.Quest.restoreFromBundle( quests );\n\t\t\t} else {\n\t\t\t\tGhost.Quest.reset();\n\t\t\t\tWandmaker.Quest.reset();\n\t\t\t\tBlacksmith.Quest.reset();\n\t\t\t\tImp.Quest.reset();\n\t\t\t}\n\t\t\t\n\t\t\tSpecialRoom.restoreRoomsFromBundle(bundle);\n\t\t\tSecretRoom.restoreRoomsFromBundle(bundle);\n\t\t}\n\t\t\n\t\tBundle badges = bundle.getBundle(BADGES);\n\t\tif (!badges.isNull()) {\n\t\t\tBadges.loadLocal( badges );\n\t\t} else {\n\t\t\tBadges.reset();\n\t\t}\n\t\t\n\t\tNotes.restoreFromBundle( bundle );\n\t\t\n\t\thero = null;\n\t\thero = (Hero)bundle.get( HERO );\n\t\t\n\t\tdepth = bundle.getInt( DEPTH );\n\t\tbranch = bundle.getInt( BRANCH );\n\n\t\tgold = bundle.getInt( GOLD );\n\t\tenergy = bundle.getInt( ENERGY );\n\t\tbullet = bundle.getInt( BULLET );\n\n\t\tStatistics.restoreFromBundle( bundle );\n\t\tGenerator.restoreFromBundle( bundle );\n\n\t\tgeneratedLevels.clear();\n\t\tif (bundle.contains(GENERATED_LEVELS)){\n\t\t\tfor (int i : bundle.getIntArray(GENERATED_LEVELS)){\n\t\t\t\tgeneratedLevels.add(i);\n\t\t\t}\n\t\t//pre-v2.1.1 saves\n\t\t} else {\n\t\t\tfor (int i = 1; i <= Statistics.deepestFloor; i++){\n\t\t\t\tgeneratedLevels.add(i);\n\t\t\t}\n\t\t}\n\n\t\tdroppedItems = new SparseArray<>();\n\t\tfor (int i=1; i <= 31; i++) {\n\t\t\t\n\t\t\t//dropped items\n\t\t\tArrayList<Item> items = new ArrayList<>();\n\t\t\tif (bundle.contains(Messages.format( DROPPED, i )))\n\t\t\t\tfor (Bundlable b : bundle.getCollection( Messages.format( DROPPED, i ) ) ) {\n\t\t\t\t\titems.add( (Item)b );\n\t\t\t\t}\n\t\t\tif (!items.isEmpty()) {\n\t\t\t\tdroppedItems.put( i, items );\n\t\t\t}\n\n\t\t}\n\t}\n\t\n\tpublic static Level loadLevel( int save ) throws IOException {\n\t\t\n\t\tDungeon.level = null;\n\t\tActor.clear();\n\n\t\tBundle bundle = FileUtils.bundleFromFile( GamesInProgress.depthFile( save, depth, branch ));\n\n\t\tLevel level = (Level)bundle.get( LEVEL );\n\n\t\tif (level == null){\n\t\t\tthrow new IOException();\n\t\t} else {\n\t\t\treturn level;\n\t\t}\n\t}\n\t\n\tpublic static void deleteGame( int save, boolean deleteLevels ) {\n\n\t\tif (deleteLevels) {\n\t\t\tString folder = GamesInProgress.gameFolder(save);\n\t\t\tfor (String file : FileUtils.filesInDir(folder)){\n\t\t\t\tif (file.contains(\"depth\")){\n\t\t\t\t\tFileUtils.deleteFile(folder + \"/\" + file);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tFileUtils.overwriteFile(GamesInProgress.gameFile(save), 1);\n\t\t\n\t\tGamesInProgress.delete( save );\n\t}\n\t\n\tpublic static void preview( GamesInProgress.Info info, Bundle bundle ) {\n\t\tinfo.depth = bundle.getInt( DEPTH );\n\t\tinfo.version = bundle.getInt( VERSION );\n\t\tinfo.challenges = bundle.getInt( CHALLENGES );\n\t\tinfo.seed = bundle.getLong( SEED );\n\t\tinfo.customSeed = bundle.getString( CUSTOM_SEED );\n\t\tinfo.daily = bundle.getBoolean( DAILY );\n\t\tinfo.dailyReplay = bundle.getBoolean( DAILY_REPLAY );\n\n\t\tHero.preview( info, bundle.getBundle( HERO ) );\n\t\tStatistics.preview( info, bundle );\n\t}\n\t\n\tpublic static void fail( Object cause ) {\n\t\tif (WndResurrect.instance == null) {\n\t\t\tupdateLevelExplored();\n\t\t\tStatistics.gameWon = false;\n\t\t\tRankings.INSTANCE.submit( false, cause );\n\t\t}\n\t}\n\t\n\tpublic static void win( Object cause ) {\n\n\t\tupdateLevelExplored();\n\t\tStatistics.gameWon = true;\n\n\t\thero.belongings.identify();\n\n\t\tRankings.INSTANCE.submit( true, cause );\n\t}\n\n\tpublic static void updateLevelExplored(){\n\t\tif (branch == 0 && level instanceof RegularLevel && !Dungeon.bossLevel()){\n\t\t\tStatistics.floorsExplored.put( depth, level.isLevelExplored(depth));\n\t\t}\n\t}\n\n\t//default to recomputing based on max hero vision, in case vision just shrank/grew\n\tpublic static void observe(){\n\t\tint dist = Math.max(Dungeon.hero.viewDistance, 8);\n\t\tdist *= 1f + 0.25f*Dungeon.hero.pointsInTalent(Talent.FARSIGHT);\n\t\tdist *= 1f + 0.25f*Dungeon.hero.pointsInTalent(Talent.TELESCOPE);\n\n\t\tif (Dungeon.hero.buff(MagicalSight.class) != null){\n\t\t\tdist = Math.max( dist, MagicalSight.DISTANCE );\n\t\t}\n\n\t\tobserve( dist+1 );\n\t}\n\t\n\tpublic static void observe( int dist ) {\n\n\t\tif (level == null) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlevel.updateFieldOfView(hero, level.heroFOV);\n\n\t\tint x = hero.pos % level.width();\n\t\tint y = hero.pos / level.width();\n\t\n\t\t//left, right, top, bottom\n\t\tint l = Math.max( 0, x - dist );\n\t\tint r = Math.min( x + dist, level.width() - 1 );\n\t\tint t = Math.max( 0, y - dist );\n\t\tint b = Math.min( y + dist, level.height() - 1 );\n\t\n\t\tint width = r - l + 1;\n\t\tint height = b - t + 1;\n\t\t\n\t\tint pos = l + t * level.width();\n\t\n\t\tfor (int i = t; i <= b; i++) {\n\t\t\tBArray.or( level.visited, level.heroFOV, pos, width, level.visited );\n\t\t\tpos+=level.width();\n\t\t}\n\t\n\t\tGameScene.updateFog(l, t, width, height);\n\n\t\tif (hero.buff(MindVision.class) != null){\n\t\t\tfor (Mob m : level.mobs.toArray(new Mob[0])){\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1 - level.width(), 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1, 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1 + level.width(), 3, level.visited );\n\t\t\t\t//updates adjacent cells too\n\t\t\t\tGameScene.updateFog(m.pos, 2);\n\t\t\t}\n\t\t}\n\n\t\tif (hero.buff(Awareness.class) != null){\n\t\t\tfor (Heap h : level.heaps.valueList()){\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 - level.width(), 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1, 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 + level.width(), 3, level.visited );\n\t\t\t\tGameScene.updateFog(h.pos, 2);\n\t\t\t}\n\t\t}\n\n\t\tfor (TalismanOfForesight.CharAwareness c : hero.buffs(TalismanOfForesight.CharAwareness.class)){\n\t\t\tChar ch = (Char) Actor.findById(c.charID);\n\t\t\tif (ch == null || !ch.isAlive()) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(ch.pos, 2);\n\t\t}\n\n\t\tfor (TalismanOfForesight.HeapAwareness h : hero.buffs(TalismanOfForesight.HeapAwareness.class)){\n\t\t\tif (Dungeon.depth != h.depth || Dungeon.branch != h.branch) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(h.pos, 2);\n\t\t}\n\n\t\tfor (RevealedArea a : hero.buffs(RevealedArea.class)){\n\t\t\tif (Dungeon.depth != a.depth || Dungeon.branch != a.branch) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(a.pos, 2);\n\t\t}\n\n\t\tfor (Char ch : Actor.chars()){\n\t\t\tif (ch instanceof WandOfWarding.Ward\n\t\t\t\t\t|| ch instanceof WandOfRegrowth.Lotus\n\t\t\t\t\t|| ch instanceof SpiritHawk.HawkAlly){\n\t\t\t\tx = ch.pos % level.width();\n\t\t\t\ty = ch.pos / level.width();\n\n\t\t\t\t//left, right, top, bottom\n\t\t\t\tdist = ch.viewDistance+1;\n\t\t\t\tl = Math.max( 0, x - dist );\n\t\t\t\tr = Math.min( x + dist, level.width() - 1 );\n\t\t\t\tt = Math.max( 0, y - dist );\n\t\t\t\tb = Math.min( y + dist, level.height() - 1 );\n\n\t\t\t\twidth = r - l + 1;\n\t\t\t\theight = b - t + 1;\n\n\t\t\t\tpos = l + t * level.width();\n\n\t\t\t\tfor (int i = t; i <= b; i++) {\n\t\t\t\t\tBArray.or( level.visited, level.heroFOV, pos, width, level.visited );\n\t\t\t\t\tpos+=level.width();\n\t\t\t\t}\n\t\t\t\tGameScene.updateFog(ch.pos, dist);\n\t\t\t}\n\t\t}\n\n\t\tGameScene.afterObserve();\n\t}\n\n\t//we store this to avoid having to re-allocate the array with each pathfind\n\tprivate static boolean[] passable;\n\n\tprivate static void setupPassable(){\n\t\tif (passable == null || passable.length != Dungeon.level.length())\n\t\t\tpassable = new boolean[Dungeon.level.length()];\n\t\telse\n\t\t\tBArray.setFalse(passable);\n\t}\n\n\tpublic static boolean[] findPassable(Char ch, boolean[] pass, boolean[] vis, boolean chars){\n\t\treturn findPassable(ch, pass, vis, chars, chars);\n\t}\n\n\tpublic static boolean[] findPassable(Char ch, boolean[] pass, boolean[] vis, boolean chars, boolean considerLarge){\n\t\tsetupPassable();\n\t\tif (ch.flying || ch.buff( Amok.class ) != null) {\n\t\t\tBArray.or( pass, Dungeon.level.avoid, passable );\n\t\t} else {\n\t\t\tSystem.arraycopy( pass, 0, passable, 0, Dungeon.level.length() );\n\t\t}\n\n\t\tif (considerLarge && Char.hasProp(ch, Char.Property.LARGE)){\n\t\t\tBArray.and( passable, Dungeon.level.openSpace, passable );\n\t\t}\n\n\t\tch.modifyPassable(passable);\n\n\t\tif (chars) {\n\t\t\tfor (Char c : Actor.chars()) {\n\t\t\t\tif (vis[c.pos]) {\n\t\t\t\t\tpassable[c.pos] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn passable;\n\t}\n\n\tpublic static PathFinder.Path findPath(Char ch, int to, boolean[] pass, boolean[] vis, boolean chars) {\n\n\t\treturn PathFinder.find( ch.pos, to, findPassable(ch, pass, vis, chars) );\n\n\t}\n\t\n\tpublic static int findStep(Char ch, int to, boolean[] pass, boolean[] visible, boolean chars ) {\n\n\t\tif (Dungeon.level.adjacent( ch.pos, to )) {\n\t\t\treturn Actor.findChar( to ) == null && pass[to] ? to : -1;\n\t\t}\n\n\t\treturn PathFinder.getStep( ch.pos, to, findPassable(ch, pass, visible, chars) );\n\n\t}\n\t\n\tpublic static int flee( Char ch, int from, boolean[] pass, boolean[] visible, boolean chars ) {\n\t\tboolean[] passable = findPassable(ch, pass, visible, false, true);\n\t\tpassable[ch.pos] = true;\n\n\t\t//only consider other chars impassable if our retreat step may collide with them\n\t\tif (chars) {\n\t\t\tfor (Char c : Actor.chars()) {\n\t\t\t\tif (c.pos == from || Dungeon.level.adjacent(c.pos, ch.pos)) {\n\t\t\t\t\tpassable[c.pos] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//chars affected by terror have a shorter lookahead and can't approach the fear source\n\t\tboolean canApproachFromPos = ch.buff(Terror.class) == null && ch.buff(Dread.class) == null;\n\t\treturn PathFinder.getStepBack( ch.pos, from, canApproachFromPos ? 8 : 4, passable, canApproachFromPos );\n\t\t\n\t}\n\n}" }, { "identifier": "Char", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/Char.java", "snippet": "public abstract class Char extends Actor {\n\t\n\tpublic int pos = 0;\n\t\n\tpublic CharSprite sprite;\n\t\n\tpublic int HT;\n\tpublic int HP;\n\t\n\tprotected float baseSpeed\t= 1;\n\tprotected PathFinder.Path path;\n\n\tpublic int paralysed\t = 0;\n\tpublic boolean rooted\t\t= false;\n\tpublic boolean flying\t\t= false;\n\tpublic int invisible\t\t= 0;\n\t\n\t//these are relative to the hero\n\tpublic enum Alignment{\n\t\tENEMY,\n\t\tNEUTRAL,\n\t\tALLY\n\t}\n\tpublic Alignment alignment;\n\t\n\tpublic int viewDistance\t= 8;\n\t\n\tpublic boolean[] fieldOfView = null;\n\t\n\tprivate LinkedHashSet<Buff> buffs = new LinkedHashSet<>();\n\t\n\t@Override\n\tprotected boolean act() {\n\t\tif (fieldOfView == null || fieldOfView.length != Dungeon.level.length()){\n\t\t\tfieldOfView = new boolean[Dungeon.level.length()];\n\t\t}\n\t\tDungeon.level.updateFieldOfView( this, fieldOfView );\n\n\t\t//throw any items that are on top of an immovable char\n\t\tif (properties().contains(Property.IMMOVABLE)){\n\t\t\tthrowItems();\n\t\t}\n\t\treturn false;\n\t}\n\n\tprotected void throwItems(){\n\t\tHeap heap = Dungeon.level.heaps.get( pos );\n\t\tif (heap != null && heap.type == Heap.Type.HEAP\n\t\t\t\t&& !(heap.peek() instanceof Tengu.BombAbility.BombItem)\n\t\t\t\t&& !(heap.peek() instanceof Tengu.ShockerAbility.ShockerItem)) {\n\t\t\tArrayList<Integer> candidates = new ArrayList<>();\n\t\t\tfor (int n : PathFinder.NEIGHBOURS8){\n\t\t\t\tif (Dungeon.level.passable[pos+n]){\n\t\t\t\t\tcandidates.add(pos+n);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!candidates.isEmpty()){\n\t\t\t\tDungeon.level.drop( heap.pickUp(), Random.element(candidates) ).sprite.drop( pos );\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic String name(){\n\t\treturn Messages.get(this, \"name\");\n\t}\n\n\tpublic boolean canInteract(Char c){\n\t\tif (Dungeon.level.adjacent( pos, c.pos )){\n\t\t\treturn true;\n\t\t} else if (c instanceof Hero\n\t\t\t\t&& alignment == Alignment.ALLY\n\t\t\t\t&& Dungeon.level.distance(pos, c.pos) <= 2*Dungeon.hero.pointsInTalent(Talent.ALLY_WARP)){\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t//swaps places by default\n\tpublic boolean interact(Char c){\n\n\t\t//don't allow char to swap onto hazard unless they're flying\n\t\t//you can swap onto a hazard though, as you're not the one instigating the swap\n\t\tif (!Dungeon.level.passable[pos] && !c.flying){\n\t\t\treturn true;\n\t\t}\n\n\t\t//can't swap into a space without room\n\t\tif (properties().contains(Property.LARGE) && !Dungeon.level.openSpace[c.pos]\n\t\t\t|| c.properties().contains(Property.LARGE) && !Dungeon.level.openSpace[pos]){\n\t\t\treturn true;\n\t\t}\n\n\t\t//we do a little raw position shuffling here so that the characters are never\n\t\t// on the same cell when logic such as occupyCell() is triggered\n\t\tint oldPos = pos;\n\t\tint newPos = c.pos;\n\n\t\t//warp instantly with allies in this case\n\t\tif (c == Dungeon.hero && Dungeon.hero.hasTalent(Talent.ALLY_WARP)){\n\t\t\tPathFinder.buildDistanceMap(c.pos, BArray.or(Dungeon.level.passable, Dungeon.level.avoid, null));\n\t\t\tif (PathFinder.distance[pos] == Integer.MAX_VALUE){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tpos = newPos;\n\t\t\tc.pos = oldPos;\n\t\t\tScrollOfTeleportation.appear(this, newPos);\n\t\t\tScrollOfTeleportation.appear(c, oldPos);\n\t\t\tDungeon.observe();\n\t\t\tGameScene.updateFog();\n\t\t\treturn true;\n\t\t}\n\n\t\t//can't swap places if one char has restricted movement\n\t\tif (rooted || c.rooted || buff(Vertigo.class) != null || c.buff(Vertigo.class) != null){\n\t\t\treturn true;\n\t\t}\n\n\t\tc.pos = oldPos;\n\t\tmoveSprite( oldPos, newPos );\n\t\tmove( newPos );\n\n\t\tc.pos = newPos;\n\t\tc.sprite.move( newPos, oldPos );\n\t\tc.move( oldPos );\n\t\t\n\t\tc.spend( 1 / c.speed() );\n\n\t\tif (c == Dungeon.hero){\n\t\t\tif (Dungeon.hero.subClass == HeroSubClass.FREERUNNER){\n\t\t\t\tBuff.affect(Dungeon.hero, Momentum.class).gainStack();\n\t\t\t}\n\n\t\t\tDungeon.hero.busy();\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t\n\tprotected boolean moveSprite( int from, int to ) {\n\t\t\n\t\tif (sprite.isVisible() && sprite.parent != null && (Dungeon.level.heroFOV[from] || Dungeon.level.heroFOV[to])) {\n\t\t\tsprite.move( from, to );\n\t\t\treturn true;\n\t\t} else {\n\t\t\tsprite.turnTo(from, to);\n\t\t\tsprite.place( to );\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic void hitSound( float pitch ){\n\t\tSample.INSTANCE.play(Assets.Sounds.HIT, 1, pitch);\n\t}\n\n\tpublic boolean blockSound( float pitch ) {\n\t\treturn false;\n\t}\n\t\n\tprotected static final String POS = \"pos\";\n\tprotected static final String TAG_HP = \"HP\";\n\tprotected static final String TAG_HT = \"HT\";\n\tprotected static final String TAG_SHLD = \"SHLD\";\n\tprotected static final String BUFFS\t = \"buffs\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.storeInBundle( bundle );\n\t\t\n\t\tbundle.put( POS, pos );\n\t\tbundle.put( TAG_HP, HP );\n\t\tbundle.put( TAG_HT, HT );\n\t\tbundle.put( BUFFS, buffs );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.restoreFromBundle( bundle );\n\t\t\n\t\tpos = bundle.getInt( POS );\n\t\tHP = bundle.getInt( TAG_HP );\n\t\tHT = bundle.getInt( TAG_HT );\n\t\t\n\t\tfor (Bundlable b : bundle.getCollection( BUFFS )) {\n\t\t\tif (b != null) {\n\t\t\t\t((Buff)b).attachTo( this );\n\t\t\t}\n\t\t}\n\t}\n\n\tfinal public boolean attack( Char enemy ){\n\t\treturn attack(enemy, 1f, 0f, 1f);\n\t}\n\t\n\tpublic boolean attack( Char enemy, float dmgMulti, float dmgBonus, float accMulti ) {\n\n\t\tif (enemy == null) return false;\n\t\t\n\t\tboolean visibleFight = Dungeon.level.heroFOV[pos] || Dungeon.level.heroFOV[enemy.pos];\n\n\t\tif (enemy.isInvulnerable(getClass())) {\n\n\t\t\tif (visibleFight) {\n\t\t\t\tenemy.sprite.showStatus( CharSprite.POSITIVE, Messages.get(this, \"invulnerable\") );\n\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1f, Random.Float(0.96f, 1.05f));\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (hit( this, enemy, accMulti, false )) {\n\t\t\t\n\t\t\tint dr = Math.round(enemy.drRoll() * AscensionChallenge.statModifier(enemy));\n\t\t\t\n\t\t\tif (this instanceof Hero){\n\t\t\t\tHero h = (Hero)this;\n\t\t\t\tif (h.belongings.attackingWeapon() instanceof MissileWeapon\n\t\t\t\t\t\t&& h.subClass == HeroSubClass.SNIPER\n\t\t\t\t\t\t&& !Dungeon.level.adjacent(h.pos, enemy.pos)){\n\t\t\t\t\tdr = 0;\n\t\t\t\t}\n\n\t\t\t\tif (h.belongings.attackingWeapon() instanceof Gun.Bullet) {\n\t\t\t\t\tdr *= ((Gun.Bullet) h.belongings.attackingWeapon()).whatBullet().armorFactor();\n\t\t\t\t}\n\n\t\t\t\tif (h.buff(MonkEnergy.MonkAbility.UnarmedAbilityTracker.class) != null){\n\t\t\t\t\tdr = 0;\n\t\t\t\t} else if (h.subClass == HeroSubClass.MONK) {\n\t\t\t\t\t//3 turns with standard attack delay\n\t\t\t\t\tBuff.prolong(h, MonkEnergy.MonkAbility.JustHitTracker.class, 4f);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//we use a float here briefly so that we don't have to constantly round while\n\t\t\t// potentially applying various multiplier effects\n\t\t\tfloat dmg;\n\t\t\tPreparation prep = buff(Preparation.class);\n\t\t\tif (prep != null){\n\t\t\t\tdmg = prep.damageRoll(this);\n\t\t\t\tif (this == Dungeon.hero && Dungeon.hero.hasTalent(Talent.BOUNTY_HUNTER)) {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.BountyHunterTracker.class, 0.0f);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdmg = damageRoll();\n\t\t\t}\n\n\t\t\tdmg = Math.round(dmg*dmgMulti);\n\n\t\t\tBerserk berserk = buff(Berserk.class);\n\t\t\tif (berserk != null) dmg = berserk.damageFactor(dmg);\n\n\t\t\tif (buff( Fury.class ) != null) {\n\t\t\t\tdmg *= 1.5f;\n\t\t\t}\n\n\t\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\t\tdmg *= buff.meleeDamageFactor();\n\t\t\t}\n\n\t\t\tdmg *= AscensionChallenge.statModifier(this);\n\n\t\t\t//flat damage bonus is applied after positive multipliers, but before negative ones\n\t\t\tdmg += dmgBonus;\n\n\t\t\t//friendly endure\n\t\t\tEndure.EndureTracker endure = buff(Endure.EndureTracker.class);\n\t\t\tif (endure != null) dmg = endure.damageFactor(dmg);\n\n\t\t\t//enemy endure\n\t\t\tendure = enemy.buff(Endure.EndureTracker.class);\n\t\t\tif (endure != null){\n\t\t\t\tdmg = endure.adjustDamageTaken(dmg);\n\t\t\t}\n\n\t\t\tif (enemy.buff(ScrollOfChallenge.ChallengeArena.class) != null){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\n\t\t\tif (enemy.buff(MonkEnergy.MonkAbility.Meditate.MeditateResistance.class) != null){\n\t\t\t\tdmg *= 0.2f;\n\t\t\t}\n\n\t\t\tif ( buff(Weakness.class) != null ){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\n\t\t\tif ( buff(SoulMark.class) != null && hero.hasTalent(Talent.MARK_OF_WEAKNESS)) {\n\t\t\t\tif (this.alignment != Alignment.ALLY) {\n\t\t\t\t\tdmg *= Math.pow(0.9f, hero.pointsInTalent(Talent.MARK_OF_WEAKNESS));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tint effectiveDamage = enemy.defenseProc( this, Math.round(dmg) );\n\t\t\t//do not trigger on-hit logic if defenseProc returned a negative value\n\t\t\tif (effectiveDamage >= 0) {\n\t\t\t\teffectiveDamage = Math.max(effectiveDamage - dr, 0);\n\n\t\t\t\tif (enemy.buff(Viscosity.ViscosityTracker.class) != null) {\n\t\t\t\t\teffectiveDamage = enemy.buff(Viscosity.ViscosityTracker.class).deferDamage(effectiveDamage);\n\t\t\t\t\tenemy.buff(Viscosity.ViscosityTracker.class).detach();\n\t\t\t\t}\n\n\t\t\t\t//vulnerable specifically applies after armor reductions\n\t\t\t\tif (enemy.buff(Vulnerable.class) != null) {\n\t\t\t\t\teffectiveDamage *= 1.33f;\n\t\t\t\t}\n\n\t\t\t\teffectiveDamage = attackProc(enemy, effectiveDamage);\n\t\t\t}\n\t\t\tif (visibleFight) {\n\t\t\t\tif (effectiveDamage > 0 || !enemy.blockSound(Random.Float(0.96f, 1.05f))) {\n\t\t\t\t\thitSound(Random.Float(0.87f, 1.15f));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If the enemy is already dead, interrupt the attack.\n\t\t\t// This matters as defence procs can sometimes inflict self-damage, such as armor glyphs.\n\t\t\tif (!enemy.isAlive()){\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tenemy.damage( effectiveDamage, this );\n\n\t\t\tif (buff(FireImbue.class) != null) buff(FireImbue.class).proc(enemy);\n\t\t\tif (buff(FrostImbue.class) != null) buff(FrostImbue.class).proc(enemy);\n\t\t\tif (buff(ThunderImbue.class) != null) buff(ThunderImbue.class).proc(enemy, (int)dmg);\n\n\t\t\tif (enemy.isAlive() && enemy.alignment != alignment && prep != null && prep.canKO(enemy)){\n\t\t\t\tenemy.HP = 0;\n\t\t\t\tif (!enemy.isAlive()) {\n\t\t\t\t\tenemy.die(this);\n\t\t\t\t} else {\n\t\t\t\t\t//helps with triggering any on-damage effects that need to activate\n\t\t\t\t\tenemy.damage(-1, this);\n\t\t\t\t\tDeathMark.processFearTheReaper(enemy);\n\t\t\t\t}\n\t\t\t\tif (enemy.sprite != null) {\n\t\t\t\t\tenemy.sprite.showStatus(CharSprite.NEGATIVE, Messages.get(Preparation.class, \"assassinated\"));\n\t\t\t\t}\n\t\t\t\tif (Random.Float() < hero.pointsInTalent(Talent.ENERGY_DRAW)/3f) {\n\t\t\t\t\tCloakOfShadows cloak = hero.belongings.getItem(CloakOfShadows.class);\n\t\t\t\t\tif (cloak != null) {\n\t\t\t\t\t\tcloak.overCharge(1);\n\t\t\t\t\t\tScrollOfRecharging.charge(Dungeon.hero);\n\t\t\t\t\t\tSpellSprite.show(hero, SpellSprite.CHARGE);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tTalent.CombinedLethalityTriggerTracker combinedLethality = buff(Talent.CombinedLethalityTriggerTracker.class);\n\t\t\tif (combinedLethality != null){\n\t\t\t\tif ( enemy.isAlive() && enemy.alignment != alignment && !Char.hasProp(enemy, Property.BOSS)\n\t\t\t\t\t\t&& !Char.hasProp(enemy, Property.MINIBOSS) && this instanceof Hero &&\n\t\t\t\t\t\t(enemy.HP/(float)enemy.HT) <= 0.4f*((Hero)this).pointsInTalent(Talent.COMBINED_LETHALITY)/3f) {\n\t\t\t\t\tenemy.HP = 0;\n\t\t\t\t\tif (!enemy.isAlive()) {\n\t\t\t\t\t\tenemy.die(this);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//helps with triggering any on-damage effects that need to activate\n\t\t\t\t\t\tenemy.damage(-1, this);\n\t\t\t\t\t\tDeathMark.processFearTheReaper(enemy);\n\t\t\t\t\t}\n\t\t\t\t\tif (enemy.sprite != null) {\n\t\t\t\t\t\tenemy.sprite.showStatus(CharSprite.NEGATIVE, Messages.get(Talent.CombinedLethalityTriggerTracker.class, \"executed\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcombinedLethality.detach();\n\t\t\t}\n\n\t\t\tif (enemy.sprite != null) {\n\t\t\t\tenemy.sprite.bloodBurstA(sprite.center(), effectiveDamage);\n\t\t\t\tenemy.sprite.flash();\n\t\t\t}\n\n\t\t\tif (!enemy.isAlive() && visibleFight) {\n\t\t\t\tif (enemy == Dungeon.hero) {\n\t\t\t\t\t\n\t\t\t\t\tif (this == Dungeon.hero) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this instanceof WandOfLivingEarth.EarthGuardian\n\t\t\t\t\t\t\t|| this instanceof MirrorImage || this instanceof PrismaticImage){\n\t\t\t\t\t\tBadges.validateDeathFromFriendlyMagic();\n\t\t\t\t\t}\n\t\t\t\t\tDungeon.fail( this );\n\t\t\t\t\tGLog.n( Messages.capitalize(Messages.get(Char.class, \"kill\", name())) );\n\t\t\t\t\t\n\t\t\t\t} else if (this == Dungeon.hero) {\n\t\t\t\t\tGLog.i( Messages.capitalize(Messages.get(Char.class, \"defeat\", enemy.name())) );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t\t\n\t\t} else {\n\n\t\t\tif (enemy instanceof Hero) {\n\t\t\t\tif (hero.pointsInTalent(Talent.SWIFT_MOVEMENT) == 3) {\n\t\t\t\t\tBuff.prolong(hero, Invisibility.class, 1.0001f);\n\t\t\t\t}\n\t\t\t\tif (Random.Int(5) < hero.pointsInTalent(Talent.COUNTER_ATTACK)) {\n\t\t\t\t\tBuff.affect(hero, Talent.CounterAttackTracker.class);\n\t\t\t\t}\n\t\t\t\tif (hero.hasTalent(Talent.QUICK_PREP)) {\n\t\t\t\t\tMomentum momentum = hero.buff(Momentum.class);\n\t\t\t\t\tif (momentum != null) {\n\t\t\t\t\t\tmomentum.quickPrep(hero.pointsInTalent(Talent.QUICK_PREP));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tenemy.sprite.showStatus( CharSprite.NEUTRAL, enemy.defenseVerb() );\n\t\t\tif (visibleFight) {\n\t\t\t\t//TODO enemy.defenseSound? currently miss plays for monks/crab even when they parry\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.MISS);\n\t\t\t}\n\t\t\t\n\t\t\treturn false;\n\t\t\t\n\t\t}\n\t}\n\n\tpublic static int INFINITE_ACCURACY = 1_000_000;\n\tpublic static int INFINITE_EVASION = 1_000_000;\n\n\tfinal public static boolean hit( Char attacker, Char defender, boolean magic ) {\n\t\treturn hit(attacker, defender, magic ? 2f : 1f, magic);\n\t}\n\n\tpublic static boolean hit( Char attacker, Char defender, float accMulti, boolean magic ) {\n\t\tfloat acuStat = attacker.attackSkill( defender );\n\t\tfloat defStat = defender.defenseSkill( attacker );\n\n\t\tif (defender instanceof Hero && ((Hero) defender).damageInterrupt){\n\t\t\t((Hero) defender).interrupt();\n\t\t}\n\n\t\t//invisible chars always hit (for the hero this is surprise attacking)\n\t\tif (attacker.invisible > 0 && attacker.canSurpriseAttack()){\n\t\t\tacuStat = INFINITE_ACCURACY;\n\t\t}\n\n\t\tif (defender.buff(MonkEnergy.MonkAbility.Focus.FocusBuff.class) != null && !magic){\n\t\t\tdefStat = INFINITE_EVASION;\n\t\t\tdefender.buff(MonkEnergy.MonkAbility.Focus.FocusBuff.class).detach();\n\t\t\tBuff.affect(defender, MonkEnergy.MonkAbility.Focus.FocusActivation.class, 0);\n\t\t}\n\n\t\t//if accuracy or evasion are large enough, treat them as infinite.\n\t\t//note that infinite evasion beats infinite accuracy\n\t\tif (defStat >= INFINITE_EVASION){\n\t\t\treturn false;\n\t\t} else if (acuStat >= INFINITE_ACCURACY){\n\t\t\treturn true;\n\t\t}\n\n\t\tfloat acuRoll = Random.Float( acuStat );\n\t\tif (attacker.buff(Bless.class) != null) acuRoll *= 1.25f;\n\t\tif (attacker.buff( Hex.class) != null) acuRoll *= 0.8f;\n\t\tif (attacker.buff( Daze.class) != null) acuRoll *= 0.5f;\n\t\tfor (ChampionEnemy buff : attacker.buffs(ChampionEnemy.class)){\n\t\t\tacuRoll *= buff.evasionAndAccuracyFactor();\n\t\t}\n\t\tacuRoll *= AscensionChallenge.statModifier(attacker);\n\t\t\n\t\tfloat defRoll = Random.Float( defStat );\n\t\tif (defender.buff(Bless.class) != null) defRoll *= 1.25f;\n\t\tif (defender.buff( Hex.class) != null) defRoll *= 0.8f;\n\t\tif (defender.buff( Daze.class) != null) defRoll *= 0.5f;\n\t\tfor (ChampionEnemy buff : defender.buffs(ChampionEnemy.class)){\n\t\t\tdefRoll *= buff.evasionAndAccuracyFactor();\n\t\t}\n\t\tdefRoll *= AscensionChallenge.statModifier(defender);\n\t\t\n\t\treturn (acuRoll * accMulti) >= defRoll;\n\t}\n\t\n\tpublic int attackSkill( Char target ) {\n\t\treturn 0;\n\t}\n\t\n\tpublic int defenseSkill( Char enemy ) {\n\t\treturn 0;\n\t}\n\t\n\tpublic String defenseVerb() {\n\t\treturn Messages.get(this, \"def_verb\");\n\t}\n\t\n\tpublic int drRoll() {\n\t\tint dr = 0;\n\n\t\tdr += Random.NormalIntRange( 0 , Barkskin.currentLevel(this) );\n\n\t\treturn dr;\n\t}\n\t\n\tpublic int damageRoll() {\n\t\treturn 1;\n\t}\n\t\n\t//TODO it would be nice to have a pre-armor and post-armor proc.\n\t// atm attack is always post-armor and defence is already pre-armor\n\t\n\tpublic int attackProc( Char enemy, int damage ) {\n\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\tbuff.onAttackProc( enemy );\n\t\t}\n\t\treturn damage;\n\t}\n\t\n\tpublic int defenseProc( Char enemy, int damage ) {\n\n\t\tEarthroot.Armor armor = buff( Earthroot.Armor.class );\n\t\tif (armor != null) {\n\t\t\tdamage = armor.absorb( damage );\n\t\t}\n\n\t\treturn damage;\n\t}\n\t\n\tpublic float speed() {\n\t\tfloat speed = baseSpeed;\n\t\tif ( buff( Cripple.class ) != null ) speed /= 2f;\n\t\tif ( buff( Stamina.class ) != null) speed *= 1.5f;\n\t\tif ( buff( Adrenaline.class ) != null) speed *= 2f;\n\t\tif ( buff( Haste.class ) != null) speed *= 3f;\n\t\tif ( buff( Dread.class ) != null) speed *= 2f;\n\t\treturn speed;\n\t}\n\n\t//currently only used by invisible chars, or by the hero\n\tpublic boolean canSurpriseAttack(){\n\t\treturn true;\n\t}\n\t\n\t//used so that buffs(Shieldbuff.class) isn't called every time unnecessarily\n\tprivate int cachedShield = 0;\n\tpublic boolean needsShieldUpdate = true;\n\t\n\tpublic int shielding(){\n\t\tif (!needsShieldUpdate){\n\t\t\treturn cachedShield;\n\t\t}\n\t\t\n\t\tcachedShield = 0;\n\t\tfor (ShieldBuff s : buffs(ShieldBuff.class)){\n\t\t\tcachedShield += s.shielding();\n\t\t}\n\t\tneedsShieldUpdate = false;\n\t\treturn cachedShield;\n\t}\n\t\n\tpublic void damage( int dmg, Object src ) {\n\t\t\n\t\tif (!isAlive() || dmg < 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tif(isInvulnerable(src.getClass())){\n\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.get(this, \"invulnerable\"));\n\t\t\treturn;\n\t\t}\n\n\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\tdmg = (int) Math.ceil(dmg * buff.damageTakenFactor());\n\t\t}\n\n\t\tif (!(src instanceof LifeLink) && buff(LifeLink.class) != null){\n\t\t\tHashSet<LifeLink> links = buffs(LifeLink.class);\n\t\t\tfor (LifeLink link : links.toArray(new LifeLink[0])){\n\t\t\t\tif (Actor.findById(link.object) == null){\n\t\t\t\t\tlinks.remove(link);\n\t\t\t\t\tlink.detach();\n\t\t\t\t}\n\t\t\t}\n\t\t\tdmg = (int)Math.ceil(dmg / (float)(links.size()+1));\n\t\t\tfor (LifeLink link : links){\n\t\t\t\tChar ch = (Char)Actor.findById(link.object);\n\t\t\t\tif (ch != null) {\n\t\t\t\t\tch.damage(dmg, link);\n\t\t\t\t\tif (!ch.isAlive()) {\n\t\t\t\t\t\tlink.detach();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tTerror t = buff(Terror.class);\n\t\tif (t != null){\n\t\t\tt.recover();\n\t\t}\n\t\tDread d = buff(Dread.class);\n\t\tif (d != null){\n\t\t\td.recover();\n\t\t}\n\t\tCharm c = buff(Charm.class);\n\t\tif (c != null){\n\t\t\tc.recover(src);\n\t\t}\n\t\tif (this.buff(Frost.class) != null){\n\t\t\tBuff.detach( this, Frost.class );\n\t\t}\n\t\tif (this.buff(MagicalSleep.class) != null){\n\t\t\tBuff.detach(this, MagicalSleep.class);\n\t\t}\n\t\tif (this.buff(Doom.class) != null && !isImmune(Doom.class)){\n\t\t\tdmg *= 1.67f;\n\t\t}\n\t\tif (alignment != Alignment.ALLY && this.buff(DeathMark.DeathMarkTracker.class) != null){\n\t\t\tdmg *= 1.25f;\n\t\t}\n\t\t\n\t\tClass<?> srcClass = src.getClass();\n\t\tif (isImmune( srcClass )) {\n\t\t\tdmg = 0;\n\t\t} else {\n\t\t\tdmg = Math.round( dmg * resist( srcClass ));\n\t\t}\n\t\t\n\t\t//TODO improve this when I have proper damage source logic\n\t\tif (AntiMagic.RESISTS.contains(src.getClass()) && buff(ArcaneArmor.class) != null){\n\t\t\tdmg -= Random.NormalIntRange(0, buff(ArcaneArmor.class).level());\n\t\t\tif (dmg < 0) dmg = 0;\n\t\t}\n\n\t\tif (buff(Sickle.HarvestBleedTracker.class) != null){\n\t\t\tif (isImmune(Bleeding.class)){\n\t\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.titleCase(Messages.get(this, \"immune\")));\n\t\t\t\tbuff(Sickle.HarvestBleedTracker.class).detach();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tBleeding b = buff(Bleeding.class);\n\t\t\tif (b == null){\n\t\t\t\tb = new Bleeding();\n\t\t\t}\n\t\t\tb.announced = false;\n\t\t\tb.set(dmg*buff(Sickle.HarvestBleedTracker.class).bleedFactor, Sickle.HarvestBleedTracker.class);\n\t\t\tb.attachTo(this);\n\t\t\tsprite.showStatus(CharSprite.WARNING, Messages.titleCase(b.name()) + \" \" + (int)b.level());\n\t\t\tbuff(Sickle.HarvestBleedTracker.class).detach();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (buff( Paralysis.class ) != null) {\n\t\t\tbuff( Paralysis.class ).processDamage(dmg);\n\t\t}\n\n\t\tint shielded = dmg;\n\t\t//FIXME: when I add proper damage properties, should add an IGNORES_SHIELDS property to use here.\n\t\tif (!(src instanceof Hunger)){\n\t\t\tfor (ShieldBuff s : buffs(ShieldBuff.class)){\n\t\t\t\tdmg = s.absorbDamage(dmg);\n\t\t\t\tif (dmg == 0) break;\n\t\t\t}\n\t\t}\n\t\tshielded -= dmg;\n\t\tHP -= dmg;\n\n\t\tif (HP > 0 && buff(Grim.GrimTracker.class) != null){\n\n\t\t\tfloat finalChance = buff(Grim.GrimTracker.class).maxChance;\n\t\t\tfinalChance *= (float)Math.pow( ((HT - HP) / (float)HT), 2);\n\n\t\t\tif (Random.Float() < finalChance) {\n\t\t\t\tint extraDmg = Math.round(HP*resist(Grim.class));\n\t\t\t\tdmg += extraDmg;\n\t\t\t\tHP -= extraDmg;\n\n\t\t\t\tsprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\tif (!isAlive() && buff(Grim.GrimTracker.class).qualifiesForBadge){\n\t\t\t\t\tBadges.validateGrimWeapon();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (HP < 0 && src instanceof Char && alignment == Alignment.ENEMY){\n\t\t\tif (((Char) src).buff(Kinetic.KineticTracker.class) != null){\n\t\t\t\tint dmgToAdd = -HP;\n\t\t\t\tdmgToAdd -= ((Char) src).buff(Kinetic.KineticTracker.class).conservedDamage;\n\t\t\t\tdmgToAdd = Math.round(dmgToAdd * Weapon.Enchantment.genericProcChanceMultiplier((Char) src));\n\t\t\t\tif (dmgToAdd > 0) {\n\t\t\t\t\tBuff.affect((Char) src, Kinetic.ConservedDamage.class).setBonus(dmgToAdd);\n\t\t\t\t}\n\t\t\t\t((Char) src).buff(Kinetic.KineticTracker.class).detach();\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (sprite != null) {\n\t\t\tsprite.showStatus(HP > HT / 2 ?\n\t\t\t\t\t\t\tCharSprite.WARNING :\n\t\t\t\t\t\t\tCharSprite.NEGATIVE,\n\t\t\t\t\tInteger.toString(dmg + shielded));\n\t\t}\n\n\t\tif (HP < 0) HP = 0;\n\n\t\tif (!isAlive()) {\n\t\t\tdie( src );\n\t\t} else if (HP == 0 && buff(DeathMark.DeathMarkTracker.class) != null){\n\t\t\tDeathMark.processFearTheReaper(this);\n\t\t}\n\t}\n\t\n\tpublic void destroy() {\n\t\tHP = 0;\n\t\tActor.remove( this );\n\n\t\tfor (Char ch : Actor.chars().toArray(new Char[0])){\n\t\t\tif (ch.buff(Charm.class) != null && ch.buff(Charm.class).object == id()){\n\t\t\t\tch.buff(Charm.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Dread.class) != null && ch.buff(Dread.class).object == id()){\n\t\t\t\tch.buff(Dread.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Terror.class) != null && ch.buff(Terror.class).object == id()){\n\t\t\t\tch.buff(Terror.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(SnipersMark.class) != null && ch.buff(SnipersMark.class).object == id()){\n\t\t\t\tch.buff(SnipersMark.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Talent.FollowupStrikeTracker.class) != null\n\t\t\t\t\t&& ch.buff(Talent.FollowupStrikeTracker.class).object == id()){\n\t\t\t\tch.buff(Talent.FollowupStrikeTracker.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Talent.DeadlyFollowupTracker.class) != null\n\t\t\t\t\t&& ch.buff(Talent.DeadlyFollowupTracker.class).object == id()){\n\t\t\t\tch.buff(Talent.DeadlyFollowupTracker.class).detach();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void die( Object src ) {\n\t\tdestroy();\n\t\tif (src != Chasm.class) sprite.die();\n\t}\n\n\t//we cache this info to prevent having to call buff(...) in isAlive.\n\t//This is relevant because we call isAlive during drawing, which has both performance\n\t//and thread coordination implications\n\tpublic boolean deathMarked = false;\n\t\n\tpublic boolean isAlive() {\n\t\treturn HP > 0 || deathMarked;\n\t}\n\n\tpublic boolean isActive() {\n\t\treturn isAlive();\n\t}\n\n\t@Override\n\tprotected void spendConstant(float time) {\n\t\tTimekeepersHourglass.timeFreeze freeze = buff(TimekeepersHourglass.timeFreeze.class);\n\t\tif (freeze != null) {\n\t\t\tfreeze.processTime(time);\n\t\t\treturn;\n\t\t}\n\n\t\tSwiftthistle.TimeBubble bubble = buff(Swiftthistle.TimeBubble.class);\n\t\tif (bubble != null){\n\t\t\tbubble.processTime(time);\n\t\t\treturn;\n\t\t}\n\n\t\tsuper.spendConstant(time);\n\t}\n\n\t@Override\n\tprotected void spend( float time ) {\n\n\t\tfloat timeScale = 1f;\n\t\tif (buff( Slow.class ) != null) {\n\t\t\ttimeScale *= 0.5f;\n\t\t\t//slowed and chilled do not stack\n\t\t} else if (buff( Chill.class ) != null) {\n\t\t\ttimeScale *= buff( Chill.class ).speedFactor();\n\t\t}\n\t\tif (buff( Speed.class ) != null) {\n\t\t\ttimeScale *= 2.0f;\n\t\t}\n\t\t\n\t\tsuper.spend( time / timeScale );\n\t}\n\t\n\tpublic synchronized LinkedHashSet<Buff> buffs() {\n\t\treturn new LinkedHashSet<>(buffs);\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\t//returns all buffs assignable from the given buff class\n\tpublic synchronized <T extends Buff> HashSet<T> buffs( Class<T> c ) {\n\t\tHashSet<T> filtered = new HashSet<>();\n\t\tfor (Buff b : buffs) {\n\t\t\tif (c.isInstance( b )) {\n\t\t\t\tfiltered.add( (T)b );\n\t\t\t}\n\t\t}\n\t\treturn filtered;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t//returns an instance of the specific buff class, if it exists. Not just assignable\n\tpublic synchronized <T extends Buff> T buff( Class<T> c ) {\n\t\tfor (Buff b : buffs) {\n\t\t\tif (b.getClass() == c) {\n\t\t\t\treturn (T)b;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic synchronized boolean isCharmedBy( Char ch ) {\n\t\tint chID = ch.id();\n\t\tfor (Buff b : buffs) {\n\t\t\tif (b instanceof Charm && ((Charm)b).object == chID) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic synchronized boolean add( Buff buff ) {\n\n\t\tif (buff(PotionOfCleansing.Cleanse.class) != null) { //cleansing buff\n\t\t\tif (buff.type == Buff.buffType.NEGATIVE\n\t\t\t\t\t&& !(buff instanceof AllyBuff)\n\t\t\t\t\t&& !(buff instanceof LostInventory)){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tif (sprite != null && buff(Challenge.SpectatorFreeze.class) != null){\n\t\t\treturn false; //can't add buffs while frozen and game is loaded\n\t\t}\n\n\t\tbuffs.add( buff );\n\t\tif (Actor.chars().contains(this)) Actor.add( buff );\n\n\t\tif (sprite != null && buff.announced) {\n\t\t\tswitch (buff.type) {\n\t\t\t\tcase POSITIVE:\n\t\t\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NEGATIVE:\n\t\t\t\t\tsprite.showStatus(CharSprite.NEGATIVE, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NEUTRAL:\n\t\t\t\tdefault:\n\t\t\t\t\tsprite.showStatus(CharSprite.NEUTRAL, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\n\t}\n\t\n\tpublic synchronized boolean remove( Buff buff ) {\n\t\t\n\t\tbuffs.remove( buff );\n\t\tActor.remove( buff );\n\n\t\treturn true;\n\t}\n\t\n\tpublic synchronized void remove( Class<? extends Buff> buffClass ) {\n\t\tfor (Buff buff : buffs( buffClass )) {\n\t\t\tremove( buff );\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected synchronized void onRemove() {\n\t\tfor (Buff buff : buffs.toArray(new Buff[buffs.size()])) {\n\t\t\tbuff.detach();\n\t\t}\n\t}\n\t\n\tpublic synchronized void updateSpriteState() {\n\t\tfor (Buff buff:buffs) {\n\t\t\tbuff.fx( true );\n\t\t}\n\t}\n\t\n\tpublic float stealth() {\n\t\treturn 0;\n\t}\n\n\tpublic final void move( int step ) {\n\t\tmove( step, true );\n\t}\n\n\t//travelling may be false when a character is moving instantaneously, such as via teleportation\n\tpublic void move( int step, boolean travelling ) {\n\n\t\tif (travelling && Dungeon.level.adjacent( step, pos ) && buff( Vertigo.class ) != null) {\n\t\t\tsprite.interruptMotion();\n\t\t\tint newPos = pos + PathFinder.NEIGHBOURS8[Random.Int( 8 )];\n\t\t\tif (!(Dungeon.level.passable[newPos] || Dungeon.level.avoid[newPos])\n\t\t\t\t\t|| (properties().contains(Property.LARGE) && !Dungeon.level.openSpace[newPos])\n\t\t\t\t\t|| Actor.findChar( newPos ) != null)\n\t\t\t\treturn;\n\t\t\telse {\n\t\t\t\tsprite.move(pos, newPos);\n\t\t\t\tstep = newPos;\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.level.map[pos] == Terrain.OPEN_DOOR) {\n\t\t\tDoor.leave( pos );\n\t\t}\n\n\t\tpos = step;\n\t\t\n\t\tif (this != Dungeon.hero) {\n\t\t\tsprite.visible = Dungeon.level.heroFOV[pos];\n\t\t}\n\t\t\n\t\tDungeon.level.occupyCell(this );\n\t}\n\t\n\tpublic int distance( Char other ) {\n\t\treturn Dungeon.level.distance( pos, other.pos );\n\t}\n\n\tpublic boolean[] modifyPassable( boolean[] passable){\n\t\t//do nothing by default, but some chars can pass over terrain that others can't\n\t\treturn passable;\n\t}\n\t\n\tpublic void onMotionComplete() {\n\t\t//Does nothing by default\n\t\t//The main actor thread already accounts for motion,\n\t\t// so calling next() here isn't necessary (see Actor.process)\n\t}\n\t\n\tpublic void onAttackComplete() {\n\t\tnext();\n\t}\n\t\n\tpublic void onOperateComplete() {\n\t\tnext();\n\t}\n\t\n\tprotected final HashSet<Class> resistances = new HashSet<>();\n\t\n\t//returns percent effectiveness after resistances\n\t//TODO currently resistances reduce effectiveness by a static 50%, and do not stack.\n\tpublic float resist( Class effect ){\n\t\tHashSet<Class> resists = new HashSet<>(resistances);\n\t\tfor (Property p : properties()){\n\t\t\tresists.addAll(p.resistances());\n\t\t}\n\t\tfor (Buff b : buffs()){\n\t\t\tresists.addAll(b.resistances());\n\t\t}\n\t\t\n\t\tfloat result = 1f;\n\t\tfor (Class c : resists){\n\t\t\tif (c.isAssignableFrom(effect)){\n\t\t\t\tresult *= 0.5f;\n\t\t\t}\n\t\t}\n\t\treturn result * RingOfElements.resist(this, effect);\n\t}\n\t\n\tprotected final HashSet<Class> immunities = new HashSet<>();\n\t\n\tpublic boolean isImmune(Class effect ){\n\t\tHashSet<Class> immunes = new HashSet<>(immunities);\n\t\tfor (Property p : properties()){\n\t\t\timmunes.addAll(p.immunities());\n\t\t}\n\t\tfor (Buff b : buffs()){\n\t\t\timmunes.addAll(b.immunities());\n\t\t}\n\t\t\n\t\tfor (Class c : immunes){\n\t\t\tif (c.isAssignableFrom(effect)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t//similar to isImmune, but only factors in damage.\n\t//Is used in AI decision-making\n\tpublic boolean isInvulnerable( Class effect ){\n\t\treturn buff(Challenge.SpectatorFreeze.class) != null;\n\t}\n\n\tprotected HashSet<Property> properties = new HashSet<>();\n\n\tpublic HashSet<Property> properties() {\n\t\tHashSet<Property> props = new HashSet<>(properties);\n\t\t//TODO any more of these and we should make it a property of the buff, like with resistances/immunities\n\t\tif (buff(ChampionEnemy.Giant.class) != null) {\n\t\t\tprops.add(Property.LARGE);\n\t\t}\n\t\treturn props;\n\t}\n\n\tpublic enum Property{\n\t\tBOSS ( new HashSet<Class>( Arrays.asList(Grim.class, GrimTrap.class, ScrollOfRetribution.class, ScrollOfPsionicBlast.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(AllyBuff.class, Dread.class) )),\n\t\tMINIBOSS ( new HashSet<Class>(),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(AllyBuff.class, Dread.class) )),\n\t\tBOSS_MINION,\n\t\tUNDEAD,\n\t\tDEMONIC,\n\t\tINORGANIC ( new HashSet<Class>(),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Bleeding.class, ToxicGas.class, Poison.class) )),\n\t\tFIERY ( new HashSet<Class>( Arrays.asList(WandOfFireblast.class, Elemental.FireElemental.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Burning.class, Blazing.class))),\n\t\tICY ( new HashSet<Class>( Arrays.asList(WandOfFrost.class, Elemental.FrostElemental.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Frost.class, Chill.class))),\n\t\tACIDIC ( new HashSet<Class>( Arrays.asList(Corrosion.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Ooze.class))),\n\t\tELECTRIC ( new HashSet<Class>( Arrays.asList(WandOfLightning.class, Shocking.class, Potential.class, Electricity.class, ShockingDart.class, Elemental.ShockElemental.class )),\n\t\t\t\tnew HashSet<Class>()),\n\t\tLARGE,\n\t\tIMMOVABLE;\n\t\t\n\t\tprivate HashSet<Class> resistances;\n\t\tprivate HashSet<Class> immunities;\n\t\t\n\t\tProperty(){\n\t\t\tthis(new HashSet<Class>(), new HashSet<Class>());\n\t\t}\n\t\t\n\t\tProperty( HashSet<Class> resistances, HashSet<Class> immunities){\n\t\t\tthis.resistances = resistances;\n\t\t\tthis.immunities = immunities;\n\t\t}\n\t\t\n\t\tpublic HashSet<Class> resistances(){\n\t\t\treturn new HashSet<>(resistances);\n\t\t}\n\t\t\n\t\tpublic HashSet<Class> immunities(){\n\t\t\treturn new HashSet<>(immunities);\n\t\t}\n\n\t}\n\n\tpublic static boolean hasProp( Char ch, Property p){\n\t\treturn (ch != null && ch.properties().contains(p));\n\t}\n\n\tpublic void heal(int amount) {\n\t\tamount = Math.min( amount, this.HT - this.HP );\n\t\tif (amount > 0 && this.isAlive()) {\n\t\t\tthis.HP += amount;\n\t\t\tthis.sprite.emitter().start( Speck.factory( Speck.HEALING ), 0.4f, 1 );\n\t\t\tthis.sprite.showStatus( CharSprite.POSITIVE, Integer.toString( amount ) );\n\t\t}\n\t}\n}" }, { "identifier": "Amok", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Amok.java", "snippet": "public class Amok extends FlavourBuff {\n\n\t{\n\t\ttype = buffType.NEGATIVE;\n\t\tannounced = true;\n\t}\n\t\n\t@Override\n\tpublic int icon() {\n\t\treturn BuffIndicator.AMOK;\n\t}\n\n\t@Override\n\tpublic void detach() {\n\t\tsuper.detach();\n\t\tif (target instanceof Mob && target.isAlive()) {\n\t\t\t((Mob) target).aggro(null);\n\t\t}\n\t}\n}" }, { "identifier": "Buff", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Buff.java", "snippet": "public class Buff extends Actor {\n\t\n\tpublic Char target;\n\n\t{\n\t\tactPriority = BUFF_PRIO; //low priority, towards the end of a turn\n\t}\n\n\t//determines how the buff is announced when it is shown.\n\tpublic enum buffType {POSITIVE, NEGATIVE, NEUTRAL}\n\tpublic buffType type = buffType.NEUTRAL;\n\t\n\t//whether or not the buff announces its name\n\tpublic boolean announced = false;\n\n\t//whether a buff should persist through revive effects for the hero\n\tpublic boolean revivePersists = false;\n\t\n\tprotected HashSet<Class> resistances = new HashSet<>();\n\t\n\tpublic HashSet<Class> resistances() {\n\t\treturn new HashSet<>(resistances);\n\t}\n\t\n\tprotected HashSet<Class> immunities = new HashSet<>();\n\t\n\tpublic HashSet<Class> immunities() {\n\t\treturn new HashSet<>(immunities);\n\t}\n\t\n\tpublic boolean attachTo( Char target ) {\n\n\t\tif (target.isImmune( getClass() )) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tthis.target = target;\n\n\t\tif (target.add( this )){\n\t\t\tif (target.sprite != null) fx( true );\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.target = null;\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic void detach() {\n\t\tif (target.remove( this ) && target.sprite != null) fx( false );\n\t}\n\t\n\t@Override\n\tpublic boolean act() {\n\t\tdiactivate();\n\t\treturn true;\n\t}\n\t\n\tpublic int icon() {\n\t\treturn BuffIndicator.NONE;\n\t}\n\n\t//some buffs may want to tint the base texture color of their icon\n\tpublic void tintIcon( Image icon ){\n\t\t//do nothing by default\n\t}\n\n\t//percent (0-1) to fade out out the buff icon, usually if buff is expiring\n\tpublic float iconFadePercent(){\n\t\treturn 0;\n\t}\n\n\t//text to display on large buff icons in the desktop UI\n\tpublic String iconTextDisplay(){\n\t\treturn \"\";\n\t}\n\n\t//visual effect usually attached to the sprite of the character the buff is attacked to\n\tpublic void fx(boolean on) {\n\t\t//do nothing by default\n\t}\n\n\tpublic String heroMessage(){\n\t\tString msg = Messages.get(this, \"heromsg\");\n\t\tif (msg.isEmpty()) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn msg;\n\t\t}\n\t}\n\n\tpublic String name() {\n\t\treturn Messages.get(this, \"name\");\n\t}\n\n\tpublic String desc(){\n\t\treturn Messages.get(this, \"desc\");\n\t}\n\n\t//to handle the common case of showing how many turns are remaining in a buff description.\n\tprotected String dispTurns(float input){\n\t\treturn Messages.decimalFormat(\"#.##\", input);\n\t}\n\n\t//buffs act after the hero, so it is often useful to use cooldown+1 when display buff time remaining\n\tpublic float visualcooldown(){\n\t\treturn cooldown()+1f;\n\t}\n\n\t//creates a fresh instance of the buff and attaches that, this allows duplication.\n\tpublic static<T extends Buff> T append( Char target, Class<T> buffClass ) {\n\t\tT buff = Reflection.newInstance(buffClass);\n\t\tbuff.attachTo( target );\n\t\treturn buff;\n\t}\n\n\tpublic static<T extends FlavourBuff> T append( Char target, Class<T> buffClass, float duration ) {\n\t\tT buff = append( target, buffClass );\n\t\tbuff.spend( duration * target.resist(buffClass) );\n\t\treturn buff;\n\t}\n\n\t//same as append, but prevents duplication.\n\tpublic static<T extends Buff> T affect( Char target, Class<T> buffClass ) {\n\t\tT buff = target.buff( buffClass );\n\t\tif (buff != null) {\n\t\t\treturn buff;\n\t\t} else {\n\t\t\treturn append( target, buffClass );\n\t\t}\n\t}\n\t\n\tpublic static<T extends FlavourBuff> T affect( Char target, Class<T> buffClass, float duration ) {\n\t\tT buff = affect( target, buffClass );\n\t\tbuff.spend( duration * target.resist(buffClass) );\n\t\treturn buff;\n\t}\n\n\t//postpones an already active buff, or creates & attaches a new buff and delays that.\n\tpublic static<T extends FlavourBuff> T prolong( Char target, Class<T> buffClass, float duration ) {\n\t\tT buff = affect( target, buffClass );\n\t\tbuff.postpone( duration * target.resist(buffClass) );\n\t\treturn buff;\n\t}\n\n\tpublic static<T extends CounterBuff> T count( Char target, Class<T> buffclass, float count ) {\n\t\tT buff = affect( target, buffclass );\n\t\tbuff.countUp( count );\n\t\treturn buff;\n\t}\n\t\n\tpublic static void detach( Char target, Class<? extends Buff> cl ) {\n\t\tfor ( Buff b : target.buffs( cl )){\n\t\t\tb.detach();\n\t\t}\n\t}\n}" }, { "identifier": "Mob", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/mobs/Mob.java", "snippet": "public abstract class Mob extends Char {\n\n\t{\n\t\tactPriority = MOB_PRIO;\n\t\t\n\t\talignment = Alignment.ENEMY;\n\t}\n\t\n\tprivate static final String\tTXT_DIED\t= \"You hear something died in the distance\";\n\t\n\tprotected static final String TXT_NOTICE1\t= \"?!\";\n\tprotected static final String TXT_RAGE\t\t= \"#$%^\";\n\tprotected static final String TXT_EXP\t\t= \"%+dEXP\";\n\n\tpublic AiState SLEEPING = new Sleeping();\n\tpublic AiState HUNTING\t\t= new Hunting();\n\tpublic AiState WANDERING\t= new Wandering();\n\tpublic AiState FLEEING\t\t= new Fleeing();\n\tpublic AiState PASSIVE\t\t= new Passive();\n\tpublic AiState state = SLEEPING;\n\t\n\tpublic Class<? extends CharSprite> spriteClass;\n\t\n\tprotected int target = -1;\n\t\n\tpublic int defenseSkill = 0;\n\t\n\tpublic int EXP = 1;\n\tpublic int maxLvl = Hero.MAX_LEVEL-1;\n\t\n\tprotected Char enemy;\n\tprotected int enemyID = -1; //used for save/restore\n\tprotected boolean enemySeen;\n\tprotected boolean alerted = false;\n\n\tprotected static final float TIME_TO_WAKE_UP = 1f;\n\n\tprotected boolean firstAdded = true;\n\tprotected void onAdd(){\n\t\tif (firstAdded) {\n\t\t\t//modify health for ascension challenge if applicable, only on first add\n\t\t\tfloat percent = HP / (float) HT;\n\t\t\tHT = Math.round(HT * AscensionChallenge.statModifier(this));\n\t\t\tHP = Math.round(HT * percent);\n\t\t\tfirstAdded = false;\n\t\t}\n\t}\n\n\tprivate static final String STATE\t= \"state\";\n\tprivate static final String SEEN\t= \"seen\";\n\tprivate static final String TARGET\t= \"target\";\n\tprivate static final String MAX_LVL\t= \"max_lvl\";\n\n\tprivate static final String ENEMY_ID\t= \"enemy_id\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.storeInBundle( bundle );\n\n\t\tif (state == SLEEPING) {\n\t\t\tbundle.put( STATE, Sleeping.TAG );\n\t\t} else if (state == WANDERING) {\n\t\t\tbundle.put( STATE, Wandering.TAG );\n\t\t} else if (state == HUNTING) {\n\t\t\tbundle.put( STATE, Hunting.TAG );\n\t\t} else if (state == FLEEING) {\n\t\t\tbundle.put( STATE, Fleeing.TAG );\n\t\t} else if (state == PASSIVE) {\n\t\t\tbundle.put( STATE, Passive.TAG );\n\t\t}\n\t\tbundle.put( SEEN, enemySeen );\n\t\tbundle.put( TARGET, target );\n\t\tbundle.put( MAX_LVL, maxLvl );\n\n\t\tif (enemy != null) {\n\t\t\tbundle.put(ENEMY_ID, enemy.id() );\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.restoreFromBundle( bundle );\n\n\t\tString state = bundle.getString( STATE );\n\t\tif (state.equals( Sleeping.TAG )) {\n\t\t\tthis.state = SLEEPING;\n\t\t} else if (state.equals( Wandering.TAG )) {\n\t\t\tthis.state = WANDERING;\n\t\t} else if (state.equals( Hunting.TAG )) {\n\t\t\tthis.state = HUNTING;\n\t\t} else if (state.equals( Fleeing.TAG )) {\n\t\t\tthis.state = FLEEING;\n\t\t} else if (state.equals( Passive.TAG )) {\n\t\t\tthis.state = PASSIVE;\n\t\t}\n\n\t\tenemySeen = bundle.getBoolean( SEEN );\n\n\t\ttarget = bundle.getInt( TARGET );\n\n\t\tif (bundle.contains(MAX_LVL)) maxLvl = bundle.getInt(MAX_LVL);\n\n\t\tif (bundle.contains(ENEMY_ID)) {\n\t\t\tenemyID = bundle.getInt(ENEMY_ID);\n\t\t}\n\n\t\t//no need to actually save this, must be false\n\t\tfirstAdded = false;\n\t}\n\n\t//mobs need to remember their targets after every actor is added\n\tpublic void restoreEnemy(){\n\t\tif (enemyID != -1 && enemy == null) enemy = (Char)Actor.findById(enemyID);\n\t}\n\t\n\tpublic CharSprite sprite() {\n\t\treturn Reflection.newInstance(spriteClass);\n\t}\n\t\n\t@Override\n\tprotected boolean act() {\n\t\t\n\t\tsuper.act();\n\t\t\n\t\tboolean justAlerted = alerted;\n\t\talerted = false;\n\t\t\n\t\tif (justAlerted){\n\t\t\tsprite.showAlert();\n\t\t} else {\n\t\t\tsprite.hideAlert();\n\t\t\tsprite.hideLost();\n\t\t}\n\t\t\n\t\tif (paralysed > 0) {\n\t\t\tenemySeen = false;\n\t\t\tspend( TICK );\n\t\t\treturn true;\n\t\t}\n\n\t\tif (buff(Terror.class) != null || buff(Dread.class) != null ){\n\t\t\tstate = FLEEING;\n\t\t}\n\t\t\n\t\tenemy = chooseEnemy();\n\t\t\n\t\tboolean enemyInFOV = enemy != null && enemy.isAlive() && fieldOfView[enemy.pos] && enemy.invisible <= 0;\n\n\t\t//prevents action, but still updates enemy seen status\n\t\tif (buff(Feint.AfterImage.FeintConfusion.class) != null){\n\t\t\tenemySeen = enemyInFOV;\n\t\t\tspend( TICK );\n\t\t\treturn true;\n\t\t}\n\n\t\treturn state.act( enemyInFOV, justAlerted );\n\t}\n\t\n\t//FIXME this is sort of a band-aid correction for allies needing more intelligent behaviour\n\tprotected boolean intelligentAlly = false;\n\t\n\tprotected Char chooseEnemy() {\n\n\t\tDread dread = buff( Dread.class );\n\t\tif (dread != null) {\n\t\t\tChar source = (Char)Actor.findById( dread.object );\n\t\t\tif (source != null) {\n\t\t\t\treturn source;\n\t\t\t}\n\t\t}\n\n\t\tTerror terror = buff( Terror.class );\n\t\tif (terror != null) {\n\t\t\tChar source = (Char)Actor.findById( terror.object );\n\t\t\tif (source != null) {\n\t\t\t\treturn source;\n\t\t\t}\n\t\t}\n\t\t\n\t\t//if we are an alert enemy, auto-hunt a target that is affected by aggression, even another enemy\n\t\tif (alignment == Alignment.ENEMY && state != PASSIVE && state != SLEEPING) {\n\t\t\tif (enemy != null && enemy.buff(StoneOfAggression.Aggression.class) != null){\n\t\t\t\tstate = HUNTING;\n\t\t\t\treturn enemy;\n\t\t\t}\n\t\t\tfor (Char ch : Actor.chars()) {\n\t\t\t\tif (ch != this && fieldOfView[ch.pos] &&\n\t\t\t\t\t\tch.buff(StoneOfAggression.Aggression.class) != null) {\n\t\t\t\t\tstate = HUNTING;\n\t\t\t\t\treturn ch;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//find a new enemy if..\n\t\tboolean newEnemy = false;\n\t\t//we have no enemy, or the current one is dead/missing\n\t\tif ( enemy == null || !enemy.isAlive() || !Actor.chars().contains(enemy) || state == WANDERING) {\n\t\t\tnewEnemy = true;\n\t\t//We are amoked and current enemy is the hero\n\t\t} else if (buff( Amok.class ) != null && enemy == Dungeon.hero) {\n\t\t\tnewEnemy = true;\n\t\t//We are charmed and current enemy is what charmed us\n\t\t} else if (buff(Charm.class) != null && buff(Charm.class).object == enemy.id()) {\n\t\t\tnewEnemy = true;\n\t\t}\n\n\t\t//additionally, if we are an ally, find a new enemy if...\n\t\tif (!newEnemy && alignment == Alignment.ALLY){\n\t\t\t//current enemy is also an ally\n\t\t\tif (enemy.alignment == Alignment.ALLY){\n\t\t\t\tnewEnemy = true;\n\t\t\t//current enemy is invulnerable\n\t\t\t} else if (enemy.isInvulnerable(getClass())){\n\t\t\t\tnewEnemy = true;\n\t\t\t}\n\t\t}\n\n\t\tif ( newEnemy ) {\n\n\t\t\tHashSet<Char> enemies = new HashSet<>();\n\n\t\t\t//if we are amoked...\n\t\t\tif ( buff(Amok.class) != null) {\n\t\t\t\t//try to find an enemy mob to attack first.\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs)\n\t\t\t\t\tif (mob.alignment == Alignment.ENEMY && mob != this\n\t\t\t\t\t\t\t&& fieldOfView[mob.pos] && mob.invisible <= 0) {\n\t\t\t\t\t\tenemies.add(mob);\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (enemies.isEmpty()) {\n\t\t\t\t\t//try to find ally mobs to attack second.\n\t\t\t\t\tfor (Mob mob : Dungeon.level.mobs)\n\t\t\t\t\t\tif (mob.alignment == Alignment.ALLY && mob != this\n\t\t\t\t\t\t\t\t&& fieldOfView[mob.pos] && mob.invisible <= 0) {\n\t\t\t\t\t\t\tenemies.add(mob);\n\t\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (enemies.isEmpty()) {\n\t\t\t\t\t\t//try to find the hero third\n\t\t\t\t\t\tif (fieldOfView[Dungeon.hero.pos] && Dungeon.hero.invisible <= 0) {\n\t\t\t\t\t\t\tenemies.add(Dungeon.hero);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t//if we are an ally...\n\t\t\t} else if ( alignment == Alignment.ALLY ) {\n\t\t\t\t//look for hostile mobs to attack\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs)\n\t\t\t\t\tif (mob.alignment == Alignment.ENEMY && fieldOfView[mob.pos]\n\t\t\t\t\t\t\t&& mob.invisible <= 0 && !mob.isInvulnerable(getClass()))\n\t\t\t\t\t\t//intelligent allies do not target mobs which are passive, wandering, or asleep\n\t\t\t\t\t\tif (!intelligentAlly ||\n\t\t\t\t\t\t\t\t(mob.state != mob.SLEEPING && mob.state != mob.PASSIVE && mob.state != mob.WANDERING)) {\n\t\t\t\t\t\t\tenemies.add(mob);\n\t\t\t\t\t\t}\n\t\t\t\t\n\t\t\t//if we are an enemy...\n\t\t\t} else if (alignment == Alignment.ENEMY) {\n\t\t\t\t//look for ally mobs to attack\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs)\n\t\t\t\t\tif (mob.alignment == Alignment.ALLY && fieldOfView[mob.pos] && mob.invisible <= 0)\n\t\t\t\t\t\tenemies.add(mob);\n\n\t\t\t\t//and look for the hero\n\t\t\t\tif (fieldOfView[Dungeon.hero.pos] && Dungeon.hero.invisible <= 0) {\n\t\t\t\t\tenemies.add(Dungeon.hero);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\n\t\t\t//do not target anything that's charming us\n\t\t\tCharm charm = buff( Charm.class );\n\t\t\tif (charm != null){\n\t\t\t\tChar source = (Char)Actor.findById( charm.object );\n\t\t\t\tif (source != null && enemies.contains(source) && enemies.size() > 1){\n\t\t\t\t\tenemies.remove(source);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//neutral characters in particular do not choose enemies.\n\t\t\tif (enemies.isEmpty()){\n\t\t\t\treturn null;\n\t\t\t} else {\n\t\t\t\t//go after the closest potential enemy, preferring enemies that can be reached/attacked, and the hero if two are equidistant\n\t\t\t\tPathFinder.buildDistanceMap(pos, Dungeon.findPassable(this, Dungeon.level.passable, fieldOfView, true));\n\t\t\t\tChar closest = null;\n\n\t\t\t\tfor (Char curr : enemies){\n\t\t\t\t\tif (closest == null){\n\t\t\t\t\t\tclosest = curr;\n\t\t\t\t\t} else if (canAttack(closest) && !canAttack(curr)){\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t} else if ((canAttack(curr) && !canAttack(closest))\n\t\t\t\t\t\t\t|| (PathFinder.distance[curr.pos] < PathFinder.distance[closest.pos])){\n\t\t\t\t\t\tclosest = curr;\n\t\t\t\t\t} else if ( curr == Dungeon.hero &&\n\t\t\t\t\t\t\t(PathFinder.distance[curr.pos] == PathFinder.distance[closest.pos]) || (canAttack(curr) && canAttack(closest))){\n\t\t\t\t\t\tclosest = curr;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//if we were going to target the hero, but an afterimage exists, target that instead\n\t\t\t\tif (closest == Dungeon.hero){\n\t\t\t\t\tfor (Char ch : enemies){\n\t\t\t\t\t\tif (ch instanceof Feint.AfterImage){\n\t\t\t\t\t\t\tclosest = ch;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn closest;\n\t\t\t}\n\n\t\t} else\n\t\t\treturn enemy;\n\t}\n\t\n\t@Override\n\tpublic boolean add( Buff buff ) {\n\t\tif (super.add( buff )) {\n\t\t\tif (buff instanceof Amok || buff instanceof AllyBuff) {\n\t\t\t\tstate = HUNTING;\n\t\t\t} else if (buff instanceof Terror || buff instanceof Dread) {\n\t\t\t\tstate = FLEEING;\n\t\t\t} else if (buff instanceof Sleep) {\n\t\t\t\tstate = SLEEPING;\n\t\t\t\tpostpone(Sleep.SWS);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic boolean remove( Buff buff ) {\n\t\tif (super.remove( buff )) {\n\t\t\tif ((buff instanceof Terror && buff(Dread.class) == null)\n\t\t\t\t\t|| (buff instanceof Dread && buff(Terror.class) == null)) {\n\t\t\t\tif (enemySeen) {\n\t\t\t\t\tsprite.showStatus(CharSprite.NEGATIVE, Messages.get(this, \"rage\"));\n\t\t\t\t\tstate = HUNTING;\n\t\t\t\t} else {\n\t\t\t\t\tstate = WANDERING;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected boolean canAttack( Char enemy ) {\n\t\tif (Dungeon.level.adjacent( pos, enemy.pos )){\n\t\t\treturn true;\n\t\t}\n\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\tif (buff.canAttackWithExtraReach( enemy )){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate boolean cellIsPathable( int cell ){\n\t\tif (!Dungeon.level.passable[cell]){\n\t\t\tif (flying || buff(Amok.class) != null){\n\t\t\t\tif (!Dungeon.level.avoid[cell]){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (Char.hasProp(this, Char.Property.LARGE) && !Dungeon.level.openSpace[cell]){\n\t\t\treturn false;\n\t\t}\n\t\tif (Actor.findChar(cell) != null){\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tprotected boolean getCloser( int target ) {\n\t\t\n\t\tif (rooted || target == pos) {\n\t\t\treturn false;\n\t\t}\n\n\t\tint step = -1;\n\n\t\tif (Dungeon.level.adjacent( pos, target )) {\n\n\t\t\tpath = null;\n\n\t\t\tif (cellIsPathable(target)) {\n\t\t\t\tstep = target;\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tboolean newPath = false;\n\t\t\t//scrap the current path if it's empty, no longer connects to the current location\n\t\t\t//or if it's extremely inefficient and checking again may result in a much better path\n\t\t\tif (path == null || path.isEmpty()\n\t\t\t\t\t|| !Dungeon.level.adjacent(pos, path.getFirst())\n\t\t\t\t\t|| path.size() > 2*Dungeon.level.distance(pos, target))\n\t\t\t\tnewPath = true;\n\t\t\telse if (path.getLast() != target) {\n\t\t\t\t//if the new target is adjacent to the end of the path, adjust for that\n\t\t\t\t//rather than scrapping the whole path.\n\t\t\t\tif (Dungeon.level.adjacent(target, path.getLast())) {\n\t\t\t\t\tint last = path.removeLast();\n\n\t\t\t\t\tif (path.isEmpty()) {\n\n\t\t\t\t\t\t//shorten for a closer one\n\t\t\t\t\t\tif (Dungeon.level.adjacent(target, pos)) {\n\t\t\t\t\t\t\tpath.add(target);\n\t\t\t\t\t\t//extend the path for a further target\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpath.add(last);\n\t\t\t\t\t\t\tpath.add(target);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//if the new target is simply 1 earlier in the path shorten the path\n\t\t\t\t\t\tif (path.getLast() == target) {\n\n\t\t\t\t\t\t//if the new target is closer/same, need to modify end of path\n\t\t\t\t\t\t} else if (Dungeon.level.adjacent(target, path.getLast())) {\n\t\t\t\t\t\t\tpath.add(target);\n\n\t\t\t\t\t\t//if the new target is further away, need to extend the path\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpath.add(last);\n\t\t\t\t\t\t\tpath.add(target);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tnewPath = true;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t//checks if the next cell along the current path can be stepped into\n\t\t\tif (!newPath) {\n\t\t\t\tint nextCell = path.removeFirst();\n\t\t\t\tif (!cellIsPathable(nextCell)) {\n\n\t\t\t\t\tnewPath = true;\n\t\t\t\t\t//If the next cell on the path can't be moved into, see if there is another cell that could replace it\n\t\t\t\t\tif (!path.isEmpty()) {\n\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS8) {\n\t\t\t\t\t\t\tif (Dungeon.level.adjacent(pos, nextCell + i) && Dungeon.level.adjacent(nextCell + i, path.getFirst())) {\n\t\t\t\t\t\t\t\tif (cellIsPathable(nextCell+i)){\n\t\t\t\t\t\t\t\t\tpath.addFirst(nextCell+i);\n\t\t\t\t\t\t\t\t\tnewPath = false;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tpath.addFirst(nextCell);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//generate a new path\n\t\t\tif (newPath) {\n\t\t\t\t//If we aren't hunting, always take a full path\n\t\t\t\tPathFinder.Path full = Dungeon.findPath(this, target, Dungeon.level.passable, fieldOfView, true);\n\t\t\t\tif (state != HUNTING){\n\t\t\t\t\tpath = full;\n\t\t\t\t} else {\n\t\t\t\t\t//otherwise, check if other characters are forcing us to take a very slow route\n\t\t\t\t\t// and don't try to go around them yet in response, basically assume their blockage is temporary\n\t\t\t\t\tPathFinder.Path ignoreChars = Dungeon.findPath(this, target, Dungeon.level.passable, fieldOfView, false);\n\t\t\t\t\tif (ignoreChars != null && (full == null || full.size() > 2*ignoreChars.size())){\n\t\t\t\t\t\t//check if first cell of shorter path is valid. If it is, use new shorter path. Otherwise do nothing and wait.\n\t\t\t\t\t\tpath = ignoreChars;\n\t\t\t\t\t\tif (!cellIsPathable(ignoreChars.getFirst())) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpath = full;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (path != null) {\n\t\t\t\tstep = path.removeFirst();\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (step != -1) {\n\t\t\tmove( step );\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprotected boolean getFurther( int target ) {\n\t\tif (rooted || target == pos) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tint step = Dungeon.flee( this, target, Dungeon.level.passable, fieldOfView, true );\n\t\tif (step != -1) {\n\t\t\tmove( step );\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void updateSpriteState() {\n\t\tsuper.updateSpriteState();\n\t\tif (Dungeon.hero.buff(TimekeepersHourglass.timeFreeze.class) != null\n\t\t\t\t|| Dungeon.hero.buff(Swiftthistle.TimeBubble.class) != null)\n\t\t\tsprite.add( CharSprite.State.PARALYSED );\n\t}\n\t\n\tpublic float attackDelay() {\n\t\tfloat delay = 1f;\n\t\tif ( buff(Adrenaline.class) != null) delay /= 1.5f;\n\t\treturn delay;\n\t}\n\t\n\tprotected boolean doAttack( Char enemy ) {\n\t\t\n\t\tif (sprite != null && (sprite.visible || enemy.sprite.visible)) {\n\t\t\tsprite.attack( enemy.pos );\n\t\t\treturn false;\n\t\t\t\n\t\t} else {\n\t\t\tattack( enemy );\n\t\t\tInvisibility.dispel(this);\n\t\t\tspend( attackDelay() );\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void onAttackComplete() {\n\t\tattack( enemy );\n\t\tInvisibility.dispel(this);\n\t\tspend( attackDelay() );\n\t\tsuper.onAttackComplete();\n\t}\n\t\n\t@Override\n\tpublic int defenseSkill( Char enemy ) {\n\t\tif ( !surprisedBy(enemy)\n\t\t\t\t&& paralysed == 0\n\t\t\t\t&& !(alignment == Alignment.ALLY && enemy == Dungeon.hero)) {\n\t\t\treturn this.defenseSkill;\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic int defenseProc( Char enemy, int damage ) {\n\t\t\n\t\tif (enemy instanceof Hero\n\t\t\t\t&& ((Hero) enemy).belongings.attackingWeapon() instanceof MissileWeapon){\n\t\t\tStatistics.thrownAttacks++;\n\t\t\tBadges.validateHuntressUnlock();\n\t\t}\n\t\t\n\t\tif (surprisedBy(enemy)) {\n\t\t\tStatistics.sneakAttacks++;\n\t\t\tBadges.validateRogueUnlock();\n\t\t\t//TODO this is somewhat messy, it would be nicer to not have to manually handle delays here\n\t\t\t// playing the strong hit sound might work best as another property of weapon?\n\t\t\tif (Dungeon.hero.belongings.attackingWeapon() instanceof SpiritBow.SpiritArrow\n\t\t\t\t|| Dungeon.hero.belongings.attackingWeapon() instanceof Dart){\n\t\t\t\tSample.INSTANCE.playDelayed(Assets.Sounds.HIT_STRONG, 0.125f);\n\t\t\t} else {\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t\t}\n\t\t\tif (enemy.buff(Preparation.class) != null) {\n\t\t\t\tWound.hit(this);\n\t\t\t} else {\n\t\t\t\tSurprise.hit(this);\n\t\t\t}\n\t\t}\n\n\t\t//if attacked by something else than current target, and that thing is closer, switch targets\n\t\tif (this.enemy == null\n\t\t\t\t|| (enemy != this.enemy && (Dungeon.level.distance(pos, enemy.pos) < Dungeon.level.distance(pos, this.enemy.pos)))) {\n\t\t\taggro(enemy);\n\t\t\ttarget = enemy.pos;\n\t\t}\n\n\t\tif (buff(SoulMark.class) != null) {\n\t\t\tint restoration = Math.min(damage, HP+shielding());\n\t\t\t\n\t\t\t//physical damage that doesn't come from the hero is less effective\n\t\t\tif (enemy != Dungeon.hero){\n\t\t\t\trestoration = Math.round(restoration * 0.4f*Dungeon.hero.pointsInTalent(Talent.SOUL_SIPHON)/3f);\n\t\t\t}\n\t\t\tif (restoration > 0) {\n\t\t\t\tBuff.affect(Dungeon.hero, Hunger.class).affectHunger(restoration*Dungeon.hero.pointsInTalent(Talent.SOUL_EATER)/3f);\n\t\t\t\tDungeon.hero.HP = (int) Math.ceil(Math.min(Dungeon.hero.HT, Dungeon.hero.HP + (restoration * 0.4f)));\n\t\t\t\tDungeon.hero.sprite.emitter().burst(Speck.factory(Speck.HEALING), 1);\n\t\t\t}\n\t\t}\n\n\t\tif (buff(BookOfTransfusion.VampiricMark.class) != null) {\n\t\t\tBookOfTransfusion.VampiricMark.proc(enemy, Math.min(damage, HP+shielding()));\n\t\t}\n\n\t\treturn super.defenseProc(enemy, damage);\n\t}\n\n\t@Override\n\tpublic float speed() {\n\t\treturn super.speed() * AscensionChallenge.enemySpeedModifier(this);\n\t}\n\n\tpublic final boolean surprisedBy( Char enemy ){\n\t\treturn surprisedBy( enemy, true);\n\t}\n\n\tpublic boolean surprisedBy( Char enemy, boolean attacking ){\n\t\treturn enemy == Dungeon.hero\n\t\t\t\t&& (enemy.invisible > 0 || !enemySeen || (fieldOfView != null && fieldOfView.length == Dungeon.level.length() && !fieldOfView[enemy.pos]))\n\t\t\t\t&& (!attacking || enemy.canSurpriseAttack());\n\t}\n\n\tpublic void aggro( Char ch ) {\n\t\tenemy = ch;\n\t\tif (state != PASSIVE){\n\t\t\tstate = HUNTING;\n\t\t}\n\t}\n\n\tpublic void clearEnemy(){\n\t\tenemy = null;\n\t\tenemySeen = false;\n\t\tif (state == HUNTING) state = WANDERING;\n\t}\n\t\n\tpublic boolean isTargeting( Char ch){\n\t\treturn enemy == ch;\n\t}\n\n\t@Override\n\tpublic void damage( int dmg, Object src ) {\n\n\t\tif (state == SLEEPING) {\n\t\t\tstate = WANDERING;\n\t\t}\n\t\tif (state != HUNTING && !(src instanceof Corruption)) {\n\t\t\talerted = true;\n\t\t}\n\t\t\n\t\tsuper.damage( dmg, src );\n\t}\n\t\n\t\n\t@Override\n\tpublic void destroy() {\n\t\t\n\t\tsuper.destroy();\n\t\t\n\t\tDungeon.level.mobs.remove( this );\n\n\t\tif (Dungeon.hero.buff(MindVision.class) != null){\n\t\t\tDungeon.observe();\n\t\t\tGameScene.updateFog(pos, 2);\n\t\t}\n\n\t\tif (Dungeon.hero.isAlive()) {\n\t\t\t\n\t\t\tif (alignment == Alignment.ENEMY) {\n\t\t\t\tStatistics.enemiesSlain++;\n\t\t\t\tBadges.validateMonstersSlain();\n\t\t\t\tStatistics.qualifiedForNoKilling = false;\n\n\t\t\t\tAscensionChallenge.processEnemyKill(this);\n\t\t\t\t\n\t\t\t\tint exp = Dungeon.hero.lvl <= maxLvl ? EXP : 0;\n\n\t\t\t\t//during ascent, under-levelled enemies grant 10 xp each until level 30\n\t\t\t\t// after this enemy kills which reduce the amulet curse still grant 10 effective xp\n\t\t\t\t// for the purposes of on-exp effects, see AscensionChallenge.processEnemyKill\n\t\t\t\tif (Dungeon.hero.buff(AscensionChallenge.class) != null &&\n\t\t\t\t\t\texp == 0 && maxLvl > 0 && EXP > 0 && Dungeon.hero.lvl < Hero.MAX_LEVEL){\n\t\t\t\t\texp = Math.round(10 * spawningWeight());\n\t\t\t\t}\n\n\t\t\t\tif (exp > 0) {\n\t\t\t\t\tDungeon.hero.sprite.showStatus(CharSprite.POSITIVE, Messages.get(this, \"exp\", exp));\n\t\t\t\t}\n\t\t\t\tDungeon.hero.earnExp(exp, getClass());\n\n\t\t\t\tif (Dungeon.hero.subClass == HeroSubClass.MONK){\n\t\t\t\t\tBuff.affect(Dungeon.hero, MonkEnergy.class).gainEnergy(this);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void die( Object cause ) {\n\n\t\tif (cause == Chasm.class){\n\t\t\t//50% chance to round up, 50% to round down\n\t\t\tif (EXP % 2 == 1) EXP += Random.Int(2);\n\t\t\tEXP /= 2;\n\t\t}\n\n\t\tif (alignment == Alignment.ENEMY){\n\t\t\trollToDropLoot();\n\n\t\t\tif (cause == Dungeon.hero || cause instanceof Weapon || cause instanceof Weapon.Enchantment){\n\t\t\t\tif (Dungeon.hero.hasTalent(Talent.LETHAL_MOMENTUM)\n\t\t\t\t\t\t&& Random.Float() < 0.34f + 0.33f* Dungeon.hero.pointsInTalent(Talent.LETHAL_MOMENTUM)){\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.LethalMomentumTracker.class, 0f);\n\t\t\t\t}\n\t\t\t\tif (Dungeon.hero.heroClass != HeroClass.DUELIST\n\t\t\t\t\t\t&& Dungeon.hero.hasTalent(Talent.LETHAL_HASTE)\n\t\t\t\t\t\t&& Dungeon.hero.buff(Talent.LethalHasteCooldown.class) == null){\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.LethalHasteCooldown.class, 100f);\n\t\t\t\t\tBuff.affect(Dungeon.hero, Haste.class, 1.67f + Dungeon.hero.pointsInTalent(Talent.LETHAL_HASTE));\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tif (Dungeon.level.map[pos] != Terrain.PIT && hero.hasTalent(Talent.ENERGY_REMAINS)) {\n\t\t\tint chance = Random.Int(6);\n\t\t\tint point = Dungeon.hero.pointsInTalent(Talent.ENERGY_REMAINS);\n\t\t\tswitch (chance) {\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0:\n\t\t\t\t\tif (point >= 1) {\n\t\t\t\t\t\tBuff.affect(hero, WandRechargeArea.class).setup(pos);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tif (point >= 2) {\n\t\t\t\t\t\tBuff.affect(hero, ArtifactRechargeArea.class).setup(pos);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tif (point >= 3) {\n\t\t\t\t\t\tBuff.affect(hero, BarrierRechargeArea.class).setup(pos);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (cause == hero) {\n\t\t\tif (Dungeon.hero.hasTalent(Talent.LETHAL_RAGE)){\n\t\t\t\tBerserk berserk = Buff.affect(hero, Berserk.class);\n\t\t\t\tberserk.add(0.067f*Dungeon.hero.pointsInTalent(Talent.LETHAL_RAGE));\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.BULLET_COLLECT)) {\n\t\t\t\tBulletItem bullet = new BulletItem();\n\t\t\t\tbullet.quantity(hero.pointsInTalent(Talent.BULLET_COLLECT));\n\t\t\t\tDungeon.level.drop(bullet, pos).sprite.drop();\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.SOUL_BULLET)) {\n\t\t\t\tBuff.affect(hero, InfiniteBullet.class, hero.pointsInTalent(Talent.SOUL_BULLET));\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.hero.isAlive() && !Dungeon.level.heroFOV[pos]) {\n\t\t\tGLog.i( Messages.get(this, \"died\") );\n\t\t}\n\n\t\tboolean soulMarked = buff(SoulMark.class) != null;\n\n\t\tsuper.die( cause );\n\n\t\tif (!(this instanceof Wraith)\n\t\t\t\t&& soulMarked\n\t\t\t\t&& Random.Float() < (0.4f*Dungeon.hero.pointsInTalent(Talent.NECROMANCERS_MINIONS)/3f)){\n\t\t\tWraith w = Wraith.spawnAt(pos, false);\n\t\t\tif (w != null) {\n\t\t\t\tBuff.affect(w, Corruption.class);\n\t\t\t\tif (Dungeon.level.heroFOV[pos]) {\n\t\t\t\t\tCellEmitter.get(pos).burst(ShadowParticle.CURSE, 6);\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.CURSED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (this instanceof Wraith && Dungeon.isChallenged(Challenges.CURSED_DUNGEON) && Random.Int(5) < 1) {\n\t\t\tWraith w = Wraith.spawnAt(pos, false);\n\t\t\tif (w != null) {\n\t\t\t\tBuff.affect(w, Corruption.class);\n\t\t\t\tif (Dungeon.level.heroFOV[pos]) {\n\t\t\t\t\tCellEmitter.get(pos).burst(ShadowParticle.CURSE, 6);\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.CURSED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic float lootChance(){\n\t\tfloat lootChance = this.lootChance;\n\n\t\tfloat dropBonus = RingOfWealth.dropChanceMultiplier( Dungeon.hero );\n\n\t\tTalent.BountyHunterTracker bhTracker = Dungeon.hero.buff(Talent.BountyHunterTracker.class);\n\t\tif (bhTracker != null){\n\t\t\tPreparation prep = Dungeon.hero.buff(Preparation.class);\n\t\t\tif (prep != null){\n\t\t\t\t// 2/4/8/16% per prep level, multiplied by talent points\n\t\t\t\tfloat bhBonus = 0.02f * (float)Math.pow(2, prep.attackLevel()-1);\n\t\t\t\tbhBonus *= Dungeon.hero.pointsInTalent(Talent.BOUNTY_HUNTER);\n\t\t\t\tdropBonus += bhBonus;\n\t\t\t}\n\t\t}\n\n\t\treturn lootChance * dropBonus;\n\t}\n\t\n\tpublic void rollToDropLoot(){\n\t\tif (Dungeon.hero.lvl > maxLvl + 2) return;\n\n\t\tMasterThievesArmband.StolenTracker stolen = buff(MasterThievesArmband.StolenTracker.class);\n\t\tif (stolen == null || !stolen.itemWasStolen()) {\n\t\t\tif (Random.Float() < lootChance()) {\n\t\t\t\tItem loot = createLoot();\n\t\t\t\tif (loot != null) {\n\t\t\t\t\tDungeon.level.drop(loot, pos).sprite.drop();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t//ring of wealth logic\n\t\tif (Ring.getBuffedBonus(Dungeon.hero, RingOfWealth.Wealth.class) > 0) {\n\t\t\tint rolls = 1;\n\t\t\tif (properties.contains(Property.BOSS)) rolls = 15;\n\t\t\telse if (properties.contains(Property.MINIBOSS)) rolls = 5;\n\t\t\tArrayList<Item> bonus = RingOfWealth.tryForBonusDrop(Dungeon.hero, rolls);\n\t\t\tif (bonus != null && !bonus.isEmpty()) {\n\t\t\t\tfor (Item b : bonus) Dungeon.level.drop(b, pos).sprite.drop();\n\t\t\t\tRingOfWealth.showFlareForBonusDrop(sprite);\n\t\t\t}\n\t\t}\n\t\t\n\t\t//lucky enchant logic\n\t\tif (buff(Lucky.LuckProc.class) != null){\n\t\t\tDungeon.level.drop(buff(Lucky.LuckProc.class).genLoot(), pos).sprite.drop();\n\t\t\tLucky.showFlare(sprite);\n\t\t}\n\n\t\t//soul eater talent\n\t\tif (buff(SoulMark.class) != null &&\n\t\t\t\tRandom.Int(10) < Dungeon.hero.pointsInTalent(Talent.SOUL_EATER)){\n\t\t\tTalent.onFoodEaten(Dungeon.hero, 0, null);\n\t\t}\n\n\t}\n\t\n\tprotected Object loot = null;\n\tprotected float lootChance = 0;\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic Item createLoot() {\n\t\tItem item;\n\t\tif (loot instanceof Generator.Category) {\n\n\t\t\titem = Generator.randomUsingDefaults( (Generator.Category)loot );\n\n\t\t} else if (loot instanceof Class<?>) {\n\n\t\t\titem = Generator.random( (Class<? extends Item>)loot );\n\n\t\t} else {\n\n\t\t\titem = (Item)loot;\n\n\t\t}\n\t\treturn item;\n\t}\n\n\t//how many mobs this one should count as when determining spawning totals\n\tpublic float spawningWeight(){\n\t\treturn 1;\n\t}\n\t\n\tpublic boolean reset() {\n\t\treturn false;\n\t}\n\t\n\tpublic void beckon( int cell ) {\n\t\t\n\t\tnotice();\n\t\t\n\t\tif (state != HUNTING && state != FLEEING) {\n\t\t\tstate = WANDERING;\n\t\t}\n\t\ttarget = cell;\n\t}\n\t\n\tpublic String description() {\n\t\treturn Messages.get(this, \"desc\");\n\t}\n\n\tpublic String info(){\n\t\tString desc = description();\n\n\t\tfor (Buff b : buffs(ChampionEnemy.class)){\n\t\t\tdesc += \"\\n\\n_\" + Messages.titleCase(b.name()) + \"_\\n\" + b.desc();\n\t\t}\n\n\t\treturn desc;\n\t}\n\t\n\tpublic void notice() {\n\t\tsprite.showAlert();\n\t}\n\t\n\tpublic void yell( String str ) {\n\t\tGLog.newLine();\n\t\tGLog.n( \"%s: \\\"%s\\\" \", Messages.titleCase(name()), str );\n\t}\n\n\tpublic interface AiState {\n\t\tboolean act( boolean enemyInFOV, boolean justAlerted );\n\t}\n\n\tprotected class Sleeping implements AiState {\n\n\t\tpublic static final String TAG\t= \"SLEEPING\";\n\n\t\t@Override\n\t\tpublic boolean act( boolean enemyInFOV, boolean justAlerted ) {\n\n\t\t\t//debuffs cause mobs to wake as well\n\t\t\tfor (Buff b : buffs()){\n\t\t\t\tif (b.type == Buff.buffType.NEGATIVE){\n\t\t\t\t\tawaken(enemyInFOV);\n\t\t\t\t\tif (state == SLEEPING){\n\t\t\t\t\t\tspend(TICK); //wait if we can't wake up for some reason\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (enemyInFOV) {\n\n\t\t\t\tfloat enemyStealth = enemy.stealth();\n\n\t\t\t\tif (enemy instanceof Hero && ((Hero) enemy).hasTalent(Talent.SILENT_STEPS)){\n\t\t\t\t\tif (Dungeon.level.distance(pos, enemy.pos) >= 4 - ((Hero) enemy).pointsInTalent(Talent.SILENT_STEPS)) {\n\t\t\t\t\t\tenemyStealth = Float.POSITIVE_INFINITY;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (Random.Float( distance( enemy ) + enemyStealth ) < 1) {\n\t\t\t\t\tawaken(enemyInFOV);\n\t\t\t\t\tif (state == SLEEPING){\n\t\t\t\t\t\tspend(TICK); //wait if we can't wake up for some reason\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tenemySeen = false;\n\t\t\tspend( TICK );\n\n\t\t\treturn true;\n\t\t}\n\n\t\tprotected void awaken( boolean enemyInFOV ){\n\t\t\tif (enemyInFOV) {\n\t\t\t\tenemySeen = true;\n\t\t\t\tnotice();\n\t\t\t\tstate = HUNTING;\n\t\t\t\ttarget = enemy.pos;\n\t\t\t} else {\n\t\t\t\tnotice();\n\t\t\t\tstate = WANDERING;\n\t\t\t\ttarget = Dungeon.level.randomDestination( Mob.this );\n\t\t\t}\n\n\t\t\tif (alignment == Alignment.ENEMY && Dungeon.isChallenged(Challenges.SWARM_INTELLIGENCE)) {\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\t\t\tif (mob.paralysed <= 0\n\t\t\t\t\t\t\t&& Dungeon.level.distance(pos, mob.pos) <= 8\n\t\t\t\t\t\t\t&& mob.state != mob.HUNTING) {\n\t\t\t\t\t\tmob.beckon(target);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tspend(TIME_TO_WAKE_UP);\n\t\t}\n\t}\n\n\tprotected class Wandering implements AiState {\n\n\t\tpublic static final String TAG\t= \"WANDERING\";\n\n\t\t@Override\n\t\tpublic boolean act( boolean enemyInFOV, boolean justAlerted ) {\n\t\t\tif (enemyInFOV && (justAlerted || Random.Float( distance( enemy ) / 2f + enemy.stealth() ) < 1)) {\n\n\t\t\t\treturn noticeEnemy();\n\n\t\t\t} else {\n\n\t\t\t\treturn continueWandering();\n\n\t\t\t}\n\t\t}\n\t\t\n\t\tprotected boolean noticeEnemy(){\n\t\t\tenemySeen = true;\n\t\t\t\n\t\t\tnotice();\n\t\t\talerted = true;\n\t\t\tstate = HUNTING;\n\t\t\ttarget = enemy.pos;\n\t\t\t\n\t\t\tif (alignment == Alignment.ENEMY && Dungeon.isChallenged( Challenges.SWARM_INTELLIGENCE )) {\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\t\t\tif (mob.paralysed <= 0\n\t\t\t\t\t\t\t&& Dungeon.level.distance(pos, mob.pos) <= 8\n\t\t\t\t\t\t\t&& mob.state != mob.HUNTING) {\n\t\t\t\t\t\tmob.beckon( target );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\tprotected boolean continueWandering(){\n\t\t\tenemySeen = false;\n\t\t\t\n\t\t\tint oldPos = pos;\n\t\t\tif (target != -1 && getCloser( target )) {\n\t\t\t\tspend( 1 / speed() );\n\t\t\t\treturn moveSprite( oldPos, pos );\n\t\t\t} else {\n\t\t\t\ttarget = randomDestination();\n\t\t\t\tspend( TICK );\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t}\n\n\t\tprotected int randomDestination(){\n\t\t\treturn Dungeon.level.randomDestination( Mob.this );\n\t\t}\n\t\t\n\t}\n\n\tprotected class Hunting implements AiState {\n\n\t\tpublic static final String TAG\t= \"HUNTING\";\n\n\t\t//prevents rare infinite loop cases\n\t\tprivate boolean recursing = false;\n\n\t\t@Override\n\t\tpublic boolean act( boolean enemyInFOV, boolean justAlerted ) {\n\t\t\tenemySeen = enemyInFOV;\n\t\t\tif (enemyInFOV && !isCharmedBy( enemy ) && canAttack( enemy )) {\n\n\t\t\t\ttarget = enemy.pos;\n\t\t\t\treturn doAttack( enemy );\n\n\t\t\t} else {\n\n\t\t\t\tif (enemyInFOV) {\n\t\t\t\t\ttarget = enemy.pos;\n\t\t\t\t} else if (enemy == null) {\n\t\t\t\t\tsprite.showLost();\n\t\t\t\t\tstate = WANDERING;\n\t\t\t\t\ttarget = Dungeon.level.randomDestination( Mob.this );\n\t\t\t\t\tspend( TICK );\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tint oldPos = pos;\n\t\t\t\tif (target != -1 && getCloser( target )) {\n\t\t\t\t\t\n\t\t\t\t\tspend( 1 / speed() );\n\t\t\t\t\treturn moveSprite( oldPos, pos );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t//if moving towards an enemy isn't possible, try to switch targets to another enemy that is closer\n\t\t\t\t\t//unless we have already done that and still can't move toward them, then move on.\n\t\t\t\t\tif (!recursing) {\n\t\t\t\t\t\tChar oldEnemy = enemy;\n\t\t\t\t\t\tenemy = null;\n\t\t\t\t\t\tenemy = chooseEnemy();\n\t\t\t\t\t\tif (enemy != null && enemy != oldEnemy) {\n\t\t\t\t\t\t\trecursing = true;\n\t\t\t\t\t\t\tboolean result = act(enemyInFOV, justAlerted);\n\t\t\t\t\t\t\trecursing = false;\n\t\t\t\t\t\t\treturn result;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tspend( TICK );\n\t\t\t\t\tif (!enemyInFOV) {\n\t\t\t\t\t\tsprite.showLost();\n\t\t\t\t\t\tstate = WANDERING;\n\t\t\t\t\t\ttarget = Dungeon.level.randomDestination( Mob.this );\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected class Fleeing implements AiState {\n\n\t\tpublic static final String TAG\t= \"FLEEING\";\n\n\t\t@Override\n\t\tpublic boolean act( boolean enemyInFOV, boolean justAlerted ) {\n\t\t\tenemySeen = enemyInFOV;\n\t\t\t//triggers escape logic when 0-dist rolls a 6 or greater.\n\t\t\tif (enemy == null || !enemyInFOV && 1 + Random.Int(Dungeon.level.distance(pos, target)) >= 6){\n\t\t\t\tescaped();\n\t\t\t\tif (state != FLEEING){\n\t\t\t\t\tspend( TICK );\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\n\t\t\t//if enemy isn't in FOV, keep running from their previous position.\n\t\t\t} else if (enemyInFOV) {\n\t\t\t\ttarget = enemy.pos;\n\t\t\t}\n\n\t\t\tint oldPos = pos;\n\t\t\tif (target != -1 && getFurther( target )) {\n\n\t\t\t\tspend( 1 / speed() );\n\t\t\t\treturn moveSprite( oldPos, pos );\n\n\t\t\t} else {\n\n\t\t\t\tspend( TICK );\n\t\t\t\tnowhereToRun();\n\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tprotected void escaped(){\n\t\t\t//does nothing by default, some enemies have special logic for this\n\t\t}\n\n\t\t//enemies will turn and fight if they have nowhere to run and aren't affect by terror\n\t\tprotected void nowhereToRun() {\n\t\t\tif (buff( Terror.class ) == null\n\t\t\t\t\t&& buffs( AllyBuff.class ).isEmpty()\n\t\t\t\t\t&& buff( Dread.class ) == null) {\n\t\t\t\tif (enemySeen) {\n\t\t\t\t\tsprite.showStatus(CharSprite.NEGATIVE, Messages.get(Mob.class, \"rage\"));\n\t\t\t\t\tstate = HUNTING;\n\t\t\t\t} else {\n\t\t\t\t\tstate = WANDERING;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected class Passive implements AiState {\n\n\t\tpublic static final String TAG\t= \"PASSIVE\";\n\n\t\t@Override\n\t\tpublic boolean act( boolean enemyInFOV, boolean justAlerted ) {\n\t\t\tenemySeen = enemyInFOV;\n\t\t\tspend( TICK );\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\t\n\tprivate static ArrayList<Mob> heldAllies = new ArrayList<>();\n\n\tpublic static void holdAllies( Level level ){\n\t\tholdAllies(level, Dungeon.hero.pos);\n\t}\n\n\tpublic static void holdAllies( Level level, int holdFromPos ){\n\t\theldAllies.clear();\n\t\tfor (Mob mob : level.mobs.toArray( new Mob[0] )) {\n\t\t\t//preserve directable allies no matter where they are\n\t\t\tif (mob instanceof DirectableAlly) {\n\t\t\t\t((DirectableAlly) mob).clearDefensingPos();\n\t\t\t\tlevel.mobs.remove( mob );\n\t\t\t\theldAllies.add(mob);\n\t\t\t\t\n\t\t\t//preserve intelligent allies if they are near the hero\n\t\t\t} else if (mob.alignment == Alignment.ALLY\n\t\t\t\t\t&& mob.intelligentAlly\n\t\t\t\t\t&& Dungeon.level.distance(holdFromPos, mob.pos) <= 5){\n\t\t\t\tlevel.mobs.remove( mob );\n\t\t\t\theldAllies.add(mob);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void restoreAllies( Level level, int pos ){\n\t\trestoreAllies(level, pos, -1);\n\t}\n\n\tpublic static void restoreAllies( Level level, int pos, int gravitatePos ){\n\t\tif (!heldAllies.isEmpty()){\n\t\t\t\n\t\t\tArrayList<Integer> candidatePositions = new ArrayList<>();\n\t\t\tfor (int i : PathFinder.NEIGHBOURS8) {\n\t\t\t\tif (!Dungeon.level.solid[i+pos] && level.findMob(i+pos) == null){\n\t\t\t\t\tcandidatePositions.add(i+pos);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//gravitate pos sets a preferred location for allies to be closer to\n\t\t\tif (gravitatePos == -1) {\n\t\t\t\tCollections.shuffle(candidatePositions);\n\t\t\t} else {\n\t\t\t\tCollections.sort(candidatePositions, new Comparator<Integer>() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic int compare(Integer t1, Integer t2) {\n\t\t\t\t\t\treturn Dungeon.level.distance(gravitatePos, t1) -\n\t\t\t\t\t\t\t\tDungeon.level.distance(gravitatePos, t2);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\t\n\t\t\tfor (Mob ally : heldAllies) {\n\t\t\t\tlevel.mobs.add(ally);\n\t\t\t\tally.state = ally.WANDERING;\n\t\t\t\t\n\t\t\t\tif (!candidatePositions.isEmpty()){\n\t\t\t\t\tally.pos = candidatePositions.remove(0);\n\t\t\t\t} else {\n\t\t\t\t\tally.pos = pos;\n\t\t\t\t}\n\t\t\t\tif (ally.sprite != null) ally.sprite.place(ally.pos);\n\n\t\t\t\tif (ally.fieldOfView == null || ally.fieldOfView.length != level.length()){\n\t\t\t\t\tally.fieldOfView = new boolean[level.length()];\n\t\t\t\t}\n\t\t\t\tDungeon.level.updateFieldOfView( ally, ally.fieldOfView );\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\theldAllies.clear();\n\t}\n\t\n\tpublic static void clearHeldAllies(){\n\t\theldAllies.clear();\n\t}\n}" }, { "identifier": "Speck", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/effects/Speck.java", "snippet": "public class Speck extends Image {\n\n\tpublic static final int HEALING = 0;\n\tpublic static final int STAR = 1;\n\tpublic static final int LIGHT = 2;\n\tpublic static final int QUESTION = 3;\n\tpublic static final int UP = 4;\n\tpublic static final int SCREAM = 5;\n\tpublic static final int BONE = 6;\n\tpublic static final int WOOL = 7;\n\tpublic static final int ROCK = 8;\n\tpublic static final int NOTE = 9;\n\tpublic static final int CHANGE = 10;\n\tpublic static final int HEART = 11;\n\tpublic static final int BUBBLE = 12;\n\tpublic static final int STEAM = 13;\n\tpublic static final int COIN = 14;\n\t\n\tpublic static final int DISCOVER = 101;\n\tpublic static final int EVOKE = 102;\n\tpublic static final int MASK = 103;\n\tpublic static final int CROWN = 104;\n\tpublic static final int RATTLE = 105;\n\tpublic static final int JET = 106;\n\tpublic static final int TOXIC = 107;\n\tpublic static final int CORROSION = 108;\n\tpublic static final int PARALYSIS = 109;\n\tpublic static final int DUST = 110;\n\tpublic static final int STENCH = 111;\n\tpublic static final int FORGE = 112;\n\tpublic static final int CONFUSION = 113;\n\tpublic static final int RED_LIGHT = 114;\n\tpublic static final int CALM = 115;\n\tpublic static final int SMOKE = 116;\n\tpublic static final int STORM = 117;\n\tpublic static final int INFERNO = 118;\n\tpublic static final int BLIZZARD = 119;\n\t\n\tprivate static final int SIZE = 7;\n\t\n\tprivate int type;\n\tprivate float lifespan;\n\tprivate float left;\n\t\n\tprivate static TextureFilm film;\n\t\n\tprivate static SparseArray<Emitter.Factory> factories = new SparseArray<>();\n\t\n\tpublic Speck() {\n\t\tsuper();\n\t\t\n\t\ttexture( Assets.Effects.SPECKS );\n\t\tif (film == null) {\n\t\t\tfilm = new TextureFilm( texture, SIZE, SIZE );\n\t\t}\n\t\t\n\t\torigin.set( SIZE / 2f );\n\t}\n\n\tpublic Speck image( int type ){\n\t\treset(0, 0, 0, type);\n\n\t\tleft = lifespan = Float.POSITIVE_INFINITY;\n\t\tthis.type = -1;\n\n\t\tresetColor();\n\t\tscale.set( 1 );\n\t\tspeed.set( 0 );\n\t\tacc.set( 0 );\n\t\tangle = 0;\n\t\tangularSpeed = 0;\n\n\t\treturn this;\n\t}\n\t\n\tpublic void reset( int index, float x, float y, int type ) {\n\t\trevive();\n\t\t\n\t\tthis.type = type;\n\t\tswitch (type) {\n\t\tcase DISCOVER:\n\t\tcase RED_LIGHT:\n\t\t\tframe( film.get( LIGHT ) );\n\t\t\tbreak;\n\t\tcase EVOKE:\n\t\tcase MASK:\n\t\tcase CROWN:\n\t\tcase FORGE:\n\t\t\tframe( film.get( STAR ) );\n\t\t\tbreak;\n\t\tcase RATTLE:\n\t\t\tframe( film.get( BONE ) );\n\t\t\tbreak;\n\t\tcase JET:\n\t\tcase TOXIC:\n\t\tcase CORROSION:\n\t\tcase PARALYSIS:\n\t\tcase STENCH:\n\t\tcase CONFUSION:\n\t\tcase STORM:\n\t\tcase DUST:\n\t\tcase SMOKE:\n\t\tcase BLIZZARD:\n\t\tcase INFERNO:\n\t\t\tframe( film.get( STEAM ) );\n\t\t\tbreak;\n\t\tcase CALM:\n\t\t\tframe( film.get( SCREAM ) );\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tframe( film.get( type ) );\n\t\t}\n\t\t\n\t\tthis.x = x - origin.x;\n\t\tthis.y = y - origin.y;\n\t\t\n\t\tresetColor();\n\t\tscale.set( 1 );\n\t\tspeed.set( 0 );\n\t\tacc.set( 0 );\n\t\tangle = 0;\n\t\tangularSpeed = 0;\n\t\t\n\t\tswitch (type) {\n\t\t\t\n\t\tcase HEALING:\n\t\t\tspeed.set( 0, -20 );\n\t\t\tlifespan = 1f;\n\t\t\tbreak;\n\t\t\t\n\t\tcase STAR:\n\t\t\tspeed.polar( Random.Float( 2 * 3.1415926f ), Random.Float( 128 ) );\n\t\t\tacc.set( 0, 128 );\n\t\t\tangle = Random.Float( 360 );\n\t\t\tangularSpeed = Random.Float( -360, +360 );\n\t\t\tlifespan = 1f;\n\t\t\tbreak;\n\t\t\n\t\tcase FORGE:\n\t\t\tspeed.polar( Random.Float( -3.1415926f ), Random.Float( 64 ) );\n\t\t\tacc.set( 0, 128 );\n\t\t\tangle = Random.Float( 360 );\n\t\t\tangularSpeed = Random.Float( -360, +360 );\n\t\t\tlifespan = 0.51f;\n\t\t\tbreak;\n\t\t\t\n\t\tcase EVOKE:\n\t\t\tspeed.polar( Random.Float( -3.1415926f ), 50 );\n\t\t\tacc.set( 0, 50 );\n\t\t\tangle = Random.Float( 360 );\n\t\t\tangularSpeed = Random.Float( -180, +180 );\n\t\t\tlifespan = 1f;\n\t\t\tbreak;\n\n\t\tcase MASK:\n\t\t\tspeed.polar( index * 3.1415926f / 5, 50 );\n\t\t\tacc.set( -speed.x, -speed.y );\n\t\t\tangle = index * 36;\n\t\t\tangularSpeed = 360;\n\t\t\tlifespan = 1f;\n\t\t\tbreak;\n\n\t\tcase CROWN:\n\t\t\tacc.set( index % 2 == 0 ? Random.Float( -512, -256 ) : Random.Float( +256, +512 ), 0 );\n\t\t\tangularSpeed = acc.x < 0 ? -180 : +180;\n\t\t\t//acc.set( -speed.x, 0 );\n\t\t\tlifespan = 0.5f;\n\t\t\tbreak;\n\n\t\tcase RED_LIGHT:\n\t\t\ttint(0xFFCC0000);\n\t\tcase LIGHT:\n\t\t\tangle = Random.Float( 360 );\n\t\t\tangularSpeed = 90;\n\t\t\tlifespan = 1f;\n\t\t\tbreak;\n\t\t\t\n\t\tcase DISCOVER:\n\t\t\tangle = Random.Float( 360 );\n\t\t\tangularSpeed = 90;\n\t\t\tlifespan = 0.5f;\n\t\t\tam = 0;\n\t\t\tbreak;\n\t\t\t\n\t\tcase QUESTION:\n\t\t\tlifespan = 0.8f;\n\t\t\tbreak;\n\t\t\t\n\t\tcase UP:\n\t\t\tspeed.set( 0, -20 );\n\t\t\tlifespan = 1f;\n\t\t\tbreak;\n\t\t\t\n\t\tcase CALM:\n\t\t\tcolor(0, 1, 1);\n\t\tcase SCREAM:\n\t\t\tlifespan = 0.9f;\n\t\t\tbreak;\n\t\t\t\n\t\tcase BONE:\n\t\t\tlifespan = 0.2f;\n\t\t\tspeed.polar( Random.Float( 2 * 3.1415926f ), 24 / lifespan );\n\t\t\tacc.set( 0, 128 );\n\t\t\tangle = Random.Float( 360 );\n\t\t\tangularSpeed = 360;\n\t\t\tbreak;\n\t\t\t\n\t\tcase RATTLE:\n\t\t\tlifespan = 0.5f;\n\t\t\tspeed.set( 0, -100 );\n\t\t\tacc.set( 0, -2 * speed.y / lifespan );\n\t\t\tangle = Random.Float( 360 );\n\t\t\tangularSpeed = 360;\n\t\t\tbreak;\n\t\t\t\n\t\tcase WOOL:\n\t\t\tlifespan = 0.5f;\n\t\t\tspeed.set( 0, -50 );\n\t\t\tangle = Random.Float( 360 );\n\t\t\tangularSpeed = Random.Float( -360, +360 );\n\t\t\tbreak;\n\t\t\t\n\t\tcase ROCK:\n\t\t\tangle = Random.Float( 360 );\n\t\t\tangularSpeed = Random.Float( -360, +360 );\n\t\t\tscale.set( Random.Float( 1, 2 ) );\n\t\t\tspeed.set( 0, 64 );\n\t\t\tlifespan = 0.2f;\n\t\t\tthis.y -= speed.y * lifespan;\n\t\t\tbreak;\n\t\t\t\n\t\tcase NOTE:\n\t\t\tangularSpeed = Random.Float( -30, +30 );\n\t\t\tspeed.polar( (angularSpeed - 90) * PointF.G2R, 30 );\n\t\t\tlifespan = 1f;\n\t\t\tbreak;\n\t\t\t\n\t\tcase CHANGE:\n\t\t\tangle = Random.Float( 360 );\n\t\t\tspeed.polar( (angle - 90) * PointF.G2R, Random.Float( 4, 12 ) );\n\t\t\tlifespan = 1.5f;\n\t\t\tbreak;\n\t\t\t\n\t\tcase HEART:\n\t\t\tspeed.set( Random.IntRange( -10, +10 ), -40 );\n\t\t\tangularSpeed = Random.Float( -45, +45 );\n\t\t\tlifespan = 1f;\n\t\t\tbreak;\n\t\t\t\n\t\tcase BUBBLE:\n\t\t\tspeed.set( 0, -15 );\n\t\t\tscale.set( Random.Float( 0.8f, 1 ) );\n\t\t\tlifespan = Random.Float( 0.8f, 1.5f );\n\t\t\tbreak;\n\t\t\t\n\t\tcase STEAM:\n\t\t\tspeed.y = -Random.Float( 10, 15 );\n\t\t\tangularSpeed = Random.Float( +180 );\n\t\t\tangle = Random.Float( 360 );\n\t\t\tlifespan = 1f;\n\t\t\tbreak;\n\t\t\t\n\t\tcase JET:\n\t\t\tspeed.y = +32;\n\t\t\tacc.y = -64;\n\t\t\tangularSpeed = Random.Float( 180, 360 );\n\t\t\tangle = Random.Float( 360 );\n\t\t\tlifespan = 0.5f;\n\t\t\tbreak;\n\t\t\t\n\t\tcase TOXIC:\n\t\t\thardlight( 0x50FF60 );\n\t\t\tangularSpeed = 30;\n\t\t\tangle = Random.Float( 360 );\n\t\t\tlifespan = Random.Float( 1f, 3f );\n\t\t\tbreak;\n\n\t\tcase CORROSION:\n\t\t\thardlight( 0xAAAAAA );\n\t\t\tangularSpeed = 30;\n\t\t\tangle = Random.Float( 360 );\n\t\t\tlifespan = Random.Float( 1f, 3f );\n\t\t\tbreak;\n\t\t\t\n\t\tcase PARALYSIS:\n\t\t\thardlight( 0xFFFF66 );\n\t\t\tangularSpeed = -30;\n\t\t\tangle = Random.Float( 360 );\n\t\t\tlifespan = Random.Float( 1f, 3f );\n\t\t\tbreak;\n\n\t\tcase STENCH:\n\t\t\thardlight( 0x003300 );\n\t\t\tangularSpeed = -30;\n\t\t\tangle = Random.Float( 360 );\n\t\t\tlifespan = Random.Float( 1f, 3f );\n\t\t\tbreak;\n\n\t\tcase CONFUSION:\n\t\t\thardlight( Random.Int( 0x1000000 ) | 0x000080 );\n\t\t\tangularSpeed = Random.Float( -20, +20 );\n\t\t\tangle = Random.Float( 360 );\n\t\t\tlifespan = Random.Float( 1f, 3f );\n\t\t\tbreak;\n\t\t\t\n\t\tcase STORM:\n\t\t\thardlight( 0x8AD8D8 );\n\t\t\tangularSpeed = Random.Float( -20, +20 );\n\t\t\tangle = Random.Float( 360 );\n\t\t\tlifespan = Random.Float( 1f, 3f );\n\t\t\tbreak;\n\t\t\t\n\t\tcase INFERNO:\n\t\t\thardlight( 0xEE7722 );\n\t\t\tangularSpeed = Random.Float( 200, 300 ) * (Random.Int(2) == 0 ? -1 : 1);\n\t\t\tangle = Random.Float( 360 );\n\t\t\tlifespan = Random.Float( 1f, 3f );\n\t\t\tbreak;\n\t\t\t\n\t\tcase BLIZZARD:\n\t\t\thardlight( 0xFFFFFF );\n\t\t\tangularSpeed = Random.Float( 200, 300 ) * (Random.Int(2) == 0 ? -1 : 1);\n\t\t\tangle = Random.Float( 360 );\n\t\t\tlifespan = Random.Float( 1f, 3f );\n\t\t\tbreak;\n\t\t\t\n\t\tcase SMOKE:\n\t\t\thardlight( 0x000000 );\n\t\t\tangularSpeed = 30;\n\t\t\tangle = Random.Float( 360 );\n\t\t\tlifespan = Random.Float( 1f, 1.5f );\n\t\t\tbreak;\n\n\t\tcase DUST:\n\t\t\thardlight( 0xFFFF66 );\n\t\t\tangle = Random.Float( 360 );\n\t\t\tspeed.polar( Random.Float( 2 * 3.1415926f ), Random.Float( 16, 48 ) );\n\t\t\tlifespan = 0.5f;\n\t\t\tbreak;\n\n\t\tcase COIN:\n\t\t\tspeed.polar( -PointF.PI * Random.Float( 0.3f, 0.7f ), Random.Float( 48, 96 ) );\n\t\t\tacc.y = 256;\n\t\t\tlifespan = -speed.y / acc.y * 2;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tleft = lifespan;\n\t}\n\t\n\t@Override\n\tpublic void update() {\n\t\tsuper.update();\n\t\t\n\t\tleft -= Game.elapsed;\n\t\tif (left <= 0) {\n\t\t\t\n\t\t\tkill();\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tfloat p = 1 - left / lifespan;\t// 0 -> 1\n\t\t\t\n\t\t\tswitch (type) {\n\t\t\t\t\n\t\t\tcase STAR:\n\t\t\tcase FORGE:\n\t\t\t\tscale.set( 1 - p );\n\t\t\t\tam = p < 0.2f ? p * 5f : (1 - p) * 1.25f;\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase MASK:\n\t\t\tcase CROWN:\n\t\t\t\tam = 1 - p * p;\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase EVOKE:\n\t\t\t\t\n\t\t\tcase HEALING:\n\t\t\t\tam = p < 0.5f ? 1 : 2 - p * 2;\n\t\t\t\tbreak;\n\n\t\t\tcase RED_LIGHT:\n\t\t\tcase LIGHT:\n\t\t\t\tam = scale.set( p < 0.2f ? p * 5f : (1 - p) * 1.25f ).x;\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase DISCOVER:\n\t\t\t\tam = 1 - p;\n\t\t\t\tscale.set( (p < 0.5f ? p : 1 - p) * 2 );\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase QUESTION:\n\t\t\t\tscale.set( (float)(Math.sqrt( p < 0.5f ? p : 1 - p ) * 3) );\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase UP:\n\t\t\t\tscale.set( (float)(Math.sqrt( p < 0.5f ? p : 1 - p ) * 2) );\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase CALM:\n\t\t\tcase SCREAM:\n\t\t\t\tam = (float)Math.sqrt( (p < 0.5f ? p : 1 - p) * 2f );\n\t\t\t\tscale.set( p * 7 );\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase BONE:\n\t\t\tcase RATTLE:\n\t\t\t\tam = p < 0.9f ? 1 : (1 - p) * 10;\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase ROCK:\n\t\t\t\tam = p < 0.2f ? p * 5 : 1 ;\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase NOTE:\n\t\t\t\tam = 1 - p * p;\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase WOOL:\n\t\t\t\tscale.set( 1 - p );\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase CHANGE:\n\t\t\t\tam = (float)Math.sqrt( (p < 0.5f ? p : 1 - p) * 2);\n\t\t\t\tscale.y = (1 + p) * 0.5f;\n\t\t\t\tscale.x = scale.y * (float)Math.cos( left * 15 );\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase HEART:\n\t\t\t\tscale.set( 1 - p );\n\t\t\t\tam = 1 - p * p;\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase BUBBLE:\n\t\t\t\tam = p < 0.2f ? p * 5 : 1;\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase STEAM:\n\t\t\tcase TOXIC:\n\t\t\tcase PARALYSIS:\n\t\t\tcase CONFUSION:\n\t\t\tcase STORM:\n\t\t\tcase BLIZZARD:\n\t\t\tcase INFERNO:\n\t\t\tcase DUST:\n\t\t\t\tam = (float)Math.sqrt( (p < 0.5f ? p : 1 - p) * 0.5f );\n\t\t\t\tscale.set( 1 + p );\n\t\t\t\tbreak;\n\n\t\t\tcase CORROSION:\n\t\t\t\thardlight( ColorMath.interpolate( 0xAAAAAA, 0xFF8800 , p ));\n\t\t\tcase STENCH:\n\t\t\tcase SMOKE:\n\t\t\t\tam = (float)Math.sqrt( (p < 0.5f ? p : 1 - p) );\n\t\t\t\tscale.set( 1 + p );\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase JET:\n\t\t\t\tam = (p < 0.5f ? p : 1 - p) * 2;\n\t\t\t\tscale.set( p * 1.5f );\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase COIN:\n\t\t\t\tscale.x = (float)Math.cos( left * 5 );\n\t\t\t\trm = gm = bm = (Math.abs( scale.x ) + 1) * 0.5f;\n\t\t\t\tam = p < 0.9f ? 1 : (1 - p) * 10;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static Emitter.Factory factory( final int type ) {\n\t\treturn factory( type, false );\n\t}\n\n\tpublic static Emitter.Factory factory( final int type, final boolean lightMode ) {\n\n\t\tEmitter.Factory factory = factories.get( type );\n\n\t\tif (factory == null) {\n\t\t\tfactory = new Emitter.Factory() {\n\t\t\t\t@Override\n\t\t\t\tpublic void emit ( Emitter emitter, int index, float x, float y ) {\n\t\t\t\t\tSpeck p = (Speck)emitter.recycle( Speck.class );\n\t\t\t\t\tp.reset( index, x, y, type );\n\t\t\t\t}\n\t\t\t\t@Override\n\t\t\t\tpublic boolean lightMode() {\n\t\t\t\t\treturn lightMode;\n\t\t\t\t}\n\t\t\t};\n\t\t\tfactories.put( type, factory );\n\t\t}\n\n\t\treturn factory;\n\t}\n}" }, { "identifier": "Messages", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/messages/Messages.java", "snippet": "public class Messages {\n\n\tprivate static ArrayList<I18NBundle> bundles;\n\tprivate static Languages lang;\n\tprivate static Locale locale;\n\n\tpublic static final String NO_TEXT_FOUND = \"!!!NO TEXT FOUND!!!\";\n\n\tpublic static Languages lang(){\n\t\treturn lang;\n\t}\n\n\tpublic static Locale locale(){\n\t\treturn locale;\n\t}\n\n\t/**\n\t * Setup Methods\n\t */\n\n\tprivate static String[] prop_files = new String[]{\n\t\t\tAssets.Messages.ACTORS,\n\t\t\tAssets.Messages.ITEMS,\n\t\t\tAssets.Messages.JOURNAL,\n\t\t\tAssets.Messages.LEVELS,\n\t\t\tAssets.Messages.MISC,\n\t\t\tAssets.Messages.PLANTS,\n\t\t\tAssets.Messages.SCENES,\n\t\t\tAssets.Messages.UI,\n\t\t\tAssets.Messages.WINDOWS\n\t};\n\n\tstatic{\n\t\tsetup(SPDSettings.language());\n\t}\n\n\tpublic static void setup( Languages lang ){\n\t\t//seeing as missing keys are part of our process, this is faster than throwing an exception\n\t\tI18NBundle.setExceptionOnMissingKey(false);\n\n\t\t//store language and locale info for various string logic\n\t\tMessages.lang = lang;\n\t\tif (lang == Languages.ENGLISH){\n\t\t\tlocale = Locale.ENGLISH;\n\t\t} else {\n\t\t\tlocale = new Locale(lang.code());\n\t\t}\n\n\t\t//strictly match the language code when fetching bundles however\n\t\tbundles = new ArrayList<>();\n\t\tLocale bundleLocal = new Locale(lang.code());\n\t\tfor (String file : prop_files) {\n\t\t\tbundles.add(I18NBundle.createBundle(Gdx.files.internal(file), bundleLocal));\n\t\t}\n\t}\n\n\n\n\t/**\n\t * Resource grabbing methods\n\t */\n\n\tpublic static String get(String key, Object...args){\n\t\treturn get(null, key, args);\n\t}\n\n\tpublic static String get(Object o, String k, Object...args){\n\t\treturn get(o.getClass(), k, args);\n\t}\n\n\tpublic static String get(Class c, String k, Object...args){\n\t\tString key;\n\t\tif (c != null){\n\t\t\tkey = c.getName().replace(\"com.shatteredpixel.shatteredpixeldungeon.\", \"\");\n\t\t\tkey += \".\" + k;\n\t\t} else\n\t\t\tkey = k;\n\n\t\tString value = getFromBundle(key.toLowerCase(Locale.ENGLISH));\n\t\tif (value != null){\n\t\t\tif (args.length > 0) return format(value, args);\n\t\t\telse return value;\n\t\t} else {\n\t\t\t//this is so child classes can inherit properties from their parents.\n\t\t\t//in cases where text is commonly grabbed as a utility from classes that aren't mean to be instantiated\n\t\t\t//(e.g. flavourbuff.dispTurns()) using .class directly is probably smarter to prevent unnecessary recursive calls.\n\t\t\tif (c != null && c.getSuperclass() != null){\n\t\t\t\treturn get(c.getSuperclass(), k, args);\n\t\t\t} else {\n\t\t\t\treturn NO_TEXT_FOUND;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static String getFromBundle(String key){\n\t\tString result;\n\t\tfor (I18NBundle b : bundles){\n\t\t\tresult = b.get(key);\n\t\t\t//if it isn't the return string for no key found, return it\n\t\t\tif (result.length() != key.length()+6 || !result.contains(key)){\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\n\n\t/**\n\t * String Utility Methods\n\t */\n\n\tpublic static String format( String format, Object...args ) {\n\t\ttry {\n\t\t\treturn String.format(Locale.ENGLISH, format, args);\n\t\t} catch (IllegalFormatException e) {\n\t\t\tShatteredPixelDungeon.reportException( new Exception(\"formatting error for the string: \" + format, e) );\n\t\t\treturn format;\n\t\t}\n\t}\n\n\tprivate static HashMap<String, DecimalFormat> formatters = new HashMap<>();\n\n\tpublic static String decimalFormat( String format, double number ){\n\t\tif (!formatters.containsKey(format)){\n\t\t\tformatters.put(format, new DecimalFormat(format, DecimalFormatSymbols.getInstance(Locale.ENGLISH)));\n\t\t}\n\t\treturn formatters.get(format).format(number);\n\t}\n\n\tpublic static String capitalize( String str ){\n\t\tif (str.length() == 0) return str;\n\t\telse return str.substring( 0, 1 ).toUpperCase(locale) + str.substring( 1 );\n\t}\n\n\t//Words which should not be capitalized in title case, mostly prepositions which appear ingame\n\t//This list is not comprehensive!\n\tprivate static final HashSet<String> noCaps = new HashSet<>(\n\t\t\tArrays.asList(\"a\", \"an\", \"and\", \"of\", \"by\", \"to\", \"the\", \"x\", \"for\")\n\t);\n\n\tpublic static String titleCase( String str ){\n\t\t//English capitalizes every word except for a few exceptions\n\t\tif (lang == Languages.ENGLISH){\n\t\t\tString result = \"\";\n\t\t\t//split by any unicode space character\n\t\t\tfor (String word : str.split(\"(?<=\\\\p{Zs})\")){\n\t\t\t\tif (noCaps.contains(word.trim().toLowerCase(Locale.ENGLISH).replaceAll(\":|[0-9]\", \"\"))){\n\t\t\t\t\tresult += word;\n\t\t\t\t} else {\n\t\t\t\t\tresult += capitalize(word);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//first character is always capitalized.\n\t\t\treturn capitalize(result);\n\t\t}\n\n\t\t//Otherwise, use sentence case\n\t\treturn capitalize(str);\n\t}\n\n\tpublic static String upperCase( String str ){\n\t\treturn str.toUpperCase(locale);\n\t}\n\n\tpublic static String lowerCase( String str ){\n\t\treturn str.toLowerCase(locale);\n\t}\n}" }, { "identifier": "ItemSpriteSheet", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/sprites/ItemSpriteSheet.java", "snippet": "public class ItemSpriteSheet {\n\n\tprivate static final int WIDTH = 16;\n\tpublic static final int SIZE = 16;\n\n\tpublic static TextureFilm film = new TextureFilm( Assets.Sprites.ITEMS, SIZE, SIZE );\n\n\tprivate static int xy(int x, int y){\n\t\tx -= 1; y -= 1;\n\t\treturn x + WIDTH*y;\n\t}\n\n\tprivate static void assignItemRect( int item, int width, int height ){\n\t\tint x = (item % WIDTH) * SIZE;\n\t\tint y = (item / WIDTH) * SIZE;\n\t\tfilm.add( item, x, y, x+width, y+height);\n\t}\n\n\tprivate static final int PLACEHOLDERS = xy(1, 1); //16 slots\n\t//SOMETHING is the default item sprite at position 0. May show up ingame if there are bugs.\n\tpublic static final int SOMETHING = PLACEHOLDERS+0;\n\tpublic static final int WEAPON_HOLDER = PLACEHOLDERS+1;\n\tpublic static final int ARMOR_HOLDER = PLACEHOLDERS+2;\n\tpublic static final int MISSILE_HOLDER = PLACEHOLDERS+3;\n\tpublic static final int WAND_HOLDER = PLACEHOLDERS+4;\n\tpublic static final int RING_HOLDER = PLACEHOLDERS+5;\n\tpublic static final int ARTIFACT_HOLDER = PLACEHOLDERS+6;\n\tpublic static final int FOOD_HOLDER = PLACEHOLDERS+7;\n\tpublic static final int BOMB_HOLDER = PLACEHOLDERS+8;\n\tpublic static final int POTION_HOLDER = PLACEHOLDERS+9;\n\tpublic static final int SCROLL_HOLDER = PLACEHOLDERS+11;\n\tpublic static final int SEED_HOLDER = PLACEHOLDERS+10;\n\tpublic static final int STONE_HOLDER = PLACEHOLDERS+12;\n\tpublic static final int CATA_HOLDER = PLACEHOLDERS+13;\n\tpublic static final int ELIXIR_HOLDER = PLACEHOLDERS+14;\n\tpublic static final int SPELL_HOLDER = PLACEHOLDERS+15;\n\tstatic{\n\t\tassignItemRect(SOMETHING, 8, 13);\n\t\tassignItemRect(WEAPON_HOLDER, 14, 14);\n\t\tassignItemRect(ARMOR_HOLDER, 14, 12);\n\t\tassignItemRect(MISSILE_HOLDER, 15, 15);\n\t\tassignItemRect(WAND_HOLDER, 14, 14);\n\t\tassignItemRect(RING_HOLDER, 8, 10);\n\t\tassignItemRect(ARTIFACT_HOLDER, 15, 15);\n\t\tassignItemRect(FOOD_HOLDER, 15, 11);\n\t\tassignItemRect(BOMB_HOLDER, 10, 13);\n\t\tassignItemRect(POTION_HOLDER, 12, 14);\n\t\tassignItemRect(SEED_HOLDER, 10, 10);\n\t\tassignItemRect(SCROLL_HOLDER, 15, 14);\n\t\tassignItemRect(STONE_HOLDER, 14, 12);\n\t\tassignItemRect(CATA_HOLDER, 6, 15);\n\t\tassignItemRect(ELIXIR_HOLDER, 12, 14);\n\t\tassignItemRect(SPELL_HOLDER, 8, 16);\n\t}\n\n\tprivate static final int UNCOLLECTIBLE = xy(1, 2); //16 slots\n\tpublic static final int GOLD = UNCOLLECTIBLE+0;\n\tpublic static final int ENERGY = UNCOLLECTIBLE+1;\n\n\tpublic static final int DEWDROP = UNCOLLECTIBLE+3;\n\tpublic static final int PETAL = UNCOLLECTIBLE+4;\n\tpublic static final int SANDBAG = UNCOLLECTIBLE+5;\n\tpublic static final int SPIRIT_ARROW = UNCOLLECTIBLE+6;\n\t\n\tpublic static final int TENGU_BOMB = UNCOLLECTIBLE+8;\n\tpublic static final int TENGU_SHOCKER = UNCOLLECTIBLE+9;\n\tstatic{\n\t\tassignItemRect(GOLD, 15, 13);\n\t\tassignItemRect(ENERGY, 16, 16);\n\n\t\tassignItemRect(DEWDROP, 10, 10);\n\t\tassignItemRect(PETAL, 8, 8);\n\t\tassignItemRect(SANDBAG, 10, 10);\n\t\tassignItemRect(SPIRIT_ARROW,11, 11);\n\t\t\n\t\tassignItemRect(TENGU_BOMB, 10, 10);\n\t\tassignItemRect(TENGU_SHOCKER, 10, 10);\n\t}\n\n\tprivate static final int CONTAINERS = xy(1, 3); //16 slots\n\tpublic static final int BONES = CONTAINERS+0;\n\tpublic static final int REMAINS = CONTAINERS+1;\n\tpublic static final int TOMB = CONTAINERS+2;\n\tpublic static final int GRAVE = CONTAINERS+3;\n\tpublic static final int CHEST = CONTAINERS+4;\n\tpublic static final int LOCKED_CHEST = CONTAINERS+5;\n\tpublic static final int CRYSTAL_CHEST = CONTAINERS+6;\n\tpublic static final int EBONY_CHEST = CONTAINERS+7;\n\tstatic{\n\t\tassignItemRect(BONES, 14, 11);\n\t\tassignItemRect(REMAINS, 14, 11);\n\t\tassignItemRect(TOMB, 14, 15);\n\t\tassignItemRect(GRAVE, 14, 15);\n\t\tassignItemRect(CHEST, 16, 14);\n\t\tassignItemRect(LOCKED_CHEST, 16, 14);\n\t\tassignItemRect(CRYSTAL_CHEST, 16, 14);\n\t\tassignItemRect(EBONY_CHEST, 16, 14);\n\t}\n\n\tprivate static final int MISC_CONSUMABLE = xy(1, 4); //16 slots\n\tpublic static final int ANKH = MISC_CONSUMABLE +0;\n\tpublic static final int STYLUS = MISC_CONSUMABLE +1;\n\tpublic static final int SEAL = MISC_CONSUMABLE +2;\n\tpublic static final int TORCH = MISC_CONSUMABLE +3;\n\tpublic static final int BEACON = MISC_CONSUMABLE +4;\n\tpublic static final int HONEYPOT = MISC_CONSUMABLE +5;\n\tpublic static final int SHATTPOT = MISC_CONSUMABLE +6;\n\tpublic static final int IRON_KEY = MISC_CONSUMABLE +7;\n\tpublic static final int GOLDEN_KEY = MISC_CONSUMABLE +8;\n\tpublic static final int CRYSTAL_KEY = MISC_CONSUMABLE +9;\n\tpublic static final int SKELETON_KEY = MISC_CONSUMABLE +10;\n\tpublic static final int MASK = MISC_CONSUMABLE +11;\n\tpublic static final int CROWN = MISC_CONSUMABLE +12;\n\tpublic static final int AMULET = MISC_CONSUMABLE +13;\n\tpublic static final int MASTERY = MISC_CONSUMABLE +14;\n\tpublic static final int KIT = MISC_CONSUMABLE +15;\n\tstatic{\n\t\tassignItemRect(ANKH, 10, 16);\n\t\tassignItemRect(STYLUS, 12, 13);\n\t\t\n\t\tassignItemRect(SEAL, 9, 15);\n\t\tassignItemRect(TORCH, 12, 15);\n\t\tassignItemRect(BEACON, 16, 15);\n\t\t\n\t\tassignItemRect(HONEYPOT, 14, 12);\n\t\tassignItemRect(SHATTPOT, 14, 12);\n\t\tassignItemRect(IRON_KEY, 8, 14);\n\t\tassignItemRect(GOLDEN_KEY, 8, 14);\n\t\tassignItemRect(CRYSTAL_KEY, 8, 14);\n\t\tassignItemRect(SKELETON_KEY, 8, 14);\n\t\tassignItemRect(MASK, 11, 9);\n\t\tassignItemRect(CROWN, 13, 7);\n\t\tassignItemRect(AMULET, 16, 16);\n\t\tassignItemRect(MASTERY, 13, 16);\n\t\tassignItemRect(KIT, 16, 15);\n\t}\n\t\n\tprivate static final int BOMBS = xy(1, 5); //16 slots\n\tpublic static final int BOMB = BOMBS+0;\n\tpublic static final int DBL_BOMB = BOMBS+1;\n\tpublic static final int FIRE_BOMB = BOMBS+2;\n\tpublic static final int FROST_BOMB = BOMBS+3;\n\tpublic static final int REGROWTH_BOMB = BOMBS+4;\n\tpublic static final int FLASHBANG = BOMBS+5;\n\tpublic static final int SHOCK_BOMB = BOMBS+6;\n\tpublic static final int HOLY_BOMB = BOMBS+7;\n\tpublic static final int WOOLY_BOMB = BOMBS+8;\n\tpublic static final int NOISEMAKER = BOMBS+9;\n\tpublic static final int ARCANE_BOMB = BOMBS+10;\n\tpublic static final int SHRAPNEL_BOMB = BOMBS+11;\n\t\n\tstatic{\n\t\tassignItemRect(BOMB, 10, 13);\n\t\tassignItemRect(DBL_BOMB, 14, 13);\n\t\tassignItemRect(FIRE_BOMB, 13, 12);\n\t\tassignItemRect(FROST_BOMB, 13, 12);\n\t\tassignItemRect(REGROWTH_BOMB, 13, 12);\n\t\tassignItemRect(FLASHBANG, 13, 12);\n\t\tassignItemRect(SHOCK_BOMB, 10, 13);\n\t\tassignItemRect(HOLY_BOMB, 10, 13);\n\t\tassignItemRect(WOOLY_BOMB, 10, 13);\n\t\tassignItemRect(NOISEMAKER, 10, 13);\n\t\tassignItemRect(ARCANE_BOMB, 10, 13);\n\t\tassignItemRect(SHRAPNEL_BOMB, 10, 13);\n\t}\n\n\t\n\t //16 free slots\n\n\tprivate static final int WEP_TIER1 = xy(1, 7); //8 slots\n\tpublic static final int WORN_SHORTSWORD = WEP_TIER1+0;\n\tpublic static final int CUDGEL = WEP_TIER1+1;\n\tpublic static final int GLOVES = WEP_TIER1+2;\n\tpublic static final int RAPIER = WEP_TIER1+3;\n\tpublic static final int DAGGER = WEP_TIER1+4;\n\tpublic static final int MAGES_STAFF = WEP_TIER1+5;\n\tstatic{\n\t\tassignItemRect(WORN_SHORTSWORD, 13, 13);\n\t\tassignItemRect(GLOVES, 12, 16);\n\t\tassignItemRect(RAPIER, 13, 14);\n\t\tassignItemRect(DAGGER, 12, 13);\n\t\tassignItemRect(MAGES_STAFF, 15, 16);\n\t}\n\n\tprivate static final int WEP_TIER2 = xy(9, 7); //8 slots\n\tpublic static final int SHORTSWORD = WEP_TIER2+0;\n\tpublic static final int HAND_AXE = WEP_TIER2+1;\n\tpublic static final int SPEAR = WEP_TIER2+2;\n\tpublic static final int QUARTERSTAFF = WEP_TIER2+3;\n\tpublic static final int DIRK = WEP_TIER2+4;\n\tpublic static final int SICKLE = WEP_TIER2+5;\n\tstatic{\n\t\tassignItemRect(SHORTSWORD, 13, 13);\n\t\tassignItemRect(HAND_AXE, 12, 14);\n\t\tassignItemRect(SPEAR, 16, 16);\n\t\tassignItemRect(QUARTERSTAFF, 16, 16);\n\t\tassignItemRect(DIRK, 13, 14);\n\t\tassignItemRect(SICKLE, 15, 15);\n\t}\n\n\tprivate static final int WEP_TIER3 = xy(1, 8); //8 slots\n\tpublic static final int SWORD = WEP_TIER3+0;\n\tpublic static final int MACE = WEP_TIER3+1;\n\tpublic static final int SCIMITAR = WEP_TIER3+2;\n\tpublic static final int ROUND_SHIELD = WEP_TIER3+3;\n\tpublic static final int SAI = WEP_TIER3+4;\n\tpublic static final int WHIP = WEP_TIER3+5;\n\tstatic{\n\t\tassignItemRect(SWORD, 14, 14);\n\t\tassignItemRect(MACE, 15, 15);\n\t\tassignItemRect(SCIMITAR, 13, 16);\n\t\tassignItemRect(ROUND_SHIELD, 16, 16);\n\t\tassignItemRect(SAI, 16, 16);\n\t\tassignItemRect(WHIP, 14, 14);\n\t}\n\n\tprivate static final int WEP_TIER4 = xy(9, 8); //8 slots\n\tpublic static final int LONGSWORD = WEP_TIER4+0;\n\tpublic static final int BATTLE_AXE = WEP_TIER4+1;\n\tpublic static final int FLAIL = WEP_TIER4+2;\n\tpublic static final int RUNIC_BLADE = WEP_TIER4+3;\n\tpublic static final int ASSASSINS_BLADE = WEP_TIER4+4;\n\tpublic static final int CROSSBOW = WEP_TIER4+5;\n\tpublic static final int KATANA = WEP_TIER4+6;\n\tstatic{\n\t\tassignItemRect(LONGSWORD, 15, 15);\n\t\tassignItemRect(BATTLE_AXE, 16, 16);\n\t\tassignItemRect(FLAIL, 14, 14);\n\t\tassignItemRect(RUNIC_BLADE, 14, 14);\n\t\tassignItemRect(ASSASSINS_BLADE, 14, 15);\n\t\tassignItemRect(CROSSBOW, 15, 15);\n\t\tassignItemRect(KATANA, 15, 16);\n\t}\n\n\tprivate static final int WEP_TIER5 = xy(1, 9); //8 slots\n\tpublic static final int GREATSWORD = WEP_TIER5+0;\n\tpublic static final int WAR_HAMMER = WEP_TIER5+1;\n\tpublic static final int GLAIVE = WEP_TIER5+2;\n\tpublic static final int GREATAXE = WEP_TIER5+3;\n\tpublic static final int GREATSHIELD = WEP_TIER5+4;\n\tpublic static final int GAUNTLETS = WEP_TIER5+5;\n\tpublic static final int WAR_SCYTHE = WEP_TIER5+6;\n\tstatic{\n\t\tassignItemRect(GREATSWORD, 16, 16);\n\t\tassignItemRect(WAR_HAMMER, 16, 16);\n\t\tassignItemRect(GLAIVE, 16, 16);\n\t\tassignItemRect(GREATAXE, 12, 16);\n\t\tassignItemRect(GREATSHIELD, 12, 16);\n\t\tassignItemRect(GAUNTLETS, 13, 15);\n\t\tassignItemRect(WAR_SCYTHE, 14, 15);\n\t}\n\n\t //8 free slots\n\n\tprivate static final int MISSILE_WEP = xy(1, 10); //16 slots. 3 per tier + bow\n\tpublic static final int SPIRIT_BOW = MISSILE_WEP+0;\n\t\n\tpublic static final int THROWING_SPIKE = MISSILE_WEP+1;\n\tpublic static final int THROWING_KNIFE = MISSILE_WEP+2;\n\tpublic static final int THROWING_STONE = MISSILE_WEP+3;\n\t\n\tpublic static final int FISHING_SPEAR = MISSILE_WEP+4;\n\tpublic static final int SHURIKEN = MISSILE_WEP+5;\n\tpublic static final int THROWING_CLUB = MISSILE_WEP+6;\n\t\n\tpublic static final int THROWING_SPEAR = MISSILE_WEP+7;\n\tpublic static final int BOLAS = MISSILE_WEP+8;\n\tpublic static final int KUNAI = MISSILE_WEP+9;\n\t\n\tpublic static final int JAVELIN = MISSILE_WEP+10;\n\tpublic static final int TOMAHAWK = MISSILE_WEP+11;\n\tpublic static final int BOOMERANG = MISSILE_WEP+12;\n\t\n\tpublic static final int TRIDENT = MISSILE_WEP+13;\n\tpublic static final int THROWING_HAMMER = MISSILE_WEP+14;\n\tpublic static final int FORCE_CUBE = MISSILE_WEP+15;\n\t\n\tstatic{\n\t\tassignItemRect(SPIRIT_BOW, 16, 16);\n\t\t\n\t\tassignItemRect(THROWING_SPIKE, 11, 10);\n\t\tassignItemRect(THROWING_KNIFE, 12, 13);\n\t\tassignItemRect(THROWING_STONE, 12, 10);\n\t\t\n\t\tassignItemRect(FISHING_SPEAR, 11, 11);\n\t\tassignItemRect(SHURIKEN, 12, 12);\n\t\tassignItemRect(THROWING_CLUB, 12, 12);\n\t\t\n\t\tassignItemRect(THROWING_SPEAR, 13, 13);\n\t\tassignItemRect(BOLAS, 15, 14);\n\t\tassignItemRect(KUNAI, 15, 15);\n\t\t\n\t\tassignItemRect(JAVELIN, 16, 16);\n\t\tassignItemRect(TOMAHAWK, 13, 13);\n\t\tassignItemRect(BOOMERANG, 14, 14);\n\t\t\n\t\tassignItemRect(TRIDENT, 16, 16);\n\t\tassignItemRect(THROWING_HAMMER, 12, 12);\n\t\tassignItemRect(FORCE_CUBE, 11, 12);\n\t}\n\t\n\tpublic static final int DARTS = xy(1, 11); //16 slots\n\tpublic static final int DART = DARTS+0;\n\tpublic static final int ROT_DART = DARTS+1;\n\tpublic static final int INCENDIARY_DART = DARTS+2;\n\tpublic static final int ADRENALINE_DART = DARTS+3;\n\tpublic static final int HEALING_DART = DARTS+4;\n\tpublic static final int CHILLING_DART = DARTS+5;\n\tpublic static final int SHOCKING_DART = DARTS+6;\n\tpublic static final int POISON_DART = DARTS+7;\n\tpublic static final int CLEANSING_DART = DARTS+8;\n\tpublic static final int PARALYTIC_DART = DARTS+9;\n\tpublic static final int HOLY_DART = DARTS+10;\n\tpublic static final int DISPLACING_DART = DARTS+11;\n\tpublic static final int BLINDING_DART = DARTS+12;\n\tstatic {\n\t\tfor (int i = DARTS; i < DARTS+16; i++)\n\t\t\tassignItemRect(i, 15, 15);\n\t}\n\t\n\tprivate static final int ARMOR = xy(1, 12); //16 slots\n\tpublic static final int ARMOR_CLOTH = ARMOR+0;\n\tpublic static final int ARMOR_LEATHER = ARMOR+1;\n\tpublic static final int ARMOR_MAIL = ARMOR+2;\n\tpublic static final int ARMOR_SCALE = ARMOR+3;\n\tpublic static final int ARMOR_PLATE = ARMOR+4;\n\tpublic static final int ARMOR_WARRIOR = ARMOR+5;\n\tpublic static final int ARMOR_MAGE = ARMOR+6;\n\tpublic static final int ARMOR_ROGUE = ARMOR+7;\n\tpublic static final int ARMOR_HUNTRESS = ARMOR+8;\n\tpublic static final int ARMOR_DUELIST = ARMOR+9;\n\tstatic{\n\t\tassignItemRect(ARMOR_CLOTH, 15, 12);\n\t\tassignItemRect(ARMOR_LEATHER, 14, 13);\n\t\tassignItemRect(ARMOR_MAIL, 14, 12);\n\t\tassignItemRect(ARMOR_SCALE, 14, 11);\n\t\tassignItemRect(ARMOR_PLATE, 12, 12);\n\t\tassignItemRect(ARMOR_WARRIOR, 12, 12);\n\t\tassignItemRect(ARMOR_MAGE, 15, 15);\n\t\tassignItemRect(ARMOR_ROGUE, 14, 12);\n\t\tassignItemRect(ARMOR_HUNTRESS, 13, 15);\n\t\tassignItemRect(ARMOR_DUELIST, 12, 13);\n\t}\n\n\t //16 free slots\n\n\tprivate static final int WANDS = xy(1, 14); //16 slots\n\tpublic static final int WAND_MAGIC_MISSILE = WANDS+0;\n\tpublic static final int WAND_FIREBOLT = WANDS+1;\n\tpublic static final int WAND_FROST = WANDS+2;\n\tpublic static final int WAND_LIGHTNING = WANDS+3;\n\tpublic static final int WAND_DISINTEGRATION = WANDS+4;\n\tpublic static final int WAND_PRISMATIC_LIGHT= WANDS+5;\n\tpublic static final int WAND_CORROSION = WANDS+6;\n\tpublic static final int WAND_LIVING_EARTH = WANDS+7;\n\tpublic static final int WAND_BLAST_WAVE = WANDS+8;\n\tpublic static final int WAND_CORRUPTION = WANDS+9;\n\tpublic static final int WAND_WARDING = WANDS+10;\n\tpublic static final int WAND_REGROWTH = WANDS+11;\n\tpublic static final int WAND_TRANSFUSION = WANDS+12;\n\tstatic {\n\t\tfor (int i = WANDS; i < WANDS+16; i++)\n\t\t\tassignItemRect(i, 14, 14);\n\t}\n\n\tprivate static final int RINGS = xy(1, 15); //16 slots\n\tpublic static final int RING_GARNET = RINGS+0;\n\tpublic static final int RING_RUBY = RINGS+1;\n\tpublic static final int RING_TOPAZ = RINGS+2;\n\tpublic static final int RING_EMERALD = RINGS+3;\n\tpublic static final int RING_ONYX = RINGS+4;\n\tpublic static final int RING_OPAL = RINGS+5;\n\tpublic static final int RING_TOURMALINE = RINGS+6;\n\tpublic static final int RING_SAPPHIRE = RINGS+7;\n\tpublic static final int RING_AMETHYST = RINGS+8;\n\tpublic static final int RING_QUARTZ = RINGS+9;\n\tpublic static final int RING_AGATE = RINGS+10;\n\tpublic static final int RING_DIAMOND = RINGS+11;\n\tstatic {\n\t\tfor (int i = RINGS; i < RINGS+16; i++)\n\t\t\tassignItemRect(i, 8, 10);\n\t}\n\n\tprivate static final int ARTIFACTS = xy(1, 16); //32 slots\n\tpublic static final int ARTIFACT_CLOAK = ARTIFACTS+0;\n\tpublic static final int ARTIFACT_ARMBAND = ARTIFACTS+1;\n\tpublic static final int ARTIFACT_CAPE = ARTIFACTS+2;\n\tpublic static final int ARTIFACT_TALISMAN = ARTIFACTS+3;\n\tpublic static final int ARTIFACT_HOURGLASS = ARTIFACTS+4;\n\tpublic static final int ARTIFACT_TOOLKIT = ARTIFACTS+5;\n\tpublic static final int ARTIFACT_SPELLBOOK = ARTIFACTS+6;\n\tpublic static final int ARTIFACT_BEACON = ARTIFACTS+7;\n\tpublic static final int ARTIFACT_CHAINS = ARTIFACTS+8;\n\tpublic static final int ARTIFACT_HORN1 = ARTIFACTS+9;\n\tpublic static final int ARTIFACT_HORN2 = ARTIFACTS+10;\n\tpublic static final int ARTIFACT_HORN3 = ARTIFACTS+11;\n\tpublic static final int ARTIFACT_HORN4 = ARTIFACTS+12;\n\tpublic static final int ARTIFACT_CHALICE1 = ARTIFACTS+13;\n\tpublic static final int ARTIFACT_CHALICE2 = ARTIFACTS+14;\n\tpublic static final int ARTIFACT_CHALICE3 = ARTIFACTS+15;\n\tpublic static final int ARTIFACT_SANDALS = ARTIFACTS+16;\n\tpublic static final int ARTIFACT_SHOES = ARTIFACTS+17;\n\tpublic static final int ARTIFACT_BOOTS = ARTIFACTS+18;\n\tpublic static final int ARTIFACT_GREAVES = ARTIFACTS+19;\n\tpublic static final int ARTIFACT_ROSE1 = ARTIFACTS+20;\n\tpublic static final int ARTIFACT_ROSE2 = ARTIFACTS+21;\n\tpublic static final int ARTIFACT_ROSE3 = ARTIFACTS+22;\n\tstatic{\n\t\tassignItemRect(ARTIFACT_CLOAK, 9, 15);\n\t\tassignItemRect(ARTIFACT_ARMBAND, 16, 13);\n\t\tassignItemRect(ARTIFACT_CAPE, 16, 14);\n\t\tassignItemRect(ARTIFACT_TALISMAN, 15, 13);\n\t\tassignItemRect(ARTIFACT_HOURGLASS, 13, 16);\n\t\tassignItemRect(ARTIFACT_TOOLKIT, 15, 13);\n\t\tassignItemRect(ARTIFACT_SPELLBOOK, 13, 16);\n\t\tassignItemRect(ARTIFACT_BEACON, 16, 16);\n\t\tassignItemRect(ARTIFACT_CHAINS, 16, 16);\n\t\tassignItemRect(ARTIFACT_HORN1, 15, 15);\n\t\tassignItemRect(ARTIFACT_HORN2, 15, 15);\n\t\tassignItemRect(ARTIFACT_HORN3, 15, 15);\n\t\tassignItemRect(ARTIFACT_HORN4, 15, 15);\n\t\tassignItemRect(ARTIFACT_CHALICE1, 12, 15);\n\t\tassignItemRect(ARTIFACT_CHALICE2, 12, 15);\n\t\tassignItemRect(ARTIFACT_CHALICE3, 12, 15);\n\t\tassignItemRect(ARTIFACT_SANDALS, 16, 6 );\n\t\tassignItemRect(ARTIFACT_SHOES, 16, 6 );\n\t\tassignItemRect(ARTIFACT_BOOTS, 16, 9 );\n\t\tassignItemRect(ARTIFACT_GREAVES, 16, 14);\n\t\tassignItemRect(ARTIFACT_ROSE1, 14, 14);\n\t\tassignItemRect(ARTIFACT_ROSE2, 14, 14);\n\t\tassignItemRect(ARTIFACT_ROSE3, 14, 14);\n\t}\n\n\t //16 free slots\n\n\tprivate static final int SCROLLS = xy(1, 19); //16 slots\n\tpublic static final int SCROLL_KAUNAN = SCROLLS+0;\n\tpublic static final int SCROLL_SOWILO = SCROLLS+1;\n\tpublic static final int SCROLL_LAGUZ = SCROLLS+2;\n\tpublic static final int SCROLL_YNGVI = SCROLLS+3;\n\tpublic static final int SCROLL_GYFU = SCROLLS+4;\n\tpublic static final int SCROLL_RAIDO = SCROLLS+5;\n\tpublic static final int SCROLL_ISAZ = SCROLLS+6;\n\tpublic static final int SCROLL_MANNAZ = SCROLLS+7;\n\tpublic static final int SCROLL_NAUDIZ = SCROLLS+8;\n\tpublic static final int SCROLL_BERKANAN = SCROLLS+9;\n\tpublic static final int SCROLL_ODAL = SCROLLS+10;\n\tpublic static final int SCROLL_TIWAZ = SCROLLS+11;\n\t\n\tpublic static final int SCROLL_CATALYST = SCROLLS+13;\n\tpublic static final int ARCANE_RESIN = SCROLLS+14;\n\tstatic {\n\t\tfor (int i = SCROLLS; i < SCROLLS+16; i++)\n\t\t\tassignItemRect(i, 15, 14);\n\t\tassignItemRect(SCROLL_CATALYST, 12, 11);\n\t\tassignItemRect(ARCANE_RESIN , 12, 11);\n\t}\n\t\n\tprivate static final int EXOTIC_SCROLLS = xy(1, 20); //16 slots\n\tpublic static final int EXOTIC_KAUNAN = EXOTIC_SCROLLS+0;\n\tpublic static final int EXOTIC_SOWILO = EXOTIC_SCROLLS+1;\n\tpublic static final int EXOTIC_LAGUZ = EXOTIC_SCROLLS+2;\n\tpublic static final int EXOTIC_YNGVI = EXOTIC_SCROLLS+3;\n\tpublic static final int EXOTIC_GYFU = EXOTIC_SCROLLS+4;\n\tpublic static final int EXOTIC_RAIDO = EXOTIC_SCROLLS+5;\n\tpublic static final int EXOTIC_ISAZ = EXOTIC_SCROLLS+6;\n\tpublic static final int EXOTIC_MANNAZ = EXOTIC_SCROLLS+7;\n\tpublic static final int EXOTIC_NAUDIZ = EXOTIC_SCROLLS+8;\n\tpublic static final int EXOTIC_BERKANAN = EXOTIC_SCROLLS+9;\n\tpublic static final int EXOTIC_ODAL = EXOTIC_SCROLLS+10;\n\tpublic static final int EXOTIC_TIWAZ = EXOTIC_SCROLLS+11;\n\tstatic {\n\t\tfor (int i = EXOTIC_SCROLLS; i < EXOTIC_SCROLLS+16; i++)\n\t\t\tassignItemRect(i, 15, 14);\n\t}\n\t\n\tprivate static final int STONES = xy(1, 21); //16 slots\n\tpublic static final int STONE_AGGRESSION = STONES+0;\n\tpublic static final int STONE_AUGMENTATION = STONES+1;\n\tpublic static final int STONE_FEAR = STONES+2;\n\tpublic static final int STONE_BLAST = STONES+3;\n\tpublic static final int STONE_BLINK = STONES+4;\n\tpublic static final int STONE_CLAIRVOYANCE = STONES+5;\n\tpublic static final int STONE_SLEEP = STONES+6;\n\tpublic static final int STONE_DISARM = STONES+7;\n\tpublic static final int STONE_ENCHANT = STONES+8;\n\tpublic static final int STONE_FLOCK = STONES+9;\n\tpublic static final int STONE_INTUITION = STONES+10;\n\tpublic static final int STONE_SHOCK = STONES+11;\n\tstatic {\n\t\tfor (int i = STONES; i < STONES+16; i++)\n\t\t\tassignItemRect(i, 14, 12);\n\t}\n\n\tprivate static final int POTIONS = xy(1, 22); //16 slots\n\tpublic static final int POTION_CRIMSON = POTIONS+0;\n\tpublic static final int POTION_AMBER = POTIONS+1;\n\tpublic static final int POTION_GOLDEN = POTIONS+2;\n\tpublic static final int POTION_JADE = POTIONS+3;\n\tpublic static final int POTION_TURQUOISE= POTIONS+4;\n\tpublic static final int POTION_AZURE = POTIONS+5;\n\tpublic static final int POTION_INDIGO = POTIONS+6;\n\tpublic static final int POTION_MAGENTA = POTIONS+7;\n\tpublic static final int POTION_BISTRE = POTIONS+8;\n\tpublic static final int POTION_CHARCOAL = POTIONS+9;\n\tpublic static final int POTION_SILVER = POTIONS+10;\n\tpublic static final int POTION_IVORY = POTIONS+11;\n\tpublic static final int POTION_CATALYST = POTIONS+13;\n\tpublic static final int LIQUID_METAL = POTIONS+14;\n\tstatic {\n\t\tfor (int i = POTIONS; i < POTIONS+16; i++)\n\t\t\tassignItemRect(i, 12, 14);\n\t\tassignItemRect(POTION_CATALYST, 6, 15);\n\t\tassignItemRect(LIQUID_METAL, 8, 15);\n\t}\n\t\n\tprivate static final int EXOTIC_POTIONS = xy(1, 23); //16 slots\n\tpublic static final int EXOTIC_CRIMSON = EXOTIC_POTIONS+0;\n\tpublic static final int EXOTIC_AMBER = EXOTIC_POTIONS+1;\n\tpublic static final int EXOTIC_GOLDEN = EXOTIC_POTIONS+2;\n\tpublic static final int EXOTIC_JADE = EXOTIC_POTIONS+3;\n\tpublic static final int EXOTIC_TURQUOISE= EXOTIC_POTIONS+4;\n\tpublic static final int EXOTIC_AZURE = EXOTIC_POTIONS+5;\n\tpublic static final int EXOTIC_INDIGO = EXOTIC_POTIONS+6;\n\tpublic static final int EXOTIC_MAGENTA = EXOTIC_POTIONS+7;\n\tpublic static final int EXOTIC_BISTRE = EXOTIC_POTIONS+8;\n\tpublic static final int EXOTIC_CHARCOAL = EXOTIC_POTIONS+9;\n\tpublic static final int EXOTIC_SILVER = EXOTIC_POTIONS+10;\n\tpublic static final int EXOTIC_IVORY = EXOTIC_POTIONS+11;\n\tstatic {\n\t\tfor (int i = EXOTIC_POTIONS; i < EXOTIC_POTIONS+16; i++)\n\t\t\tassignItemRect(i, 12, 13);\n\t}\n\n\tprivate static final int SEEDS = xy(1, 24); //16 slots\n\tpublic static final int SEED_ROTBERRY = SEEDS+0;\n\tpublic static final int SEED_FIREBLOOM = SEEDS+1;\n\tpublic static final int SEED_SWIFTTHISTLE = SEEDS+2;\n\tpublic static final int SEED_SUNGRASS = SEEDS+3;\n\tpublic static final int SEED_ICECAP = SEEDS+4;\n\tpublic static final int SEED_STORMVINE = SEEDS+5;\n\tpublic static final int SEED_SORROWMOSS = SEEDS+6;\n\tpublic static final int SEED_MAGEROYAL = SEEDS+7;\n\tpublic static final int SEED_EARTHROOT = SEEDS+8;\n\tpublic static final int SEED_STARFLOWER = SEEDS+9;\n\tpublic static final int SEED_FADELEAF = SEEDS+10;\n\tpublic static final int SEED_BLINDWEED = SEEDS+11;\n\tstatic{\n\t\tfor (int i = SEEDS; i < SEEDS+16; i++)\n\t\t\tassignItemRect(i, 10, 10);\n\t}\n\t\n\tprivate static final int BREWS = xy(1, 25); //8 slots\n\tpublic static final int BREW_INFERNAL = BREWS+0;\n\tpublic static final int BREW_BLIZZARD = BREWS+1;\n\tpublic static final int BREW_SHOCKING = BREWS+2;\n\tpublic static final int BREW_CAUSTIC = BREWS+3;\n\t\n\tprivate static final int ELIXIRS = xy(9, 25); //8 slots\n\tpublic static final int ELIXIR_HONEY = ELIXIRS+0;\n\tpublic static final int ELIXIR_AQUA = ELIXIRS+1;\n\tpublic static final int ELIXIR_MIGHT = ELIXIRS+2;\n\tpublic static final int ELIXIR_DRAGON = ELIXIRS+3;\n\tpublic static final int ELIXIR_TOXIC = ELIXIRS+4;\n\tpublic static final int ELIXIR_ICY = ELIXIRS+5;\n\tpublic static final int ELIXIR_ARCANE = ELIXIRS+6;\n\tstatic{\n\t\tfor (int i = BREWS; i < BREWS+16; i++)\n\t\t\tassignItemRect(i, 12, 14);\n\t}\n\t\n\t //16 free slots\n\t\n\tprivate static final int SPELLS = xy(1, 27); //16 slots\n\tpublic static final int MAGIC_PORTER = SPELLS+0;\n\tpublic static final int PHASE_SHIFT = SPELLS+1;\n\tpublic static final int TELE_GRAB = SPELLS+2;\n\tpublic static final int WILD_ENERGY = SPELLS+3;\n\tpublic static final int RETURN_BEACON = SPELLS+4;\n\tpublic static final int SUMMON_ELE = SPELLS+5;\n\t\n\tpublic static final int AQUA_BLAST = SPELLS+7;\n\tpublic static final int FEATHER_FALL = SPELLS+8;\n\tpublic static final int RECLAIM_TRAP = SPELLS+9;\n\t\n\tpublic static final int CURSE_INFUSE = SPELLS+11;\n\tpublic static final int MAGIC_INFUSE = SPELLS+12;\n\tpublic static final int ALCHEMIZE = SPELLS+13;\n\tpublic static final int RECYCLE = SPELLS+14;\n\tstatic{\n\t\tassignItemRect(MAGIC_PORTER, 12, 11);\n\t\tassignItemRect(PHASE_SHIFT, 12, 11);\n\t\tassignItemRect(TELE_GRAB, 12, 11);\n\t\tassignItemRect(WILD_ENERGY, 8, 16);\n\t\tassignItemRect(RETURN_BEACON, 8, 16);\n\t\tassignItemRect(SUMMON_ELE, 8, 16);\n\t\t\n\t\tassignItemRect(AQUA_BLAST, 11, 11);\n\t\tassignItemRect(FEATHER_FALL, 11, 11);\n\t\tassignItemRect(RECLAIM_TRAP, 11, 11);\n\t\t\n\t\tassignItemRect(CURSE_INFUSE, 10, 15);\n\t\tassignItemRect(MAGIC_INFUSE, 10, 15);\n\t\tassignItemRect(ALCHEMIZE, 10, 15);\n\t\tassignItemRect(RECYCLE, 10, 15);\n\t}\n\t\n\tprivate static final int FOOD = xy(1, 28); //16 slots\n\tpublic static final int MEAT = FOOD+0;\n\tpublic static final int STEAK = FOOD+1;\n\tpublic static final int STEWED = FOOD+2;\n\tpublic static final int OVERPRICED = FOOD+3;\n\tpublic static final int CARPACCIO = FOOD+4;\n\tpublic static final int RATION = FOOD+5;\n\tpublic static final int PASTY = FOOD+6;\n\tpublic static final int PUMPKIN_PIE = FOOD+7;\n\tpublic static final int CANDY_CANE = FOOD+8;\n\tpublic static final int MEAT_PIE = FOOD+9;\n\tpublic static final int BLANDFRUIT = FOOD+10;\n\tpublic static final int BLAND_CHUNKS= FOOD+11;\n\tpublic static final int BERRY = FOOD+12;\n\tpublic static final int PHANTOM_MEAT= FOOD+13;\n\tstatic{\n\t\tassignItemRect(MEAT, 15, 11);\n\t\tassignItemRect(STEAK, 15, 11);\n\t\tassignItemRect(STEWED, 15, 11);\n\t\tassignItemRect(OVERPRICED, 14, 11);\n\t\tassignItemRect(CARPACCIO, 15, 11);\n\t\tassignItemRect(RATION, 16, 12);\n\t\tassignItemRect(PASTY, 16, 11);\n\t\tassignItemRect(PUMPKIN_PIE, 16, 12);\n\t\tassignItemRect(CANDY_CANE, 13, 16);\n\t\tassignItemRect(MEAT_PIE, 16, 12);\n\t\tassignItemRect(BLANDFRUIT, 9, 12);\n\t\tassignItemRect(BLAND_CHUNKS,14, 6);\n\t\tassignItemRect(BERRY, 9, 11);\n\t\tassignItemRect(PHANTOM_MEAT,15, 11);\n\t}\n\n\tprivate static final int QUEST = xy(1, 29); //32 slots\n\tpublic static final int SKULL = QUEST+0;\n\tpublic static final int DUST = QUEST+1;\n\tpublic static final int CANDLE = QUEST+2;\n\tpublic static final int EMBER = QUEST+3;\n\tpublic static final int PICKAXE = QUEST+4;\n\tpublic static final int ORE = QUEST+5;\n\tpublic static final int TOKEN = QUEST+6;\n\tpublic static final int BLOB = QUEST+7;\n\tpublic static final int SHARD = QUEST+8;\n\tstatic{\n\t\tassignItemRect(SKULL, 16, 11);\n\t\tassignItemRect(DUST, 12, 11);\n\t\tassignItemRect(CANDLE, 12, 12);\n\t\tassignItemRect(EMBER, 12, 11);\n\t\tassignItemRect(PICKAXE, 14, 14);\n\t\tassignItemRect(ORE, 15, 15);\n\t\tassignItemRect(TOKEN, 12, 12);\n\t\tassignItemRect(BLOB, 10, 9);\n\t\tassignItemRect(SHARD, 8, 10);\n\t}\n\n\tprivate static final int BAGS = xy(1, 31); //16 slots\n\tpublic static final int WATERSKIN = BAGS+0;\n\tpublic static final int BACKPACK = BAGS+1;\n\tpublic static final int POUCH = BAGS+2;\n\tpublic static final int HOLDER = BAGS+3;\n\tpublic static final int BANDOLIER = BAGS+4;\n\tpublic static final int HOLSTER = BAGS+5;\n\tpublic static final int VIAL = BAGS+6;\n\tstatic{\n\t\tassignItemRect(WATERSKIN, 16, 14);\n\t\tassignItemRect(BACKPACK, 16, 16);\n\t\tassignItemRect(POUCH, 14, 15);\n\t\tassignItemRect(HOLDER, 16, 16);\n\t\tassignItemRect(BANDOLIER, 15, 16);\n\t\tassignItemRect(HOLSTER, 15, 16);\n\t\tassignItemRect(VIAL, 12, 12);\n\t}\n\n\tprivate static final int DOCUMENTS = xy(1, 32); //16 slots\n\tpublic static final int GUIDE_PAGE = DOCUMENTS+0;\n\tpublic static final int ALCH_PAGE = DOCUMENTS+1;\n\tpublic static final int SEWER_PAGE = DOCUMENTS+2;\n\tpublic static final int PRISON_PAGE = DOCUMENTS+3;\n\tpublic static final int CAVES_PAGE = DOCUMENTS+4;\n\tpublic static final int CITY_PAGE = DOCUMENTS+5;\n\tpublic static final int HALLS_PAGE = DOCUMENTS+6;\n\tpublic static final int LABS_PAGE = DOCUMENTS+7;\n\tstatic{\n\t\tassignItemRect(GUIDE_PAGE, 10, 11);\n\t\tassignItemRect(ALCH_PAGE, 10, 11);\n\t\tassignItemRect(SEWER_PAGE, 10, 11);\n\t\tassignItemRect(PRISON_PAGE, 10, 11);\n\t\tassignItemRect(CAVES_PAGE, 10, 11);\n\t\tassignItemRect(CITY_PAGE, 10, 11);\n\t\tassignItemRect(HALLS_PAGE, 10, 11);\n\t\tassignItemRect(LABS_PAGE, \t10, 11);\n\t}\n\n\t// ****** new sprites ******\n\n//\tprivate static final int \t\t\t \t=\t\t\txy(1, ); //16 slots\n//\tpublic static final int \t\t\t\t= +0;\n//\tpublic static final int \t\t\t\t= +1;\n//\tpublic static final int \t\t\t\t= +2;\n//\tpublic static final int \t\t\t\t= +3;\n//\tpublic static final int \t\t\t\t= +4;\n//\tpublic static final int \t\t\t\t= +5;\n//\tpublic static final int \t\t\t\t= +6;\n//\tstatic{\n//\t\tassignItemRect(, 16, 16);\n//\t\tassignItemRect(, 16, 16);\n//\t\tassignItemRect(, 16, 16);\n//\t\tassignItemRect(, 16, 16);\n//\t\tassignItemRect(, 16, 16);\n//\t\tassignItemRect(, 16, 16);\n//\t\tassignItemRect(, 16, 16);\n//\t}\n\n\t//free 16 slots\n\n\t//free 16 slots\n\n\tprivate static final int NEW_SPECIAL_ITEM\t=\t\txy(1, 35); //16 slots\n\tpublic static final int AMMO_BELT\t\t\t= NEW_SPECIAL_ITEM+0;\n\tpublic static final int SHEATH\t\t\t\t= NEW_SPECIAL_ITEM+1;\n\tpublic static final int KNIGHT_SHIELD\t\t= NEW_SPECIAL_ITEM+2;\n\tpublic static final int GAMMA_GUN\t\t\t= NEW_SPECIAL_ITEM+3;\n\tpublic static final int HAND_MIRROR\t\t\t= NEW_SPECIAL_ITEM+4;\n\tpublic static final int TELEPORTER\t\t\t= NEW_SPECIAL_ITEM+5;\n\tstatic{\n\t\tassignItemRect(AMMO_BELT\t, 15, 15);\n\t\tassignItemRect(SHEATH\t\t, 13, 13);\n\t\tassignItemRect(KNIGHT_SHIELD, 16, 15);\n\t\tassignItemRect(GAMMA_GUN\t, 12, 15);\n\t\tassignItemRect(HAND_MIRROR\t, 10, 16);\n\t\tassignItemRect(TELEPORTER\t, 14, 14);\n\t}\n\n\tprivate static final int NEW_ARMOR\t \t=\t\t\txy(1, 36); //16 slots\n\tpublic static final int ARMOR_GUNNER\t= NEW_ARMOR+0;\n\tpublic static final int ARMOR_SAMURAI\t= NEW_ARMOR+1;\n\tpublic static final int ARMOR_PLANTER\t= NEW_ARMOR+2;\n\tpublic static final int ARMOR_KNIGHT\t= NEW_ARMOR+3;\n\tpublic static final int ARMOR_NURSE\t\t= NEW_ARMOR+4;\n\tstatic{\n\t\tassignItemRect(ARMOR_GUNNER\t, 15, 13);\n\t\tassignItemRect(ARMOR_SAMURAI, 12, 16);\n\t\tassignItemRect(ARMOR_PLANTER, 15, 12);\n\t\tassignItemRect(ARMOR_KNIGHT\t, 14, 12);\n\t\tassignItemRect(ARMOR_NURSE\t, 14, 12);\n\t}\n\n\tprivate static final int NEW_SCROLL \t=\t\t\txy(1, 37); //16 slots\n\tpublic static final int SCROLL_PLUS\t\t= NEW_SCROLL+0;\n\tpublic static final int BLUEPRINT\t\t= NEW_SCROLL+1;\n\tstatic{\n\t\tassignItemRect(SCROLL_PLUS, 15, 14);\n\t}\n\n\tprivate static final int NEW_EXOTIC_SCROLL \t=\t\txy(1, 38); //16 slots\n\tpublic static final int EXOTIC_SCROLL_PLUS\t= NEW_EXOTIC_SCROLL+0;\n\tstatic{\n\t\tassignItemRect(EXOTIC_SCROLL_PLUS, 15, 14);\n\t}\n\n\tprivate static final int NEW_RING\t\t=\t\t\txy(1, 39); //16 slots\n\tpublic static final int RING_OBSIDIAN = NEW_RING+0;\n\tpublic static final int RING_PEARL \t= NEW_RING+1;\n\tpublic static final int RING_GOLD \t= NEW_RING+2;\n\tpublic static final int RING_EMBER \t= NEW_RING+3;\n\tpublic static final int RING_IOLITE\t\t= NEW_RING+4;\n\tpublic static final int RING_AQUAMARINE = NEW_RING+5;\n\tpublic static final int RING_JADE\t\t= NEW_RING+6;\n\tstatic{\n\t\tfor (int i = NEW_RING; i < NEW_RING+6; i++)\n\t\t\tassignItemRect(i, 8, 10);\n\t}\n\n\t//free 16 slots\n\n\tprivate static final int BULLET_ITEM\t=\t\t\txy(1, 41); //16 slots\n\tpublic static final int BULLET\t\t= BULLET_ITEM+0;\n\tpublic static final int HP_BULLET\t= BULLET_ITEM+1;\n\tpublic static final int AP_BULLET\t= BULLET_ITEM+2;\n\tpublic static final int CARTRIDGE\t= BULLET_ITEM+3;\n\tpublic static final int BULLET_BELT\t= BULLET_ITEM+4;\n\tpublic static final int OLD_AMULET\t= BULLET_ITEM+5;\n\tstatic{\n\t\tassignItemRect(BULLET\t\t, 13, 13);\n\t\tassignItemRect(HP_BULLET\t, 13, 13);\n\t\tassignItemRect(AP_BULLET\t, 13, 13);\n\t\tassignItemRect(CARTRIDGE\t, 11, 11);\n\t\tassignItemRect(BULLET_BELT\t, 15, 15);\n\t\tassignItemRect(OLD_AMULET\t, 16, 16);\n\t}\n\n\tprivate static final int BULLETS\t\t=\t\t\txy(1, 42); //16 slots\n\tpublic static final int SINGLE_BULLET\t= BULLETS+0;\n\tpublic static final int DOUBLE_BULLET\t= BULLETS+1;\n\tpublic static final int TRIPLE_BULLET\t= BULLETS+2;\n\tpublic static final int SNIPER_BULLET\t= BULLETS+3;\n\tpublic static final int GHOST_BULLET\t= BULLETS+4;\n\tstatic{\n\t\tassignItemRect(SINGLE_BULLET\t, 8, 8);\n\t\tassignItemRect(DOUBLE_BULLET\t, 11, 10);\n\t\tassignItemRect(TRIPLE_BULLET\t, 11, 11);\n\t\tassignItemRect(SNIPER_BULLET\t, 8, 8);\n\t\tassignItemRect(GHOST_BULLET\t\t, 8, 8);\n\t}\n\n\tprivate static final int SPECIAL_BULLETS=\t\t\txy(1, 43); //16 slots\n\tpublic static final int GRENADE_GREEN\t= SPECIAL_BULLETS+0;\n\tpublic static final int GRENADE_RED\t\t= SPECIAL_BULLETS+1;\n\tpublic static final int GRENADE_WHITE\t= SPECIAL_BULLETS+2;\n\tpublic static final int ROCKET\t\t\t= SPECIAL_BULLETS+3;\n\tpublic static final int BATTERY_SINGLE\t= SPECIAL_BULLETS+4;\n\tpublic static final int BATTERY_DOUBLE\t= SPECIAL_BULLETS+5;\n\tpublic static final int BATTERY_POWER\t= SPECIAL_BULLETS+6;\n\tstatic{\n\t\tassignItemRect(GRENADE_GREEN\t, 7, 7);\n\t\tassignItemRect(GRENADE_RED\t\t, 7, 7);\n\t\tassignItemRect(GRENADE_WHITE\t, 7, 7);\n\t\tassignItemRect(ROCKET\t\t\t, 9, 9);\n\t\tassignItemRect(BATTERY_SINGLE\t, 10, 10);\n\t\tassignItemRect(BATTERY_DOUBLE\t, 12, 12);\n\t\tassignItemRect(BATTERY_POWER\t, 12, 12);\n\t}\n\n\tprivate static final int ARROWS\t\t\t=\t\t\txy(1, 44); //16 slots\n\tpublic static final int ARROW_WIND\t\t= ARROWS+0;\n\tpublic static final int ARROW_NATURE\t= ARROWS+1;\n\tpublic static final int ARROW_GOLD\t\t= ARROWS+2;\n\tpublic static final int ARROW_CORROSION\t= ARROWS+3;\n\tpublic static final int ARROW_TACTICAL\t= ARROWS+4;\n\tstatic{\n\t\tassignItemRect(ARROW_WIND\t\t, 11, 11);\n\t\tassignItemRect(ARROW_NATURE\t\t, 11, 11);\n\t\tassignItemRect(ARROW_GOLD\t\t, 11, 11);\n\t\tassignItemRect(ARROW_CORROSION\t, 11, 11);\n\t\tassignItemRect(ARROW_TACTICAL\t, 11, 11);\n\t}\n\n\tprivate static final int NEW_WEP_TIER_1\t=\t\t\txy(1, 45); //8 slots\n\tpublic static final int WORN_KATANA\t\t= NEW_WEP_TIER_1+0;\n\tpublic static final int SABER\t\t\t= NEW_WEP_TIER_1+1;\n\tpublic static final int HEALING_BOOK\t= NEW_WEP_TIER_1+2;\n\tstatic{\n\t\tassignItemRect(WORN_KATANA\t, 13, 13);\n\t\tassignItemRect(SABER\t\t, 13, 15);\n\t\tassignItemRect(HEALING_BOOK\t, 13, 15);\n\t}\n\n\tprivate static final int NEW_WEP_TIER_2\t=\t\t\txy(9, 45); //8 slots\n\tpublic static final int SHORT_KATANA\t= NEW_WEP_TIER_2+0;\n\tpublic static final int KNIFE\t\t\t= NEW_WEP_TIER_2+1;\n\tpublic static final int NUNCHAKU\t\t= NEW_WEP_TIER_2+2;\n\tpublic static final int DUAL_DAGGER\t\t= NEW_WEP_TIER_2+3;\n\tstatic{\n\t\tassignItemRect(SHORT_KATANA\t, 14, 14);\n\t\tassignItemRect(KNIFE\t\t, 12, 13);\n\t\tassignItemRect(NUNCHAKU\t\t, 16, 16);\n\t\tassignItemRect(DUAL_DAGGER\t, 16, 16);\n\t}\n\n\tprivate static final int NEW_WEP_TIER_3\t=\t\t\txy(1, 46); //8 slots\n\tpublic static final int NORMAL_KATANA\t= NEW_WEP_TIER_3+0;\n\tpublic static final int BIBLE\t\t\t= NEW_WEP_TIER_3+1;\n\tpublic static final int RUNE_DAGGER\t\t= NEW_WEP_TIER_3+2;\n\tstatic{\n\t\tassignItemRect(NORMAL_KATANA, 14, 15);\n\t\tassignItemRect(BIBLE\t\t, 13, 16);\n\t\tassignItemRect(RUNE_DAGGER\t, 13, 14);\n\t}\n\n\tprivate static final int NEW_WEP_TIER_4 =\t\t\txy(9, 46); //8 slots\n\tpublic static final int LONG_KATANA\t\t= NEW_WEP_TIER_4+0;\n\tstatic{\n\t\tassignItemRect(LONG_KATANA, 15, 16);\n\t}\n\n\tprivate static final int NEW_WEP_TIER_5\t=\t\t\txy(1, 47); //8 slots\n\tpublic static final int LARGE_KATANA= NEW_WEP_TIER_5+0;\n\tpublic static final int LARGE_SHORD\t= NEW_WEP_TIER_5+1;\n\tstatic{\n\t\tassignItemRect(LARGE_KATANA\t, 12, 16);\n\t\tassignItemRect(LARGE_SHORD\t, 14, 16);\n\t}\n\n//\tprivate static final int NEW_WEP_TIER_6\t=\t\t\txy(9, 47); //8 slots\n//\tstatic{\n//\t}\n\n\tprivate static final int HG\t \t=\t\t\txy(1, 48); //8 slots\n\tpublic static final int HG_T1\t\t= HG+0;\n\tpublic static final int HG_T2\t\t= HG+1;\n\tpublic static final int HG_T3\t\t= HG+2;\n\tpublic static final int HG_T4\t\t= HG+3;\n\tpublic static final int HG_T5\t\t= HG+4;\n\tpublic static final int HG_AL\t\t= HG+5;\n\tpublic static final int HG_T6\t\t= HG+6;\n\tstatic{\n\t\tassignItemRect(HG_T1, 10, 13);\n\t\tassignItemRect(HG_T2, 11, 15);\n\t\tassignItemRect(HG_T3, 12, 15);\n\t\tassignItemRect(HG_T4, 13, 16);\n\t\tassignItemRect(HG_T5, 12, 16);\n\t\tassignItemRect(HG_AL, 12, 15);\n\t\tassignItemRect(HG_T6, 16, 16);\n\t}\n\n\tprivate static final int SMG\t=\t\t\txy(9, 48); //8 slots\n//\tpublic static final int SMG_T1\t\t= SMG+0;\n\tpublic static final int SMG_T2\t\t= SMG+1;\n//\tpublic static final int SMG_T3\t\t= SMG+2;\n//\tpublic static final int SMG_T4\t\t= SMG+3;\n\tpublic static final int SMG_T5\t\t= SMG+4;\n//\tpublic static final int SMG_AL\t\t= SMG+5;\n//\tpublic static final int SMG_T6\t\t= SMG+6;\n\tstatic{\n//\t\tassignItemRect(SMG_T1, 16, 16);\n\t\tassignItemRect(SMG_T2, 15, 16);\n//\t\tassignItemRect(SMG_T3, 16, 16);\n//\t\tassignItemRect(SMG_T4, 16, 16);\n\t\tassignItemRect(SMG_T5, 15, 15);\n//\t\tassignItemRect(SMG_AL, 16, 16);\n//\t\tassignItemRect(SMG_T6, 16, 16);\n\t}\n\n\tprivate static final int MG\t \t=\t\t\txy(1, 49); //8 slots\n//\tpublic static final int MG_T1\t\t= MG+0;\n//\tpublic static final int MG_T2\t\t= MG+1;\n\tpublic static final int MG_T3\t\t= MG+2;\n//\tpublic static final int MG_T4\t\t= MG+3;\n\tpublic static final int MG_T5\t\t= MG+4;\n//\tpublic static final int MG_AL\t\t= MG+5;\n//\tpublic static final int MG_T6\t\t= MG+6;\n\tstatic{\n//\t\tassignItemRect(MG_T1, 16, 16);\n//\t\tassignItemRect(MG_T2, 16, 16);\n\t\tassignItemRect(MG_T3, 13, 15);\n//\t\tassignItemRect(MG_T4, 16, 16);\n\t\tassignItemRect(MG_T5, 16, 15);\n//\t\tassignItemRect(MG_AL, 16, 16);\n//\t\tassignItemRect(MG_T6, 16, 16);\n\t}\n\n\n\n\tprivate static final int SG\t \t=\t\t\txy(9, 49); //8 slots\n//\tpublic static final int SG_T1\t\t= SG+0;\n//\tpublic static final int SG_T2\t\t= SG+1;\n\tpublic static final int SG_T3\t\t= SG+2;\n//\tpublic static final int SG_T4\t\t= SG+3;\n\tpublic static final int SG_T5\t\t= SG+4;\n//\tpublic static final int SG_AL\t\t= SG+5;\n//\tpublic static final int SG_T6\t\t= SG+6;\n\tstatic{\n//\t\tassignItemRect(SG_T1, 16, 16);\n//\t\tassignItemRect(SG_T2, 16, 16);\n\t\tassignItemRect(SG_T3, 14, 16);\n//\t\tassignItemRect(SG_T4, 16, 16);\n\t\tassignItemRect(SG_T5, 15, 16);\n//\t\tassignItemRect(SG_AL, 16, 16);\n//\t\tassignItemRect(SG_T6, 16, 16);\n\t}\n\n\tprivate static final int SR\t\t\t \t=\t\t\txy(1, 50); //8 slots\n\tpublic static final int SR_T1\t\t\t= SR+0;\n\tpublic static final int SR_T2\t\t\t= SR+1;\n\tpublic static final int SR_T3\t\t\t= SR+2;\n\tpublic static final int SR_T4\t\t\t= SR+3;\n\tpublic static final int SR_T5\t\t\t= SR+4;\n\tpublic static final int SR_AL\t\t\t= SR+5;\n\tpublic static final int SR_T6\t\t\t= SR+6;\n\tstatic{\n\t\tassignItemRect(SR_T1, 11, 15);\n\t\tassignItemRect(SR_T2, 13, 16);\n\t\tassignItemRect(SR_T3, 13, 16);\n\t\tassignItemRect(SR_T4, 14, 16);\n\t\tassignItemRect(SR_T5, 15, 16);\n\t\tassignItemRect(SR_AL, 16, 16);\n\t\tassignItemRect(SR_T6, 15, 16);\n\t}\n\n\tprivate static final int AR\t\t\t \t=\t\t\txy(9, 50); //8 slots\n\tpublic static final int AR_T1\t\t\t= AR+0;\n\tpublic static final int AR_T2\t\t\t= AR+1;\n\tpublic static final int AR_T3\t\t\t= AR+2;\n\tpublic static final int AR_T4\t\t\t= AR+3;\n\tpublic static final int AR_T5\t\t\t= AR+4;\n\tpublic static final int AR_AL\t\t\t= AR+5;\n\tpublic static final int AR_T6\t\t\t= AR+6;\n\tstatic{\n\t\tassignItemRect(AR_T1, 12, 13);\n\t\tassignItemRect(AR_T2, 13, 14);\n\t\tassignItemRect(AR_T3, 15, 16);\n\t\tassignItemRect(AR_T4, 16, 15);\n\t\tassignItemRect(AR_T5, 15, 16);\n\t\tassignItemRect(AR_AL, 16, 16);\n\t\tassignItemRect(AR_T6, 15, 16);\n\t}\n\n\t//GL, RL, 화염방사기, 레이저총 추후 추가\n\n\tprivate static final int BOWS\t\t\t=\t\t\txy(1, 53); //8 slots\n\tpublic static final int WIND_BOW\t\t= BOWS+0;\n\tpublic static final int NATURE_BOW\t\t= BOWS+1;\n\tpublic static final int GOLDEN_BOW\t\t= BOWS+2;\n\tpublic static final int CORROSION_BOW\t= BOWS+3;\n\tpublic static final int TACTICAL_BOW\t= BOWS+4;\n\tstatic{\n\t\tassignItemRect(WIND_BOW\t\t, 16, 16);\n\t\tassignItemRect(NATURE_BOW\t, 16, 16);\n\t\tassignItemRect(GOLDEN_BOW\t, 16, 16);\n\t\tassignItemRect(CORROSION_BOW, 16, 16);\n\t\tassignItemRect(TACTICAL_BOW\t, 16, 16);\n\t}\n\n\t//보조무기 추후 추가\n\n\t//free 16 slots\n\n\t//Alchemy melee weapons\n\n\tprivate static final int AL_WEP_T3\t\t\t=\t\t\txy(1, 56); //16 slots\n\tpublic static final int SPEAR_N_SHIELD\t\t= AL_WEP_T3+0;\n\tpublic static final int UNHOLY_SWORD\t\t= AL_WEP_T3+1;\n\tpublic static final int CHAOS_SWORD\t\t\t= AL_WEP_T3+2;\n\tpublic static final int FIRE_SCIMITAR\t\t= AL_WEP_T3+3;\n\tpublic static final int FROST_SCIMITAR\t\t= AL_WEP_T3+4;\n\tpublic static final int POISON_SCIMITAR\t\t= AL_WEP_T3+5;\n\tpublic static final int ELECTRIC_SCIMITAR\t= AL_WEP_T3+6;\n\tstatic{\n\t\tassignItemRect(SPEAR_N_SHIELD\t, 16, 15);\n\t\tassignItemRect(UNHOLY_SWORD\t\t, 14, 14);\n\t\tassignItemRect(CHAOS_SWORD\t\t, 14, 14);\n\t\tassignItemRect(FIRE_SCIMITAR\t, 13, 16);\n\t\tassignItemRect(FROST_SCIMITAR\t, 13, 16);\n\t\tassignItemRect(POISON_SCIMITAR\t, 13, 16);\n\t\tassignItemRect(ELECTRIC_SCIMITAR, 13, 16);\n\t}\n\n\tprivate static final int AL_WEP_T4\t\t=\t\t\txy(1, 57); //16 slots\n\tpublic static final int UNHOLY_BIBLE\t\t= AL_WEP_T4+0;\n\tstatic{\n\t\tassignItemRect(UNHOLY_BIBLE\t, \t13, 16);\n\t}\n\n\tprivate static final int AL_WEP_T5\t\t=\t\t\txy(1, 58); //16 slots\n\tpublic static final int TRUE_RUNIC_BLADE= AL_WEP_T5+0;\n\tpublic static final int CHAIN_WHIP\t\t= AL_WEP_T5+1;\n\tstatic{\n\t\tassignItemRect(TRUE_RUNIC_BLADE, 14, 14);\n\t\tassignItemRect(CHAIN_WHIP, \t\t 14, 14);\n\t}\n\n\tprivate static final int AL_WEP_T6\t \t=\t\t\txy(1, 59); //16 slots\n\tpublic static final int DUAL_GREATSWORD\t= AL_WEP_T6+0;\n\tpublic static final int FORCE_GLOVE\t\t= AL_WEP_T6+1;\n\tpublic static final int CHAIN_FLAIL\t\t= AL_WEP_T6+2;\n\tpublic static final int UNFORMED_BLADE\t= AL_WEP_T6+3;\n\tpublic static final int ASSASSINS_SPEAR\t= AL_WEP_T6+4;\n\tpublic static final int SHARP_KATANA\t= AL_WEP_T6+5;\n\tpublic static final int OBSIDIAN_SHIELD\t= AL_WEP_T6+6;\n\tpublic static final int LANCE\t\t\t= AL_WEP_T6+7;\n\tpublic static final int BEAM_SABER\t\t= AL_WEP_T6+8;\n\tpublic static final int MEISTER_HAMMER\t= AL_WEP_T6+9;\n\tpublic static final int HUGE_SWORD\t\t= AL_WEP_T6+10;\n\tstatic{\n\t\tassignItemRect(DUAL_GREATSWORD\t, 16, 16);\n\t\tassignItemRect(FORCE_GLOVE\t\t, 13, 15);\n\t\tassignItemRect(CHAIN_FLAIL\t\t, 16, 16);\n\t\tassignItemRect(UNFORMED_BLADE\t, 14, 15);\n\t\tassignItemRect(ASSASSINS_SPEAR\t, 16, 16);\n\t\tassignItemRect(SHARP_KATANA\t\t, 12, 16);\n\t\tassignItemRect(OBSIDIAN_SHIELD\t, 12, 16);\n\t\tassignItemRect(LANCE\t\t\t, 15, 15);\n\t\tassignItemRect(BEAM_SABER\t\t, 16, 15);\n\t\tassignItemRect(MEISTER_HAMMER\t, 16, 16);\n\t\tassignItemRect(HUGE_SWORD\t\t, 16, 16);\n\t}\n\n\tprivate static final int AL_WEP_T7\t\t=\t\t\txy(1, 60); //16 slots\n\tpublic static final int LANCE_N_SHIELD\t= AL_WEP_T7+0;\n\tpublic static final int TACTICAL_SHIELD\t= AL_WEP_T7+1;\n\tpublic static final int HOLYSWORD_TRUE\t= AL_WEP_T7+2;\n\tpublic static final int HOLYSWORD\t\t= AL_WEP_T7+3;\n\tstatic{\n\t\tassignItemRect(LANCE_N_SHIELD\t, 16, 15);\n\t\tassignItemRect(TACTICAL_SHIELD\t, 12, 16);\n\t\tassignItemRect(HOLYSWORD_TRUE\t, 16, 16);\n\t\tassignItemRect(HOLYSWORD\t\t, 16, 16);\n\t}\n\n\tprivate static final int ENERGY_WEP\t\t\t \t=\t\t\txy(1, 61); //16 slots\n\tpublic static final int WORN_SHORTSWORD_ENERGY\t= ENERGY_WEP+0;\n//\tpublic static final int \t\t\t\t\t\t= ENERGY_WEP+1;\n\tpublic static final int DAGGER_ENERGY\t\t\t= ENERGY_WEP+2;\n\tpublic static final int GLOVES_ENERGY\t\t\t= ENERGY_WEP+3;\n\tpublic static final int RAPIER_ENERGY\t\t\t= ENERGY_WEP+4;\n\tpublic static final int HG_T1_ENERGY\t\t\t= ENERGY_WEP+5;\n\tpublic static final int WORN_KATANA_ENERGY\t\t= ENERGY_WEP+6;\n\tpublic static final int SABER_ENERGY\t\t\t= ENERGY_WEP+7;\n\tstatic{\n\t\tassignItemRect(WORN_SHORTSWORD_ENERGY\t, 13, 13);\n//\t\tassignItemRect(\t\t\t\t\t\t\t, 16, 16);\n\t\tassignItemRect(DAGGER_ENERGY\t\t\t, 12, 13);\n\t\tassignItemRect(GLOVES_ENERGY\t\t\t, 12, 16);\n\t\tassignItemRect(RAPIER_ENERGY\t\t\t, 13, 14);\n\t\tassignItemRect(HG_T1_ENERGY\t\t\t\t, 10, 13);\n\t\tassignItemRect(WORN_KATANA_ENERGY\t\t, 13, 13);\n\t\tassignItemRect(SABER_ENERGY\t\t\t\t, 13, 15);\n\t}\n\n\tprivate static final int SPELLBOOK\t\t\t \t\t=\t\txy(1, 62); //16 slots\n\tpublic static final int BOOK_OF_MAGIC \t\t\t= SPELLBOOK+0;\n\tpublic static final int BOOK_OF_FIRE \t\t= SPELLBOOK+1;\n\tpublic static final int BOOK_OF_FROST \t= SPELLBOOK+2;\n\tpublic static final int BOOK_OF_THUNDERBOLT \t= SPELLBOOK+3;\n\tpublic static final int BOOK_OF_DISINTEGRATION \t= SPELLBOOK+4;\n\tpublic static final int BOOK_OF_LIGHT\t\t\t= SPELLBOOK+5;\n\tpublic static final int BOOK_OF_CORROSION \t= SPELLBOOK+6;\n\tpublic static final int BOOK_OF_EARTH \t\t= SPELLBOOK+7;\n\tpublic static final int BOOK_OF_BLAST \t\t= SPELLBOOK+8;\n\tpublic static final int BOOK_OF_CORRUPTION \t= SPELLBOOK+9;\n\tpublic static final int BOOK_OF_WARDING \t= SPELLBOOK+10;\n\tpublic static final int BOOK_OF_REGROWTH \t= SPELLBOOK+11;\n\tpublic static final int BOOK_OF_TRANSFUSION \t= SPELLBOOK+12;\n\tstatic{\n\t\tassignItemRect(BOOK_OF_MAGIC \t\t\t, 12, 16);\n\t\tassignItemRect(BOOK_OF_FIRE \t\t, 12, 16);\n\t\tassignItemRect(BOOK_OF_FROST \t, 12, 16);\n\t\tassignItemRect(BOOK_OF_THUNDERBOLT \t, 12, 16);\n\t\tassignItemRect(BOOK_OF_DISINTEGRATION \t, 12, 16);\n\t\tassignItemRect(BOOK_OF_LIGHT\t\t\t, 12, 16);\n\t\tassignItemRect(BOOK_OF_CORROSION \t, 12, 16);\n\t\tassignItemRect(BOOK_OF_EARTH \t\t\t, 12, 16);\n\t\tassignItemRect(BOOK_OF_BLAST \t\t, 12, 16);\n\t\tassignItemRect(BOOK_OF_CORRUPTION \t, 12, 16);\n\t\tassignItemRect(BOOK_OF_WARDING \t, 12, 16);\n\t\tassignItemRect(BOOK_OF_REGROWTH \t, 12, 16);\n\t\tassignItemRect(BOOK_OF_TRANSFUSION \t, 12, 16);\n\t}\n\n\tprivate static final int SHOVEL\t\t\t=\t\t\t\txy(1, 63); //8 slots\n\tpublic static final int PLANTER_SHOVEL\t= SHOVEL+0;\n\tpublic static final int GILDED_SHOVEL\t= SHOVEL+1;\n\tpublic static final int BATTLE_SHOVEL\t= SHOVEL+2;\n\tpublic static final int MINERS_TOOL\t\t= SHOVEL+3;\n\tstatic{\n\t\tassignItemRect(PLANTER_SHOVEL\t, 16, 16);\n\t\tassignItemRect(GILDED_SHOVEL\t, 16, 16);\n\t\tassignItemRect(BATTLE_SHOVEL\t, 16, 16);\n\t\tassignItemRect(MINERS_TOOL\t\t, 16, 16);\n\t}\n\n\tprivate static final int SPECIAL_ITEM\t\t\t=\t\txy(9, 63); //8 slots\n\tpublic static final int HERO_SWORD\t= SPECIAL_ITEM+0;\n\tstatic{\n\t\tassignItemRect(HERO_SWORD\t, 14, 14);\n\t}\n\n\tprivate static final int NEW_POTIONS\t\t=\t\t\txy(1, 64); //16 slots\n\tpublic static final int POTION_FLUORESCENT\t= NEW_POTIONS+0;\n\tpublic static final int POTION_ASH\t\t\t= NEW_POTIONS+1;\n\tstatic{\n\t\tfor (int i = NEW_POTIONS; i < NEW_POTIONS+1; i++)\n\t\t\tassignItemRect(i, 12, 14);\n\t}\n\n\tprivate static final int NEW_EXOTIC_POTIONS\t=\t\t\txy(1, 65); //16 slots\n\tpublic static final int EXOTIC_FLUORESCENT\t= NEW_EXOTIC_POTIONS+0;\n\tpublic static final int EXOTIC_ASH\t\t\t= NEW_EXOTIC_POTIONS+1;\n\tstatic{\n\t\tfor (int i = NEW_EXOTIC_POTIONS; i < NEW_EXOTIC_POTIONS+1; i++)\n\t\t\tassignItemRect(i, 12, 13);\n\t}\n\n\tprivate static final int NEW_BREWS\t\t\t=\t\t\txy(1, 66); //16 slots\n\tpublic static final int BREW_SATISFACTION\t= NEW_BREWS+0;\n\tpublic static final int BREW_TALENT\t\t\t= NEW_BREWS+1;\n\tstatic{\n\t\tfor (int i = NEW_BREWS; i < NEW_BREWS+2; i++)\n\t\t\tassignItemRect(i, 12, 14);\n\t}\n\n\tprivate static final int NEW_SPELLS\t\t\t=\t\t\txy(1, 67); //16 slots\n\tpublic static final int FIRE_IMBUE\t\t\t= NEW_SPELLS+0;\n\tpublic static final int XRAY\t\t\t\t= NEW_SPELLS+1;\n\tpublic static final int FIREMAKER\t\t\t= NEW_SPELLS+2;\n\tpublic static final int ICEMAKER\t\t\t= NEW_SPELLS+3;\n\tpublic static final int RAPID_GROWTH\t\t= NEW_SPELLS+4;\n\tpublic static final int\tHANDY_BARRICADE\t\t= NEW_SPELLS+5;\n\tpublic static final int ADVANCED_EVOLUTION\t= NEW_SPELLS+6;\n\tpublic static final int EVOLUTION\t\t\t= NEW_SPELLS+7;\n\tpublic static final int UPGRADE_DUST\t\t= NEW_SPELLS+8;\n\tstatic{\n\t\tassignItemRect(FIRE_IMBUE\t\t\t, 11, 11);\n\t\tassignItemRect(XRAY\t\t\t\t\t, 11, 11);\n\t\tassignItemRect(FIREMAKER\t\t\t, 12, 11);\n\t\tassignItemRect(ICEMAKER\t\t\t\t, 12, 11);\n\t\tassignItemRect(RAPID_GROWTH\t\t\t, 8, 16);\n\t\tassignItemRect(HANDY_BARRICADE\t\t, 8, 16);\n\t\tassignItemRect(ADVANCED_EVOLUTION\t, 10, 15);\n\t\tassignItemRect(EVOLUTION\t\t\t, 10, 15);\n\t\tassignItemRect(UPGRADE_DUST\t\t\t, 12, 11);\n\t}\n\n\t// ****** new sprites end ******\n\n\n\n\t//for smaller 8x8 icons that often accompany an item sprite\n\tpublic static class Icons {\n\n\t\tprivate static final int WIDTH = 16;\n\t\tpublic static final int SIZE = 8;\n\n\t\tpublic static TextureFilm film = new TextureFilm( Assets.Sprites.ITEM_ICONS, SIZE, SIZE );\n\n\t\tprivate static int xy(int x, int y){\n\t\t\tx -= 1; y -= 1;\n\t\t\treturn x + WIDTH*y;\n\t\t}\n\n\t\tprivate static void assignIconRect( int item, int width, int height ){\n\t\t\tint x = (item % WIDTH) * SIZE;\n\t\t\tint y = (item / WIDTH) * SIZE;\n\t\t\tfilm.add( item, x, y, x+width, y+height);\n\t\t}\n\n\t\tprivate static final int RINGS = xy(1, 1); //16 slots\n\t\tpublic static final int RING_ACCURACY = RINGS+0;\n\t\tpublic static final int RING_ARCANA = RINGS+1;\n\t\tpublic static final int RING_ELEMENTS = RINGS+2;\n\t\tpublic static final int RING_ENERGY = RINGS+3;\n\t\tpublic static final int RING_EVASION = RINGS+4;\n\t\tpublic static final int RING_FORCE = RINGS+5;\n\t\tpublic static final int RING_FUROR = RINGS+6;\n\t\tpublic static final int RING_HASTE = RINGS+7;\n\t\tpublic static final int RING_MIGHT = RINGS+8;\n\t\tpublic static final int RING_SHARPSHOOT = RINGS+9;\n\t\tpublic static final int RING_TENACITY = RINGS+10;\n\t\tpublic static final int RING_WEALTH = RINGS+11;\n\t\tstatic {\n\t\t\tassignIconRect( RING_ACCURACY, 7, 7 );\n\t\t\tassignIconRect( RING_ARCANA, 7, 7 );\n\t\t\tassignIconRect( RING_ELEMENTS, 7, 7 );\n\t\t\tassignIconRect( RING_ENERGY, 7, 5 );\n\t\t\tassignIconRect( RING_EVASION, 7, 7 );\n\t\t\tassignIconRect( RING_FORCE, 5, 6 );\n\t\t\tassignIconRect( RING_FUROR, 7, 6 );\n\t\t\tassignIconRect( RING_HASTE, 6, 6 );\n\t\t\tassignIconRect( RING_MIGHT, 7, 7 );\n\t\t\tassignIconRect( RING_SHARPSHOOT, 7, 7 );\n\t\t\tassignIconRect( RING_TENACITY, 6, 6 );\n\t\t\tassignIconRect( RING_WEALTH, 7, 6 );\n\t\t}\n\n\t\t //16 free slots\n\n\t\tprivate static final int SCROLLS = xy(1, 3); //16 slots\n\t\tpublic static final int SCROLL_UPGRADE = SCROLLS+0;\n\t\tpublic static final int SCROLL_IDENTIFY = SCROLLS+1;\n\t\tpublic static final int SCROLL_REMCURSE = SCROLLS+2;\n\t\tpublic static final int SCROLL_MIRRORIMG= SCROLLS+3;\n\t\tpublic static final int SCROLL_RECHARGE = SCROLLS+4;\n\t\tpublic static final int SCROLL_TELEPORT = SCROLLS+5;\n\t\tpublic static final int SCROLL_LULLABY = SCROLLS+6;\n\t\tpublic static final int SCROLL_MAGICMAP = SCROLLS+7;\n\t\tpublic static final int SCROLL_RAGE = SCROLLS+8;\n\t\tpublic static final int SCROLL_RETRIB = SCROLLS+9;\n\t\tpublic static final int SCROLL_TERROR = SCROLLS+10;\n\t\tpublic static final int SCROLL_TRANSMUTE= SCROLLS+11;\n\t\tstatic {\n\t\t\tassignIconRect( SCROLL_UPGRADE, 7, 7 );\n\t\t\tassignIconRect( SCROLL_IDENTIFY, 4, 7 );\n\t\t\tassignIconRect( SCROLL_REMCURSE, 7, 7 );\n\t\t\tassignIconRect( SCROLL_MIRRORIMG, 7, 5 );\n\t\t\tassignIconRect( SCROLL_RECHARGE, 7, 5 );\n\t\t\tassignIconRect( SCROLL_TELEPORT, 7, 7 );\n\t\t\tassignIconRect( SCROLL_LULLABY, 7, 6 );\n\t\t\tassignIconRect( SCROLL_MAGICMAP, 7, 7 );\n\t\t\tassignIconRect( SCROLL_RAGE, 6, 6 );\n\t\t\tassignIconRect( SCROLL_RETRIB, 5, 6 );\n\t\t\tassignIconRect( SCROLL_TERROR, 5, 7 );\n\t\t\tassignIconRect( SCROLL_TRANSMUTE, 7, 7 );\n\t\t}\n\n\t\tprivate static final int EXOTIC_SCROLLS = xy(1, 4); //16 slots\n\t\tpublic static final int SCROLL_ENCHANT = EXOTIC_SCROLLS+0;\n\t\tpublic static final int SCROLL_DIVINATE = EXOTIC_SCROLLS+1;\n\t\tpublic static final int SCROLL_ANTIMAGIC= EXOTIC_SCROLLS+2;\n\t\tpublic static final int SCROLL_PRISIMG = EXOTIC_SCROLLS+3;\n\t\tpublic static final int SCROLL_MYSTENRG = EXOTIC_SCROLLS+4;\n\t\tpublic static final int SCROLL_PASSAGE = EXOTIC_SCROLLS+5;\n\t\tpublic static final int SCROLL_SIREN = EXOTIC_SCROLLS+6;\n\t\tpublic static final int SCROLL_FORESIGHT= EXOTIC_SCROLLS+7;\n\t\tpublic static final int SCROLL_CHALLENGE= EXOTIC_SCROLLS+8;\n\t\tpublic static final int SCROLL_PSIBLAST = EXOTIC_SCROLLS+9;\n\t\tpublic static final int SCROLL_DREAD = EXOTIC_SCROLLS+10;\n\t\tpublic static final int SCROLL_METAMORPH= EXOTIC_SCROLLS+11;\n\t\tstatic {\n\t\t\tassignIconRect( SCROLL_ENCHANT, 7, 7 );\n\t\t\tassignIconRect( SCROLL_DIVINATE, 7, 6 );\n\t\t\tassignIconRect( SCROLL_ANTIMAGIC, 7, 7 );\n\t\t\tassignIconRect( SCROLL_PRISIMG, 5, 7 );\n\t\t\tassignIconRect( SCROLL_MYSTENRG, 7, 5 );\n\t\t\tassignIconRect( SCROLL_PASSAGE, 5, 7 );\n\t\t\tassignIconRect( SCROLL_SIREN, 7, 6 );\n\t\t\tassignIconRect( SCROLL_FORESIGHT, 7, 5 );\n\t\t\tassignIconRect( SCROLL_CHALLENGE, 7, 7 );\n\t\t\tassignIconRect( SCROLL_PSIBLAST, 5, 6 );\n\t\t\tassignIconRect( SCROLL_DREAD, 5, 7 );\n\t\t\tassignIconRect( SCROLL_METAMORPH, 7, 7 );\n\t\t}\n\n\t\t //16 free slots\n\n\t\tprivate static final int POTIONS = xy(1, 6); //16 slots\n\t\tpublic static final int POTION_STRENGTH = POTIONS+0;\n\t\tpublic static final int POTION_HEALING = POTIONS+1;\n\t\tpublic static final int POTION_MINDVIS = POTIONS+2;\n\t\tpublic static final int POTION_FROST = POTIONS+3;\n\t\tpublic static final int POTION_LIQFLAME = POTIONS+4;\n\t\tpublic static final int POTION_TOXICGAS = POTIONS+5;\n\t\tpublic static final int POTION_HASTE = POTIONS+6;\n\t\tpublic static final int POTION_INVIS = POTIONS+7;\n\t\tpublic static final int POTION_LEVITATE = POTIONS+8;\n\t\tpublic static final int POTION_PARAGAS = POTIONS+9;\n\t\tpublic static final int POTION_PURITY = POTIONS+10;\n\t\tpublic static final int POTION_EXP = POTIONS+11;\n\t\tstatic {\n\t\t\tassignIconRect( POTION_STRENGTH, 7, 7 );\n\t\t\tassignIconRect( POTION_HEALING, 6, 7 );\n\t\t\tassignIconRect( POTION_MINDVIS, 7, 5 );\n\t\t\tassignIconRect( POTION_FROST, 7, 7 );\n\t\t\tassignIconRect( POTION_LIQFLAME, 5, 7 );\n\t\t\tassignIconRect( POTION_TOXICGAS, 7, 7 );\n\t\t\tassignIconRect( POTION_HASTE, 6, 6 );\n\t\t\tassignIconRect( POTION_INVIS, 5, 7 );\n\t\t\tassignIconRect( POTION_LEVITATE, 6, 7 );\n\t\t\tassignIconRect( POTION_PARAGAS, 7, 7 );\n\t\t\tassignIconRect( POTION_PURITY, 5, 7 );\n\t\t\tassignIconRect( POTION_EXP, 7, 7 );\n\t\t}\n\n\t\tprivate static final int EXOTIC_POTIONS = xy(1, 7); //16 slots\n\t\tpublic static final int POTION_MASTERY = EXOTIC_POTIONS+0;\n\t\tpublic static final int POTION_SHIELDING= EXOTIC_POTIONS+1;\n\t\tpublic static final int POTION_MAGISIGHT= EXOTIC_POTIONS+2;\n\t\tpublic static final int POTION_SNAPFREEZ= EXOTIC_POTIONS+3;\n\t\tpublic static final int POTION_DRGBREATH= EXOTIC_POTIONS+4;\n\t\tpublic static final int POTION_CORROGAS = EXOTIC_POTIONS+5;\n\t\tpublic static final int POTION_STAMINA = EXOTIC_POTIONS+6;\n\t\tpublic static final int POTION_SHROUDFOG= EXOTIC_POTIONS+7;\n\t\tpublic static final int POTION_STRMCLOUD= EXOTIC_POTIONS+8;\n\t\tpublic static final int POTION_EARTHARMR= EXOTIC_POTIONS+9;\n\t\tpublic static final int POTION_CLEANSE = EXOTIC_POTIONS+10;\n\t\tpublic static final int POTION_DIVINE = EXOTIC_POTIONS+11;\n\t\tstatic {\n\t\t\tassignIconRect( POTION_MASTERY, 7, 7 );\n\t\t\tassignIconRect( POTION_SHIELDING, 6, 6 );\n\t\t\tassignIconRect( POTION_MAGISIGHT, 7, 5 );\n\t\t\tassignIconRect( POTION_SNAPFREEZ, 7, 7 );\n\t\t\tassignIconRect( POTION_DRGBREATH, 7, 7 );\n\t\t\tassignIconRect( POTION_CORROGAS, 7, 7 );\n\t\t\tassignIconRect( POTION_STAMINA, 6, 6 );\n\t\t\tassignIconRect( POTION_SHROUDFOG, 7, 7 );\n\t\t\tassignIconRect( POTION_STRMCLOUD, 7, 7 );\n\t\t\tassignIconRect( POTION_EARTHARMR, 6, 6 );\n\t\t\tassignIconRect( POTION_CLEANSE, 7, 7 );\n\t\t\tassignIconRect( POTION_DIVINE, 7, 7 );\n\t\t}\n\n\t\t //16 free slots\n\n\t}\n\n}" }, { "identifier": "GLog", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/utils/GLog.java", "snippet": "public class GLog {\n\n\tpublic static final String TAG = \"GAME\";\n\t\n\tpublic static final String POSITIVE\t\t= \"++ \";\n\tpublic static final String NEGATIVE\t\t= \"-- \";\n\tpublic static final String WARNING\t\t= \"** \";\n\tpublic static final String HIGHLIGHT\t= \"@@ \";\n\n\tpublic static final String NEW_LINE\t = \"\\n\";\n\t\n\tpublic static Signal<String> update = new Signal<>();\n\n\tpublic static void newLine(){\n\t\tupdate.dispatch( NEW_LINE );\n\t}\n\t\n\tpublic static void i( String text, Object... args ) {\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttext = Messages.format( text, args );\n\t\t}\n\t\t\n\t\tDeviceCompat.log( TAG, text );\n\t\tupdate.dispatch( text );\n\t}\n\t\n\tpublic static void p( String text, Object... args ) {\n\t\ti( POSITIVE + text, args );\n\t}\n\t\n\tpublic static void n( String text, Object... args ) {\n\t\ti( NEGATIVE + text, args );\n\t}\n\t\n\tpublic static void w( String text, Object... args ) {\n\t\ti( WARNING + text, args );\n\t}\n\t\n\tpublic static void h( String text, Object... args ) {\n\t\ti( HIGHLIGHT + text, args );\n\t}\n}" }, { "identifier": "Sample", "path": "SPD-classes/src/main/java/com/watabou/noosa/audio/Sample.java", "snippet": "public enum Sample {\n\n\tINSTANCE;\n\n\tprotected HashMap<Object, Sound> ids = new HashMap<>();\n\n\tprivate boolean enabled = true;\n\tprivate float globalVolume = 1f;\n\n\tpublic synchronized void reset() {\n\n\t\tfor (Sound sound : ids.values()){\n\t\t\tsound.dispose();\n\t\t}\n\t\t\n\t\tids.clear();\n\t\tdelayedSFX.clear();\n\n\t}\n\n\tpublic synchronized void pause() {\n\t\tfor (Sound sound : ids.values()) {\n\t\t\tsound.pause();\n\t\t}\n\t}\n\n\tpublic synchronized void resume() {\n\t\tfor (Sound sound : ids.values()) {\n\t\t\tsound.resume();\n\t\t}\n\t}\n\n\tpublic synchronized void load( final String... assets ) {\n\n\t\tfinal ArrayList<String> toLoad = new ArrayList<>();\n\n\t\tfor (String asset : assets){\n\t\t\tif (!ids.containsKey(asset)){\n\t\t\t\ttoLoad.add(asset);\n\t\t\t}\n\t\t}\n\n\t\t//don't make a new thread of all assets are already loaded\n\t\tif (toLoad.isEmpty()) return;\n\n\t\t//load in a separate thread to prevent this blocking the UI\n\t\tnew Thread(){\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tfor (String asset : toLoad) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tSound newSound = Gdx.audio.newSound(Gdx.files.internal(asset));\n\t\t\t\t\t\tsynchronized (INSTANCE) {\n\t\t\t\t\t\t\tids.put(asset, newSound);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (Exception e){\n\t\t\t\t\t\tGame.reportException(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}.start();\n\t\t\n\t}\n\n\tpublic synchronized void unload( Object src ) {\n\t\tif (ids.containsKey( src )) {\n\t\t\tids.get( src ).dispose();\n\t\t\tids.remove( src );\n\t\t}\n\t}\n\n\tpublic long play( Object id ) {\n\t\treturn play( id, 1 );\n\t}\n\n\tpublic long play( Object id, float volume ) {\n\t\treturn play( id, volume, volume, 1 );\n\t}\n\t\n\tpublic long play( Object id, float volume, float pitch ) {\n\t\treturn play( id, volume, volume, pitch );\n\t}\n\t\n\tpublic synchronized long play( Object id, float leftVolume, float rightVolume, float pitch ) {\n\t\tfloat volume = Math.max(leftVolume, rightVolume);\n\t\tfloat pan = rightVolume - leftVolume;\n\t\tif (enabled && ids.containsKey( id )) {\n\t\t\treturn ids.get(id).play( globalVolume*volume, pitch, pan );\n\t\t} else {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tprivate class DelayedSoundEffect{\n\t\tObject id;\n\t\tfloat delay;\n\n\t\tfloat leftVol;\n\t\tfloat rightVol;\n\t\tfloat pitch;\n\t}\n\n\tprivate static final HashSet<DelayedSoundEffect> delayedSFX = new HashSet<>();\n\n\tpublic void playDelayed( Object id, float delay ){\n\t\tplayDelayed( id, delay, 1 );\n\t}\n\n\tpublic void playDelayed( Object id, float delay, float volume ) {\n\t\tplayDelayed( id, delay, volume, volume, 1 );\n\t}\n\n\tpublic void playDelayed( Object id, float delay, float volume, float pitch ) {\n\t\tplayDelayed( id, delay, volume, volume, pitch );\n\t}\n\n\tpublic void playDelayed( Object id, float delay, float leftVolume, float rightVolume, float pitch ) {\n\t\tif (delay <= 0) {\n\t\t\tplay(id, leftVolume, rightVolume, pitch);\n\t\t\treturn;\n\t\t}\n\t\tDelayedSoundEffect sfx = new DelayedSoundEffect();\n\t\tsfx.id = id;\n\t\tsfx.delay = delay;\n\t\tsfx.leftVol = leftVolume;\n\t\tsfx.rightVol = rightVolume;\n\t\tsfx.pitch = pitch;\n\t\tsynchronized (delayedSFX) {\n\t\t\tdelayedSFX.add(sfx);\n\t\t}\n\t}\n\n\tpublic void update(){\n\t\tsynchronized (delayedSFX) {\n\t\t\tif (delayedSFX.isEmpty()) return;\n\t\t\tfor (DelayedSoundEffect sfx : delayedSFX.toArray(new DelayedSoundEffect[0])) {\n\t\t\t\tsfx.delay -= Game.elapsed;\n\t\t\t\tif (sfx.delay <= 0) {\n\t\t\t\t\tdelayedSFX.remove(sfx);\n\t\t\t\t\tplay(sfx.id, sfx.leftVol, sfx.rightVol, sfx.pitch);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void enable( boolean value ) {\n\t\tenabled = value;\n\t}\n\n\tpublic void volume( float value ) {\n\t\tglobalVolume = value;\n\t}\n\n\tpublic boolean isEnabled() {\n\t\treturn enabled;\n\t}\n\t\n}" } ]
import com.shatteredpixel.shatteredpixeldungeon.utils.GLog; import com.watabou.noosa.audio.Sample; import com.shatteredpixel.shatteredpixeldungeon.Assets; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.actors.Char; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Amok; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff; import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.Mob; import com.shatteredpixel.shatteredpixeldungeon.effects.Speck; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet;
66,066
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.items.scrolls; public class ScrollOfRage extends Scroll { { icon = ItemSpriteSheet.Icons.SCROLL_RAGE; } @Override public void doRead() { detach(curUser.belongings.backpack); for (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] )) { mob.beckon( curUser.pos ); if (mob.alignment != Char.Alignment.ALLY && Dungeon.level.heroFOV[mob.pos]) {
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.items.scrolls; public class ScrollOfRage extends Scroll { { icon = ItemSpriteSheet.Icons.SCROLL_RAGE; } @Override public void doRead() { detach(curUser.belongings.backpack); for (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] )) { mob.beckon( curUser.pos ); if (mob.alignment != Char.Alignment.ALLY && Dungeon.level.heroFOV[mob.pos]) {
Buff.prolong(mob, Amok.class, 5f);
4
2023-11-27 05:56:58+00:00
128k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/swt/org/jfree/experimental/chart/swt/ChartComposite.java
[ { "identifier": "ChartMouseEvent", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/ChartMouseEvent.java", "snippet": "public class ChartMouseEvent extends EventObject implements Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -682393837314562149L;\r\n\r\n /** The chart that the mouse event relates to. */\r\n private JFreeChart chart;\r\n\r\n /** The Java mouse event that triggered this event. */\r\n private MouseEvent trigger;\r\n\r\n /** The chart entity (if any). */\r\n private ChartEntity entity;\r\n\r\n /**\r\n * Constructs a new event.\r\n *\r\n * @param chart the source chart (<code>null</code> not permitted).\r\n * @param trigger the mouse event that triggered this event\r\n * (<code>null</code> not permitted).\r\n * @param entity the chart entity (if any) under the mouse point\r\n * (<code>null</code> permitted).\r\n */\r\n public ChartMouseEvent(JFreeChart chart, MouseEvent trigger,\r\n ChartEntity entity) {\r\n super(chart);\r\n this.chart = chart;\r\n this.trigger = trigger;\r\n this.entity = entity;\r\n }\r\n\r\n /**\r\n * Returns the chart that the mouse event relates to.\r\n *\r\n * @return The chart (never <code>null</code>).\r\n */\r\n public JFreeChart getChart() {\r\n return this.chart;\r\n }\r\n\r\n /**\r\n * Returns the mouse event that triggered this event.\r\n *\r\n * @return The event (never <code>null</code>).\r\n */\r\n public MouseEvent getTrigger() {\r\n return this.trigger;\r\n }\r\n\r\n /**\r\n * Returns the chart entity (if any) under the mouse point.\r\n *\r\n * @return The chart entity (possibly <code>null</code>).\r\n */\r\n public ChartEntity getEntity() {\r\n return this.entity;\r\n }\r\n\r\n}\r" }, { "identifier": "ChartMouseListener", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/ChartMouseListener.java", "snippet": "public interface ChartMouseListener extends EventListener {\r\n\r\n /**\r\n * Callback method for receiving notification of a mouse click on a chart.\r\n *\r\n * @param event information about the event.\r\n */\r\n void chartMouseClicked(ChartMouseEvent event);\r\n\r\n /**\r\n * Callback method for receiving notification of a mouse movement on a\r\n * chart.\r\n *\r\n * @param event information about the event.\r\n */\r\n void chartMouseMoved(ChartMouseEvent event);\r\n\r\n}\r" }, { "identifier": "ChartRenderingInfo", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/ChartRenderingInfo.java", "snippet": "public class ChartRenderingInfo implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 2751952018173406822L;\r\n\r\n /** The area in which the chart is drawn. */\r\n private transient Rectangle2D chartArea;\r\n\r\n /** Rendering info for the chart's plot (and subplots, if any). */\r\n private PlotRenderingInfo plotInfo;\r\n\r\n /**\r\n * Storage for the chart entities. Since retaining entity information for\r\n * charts with a large number of data points consumes a lot of memory, it\r\n * is intended that you can set this to <code>null</code> to prevent the\r\n * information being collected.\r\n */\r\n private EntityCollection entities;\r\n\r\n /**\r\n * Constructs a new ChartRenderingInfo structure that can be used to\r\n * collect information about the dimensions of a rendered chart.\r\n */\r\n public ChartRenderingInfo() {\r\n this(new StandardEntityCollection());\r\n }\r\n\r\n /**\r\n * Constructs a new instance. If an entity collection is supplied, it will\r\n * be populated with information about the entities in a chart. If it is\r\n * <code>null</code>, no entity information (including tool tips) will\r\n * be collected.\r\n *\r\n * @param entities an entity collection (<code>null</code> permitted).\r\n */\r\n public ChartRenderingInfo(EntityCollection entities) {\r\n this.chartArea = new Rectangle2D.Double();\r\n this.plotInfo = new PlotRenderingInfo(this);\r\n this.entities = entities;\r\n }\r\n\r\n /**\r\n * Returns the area in which the chart was drawn.\r\n *\r\n * @return The area in which the chart was drawn.\r\n *\r\n * @see #setChartArea(Rectangle2D)\r\n */\r\n public Rectangle2D getChartArea() {\r\n return this.chartArea;\r\n }\r\n\r\n /**\r\n * Sets the area in which the chart was drawn.\r\n *\r\n * @param area the chart area.\r\n *\r\n * @see #getChartArea()\r\n */\r\n public void setChartArea(Rectangle2D area) {\r\n this.chartArea.setRect(area);\r\n }\r\n\r\n /**\r\n * Returns the collection of entities maintained by this instance.\r\n *\r\n * @return The entity collection (possibly <code>null</code>).\r\n *\r\n * @see #setEntityCollection(EntityCollection)\r\n */\r\n public EntityCollection getEntityCollection() {\r\n return this.entities;\r\n }\r\n\r\n /**\r\n * Sets the entity collection.\r\n *\r\n * @param entities the entity collection (<code>null</code> permitted).\r\n *\r\n * @see #getEntityCollection()\r\n */\r\n public void setEntityCollection(EntityCollection entities) {\r\n this.entities = entities;\r\n }\r\n\r\n /**\r\n * Clears the information recorded by this object.\r\n */\r\n public void clear() {\r\n this.chartArea.setRect(0.0, 0.0, 0.0, 0.0);\r\n this.plotInfo = new PlotRenderingInfo(this);\r\n if (this.entities != null) {\r\n this.entities.clear();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the rendering info for the chart's plot.\r\n *\r\n * @return The rendering info for the plot.\r\n */\r\n public PlotRenderingInfo getPlotInfo() {\r\n return this.plotInfo;\r\n }\r\n\r\n /**\r\n * Tests this object for equality with an arbitrary object.\r\n *\r\n * @param obj the object to test against (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof ChartRenderingInfo)) {\r\n return false;\r\n }\r\n ChartRenderingInfo that = (ChartRenderingInfo) obj;\r\n if (!ObjectUtilities.equal(this.chartArea, that.chartArea)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.plotInfo, that.plotInfo)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.entities, that.entities)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a clone of this object.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the object cannot be cloned.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n ChartRenderingInfo clone = (ChartRenderingInfo) super.clone();\r\n if (this.chartArea != null) {\r\n clone.chartArea = (Rectangle2D) this.chartArea.clone();\r\n }\r\n if (this.entities instanceof PublicCloneable) {\r\n PublicCloneable pc = (PublicCloneable) this.entities;\r\n clone.entities = (EntityCollection) pc.clone();\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeShape(this.chartArea, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.chartArea = (Rectangle2D) SerialUtilities.readShape(stream);\r\n }\r\n\r\n}\r" }, { "identifier": "ChartUtilities", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/ChartUtilities.java", "snippet": "public abstract class ChartUtilities {\r\n\r\n /**\r\n * Applies the current theme to the specified chart. This method is\r\n * provided for convenience, the theme itself is stored in the\r\n * {@link ChartFactory} class.\r\n *\r\n * @param chart the chart (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public static void applyCurrentTheme(JFreeChart chart) {\r\n ChartFactory.getChartTheme().apply(chart);\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in PNG format.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsPNG(OutputStream out, JFreeChart chart,\r\n int width, int height) throws IOException {\r\n\r\n // defer argument checking...\r\n writeChartAsPNG(out, chart, width, height, null);\r\n\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in PNG format.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param encodeAlpha encode alpha?\r\n * @param compression the compression level (0-9).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsPNG(OutputStream out, JFreeChart chart,\r\n int width, int height, boolean encodeAlpha, int compression)\r\n throws IOException {\r\n\r\n // defer argument checking...\r\n ChartUtilities.writeChartAsPNG(out, chart, width, height, null,\r\n encodeAlpha, compression);\r\n\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in PNG format. This method allows\r\n * you to pass in a {@link ChartRenderingInfo} object, to collect\r\n * information about the chart dimensions/entities. You will need this\r\n * info if you want to create an HTML image map.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info the chart rendering info (<code>null</code> permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsPNG(OutputStream out, JFreeChart chart,\r\n int width, int height, ChartRenderingInfo info)\r\n throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n BufferedImage bufferedImage\r\n = chart.createBufferedImage(width, height, info);\r\n EncoderUtil.writeBufferedImage(bufferedImage, ImageFormat.PNG, out);\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in PNG format. This method allows\r\n * you to pass in a {@link ChartRenderingInfo} object, to collect\r\n * information about the chart dimensions/entities. You will need this\r\n * info if you want to create an HTML image map.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info carries back chart rendering info (<code>null</code>\r\n * permitted).\r\n * @param encodeAlpha encode alpha?\r\n * @param compression the PNG compression level (0-9).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsPNG(OutputStream out, JFreeChart chart,\r\n int width, int height, ChartRenderingInfo info,\r\n boolean encodeAlpha, int compression) throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(out, \"out\");\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n BufferedImage chartImage = chart.createBufferedImage(width, height,\r\n BufferedImage.TYPE_INT_ARGB, info);\r\n ChartUtilities.writeBufferedImageAsPNG(out, chartImage, encodeAlpha,\r\n compression);\r\n\r\n }\r\n\r\n /**\r\n * Writes a scaled version of a chart to an output stream in PNG format.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the unscaled chart width.\r\n * @param height the unscaled chart height.\r\n * @param widthScaleFactor the horizontal scale factor.\r\n * @param heightScaleFactor the vertical scale factor.\r\n *\r\n * @throws IOException if there are any I/O problems.\r\n */\r\n public static void writeScaledChartAsPNG(OutputStream out,\r\n JFreeChart chart, int width, int height, int widthScaleFactor,\r\n int heightScaleFactor) throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(out, \"out\");\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n\r\n double desiredWidth = width * widthScaleFactor;\r\n double desiredHeight = height * heightScaleFactor;\r\n double defaultWidth = width;\r\n double defaultHeight = height;\r\n boolean scale = false;\r\n\r\n // get desired width and height from somewhere then...\r\n if ((widthScaleFactor != 1) || (heightScaleFactor != 1)) {\r\n scale = true;\r\n }\r\n\r\n double scaleX = desiredWidth / defaultWidth;\r\n double scaleY = desiredHeight / defaultHeight;\r\n\r\n BufferedImage image = new BufferedImage((int) desiredWidth,\r\n (int) desiredHeight, BufferedImage.TYPE_INT_ARGB);\r\n Graphics2D g2 = image.createGraphics();\r\n\r\n if (scale) {\r\n AffineTransform saved = g2.getTransform();\r\n g2.transform(AffineTransform.getScaleInstance(scaleX, scaleY));\r\n chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth,\r\n defaultHeight), null, null);\r\n g2.setTransform(saved);\r\n g2.dispose();\r\n }\r\n else {\r\n chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth,\r\n defaultHeight), null, null);\r\n }\r\n out.write(encodeAsPNG(image));\r\n\r\n }\r\n\r\n /**\r\n * Saves a chart to the specified file in PNG format.\r\n *\r\n * @param file the file name (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void saveChartAsPNG(File file, JFreeChart chart,\r\n int width, int height) throws IOException {\r\n\r\n // defer argument checking...\r\n saveChartAsPNG(file, chart, width, height, null);\r\n\r\n }\r\n\r\n /**\r\n * Saves a chart to a file in PNG format. This method allows you to pass\r\n * in a {@link ChartRenderingInfo} object, to collect information about the\r\n * chart dimensions/entities. You will need this info if you want to\r\n * create an HTML image map.\r\n *\r\n * @param file the file (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info the chart rendering info (<code>null</code> permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void saveChartAsPNG(File file, JFreeChart chart,\r\n int width, int height, ChartRenderingInfo info)\r\n throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(file, \"file\");\r\n OutputStream out = new BufferedOutputStream(new FileOutputStream(file));\r\n try {\r\n ChartUtilities.writeChartAsPNG(out, chart, width, height, info);\r\n }\r\n finally {\r\n out.close();\r\n }\r\n }\r\n\r\n /**\r\n * Saves a chart to a file in PNG format. This method allows you to pass\r\n * in a {@link ChartRenderingInfo} object, to collect information about the\r\n * chart dimensions/entities. You will need this info if you want to\r\n * create an HTML image map.\r\n *\r\n * @param file the file (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info the chart rendering info (<code>null</code> permitted).\r\n * @param encodeAlpha encode alpha?\r\n * @param compression the PNG compression level (0-9).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void saveChartAsPNG(File file, JFreeChart chart,\r\n int width, int height, ChartRenderingInfo info, boolean encodeAlpha,\r\n int compression) throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(file, \"file\");\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n OutputStream out = new BufferedOutputStream(new FileOutputStream(file));\r\n try {\r\n writeChartAsPNG(out, chart, width, height, info, encodeAlpha,\r\n compression);\r\n }\r\n finally {\r\n out.close();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in JPEG format. Please note that\r\n * JPEG is a poor format for chart images, use PNG if possible.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsJPEG(OutputStream out,\r\n JFreeChart chart, int width, int height) throws IOException {\r\n\r\n // defer argument checking...\r\n writeChartAsJPEG(out, chart, width, height, null);\r\n\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in JPEG format. Please note that\r\n * JPEG is a poor format for chart images, use PNG if possible.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param quality the quality setting.\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsJPEG(OutputStream out, float quality,\r\n JFreeChart chart, int width, int height) throws IOException {\r\n\r\n // defer argument checking...\r\n ChartUtilities.writeChartAsJPEG(out, quality, chart, width, height,\r\n null);\r\n\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in JPEG format. This method allows\r\n * you to pass in a {@link ChartRenderingInfo} object, to collect\r\n * information about the chart dimensions/entities. You will need this\r\n * info if you want to create an HTML image map.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info the chart rendering info (<code>null</code> permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsJPEG(OutputStream out, JFreeChart chart,\r\n int width, int height, ChartRenderingInfo info)\r\n throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(out, \"out\");\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n BufferedImage image = chart.createBufferedImage(width, height,\r\n BufferedImage.TYPE_INT_RGB, info);\r\n EncoderUtil.writeBufferedImage(image, ImageFormat.JPEG, out);\r\n\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in JPEG format. This method allows\r\n * you to pass in a {@link ChartRenderingInfo} object, to collect\r\n * information about the chart dimensions/entities. You will need this\r\n * info if you want to create an HTML image map.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param quality the output quality (0.0f to 1.0f).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info the chart rendering info (<code>null</code> permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsJPEG(OutputStream out, float quality,\r\n JFreeChart chart, int width, int height, ChartRenderingInfo info)\r\n throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(out, \"out\");\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n BufferedImage image = chart.createBufferedImage(width, height,\r\n BufferedImage.TYPE_INT_RGB, info);\r\n EncoderUtil.writeBufferedImage(image, ImageFormat.JPEG, out, quality);\r\n\r\n }\r\n\r\n /**\r\n * Saves a chart to a file in JPEG format.\r\n *\r\n * @param file the file (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void saveChartAsJPEG(File file, JFreeChart chart,\r\n int width, int height) throws IOException {\r\n\r\n // defer argument checking...\r\n saveChartAsJPEG(file, chart, width, height, null);\r\n\r\n }\r\n\r\n /**\r\n * Saves a chart to a file in JPEG format.\r\n *\r\n * @param file the file (<code>null</code> not permitted).\r\n * @param quality the JPEG quality setting.\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void saveChartAsJPEG(File file, float quality,\r\n JFreeChart chart, int width, int height) throws IOException {\r\n\r\n // defer argument checking...\r\n saveChartAsJPEG(file, quality, chart, width, height, null);\r\n\r\n }\r\n\r\n /**\r\n * Saves a chart to a file in JPEG format. This method allows you to pass\r\n * in a {@link ChartRenderingInfo} object, to collect information about the\r\n * chart dimensions/entities. You will need this info if you want to\r\n * create an HTML image map.\r\n *\r\n * @param file the file name (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info the chart rendering info (<code>null</code> permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void saveChartAsJPEG(File file, JFreeChart chart,\r\n int width, int height, ChartRenderingInfo info) throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(file, \"file\");\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n OutputStream out = new BufferedOutputStream(new FileOutputStream(file));\r\n try {\r\n writeChartAsJPEG(out, chart, width, height, info);\r\n }\r\n finally {\r\n out.close();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Saves a chart to a file in JPEG format. This method allows you to pass\r\n * in a {@link ChartRenderingInfo} object, to collect information about the\r\n * chart dimensions/entities. You will need this info if you want to\r\n * create an HTML image map.\r\n *\r\n * @param file the file name (<code>null</code> not permitted).\r\n * @param quality the quality setting.\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info the chart rendering info (<code>null</code> permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void saveChartAsJPEG(File file, float quality,\r\n JFreeChart chart, int width, int height,\r\n ChartRenderingInfo info) throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(file, \"file\");\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n OutputStream out = new BufferedOutputStream(new FileOutputStream(\r\n file));\r\n try {\r\n writeChartAsJPEG(out, quality, chart, width, height, info);\r\n }\r\n finally {\r\n out.close();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Writes a {@link BufferedImage} to an output stream in JPEG format.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param image the image (<code>null</code> not permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeBufferedImageAsJPEG(OutputStream out,\r\n BufferedImage image) throws IOException {\r\n\r\n // defer argument checking...\r\n writeBufferedImageAsJPEG(out, 0.75f, image);\r\n\r\n }\r\n\r\n /**\r\n * Writes a {@link BufferedImage} to an output stream in JPEG format.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param quality the image quality (0.0f to 1.0f).\r\n * @param image the image (<code>null</code> not permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeBufferedImageAsJPEG(OutputStream out, float quality,\r\n BufferedImage image) throws IOException {\r\n\r\n EncoderUtil.writeBufferedImage(image, ImageFormat.JPEG, out, quality);\r\n\r\n }\r\n\r\n /**\r\n * Writes a {@link BufferedImage} to an output stream in PNG format.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param image the image (<code>null</code> not permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeBufferedImageAsPNG(OutputStream out,\r\n BufferedImage image) throws IOException {\r\n\r\n EncoderUtil.writeBufferedImage(image, ImageFormat.PNG, out);\r\n\r\n }\r\n\r\n /**\r\n * Writes a {@link BufferedImage} to an output stream in PNG format.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param image the image (<code>null</code> not permitted).\r\n * @param encodeAlpha encode alpha?\r\n * @param compression the compression level (0-9).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeBufferedImageAsPNG(OutputStream out,\r\n BufferedImage image, boolean encodeAlpha, int compression)\r\n throws IOException {\r\n\r\n EncoderUtil.writeBufferedImage(image, ImageFormat.PNG, out,\r\n compression, encodeAlpha);\r\n }\r\n\r\n /**\r\n * Encodes a {@link BufferedImage} to PNG format.\r\n *\r\n * @param image the image (<code>null</code> not permitted).\r\n *\r\n * @return A byte array in PNG format.\r\n *\r\n * @throws IOException if there is an I/O problem.\r\n */\r\n public static byte[] encodeAsPNG(BufferedImage image) throws IOException {\r\n return EncoderUtil.encode(image, ImageFormat.PNG);\r\n }\r\n\r\n /**\r\n * Encodes a {@link BufferedImage} to PNG format.\r\n *\r\n * @param image the image (<code>null</code> not permitted).\r\n * @param encodeAlpha encode alpha?\r\n * @param compression the PNG compression level (0-9).\r\n *\r\n * @return The byte array in PNG format.\r\n *\r\n * @throws IOException if there is an I/O problem.\r\n */\r\n public static byte[] encodeAsPNG(BufferedImage image, boolean encodeAlpha,\r\n int compression) throws IOException {\r\n return EncoderUtil.encode(image, ImageFormat.PNG, compression,\r\n encodeAlpha);\r\n }\r\n\r\n /**\r\n * Writes an image map to an output stream.\r\n *\r\n * @param writer the writer (<code>null</code> not permitted).\r\n * @param name the map name (<code>null</code> not permitted).\r\n * @param info the chart rendering info (<code>null</code> not permitted).\r\n * @param useOverLibForToolTips whether to use OverLIB for tooltips\r\n * (http://www.bosrup.com/web/overlib/).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeImageMap(PrintWriter writer, String name,\r\n ChartRenderingInfo info, boolean useOverLibForToolTips)\r\n throws IOException {\r\n\r\n ToolTipTagFragmentGenerator toolTipTagFragmentGenerator;\r\n if (useOverLibForToolTips) {\r\n toolTipTagFragmentGenerator\r\n = new OverLIBToolTipTagFragmentGenerator();\r\n }\r\n else {\r\n toolTipTagFragmentGenerator\r\n = new StandardToolTipTagFragmentGenerator();\r\n }\r\n ImageMapUtilities.writeImageMap(writer, name, info,\r\n toolTipTagFragmentGenerator,\r\n new StandardURLTagFragmentGenerator());\r\n\r\n }\r\n\r\n /**\r\n * Writes an image map to the specified writer.\r\n *\r\n * @param writer the writer (<code>null</code> not permitted).\r\n * @param name the map name (<code>null</code> not permitted).\r\n * @param info the chart rendering info (<code>null</code> not permitted).\r\n * @param toolTipTagFragmentGenerator a generator for the HTML fragment\r\n * that will contain the tooltip text (<code>null</code> not permitted\r\n * if <code>info</code> contains tooltip information).\r\n * @param urlTagFragmentGenerator a generator for the HTML fragment that\r\n * will contain the URL reference (<code>null</code> not permitted if\r\n * <code>info</code> contains URLs).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeImageMap(PrintWriter writer, String name,\r\n ChartRenderingInfo info,\r\n ToolTipTagFragmentGenerator toolTipTagFragmentGenerator,\r\n URLTagFragmentGenerator urlTagFragmentGenerator)\r\n throws IOException {\r\n\r\n writer.println(ImageMapUtilities.getImageMap(name, info,\r\n toolTipTagFragmentGenerator, urlTagFragmentGenerator));\r\n }\r\n\r\n /**\r\n * Creates an HTML image map. This method maps to\r\n * {@link ImageMapUtilities#getImageMap(String, ChartRenderingInfo,\r\n * ToolTipTagFragmentGenerator, URLTagFragmentGenerator)}, using default\r\n * generators.\r\n *\r\n * @param name the map name (<code>null</code> not permitted).\r\n * @param info the chart rendering info (<code>null</code> not permitted).\r\n *\r\n * @return The map tag.\r\n */\r\n public static String getImageMap(String name, ChartRenderingInfo info) {\r\n return ImageMapUtilities.getImageMap(name, info,\r\n new StandardToolTipTagFragmentGenerator(),\r\n new StandardURLTagFragmentGenerator());\r\n }\r\n\r\n /**\r\n * Creates an HTML image map. This method maps directly to\r\n * {@link ImageMapUtilities#getImageMap(String, ChartRenderingInfo,\r\n * ToolTipTagFragmentGenerator, URLTagFragmentGenerator)}.\r\n *\r\n * @param name the map name (<code>null</code> not permitted).\r\n * @param info the chart rendering info (<code>null</code> not permitted).\r\n * @param toolTipTagFragmentGenerator a generator for the HTML fragment\r\n * that will contain the tooltip text (<code>null</code> not permitted\r\n * if <code>info</code> contains tooltip information).\r\n * @param urlTagFragmentGenerator a generator for the HTML fragment that\r\n * will contain the URL reference (<code>null</code> not permitted if\r\n * <code>info</code> contains URLs).\r\n *\r\n * @return The map tag.\r\n */\r\n public static String getImageMap(String name, ChartRenderingInfo info,\r\n ToolTipTagFragmentGenerator toolTipTagFragmentGenerator,\r\n URLTagFragmentGenerator urlTagFragmentGenerator) {\r\n\r\n return ImageMapUtilities.getImageMap(name, info,\r\n toolTipTagFragmentGenerator, urlTagFragmentGenerator);\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "JFreeChart", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/JFreeChart.java", "snippet": "public class JFreeChart implements Drawable, TitleChangeListener,\r\n PlotChangeListener, Serializable, Cloneable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -3470703747817429120L;\r\n\r\n /** Information about the project. */\r\n public static final ProjectInfo INFO = new JFreeChartInfo();\r\n\r\n /** The default font for titles. */\r\n public static final Font DEFAULT_TITLE_FONT\r\n = new Font(\"SansSerif\", Font.BOLD, 18);\r\n\r\n /** The default background color. */\r\n public static final Paint DEFAULT_BACKGROUND_PAINT\r\n = UIManager.getColor(\"Panel.background\");\r\n\r\n /** The default background image. */\r\n public static final Image DEFAULT_BACKGROUND_IMAGE = null;\r\n\r\n /** The default background image alignment. */\r\n public static final int DEFAULT_BACKGROUND_IMAGE_ALIGNMENT = Align.FIT;\r\n\r\n /** The default background image alpha. */\r\n public static final float DEFAULT_BACKGROUND_IMAGE_ALPHA = 0.5f;\r\n\r\n /**\r\n * The key for a rendering hint that can suppress the generation of a \r\n * shadow effect when drawing the chart. The hint value must be a \r\n * Boolean.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static final RenderingHints.Key KEY_SUPPRESS_SHADOW_GENERATION\r\n = new RenderingHints.Key(0) {\r\n @Override\r\n public boolean isCompatibleValue(Object val) {\r\n return val instanceof Boolean;\r\n }\r\n };\r\n \r\n /**\r\n * Rendering hints that will be used for chart drawing. This should never\r\n * be <code>null</code>.\r\n */\r\n private transient RenderingHints renderingHints;\r\n\r\n /** A flag that controls whether or not the chart border is drawn. */\r\n private boolean borderVisible;\r\n\r\n /** The stroke used to draw the chart border (if visible). */\r\n private transient Stroke borderStroke;\r\n\r\n /** The paint used to draw the chart border (if visible). */\r\n private transient Paint borderPaint;\r\n\r\n /** The padding between the chart border and the chart drawing area. */\r\n private RectangleInsets padding;\r\n\r\n /** The chart title (optional). */\r\n private TextTitle title;\r\n\r\n /**\r\n * The chart subtitles (zero, one or many). This field should never be\r\n * <code>null</code>.\r\n */\r\n private List subtitles;\r\n\r\n /** Draws the visual representation of the data. */\r\n private Plot plot;\r\n\r\n /** Paint used to draw the background of the chart. */\r\n private transient Paint backgroundPaint;\r\n\r\n /** An optional background image for the chart. */\r\n private transient Image backgroundImage; // todo: not serialized yet\r\n\r\n /** The alignment for the background image. */\r\n private int backgroundImageAlignment = Align.FIT;\r\n\r\n /** The alpha transparency for the background image. */\r\n private float backgroundImageAlpha = 0.5f;\r\n\r\n /** Storage for registered change listeners. */\r\n private transient EventListenerList changeListeners;\r\n\r\n /** Storage for registered progress listeners. */\r\n private transient EventListenerList progressListeners;\r\n\r\n /**\r\n * A flag that can be used to enable/disable notification of chart change\r\n * events.\r\n */\r\n private boolean notify;\r\n\r\n /**\r\n * Creates a new chart based on the supplied plot. The chart will have\r\n * a legend added automatically, but no title (although you can easily add\r\n * one later).\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(Plot plot) {\r\n this(null, null, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. A default font\r\n * ({@link #DEFAULT_TITLE_FONT}) is used for the title, and the chart will\r\n * have a legend added automatically.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(String title, Plot plot) {\r\n this(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. The\r\n * <code>createLegend</code> argument specifies whether or not a legend\r\n * should be added to the chart.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param titleFont the font for displaying the chart title\r\n * (<code>null</code> permitted).\r\n * @param plot controller of the visual representation of the data\r\n * (<code>null</code> not permitted).\r\n * @param createLegend a flag indicating whether or not a legend should\r\n * be created for the chart.\r\n */\r\n public JFreeChart(String title, Font titleFont, Plot plot,\r\n boolean createLegend) {\r\n\r\n ParamChecks.nullNotPermitted(plot, \"plot\");\r\n\r\n // create storage for listeners...\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.notify = true; // default is to notify listeners when the\r\n // chart changes\r\n\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n // added the following hint because of \r\n // http://stackoverflow.com/questions/7785082/\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n this.borderVisible = false;\r\n this.borderStroke = new BasicStroke(1.0f);\r\n this.borderPaint = Color.black;\r\n\r\n this.padding = RectangleInsets.ZERO_INSETS;\r\n\r\n this.plot = plot;\r\n plot.addChangeListener(this);\r\n\r\n this.subtitles = new ArrayList();\r\n\r\n // create a legend, if requested...\r\n if (createLegend) {\r\n LegendTitle legend = new LegendTitle(this.plot);\r\n legend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));\r\n legend.setFrame(new LineBorder());\r\n legend.setBackgroundPaint(Color.white);\r\n legend.setPosition(RectangleEdge.BOTTOM);\r\n this.subtitles.add(legend);\r\n legend.addChangeListener(this);\r\n }\r\n\r\n // add the chart title, if one has been specified...\r\n if (title != null) {\r\n if (titleFont == null) {\r\n titleFont = DEFAULT_TITLE_FONT;\r\n }\r\n this.title = new TextTitle(title, titleFont);\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n this.backgroundPaint = DEFAULT_BACKGROUND_PAINT;\r\n\r\n this.backgroundImage = DEFAULT_BACKGROUND_IMAGE;\r\n this.backgroundImageAlignment = DEFAULT_BACKGROUND_IMAGE_ALIGNMENT;\r\n this.backgroundImageAlpha = DEFAULT_BACKGROUND_IMAGE_ALPHA;\r\n\r\n }\r\n\r\n /**\r\n * Returns the collection of rendering hints for the chart.\r\n *\r\n * @return The rendering hints for the chart (never <code>null</code>).\r\n *\r\n * @see #setRenderingHints(RenderingHints)\r\n */\r\n public RenderingHints getRenderingHints() {\r\n return this.renderingHints;\r\n }\r\n\r\n /**\r\n * Sets the rendering hints for the chart. These will be added (using the\r\n * {@code Graphics2D.addRenderingHints()} method) near the start of the\r\n * {@code JFreeChart.draw()} method.\r\n *\r\n * @param renderingHints the rendering hints ({@code null} not permitted).\r\n *\r\n * @see #getRenderingHints()\r\n */\r\n public void setRenderingHints(RenderingHints renderingHints) {\r\n ParamChecks.nullNotPermitted(renderingHints, \"renderingHints\");\r\n this.renderingHints = renderingHints;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setBorderVisible(boolean)\r\n */\r\n public boolean isBorderVisible() {\r\n return this.borderVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isBorderVisible()\r\n */\r\n public void setBorderVisible(boolean visible) {\r\n this.borderVisible = visible;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the chart border (if visible).\r\n *\r\n * @return The border stroke.\r\n *\r\n * @see #setBorderStroke(Stroke)\r\n */\r\n public Stroke getBorderStroke() {\r\n return this.borderStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the chart border (if visible).\r\n *\r\n * @param stroke the stroke.\r\n *\r\n * @see #getBorderStroke()\r\n */\r\n public void setBorderStroke(Stroke stroke) {\r\n this.borderStroke = stroke;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the chart border (if visible).\r\n *\r\n * @return The border paint.\r\n *\r\n * @see #setBorderPaint(Paint)\r\n */\r\n public Paint getBorderPaint() {\r\n return this.borderPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the chart border (if visible).\r\n *\r\n * @param paint the paint.\r\n *\r\n * @see #getBorderPaint()\r\n */\r\n public void setBorderPaint(Paint paint) {\r\n this.borderPaint = paint;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the padding between the chart border and the chart drawing area.\r\n *\r\n * @return The padding (never <code>null</code>).\r\n *\r\n * @see #setPadding(RectangleInsets)\r\n */\r\n public RectangleInsets getPadding() {\r\n return this.padding;\r\n }\r\n\r\n /**\r\n * Sets the padding between the chart border and the chart drawing area,\r\n * and sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param padding the padding (<code>null</code> not permitted).\r\n *\r\n * @see #getPadding()\r\n */\r\n public void setPadding(RectangleInsets padding) {\r\n ParamChecks.nullNotPermitted(padding, \"padding\");\r\n this.padding = padding;\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the main chart title. Very often a chart will have just one\r\n * title, so we make this case simple by providing accessor methods for\r\n * the main title. However, multiple titles are supported - see the\r\n * {@link #addSubtitle(Title)} method.\r\n *\r\n * @return The chart title (possibly <code>null</code>).\r\n *\r\n * @see #setTitle(TextTitle)\r\n */\r\n public TextTitle getTitle() {\r\n return this.title;\r\n }\r\n\r\n /**\r\n * Sets the main title for the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners. If you do not want a title for the\r\n * chart, set it to <code>null</code>. If you want more than one title on\r\n * a chart, use the {@link #addSubtitle(Title)} method.\r\n *\r\n * @param title the title (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(TextTitle title) {\r\n if (this.title != null) {\r\n this.title.removeChangeListener(this);\r\n }\r\n this.title = title;\r\n if (title != null) {\r\n title.addChangeListener(this);\r\n }\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Sets the chart title and sends a {@link ChartChangeEvent} to all\r\n * registered listeners. This is a convenience method that ends up calling\r\n * the {@link #setTitle(TextTitle)} method. If there is an existing title,\r\n * its text is updated, otherwise a new title using the default font is\r\n * added to the chart. If <code>text</code> is <code>null</code> the chart\r\n * title is set to <code>null</code>.\r\n *\r\n * @param text the title text (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(String text) {\r\n if (text != null) {\r\n if (this.title == null) {\r\n setTitle(new TextTitle(text, JFreeChart.DEFAULT_TITLE_FONT));\r\n }\r\n else {\r\n this.title.setText(text);\r\n }\r\n }\r\n else {\r\n setTitle((TextTitle) null);\r\n }\r\n }\r\n\r\n /**\r\n * Adds a legend to the plot and sends a {@link ChartChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param legend the legend (<code>null</code> not permitted).\r\n *\r\n * @see #removeLegend()\r\n */\r\n public void addLegend(LegendTitle legend) {\r\n addSubtitle(legend);\r\n }\r\n\r\n /**\r\n * Returns the legend for the chart, if there is one. Note that a chart\r\n * can have more than one legend - this method returns the first.\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #getLegend(int)\r\n */\r\n public LegendTitle getLegend() {\r\n return getLegend(0);\r\n }\r\n\r\n /**\r\n * Returns the nth legend for a chart, or <code>null</code>.\r\n *\r\n * @param index the legend index (zero-based).\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #addLegend(LegendTitle)\r\n */\r\n public LegendTitle getLegend(int index) {\r\n int seen = 0;\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title subtitle = (Title) iterator.next();\r\n if (subtitle instanceof LegendTitle) {\r\n if (seen == index) {\r\n return (LegendTitle) subtitle;\r\n }\r\n else {\r\n seen++;\r\n }\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Removes the first legend in the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @see #getLegend()\r\n */\r\n public void removeLegend() {\r\n removeSubtitle(getLegend());\r\n }\r\n\r\n /**\r\n * Returns the list of subtitles for the chart.\r\n *\r\n * @return The subtitle list (possibly empty, but never <code>null</code>).\r\n *\r\n * @see #setSubtitles(List)\r\n */\r\n public List getSubtitles() {\r\n return new ArrayList(this.subtitles);\r\n }\r\n\r\n /**\r\n * Sets the title list for the chart (completely replaces any existing\r\n * titles) and sends a {@link ChartChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param subtitles the new list of subtitles (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public void setSubtitles(List subtitles) {\r\n if (subtitles == null) {\r\n throw new NullPointerException(\"Null 'subtitles' argument.\");\r\n }\r\n setNotify(false);\r\n clearSubtitles();\r\n Iterator iterator = subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n if (t != null) {\r\n addSubtitle(t);\r\n }\r\n }\r\n setNotify(true); // this fires a ChartChangeEvent\r\n }\r\n\r\n /**\r\n * Returns the number of titles for the chart.\r\n *\r\n * @return The number of titles for the chart.\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public int getSubtitleCount() {\r\n return this.subtitles.size();\r\n }\r\n\r\n /**\r\n * Returns a chart subtitle.\r\n *\r\n * @param index the index of the chart subtitle (zero based).\r\n *\r\n * @return A chart subtitle.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public Title getSubtitle(int index) {\r\n if ((index < 0) || (index >= getSubtitleCount())) {\r\n throw new IllegalArgumentException(\"Index out of range.\");\r\n }\r\n return (Title) this.subtitles.get(index);\r\n }\r\n\r\n /**\r\n * Adds a chart subtitle, and notifies registered listeners that the chart\r\n * has been modified.\r\n *\r\n * @param subtitle the subtitle (<code>null</code> not permitted).\r\n *\r\n * @see #getSubtitle(int)\r\n */\r\n public void addSubtitle(Title subtitle) {\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Adds a subtitle at a particular position in the subtitle list, and sends\r\n * a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param index the index (in the range 0 to {@link #getSubtitleCount()}).\r\n * @param subtitle the subtitle to add (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.6\r\n */\r\n public void addSubtitle(int index, Title subtitle) {\r\n if (index < 0 || index > getSubtitleCount()) {\r\n throw new IllegalArgumentException(\r\n \"The 'index' argument is out of range.\");\r\n }\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(index, subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Clears all subtitles from the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void clearSubtitles() {\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n t.removeChangeListener(this);\r\n }\r\n this.subtitles.clear();\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Removes the specified subtitle and sends a {@link ChartChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param title the title.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void removeSubtitle(Title title) {\r\n this.subtitles.remove(title);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the plot for the chart. The plot is a class responsible for\r\n * coordinating the visual representation of the data, including the axes\r\n * (if any).\r\n *\r\n * @return The plot.\r\n */\r\n public Plot getPlot() {\r\n return this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as a {@link CategoryPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link CategoryPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public CategoryPlot getCategoryPlot() {\r\n return (CategoryPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as an {@link XYPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link XYPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public XYPlot getXYPlot() {\r\n return (XYPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns a flag that indicates whether or not anti-aliasing is used when\r\n * the chart is drawn.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAntiAlias(boolean)\r\n */\r\n public boolean getAntiAlias() {\r\n Object val = this.renderingHints.get(RenderingHints.KEY_ANTIALIASING);\r\n return RenderingHints.VALUE_ANTIALIAS_ON.equals(val);\r\n }\r\n\r\n /**\r\n * Sets a flag that indicates whether or not anti-aliasing is used when the\r\n * chart is drawn.\r\n * <P>\r\n * Anti-aliasing usually improves the appearance of charts, but is slower.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #getAntiAlias()\r\n */\r\n public void setAntiAlias(boolean flag) {\r\n Object hint = flag ? RenderingHints.VALUE_ANTIALIAS_ON \r\n : RenderingHints.VALUE_ANTIALIAS_OFF;\r\n this.renderingHints.put(RenderingHints.KEY_ANTIALIASING, hint);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the current value stored in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING}.\r\n *\r\n * @return The hint value (possibly <code>null</code>).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public Object getTextAntiAlias() {\r\n return this.renderingHints.get(RenderingHints.KEY_TEXT_ANTIALIASING);\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} to either\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_ON} or\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_OFF}, then sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public void setTextAntiAlias(boolean flag) {\r\n if (flag) {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\r\n }\r\n else {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);\r\n }\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param val the new value (<code>null</code> permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(boolean)\r\n */\r\n public void setTextAntiAlias(Object val) {\r\n this.renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, val);\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the paint used for the chart background.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundPaint(Paint)\r\n */\r\n public Paint getBackgroundPaint() {\r\n return this.backgroundPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to fill the chart background and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundPaint()\r\n */\r\n public void setBackgroundPaint(Paint paint) {\r\n\r\n if (this.backgroundPaint != null) {\r\n if (!this.backgroundPaint.equals(paint)) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (paint != null) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image for the chart, or <code>null</code> if\r\n * there is no image.\r\n *\r\n * @return The image (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundImage(Image)\r\n */\r\n public Image getBackgroundImage() {\r\n return this.backgroundImage;\r\n }\r\n\r\n /**\r\n * Sets the background image for the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param image the image (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundImage()\r\n */\r\n public void setBackgroundImage(Image image) {\r\n\r\n if (this.backgroundImage != null) {\r\n if (!this.backgroundImage.equals(image)) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (image != null) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image alignment. Alignment constants are defined\r\n * in the <code>org.jfree.ui.Align</code> class in the JCommon class\r\n * library.\r\n *\r\n * @return The alignment.\r\n *\r\n * @see #setBackgroundImageAlignment(int)\r\n */\r\n public int getBackgroundImageAlignment() {\r\n return this.backgroundImageAlignment;\r\n }\r\n\r\n /**\r\n * Sets the background alignment. Alignment options are defined by the\r\n * {@link org.jfree.ui.Align} class.\r\n *\r\n * @param alignment the alignment.\r\n *\r\n * @see #getBackgroundImageAlignment()\r\n */\r\n public void setBackgroundImageAlignment(int alignment) {\r\n if (this.backgroundImageAlignment != alignment) {\r\n this.backgroundImageAlignment = alignment;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha-transparency for the chart's background image.\r\n *\r\n * @return The alpha-transparency.\r\n *\r\n * @see #setBackgroundImageAlpha(float)\r\n */\r\n public float getBackgroundImageAlpha() {\r\n return this.backgroundImageAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha-transparency for the chart's background image.\r\n * Registered listeners are notified that the chart has been changed.\r\n *\r\n * @param alpha the alpha value.\r\n *\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void setBackgroundImageAlpha(float alpha) {\r\n\r\n if (this.backgroundImageAlpha != alpha) {\r\n this.backgroundImageAlpha = alpha;\r\n fireChartChanged();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not change events are sent to\r\n * registered listeners.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNotify(boolean)\r\n */\r\n public boolean isNotify() {\r\n return this.notify;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not listeners receive\r\n * {@link ChartChangeEvent} notifications.\r\n *\r\n * @param notify a boolean.\r\n *\r\n * @see #isNotify()\r\n */\r\n public void setNotify(boolean notify) {\r\n this.notify = notify;\r\n // if the flag is being set to true, there may be queued up changes...\r\n if (notify) {\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area) {\r\n draw(g2, area, null, null);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer). This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D area, ChartRenderingInfo info) {\r\n draw(g2, area, null, info);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param chartArea the area within which the chart should be drawn.\r\n * @param anchor the anchor point (in Java2D space) for the chart\r\n * (<code>null</code> permitted).\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D chartArea, Point2D anchor,\r\n ChartRenderingInfo info) {\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_STARTED, 0));\r\n \r\n EntityCollection entities = null;\r\n // record the chart area, if info is requested...\r\n if (info != null) {\r\n info.clear();\r\n info.setChartArea(chartArea);\r\n entities = info.getEntityCollection();\r\n }\r\n if (entities != null) {\r\n entities.add(new JFreeChartEntity((Rectangle2D) chartArea.clone(),\r\n this));\r\n }\r\n\r\n // ensure no drawing occurs outside chart area...\r\n Shape savedClip = g2.getClip();\r\n g2.clip(chartArea);\r\n\r\n g2.addRenderingHints(this.renderingHints);\r\n\r\n // draw the chart background...\r\n if (this.backgroundPaint != null) {\r\n g2.setPaint(this.backgroundPaint);\r\n g2.fill(chartArea);\r\n }\r\n\r\n if (this.backgroundImage != null) {\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundImageAlpha));\r\n Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,\r\n this.backgroundImage.getWidth(null),\r\n this.backgroundImage.getHeight(null));\r\n Align.align(dest, chartArea, this.backgroundImageAlignment);\r\n g2.drawImage(this.backgroundImage, (int) dest.getX(),\r\n (int) dest.getY(), (int) dest.getWidth(),\r\n (int) dest.getHeight(), null);\r\n g2.setComposite(originalComposite);\r\n }\r\n\r\n if (isBorderVisible()) {\r\n Paint paint = getBorderPaint();\r\n Stroke stroke = getBorderStroke();\r\n if (paint != null && stroke != null) {\r\n Rectangle2D borderArea = new Rectangle2D.Double(\r\n chartArea.getX(), chartArea.getY(),\r\n chartArea.getWidth() - 1.0, chartArea.getHeight()\r\n - 1.0);\r\n g2.setPaint(paint);\r\n g2.setStroke(stroke);\r\n g2.draw(borderArea);\r\n }\r\n }\r\n\r\n // draw the title and subtitles...\r\n Rectangle2D nonTitleArea = new Rectangle2D.Double();\r\n nonTitleArea.setRect(chartArea);\r\n this.padding.trim(nonTitleArea);\r\n\r\n if (this.title != null && this.title.isVisible()) {\r\n EntityCollection e = drawTitle(this.title, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title currentTitle = (Title) iterator.next();\r\n if (currentTitle.isVisible()) {\r\n EntityCollection e = drawTitle(currentTitle, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n }\r\n\r\n Rectangle2D plotArea = nonTitleArea;\r\n\r\n // draw the plot (axes and data visualisation)\r\n PlotRenderingInfo plotInfo = null;\r\n if (info != null) {\r\n plotInfo = info.getPlotInfo();\r\n }\r\n this.plot.draw(g2, plotArea, anchor, null, plotInfo);\r\n\r\n g2.setClip(savedClip);\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_FINISHED, 100));\r\n }\r\n\r\n /**\r\n * Creates a rectangle that is aligned to the frame.\r\n *\r\n * @param dimensions the dimensions for the rectangle.\r\n * @param frame the frame to align to.\r\n * @param hAlign the horizontal alignment.\r\n * @param vAlign the vertical alignment.\r\n *\r\n * @return A rectangle.\r\n */\r\n private Rectangle2D createAlignedRectangle2D(Size2D dimensions,\r\n Rectangle2D frame, HorizontalAlignment hAlign,\r\n VerticalAlignment vAlign) {\r\n double x = Double.NaN;\r\n double y = Double.NaN;\r\n if (hAlign == HorizontalAlignment.LEFT) {\r\n x = frame.getX();\r\n }\r\n else if (hAlign == HorizontalAlignment.CENTER) {\r\n x = frame.getCenterX() - (dimensions.width / 2.0);\r\n }\r\n else if (hAlign == HorizontalAlignment.RIGHT) {\r\n x = frame.getMaxX() - dimensions.width;\r\n }\r\n if (vAlign == VerticalAlignment.TOP) {\r\n y = frame.getY();\r\n }\r\n else if (vAlign == VerticalAlignment.CENTER) {\r\n y = frame.getCenterY() - (dimensions.height / 2.0);\r\n }\r\n else if (vAlign == VerticalAlignment.BOTTOM) {\r\n y = frame.getMaxY() - dimensions.height;\r\n }\r\n\r\n return new Rectangle2D.Double(x, y, dimensions.width,\r\n dimensions.height);\r\n }\r\n\r\n /**\r\n * Draws a title. The title should be drawn at the top, bottom, left or\r\n * right of the specified area, and the area should be updated to reflect\r\n * the amount of space used by the title.\r\n *\r\n * @param t the title (<code>null</code> not permitted).\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param area the chart area, excluding any existing titles\r\n * (<code>null</code> not permitted).\r\n * @param entities a flag that controls whether or not an entity\r\n * collection is returned for the title.\r\n *\r\n * @return An entity collection for the title (possibly <code>null</code>).\r\n */\r\n protected EntityCollection drawTitle(Title t, Graphics2D g2,\r\n Rectangle2D area, boolean entities) {\r\n\r\n ParamChecks.nullNotPermitted(t, \"t\");\r\n ParamChecks.nullNotPermitted(area, \"area\");\r\n Rectangle2D titleArea;\r\n RectangleEdge position = t.getPosition();\r\n double ww = area.getWidth();\r\n if (ww <= 0.0) {\r\n return null;\r\n }\r\n double hh = area.getHeight();\r\n if (hh <= 0.0) {\r\n return null;\r\n }\r\n RectangleConstraint constraint = new RectangleConstraint(ww,\r\n new Range(0.0, ww), LengthConstraintType.RANGE, hh,\r\n new Range(0.0, hh), LengthConstraintType.RANGE);\r\n Object retValue = null;\r\n BlockParams p = new BlockParams();\r\n p.setGenerateEntities(entities);\r\n if (position == RectangleEdge.TOP) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.TOP);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), Math.min(area.getY() + size.height,\r\n area.getMaxY()), area.getWidth(), Math.max(area.getHeight()\r\n - size.height, 0));\r\n }\r\n else if (position == RectangleEdge.BOTTOM) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.BOTTOM);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth(),\r\n area.getHeight() - size.height);\r\n }\r\n else if (position == RectangleEdge.RIGHT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.RIGHT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n\r\n else if (position == RectangleEdge.LEFT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.LEFT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX() + size.width, area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n else {\r\n throw new RuntimeException(\"Unrecognised title position.\");\r\n }\r\n EntityCollection result = null;\r\n if (retValue instanceof EntityBlockResult) {\r\n EntityBlockResult ebr = (EntityBlockResult) retValue;\r\n result = ebr.getEntityCollection();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height) {\r\n return createBufferedImage(width, height, null);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n ChartRenderingInfo info) {\r\n return createBufferedImage(width, height, BufferedImage.TYPE_INT_ARGB,\r\n info);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param imageType the image type.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n int imageType,\r\n ChartRenderingInfo info) {\r\n BufferedImage image = new BufferedImage(width, height, imageType);\r\n Graphics2D g2 = image.createGraphics();\r\n draw(g2, new Rectangle2D.Double(0, 0, width, height), null, info);\r\n g2.dispose();\r\n return image;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param imageWidth the image width.\r\n * @param imageHeight the image height.\r\n * @param drawWidth the width for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param drawHeight the height for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param info optional object for collection chart dimension and entity\r\n * information.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int imageWidth,\r\n int imageHeight,\r\n double drawWidth,\r\n double drawHeight,\r\n ChartRenderingInfo info) {\r\n\r\n BufferedImage image = new BufferedImage(imageWidth, imageHeight,\r\n BufferedImage.TYPE_INT_ARGB);\r\n Graphics2D g2 = image.createGraphics();\r\n double scaleX = imageWidth / drawWidth;\r\n double scaleY = imageHeight / drawHeight;\r\n AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);\r\n g2.transform(st);\r\n draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,\r\n info);\r\n g2.dispose();\r\n return image;\r\n\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the chart. JFreeChart is not a UI component, so\r\n * some other object (for example, {@link ChartPanel}) needs to capture\r\n * the click event and pass it onto the JFreeChart object.\r\n * If you are not using JFreeChart in a client application, then this\r\n * method is not required.\r\n *\r\n * @param x x-coordinate of the click (in Java2D space).\r\n * @param y y-coordinate of the click (in Java2D space).\r\n * @param info contains chart dimension and entity information\r\n * (<code>null</code> not permitted).\r\n */\r\n public void handleClick(int x, int y, ChartRenderingInfo info) {\r\n\r\n // pass the click on to the plot...\r\n // rely on the plot to post a plot change event and redraw the chart...\r\n this.plot.handleClick(x, y, info.getPlotInfo());\r\n\r\n }\r\n\r\n /**\r\n * Registers an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted).\r\n *\r\n * @see #removeChangeListener(ChartChangeListener)\r\n */\r\n public void addChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.add(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted)\r\n *\r\n * @see #addChangeListener(ChartChangeListener)\r\n */\r\n public void removeChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.remove(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a default {@link ChartChangeEvent} to all registered listeners.\r\n * <P>\r\n * This method is for convenience only.\r\n */\r\n public void fireChartChanged() {\r\n ChartChangeEvent event = new ChartChangeEvent(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartChangeEvent event) {\r\n if (this.notify) {\r\n Object[] listeners = this.changeListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartChangeListener.class) {\r\n ((ChartChangeListener) listeners[i + 1]).chartChanged(\r\n event);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Registers an object for notification of progress events relating to the\r\n * chart.\r\n *\r\n * @param listener the object being registered.\r\n *\r\n * @see #removeProgressListener(ChartProgressListener)\r\n */\r\n public void addProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.add(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the object being deregistered.\r\n *\r\n * @see #addProgressListener(ChartProgressListener)\r\n */\r\n public void removeProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.remove(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartProgressEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartProgressEvent event) {\r\n\r\n Object[] listeners = this.progressListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartProgressListener.class) {\r\n ((ChartProgressListener) listeners[i + 1]).chartProgress(event);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Receives notification that a chart title has changed, and passes this\r\n * on to registered listeners.\r\n *\r\n * @param event information about the chart title change.\r\n */\r\n @Override\r\n public void titleChanged(TitleChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Receives notification that the plot has changed, and passes this on to\r\n * registered listeners.\r\n *\r\n * @param event information about the plot change.\r\n */\r\n @Override\r\n public void plotChanged(PlotChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Tests this chart for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof JFreeChart)) {\r\n return false;\r\n }\r\n JFreeChart that = (JFreeChart) obj;\r\n if (!this.renderingHints.equals(that.renderingHints)) {\r\n return false;\r\n }\r\n if (this.borderVisible != that.borderVisible) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.borderStroke, that.borderStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.borderPaint, that.borderPaint)) {\r\n return false;\r\n }\r\n if (!this.padding.equals(that.padding)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.title, that.title)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.subtitles, that.subtitles)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.plot, that.plot)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(\r\n this.backgroundPaint, that.backgroundPaint\r\n )) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundImage,\r\n that.backgroundImage)) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlignment != that.backgroundImageAlignment) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlpha != that.backgroundImageAlpha) {\r\n return false;\r\n }\r\n if (this.notify != that.notify) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.borderStroke, stream);\r\n SerialUtilities.writePaint(this.borderPaint, stream);\r\n SerialUtilities.writePaint(this.backgroundPaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.borderStroke = SerialUtilities.readStroke(stream);\r\n this.borderPaint = SerialUtilities.readPaint(stream);\r\n this.backgroundPaint = SerialUtilities.readPaint(stream);\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n // register as a listener with sub-components...\r\n if (this.title != null) {\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n getSubtitle(i).addChangeListener(this);\r\n }\r\n this.plot.addChangeListener(this);\r\n }\r\n\r\n /**\r\n * Prints information about JFreeChart to standard output.\r\n *\r\n * @param args no arguments are honored.\r\n */\r\n public static void main(String[] args) {\r\n System.out.println(JFreeChart.INFO.toString());\r\n }\r\n\r\n /**\r\n * Clones the object, and takes care of listeners.\r\n * Note: caller shall register its own listeners on cloned graph.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the chart is not cloneable.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n JFreeChart chart = (JFreeChart) super.clone();\r\n\r\n chart.renderingHints = (RenderingHints) this.renderingHints.clone();\r\n // private boolean borderVisible;\r\n // private transient Stroke borderStroke;\r\n // private transient Paint borderPaint;\r\n\r\n if (this.title != null) {\r\n chart.title = (TextTitle) this.title.clone();\r\n chart.title.addChangeListener(chart);\r\n }\r\n\r\n chart.subtitles = new ArrayList();\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n Title subtitle = (Title) getSubtitle(i).clone();\r\n chart.subtitles.add(subtitle);\r\n subtitle.addChangeListener(chart);\r\n }\r\n\r\n if (this.plot != null) {\r\n chart.plot = (Plot) this.plot.clone();\r\n chart.plot.addChangeListener(chart);\r\n }\r\n\r\n chart.progressListeners = new EventListenerList();\r\n chart.changeListeners = new EventListenerList();\r\n return chart;\r\n }\r\n\r\n}\r" }, { "identifier": "ChartEntity", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/entity/ChartEntity.java", "snippet": "public class ChartEntity implements Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -4445994133561919083L;\r\n\r\n /** The area occupied by the entity (in Java 2D space). */\r\n private transient Shape area;\r\n\r\n /** The tool tip text for the entity. */\r\n private String toolTipText;\r\n\r\n /** The URL text for the entity. */\r\n private String urlText;\r\n\r\n /**\r\n * Creates a new chart entity.\r\n *\r\n * @param area the area (<code>null</code> not permitted).\r\n */\r\n public ChartEntity(Shape area) {\r\n // defer argument checks...\r\n this(area, null);\r\n }\r\n\r\n /**\r\n * Creates a new chart entity.\r\n *\r\n * @param area the area (<code>null</code> not permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n */\r\n public ChartEntity(Shape area, String toolTipText) {\r\n // defer argument checks...\r\n this(area, toolTipText, null);\r\n }\r\n\r\n /**\r\n * Creates a new entity.\r\n *\r\n * @param area the area (<code>null</code> not permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text for HTML image maps (<code>null</code>\r\n * permitted).\r\n */\r\n public ChartEntity(Shape area, String toolTipText, String urlText) {\r\n ParamChecks.nullNotPermitted(area, \"area\");\r\n this.area = area;\r\n this.toolTipText = toolTipText;\r\n this.urlText = urlText;\r\n }\r\n\r\n /**\r\n * Returns the area occupied by the entity (in Java 2D space).\r\n *\r\n * @return The area (never <code>null</code>).\r\n */\r\n public Shape getArea() {\r\n return this.area;\r\n }\r\n\r\n /**\r\n * Sets the area for the entity.\r\n * <P>\r\n * This class conveys information about chart entities back to a client.\r\n * Setting this area doesn't change the entity (which has already been\r\n * drawn).\r\n *\r\n * @param area the area (<code>null</code> not permitted).\r\n */\r\n public void setArea(Shape area) {\r\n ParamChecks.nullNotPermitted(area, \"area\");\r\n this.area = area;\r\n }\r\n\r\n /**\r\n * Returns the tool tip text for the entity. Be aware that this text\r\n * may have been generated from user supplied data, so for security\r\n * reasons some form of filtering should be applied before incorporating\r\n * this text into any HTML output.\r\n *\r\n * @return The tool tip text (possibly <code>null</code>).\r\n */\r\n public String getToolTipText() {\r\n return this.toolTipText;\r\n }\r\n\r\n /**\r\n * Sets the tool tip text.\r\n *\r\n * @param text the text (<code>null</code> permitted).\r\n */\r\n public void setToolTipText(String text) {\r\n this.toolTipText = text;\r\n }\r\n\r\n /**\r\n * Returns the URL text for the entity. Be aware that this text\r\n * may have been generated from user supplied data, so some form of\r\n * filtering should be applied before this \"URL\" is used in any output.\r\n *\r\n * @return The URL text (possibly <code>null</code>).\r\n */\r\n public String getURLText() {\r\n return this.urlText;\r\n }\r\n\r\n /**\r\n * Sets the URL text.\r\n *\r\n * @param text the text (<code>null</code> permitted).\r\n */\r\n public void setURLText(String text) {\r\n this.urlText = text;\r\n }\r\n\r\n /**\r\n * Returns a string describing the entity area. This string is intended\r\n * for use in an AREA tag when generating an image map.\r\n *\r\n * @return The shape type (never <code>null</code>).\r\n */\r\n public String getShapeType() {\r\n if (this.area instanceof Rectangle2D) {\r\n return \"rect\";\r\n }\r\n else {\r\n return \"poly\";\r\n }\r\n }\r\n\r\n /**\r\n * Returns the shape coordinates as a string.\r\n *\r\n * @return The shape coordinates (never <code>null</code>).\r\n */\r\n public String getShapeCoords() {\r\n if (this.area instanceof Rectangle2D) {\r\n return getRectCoords((Rectangle2D) this.area);\r\n }\r\n else {\r\n return getPolyCoords(this.area);\r\n }\r\n }\r\n\r\n /**\r\n * Returns a string containing the coordinates (x1, y1, x2, y2) for a given\r\n * rectangle. This string is intended for use in an image map.\r\n *\r\n * @param rectangle the rectangle (<code>null</code> not permitted).\r\n *\r\n * @return Upper left and lower right corner of a rectangle.\r\n */\r\n private String getRectCoords(Rectangle2D rectangle) {\r\n ParamChecks.nullNotPermitted(rectangle, \"rectangle\");\r\n int x1 = (int) rectangle.getX();\r\n int y1 = (int) rectangle.getY();\r\n int x2 = x1 + (int) rectangle.getWidth();\r\n int y2 = y1 + (int) rectangle.getHeight();\r\n // fix by rfuller\r\n if (x2 == x1) {\r\n x2++;\r\n }\r\n if (y2 == y1) {\r\n y2++;\r\n }\r\n // end fix by rfuller\r\n return x1 + \",\" + y1 + \",\" + x2 + \",\" + y2;\r\n }\r\n\r\n /**\r\n * Returns a string containing the coordinates for a given shape. This\r\n * string is intended for use in an image map.\r\n *\r\n * @param shape the shape (<code>null</code> not permitted).\r\n *\r\n * @return The coordinates for a given shape as string.\r\n */\r\n private String getPolyCoords(Shape shape) {\r\n ParamChecks.nullNotPermitted(shape, \"shape\");\r\n StringBuilder result = new StringBuilder();\r\n boolean first = true;\r\n float[] coords = new float[6];\r\n PathIterator pi = shape.getPathIterator(null, 1.0);\r\n while (!pi.isDone()) {\r\n pi.currentSegment(coords);\r\n if (first) {\r\n first = false;\r\n result.append((int) coords[0]);\r\n result.append(\",\").append((int) coords[1]);\r\n }\r\n else {\r\n result.append(\",\");\r\n result.append((int) coords[0]);\r\n result.append(\",\");\r\n result.append((int) coords[1]);\r\n }\r\n pi.next();\r\n }\r\n return result.toString();\r\n }\r\n\r\n /**\r\n * Returns an HTML image map tag for this entity. The returned fragment\r\n * should be <code>XHTML 1.0</code> compliant.\r\n *\r\n * @param toolTipTagFragmentGenerator a generator for the HTML fragment\r\n * that will contain the tooltip text (<code>null</code> not permitted\r\n * if this entity contains tooltip information).\r\n * @param urlTagFragmentGenerator a generator for the HTML fragment that\r\n * will contain the URL reference (<code>null</code> not permitted if\r\n * this entity has a URL).\r\n *\r\n * @return The HTML tag.\r\n */\r\n public String getImageMapAreaTag(\r\n ToolTipTagFragmentGenerator toolTipTagFragmentGenerator,\r\n URLTagFragmentGenerator urlTagFragmentGenerator) {\r\n\r\n StringBuilder tag = new StringBuilder();\r\n boolean hasURL = (this.urlText == null ? false\r\n : !this.urlText.equals(\"\"));\r\n boolean hasToolTip = (this.toolTipText == null ? false\r\n : !this.toolTipText.equals(\"\"));\r\n if (hasURL || hasToolTip) {\r\n tag.append(\"<area shape=\\\"\").append(getShapeType()).append(\"\\\"\")\r\n .append(\" coords=\\\"\").append(getShapeCoords()).append(\"\\\"\");\r\n if (hasToolTip) {\r\n tag.append(toolTipTagFragmentGenerator.generateToolTipFragment(\r\n this.toolTipText));\r\n }\r\n if (hasURL) {\r\n tag.append(urlTagFragmentGenerator.generateURLFragment(\r\n this.urlText));\r\n }\r\n else {\r\n tag.append(\" nohref=\\\"nohref\\\"\");\r\n }\r\n // if there is a tool tip, we expect it to generate the title and\r\n // alt values, so we only add an empty alt if there is no tooltip\r\n if (!hasToolTip) {\r\n tag.append(\" alt=\\\"\\\"\");\r\n }\r\n tag.append(\"/>\");\r\n }\r\n return tag.toString();\r\n }\r\n\r\n /**\r\n * Returns a string representation of the chart entity, useful for\r\n * debugging.\r\n *\r\n * @return A string.\r\n */\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"ChartEntity: \");\r\n sb.append(\"tooltip = \");\r\n sb.append(this.toolTipText);\r\n return sb.toString();\r\n }\r\n\r\n /**\r\n * Tests the entity for equality with an arbitrary object.\r\n *\r\n * @param obj the object to test against (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof ChartEntity)) {\r\n return false;\r\n }\r\n ChartEntity that = (ChartEntity) obj;\r\n if (!this.area.equals(that.area)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.toolTipText, that.toolTipText)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.urlText, that.urlText)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code for this instance.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result = 37;\r\n result = HashUtilities.hashCode(result, this.toolTipText);\r\n result = HashUtilities.hashCode(result, this.urlText);\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a clone of the entity.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if there is a problem cloning the\r\n * entity.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n return super.clone();\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeShape(this.area, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.area = SerialUtilities.readShape(stream);\r\n }\r\n\r\n}\r" }, { "identifier": "EntityCollection", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/entity/EntityCollection.java", "snippet": "public interface EntityCollection {\r\n\r\n /**\r\n * Clears all entities.\r\n */\r\n public void clear();\r\n\r\n /**\r\n * Adds an entity to the collection.\r\n *\r\n * @param entity the entity (<code>null</code> not permitted).\r\n */\r\n public void add(ChartEntity entity);\r\n\r\n /**\r\n * Adds the entities from another collection to this collection.\r\n *\r\n * @param collection the other collection.\r\n */\r\n public void addAll(EntityCollection collection);\r\n\r\n /**\r\n * Returns an entity whose area contains the specified point.\r\n *\r\n * @param x the x coordinate.\r\n * @param y the y coordinate.\r\n *\r\n * @return The entity.\r\n */\r\n public ChartEntity getEntity(double x, double y);\r\n\r\n /**\r\n * Returns an entity from the collection.\r\n *\r\n * @param index the index (zero-based).\r\n *\r\n * @return An entity.\r\n */\r\n public ChartEntity getEntity(int index);\r\n\r\n /**\r\n * Returns the entity count.\r\n *\r\n * @return The entity count.\r\n */\r\n public int getEntityCount();\r\n\r\n /**\r\n * Returns the entities in an unmodifiable collection.\r\n *\r\n * @return The entities.\r\n */\r\n public Collection getEntities();\r\n\r\n /**\r\n * Returns an iterator for the entities in the collection.\r\n *\r\n * @return An iterator.\r\n */\r\n public Iterator iterator();\r\n\r\n}\r" }, { "identifier": "ChartChangeEvent", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/event/ChartChangeEvent.java", "snippet": "public class ChartChangeEvent extends EventObject {\r\n\r\n /** The type of event. */\r\n private ChartChangeEventType type;\r\n\r\n /** The chart that generated the event. */\r\n private JFreeChart chart;\r\n\r\n /**\r\n * Creates a new chart change event.\r\n *\r\n * @param source the source of the event (could be the chart, a title,\r\n * an axis etc.)\r\n */\r\n public ChartChangeEvent(Object source) {\r\n this(source, null, ChartChangeEventType.GENERAL);\r\n }\r\n\r\n /**\r\n * Creates a new chart change event.\r\n *\r\n * @param source the source of the event (could be the chart, a title, an\r\n * axis etc.)\r\n * @param chart the chart that generated the event.\r\n */\r\n public ChartChangeEvent(Object source, JFreeChart chart) {\r\n this(source, chart, ChartChangeEventType.GENERAL);\r\n }\r\n\r\n /**\r\n * Creates a new chart change event.\r\n *\r\n * @param source the source of the event (could be the chart, a title, an\r\n axis etc.)\r\n * @param chart the chart that generated the event.\r\n * @param type the type of event.\r\n */\r\n public ChartChangeEvent(Object source, JFreeChart chart,\r\n ChartChangeEventType type) {\r\n super(source);\r\n this.chart = chart;\r\n this.type = type;\r\n }\r\n\r\n /**\r\n * Returns the chart that generated the change event.\r\n *\r\n * @return The chart that generated the change event.\r\n */\r\n public JFreeChart getChart() {\r\n return this.chart;\r\n }\r\n\r\n /**\r\n * Sets the chart that generated the change event.\r\n *\r\n * @param chart the chart that generated the event.\r\n */\r\n public void setChart(JFreeChart chart) {\r\n this.chart = chart;\r\n }\r\n\r\n /**\r\n * Returns the event type.\r\n *\r\n * @return The event type.\r\n */\r\n public ChartChangeEventType getType() {\r\n return this.type;\r\n }\r\n\r\n /**\r\n * Sets the event type.\r\n *\r\n * @param type the event type.\r\n */\r\n public void setType(ChartChangeEventType type) {\r\n this.type = type;\r\n }\r\n\r\n}\r" }, { "identifier": "ChartChangeListener", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/event/ChartChangeListener.java", "snippet": "public interface ChartChangeListener extends EventListener {\r\n\r\n /**\r\n * Receives notification of a chart change event.\r\n *\r\n * @param event the event.\r\n */\r\n public void chartChanged(ChartChangeEvent event);\r\n\r\n}\r" }, { "identifier": "ChartProgressEvent", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/event/ChartProgressEvent.java", "snippet": "public class ChartProgressEvent extends java.util.EventObject {\r\n\r\n /** Indicates drawing has started. */\r\n public static final int DRAWING_STARTED = 1;\r\n\r\n /** Indicates drawing has finished. */\r\n public static final int DRAWING_FINISHED = 2;\r\n\r\n /** The type of event. */\r\n private int type;\r\n\r\n /** The percentage of completion. */\r\n private int percent;\r\n\r\n /** The chart that generated the event. */\r\n private JFreeChart chart;\r\n\r\n /**\r\n * Creates a new chart change event.\r\n *\r\n * @param source the source of the event (could be the chart, a title, an\r\n * axis etc.)\r\n * @param chart the chart that generated the event.\r\n * @param type the type of event.\r\n * @param percent the percentage of completion.\r\n */\r\n public ChartProgressEvent(Object source, JFreeChart chart, int type,\r\n int percent) {\r\n super(source);\r\n this.chart = chart;\r\n this.type = type;\r\n this.percent = percent;\r\n }\r\n\r\n /**\r\n * Returns the chart that generated the change event.\r\n *\r\n * @return The chart that generated the change event.\r\n */\r\n public JFreeChart getChart() {\r\n return this.chart;\r\n }\r\n\r\n /**\r\n * Sets the chart that generated the change event.\r\n *\r\n * @param chart the chart that generated the event.\r\n */\r\n public void setChart(JFreeChart chart) {\r\n this.chart = chart;\r\n }\r\n\r\n /**\r\n * Returns the event type.\r\n *\r\n * @return The event type.\r\n */\r\n public int getType() {\r\n return this.type;\r\n }\r\n\r\n /**\r\n * Sets the event type.\r\n *\r\n * @param type the event type.\r\n */\r\n public void setType(int type) {\r\n this.type = type;\r\n }\r\n\r\n /**\r\n * Returns the percentage complete.\r\n *\r\n * @return The percentage complete.\r\n */\r\n public int getPercent() {\r\n return this.percent;\r\n }\r\n\r\n /**\r\n * Sets the percentage complete.\r\n *\r\n * @param percent the percentage.\r\n */\r\n public void setPercent(int percent) {\r\n this.percent = percent;\r\n }\r\n\r\n}\r" }, { "identifier": "ChartProgressListener", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/event/ChartProgressListener.java", "snippet": "public interface ChartProgressListener extends EventListener {\r\n\r\n /**\r\n * Receives notification of a chart progress event.\r\n *\r\n * @param event the event.\r\n */\r\n public void chartProgress(ChartProgressEvent event);\r\n\r\n}\r" }, { "identifier": "Plot", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/Plot.java", "snippet": "public abstract class Plot implements AxisChangeListener,\r\n DatasetChangeListener, AnnotationChangeListener, MarkerChangeListener,\r\n LegendItemSource, PublicCloneable, Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -8831571430103671324L;\r\n\r\n /** Useful constant representing zero. */\r\n public static final Number ZERO = new Integer(0);\r\n\r\n /** The default insets. */\r\n public static final RectangleInsets DEFAULT_INSETS\r\n = new RectangleInsets(4.0, 8.0, 4.0, 8.0);\r\n\r\n /** The default outline stroke. */\r\n public static final Stroke DEFAULT_OUTLINE_STROKE = new BasicStroke(0.5f,\r\n BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);\r\n\r\n /** The default outline color. */\r\n public static final Paint DEFAULT_OUTLINE_PAINT = Color.gray;\r\n\r\n /** The default foreground alpha transparency. */\r\n public static final float DEFAULT_FOREGROUND_ALPHA = 1.0f;\r\n\r\n /** The default background alpha transparency. */\r\n public static final float DEFAULT_BACKGROUND_ALPHA = 1.0f;\r\n\r\n /** The default background color. */\r\n public static final Paint DEFAULT_BACKGROUND_PAINT = Color.white;\r\n\r\n /** The minimum width at which the plot should be drawn. */\r\n public static final int MINIMUM_WIDTH_TO_DRAW = 10;\r\n\r\n /** The minimum height at which the plot should be drawn. */\r\n public static final int MINIMUM_HEIGHT_TO_DRAW = 10;\r\n\r\n /** A default box shape for legend items. */\r\n public static final Shape DEFAULT_LEGEND_ITEM_BOX\r\n = new Rectangle2D.Double(-4.0, -4.0, 8.0, 8.0);\r\n\r\n /** A default circle shape for legend items. */\r\n public static final Shape DEFAULT_LEGEND_ITEM_CIRCLE\r\n = new Ellipse2D.Double(-4.0, -4.0, 8.0, 8.0);\r\n\r\n /** The parent plot (<code>null</code> if this is the root plot). */\r\n private Plot parent;\r\n\r\n /** The dataset group (to be used for thread synchronisation). */\r\n private DatasetGroup datasetGroup;\r\n\r\n /** The message to display if no data is available. */\r\n private String noDataMessage;\r\n\r\n /** The font used to display the 'no data' message. */\r\n private Font noDataMessageFont;\r\n\r\n /** The paint used to draw the 'no data' message. */\r\n private transient Paint noDataMessagePaint;\r\n\r\n /** Amount of blank space around the plot area. */\r\n private RectangleInsets insets;\r\n\r\n /**\r\n * A flag that controls whether or not the plot outline is drawn.\r\n *\r\n * @since 1.0.6\r\n */\r\n private boolean outlineVisible;\r\n\r\n /** The Stroke used to draw an outline around the plot. */\r\n private transient Stroke outlineStroke;\r\n\r\n /** The Paint used to draw an outline around the plot. */\r\n private transient Paint outlinePaint;\r\n\r\n /** An optional color used to fill the plot background. */\r\n private transient Paint backgroundPaint;\r\n\r\n /** An optional image for the plot background. */\r\n private transient Image backgroundImage; // not currently serialized\r\n\r\n /** The alignment for the background image. */\r\n private int backgroundImageAlignment = Align.FIT;\r\n\r\n /** The alpha value used to draw the background image. */\r\n private float backgroundImageAlpha = 0.5f;\r\n\r\n /** The alpha-transparency for the plot. */\r\n private float foregroundAlpha;\r\n\r\n /** The alpha transparency for the background paint. */\r\n private float backgroundAlpha;\r\n\r\n /** The drawing supplier. */\r\n private DrawingSupplier drawingSupplier;\r\n\r\n /** Storage for registered change listeners. */\r\n private transient EventListenerList listenerList;\r\n\r\n /**\r\n * A flag that controls whether or not the plot will notify listeners\r\n * of changes (defaults to true, but sometimes it is useful to disable\r\n * this).\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean notify;\r\n\r\n /**\r\n * Creates a new plot.\r\n */\r\n protected Plot() {\r\n\r\n this.parent = null;\r\n this.insets = DEFAULT_INSETS;\r\n this.backgroundPaint = DEFAULT_BACKGROUND_PAINT;\r\n this.backgroundAlpha = DEFAULT_BACKGROUND_ALPHA;\r\n this.backgroundImage = null;\r\n this.outlineVisible = true;\r\n this.outlineStroke = DEFAULT_OUTLINE_STROKE;\r\n this.outlinePaint = DEFAULT_OUTLINE_PAINT;\r\n this.foregroundAlpha = DEFAULT_FOREGROUND_ALPHA;\r\n\r\n this.noDataMessage = null;\r\n this.noDataMessageFont = new Font(\"SansSerif\", Font.PLAIN, 12);\r\n this.noDataMessagePaint = Color.black;\r\n\r\n this.drawingSupplier = new DefaultDrawingSupplier();\r\n\r\n this.notify = true;\r\n this.listenerList = new EventListenerList();\r\n\r\n }\r\n\r\n /**\r\n * Returns the dataset group for the plot (not currently used).\r\n *\r\n * @return The dataset group.\r\n *\r\n * @see #setDatasetGroup(DatasetGroup)\r\n */\r\n public DatasetGroup getDatasetGroup() {\r\n return this.datasetGroup;\r\n }\r\n\r\n /**\r\n * Sets the dataset group (not currently used).\r\n *\r\n * @param group the dataset group (<code>null</code> permitted).\r\n *\r\n * @see #getDatasetGroup()\r\n */\r\n protected void setDatasetGroup(DatasetGroup group) {\r\n this.datasetGroup = group;\r\n }\r\n\r\n /**\r\n * Returns the string that is displayed when the dataset is empty or\r\n * <code>null</code>.\r\n *\r\n * @return The 'no data' message (<code>null</code> possible).\r\n *\r\n * @see #setNoDataMessage(String)\r\n * @see #getNoDataMessageFont()\r\n * @see #getNoDataMessagePaint()\r\n */\r\n public String getNoDataMessage() {\r\n return this.noDataMessage;\r\n }\r\n\r\n /**\r\n * Sets the message that is displayed when the dataset is empty or\r\n * <code>null</code>, and sends a {@link PlotChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param message the message (<code>null</code> permitted).\r\n *\r\n * @see #getNoDataMessage()\r\n */\r\n public void setNoDataMessage(String message) {\r\n this.noDataMessage = message;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the font used to display the 'no data' message.\r\n *\r\n * @return The font (never <code>null</code>).\r\n *\r\n * @see #setNoDataMessageFont(Font)\r\n * @see #getNoDataMessage()\r\n */\r\n public Font getNoDataMessageFont() {\r\n return this.noDataMessageFont;\r\n }\r\n\r\n /**\r\n * Sets the font used to display the 'no data' message and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param font the font (<code>null</code> not permitted).\r\n *\r\n * @see #getNoDataMessageFont()\r\n */\r\n public void setNoDataMessageFont(Font font) {\r\n ParamChecks.nullNotPermitted(font, \"font\");\r\n this.noDataMessageFont = font;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used to display the 'no data' message.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setNoDataMessagePaint(Paint)\r\n * @see #getNoDataMessage()\r\n */\r\n public Paint getNoDataMessagePaint() {\r\n return this.noDataMessagePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to display the 'no data' message and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getNoDataMessagePaint()\r\n */\r\n public void setNoDataMessagePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.noDataMessagePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a short string describing the plot type.\r\n * <P>\r\n * Note: this gets used in the chart property editing user interface,\r\n * but there needs to be a better mechanism for identifying the plot type.\r\n *\r\n * @return A short string describing the plot type (never\r\n * <code>null</code>).\r\n */\r\n public abstract String getPlotType();\r\n\r\n /**\r\n * Returns the parent plot (or <code>null</code> if this plot is not part\r\n * of a combined plot).\r\n *\r\n * @return The parent plot.\r\n *\r\n * @see #setParent(Plot)\r\n * @see #getRootPlot()\r\n */\r\n public Plot getParent() {\r\n return this.parent;\r\n }\r\n\r\n /**\r\n * Sets the parent plot. This method is intended for internal use, you\r\n * shouldn't need to call it directly.\r\n *\r\n * @param parent the parent plot (<code>null</code> permitted).\r\n *\r\n * @see #getParent()\r\n */\r\n public void setParent(Plot parent) {\r\n this.parent = parent;\r\n }\r\n\r\n /**\r\n * Returns the root plot.\r\n *\r\n * @return The root plot.\r\n *\r\n * @see #getParent()\r\n */\r\n public Plot getRootPlot() {\r\n\r\n Plot p = getParent();\r\n if (p == null) {\r\n return this;\r\n }\r\n return p.getRootPlot();\r\n\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this plot is part of a combined plot\r\n * structure (that is, {@link #getParent()} returns a non-<code>null</code>\r\n * value), and <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> if this plot is part of a combined plot\r\n * structure.\r\n *\r\n * @see #getParent()\r\n */\r\n public boolean isSubplot() {\r\n return (getParent() != null);\r\n }\r\n\r\n /**\r\n * Returns the insets for the plot area.\r\n *\r\n * @return The insets (never <code>null</code>).\r\n *\r\n * @see #setInsets(RectangleInsets)\r\n */\r\n public RectangleInsets getInsets() {\r\n return this.insets;\r\n }\r\n\r\n /**\r\n * Sets the insets for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param insets the new insets (<code>null</code> not permitted).\r\n *\r\n * @see #getInsets()\r\n * @see #setInsets(RectangleInsets, boolean)\r\n */\r\n public void setInsets(RectangleInsets insets) {\r\n setInsets(insets, true);\r\n }\r\n\r\n /**\r\n * Sets the insets for the plot and, if requested, and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param insets the new insets (<code>null</code> not permitted).\r\n * @param notify a flag that controls whether the registered listeners are\r\n * notified.\r\n *\r\n * @see #getInsets()\r\n * @see #setInsets(RectangleInsets)\r\n */\r\n public void setInsets(RectangleInsets insets, boolean notify) {\r\n ParamChecks.nullNotPermitted(insets, \"insets\");\r\n if (!this.insets.equals(insets)) {\r\n this.insets = insets;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background color of the plot area.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundPaint(Paint)\r\n */\r\n public Paint getBackgroundPaint() {\r\n return this.backgroundPaint;\r\n }\r\n\r\n /**\r\n * Sets the background color of the plot area and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundPaint()\r\n */\r\n public void setBackgroundPaint(Paint paint) {\r\n\r\n if (paint == null) {\r\n if (this.backgroundPaint != null) {\r\n this.backgroundPaint = null;\r\n fireChangeEvent();\r\n }\r\n }\r\n else {\r\n if (this.backgroundPaint != null) {\r\n if (this.backgroundPaint.equals(paint)) {\r\n return; // nothing to do\r\n }\r\n }\r\n this.backgroundPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the alpha transparency of the plot area background.\r\n *\r\n * @return The alpha transparency.\r\n *\r\n * @see #setBackgroundAlpha(float)\r\n */\r\n public float getBackgroundAlpha() {\r\n return this.backgroundAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha transparency of the plot area background, and notifies\r\n * registered listeners that the plot has been modified.\r\n *\r\n * @param alpha the new alpha value (in the range 0.0f to 1.0f).\r\n *\r\n * @see #getBackgroundAlpha()\r\n */\r\n public void setBackgroundAlpha(float alpha) {\r\n if (this.backgroundAlpha != alpha) {\r\n this.backgroundAlpha = alpha;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the drawing supplier for the plot.\r\n *\r\n * @return The drawing supplier (possibly <code>null</code>).\r\n *\r\n * @see #setDrawingSupplier(DrawingSupplier)\r\n */\r\n public DrawingSupplier getDrawingSupplier() {\r\n DrawingSupplier result;\r\n Plot p = getParent();\r\n if (p != null) {\r\n result = p.getDrawingSupplier();\r\n }\r\n else {\r\n result = this.drawingSupplier;\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the drawing supplier for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. The drawing\r\n * supplier is responsible for supplying a limitless (possibly repeating)\r\n * sequence of <code>Paint</code>, <code>Stroke</code> and\r\n * <code>Shape</code> objects that the plot's renderer(s) can use to\r\n * populate its (their) tables.\r\n *\r\n * @param supplier the new supplier.\r\n *\r\n * @see #getDrawingSupplier()\r\n */\r\n public void setDrawingSupplier(DrawingSupplier supplier) {\r\n this.drawingSupplier = supplier;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Sets the drawing supplier for the plot and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners. The drawing\r\n * supplier is responsible for supplying a limitless (possibly repeating)\r\n * sequence of <code>Paint</code>, <code>Stroke</code> and\r\n * <code>Shape</code> objects that the plot's renderer(s) can use to\r\n * populate its (their) tables.\r\n *\r\n * @param supplier the new supplier.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDrawingSupplier()\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setDrawingSupplier(DrawingSupplier supplier, boolean notify) {\r\n this.drawingSupplier = supplier;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the background image that is used to fill the plot's background\r\n * area.\r\n *\r\n * @return The image (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundImage(Image)\r\n */\r\n public Image getBackgroundImage() {\r\n return this.backgroundImage;\r\n }\r\n\r\n /**\r\n * Sets the background image for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param image the image (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundImage()\r\n */\r\n public void setBackgroundImage(Image image) {\r\n this.backgroundImage = image;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the background image alignment. Alignment constants are defined\r\n * in the <code>org.jfree.ui.Align</code> class in the JCommon class\r\n * library.\r\n *\r\n * @return The alignment.\r\n *\r\n * @see #setBackgroundImageAlignment(int)\r\n */\r\n public int getBackgroundImageAlignment() {\r\n return this.backgroundImageAlignment;\r\n }\r\n\r\n /**\r\n * Sets the alignment for the background image and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. Alignment options\r\n * are defined by the {@link org.jfree.ui.Align} class in the JCommon\r\n * class library.\r\n *\r\n * @param alignment the alignment.\r\n *\r\n * @see #getBackgroundImageAlignment()\r\n */\r\n public void setBackgroundImageAlignment(int alignment) {\r\n if (this.backgroundImageAlignment != alignment) {\r\n this.backgroundImageAlignment = alignment;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha transparency used to draw the background image. This\r\n * is a value in the range 0.0f to 1.0f, where 0.0f is fully transparent\r\n * and 1.0f is fully opaque.\r\n *\r\n * @return The alpha transparency.\r\n *\r\n * @see #setBackgroundImageAlpha(float)\r\n */\r\n public float getBackgroundImageAlpha() {\r\n return this.backgroundImageAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha transparency used when drawing the background image.\r\n *\r\n * @param alpha the alpha transparency (in the range 0.0f to 1.0f, where\r\n * 0.0f is fully transparent, and 1.0f is fully opaque).\r\n *\r\n * @throws IllegalArgumentException if <code>alpha</code> is not within\r\n * the specified range.\r\n *\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void setBackgroundImageAlpha(float alpha) {\r\n if (alpha < 0.0f || alpha > 1.0f) {\r\n throw new IllegalArgumentException(\r\n \"The 'alpha' value must be in the range 0.0f to 1.0f.\");\r\n }\r\n if (this.backgroundImageAlpha != alpha) {\r\n this.backgroundImageAlpha = alpha;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the plot outline is\r\n * drawn. The default value is <code>true</code>. Note that for\r\n * historical reasons, the plot's outline paint and stroke can take on\r\n * <code>null</code> values, in which case the outline will not be drawn\r\n * even if this flag is set to <code>true</code>.\r\n *\r\n * @return The outline visibility flag.\r\n *\r\n * @since 1.0.6\r\n *\r\n * @see #setOutlineVisible(boolean)\r\n */\r\n public boolean isOutlineVisible() {\r\n return this.outlineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the plot's outline is\r\n * drawn, and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the new flag value.\r\n *\r\n * @since 1.0.6\r\n *\r\n * @see #isOutlineVisible()\r\n */\r\n public void setOutlineVisible(boolean visible) {\r\n this.outlineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to outline the plot area.\r\n *\r\n * @return The stroke (possibly <code>null</code>).\r\n *\r\n * @see #setOutlineStroke(Stroke)\r\n */\r\n public Stroke getOutlineStroke() {\r\n return this.outlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to outline the plot area and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. If you set this\r\n * attribute to <code>null</code>, no outline will be drawn.\r\n *\r\n * @param stroke the stroke (<code>null</code> permitted).\r\n *\r\n * @see #getOutlineStroke()\r\n */\r\n public void setOutlineStroke(Stroke stroke) {\r\n if (stroke == null) {\r\n if (this.outlineStroke != null) {\r\n this.outlineStroke = null;\r\n fireChangeEvent();\r\n }\r\n }\r\n else {\r\n if (this.outlineStroke != null) {\r\n if (this.outlineStroke.equals(stroke)) {\r\n return; // nothing to do\r\n }\r\n }\r\n this.outlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the color used to draw the outline of the plot area.\r\n *\r\n * @return The color (possibly <code>null</code>).\r\n *\r\n * @see #setOutlinePaint(Paint)\r\n */\r\n public Paint getOutlinePaint() {\r\n return this.outlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the outline of the plot area and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. If you set this\r\n * attribute to <code>null</code>, no outline will be drawn.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getOutlinePaint()\r\n */\r\n public void setOutlinePaint(Paint paint) {\r\n if (paint == null) {\r\n if (this.outlinePaint != null) {\r\n this.outlinePaint = null;\r\n fireChangeEvent();\r\n }\r\n }\r\n else {\r\n if (this.outlinePaint != null) {\r\n if (this.outlinePaint.equals(paint)) {\r\n return; // nothing to do\r\n }\r\n }\r\n this.outlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha-transparency for the plot foreground.\r\n *\r\n * @return The alpha-transparency.\r\n *\r\n * @see #setForegroundAlpha(float)\r\n */\r\n public float getForegroundAlpha() {\r\n return this.foregroundAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha-transparency for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param alpha the new alpha transparency.\r\n *\r\n * @see #getForegroundAlpha()\r\n */\r\n public void setForegroundAlpha(float alpha) {\r\n if (this.foregroundAlpha != alpha) {\r\n this.foregroundAlpha = alpha;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the legend items for the plot. By default, this method returns\r\n * <code>null</code>. Subclasses should override to return a\r\n * {@link LegendItemCollection}.\r\n *\r\n * @return The legend items for the plot (possibly <code>null</code>).\r\n */\r\n @Override\r\n public LegendItemCollection getLegendItems() {\r\n return null;\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not change events are sent to\r\n * registered listeners.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNotify(boolean)\r\n *\r\n * @since 1.0.13\r\n */\r\n public boolean isNotify() {\r\n return this.notify;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not listeners receive\r\n * {@link PlotChangeEvent} notifications.\r\n *\r\n * @param notify a boolean.\r\n *\r\n * @see #isNotify()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setNotify(boolean notify) {\r\n this.notify = notify;\r\n // if the flag is being set to true, there may be queued up changes...\r\n if (notify) {\r\n notifyListeners(new PlotChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Registers an object for notification of changes to the plot.\r\n *\r\n * @param listener the object to be registered.\r\n *\r\n * @see #removeChangeListener(PlotChangeListener)\r\n */\r\n public void addChangeListener(PlotChangeListener listener) {\r\n this.listenerList.add(PlotChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Unregisters an object for notification of changes to the plot.\r\n *\r\n * @param listener the object to be unregistered.\r\n *\r\n * @see #addChangeListener(PlotChangeListener)\r\n */\r\n public void removeChangeListener(PlotChangeListener listener) {\r\n this.listenerList.remove(PlotChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Notifies all registered listeners that the plot has been modified.\r\n *\r\n * @param event information about the change event.\r\n */\r\n public void notifyListeners(PlotChangeEvent event) {\r\n // if the 'notify' flag has been switched to false, we don't notify\r\n // the listeners\r\n if (!this.notify) {\r\n return;\r\n }\r\n Object[] listeners = this.listenerList.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == PlotChangeListener.class) {\r\n ((PlotChangeListener) listeners[i + 1]).plotChanged(event);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @since 1.0.10\r\n */\r\n protected void fireChangeEvent() {\r\n notifyListeners(new PlotChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Draws the plot within the specified area. The anchor is a point on the\r\n * chart that is specified externally (for instance, it may be the last\r\n * point of the last mouse click performed by the user) - plots can use or\r\n * ignore this value as they see fit.\r\n * <br><br>\r\n * Subclasses need to provide an implementation of this method, obviously.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the plot area.\r\n * @param anchor the anchor point (<code>null</code> permitted).\r\n * @param parentState the parent state (if any).\r\n * @param info carries back plot rendering info.\r\n */\r\n public abstract void draw(Graphics2D g2,\r\n Rectangle2D area,\r\n Point2D anchor,\r\n PlotState parentState,\r\n PlotRenderingInfo info);\r\n\r\n /**\r\n * Draws the plot background (the background color and/or image).\r\n * <P>\r\n * This method will be called during the chart drawing process and is\r\n * declared public so that it can be accessed by the renderers used by\r\n * certain subclasses. You shouldn't need to call this method directly.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot should be drawn.\r\n */\r\n public void drawBackground(Graphics2D g2, Rectangle2D area) {\r\n // some subclasses override this method completely, so don't put\r\n // anything here that *must* be done\r\n fillBackground(g2, area);\r\n drawBackgroundImage(g2, area);\r\n }\r\n\r\n /**\r\n * Fills the specified area with the background paint.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n *\r\n * @see #getBackgroundPaint()\r\n * @see #getBackgroundAlpha()\r\n * @see #fillBackground(Graphics2D, Rectangle2D, PlotOrientation)\r\n */\r\n protected void fillBackground(Graphics2D g2, Rectangle2D area) {\r\n fillBackground(g2, area, PlotOrientation.VERTICAL);\r\n }\r\n\r\n /**\r\n * Fills the specified area with the background paint. If the background\r\n * paint is an instance of <code>GradientPaint</code>, the gradient will\r\n * run in the direction suggested by the plot's orientation.\r\n *\r\n * @param g2 the graphics target.\r\n * @param area the plot area.\r\n * @param orientation the plot orientation (<code>null</code> not\r\n * permitted).\r\n *\r\n * @since 1.0.6\r\n */\r\n protected void fillBackground(Graphics2D g2, Rectangle2D area,\r\n PlotOrientation orientation) {\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n if (this.backgroundPaint == null) {\r\n return;\r\n }\r\n Paint p = this.backgroundPaint;\r\n if (p instanceof GradientPaint) {\r\n GradientPaint gp = (GradientPaint) p;\r\n if (orientation == PlotOrientation.VERTICAL) {\r\n p = new GradientPaint((float) area.getCenterX(),\r\n (float) area.getMaxY(), gp.getColor1(),\r\n (float) area.getCenterX(), (float) area.getMinY(),\r\n gp.getColor2());\r\n }\r\n else if (orientation == PlotOrientation.HORIZONTAL) {\r\n p = new GradientPaint((float) area.getMinX(),\r\n (float) area.getCenterY(), gp.getColor1(),\r\n (float) area.getMaxX(), (float) area.getCenterY(),\r\n gp.getColor2());\r\n }\r\n }\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundAlpha));\r\n g2.setPaint(p);\r\n g2.fill(area);\r\n g2.setComposite(originalComposite);\r\n }\r\n\r\n /**\r\n * Draws the background image (if there is one) aligned within the\r\n * specified area.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n *\r\n * @see #getBackgroundImage()\r\n * @see #getBackgroundImageAlignment()\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void drawBackgroundImage(Graphics2D g2, Rectangle2D area) {\r\n if (this.backgroundImage == null) {\r\n return; // nothing to do\r\n }\r\n Composite savedComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundImageAlpha));\r\n Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,\r\n this.backgroundImage.getWidth(null),\r\n this.backgroundImage.getHeight(null));\r\n Align.align(dest, area, this.backgroundImageAlignment);\r\n Shape savedClip = g2.getClip();\r\n g2.clip(area);\r\n g2.drawImage(this.backgroundImage, (int) dest.getX(),\r\n (int) dest.getY(), (int) dest.getWidth() + 1,\r\n (int) dest.getHeight() + 1, null);\r\n g2.setClip(savedClip);\r\n g2.setComposite(savedComposite);\r\n }\r\n\r\n /**\r\n * Draws the plot outline. This method will be called during the chart\r\n * drawing process and is declared public so that it can be accessed by the\r\n * renderers used by certain subclasses. You shouldn't need to call this\r\n * method directly.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot should be drawn.\r\n */\r\n public void drawOutline(Graphics2D g2, Rectangle2D area) {\r\n if (!this.outlineVisible) {\r\n return;\r\n }\r\n if ((this.outlineStroke != null) && (this.outlinePaint != null)) {\r\n g2.setStroke(this.outlineStroke);\r\n g2.setPaint(this.outlinePaint);\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);\r\n g2.draw(area);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n }\r\n\r\n /**\r\n * Draws a message to state that there is no data to plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot should be drawn.\r\n */\r\n protected void drawNoDataMessage(Graphics2D g2, Rectangle2D area) {\r\n Shape savedClip = g2.getClip();\r\n g2.clip(area);\r\n String message = this.noDataMessage;\r\n if (message != null) {\r\n g2.setFont(this.noDataMessageFont);\r\n g2.setPaint(this.noDataMessagePaint);\r\n TextBlock block = TextUtilities.createTextBlock(\r\n this.noDataMessage, this.noDataMessageFont,\r\n this.noDataMessagePaint, 0.9f * (float) area.getWidth(),\r\n new G2TextMeasurer(g2));\r\n block.draw(g2, (float) area.getCenterX(),\r\n (float) area.getCenterY(), TextBlockAnchor.CENTER);\r\n }\r\n g2.setClip(savedClip);\r\n }\r\n\r\n /**\r\n * Creates a plot entity that contains a reference to the plot and the\r\n * data area as shape.\r\n *\r\n * @param dataArea the data area used as hot spot for the entity.\r\n * @param plotState the plot rendering info containing a reference to the\r\n * EntityCollection.\r\n * @param toolTip the tool tip (defined in the respective Plot\r\n * subclass) (<code>null</code> permitted).\r\n * @param urlText the url (defined in the respective Plot subclass)\r\n * (<code>null</code> permitted).\r\n *\r\n * @since 1.0.13\r\n */\r\n protected void createAndAddEntity(Rectangle2D dataArea,\r\n PlotRenderingInfo plotState, String toolTip, String urlText) {\r\n if (plotState != null && plotState.getOwner() != null) {\r\n EntityCollection e = plotState.getOwner().getEntityCollection();\r\n if (e != null) {\r\n e.add(new PlotEntity(dataArea, this, toolTip, urlText));\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the plot. Since the plot does not maintain any\r\n * information about where it has been drawn, the plot rendering info is\r\n * supplied as an argument so that the plot dimensions can be determined.\r\n *\r\n * @param x the x coordinate (in Java2D space).\r\n * @param y the y coordinate (in Java2D space).\r\n * @param info an object containing information about the dimensions of\r\n * the plot.\r\n */\r\n public void handleClick(int x, int y, PlotRenderingInfo info) {\r\n // provides a 'no action' default\r\n }\r\n\r\n /**\r\n * Performs a zoom on the plot. Subclasses should override if zooming is\r\n * appropriate for the type of plot.\r\n *\r\n * @param percent the zoom percentage.\r\n */\r\n public void zoom(double percent) {\r\n // do nothing by default.\r\n }\r\n\r\n /**\r\n * Receives notification of a change to an {@link Annotation} added to\r\n * this plot.\r\n *\r\n * @param event information about the event (not used here).\r\n *\r\n * @since 1.0.14\r\n */\r\n @Override\r\n public void annotationChanged(AnnotationChangeEvent event) {\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Receives notification of a change to one of the plot's axes.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void axisChanged(AxisChangeEvent event) {\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Receives notification of a change to the plot's dataset.\r\n * <P>\r\n * The plot reacts by passing on a plot change event to all registered\r\n * listeners.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void datasetChanged(DatasetChangeEvent event) {\r\n PlotChangeEvent newEvent = new PlotChangeEvent(this);\r\n newEvent.setType(ChartChangeEventType.DATASET_UPDATED);\r\n notifyListeners(newEvent);\r\n }\r\n\r\n /**\r\n * Receives notification of a change to a marker that is assigned to the\r\n * plot.\r\n *\r\n * @param event the event.\r\n *\r\n * @since 1.0.3\r\n */\r\n @Override\r\n public void markerChanged(MarkerChangeEvent event) {\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adjusts the supplied x-value.\r\n *\r\n * @param x the x-value.\r\n * @param w1 width 1.\r\n * @param w2 width 2.\r\n * @param edge the edge (left or right).\r\n *\r\n * @return The adjusted x-value.\r\n */\r\n protected double getRectX(double x, double w1, double w2,\r\n RectangleEdge edge) {\r\n\r\n double result = x;\r\n if (edge == RectangleEdge.LEFT) {\r\n result = result + w1;\r\n }\r\n else if (edge == RectangleEdge.RIGHT) {\r\n result = result + w2;\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Adjusts the supplied y-value.\r\n *\r\n * @param y the x-value.\r\n * @param h1 height 1.\r\n * @param h2 height 2.\r\n * @param edge the edge (top or bottom).\r\n *\r\n * @return The adjusted y-value.\r\n */\r\n protected double getRectY(double y, double h1, double h2,\r\n RectangleEdge edge) {\r\n\r\n double result = y;\r\n if (edge == RectangleEdge.TOP) {\r\n result = result + h1;\r\n }\r\n else if (edge == RectangleEdge.BOTTOM) {\r\n result = result + h2;\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Tests this plot for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof Plot)) {\r\n return false;\r\n }\r\n Plot that = (Plot) obj;\r\n if (!ObjectUtilities.equal(this.noDataMessage, that.noDataMessage)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(\r\n this.noDataMessageFont, that.noDataMessageFont\r\n )) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.noDataMessagePaint,\r\n that.noDataMessagePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.insets, that.insets)) {\r\n return false;\r\n }\r\n if (this.outlineVisible != that.outlineVisible) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.outlineStroke, that.outlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.backgroundPaint, that.backgroundPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundImage,\r\n that.backgroundImage)) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlignment != that.backgroundImageAlignment) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlpha != that.backgroundImageAlpha) {\r\n return false;\r\n }\r\n if (this.foregroundAlpha != that.foregroundAlpha) {\r\n return false;\r\n }\r\n if (this.backgroundAlpha != that.backgroundAlpha) {\r\n return false;\r\n }\r\n if (!this.drawingSupplier.equals(that.drawingSupplier)) {\r\n return false;\r\n }\r\n if (this.notify != that.notify) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Creates a clone of the plot.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if some component of the plot does not\r\n * support cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n\r\n Plot clone = (Plot) super.clone();\r\n // private Plot parent <-- don't clone the parent plot, but take care\r\n // childs in combined plots instead\r\n if (this.datasetGroup != null) {\r\n clone.datasetGroup\r\n = (DatasetGroup) ObjectUtilities.clone(this.datasetGroup);\r\n }\r\n clone.drawingSupplier\r\n = (DrawingSupplier) ObjectUtilities.clone(this.drawingSupplier);\r\n clone.listenerList = new EventListenerList();\r\n return clone;\r\n\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writePaint(this.noDataMessagePaint, stream);\r\n SerialUtilities.writeStroke(this.outlineStroke, stream);\r\n SerialUtilities.writePaint(this.outlinePaint, stream);\r\n // backgroundImage\r\n SerialUtilities.writePaint(this.backgroundPaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.noDataMessagePaint = SerialUtilities.readPaint(stream);\r\n this.outlineStroke = SerialUtilities.readStroke(stream);\r\n this.outlinePaint = SerialUtilities.readPaint(stream);\r\n // backgroundImage\r\n this.backgroundPaint = SerialUtilities.readPaint(stream);\r\n\r\n this.listenerList = new EventListenerList();\r\n\r\n }\r\n\r\n /**\r\n * Resolves a domain axis location for a given plot orientation.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param orientation the orientation (<code>null</code> not permitted).\r\n *\r\n * @return The edge (never <code>null</code>).\r\n */\r\n public static RectangleEdge resolveDomainAxisLocation(\r\n AxisLocation location, PlotOrientation orientation) {\r\n\r\n ParamChecks.nullNotPermitted(location, \"location\");\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n\r\n RectangleEdge result = null;\r\n if (location == AxisLocation.TOP_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n }\r\n else if (location == AxisLocation.TOP_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n }\r\n // the above should cover all the options...\r\n if (result == null) {\r\n throw new IllegalStateException(\"resolveDomainAxisLocation()\");\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Resolves a range axis location for a given plot orientation.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param orientation the orientation (<code>null</code> not permitted).\r\n *\r\n * @return The edge (never <code>null</code>).\r\n */\r\n public static RectangleEdge resolveRangeAxisLocation(\r\n AxisLocation location, PlotOrientation orientation) {\r\n\r\n ParamChecks.nullNotPermitted(location, \"location\");\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n\r\n RectangleEdge result = null;\r\n if (location == AxisLocation.TOP_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n }\r\n else if (location == AxisLocation.TOP_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n }\r\n\r\n // the above should cover all the options...\r\n if (result == null) {\r\n throw new IllegalStateException(\"resolveRangeAxisLocation()\");\r\n }\r\n return result;\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "PlotOrientation", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/PlotOrientation.java", "snippet": "public final class PlotOrientation implements Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -2508771828190337782L;\r\n\r\n /** For a plot where the range axis is horizontal. */\r\n public static final PlotOrientation HORIZONTAL\r\n = new PlotOrientation(\"PlotOrientation.HORIZONTAL\");\r\n\r\n /** For a plot where the range axis is vertical. */\r\n public static final PlotOrientation VERTICAL\r\n = new PlotOrientation(\"PlotOrientation.VERTICAL\");\r\n\r\n /** The name. */\r\n private String name;\r\n\r\n /**\r\n * Private constructor.\r\n *\r\n * @param name the name.\r\n */\r\n private PlotOrientation(String name) {\r\n this.name = name;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this orientation is <code>HORIZONTAL</code>,\r\n * and <code>false</code> otherwise. \r\n * \r\n * @return A boolean.\r\n * \r\n * @since 1.0.18\r\n */\r\n public boolean isHorizontal() {\r\n return this.equals(PlotOrientation.HORIZONTAL);\r\n }\r\n \r\n /**\r\n * Returns <code>true</code> if this orientation is <code>VERTICAL</code>,\r\n * and <code>false</code> otherwise.\r\n * \r\n * @return A boolean.\r\n * \r\n * @since 1.0.18\r\n */\r\n public boolean isVertical() {\r\n return this.equals(PlotOrientation.VERTICAL);\r\n }\r\n \r\n /**\r\n * Returns a string representing the object.\r\n *\r\n * @return The string.\r\n */\r\n @Override\r\n public String toString() {\r\n return this.name;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this object is equal to the specified\r\n * object, and <code>false</code> otherwise.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) {\r\n return true;\r\n }\r\n if (!(obj instanceof PlotOrientation)) {\r\n return false;\r\n }\r\n PlotOrientation orientation = (PlotOrientation) obj;\r\n if (!this.name.equals(orientation.toString())) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code for this instance.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n return this.name.hashCode();\r\n }\r\n\r\n /**\r\n * Ensures that serialization returns the unique instances.\r\n *\r\n * @return The object.\r\n *\r\n * @throws ObjectStreamException if there is a problem.\r\n */\r\n private Object readResolve() throws ObjectStreamException {\r\n Object result = null;\r\n if (this.equals(PlotOrientation.HORIZONTAL)) {\r\n result = PlotOrientation.HORIZONTAL;\r\n }\r\n else if (this.equals(PlotOrientation.VERTICAL)) {\r\n result = PlotOrientation.VERTICAL;\r\n }\r\n return result;\r\n }\r\n\r\n}\r" }, { "identifier": "PlotRenderingInfo", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/PlotRenderingInfo.java", "snippet": "public class PlotRenderingInfo implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 8446720134379617220L;\r\n\r\n /** The owner of this info. */\r\n private ChartRenderingInfo owner;\r\n\r\n /** The plot area. */\r\n private transient Rectangle2D plotArea;\r\n\r\n /** The data area. */\r\n private transient Rectangle2D dataArea;\r\n\r\n /**\r\n * Storage for the plot rendering info objects belonging to the subplots.\r\n */\r\n private List subplotInfo;\r\n\r\n /**\r\n * Creates a new instance.\r\n *\r\n * @param owner the owner (<code>null</code> permitted).\r\n */\r\n public PlotRenderingInfo(ChartRenderingInfo owner) {\r\n this.owner = owner;\r\n this.dataArea = new Rectangle2D.Double();\r\n this.subplotInfo = new java.util.ArrayList();\r\n }\r\n\r\n /**\r\n * Returns the owner (as specified in the constructor).\r\n *\r\n * @return The owner (possibly <code>null</code>).\r\n */\r\n public ChartRenderingInfo getOwner() {\r\n return this.owner;\r\n }\r\n\r\n /**\r\n * Returns the plot area (in Java2D space).\r\n *\r\n * @return The plot area (possibly <code>null</code>).\r\n *\r\n * @see #setPlotArea(Rectangle2D)\r\n */\r\n public Rectangle2D getPlotArea() {\r\n return this.plotArea;\r\n }\r\n\r\n /**\r\n * Sets the plot area.\r\n *\r\n * @param area the plot area (in Java2D space, <code>null</code>\r\n * permitted but discouraged)\r\n *\r\n * @see #getPlotArea()\r\n */\r\n public void setPlotArea(Rectangle2D area) {\r\n this.plotArea = area;\r\n }\r\n\r\n /**\r\n * Returns the plot's data area (in Java2D space).\r\n *\r\n * @return The data area (possibly <code>null</code>).\r\n *\r\n * @see #setDataArea(Rectangle2D)\r\n */\r\n public Rectangle2D getDataArea() {\r\n return this.dataArea;\r\n }\r\n\r\n /**\r\n * Sets the data area.\r\n *\r\n * @param area the data area (in Java2D space, <code>null</code> permitted\r\n * but discouraged).\r\n *\r\n * @see #getDataArea()\r\n */\r\n public void setDataArea(Rectangle2D area) {\r\n this.dataArea = area;\r\n }\r\n\r\n /**\r\n * Returns the number of subplots (possibly zero).\r\n *\r\n * @return The subplot count.\r\n */\r\n public int getSubplotCount() {\r\n return this.subplotInfo.size();\r\n }\r\n\r\n /**\r\n * Adds the info for a subplot.\r\n *\r\n * @param info the subplot info.\r\n *\r\n * @see #getSubplotInfo(int)\r\n */\r\n public void addSubplotInfo(PlotRenderingInfo info) {\r\n this.subplotInfo.add(info);\r\n }\r\n\r\n /**\r\n * Returns the info for a subplot.\r\n *\r\n * @param index the subplot index.\r\n *\r\n * @return The info.\r\n *\r\n * @see #addSubplotInfo(PlotRenderingInfo)\r\n */\r\n public PlotRenderingInfo getSubplotInfo(int index) {\r\n return (PlotRenderingInfo) this.subplotInfo.get(index);\r\n }\r\n\r\n /**\r\n * Returns the index of the subplot that contains the specified\r\n * (x, y) point (the \"source\" point). The source point will usually\r\n * come from a mouse click on a {@link org.jfree.chart.ChartPanel},\r\n * and this method is then used to determine the subplot that\r\n * contains the source point.\r\n *\r\n * @param source the source point (in Java2D space, <code>null</code> not\r\n * permitted).\r\n *\r\n * @return The subplot index (or -1 if no subplot contains\r\n * <code>source</code>).\r\n */\r\n public int getSubplotIndex(Point2D source) {\r\n ParamChecks.nullNotPermitted(source, \"source\");\r\n int subplotCount = getSubplotCount();\r\n for (int i = 0; i < subplotCount; i++) {\r\n PlotRenderingInfo info = getSubplotInfo(i);\r\n Rectangle2D area = info.getDataArea();\r\n if (area.contains(source)) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Tests this instance for equality against an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) {\r\n return true;\r\n }\r\n if (!(obj instanceof PlotRenderingInfo)) {\r\n return false;\r\n }\r\n PlotRenderingInfo that = (PlotRenderingInfo) obj;\r\n if (!ObjectUtilities.equal(this.dataArea, that.dataArea)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.plotArea, that.plotArea)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.subplotInfo, that.subplotInfo)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a clone of this object.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if there is a problem cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n PlotRenderingInfo clone = (PlotRenderingInfo) super.clone();\r\n if (this.plotArea != null) {\r\n clone.plotArea = (Rectangle2D) this.plotArea.clone();\r\n }\r\n if (this.dataArea != null) {\r\n clone.dataArea = (Rectangle2D) this.dataArea.clone();\r\n }\r\n clone.subplotInfo = new java.util.ArrayList(this.subplotInfo.size());\r\n for (int i = 0; i < this.subplotInfo.size(); i++) {\r\n PlotRenderingInfo info\r\n = (PlotRenderingInfo) this.subplotInfo.get(i);\r\n clone.subplotInfo.add(info.clone());\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeShape(this.dataArea, stream);\r\n SerialUtilities.writeShape(this.plotArea, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.dataArea = (Rectangle2D) SerialUtilities.readShape(stream);\r\n this.plotArea = (Rectangle2D) SerialUtilities.readShape(stream);\r\n }\r\n\r\n}\r" }, { "identifier": "ValueAxisPlot", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/ValueAxisPlot.java", "snippet": "public interface ValueAxisPlot {\r\n\r\n /**\r\n * Returns the data range that should apply for the specified axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The data range.\r\n */\r\n public Range getDataRange(ValueAxis axis);\r\n\r\n}\r" }, { "identifier": "Zoomable", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/Zoomable.java", "snippet": "public interface Zoomable {\r\n\r\n /**\r\n * Returns <code>true</code> if the plot's domain is zoomable, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isRangeZoomable()\r\n */\r\n public boolean isDomainZoomable();\r\n\r\n /**\r\n * Returns <code>true</code> if the plot's range is zoomable, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isDomainZoomable()\r\n */\r\n public boolean isRangeZoomable();\r\n\r\n /**\r\n * Returns the orientation of the plot.\r\n *\r\n * @return The orientation.\r\n */\r\n public PlotOrientation getOrientation();\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n * The <code>source</code> point can be used in some cases to identify a\r\n * subplot, or to determine the center of zooming (refer to the\r\n * documentation of the implementing class for details).\r\n *\r\n * @param factor the zoom factor.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D coordinates).\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D)\r\n */\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo state,\r\n Point2D source);\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n * The <code>source</code> point can be used in some cases to identify a\r\n * subplot, or to determine the center of zooming (refer to the\r\n * documentation of the implementing class for details).\r\n *\r\n * @param factor the zoom factor.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D coordinates).\r\n * @param useAnchor use source point as zoom anchor?\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo state,\r\n Point2D source, boolean useAnchor);\r\n\r\n /**\r\n * Zooms in on the domain axes. The <code>source</code> point can be used\r\n * in some cases to identify a subplot for zooming.\r\n *\r\n * @param lowerPercent the new lower bound.\r\n * @param upperPercent the new upper bound.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D coordinates).\r\n *\r\n * @see #zoomRangeAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n public void zoomDomainAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo state, Point2D source);\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n * The <code>source</code> point can be used in some cases to identify a\r\n * subplot, or to determine the center of zooming (refer to the\r\n * documentation of the implementing class for details).\r\n *\r\n * @param factor the zoom factor.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D coordinates).\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D)\r\n */\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo state,\r\n Point2D source);\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n * The <code>source</code> point can be used in some cases to identify a\r\n * subplot, or to determine the center of zooming (refer to the\r\n * documentation of the implementing class for details).\r\n *\r\n * @param factor the zoom factor.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D coordinates).\r\n * @param useAnchor use source point as zoom anchor?\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D)\r\n *\r\n * @since 1.0.7\r\n */\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo state,\r\n Point2D source, boolean useAnchor);\r\n\r\n /**\r\n * Zooms in on the range axes. The <code>source</code> point can be used\r\n * in some cases to identify a subplot for zooming.\r\n *\r\n * @param lowerPercent the new lower bound.\r\n * @param upperPercent the new upper bound.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D coordinates).\r\n *\r\n * @see #zoomDomainAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n public void zoomRangeAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo state, Point2D source);\r\n\r\n}\r" }, { "identifier": "ResourceBundleWrapper", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/util/ResourceBundleWrapper.java", "snippet": "public class ResourceBundleWrapper {\r\n\r\n /**\r\n * A special class loader with no code base lookup. This field may be\r\n * <code>null</code> (the field is only initialised if removeCodeBase() is\r\n * called from an applet).\r\n */\r\n private static URLClassLoader noCodeBaseClassLoader;\r\n\r\n /**\r\n * Private constructor.\r\n */\r\n private ResourceBundleWrapper() {\r\n // all methods are static, no need to instantiate\r\n }\r\n\r\n /**\r\n * Instantiate a {@link URLClassLoader} for resource lookups where the\r\n * codeBase URL is removed. This method is typically called from an\r\n * applet's init() method. If this method is never called, the\r\n * <code>getBundle()</code> methods map to the standard\r\n * {@link ResourceBundle} lookup methods.\r\n *\r\n * @param codeBase the codeBase URL.\r\n * @param urlClassLoader the class loader.\r\n */\r\n public static void removeCodeBase(URL codeBase,\r\n URLClassLoader urlClassLoader) {\r\n List urlsNoBase = new ArrayList();\r\n\r\n URL[] urls = urlClassLoader.getURLs();\r\n for (int i = 0; i < urls.length; i++) {\r\n if (!urls[i].sameFile(codeBase)) {\r\n urlsNoBase.add(urls[i]);\r\n }\r\n }\r\n // substitute the filtered URL list\r\n URL[] urlsNoBaseArray = (URL[]) urlsNoBase.toArray(new URL[0]);\r\n noCodeBaseClassLoader = URLClassLoader.newInstance(urlsNoBaseArray);\r\n }\r\n\r\n /**\r\n * Finds and returns the specified resource bundle.\r\n *\r\n * @param baseName the base name.\r\n *\r\n * @return The resource bundle.\r\n */\r\n public static ResourceBundle getBundle(String baseName) {\r\n // the noCodeBaseClassLoader is configured by a call to the\r\n // removeCodeBase() method, typically in the init() method of an\r\n // applet...\r\n if (noCodeBaseClassLoader != null) {\r\n return ResourceBundle.getBundle(baseName, Locale.getDefault(),\r\n noCodeBaseClassLoader);\r\n }\r\n else {\r\n // standard ResourceBundle behaviour\r\n return ResourceBundle.getBundle(baseName);\r\n }\r\n }\r\n\r\n /**\r\n * Finds and returns the specified resource bundle.\r\n *\r\n * @param baseName the base name.\r\n * @param locale the locale.\r\n *\r\n * @return The resource bundle.\r\n */\r\n public static ResourceBundle getBundle(String baseName, Locale locale) {\r\n\r\n // the noCodeBaseClassLoader is configured by a call to the\r\n // removeCodeBase() method, typically in the init() method of an\r\n // applet...\r\n if (noCodeBaseClassLoader != null) {\r\n return ResourceBundle.getBundle(baseName, locale,\r\n noCodeBaseClassLoader);\r\n }\r\n else {\r\n // standard ResourceBundle behaviour\r\n return ResourceBundle.getBundle(baseName, locale);\r\n }\r\n }\r\n\r\n /**\r\n * Maps directly to <code>ResourceBundle.getBundle(baseName, locale,\r\n * loader)</code>.\r\n *\r\n * @param baseName the base name.\r\n * @param locale the locale.\r\n * @param loader the class loader.\r\n *\r\n * @return The resource bundle.\r\n */\r\n public static ResourceBundle getBundle(String baseName, Locale locale,\r\n ClassLoader loader) {\r\n return ResourceBundle.getBundle(baseName, locale, loader);\r\n }\r\n\r\n}\r" }, { "identifier": "SWTChartEditor", "path": "lib/jfreechart-1.0.19/swt/org/jfree/experimental/chart/swt/editor/SWTChartEditor.java", "snippet": "public class SWTChartEditor implements ChartEditor {\n\n /** The shell */\n private Shell shell;\n\n /** The chart which the properties have to be edited */\n private JFreeChart chart;\n\n /** A composite for displaying/editing the properties of the title. */\n private SWTTitleEditor titleEditor;\n\n /** A composite for displaying/editing the properties of the plot. */\n private SWTPlotEditor plotEditor;\n\n /** A composite for displaying/editing the other properties of the chart. */\n private SWTOtherEditor otherEditor;\n\n /** The resourceBundle for the localization. */\n protected static ResourceBundle localizationResources\n = ResourceBundleWrapper.getBundle(\n \"org.jfree.chart.editor.LocalizationBundle\");\n\n /**\n * Creates a new editor.\n *\n * @param display the display.\n * @param chart2edit the chart to edit.\n */\n public SWTChartEditor(Display display, JFreeChart chart2edit) {\n this.shell = new Shell(display, SWT.DIALOG_TRIM);\n this.shell.setSize(400, 500);\n this.chart = chart2edit;\n this.shell.setText(ResourceBundleWrapper.getBundle(\n \"org.jfree.chart.LocalizationBundle\").getString(\n \"Chart_Properties\"));\n GridLayout layout = new GridLayout(2, true);\n layout.marginLeft = layout.marginTop = layout.marginRight\n = layout.marginBottom = 5;\n this.shell.setLayout(layout);\n Composite main = new Composite(this.shell, SWT.NONE);\n main.setLayout(new FillLayout());\n main.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));\n\n TabFolder tab = new TabFolder(main, SWT.BORDER);\n // build first tab\n TabItem item1 = new TabItem(tab, SWT.NONE);\n item1.setText(\" \" + localizationResources.getString(\"Title\") + \" \");\n this.titleEditor = new SWTTitleEditor(tab, SWT.NONE,\n this.chart.getTitle());\n item1.setControl(this.titleEditor);\n // build second tab\n TabItem item2 = new TabItem(tab, SWT.NONE);\n item2.setText(\" \" + localizationResources.getString(\"Plot\") + \" \");\n this.plotEditor = new SWTPlotEditor(tab, SWT.NONE,\n this.chart.getPlot());\n item2.setControl(this.plotEditor);\n // build the third tab\n TabItem item3 = new TabItem(tab, SWT.NONE);\n item3.setText(\" \" + localizationResources.getString(\"Other\") + \" \");\n this.otherEditor = new SWTOtherEditor(tab, SWT.NONE, this.chart);\n item3.setControl(this.otherEditor);\n\n // ok and cancel buttons\n Button ok = new Button(this.shell, SWT.PUSH | SWT.OK);\n ok.setText(\" Ok \");\n ok.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));\n ok.addSelectionListener(new SelectionAdapter() {\n public void widgetSelected(SelectionEvent e) {\n updateChart(SWTChartEditor.this.chart);\n SWTChartEditor.this.shell.dispose();\n }\n });\n Button cancel = new Button(this.shell, SWT.PUSH);\n cancel.setText(\" Cancel \");\n cancel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));\n cancel.addSelectionListener(new SelectionAdapter() {\n public void widgetSelected(SelectionEvent e) {\n SWTChartEditor.this.shell.dispose();\n }\n });\n }\n\n /**\n * Opens the editor.\n */\n public void open() {\n this.shell.open();\n this.shell.layout();\n while (!this.shell.isDisposed()) {\n if (!this.shell.getDisplay().readAndDispatch()) {\n this.shell.getDisplay().sleep();\n }\n }\n }\n\n /**\n * Updates the chart properties.\n *\n * @param chart the chart.\n */\n public void updateChart(JFreeChart chart)\n {\n this.titleEditor.setTitleProperties(chart);\n this.plotEditor.updatePlotProperties(chart.getPlot());\n this.otherEditor.updateChartProperties(chart);\n }\n\n}" }, { "identifier": "SWTGraphics2D", "path": "lib/jfreechart-1.0.19/swt/org/jfree/experimental/swt/SWTGraphics2D.java", "snippet": "public class SWTGraphics2D extends Graphics2D {\n\n /** The swt graphic composite */\n private GC gc;\n\n /**\n * The rendering hints. For now, these are not used, but at least the\n * basic mechanism is present.\n */\n private RenderingHints hints;\n\n /** A reference to the compositing rule to apply. This is necessary\n * due to the poor compositing interface of the SWT toolkit. */\n private java.awt.Composite composite;\n\n /** A HashMap to store the Swt color resources. */\n private Map colorsPool = new HashMap();\n\n /** A HashMap to store the Swt font resources. */\n private Map fontsPool = new HashMap();\n\n /** A HashMap to store the Swt transform resources. */\n private Map transformsPool = new HashMap();\n\n /** A List to store the Swt resources. */\n private List resourcePool = new ArrayList();\n\n /**\n * Creates a new instance.\n *\n * @param gc the graphics context.\n */\n public SWTGraphics2D(GC gc) {\n super();\n this.gc = gc;\n this.hints = new RenderingHints(null);\n this.composite = AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f);\n setStroke(new BasicStroke());\n }\n\n /**\n * Not implemented yet - see {@link Graphics#create()}.\n *\n * @return <code>null</code>.\n */\n public Graphics create() {\n // TODO Auto-generated method stub\n return null;\n }\n\n /**\n * Not implemented yet - see {@link Graphics2D#getDeviceConfiguration()}.\n *\n * @return <code>null</code>.\n */\n public GraphicsConfiguration getDeviceConfiguration() {\n // TODO Auto-generated method stub\n return null;\n }\n\n /**\n * Returns the current value for the specified hint key, or\n * <code>null</code> if no value is set.\n *\n * @param hintKey the hint key (<code>null</code> permitted).\n *\n * @return The hint value, or <code>null</code>.\n *\n * @see #setRenderingHint(RenderingHints.Key, Object)\n */\n public Object getRenderingHint(Key hintKey) {\n return this.hints.get(hintKey);\n }\n\n /**\n * Sets the value for a rendering hint. For now, this graphics context\n * ignores all hints.\n *\n * @param hintKey the key (<code>null</code> not permitted).\n * @param hintValue the value (must be compatible with the specified key).\n *\n * @throws IllegalArgumentException if <code>hintValue</code> is not\n * compatible with the <code>hintKey</code>.\n *\n * @see #getRenderingHint(RenderingHints.Key)\n */\n public void setRenderingHint(Key hintKey, Object hintValue) {\n this.hints.put(hintKey, hintValue);\n }\n\n /**\n * Returns a copy of the hints collection for this graphics context.\n *\n * @return A copy of the hints collection.\n */\n public RenderingHints getRenderingHints() {\n return (RenderingHints) this.hints.clone();\n }\n\n /**\n * Adds the hints in the specified map to the graphics context, replacing\n * any existing hints. For now, this graphics context ignores all hints.\n *\n * @param hints the hints (<code>null</code> not permitted).\n *\n * @see #setRenderingHints(Map)\n */\n public void addRenderingHints(Map hints) {\n this.hints.putAll(hints);\n }\n\n /**\n * Replaces the existing hints with those contained in the specified\n * map. Note that, for now, this graphics context ignores all hints.\n *\n * @param hints the hints (<code>null</code> not permitted).\n *\n * @see #addRenderingHints(Map)\n */\n public void setRenderingHints(Map hints) {\n if (hints == null) {\n throw new NullPointerException(\"Null 'hints' argument.\");\n }\n this.hints = new RenderingHints(hints);\n }\n\n /**\n * Returns the current paint for this graphics context.\n *\n * @return The current paint.\n *\n * @see #setPaint(Paint)\n */\n public Paint getPaint() {\n // TODO: it might be a good idea to keep a reference to the color\n // specified in setPaint() or setColor(), rather than creating a\n // new object every time getPaint() is called.\n return SWTUtils.toAwtColor(this.gc.getForeground());\n }\n\n /**\n * Sets the paint for this graphics context. For now, this graphics\n * context only supports instances of {@link Color} or\n * {@link GradientPaint} (in the latter case there is no real gradient\n * support, the paint used is the <code>Color</code> returned by\n * <code>getColor1()</code>).\n *\n * @param paint the paint (<code>null</code> permitted, ignored).\n *\n * @see #getPaint()\n * @see #setColor(Color)\n */\n public void setPaint(Paint paint) {\n if (paint == null) {\n return; // to be consistent with other Graphics2D implementations\n }\n if (paint instanceof Color) {\n setColor((Color) paint);\n }\n else if (paint instanceof GradientPaint) {\n GradientPaint gp = (GradientPaint) paint;\n setColor(gp.getColor1());\n }\n else {\n throw new RuntimeException(\"Can only handle 'Color' at present.\");\n }\n }\n\n /**\n * Returns the current color for this graphics context.\n *\n * @return The current color.\n *\n * @see #setColor(Color)\n */\n public Color getColor() {\n // TODO: it might be a good idea to keep a reference to the color\n // specified in setPaint() or setColor(), rather than creating a\n // new object every time getPaint() is called.\n return SWTUtils.toAwtColor(this.gc.getForeground());\n }\n\n /**\n * Sets the current color for this graphics context.\n *\n * @param color the color (<code>null</code> permitted but ignored).\n *\n * @see #getColor()\n */\n public void setColor(Color color) {\n if (color == null) {\n return;\n }\n org.eclipse.swt.graphics.Color swtColor = getSwtColorFromPool(color);\n this.gc.setForeground(swtColor);\n // handle transparency and compositing.\n if (this.composite instanceof AlphaComposite) {\n AlphaComposite acomp = (AlphaComposite) this.composite;\n switch (acomp.getRule()) {\n case AlphaComposite.SRC_OVER:\n this.gc.setAlpha((int) (color.getAlpha() * acomp.getAlpha()));\n break;\n default:\n this.gc.setAlpha(color.getAlpha());\n break;\n }\n }\n }\n\n private Color backgroundColor;\n \n /**\n * Sets the background colour.\n *\n * @param color the colour.\n */\n public void setBackground(Color color) {\n // since this is only used by clearRect(), we don't update the GC yet\n this.backgroundColor = color;\n }\n\n /**\n * Returns the background colour.\n *\n * @return The background colour (possibly <code>null</code>)..\n */\n public Color getBackground() {\n return this.backgroundColor;\n }\n\n /**\n * Not implemented - see {@link Graphics#setPaintMode()}.\n */\n public void setPaintMode() {\n // TODO Auto-generated method stub\n }\n\n /**\n * Not implemented - see {@link Graphics#setXORMode(Color)}.\n *\n * @param color the colour.\n */\n public void setXORMode(Color color) {\n // TODO Auto-generated method stub\n }\n\n /**\n * Returns the current composite.\n *\n * @return The current composite.\n *\n * @see #setComposite(Composite)\n */\n public Composite getComposite() {\n return this.composite;\n }\n\n /**\n * Sets the current composite. This implementation currently supports\n * only the {@link AlphaComposite} class.\n *\n * @param comp the composite (<code>null</code> not permitted).\n */\n public void setComposite(Composite comp) {\n if (comp == null) {\n throw new IllegalArgumentException(\"Null 'comp' argument.\");\n }\n this.composite = comp;\n if (comp instanceof AlphaComposite) {\n AlphaComposite acomp = (AlphaComposite) comp;\n int alpha = (int) (acomp.getAlpha() * 0xFF);\n this.gc.setAlpha(alpha);\n }\n }\n\n /**\n * Returns the current stroke for this graphics context.\n *\n * @return The current stroke.\n *\n * @see #setStroke(Stroke)\n */\n public Stroke getStroke() {\n return new BasicStroke(this.gc.getLineWidth(),\n toAwtLineCap(this.gc.getLineCap()),\n toAwtLineJoin(this.gc.getLineJoin()));\n }\n\n /**\n * Sets the stroke for this graphics context. For now, this implementation\n * only recognises the {@link BasicStroke} class.\n *\n * @param stroke the stroke (<code>null</code> not permitted).\n *\n * @see #getStroke()\n */\n public void setStroke(Stroke stroke) {\n if (stroke == null) {\n throw new IllegalArgumentException(\"Null 'stroke' argument.\");\n }\n if (stroke instanceof BasicStroke) {\n BasicStroke bs = (BasicStroke) stroke;\n this.gc.setLineWidth((int) bs.getLineWidth());\n this.gc.setLineJoin(toSwtLineJoin(bs.getLineJoin()));\n this.gc.setLineCap(toSwtLineCap(bs.getEndCap()));\n\n // set the line style to solid by default\n this.gc.setLineStyle(SWT.LINE_SOLID);\n\n // apply dash style if any\n float[] dashes = bs.getDashArray();\n if (dashes != null) {\n int[] swtDashes = new int[dashes.length];\n for (int i = 0; i < swtDashes.length; i++) {\n swtDashes[i] = (int) dashes[i];\n }\n this.gc.setLineDash(swtDashes);\n }\n }\n else {\n throw new RuntimeException(\n \"Can only handle 'Basic Stroke' at present.\");\n }\n }\n\n /**\n * Applies the specified clip.\n *\n * @param s the shape for the clip.\n */\n public void clip(Shape s) {\n Path path = toSwtPath(s);\n this.gc.setClipping(path);\n path.dispose();\n }\n\n /**\n * Returns the clip bounds.\n *\n * @return The clip bounds.\n */\n public Rectangle getClipBounds() {\n org.eclipse.swt.graphics.Rectangle clip = this.gc.getClipping();\n return new Rectangle(clip.x, clip.y, clip.width, clip.height);\n }\n\n /**\n * Sets the clipping to the intersection of the current clip region and\n * the specified rectangle.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the width.\n * @param height the height.\n */\n public void clipRect(int x, int y, int width, int height) {\n org.eclipse.swt.graphics.Rectangle clip = this.gc.getClipping();\n org.eclipse.swt.graphics.Rectangle r \n = new org.eclipse.swt.graphics.Rectangle(x, y, width, height);\n clip.intersect(r);\n this.gc.setClipping(clip);\n }\n\n /**\n * Returns the current clip.\n *\n * @return The current clip.\n */\n public Shape getClip() {\n return SWTUtils.toAwtRectangle(this.gc.getClipping());\n }\n\n /**\n * Sets the clip region.\n *\n * @param clip the clip.\n */\n public void setClip(Shape clip) {\n if (clip == null) {\n return;\n }\n Path clipPath = toSwtPath(clip);\n this.gc.setClipping(clipPath);\n clipPath.dispose();\n }\n\n /**\n * Sets the clip region to the specified rectangle.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the width.\n * @param height the height.\n */\n public void setClip(int x, int y, int width, int height) {\n this.gc.setClipping(x, y, width, height);\n }\n\n /**\n * Returns the current transform.\n *\n * @return The current transform.\n */\n public AffineTransform getTransform() {\n Transform swtTransform = new Transform(this.gc.getDevice());\n this.gc.getTransform(swtTransform);\n AffineTransform awtTransform = toAwtTransform(swtTransform);\n swtTransform.dispose();\n return awtTransform;\n }\n\n /**\n * Sets the current transform.\n *\n * @param t the transform.\n */\n public void setTransform(AffineTransform t) {\n Transform transform = getSwtTransformFromPool(t);\n this.gc.setTransform(transform);\n }\n\n /**\n * Concatenates the specified transform to the existing transform.\n *\n * @param t the transform.\n */\n public void transform(AffineTransform t) {\n Transform swtTransform = new Transform(this.gc.getDevice());\n this.gc.getTransform(swtTransform);\n swtTransform.multiply(getSwtTransformFromPool(t));\n this.gc.setTransform(swtTransform);\n swtTransform.dispose();\n }\n\n /**\n * Applies a translation.\n *\n * @param x the translation along the x-axis.\n * @param y the translation along the y-axis.\n */\n public void translate(int x, int y) {\n Transform swtTransform = new Transform(this.gc.getDevice());\n this.gc.getTransform(swtTransform);\n swtTransform.translate(x, y);\n this.gc.setTransform(swtTransform);\n swtTransform.dispose();\n }\n\n /**\n * Applies a translation.\n *\n * @param tx the translation along the x-axis.\n * @param ty the translation along the y-axis.\n */\n public void translate(double tx, double ty) {\n translate((int) tx, (int) ty);\n }\n\n /**\n * Applies a rotation transform.\n *\n * @param theta the angle of rotation.\n */\n public void rotate(double theta) {\n AffineTransform t = getTransform();\n t.rotate(theta);\n setTransform(t);\n }\n\n /**\n * Not implemented - see {@link Graphics2D#rotate(double, double, double)}.\n *\n * @see java.awt.Graphics2D#rotate(double, double, double)\n */\n public void rotate(double theta, double x, double y) {\n translate(x, y);\n rotate(theta);\n translate(-x, -y);\n }\n\n /**\n * Applies a scale transform.\n *\n * @param scaleX the scale factor along the x-axis.\n * @param scaleY the scale factor along the y-axis.\n */\n public void scale(double scaleX, double scaleY) {\n Transform swtTransform = new Transform(this.gc.getDevice());\n this.gc.getTransform(swtTransform);\n swtTransform.scale((float) scaleX, (float) scaleY);\n this.gc.setTransform(swtTransform);\n swtTransform.dispose();\n }\n\n /**\n * Applies a shear transform.\n *\n * @param shearX the x-factor.\n * @param shearY the y-factor.\n */\n public void shear(double shearX, double shearY) {\n transform(AffineTransform.getShearInstance(shearX, shearY));\n }\n\n /**\n * Draws the outline of the specified shape using the current stroke and\n * paint settings.\n *\n * @param shape the shape (<code>null</code> not permitted).\n *\n * @see #getPaint()\n * @see #getStroke()\n * @see #fill(Shape)\n */\n public void draw(Shape shape) {\n Path path = toSwtPath(shape);\n this.gc.drawPath(path);\n path.dispose();\n }\n\n /**\n * Draws a line from (x1, y1) to (x2, y2) using the current stroke\n * and paint settings.\n *\n * @param x1 the x-coordinate for the starting point.\n * @param y1 the y-coordinate for the starting point.\n * @param x2 the x-coordinate for the ending point.\n * @param y2 the y-coordinate for the ending point.\n *\n * @see #draw(Shape)\n */\n public void drawLine(int x1, int y1, int x2, int y2) {\n this.gc.drawLine(x1, y1, x2, y2);\n }\n\n /**\n * Draws the outline of the polygon specified by the given points, using\n * the current paint and stroke settings.\n *\n * @param xPoints the x-coordinates.\n * @param yPoints the y-coordinates.\n * @param npoints the number of points in the polygon.\n *\n * @see #draw(Shape)\n */\n public void drawPolygon(int [] xPoints, int [] yPoints, int npoints) {\n drawPolyline(xPoints, yPoints, npoints);\n if (npoints > 1) {\n this.gc.drawLine(xPoints[npoints - 1], yPoints[npoints - 1],\n xPoints[0], yPoints[0]);\n }\n }\n\n /**\n * Draws a sequence of connected lines specified by the given points, using\n * the current paint and stroke settings.\n *\n * @param xPoints the x-coordinates.\n * @param yPoints the y-coordinates.\n * @param npoints the number of points in the polygon.\n *\n * @see #draw(Shape)\n */\n public void drawPolyline(int [] xPoints, int [] yPoints, int npoints) {\n if (npoints > 1) {\n int x0 = xPoints[0];\n int y0 = yPoints[0];\n int x1 = 0, y1 = 0;\n for (int i = 1; i < npoints; i++) {\n x1 = xPoints[i];\n y1 = yPoints[i];\n this.gc.drawLine(x0, y0, x1, y1);\n x0 = x1;\n y0 = y1;\n }\n }\n }\n\n /**\n * Draws an oval that fits within the specified rectangular region.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the frame width.\n * @param height the frame height.\n *\n * @see #fillOval(int, int, int, int)\n * @see #draw(Shape)\n */\n public void drawOval(int x, int y, int width, int height) {\n this.gc.drawOval(x, y, width - 1, height - 1);\n }\n\n /**\n * Draws an arc that is part of an ellipse that fits within the specified\n * framing rectangle.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the frame width.\n * @param height the frame height.\n * @param arcStart the arc starting point, in degrees.\n * @param arcAngle the extent of the arc.\n *\n * @see #fillArc(int, int, int, int, int, int)\n */\n public void drawArc(int x, int y, int width, int height, int arcStart,\n int arcAngle) {\n this.gc.drawArc(x, y, width - 1, height - 1, arcStart, arcAngle);\n }\n\n /**\n * Draws a rectangle with rounded corners that fits within the specified\n * framing rectangle.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the frame width.\n * @param height the frame height.\n * @param arcWidth the width of the arc defining the roundedness of the\n * rectangle's corners.\n * @param arcHeight the height of the arc defining the roundedness of the\n * rectangle's corners.\n *\n * @see #fillRoundRect(int, int, int, int, int, int)\n */\n public void drawRoundRect(int x, int y, int width, int height,\n int arcWidth, int arcHeight) {\n this.gc.drawRoundRectangle(x, y, width - 1, height - 1, arcWidth,\n arcHeight);\n }\n\n /**\n * Fills the specified shape using the current paint.\n *\n * @param shape the shape (<code>null</code> not permitted).\n *\n * @see #getPaint()\n * @see #draw(Shape)\n */\n public void fill(Shape shape) {\n Path path = toSwtPath(shape);\n // Note that for consistency with the AWT implementation, it is\n // necessary to switch temporarily the foreground and background\n // colours\n switchColors();\n this.gc.fillPath(path);\n switchColors();\n path.dispose();\n }\n\n /**\n * Fill a rectangle area on the swt graphic composite.\n * The <code>fillRectangle</code> method of the <code>GC</code>\n * class uses the background color so we must switch colors.\n * @see java.awt.Graphics#fillRect(int, int, int, int)\n */\n public void fillRect(int x, int y, int width, int height) {\n this.switchColors();\n this.gc.fillRectangle(x, y, width, height);\n this.switchColors();\n }\n\n /**\n * Fills the specified rectangle with the current background colour.\n *\n * @param x the x-coordinate for the rectangle.\n * @param y the y-coordinate for the rectangle.\n * @param width the width.\n * @param height the height.\n *\n * @see #fillRect(int, int, int, int)\n */\n public void clearRect(int x, int y, int width, int height) {\n Color bgcolor = getBackground();\n if (bgcolor == null) {\n return; // we can't do anything\n }\n Paint saved = getPaint();\n setPaint(bgcolor);\n fillRect(x, y, width, height);\n setPaint(saved);\n }\n\n /**\n * Fills the specified polygon.\n *\n * @param xPoints the x-coordinates.\n * @param yPoints the y-coordinates.\n * @param npoints the number of points.\n */\n public void fillPolygon(int[] xPoints, int[] yPoints, int npoints) {\n int[] pointArray = new int[npoints * 2];\n for (int i = 0; i < npoints; i++) {\n pointArray[2 * i] = xPoints[i];\n pointArray[2 * i + 1] = yPoints[i];\n }\n switchColors();\n this.gc.fillPolygon(pointArray);\n switchColors();\n }\n\n /**\n * Draws a rectangle with rounded corners that fits within the specified\n * framing rectangle.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the frame width.\n * @param height the frame height.\n * @param arcWidth the width of the arc defining the roundedness of the\n * rectangle's corners.\n * @param arcHeight the height of the arc defining the roundedness of the\n * rectangle's corners.\n *\n * @see #drawRoundRect(int, int, int, int, int, int)\n */\n public void fillRoundRect(int x, int y, int width, int height,\n int arcWidth, int arcHeight) {\n switchColors();\n this.gc.fillRoundRectangle(x, y, width - 1, height - 1, arcWidth,\n arcHeight);\n switchColors();\n }\n\n /**\n * Fills an oval that fits within the specified rectangular region.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the frame width.\n * @param height the frame height.\n *\n * @see #drawOval(int, int, int, int)\n * @see #fill(Shape)\n */\n public void fillOval(int x, int y, int width, int height) {\n switchColors();\n this.gc.fillOval(x, y, width - 1, height - 1);\n switchColors();\n }\n\n /**\n * Fills an arc that is part of an ellipse that fits within the specified\n * framing rectangle.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the frame width.\n * @param height the frame height.\n * @param arcStart the arc starting point, in degrees.\n * @param arcAngle the extent of the arc.\n *\n * @see #drawArc(int, int, int, int, int, int)\n */\n public void fillArc(int x, int y, int width, int height, int arcStart,\n int arcAngle) {\n switchColors();\n this.gc.fillArc(x, y, width - 1, height - 1, arcStart, arcAngle);\n switchColors();\n }\n\n /**\n * Returns the font in form of an awt font created\n * with the parameters of the font of the swt graphic\n * composite.\n * @see java.awt.Graphics#getFont()\n */\n public Font getFont() {\n // retrieve the swt font description in an os indept way\n FontData[] fontData = this.gc.getFont().getFontData();\n // create a new awt font with the appropiate data\n return SWTUtils.toAwtFont(this.gc.getDevice(), fontData[0], true);\n }\n\n /**\n * Set the font swt graphic composite from the specified\n * awt font. Be careful that the newly created swt font\n * must be disposed separately.\n * @see java.awt.Graphics#setFont(java.awt.Font)\n */\n public void setFont(Font font) {\n org.eclipse.swt.graphics.Font swtFont = getSwtFontFromPool(font);\n this.gc.setFont(swtFont);\n }\n\n /**\n * Returns the font metrics.\n *\n * @param font the font.\n *\n * @return The font metrics.\n */\n public FontMetrics getFontMetrics(Font font) {\n return SWTUtils.DUMMY_PANEL.getFontMetrics(font);\n }\n\n /**\n * Returns the font render context.\n *\n * @return The font render context.\n */\n public FontRenderContext getFontRenderContext() {\n FontRenderContext fontRenderContext = new FontRenderContext(\n new AffineTransform(), true, true);\n return fontRenderContext;\n }\n\n /**\n * Draws the specified glyph vector at the location <code>(x, y)</code>.\n * \n * @param g the glyph vector (<code>null</code> not permitted).\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n */\n public void drawGlyphVector(GlyphVector g, float x, float y) {\n fill(g.getOutline(x, y));\n }\n\n /**\n * Draws a string on the receiver. note that\n * to be consistent with the awt method,\n * the y has to be modified with the ascent of the font.\n *\n * @see java.awt.Graphics#drawString(java.lang.String, int, int)\n */\n public void drawString(String text, int x, int y) {\n drawString(text, (float) x, (float) y);\n }\n\n /**\n * Draws a string at the specified position.\n *\n * @param text the string.\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n */\n public void drawString(String text, float x, float y) {\n if (text == null) {\n throw new NullPointerException(\"Null 'text' argument.\");\n }\n float fm = this.gc.getFontMetrics().getAscent();\n this.gc.drawString(text, (int) x, (int) (y - fm), true);\n }\n\n /**\n * Draws a string at the specified position.\n *\n * @param iterator the string.\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n */\n public void drawString(AttributedCharacterIterator iterator, int x, int y) {\n // for now we simply want to extract the chars from the iterator\n // and call an unstyled text renderer\n StringBuffer sb = new StringBuffer();\n int numChars = iterator.getEndIndex() - iterator.getBeginIndex();\n char c = iterator.first();\n for (int i = 0; i < numChars; i++) {\n sb.append(c);\n c = iterator.next();\n }\n drawString(new String(sb),x,y);\n }\n\n /**\n * Draws a string at the specified position.\n *\n * @param iterator the string.\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n */\n public void drawString(AttributedCharacterIterator iterator, float x,\n float y) {\n drawString(iterator, (int) x, (int) y);\n }\n\n /**\n * Returns <code>true</code> if the rectangle (in device space) intersects\n * with the shape (the interior, if <code>onStroke</code> is false, \n * otherwise the stroked outline of the shape).\n * \n * @param rect a rectangle (in device space).\n * @param s the shape.\n * @param onStroke test the stroked outline only?\n * \n * @return A boolean. \n */\n @Override\n public boolean hit(Rectangle rect, Shape s, boolean onStroke) {\n AffineTransform transform = getTransform();\n Shape ts;\n if (onStroke) {\n Stroke stroke = getStroke();\n ts = transform.createTransformedShape(stroke.createStrokedShape(s));\n } else {\n ts = transform.createTransformedShape(s);\n }\n if (!rect.getBounds2D().intersects(ts.getBounds2D())) {\n return false;\n }\n Area a1 = new Area(rect);\n Area a2 = new Area(ts);\n a1.intersect(a2);\n return !a1.isEmpty();\n }\n\n /**\n * Not implemented - see {@link Graphics#copyArea(int, int, int, int, int,\n * int)}.\n */\n public void copyArea(int x, int y, int width, int height, int dx, int dy) {\n // TODO Auto-generated method stub\n }\n\n /**\n * Not implemented - see {@link Graphics2D#drawImage(Image,\n * AffineTransform, ImageObserver)}.\n *\n * @param image the image.\n * @param xform the transform.\n * @param obs an image observer.\n *\n * @return A boolean.\n */\n public boolean drawImage(Image image, AffineTransform xform,\n ImageObserver obs) {\n // TODO Auto-generated method stub\n return false;\n }\n\n /**\n * Draws an image.\n *\n * @param image the image.\n * @param op the image operation.\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n */\n public void drawImage(BufferedImage image, BufferedImageOp op, int x,\n int y) {\n org.eclipse.swt.graphics.Image im = new org.eclipse.swt.graphics.Image(\n this.gc.getDevice(), SWTUtils.convertToSWT(image));\n this.gc.drawImage(im, x, y);\n im.dispose();\n }\n\n /**\n * Draws an SWT image with the top left corner of the image aligned to the\n * point (x, y).\n *\n * @param image the image.\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n */\n public void drawImage(org.eclipse.swt.graphics.Image image, int x, int y) {\n this.gc.drawImage(image, x, y);\n }\n\n /**\n * Not implemented - see {@link Graphics2D#drawRenderedImage(RenderedImage,\n * AffineTransform)}.\n *\n * @param image the image.\n * @param xform the transform.\n */\n public void drawRenderedImage(RenderedImage image, AffineTransform xform) {\n // TODO Auto-generated method stub\n }\n\n /**\n * Not implemented - see {@link Graphics2D#drawRenderableImage(\n * RenderableImage, AffineTransform)}.\n *\n * @param image the image.\n * @param xform the transform.\n */\n public void drawRenderableImage(RenderableImage image,\n AffineTransform xform) {\n // TODO Auto-generated method stub\n\n }\n\n /**\n * Draws an image with the top left corner aligned to the point (x, y).\n *\n * @param image the image.\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param observer ignored here.\n *\n * @return <code>true</code> if the image has been drawn.\n */\n public boolean drawImage(Image image, int x, int y,\n ImageObserver observer) {\n ImageData data = SWTUtils.convertAWTImageToSWT(image);\n if (data == null) {\n return false;\n }\n org.eclipse.swt.graphics.Image im = new org.eclipse.swt.graphics.Image(\n this.gc.getDevice(), data);\n this.gc.drawImage(im, x, y);\n im.dispose();\n return true;\n }\n\n /**\n * Draws an image with the top left corner aligned to the point (x, y),\n * and scaled to the specified width and height.\n *\n * @param image the image.\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the width for the rendered image.\n * @param height the height for the rendered image.\n * @param observer ignored here.\n *\n * @return <code>true</code> if the image has been drawn.\n */\n public boolean drawImage(Image image, int x, int y, int width, int height,\n ImageObserver observer) {\n ImageData data = SWTUtils.convertAWTImageToSWT(image);\n if (data == null) {\n return false;\n }\n org.eclipse.swt.graphics.Image im = new org.eclipse.swt.graphics.Image(\n this.gc.getDevice(), data);\n org.eclipse.swt.graphics.Rectangle bounds = im.getBounds();\n this.gc.drawImage(im, 0, 0, bounds.width, bounds.height, x, y, width,\n height);\n im.dispose();\n return true;\n }\n\n /**\n * Draws an image.\n *\n * @param image (<code>null</code> not permitted).\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param bgcolor the background color.\n * @param observer an image observer.\n *\n * @return A boolean.\n */\n public boolean drawImage(Image image, int x, int y, Color bgcolor,\n ImageObserver observer) {\n ParamChecks.nullNotPermitted(image, \"image\");\n int w = image.getWidth(null);\n int h = image.getHeight(null);\n if (w == -1 || h == -1) {\n return false;\n }\n Paint savedPaint = getPaint();\n fill(new Rectangle2D.Double(x, y, w, h));\n setPaint(savedPaint);\n return drawImage(image, x, y, observer);\n }\n\n /**\n * Draws an image.\n *\n * @param image the image (<code>null</code> not permitted).\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the width.\n * @param height the height.\n * @param bgcolor the background colour.\n * @param observer an image observer.\n *\n * @return A boolean.\n */\n public boolean drawImage(Image image, int x, int y, int width, int height,\n Color bgcolor, ImageObserver observer) {\n ParamChecks.nullNotPermitted(image, \"image\");\n int w = image.getWidth(null);\n int h = image.getHeight(null);\n if (w == -1 || h == -1) {\n return false;\n }\n Paint savedPaint = getPaint();\n fill(new Rectangle2D.Double(x, y, w, h));\n setPaint(savedPaint);\n return drawImage(image, x, y, width, height, observer);\n }\n\n /**\n * Not implemented - see {@link Graphics#drawImage(Image, int, int, int,\n * int, int, int, int, int, ImageObserver)}.\n *\n * @param image the image.\n * @param dx1\n * @param dy1\n * @param dx2\n * @param dy2\n * @param sx1\n * @param sy1\n * @param sx2\n * @param sy2\n * @param observer\n */\n public boolean drawImage(Image image, int dx1, int dy1, int dx2, int dy2,\n int sx1, int sy1, int sx2, int sy2, ImageObserver observer) {\n // TODO Auto-generated method stub\n return false;\n }\n\n /**\n * Not implemented - see {@link Graphics#drawImage(Image, int, int, int,\n * int, int, int, int, int, Color, ImageObserver)}.\n *\n * @param image the image.\n * @param dx1\n * @param dy1\n * @param dx2\n * @param dy2\n * @param sx1\n * @param sy1\n * @param sx2\n * @param sy2\n * @param bgcolor\n * @param observer\n */\n public boolean drawImage(Image image, int dx1, int dy1, int dx2, int dy2,\n int sx1, int sy1, int sx2, int sy2, Color bgcolor,\n ImageObserver observer) {\n // TODO Auto-generated method stub\n return false;\n }\n\n /**\n * Releases resources held by this instance (but note that the caller\n * must dispose of the 'GC' passed to the constructor).\n *\n * @see java.awt.Graphics#dispose()\n */\n public void dispose() {\n // we dispose resources we own but user must dispose gc\n disposeResourcePool();\n }\n\n /**\n * Add given swt resource to the resource pool. All resources added\n * to the resource pool will be disposed when {@link #dispose()} is called.\n *\n * @param resource the resource to add to the pool.\n * @return the swt <code>Resource</code> just added.\n */\n private Resource addToResourcePool(Resource resource) {\n this.resourcePool.add(resource);\n return resource;\n }\n\n /**\n * Dispose the resource pool.\n */\n private void disposeResourcePool() {\n for (Iterator it = this.resourcePool.iterator(); it.hasNext();) {\n Resource resource = (Resource) it.next();\n resource.dispose();\n }\n this.fontsPool.clear();\n this.colorsPool.clear();\n this.transformsPool.clear();\n this.resourcePool.clear();\n }\n\n /**\n * Internal method to convert a AWT font object into\n * a SWT font resource. If a corresponding SWT font\n * instance is already in the pool, it will be used\n * instead of creating a new one. This is used in\n * {@link #setFont()} for instance.\n *\n * @param font The AWT font to convert.\n * @return The SWT font instance.\n */\n private org.eclipse.swt.graphics.Font getSwtFontFromPool(Font font) {\n org.eclipse.swt.graphics.Font swtFont = (org.eclipse.swt.graphics.Font)\n this.fontsPool.get(font);\n if (swtFont == null) {\n swtFont = new org.eclipse.swt.graphics.Font(this.gc.getDevice(),\n SWTUtils.toSwtFontData(this.gc.getDevice(), font, true));\n addToResourcePool(swtFont);\n this.fontsPool.put(font, swtFont);\n }\n return swtFont;\n }\n\n /**\n * Internal method to convert a AWT color object into\n * a SWT color resource. If a corresponding SWT color\n * instance is already in the pool, it will be used\n * instead of creating a new one. This is used in\n * {@link #setColor()} for instance.\n *\n * @param awtColor The AWT color to convert.\n * @return A SWT color instance.\n */\n private org.eclipse.swt.graphics.Color getSwtColorFromPool(Color awtColor) {\n org.eclipse.swt.graphics.Color swtColor =\n (org.eclipse.swt.graphics.Color)\n // we can't use the following valueOf() method, because it\n // won't compile with JDK1.4\n // this.colorsPool.get(Integer.valueOf(awtColor.getRGB()));\n this.colorsPool.get(new Integer(awtColor.getRGB()));\n if (swtColor == null) {\n swtColor = SWTUtils.toSwtColor(this.gc.getDevice(), awtColor);\n addToResourcePool(swtColor);\n // see comment above\n //this.colorsPool.put(Integer.valueOf(awtColor.getRGB()), swtColor);\n this.colorsPool.put(new Integer(awtColor.getRGB()), swtColor);\n }\n return swtColor;\n }\n\n /**\n * Internal method to convert a AWT transform object into\n * a SWT transform resource. If a corresponding SWT transform\n * instance is already in the pool, it will be used\n * instead of creating a new one. This is used in\n * {@link #setTransform()} for instance.\n *\n * @param awtTransform The AWT transform to convert.\n * @return A SWT transform instance.\n */\n private Transform getSwtTransformFromPool(AffineTransform awtTransform) {\n Transform t = (Transform) this.transformsPool.get(awtTransform);\n if (t == null) {\n t = new Transform(this.gc.getDevice());\n double[] matrix = new double[6];\n awtTransform.getMatrix(matrix);\n t.setElements((float) matrix[0], (float) matrix[1],\n (float) matrix[2], (float) matrix[3],\n (float) matrix[4], (float) matrix[5]);\n addToResourcePool(t);\n this.transformsPool.put(awtTransform, t);\n }\n return t;\n }\n\n /**\n * Perform a switch between foreground and background\n * color of gc. This is needed for consistency with\n * the awt behaviour, and is required notably for the\n * filling methods.\n */\n private void switchColors() {\n org.eclipse.swt.graphics.Color bg = this.gc.getBackground();\n org.eclipse.swt.graphics.Color fg = this.gc.getForeground();\n this.gc.setBackground(fg);\n this.gc.setForeground(bg);\n }\n\n /**\n * Converts an AWT <code>Shape</code> into a SWT <code>Path</code>.\n *\n * @param shape the shape (<code>null</code> not permitted).\n *\n * @return The path.\n */\n private Path toSwtPath(Shape shape) {\n int type;\n float[] coords = new float[6];\n Path path = new Path(this.gc.getDevice());\n PathIterator pit = shape.getPathIterator(null);\n while (!pit.isDone()) {\n type = pit.currentSegment(coords);\n switch (type) {\n case (PathIterator.SEG_MOVETO):\n path.moveTo(coords[0], coords[1]);\n break;\n case (PathIterator.SEG_LINETO):\n path.lineTo(coords[0], coords[1]);\n break;\n case (PathIterator.SEG_QUADTO):\n path.quadTo(coords[0], coords[1], coords[2], coords[3]);\n break;\n case (PathIterator.SEG_CUBICTO):\n path.cubicTo(coords[0], coords[1], coords[2],\n coords[3], coords[4], coords[5]);\n break;\n case (PathIterator.SEG_CLOSE):\n path.close();\n break;\n default:\n break;\n }\n pit.next();\n }\n return path;\n }\n\n /**\n * Converts an SWT transform into the equivalent AWT transform.\n *\n * @param swtTransform the SWT transform.\n *\n * @return The AWT transform.\n */\n private AffineTransform toAwtTransform(Transform swtTransform) {\n float[] elements = new float[6];\n swtTransform.getElements(elements);\n AffineTransform awtTransform = new AffineTransform(elements);\n return awtTransform;\n }\n\n /**\n * Returns the AWT line cap corresponding to the specified SWT line cap.\n *\n * @param swtLineCap the SWT line cap.\n *\n * @return The AWT line cap.\n */\n private int toAwtLineCap(int swtLineCap) {\n if (swtLineCap == SWT.CAP_FLAT) {\n return BasicStroke.CAP_BUTT;\n }\n else if (swtLineCap == SWT.CAP_ROUND) {\n return BasicStroke.CAP_ROUND;\n }\n else if (swtLineCap == SWT.CAP_SQUARE) {\n return BasicStroke.CAP_SQUARE;\n }\n else {\n throw new IllegalArgumentException(\"SWT LineCap \" + swtLineCap\n + \" not recognised\");\n }\n }\n\n /**\n * Returns the AWT line join corresponding to the specified SWT line join.\n *\n * @param swtLineJoin the SWT line join.\n *\n * @return The AWT line join.\n */\n private int toAwtLineJoin(int swtLineJoin) {\n if (swtLineJoin == SWT.JOIN_BEVEL) {\n return BasicStroke.JOIN_BEVEL;\n }\n else if (swtLineJoin == SWT.JOIN_MITER) {\n return BasicStroke.JOIN_MITER;\n }\n else if (swtLineJoin == SWT.JOIN_ROUND) {\n return BasicStroke.JOIN_ROUND;\n }\n else {\n throw new IllegalArgumentException(\"SWT LineJoin \" + swtLineJoin\n + \" not recognised\");\n }\n }\n\n /**\n * Returns the SWT line cap corresponding to the specified AWT line cap.\n *\n * @param awtLineCap the AWT line cap.\n *\n * @return The SWT line cap.\n */\n private int toSwtLineCap(int awtLineCap) {\n if (awtLineCap == BasicStroke.CAP_BUTT) {\n return SWT.CAP_FLAT;\n }\n else if (awtLineCap == BasicStroke.CAP_ROUND) {\n return SWT.CAP_ROUND;\n }\n else if (awtLineCap == BasicStroke.CAP_SQUARE) {\n return SWT.CAP_SQUARE;\n }\n else {\n throw new IllegalArgumentException(\"AWT LineCap \" + awtLineCap\n + \" not recognised\");\n }\n }\n\n /**\n * Returns the SWT line join corresponding to the specified AWT line join.\n *\n * @param awtLineJoin the AWT line join.\n *\n * @return The SWT line join.\n */\n private int toSwtLineJoin(int awtLineJoin) {\n if (awtLineJoin == BasicStroke.JOIN_BEVEL) {\n return SWT.JOIN_BEVEL;\n }\n else if (awtLineJoin == BasicStroke.JOIN_MITER) {\n return SWT.JOIN_MITER;\n }\n else if (awtLineJoin == BasicStroke.JOIN_ROUND) {\n return SWT.JOIN_ROUND;\n }\n else {\n throw new IllegalArgumentException(\"AWT LineJoin \" + awtLineJoin\n + \" not recognised\");\n }\n }\n}" }, { "identifier": "SWTUtils", "path": "lib/jfreechart-1.0.19/swt/org/jfree/experimental/swt/SWTUtils.java", "snippet": "public class SWTUtils {\n\n private final static String Az = \"ABCpqr\";\n\n /** A dummy JPanel used to provide font metrics. */\n protected static final JPanel DUMMY_PANEL = new JPanel();\n\n /**\n * Create a <code>FontData</code> object which encapsulate\n * the essential data to create a swt font. The data is taken\n * from the provided awt Font.\n * <p>Generally speaking, given a font size, the returned swt font\n * will display differently on the screen than the awt one.\n * Because the SWT toolkit use native graphical resources whenever\n * it is possible, this fact is platform dependent. To address\n * this issue, it is possible to enforce the method to return\n * a font with the same size (or at least as close as possible)\n * as the awt one.\n * <p>When the object is no more used, the user must explicitly\n * call the dispose method on the returned font to free the\n * operating system resources (the garbage collector won't do it).\n *\n * @param device The swt device to draw on (display or gc device).\n * @param font The awt font from which to get the data.\n * @param ensureSameSize A boolean used to enforce the same size\n * (in pixels) between the awt font and the newly created swt font.\n * @return a <code>FontData</code> object.\n */\n public static FontData toSwtFontData(Device device, java.awt.Font font,\n boolean ensureSameSize) {\n FontData fontData = new FontData();\n fontData.setName(font.getFamily());\n // SWT and AWT share the same style constants.\n fontData.setStyle(font.getStyle());\n // convert the font size (in pt for awt) to height in pixels for swt\n int height = (int) Math.round(font.getSize() * 72.0\n / device.getDPI().y);\n fontData.setHeight(height);\n // hack to ensure the newly created swt fonts will be rendered with the\n // same height as the awt one\n if (ensureSameSize) {\n GC tmpGC = new GC(device);\n Font tmpFont = new Font(device, fontData);\n tmpGC.setFont(tmpFont);\n if (tmpGC.textExtent(Az).x\n > DUMMY_PANEL.getFontMetrics(font).stringWidth(Az)) {\n while (tmpGC.textExtent(Az).x\n > DUMMY_PANEL.getFontMetrics(font).stringWidth(Az)) {\n tmpFont.dispose();\n height--;\n fontData.setHeight(height);\n tmpFont = new Font(device, fontData);\n tmpGC.setFont(tmpFont);\n }\n }\n else if (tmpGC.textExtent(Az).x\n < DUMMY_PANEL.getFontMetrics(font).stringWidth(Az)) {\n while (tmpGC.textExtent(Az).x\n < DUMMY_PANEL.getFontMetrics(font).stringWidth(Az)) {\n tmpFont.dispose();\n height++;\n fontData.setHeight(height);\n tmpFont = new Font(device, fontData);\n tmpGC.setFont(tmpFont);\n }\n }\n tmpFont.dispose();\n tmpGC.dispose();\n }\n return fontData;\n }\n\n /**\n * Create an awt font by converting as much information\n * as possible from the provided swt <code>FontData</code>.\n * <p>Generally speaking, given a font size, an swt font will\n * display differently on the screen than the corresponding awt\n * one. Because the SWT toolkit use native graphical ressources whenever\n * it is possible, this fact is platform dependent. To address\n * this issue, it is possible to enforce the method to return\n * an awt font with the same height as the swt one.\n *\n * @param device The swt device being drawn on (display or gc device).\n * @param fontData The swt font to convert.\n * @param ensureSameSize A boolean used to enforce the same size\n * (in pixels) between the swt font and the newly created awt font.\n * @return An awt font converted from the provided swt font.\n */\n public static java.awt.Font toAwtFont(Device device, FontData fontData,\n boolean ensureSameSize) {\n int height = (int) Math.round(fontData.getHeight() * device.getDPI().y\n / 72.0);\n // hack to ensure the newly created awt fonts will be rendered with the\n // same height as the swt one\n if (ensureSameSize) {\n GC tmpGC = new GC(device);\n Font tmpFont = new Font(device, fontData);\n tmpGC.setFont(tmpFont);\n JPanel DUMMY_PANEL = new JPanel();\n java.awt.Font tmpAwtFont = new java.awt.Font(fontData.getName(),\n fontData.getStyle(), height);\n if (DUMMY_PANEL.getFontMetrics(tmpAwtFont).stringWidth(Az)\n > tmpGC.textExtent(Az).x) {\n while (DUMMY_PANEL.getFontMetrics(tmpAwtFont).stringWidth(Az)\n > tmpGC.textExtent(Az).x) {\n height--;\n tmpAwtFont = new java.awt.Font(fontData.getName(),\n fontData.getStyle(), height);\n }\n }\n else if (DUMMY_PANEL.getFontMetrics(tmpAwtFont).stringWidth(Az)\n < tmpGC.textExtent(Az).x) {\n while (DUMMY_PANEL.getFontMetrics(tmpAwtFont).stringWidth(Az)\n < tmpGC.textExtent(Az).x) {\n height++;\n tmpAwtFont = new java.awt.Font(fontData.getName(),\n fontData.getStyle(), height);\n }\n }\n tmpFont.dispose();\n tmpGC.dispose();\n }\n return new java.awt.Font(fontData.getName(), fontData.getStyle(),\n height);\n }\n\n /**\n * Create an awt font by converting as much information\n * as possible from the provided swt <code>Font</code>.\n *\n * @param device The swt device to draw on (display or gc device).\n * @param font The swt font to convert.\n * @return An awt font converted from the provided swt font.\n */\n public static java.awt.Font toAwtFont(Device device, Font font) {\n FontData fontData = font.getFontData()[0];\n return toAwtFont(device, fontData, true);\n }\n\n /**\n * Creates an awt color instance to match the rgb values\n * of the specified swt color.\n *\n * @param color The swt color to match.\n * @return an awt color abject.\n */\n public static java.awt.Color toAwtColor(Color color) {\n return new java.awt.Color(color.getRed(), color.getGreen(),\n color.getBlue());\n }\n\n /**\n * Creates a swt color instance to match the rgb values\n * of the specified awt paint. For now, this method test\n * if the paint is a color and then return the adequate\n * swt color. Otherwise plain black is assumed.\n *\n * @param device The swt device to draw on (display or gc device).\n * @param paint The awt color to match.\n * @return a swt color object.\n */\n public static Color toSwtColor(Device device, java.awt.Paint paint) {\n java.awt.Color color;\n if (paint instanceof java.awt.Color) {\n color = (java.awt.Color) paint;\n }\n else {\n try {\n throw new Exception(\"only color is supported at present... \"\n + \"setting paint to uniform black color\");\n }\n catch (Exception e) {\n e.printStackTrace();\n color = new java.awt.Color(0, 0, 0);\n }\n }\n return new org.eclipse.swt.graphics.Color(device,\n color.getRed(), color.getGreen(), color.getBlue());\n }\n\n /**\n * Creates a swt color instance to match the rgb values\n * of the specified awt color. alpha channel is not supported.\n * Note that the dispose method will need to be called on the\n * returned object.\n *\n * @param device The swt device to draw on (display or gc device).\n * @param color The awt color to match.\n * @return a swt color object.\n */\n public static Color toSwtColor(Device device, java.awt.Color color) {\n return new org.eclipse.swt.graphics.Color(device,\n color.getRed(), color.getGreen(), color.getBlue());\n }\n\n /**\n * Transform an awt Rectangle2d instance into a swt one.\n * The coordinates are rounded to integer for the swt object.\n * @param rect2d The awt rectangle to map.\n * @return an swt <code>Rectangle</code> object.\n */\n public static Rectangle toSwtRectangle(Rectangle2D rect2d) {\n return new Rectangle(\n (int) Math.round(rect2d.getMinX()),\n (int) Math.round(rect2d.getMinY()),\n (int) Math.round(rect2d.getWidth()),\n (int) Math.round(rect2d.getHeight()));\n }\n\n /**\n * Transform a swt Rectangle instance into an awt one.\n * @param rect the swt <code>Rectangle</code>\n * @return a Rectangle2D.Double instance with\n * the eappropriate location and size.\n */\n public static Rectangle2D toAwtRectangle(Rectangle rect) {\n Rectangle2D rect2d = new Rectangle2D.Double();\n rect2d.setRect(rect.x, rect.y, rect.width, rect.height);\n return rect2d;\n }\n\n /**\n * Returns an AWT point with the same coordinates as the specified\n * SWT point.\n *\n * @param p the SWT point (<code>null</code> not permitted).\n *\n * @return An AWT point with the same coordinates as <code>p</code>.\n *\n * @see #toSwtPoint(java.awt.Point)\n */\n public static Point2D toAwtPoint(Point p) {\n return new java.awt.Point(p.x, p.y);\n }\n\n /**\n * Returns an SWT point with the same coordinates as the specified\n * AWT point.\n *\n * @param p the AWT point (<code>null</code> not permitted).\n *\n * @return An SWT point with the same coordinates as <code>p</code>.\n *\n * @see #toAwtPoint(Point)\n */\n public static Point toSwtPoint(java.awt.Point p) {\n return new Point(p.x, p.y);\n }\n\n /**\n * Returns an SWT point with the same coordinates as the specified AWT\n * point (rounded to integer values).\n *\n * @param p the AWT point (<code>null</code> not permitted).\n *\n * @return An SWT point with the same coordinates as <code>p</code>.\n *\n * @see #toAwtPoint(Point)\n */\n public static Point toSwtPoint(java.awt.geom.Point2D p) {\n return new Point((int) Math.round(p.getX()),\n (int) Math.round(p.getY()));\n }\n\n /**\n * Creates an AWT <code>MouseEvent</code> from a swt event.\n * This method helps passing SWT mouse event to awt components.\n * @param event The swt event.\n * @return A AWT mouse event based on the given SWT event.\n */\n public static MouseEvent toAwtMouseEvent(org.eclipse.swt.events.MouseEvent event) {\n int button = MouseEvent.NOBUTTON;\n switch (event.button) {\n case 1: button = MouseEvent.BUTTON1; break;\n case 2: button = MouseEvent.BUTTON2; break;\n case 3: button = MouseEvent.BUTTON3; break;\n }\n int modifiers = 0;\n if ((event.stateMask & SWT.CTRL) != 0) {\n modifiers |= InputEvent.CTRL_DOWN_MASK;\n }\n if ((event.stateMask & SWT.SHIFT) != 0) {\n modifiers |= InputEvent.SHIFT_DOWN_MASK;\n }\n if ((event.stateMask & SWT.ALT) != 0) {\n modifiers |= InputEvent.ALT_DOWN_MASK;\n }\n MouseEvent awtMouseEvent = new MouseEvent(DUMMY_PANEL, event.hashCode(),\n event.time, modifiers, event.x, event.y, 1, false, button);\n return awtMouseEvent;\n }\n\n /**\n * Converts an AWT image to SWT.\n *\n * @param image the image (<code>null</code> not permitted).\n *\n * @return Image data.\n */\n public static ImageData convertAWTImageToSWT(Image image) {\n ParamChecks.nullNotPermitted(image, \"image\");\n int w = image.getWidth(null);\n int h = image.getHeight(null);\n if (w == -1 || h == -1) {\n return null;\n }\n BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);\n Graphics g = bi.getGraphics();\n g.drawImage(image, 0, 0, null);\n g.dispose();\n return convertToSWT(bi);\n }\n\n /**\n * Converts a buffered image to SWT <code>ImageData</code>.\n *\n * @param bufferedImage the buffered image (<code>null</code> not\n * permitted).\n *\n * @return The image data.\n */\n public static ImageData convertToSWT(BufferedImage bufferedImage) {\n if (bufferedImage.getColorModel() instanceof DirectColorModel) {\n DirectColorModel colorModel\n = (DirectColorModel) bufferedImage.getColorModel();\n PaletteData palette = new PaletteData(colorModel.getRedMask(),\n colorModel.getGreenMask(), colorModel.getBlueMask());\n ImageData data = new ImageData(bufferedImage.getWidth(),\n bufferedImage.getHeight(), colorModel.getPixelSize(),\n palette);\n WritableRaster raster = bufferedImage.getRaster();\n int[] pixelArray = new int[3];\n for (int y = 0; y < data.height; y++) {\n for (int x = 0; x < data.width; x++) {\n raster.getPixel(x, y, pixelArray);\n int pixel = palette.getPixel(new RGB(pixelArray[0],\n pixelArray[1], pixelArray[2]));\n data.setPixel(x, y, pixel);\n }\n }\n return data;\n }\n else if (bufferedImage.getColorModel() instanceof IndexColorModel) {\n IndexColorModel colorModel = (IndexColorModel)\n bufferedImage.getColorModel();\n int size = colorModel.getMapSize();\n byte[] reds = new byte[size];\n byte[] greens = new byte[size];\n byte[] blues = new byte[size];\n colorModel.getReds(reds);\n colorModel.getGreens(greens);\n colorModel.getBlues(blues);\n RGB[] rgbs = new RGB[size];\n for (int i = 0; i < rgbs.length; i++) {\n rgbs[i] = new RGB(reds[i] & 0xFF, greens[i] & 0xFF,\n blues[i] & 0xFF);\n }\n PaletteData palette = new PaletteData(rgbs);\n ImageData data = new ImageData(bufferedImage.getWidth(),\n bufferedImage.getHeight(), colorModel.getPixelSize(),\n palette);\n data.transparentPixel = colorModel.getTransparentPixel();\n WritableRaster raster = bufferedImage.getRaster();\n int[] pixelArray = new int[1];\n for (int y = 0; y < data.height; y++) {\n for (int x = 0; x < data.width; x++) {\n raster.getPixel(x, y, pixelArray);\n data.setPixel(x, y, pixelArray[0]);\n }\n }\n return data;\n }\n return null;\n }\n\n}" } ]
import org.jfree.chart.entity.ChartEntity; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.ChartChangeEvent; import org.jfree.chart.event.ChartChangeListener; import org.jfree.chart.event.ChartProgressEvent; import org.jfree.chart.event.ChartProgressListener; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.ValueAxisPlot; import org.jfree.chart.plot.Zoomable; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.experimental.chart.swt.editor.SWTChartEditor; import org.jfree.experimental.swt.SWTGraphics2D; import org.jfree.experimental.swt.SWTUtils; import java.awt.Graphics; import java.awt.Point; import java.awt.RenderingHints; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.io.File; import java.io.IOException; import java.util.EventListener; import java.util.ResourceBundle; import javax.swing.event.EventListenerList; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.HelpListener; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.MouseTrackListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.jfree.chart.ChartMouseEvent; import org.jfree.chart.ChartMouseListener; import org.jfree.chart.ChartRenderingInfo; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart;
60,104
* @param x the x value (in screen coordinates). * @param y the y value (in screen coordinates). */ public void zoomOutBoth(double x, double y) { zoomOutDomain(x, y); zoomOutRange(x, y); } /** * Increases the length of the domain axis, centered about the given * coordinate on the screen. The length of the domain axis is increased * by the value of {@link #getZoomOutFactor()}. * * @param x the x coordinate (in screen coordinates). * @param y the y-coordinate (in screen coordinates). */ public void zoomOutDomain(double x, double y) { Plot p = this.chart.getPlot(); if (p instanceof Zoomable) { Zoomable z = (Zoomable) p; z.zoomDomainAxes(this.zoomOutFactor, this.info.getPlotInfo(), translateScreenToJava2D(new Point((int) x, (int) y))); } } /** * Increases the length the range axis, centered about the given * coordinate on the screen. The length of the range axis is increased * by the value of {@link #getZoomOutFactor()}. * * @param x the x coordinate (in screen coordinates). * @param y the y-coordinate (in screen coordinates). */ public void zoomOutRange(double x, double y) { Plot p = this.chart.getPlot(); if (p instanceof Zoomable) { Zoomable z = (Zoomable) p; z.zoomRangeAxes(this.zoomOutFactor, this.info.getPlotInfo(), translateScreenToJava2D(new Point((int) x, (int) y))); } } /** * Zooms in on a selected region. * * @param selection the selected region. */ public void zoom(Rectangle selection) { // get the origin of the zoom selection in the Java2D space used for // drawing the chart (that is, before any scaling to fit the panel) Point2D selectOrigin = translateScreenToJava2D( new Point(selection.x, selection.y)); PlotRenderingInfo plotInfo = this.info.getPlotInfo(); Rectangle scaledDataArea = getScreenDataArea( (selection.x + selection.width / 2), (selection.y + selection.height / 2)); if ((selection.height > 0) && (selection.width > 0)) { double hLower = (selection.x - scaledDataArea.x) / (double) scaledDataArea.width; double hUpper = (selection.x + selection.width - scaledDataArea.x) / (double) scaledDataArea.width; double vLower = (scaledDataArea.y + scaledDataArea.height - selection.y - selection.height) / (double) scaledDataArea.height; double vUpper = (scaledDataArea.y + scaledDataArea.height - selection.y) / (double) scaledDataArea.height; Plot p = this.chart.getPlot(); if (p instanceof Zoomable) { Zoomable z = (Zoomable) p; if (z.getOrientation() == PlotOrientation.HORIZONTAL) { z.zoomDomainAxes(vLower, vUpper, plotInfo, selectOrigin); z.zoomRangeAxes(hLower, hUpper, plotInfo, selectOrigin); } else { z.zoomDomainAxes(hLower, hUpper, plotInfo, selectOrigin); z.zoomRangeAxes(vLower, vUpper, plotInfo, selectOrigin); } } } } /** * Receives notification of changes to the chart, and redraws the chart. * * @param event details of the chart change event. */ public void chartChanged(ChartChangeEvent event) { this.refreshBuffer = true; Plot plot = this.chart.getPlot(); if (plot instanceof Zoomable) { Zoomable z = (Zoomable) plot; this.orientation = z.getOrientation(); } this.canvas.redraw(); } /** * Forces a redraw of the canvas by invoking a new PaintEvent. */ public void forceRedraw() { Event ev = new Event(); ev.gc = new GC(this.canvas); ev.x = 0; ev.y = 0; ev.width = this.canvas.getBounds().width; ev.height = this.canvas.getBounds().height; ev.count = 0; this.canvas.notifyListeners(SWT.Paint, ev); ev.gc.dispose(); } /** * Adds a listener to the list of objects listening for chart mouse events. * * @param listener the listener (<code>null</code> not permitted). */
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------- * ChartComposite.java * ------------------- * (C) Copyright 2006-2012, by Henry Proudhon and Contributors. * * Original Author: Henry Proudhon (henry.proudhon AT ensmp.fr); * Contributor(s): David Gilbert (for Object Refinery Limited); * Cedric Chabanois (cchabanois AT no-log.org); * Christoph Beck; * Sebastiao Correia (patch 3463807); * Jonas Rüttimann (bug fix 2963199); * Bernard Sarter; * * Changes * ------- * 19-Jun-2006 : New class (HP); * 06-Nov-2006 : Added accessor methods for zoomInFactor and zoomOutFactor (DG); * 28-Nov-2006 : Added support for trace lines (HP); * 30-Nov-2006 : Improved zoom box handling (HP); * 06-Dec-2006 : Added (simplified) tool tip support (HP); * 11-Dec-2006 : Fixed popup menu location by fgiust, bug 1612770 (HP); * 31-Jan-2007 : Fixed some issues with the trace lines, fixed cross hair not * being drawn, added getter and setter methods for the trace * lines (HP); * 07-Apr-2007 : Changed this.redraw() into canvas.redraw() to fix redraw * problems (HP); * 19-May-2007 : Small fix in paintControl to check for null charts, bug * 1719260 (HP); * 19-May-2007 : Corrected bug with scaling when the drawing region is larger * than maximum draw width/height (HP); * 23-May-2007 : Added some dispose call to free SWT resources, patch sent by * Cédric Chabanois (CC); * 06-Jun-2007 : Fixed minor issues with tooltips. bug reported and fix * proposed by Christoph Beck, bug 1726404 (HP); * 22-Oct-2007 : Added addChartMouseListener and removeChartMouseListener * methods as suggested by Christoph Beck, bug 1742002 (HP); * 22-Oct-2007 : Fixed bug in zooming with multiple plots (HP); * 22-Oct-2007 : Check for null zoom point when restoring auto range and domain * bounds (HP); * 22-Oct-2007 : Pass mouse moved events to listening ChartMouseListeners (HP); * 22-Oct-2007 : Refactored class, now implements PaintListener, MouseListener, * MouseMoveListener. Made the chart field be private again and * added new method addSWTListener to allow custom behavior. * 14-Nov-2007 : Create canvas with SWT.DOUBLE_BUFFER, added * getChartRenderingInfo(), is/setDomainZoomable() and * is/setRangeZoomable() as per feature request (DG); * 11-Jul-2008 : Bug 1994355 fix (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see patch 1607918 by * Jess Thrysoee (DG); * 08-Jan-2012 : Dispose popup-menu (patch 3463807 by Sebastiao Correia) (DG) * 05-Jul-2012 : Fix SWT print (bug 2963199 by Jonas Rüttimann); * 26-Jul-2013 : Fix memory leak (patch in forum from Bernard Sarter) (DG); * */ package org.jfree.experimental.chart.swt; /** * A SWT GUI composite for displaying a {@link JFreeChart} object. * <p> * The composite listens to the chart to receive notification of changes to any * component of the chart. The chart is redrawn automatically whenever this * notification is received. */ public class ChartComposite extends Composite implements ChartChangeListener, ChartProgressListener, PaintListener, SelectionListener, MouseListener, MouseMoveListener, Printable { /** Default setting for buffer usage. */ public static final boolean DEFAULT_BUFFER_USED = false; /** The default panel width. */ public static final int DEFAULT_WIDTH = 680; /** The default panel height. */ public static final int DEFAULT_HEIGHT = 420; /** The default limit below which chart scaling kicks in. */ public static final int DEFAULT_MINIMUM_DRAW_WIDTH = 300; /** The default limit below which chart scaling kicks in. */ public static final int DEFAULT_MINIMUM_DRAW_HEIGHT = 200; /** The default limit below which chart scaling kicks in. */ public static final int DEFAULT_MAXIMUM_DRAW_WIDTH = 800; /** The default limit below which chart scaling kicks in. */ public static final int DEFAULT_MAXIMUM_DRAW_HEIGHT = 600; /** The minimum size required to perform a zoom on a rectangle */ public static final int DEFAULT_ZOOM_TRIGGER_DISTANCE = 10; /** Properties action command. */ public static final String PROPERTIES_COMMAND = "PROPERTIES"; /** Save action command. */ public static final String SAVE_COMMAND = "SAVE"; /** Print action command. */ public static final String PRINT_COMMAND = "PRINT"; /** Zoom in (both axes) action command. */ public static final String ZOOM_IN_BOTH_COMMAND = "ZOOM_IN_BOTH"; /** Zoom in (domain axis only) action command. */ public static final String ZOOM_IN_DOMAIN_COMMAND = "ZOOM_IN_DOMAIN"; /** Zoom in (range axis only) action command. */ public static final String ZOOM_IN_RANGE_COMMAND = "ZOOM_IN_RANGE"; /** Zoom out (both axes) action command. */ public static final String ZOOM_OUT_BOTH_COMMAND = "ZOOM_OUT_BOTH"; /** Zoom out (domain axis only) action command. */ public static final String ZOOM_OUT_DOMAIN_COMMAND = "ZOOM_DOMAIN_BOTH"; /** Zoom out (range axis only) action command. */ public static final String ZOOM_OUT_RANGE_COMMAND = "ZOOM_RANGE_BOTH"; /** Zoom reset (both axes) action command. */ public static final String ZOOM_RESET_BOTH_COMMAND = "ZOOM_RESET_BOTH"; /** Zoom reset (domain axis only) action command. */ public static final String ZOOM_RESET_DOMAIN_COMMAND = "ZOOM_RESET_DOMAIN"; /** Zoom reset (range axis only) action command. */ public static final String ZOOM_RESET_RANGE_COMMAND = "ZOOM_RESET_RANGE"; /** The chart that is displayed in the panel. */ private JFreeChart chart; /** The canvas to display the chart. */ private Canvas canvas; /** Storage for registered (chart) mouse listeners. */ private EventListenerList chartMouseListeners; /** A flag that controls whether or not the off-screen buffer is used. */ private boolean useBuffer; /** A flag that indicates that the buffer should be refreshed. */ private boolean refreshBuffer; /** A flag that indicates that the tooltips should be displayed. */ private boolean displayToolTips; /** A buffer for the rendered chart. */ private org.eclipse.swt.graphics.Image chartBuffer; /** The height of the chart buffer. */ private int chartBufferHeight; /** The width of the chart buffer. */ private int chartBufferWidth; /** * The minimum width for drawing a chart (uses scaling for smaller widths). */ private int minimumDrawWidth; /** * The minimum height for drawing a chart (uses scaling for smaller * heights). */ private int minimumDrawHeight; /** * The maximum width for drawing a chart (uses scaling for bigger * widths). */ private int maximumDrawWidth; /** * The maximum height for drawing a chart (uses scaling for bigger * heights). */ private int maximumDrawHeight; /** The popup menu for the frame. */ private Menu popup; /** The drawing info collected the last time the chart was drawn. */ private ChartRenderingInfo info; /** The chart anchor point. */ private Point2D anchor; /** The scale factor used to draw the chart. */ private double scaleX; /** The scale factor used to draw the chart. */ private double scaleY; /** The plot orientation. */ private PlotOrientation orientation = PlotOrientation.VERTICAL; /** A flag that controls whether or not domain zooming is enabled. */ private boolean domainZoomable = false; /** A flag that controls whether or not range zooming is enabled. */ private boolean rangeZoomable = false; /** * The zoom rectangle starting point (selected by the user with a mouse * click). This is a point on the screen, not the chart (which may have * been scaled up or down to fit the panel). */ private org.eclipse.swt.graphics.Point zoomPoint = null; /** The zoom rectangle (selected by the user with the mouse). */ private transient Rectangle zoomRectangle = null; /** Controls if the zoom rectangle is drawn as an outline or filled. */ //TODO private boolean fillZoomRectangle = true; /** The minimum distance required to drag the mouse to trigger a zoom. */ private int zoomTriggerDistance; /** A flag that controls whether or not horizontal tracing is enabled. */ private boolean horizontalAxisTrace = false; /** A flag that controls whether or not vertical tracing is enabled. */ private boolean verticalAxisTrace = false; /** A vertical trace line. */ private transient int verticalTraceLineX; /** A horizontal trace line. */ private transient int horizontalTraceLineY; /** Menu item for zooming in on a chart (both axes). */ private MenuItem zoomInBothMenuItem; /** Menu item for zooming in on a chart (domain axis). */ private MenuItem zoomInDomainMenuItem; /** Menu item for zooming in on a chart (range axis). */ private MenuItem zoomInRangeMenuItem; /** Menu item for zooming out on a chart. */ private MenuItem zoomOutBothMenuItem; /** Menu item for zooming out on a chart (domain axis). */ private MenuItem zoomOutDomainMenuItem; /** Menu item for zooming out on a chart (range axis). */ private MenuItem zoomOutRangeMenuItem; /** Menu item for resetting the zoom (both axes). */ private MenuItem zoomResetBothMenuItem; /** Menu item for resetting the zoom (domain axis only). */ private MenuItem zoomResetDomainMenuItem; /** Menu item for resetting the zoom (range axis only). */ private MenuItem zoomResetRangeMenuItem; /** A flag that controls whether or not file extensions are enforced. */ private boolean enforceFileExtensions; /** The factor used to zoom in on an axis range. */ private double zoomInFactor = 0.5; /** The factor used to zoom out on an axis range. */ private double zoomOutFactor = 2.0; /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.LocalizationBundle"); /** * Create a new chart composite with a default FillLayout. * This way, when drawn, the chart will fill all the space. * @param comp The parent. * @param style The style of the composite. */ public ChartComposite(Composite comp, int style) { this(comp, style, null, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_MINIMUM_DRAW_WIDTH, DEFAULT_MINIMUM_DRAW_HEIGHT, DEFAULT_MAXIMUM_DRAW_WIDTH, DEFAULT_MAXIMUM_DRAW_HEIGHT, DEFAULT_BUFFER_USED, true, // properties true, // save true, // print true, // zoom true // tooltips ); } /** * Constructs a panel that displays the specified chart. * * @param comp The parent. * @param style The style of the composite. * @param chart the chart. */ public ChartComposite(Composite comp, int style, JFreeChart chart) { this(comp, style, chart, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_MINIMUM_DRAW_WIDTH, DEFAULT_MINIMUM_DRAW_HEIGHT, DEFAULT_MAXIMUM_DRAW_WIDTH, DEFAULT_MAXIMUM_DRAW_HEIGHT, DEFAULT_BUFFER_USED, true, // properties true, // save true, // print true, // zoom true // tooltips ); } /** * Constructs a panel containing a chart. * * @param comp The parent. * @param style The style of the composite. * @param chart the chart. * @param useBuffer a flag controlling whether or not an off-screen buffer * is used. */ public ChartComposite(Composite comp, int style, JFreeChart chart, boolean useBuffer) { this(comp, style, chart, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_MINIMUM_DRAW_WIDTH, DEFAULT_MINIMUM_DRAW_HEIGHT, DEFAULT_MAXIMUM_DRAW_WIDTH, DEFAULT_MAXIMUM_DRAW_HEIGHT, useBuffer, true, // properties true, // save true, // print true, // zoom true // tooltips ); } /** * Constructs a JFreeChart panel. * * @param comp The parent. * @param style The style of the composite. * @param chart the chart. * @param properties a flag indicating whether or not the chart property * editor should be available via the popup menu. * @param save a flag indicating whether or not save options should be * available via the popup menu. * @param print a flag indicating whether or not the print option * should be available via the popup menu. * @param zoom a flag indicating whether or not zoom options should * be added to the popup menu. * @param tooltips a flag indicating whether or not tooltips should be * enabled for the chart. */ public ChartComposite( Composite comp, int style, JFreeChart chart, boolean properties, boolean save, boolean print, boolean zoom, boolean tooltips) { this( comp, style, chart, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_MINIMUM_DRAW_WIDTH, DEFAULT_MINIMUM_DRAW_HEIGHT, DEFAULT_MAXIMUM_DRAW_WIDTH, DEFAULT_MAXIMUM_DRAW_HEIGHT, DEFAULT_BUFFER_USED, properties, save, print, zoom, tooltips ); } /** * Constructs a JFreeChart panel. * * @param comp The parent. * @param style The style of the composite. * @param jfreechart the chart. * @param width the preferred width of the panel. * @param height the preferred height of the panel. * @param minimumDrawW the minimum drawing width. * @param minimumDrawH the minimum drawing height. * @param maximumDrawW the maximum drawing width. * @param maximumDrawH the maximum drawing height. * @param usingBuffer a flag that indicates whether to use the off-screen * buffer to improve performance (at the expense of * memory). * @param properties a flag indicating whether or not the chart property * editor should be available via the popup menu. * @param save a flag indicating whether or not save options should be * available via the popup menu. * @param print a flag indicating whether or not the print option * should be available via the popup menu. * @param zoom a flag indicating whether or not zoom options should be * added to the popup menu. * @param tooltips a flag indicating whether or not tooltips should be * enabled for the chart. */ public ChartComposite(Composite comp, int style, JFreeChart jfreechart, int width, int height, int minimumDrawW, int minimumDrawH, int maximumDrawW, int maximumDrawH, boolean usingBuffer, boolean properties, boolean save, boolean print, boolean zoom, boolean tooltips) { super(comp, style); setChart(jfreechart); this.chartMouseListeners = new EventListenerList(); setLayout(new FillLayout()); this.info = new ChartRenderingInfo(); this.useBuffer = usingBuffer; this.refreshBuffer = false; this.minimumDrawWidth = minimumDrawW; this.minimumDrawHeight = minimumDrawH; this.maximumDrawWidth = maximumDrawW; this.maximumDrawHeight = maximumDrawH; this.zoomTriggerDistance = DEFAULT_ZOOM_TRIGGER_DISTANCE; setDisplayToolTips(tooltips); // create the canvas and add the required listeners this.canvas = new Canvas(this, SWT.DOUBLE_BUFFERED | SWT.NO_BACKGROUND); this.canvas.addPaintListener(this); this.canvas.addMouseListener(this); this.canvas.addMouseMoveListener(this); this.canvas.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { org.eclipse.swt.graphics.Image img; img = (org.eclipse.swt.graphics.Image) canvas.getData("double-buffer-image"); if (img != null) { img.dispose(); } } }); // set up popup menu... this.popup = null; if (properties || save || print || zoom) this.popup = createPopupMenu(properties, save, print, zoom); this.enforceFileExtensions = true; } /** * Returns the X scale factor for the chart. This will be 1.0 if no * scaling has been used. * * @return The scale factor. */ public double getScaleX() { return this.scaleX; } /** * Returns the Y scale factory for the chart. This will be 1.0 if no * scaling has been used. * * @return The scale factor. */ public double getScaleY() { return this.scaleY; } /** * Returns the anchor point. * * @return The anchor point (possibly <code>null</code>). */ public Point2D getAnchor() { return this.anchor; } /** * Sets the anchor point. This method is provided for the use of * subclasses, not end users. * * @param anchor the anchor point (<code>null</code> permitted). */ protected void setAnchor(Point2D anchor) { this.anchor = anchor; } /** * Returns the chart contained in the panel. * * @return The chart (possibly <code>null</code>). */ public JFreeChart getChart() { return this.chart; } /** * Sets the chart that is displayed in the panel. * * @param chart the chart (<code>null</code> permitted). */ public void setChart(JFreeChart chart) { // stop listening for changes to the existing chart if (this.chart != null) { this.chart.removeChangeListener(this); this.chart.removeProgressListener(this); } // add the new chart this.chart = chart; if (chart != null) { this.chart.addChangeListener(this); this.chart.addProgressListener(this); Plot plot = chart.getPlot(); this.domainZoomable = false; this.rangeZoomable = false; if (plot instanceof Zoomable) { Zoomable z = (Zoomable) plot; this.domainZoomable = z.isDomainZoomable(); this.rangeZoomable = z.isRangeZoomable(); this.orientation = z.getOrientation(); } } else { this.domainZoomable = false; this.rangeZoomable = false; } if (this.useBuffer) { this.refreshBuffer = true; } } /** * Returns the chart rendering info from the most recent chart redraw. * * @return The chart rendering info (possibly <code>null</code>). */ public ChartRenderingInfo getChartRenderingInfo() { return this.info; } /** * Returns the flag that determines whether or not zooming is enabled for * the domain axis. * * @return A boolean. */ public boolean isDomainZoomable() { return this.domainZoomable; } /** * Sets the flag that controls whether or not zooming is enable for the * domain axis. A check is made to ensure that the current plot supports * zooming for the domain values. * * @param flag <code>true</code> enables zooming if possible. */ public void setDomainZoomable(boolean flag) { if (flag) { Plot plot = this.chart.getPlot(); if (plot instanceof Zoomable) { Zoomable z = (Zoomable) plot; this.domainZoomable = flag && (z.isDomainZoomable()); } } else { this.domainZoomable = false; } } /** * Returns the flag that determines whether or not zooming is enabled for * the range axis. * * @return A boolean. */ public boolean isRangeZoomable() { return this.rangeZoomable; } /** * A flag that controls mouse-based zooming on the vertical axis. * * @param flag <code>true</code> enables zooming. */ public void setRangeZoomable(boolean flag) { if (flag) { Plot plot = this.chart.getPlot(); if (plot instanceof Zoomable) { Zoomable z = (Zoomable) plot; this.rangeZoomable = flag && (z.isRangeZoomable()); } } else { this.rangeZoomable = false; } } /** * Returns the zoom in factor. * * @return The zoom in factor. * * @see #setZoomInFactor(double) */ public double getZoomInFactor() { return this.zoomInFactor; } /** * Sets the zoom in factor. * * @param factor the factor. * * @see #getZoomInFactor() */ public void setZoomInFactor(double factor) { this.zoomInFactor = factor; } /** * Returns the zoom out factor. * * @return The zoom out factor. * * @see #setZoomOutFactor(double) */ public double getZoomOutFactor() { return this.zoomOutFactor; } /** * Sets the zoom out factor. * * @param factor the factor. * * @see #getZoomOutFactor() */ public void setZoomOutFactor(double factor) { this.zoomOutFactor = factor; } /** * Displays a dialog that allows the user to edit the properties for the * current chart. */ private void attemptEditChartProperties() { SWTChartEditor editor = new SWTChartEditor(this.canvas.getDisplay(), this.chart); //ChartEditorManager.getChartEditor(canvas.getDisplay(), this.chart); editor.open(); } /** * Returns <code>true</code> if file extensions should be enforced, and * <code>false</code> otherwise. * * @return The flag. */ public boolean isEnforceFileExtensions() { return this.enforceFileExtensions; } /** * Sets a flag that controls whether or not file extensions are enforced. * * @param enforce the new flag value. */ public void setEnforceFileExtensions(boolean enforce) { this.enforceFileExtensions = enforce; } /** * Opens a file chooser and gives the user an opportunity to save the chart * in PNG format. * * @throws IOException if there is an I/O error. */ public void doSaveAs() throws IOException { FileDialog fileDialog = new FileDialog(this.canvas.getShell(), SWT.SAVE); String[] extensions = {"*.png"}; fileDialog.setFilterExtensions(extensions); String filename = fileDialog.open(); if (filename != null) { if (isEnforceFileExtensions()) { if (!filename.endsWith(".png")) { filename = filename + ".png"; } } //TODO replace getSize by getBounds ? ChartUtilities.saveChartAsPNG(new File(filename), this.chart, this.canvas.getSize().x, this.canvas.getSize().y); } } /** * Returns a point based on (x, y) but constrained to be within the bounds * of the given rectangle. This method could be moved to JCommon. * * @param x the x-coordinate. * @param y the y-coordinate. * @param area the rectangle (<code>null</code> not permitted). * * @return A point within the rectangle. */ private org.eclipse.swt.graphics.Point getPointInRectangle(int x, int y, Rectangle area) { x = Math.max(area.x, Math.min(x, area.x + area.width)); y = Math.max(area.y, Math.min(y, area.y + area.height)); return new org.eclipse.swt.graphics.Point(x, y); } /** * Zooms in on an anchor point (specified in screen coordinate space). * * @param x the x value (in screen coordinates). * @param y the y value (in screen coordinates). */ public void zoomInBoth(double x, double y) { zoomInDomain(x, y); zoomInRange(x, y); } /** * Decreases the length of the domain axis, centered about the given * coordinate on the screen. The length of the domain axis is reduced * by the value of {@link #getZoomInFactor()}. * * @param x the x coordinate (in screen coordinates). * @param y the y-coordinate (in screen coordinates). */ public void zoomInDomain(double x, double y) { Plot p = this.chart.getPlot(); if (p instanceof Zoomable) { Zoomable plot = (Zoomable) p; plot.zoomDomainAxes(this.zoomInFactor, this.info.getPlotInfo(), translateScreenToJava2D(new Point((int) x, (int) y))); } } /** * Decreases the length of the range axis, centered about the given * coordinate on the screen. The length of the range axis is reduced by * the value of {@link #getZoomInFactor()}. * * @param x the x-coordinate (in screen coordinates). * @param y the y coordinate (in screen coordinates). */ public void zoomInRange(double x, double y) { Plot p = this.chart.getPlot(); if (p instanceof Zoomable) { Zoomable z = (Zoomable) p; z.zoomRangeAxes(this.zoomInFactor, this.info.getPlotInfo(), translateScreenToJava2D(new Point((int) x, (int) y))); } } /** * Zooms out on an anchor point (specified in screen coordinate space). * * @param x the x value (in screen coordinates). * @param y the y value (in screen coordinates). */ public void zoomOutBoth(double x, double y) { zoomOutDomain(x, y); zoomOutRange(x, y); } /** * Increases the length of the domain axis, centered about the given * coordinate on the screen. The length of the domain axis is increased * by the value of {@link #getZoomOutFactor()}. * * @param x the x coordinate (in screen coordinates). * @param y the y-coordinate (in screen coordinates). */ public void zoomOutDomain(double x, double y) { Plot p = this.chart.getPlot(); if (p instanceof Zoomable) { Zoomable z = (Zoomable) p; z.zoomDomainAxes(this.zoomOutFactor, this.info.getPlotInfo(), translateScreenToJava2D(new Point((int) x, (int) y))); } } /** * Increases the length the range axis, centered about the given * coordinate on the screen. The length of the range axis is increased * by the value of {@link #getZoomOutFactor()}. * * @param x the x coordinate (in screen coordinates). * @param y the y-coordinate (in screen coordinates). */ public void zoomOutRange(double x, double y) { Plot p = this.chart.getPlot(); if (p instanceof Zoomable) { Zoomable z = (Zoomable) p; z.zoomRangeAxes(this.zoomOutFactor, this.info.getPlotInfo(), translateScreenToJava2D(new Point((int) x, (int) y))); } } /** * Zooms in on a selected region. * * @param selection the selected region. */ public void zoom(Rectangle selection) { // get the origin of the zoom selection in the Java2D space used for // drawing the chart (that is, before any scaling to fit the panel) Point2D selectOrigin = translateScreenToJava2D( new Point(selection.x, selection.y)); PlotRenderingInfo plotInfo = this.info.getPlotInfo(); Rectangle scaledDataArea = getScreenDataArea( (selection.x + selection.width / 2), (selection.y + selection.height / 2)); if ((selection.height > 0) && (selection.width > 0)) { double hLower = (selection.x - scaledDataArea.x) / (double) scaledDataArea.width; double hUpper = (selection.x + selection.width - scaledDataArea.x) / (double) scaledDataArea.width; double vLower = (scaledDataArea.y + scaledDataArea.height - selection.y - selection.height) / (double) scaledDataArea.height; double vUpper = (scaledDataArea.y + scaledDataArea.height - selection.y) / (double) scaledDataArea.height; Plot p = this.chart.getPlot(); if (p instanceof Zoomable) { Zoomable z = (Zoomable) p; if (z.getOrientation() == PlotOrientation.HORIZONTAL) { z.zoomDomainAxes(vLower, vUpper, plotInfo, selectOrigin); z.zoomRangeAxes(hLower, hUpper, plotInfo, selectOrigin); } else { z.zoomDomainAxes(hLower, hUpper, plotInfo, selectOrigin); z.zoomRangeAxes(vLower, vUpper, plotInfo, selectOrigin); } } } } /** * Receives notification of changes to the chart, and redraws the chart. * * @param event details of the chart change event. */ public void chartChanged(ChartChangeEvent event) { this.refreshBuffer = true; Plot plot = this.chart.getPlot(); if (plot instanceof Zoomable) { Zoomable z = (Zoomable) plot; this.orientation = z.getOrientation(); } this.canvas.redraw(); } /** * Forces a redraw of the canvas by invoking a new PaintEvent. */ public void forceRedraw() { Event ev = new Event(); ev.gc = new GC(this.canvas); ev.x = 0; ev.y = 0; ev.width = this.canvas.getBounds().width; ev.height = this.canvas.getBounds().height; ev.count = 0; this.canvas.notifyListeners(SWT.Paint, ev); ev.gc.dispose(); } /** * Adds a listener to the list of objects listening for chart mouse events. * * @param listener the listener (<code>null</code> not permitted). */
public void addChartMouseListener(ChartMouseListener listener) {
1
2023-12-24 12:36:47+00:00
128k
Hoto-Mocha/Re-ARranged-Pixel-Dungeon
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/mobs/CrystalSpire.java
[ { "identifier": "Assets", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/Assets.java", "snippet": "public class Assets {\n\n\tpublic static class Effects {\n\t\tpublic static final String EFFECTS = \"effects/effects.png\";\n\t\tpublic static final String FIREBALL = \"effects/fireball.png\";\n\t\tpublic static final String SPECKS = \"effects/specks.png\";\n\t\tpublic static final String SPELL_ICONS = \"effects/spell_icons.png\";\n\t}\n\n\tpublic static class Environment {\n\t\tpublic static final String TERRAIN_FEATURES = \"environment/terrain_features.png\";\n\n\t\tpublic static final String VISUAL_GRID = \"environment/visual_grid.png\";\n\t\tpublic static final String WALL_BLOCKING= \"environment/wall_blocking.png\";\n\n\t\tpublic static final String TILES_SEWERS = \"environment/tiles_sewers.png\";\n\t\tpublic static final String TILES_PRISON = \"environment/tiles_prison.png\";\n\t\tpublic static final String TILES_CAVES = \"environment/tiles_caves.png\";\n\t\tpublic static final String TILES_CITY = \"environment/tiles_city.png\";\n\t\tpublic static final String TILES_HALLS = \"environment/tiles_halls.png\";\n\t\tpublic static final String TILES_TEMPLE = \"environment/tiles_temple.png\";\n\t\tpublic static final String TILES_LABS\t= \"environment/tiles_labs.png\";\n\n\t\tpublic static final String WATER_SEWERS = \"environment/water0.png\";\n\t\tpublic static final String WATER_PRISON = \"environment/water1.png\";\n\t\tpublic static final String WATER_CAVES = \"environment/water2.png\";\n\t\tpublic static final String WATER_CITY = \"environment/water3.png\";\n\t\tpublic static final String WATER_HALLS = \"environment/water4.png\";\n\t\tpublic static final String WATER_TEMPLE = \"environment/water0_temple.png\";\n\t\tpublic static final String WATER_LABS\t= \"environment/water5.png\";\n\n\t\tpublic static final String WEAK_FLOOR = \"environment/custom_tiles/weak_floor.png\";\n\t\tpublic static final String SEWER_BOSS = \"environment/custom_tiles/sewer_boss.png\";\n\t\tpublic static final String PRISON_QUEST = \"environment/custom_tiles/prison_quest.png\";\n\t\tpublic static final String PRISON_EXIT = \"environment/custom_tiles/prison_exit.png\";\n\t\tpublic static final String CAVES_QUEST = \"environment/custom_tiles/caves_quest.png\";\n\t\tpublic static final String CAVES_BOSS = \"environment/custom_tiles/caves_boss.png\";\n\t\tpublic static final String CITY_BOSS = \"environment/custom_tiles/city_boss.png\";\n\t\tpublic static final String HALLS_SP = \"environment/custom_tiles/halls_special.png\";\n\t\tpublic static final String TEMPLE_SP = \"environment/custom_tiles/temple_special.png\";\n\t}\n\t\n\t//TODO include other font assets here? Some are platform specific though...\n\tpublic static class Fonts {\n\t\tpublic static final String PIXELFONT= \"fonts/pixel_font.png\";\n\t}\n\n\tpublic static class Interfaces {\n\t\tpublic static final String ARCS_BG = \"interfaces/arcs1.png\";\n\t\tpublic static final String ARCS_FG = \"interfaces/arcs2.png\";\n\n\t\tpublic static final String BANNERS = \"interfaces/banners.png\";\n\t\tpublic static final String BADGES = \"interfaces/badges.png\";\n\t\tpublic static final String LOCKED = \"interfaces/locked_badge.png\";\n\n\t\tpublic static final String CHROME = \"interfaces/chrome.png\";\n\t\tpublic static final String ICONS = \"interfaces/icons.png\";\n\t\tpublic static final String STATUS = \"interfaces/status_pane.png\";\n\t\tpublic static final String MENU = \"interfaces/menu_pane.png\";\n\t\tpublic static final String MENU_BTN = \"interfaces/menu_button.png\";\n\t\tpublic static final String TOOLBAR = \"interfaces/toolbar.png\";\n\t\tpublic static final String SHADOW = \"interfaces/shadow.png\";\n\t\tpublic static final String BOSSHP = \"interfaces/boss_hp.png\";\n\n\t\tpublic static final String SURFACE = \"interfaces/surface.png\";\n\n\t\tpublic static final String LOADING_SEWERS = \"interfaces/loading_sewers.png\";\n\t\tpublic static final String LOADING_PRISON = \"interfaces/loading_prison.png\";\n\t\tpublic static final String LOADING_CAVES = \"interfaces/loading_caves.png\";\n\t\tpublic static final String LOADING_CITY = \"interfaces/loading_city.png\";\n\t\tpublic static final String LOADING_HALLS = \"interfaces/loading_halls.png\";\n\n\t\tpublic static final String BUFFS_SMALL = \"interfaces/buffs.png\";\n\t\tpublic static final String BUFFS_LARGE = \"interfaces/large_buffs.png\";\n\n\t\tpublic static final String TALENT_ICONS = \"interfaces/talent_icons.png\";\n\t\tpublic static final String TALENT_BUTTON = \"interfaces/talent_button.png\";\n\n\t\tpublic static final String HERO_ICONS = \"interfaces/hero_icons.png\";\n\n\t\tpublic static final String RADIAL_MENU = \"interfaces/radial_menu.png\";\n\t}\n\n\t//these points to resource bundles, not raw asset files\n\tpublic static class Messages {\n\t\tpublic static final String ACTORS = \"messages/actors/actors\";\n\t\tpublic static final String ITEMS = \"messages/items/items\";\n\t\tpublic static final String JOURNAL = \"messages/journal/journal\";\n\t\tpublic static final String LEVELS = \"messages/levels/levels\";\n\t\tpublic static final String MISC = \"messages/misc/misc\";\n\t\tpublic static final String PLANTS = \"messages/plants/plants\";\n\t\tpublic static final String SCENES = \"messages/scenes/scenes\";\n\t\tpublic static final String UI = \"messages/ui/ui\";\n\t\tpublic static final String WINDOWS = \"messages/windows/windows\";\n\t}\n\n\tpublic static class Music {\n\t\tpublic static final String THEME_1 = \"music/theme_1.ogg\";\n\t\tpublic static final String THEME_2 = \"music/theme_2.ogg\";\n\t\tpublic static final String THEME_FINALE = \"music/theme_finale.ogg\";\n\n\t\tpublic static final String SEWERS_1 = \"music/sewers_1.ogg\";\n\t\tpublic static final String SEWERS_2 = \"music/sewers_2.ogg\";\n\t\tpublic static final String SEWERS_3 = \"music/sewers_3.ogg\";\n\t\tpublic static final String SEWERS_TENSE = \"music/sewers_tense.ogg\";\n\t\tpublic static final String SEWERS_BOSS = \"music/sewers_boss.ogg\";\n\n\t\tpublic static final String PRISON_1 = \"music/prison_1.ogg\";\n\t\tpublic static final String PRISON_2 = \"music/prison_2.ogg\";\n\t\tpublic static final String PRISON_3 = \"music/prison_3.ogg\";\n\t\tpublic static final String PRISON_TENSE = \"music/prison_tense.ogg\";\n\t\tpublic static final String PRISON_BOSS = \"music/prison_boss.ogg\";\n\n\t\tpublic static final String CAVES_1 = \"music/caves_1.ogg\";\n\t\tpublic static final String CAVES_2 = \"music/caves_2.ogg\";\n\t\tpublic static final String CAVES_3 = \"music/caves_3.ogg\";\n\t\tpublic static final String CAVES_TENSE = \"music/caves_tense.ogg\";\n\t\tpublic static final String CAVES_BOSS = \"music/caves_boss.ogg\";\n\t\tpublic static final String CAVES_BOSS_FINALE = \"music/caves_boss_finale.ogg\";\n\n\t\tpublic static final String CITY_1 = \"music/city_1.ogg\";\n\t\tpublic static final String CITY_2 = \"music/city_2.ogg\";\n\t\tpublic static final String CITY_3 = \"music/city_3.ogg\";\n\t\tpublic static final String CITY_TENSE = \"music/city_tense.ogg\";\n\t\tpublic static final String CITY_BOSS = \"music/city_boss.ogg\";\n\t\tpublic static final String CITY_BOSS_FINALE = \"music/city_boss_finale.ogg\";\n\n\t\tpublic static final String HALLS_1 = \"music/halls_1.ogg\";\n\t\tpublic static final String HALLS_2 = \"music/halls_2.ogg\";\n\t\tpublic static final String HALLS_3 = \"music/halls_3.ogg\";\n\t\tpublic static final String HALLS_TENSE = \"music/halls_tense.ogg\";\n\t\tpublic static final String HALLS_BOSS = \"music/halls_boss.ogg\";\n\t\tpublic static final String HALLS_BOSS_FINALE = \"music/halls_boss_finale.ogg\";\n\t}\n\n\tpublic static class Sounds {\n\t\tpublic static final String CLICK = \"sounds/click.mp3\";\n\t\tpublic static final String BADGE = \"sounds/badge.mp3\";\n\t\tpublic static final String GOLD = \"sounds/gold.mp3\";\n\n\t\tpublic static final String OPEN = \"sounds/door_open.mp3\";\n\t\tpublic static final String UNLOCK = \"sounds/unlock.mp3\";\n\t\tpublic static final String ITEM = \"sounds/item.mp3\";\n\t\tpublic static final String DEWDROP = \"sounds/dewdrop.mp3\";\n\t\tpublic static final String STEP = \"sounds/step.mp3\";\n\t\tpublic static final String WATER = \"sounds/water.mp3\";\n\t\tpublic static final String GRASS = \"sounds/grass.mp3\";\n\t\tpublic static final String TRAMPLE = \"sounds/trample.mp3\";\n\t\tpublic static final String STURDY = \"sounds/sturdy.mp3\";\n\n\t\tpublic static final String HIT = \"sounds/hit.mp3\";\n\t\tpublic static final String MISS = \"sounds/miss.mp3\";\n\t\tpublic static final String HIT_SLASH = \"sounds/hit_slash.mp3\";\n\t\tpublic static final String HIT_STAB = \"sounds/hit_stab.mp3\";\n\t\tpublic static final String HIT_CRUSH = \"sounds/hit_crush.mp3\";\n\t\tpublic static final String HIT_MAGIC = \"sounds/hit_magic.mp3\";\n\t\tpublic static final String HIT_STRONG = \"sounds/hit_strong.mp3\";\n\t\tpublic static final String HIT_PARRY = \"sounds/hit_parry.mp3\";\n\t\tpublic static final String HIT_ARROW = \"sounds/hit_arrow.mp3\";\n\t\tpublic static final String ATK_SPIRITBOW = \"sounds/atk_spiritbow.mp3\";\n\t\tpublic static final String ATK_CROSSBOW = \"sounds/atk_crossbow.mp3\";\n\t\tpublic static final String HEALTH_WARN = \"sounds/health_warn.mp3\";\n\t\tpublic static final String HEALTH_CRITICAL = \"sounds/health_critical.mp3\";\n\n\t\tpublic static final String DESCEND = \"sounds/descend.mp3\";\n\t\tpublic static final String EAT = \"sounds/eat.mp3\";\n\t\tpublic static final String READ = \"sounds/read.mp3\";\n\t\tpublic static final String LULLABY = \"sounds/lullaby.mp3\";\n\t\tpublic static final String DRINK = \"sounds/drink.mp3\";\n\t\tpublic static final String SHATTER = \"sounds/shatter.mp3\";\n\t\tpublic static final String ZAP = \"sounds/zap.mp3\";\n\t\tpublic static final String LIGHTNING= \"sounds/lightning.mp3\";\n\t\tpublic static final String LEVELUP = \"sounds/levelup.mp3\";\n\t\tpublic static final String DEATH = \"sounds/death.mp3\";\n\t\tpublic static final String CHALLENGE= \"sounds/challenge.mp3\";\n\t\tpublic static final String CURSED = \"sounds/cursed.mp3\";\n\t\tpublic static final String TRAP = \"sounds/trap.mp3\";\n\t\tpublic static final String EVOKE = \"sounds/evoke.mp3\";\n\t\tpublic static final String TOMB = \"sounds/tomb.mp3\";\n\t\tpublic static final String ALERT = \"sounds/alert.mp3\";\n\t\tpublic static final String MELD = \"sounds/meld.mp3\";\n\t\tpublic static final String BOSS = \"sounds/boss.mp3\";\n\t\tpublic static final String BLAST = \"sounds/blast.mp3\";\n\t\tpublic static final String PLANT = \"sounds/plant.mp3\";\n\t\tpublic static final String RAY = \"sounds/ray.mp3\";\n\t\tpublic static final String BEACON = \"sounds/beacon.mp3\";\n\t\tpublic static final String TELEPORT = \"sounds/teleport.mp3\";\n\t\tpublic static final String CHARMS = \"sounds/charms.mp3\";\n\t\tpublic static final String MASTERY = \"sounds/mastery.mp3\";\n\t\tpublic static final String PUFF = \"sounds/puff.mp3\";\n\t\tpublic static final String ROCKS = \"sounds/rocks.mp3\";\n\t\tpublic static final String BURNING = \"sounds/burning.mp3\";\n\t\tpublic static final String FALLING = \"sounds/falling.mp3\";\n\t\tpublic static final String GHOST = \"sounds/ghost.mp3\";\n\t\tpublic static final String SECRET = \"sounds/secret.mp3\";\n\t\tpublic static final String BONES = \"sounds/bones.mp3\";\n\t\tpublic static final String BEE = \"sounds/bee.mp3\";\n\t\tpublic static final String DEGRADE = \"sounds/degrade.mp3\";\n\t\tpublic static final String MIMIC = \"sounds/mimic.mp3\";\n\t\tpublic static final String DEBUFF = \"sounds/debuff.mp3\";\n\t\tpublic static final String CHARGEUP = \"sounds/chargeup.mp3\";\n\t\tpublic static final String GAS = \"sounds/gas.mp3\";\n\t\tpublic static final String CHAINS = \"sounds/chains.mp3\";\n\t\tpublic static final String SCAN = \"sounds/scan.mp3\";\n\t\tpublic static final String SHEEP = \"sounds/sheep.mp3\";\n\t\tpublic static final String MINE = \"sounds/mine.mp3\";\n\n\t\tpublic static final String[] all = new String[]{\n\t\t\t\tCLICK, BADGE, GOLD,\n\n\t\t\t\tOPEN, UNLOCK, ITEM, DEWDROP, STEP, WATER, GRASS, TRAMPLE, STURDY,\n\n\t\t\t\tHIT, MISS, HIT_SLASH, HIT_STAB, HIT_CRUSH, HIT_MAGIC, HIT_STRONG, HIT_PARRY,\n\t\t\t\tHIT_ARROW, ATK_SPIRITBOW, ATK_CROSSBOW, HEALTH_WARN, HEALTH_CRITICAL,\n\n\t\t\t\tDESCEND, EAT, READ, LULLABY, DRINK, SHATTER, ZAP, LIGHTNING, LEVELUP, DEATH,\n\t\t\t\tCHALLENGE, CURSED, TRAP, EVOKE, TOMB, ALERT, MELD, BOSS, BLAST, PLANT, RAY, BEACON,\n\t\t\t\tTELEPORT, CHARMS, MASTERY, PUFF, ROCKS, BURNING, FALLING, GHOST, SECRET, BONES,\n\t\t\t\tBEE, DEGRADE, MIMIC, DEBUFF, CHARGEUP, GAS, CHAINS, SCAN, SHEEP, MINE\n\t\t};\n\t}\n\n\tpublic static class Splashes {\n\t\tpublic static final String WARRIOR = \"splashes/warrior.jpg\";\n\t\tpublic static final String MAGE = \"splashes/mage.jpg\";\n\t\tpublic static final String ROGUE = \"splashes/rogue.jpg\";\n\t\tpublic static final String HUNTRESS = \"splashes/huntress.jpg\";\n\t\tpublic static final String DUELIST = \"splashes/duelist.jpg\";\n\t\tpublic static final String GUNNER\t= \"splashes/gunner.jpg\";\n\t\tpublic static final String SAMURAI = \"splashes/samurai.jpg\";\n\t\tpublic static final String PLANTER\t= \"splashes/planter.jpg\";\n\t\tpublic static final String KNIGHT\t= \"splashes/knight.jpg\";\n\t\tpublic static final String NURSE\t= \"splashes/nurse.jpg\";\n\t}\n\n\tpublic static class Sprites {\n\t\tpublic static final String ITEMS = \"sprites/items.png\";\n\t\tpublic static final String ITEM_ICONS = \"sprites/item_icons.png\";\n\n\t\tpublic static final String WARRIOR = \"sprites/warrior.png\";\n\t\tpublic static final String MAGE = \"sprites/mage.png\";\n\t\tpublic static final String ROGUE = \"sprites/rogue.png\";\n\t\tpublic static final String HUNTRESS = \"sprites/huntress.png\";\n\t\tpublic static final String DUELIST = \"sprites/duelist.png\";\n\t\tpublic static final String GUNNER\t= \"sprites/gunner.png\";\n\t\tpublic static final String SAMURAI\t= \"sprites/samurai.png\";\n\t\tpublic static final String PLANTER\t= \"sprites/planter.png\";\n\t\tpublic static final String KNIGHT\t= \"sprites/knight.png\";\n\t\tpublic static final String NURSE\t= \"sprites/nurse.png\";\n\t\tpublic static final String AVATARS = \"sprites/avatars.png\";\n\t\tpublic static final String PET = \"sprites/pet.png\";\n\t\tpublic static final String AMULET = \"sprites/amulet.png\";\n\n\t\tpublic static final String RAT = \"sprites/rat.png\";\n\t\tpublic static final String BRUTE = \"sprites/brute.png\";\n\t\tpublic static final String SPINNER = \"sprites/spinner.png\";\n\t\tpublic static final String DM300 = \"sprites/dm300.png\";\n\t\tpublic static final String WRAITH = \"sprites/wraith.png\";\n\t\tpublic static final String UNDEAD = \"sprites/undead.png\";\n\t\tpublic static final String KING = \"sprites/king.png\";\n\t\tpublic static final String PIRANHA = \"sprites/piranha.png\";\n\t\tpublic static final String EYE = \"sprites/eye.png\";\n\t\tpublic static final String GNOLL = \"sprites/gnoll.png\";\n\t\tpublic static final String CRAB = \"sprites/crab.png\";\n\t\tpublic static final String GOO = \"sprites/goo.png\";\n\t\tpublic static final String SWARM = \"sprites/swarm.png\";\n\t\tpublic static final String SKELETON = \"sprites/skeleton.png\";\n\t\tpublic static final String SHAMAN = \"sprites/shaman.png\";\n\t\tpublic static final String THIEF = \"sprites/thief.png\";\n\t\tpublic static final String TENGU = \"sprites/tengu.png\";\n\t\tpublic static final String SHEEP = \"sprites/sheep.png\";\n\t\tpublic static final String KEEPER = \"sprites/shopkeeper.png\";\n\t\tpublic static final String BAT = \"sprites/bat.png\";\n\t\tpublic static final String ELEMENTAL= \"sprites/elemental.png\";\n\t\tpublic static final String MONK = \"sprites/monk.png\";\n\t\tpublic static final String WARLOCK = \"sprites/warlock.png\";\n\t\tpublic static final String GOLEM = \"sprites/golem.png\";\n\t\tpublic static final String STATUE = \"sprites/statue.png\";\n\t\tpublic static final String SUCCUBUS = \"sprites/succubus.png\";\n\t\tpublic static final String SCORPIO = \"sprites/scorpio.png\";\n\t\tpublic static final String FISTS = \"sprites/yog_fists.png\";\n\t\tpublic static final String YOG = \"sprites/yog.png\";\n\t\tpublic static final String LARVA = \"sprites/larva.png\";\n\t\tpublic static final String GHOST = \"sprites/ghost.png\";\n\t\tpublic static final String MAKER = \"sprites/wandmaker.png\";\n\t\tpublic static final String TROLL = \"sprites/blacksmith.png\";\n\t\tpublic static final String IMP = \"sprites/demon.png\";\n\t\tpublic static final String RATKING = \"sprites/ratking.png\";\n\t\tpublic static final String BEE = \"sprites/bee.png\";\n\t\tpublic static final String MIMIC = \"sprites/mimic.png\";\n\t\tpublic static final String ROT_LASH = \"sprites/rot_lasher.png\";\n\t\tpublic static final String ROT_HEART= \"sprites/rot_heart.png\";\n\t\tpublic static final String GUARD = \"sprites/guard.png\";\n\t\tpublic static final String WARDS = \"sprites/wards.png\";\n\t\tpublic static final String GUARDIAN = \"sprites/guardian.png\";\n\t\tpublic static final String SLIME = \"sprites/slime.png\";\n\t\tpublic static final String SNAKE = \"sprites/snake.png\";\n\t\tpublic static final String NECRO = \"sprites/necromancer.png\";\n\t\tpublic static final String GHOUL = \"sprites/ghoul.png\";\n\t\tpublic static final String RIPPER = \"sprites/ripper.png\";\n\t\tpublic static final String SPAWNER = \"sprites/spawner.png\";\n\t\tpublic static final String DM100 = \"sprites/dm100.png\";\n\t\tpublic static final String PYLON = \"sprites/pylon.png\";\n\t\tpublic static final String DM200 = \"sprites/dm200.png\";\n\t\tpublic static final String LOTUS = \"sprites/lotus.png\";\n\t\tpublic static final String NINJA_LOG= \"sprites/ninja_log.png\";\n\t\tpublic static final String SPIRIT_HAWK= \"sprites/spirit_hawk.png\";\n\t\tpublic static final String RED_SENTRY= \"sprites/red_sentry.png\";\n\t\tpublic static final String NEW_SENTRY= \"sprites/new_sentry.png\";\n\t\tpublic static final String CRYSTAL_WISP= \"sprites/crystal_wisp.png\";\n\t\tpublic static final String CRYSTAL_GUARDIAN= \"sprites/crystal_guardian.png\";\n\t\tpublic static final String CRYSTAL_SPIRE= \"sprites/crystal_spire.png\";\n\t\tpublic static final String GNOLL_GUARD= \"sprites/gnoll_guard.png\";\n\n\t\tpublic static final String SOLDIER= \"sprites/soldier.png\";\n\t\tpublic static final String RESEARCHER= \"sprites/researcher.png\";\n\t\tpublic static final String TANK= \"sprites/tank.png\";\n\t\tpublic static final String SUPRESSION= \"sprites/supression.png\";\n\t\tpublic static final String MEDIC= \"sprites/medic.png\";\n\t\tpublic static final String REBEL= \"sprites/rebel.png\";\n\t}\n}" }, { "identifier": "Dungeon", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/Dungeon.java", "snippet": "public class Dungeon {\n\n\t//enum of items which have limited spawns, records how many have spawned\n\t//could all be their own separate numbers, but this allows iterating, much nicer for bundling/initializing.\n\tpublic static enum LimitedDrops {\n\t\t//limited world drops\n\t\tSTRENGTH_POTIONS,\n\t\tUPGRADE_SCROLLS,\n\t\tARCANE_STYLI,\n\n\t\t//Health potion sources\n\t\t//enemies\n\t\tSWARM_HP,\n\t\tNECRO_HP,\n\t\tBAT_HP,\n\t\tWARLOCK_HP,\n\t\t//Demon spawners are already limited in their spawnrate, no need to limit their health drops\n\t\t//alchemy\n\t\tCOOKING_HP,\n\t\tBLANDFRUIT_SEED,\n\n\t\t//Other limited enemy drops\n\t\tSLIME_WEP,\n\t\tSKELE_WEP,\n\t\tTHEIF_MISC,\n\t\tGUARD_ARM,\n\t\tSHAMAN_WAND,\n\t\tDM200_EQUIP,\n\t\tGOLEM_EQUIP,\n\t\tSOLDIER_WEP,\n\t\tMEDIC_HP,\n\n\t\t//containers\n\t\tVELVET_POUCH,\n\t\tSCROLL_HOLDER,\n\t\tPOTION_BANDOLIER,\n\t\tMAGICAL_HOLSTER,\n\n\t\t//lore documents\n\t\tLORE_SEWERS,\n\t\tLORE_PRISON,\n\t\tLORE_CAVES,\n\t\tLORE_CITY,\n\t\tLORE_HALLS,\n\t\tLORE_LABS;\n\n\t\tpublic int count = 0;\n\n\t\t//for items which can only be dropped once, should directly access count otherwise.\n\t\tpublic boolean dropped(){\n\t\t\treturn count != 0;\n\t\t}\n\t\tpublic void drop(){\n\t\t\tcount = 1;\n\t\t}\n\n\t\tpublic static void reset(){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tlim.count = 0;\n\t\t\t}\n\t\t}\n\n\t\tpublic static void store( Bundle bundle ){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tbundle.put(lim.name(), lim.count);\n\t\t\t}\n\t\t}\n\n\t\tpublic static void restore( Bundle bundle ){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tif (bundle.contains(lim.name())){\n\t\t\t\t\tlim.count = bundle.getInt(lim.name());\n\t\t\t\t} else {\n\t\t\t\t\tlim.count = 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\n\t\t\t//pre-v2.2.0 saves\n\t\t\tif (Dungeon.version < 750\n\t\t\t\t\t&& Dungeon.isChallenged(Challenges.NO_SCROLLS)\n\t\t\t\t\t&& UPGRADE_SCROLLS.count > 0){\n\t\t\t\t//we now count SOU fully, and just don't drop every 2nd one\n\t\t\t\tUPGRADE_SCROLLS.count += UPGRADE_SCROLLS.count-1;\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic static int challenges;\n\tpublic static int mobsToChampion;\n\n\tpublic static Hero hero;\n\tpublic static Level level;\n\n\tpublic static QuickSlot quickslot = new QuickSlot();\n\t\n\tpublic static int depth;\n\t//determines path the hero is on. Current uses:\n\t// 0 is the default path\n\t// 1 is for quest sub-floors\n\tpublic static int branch;\n\n\t//keeps track of what levels the game should try to load instead of creating fresh\n\tpublic static ArrayList<Integer> generatedLevels = new ArrayList<>();\n\n\tpublic static int gold;\n\tpublic static int energy;\n\tpublic static int bullet;\n\n\tpublic static HashSet<Integer> chapters;\n\n\tpublic static SparseArray<ArrayList<Item>> droppedItems;\n\n\t//first variable is only assigned when game is started, second is updated every time game is saved\n\tpublic static int initialVersion;\n\tpublic static int version;\n\n\tpublic static boolean daily;\n\tpublic static boolean dailyReplay;\n\tpublic static String customSeedText = \"\";\n\tpublic static long seed;\n\t\n\tpublic static void init() {\n\n\t\tinitialVersion = version = Game.versionCode;\n\t\tchallenges = SPDSettings.challenges();\n\t\tmobsToChampion = -1;\n\n\t\tif (daily) {\n\t\t\t//Ensures that daily seeds are not in the range of user-enterable seeds\n\t\t\tseed = SPDSettings.lastDaily() + DungeonSeed.TOTAL_SEEDS;\n\t\t\tDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ROOT);\n\t\t\tformat.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\t\t\tcustomSeedText = format.format(new Date(SPDSettings.lastDaily()));\n\t\t} else if (!SPDSettings.customSeed().isEmpty()){\n\t\t\tcustomSeedText = SPDSettings.customSeed();\n\t\t\tseed = DungeonSeed.convertFromText(customSeedText);\n\t\t} else {\n\t\t\tcustomSeedText = \"\";\n\t\t\tseed = DungeonSeed.randomSeed();\n\t\t}\n\n\t\tActor.clear();\n\t\tActor.resetNextID();\n\n\t\t//offset seed slightly to avoid output patterns\n\t\tRandom.pushGenerator( seed+1 );\n\n\t\t\tScroll.initLabels();\n\t\t\tPotion.initColors();\n\t\t\tRing.initGems();\n\n\t\t\tSpecialRoom.initForRun();\n\t\t\tSecretRoom.initForRun();\n\n\t\t\tGenerator.fullReset();\n\n\t\tRandom.resetGenerators();\n\t\t\n\t\tStatistics.reset();\n\t\tNotes.reset();\n\n\t\tquickslot.reset();\n\t\tQuickSlotButton.reset();\n\t\tToolbar.swappedQuickslots = false;\n\t\t\n\t\tdepth = 1;\n\t\tbranch = 0;\n\t\tgeneratedLevels.clear();\n\n\t\tgold = 0;\n\t\tenergy = 0;\n\t\tbullet = 0;\n\n\t\tdroppedItems = new SparseArray<>();\n\n\t\tLimitedDrops.reset();\n\t\t\n\t\tchapters = new HashSet<>();\n\t\t\n\t\tGhost.Quest.reset();\n\t\tWandmaker.Quest.reset();\n\t\tBlacksmith.Quest.reset();\n\t\tImp.Quest.reset();\n\n\t\thero = new Hero();\n\t\thero.live();\n\t\t\n\t\tBadges.reset();\n\t\t\n\t\tGamesInProgress.selectedClass.initHero( hero );\n\t}\n\n\tpublic static boolean isChallenged( int mask ) {\n\t\treturn (challenges & mask) != 0;\n\t}\n\n\tpublic static boolean levelHasBeenGenerated(int depth, int branch){\n\t\treturn generatedLevels.contains(depth + 1000*branch);\n\t}\n\t\n\tpublic static Level newLevel() {\n\t\t\n\t\tDungeon.level = null;\n\t\tActor.clear();\n\t\t\n\t\tLevel level;\n\t\tif (branch == 0) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 1:\n\t\t\t\tcase 2:\n\t\t\t\tcase 3:\n\t\t\t\tcase 4:\n\t\t\t\t\tlevel = new SewerLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\tlevel = new SewerBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 6:\n\t\t\t\tcase 7:\n\t\t\t\tcase 8:\n\t\t\t\tcase 9:\n\t\t\t\t\tlevel = new PrisonLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 10:\n\t\t\t\t\tlevel = new PrisonBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 11:\n\t\t\t\tcase 12:\n\t\t\t\tcase 13:\n\t\t\t\tcase 14:\n\t\t\t\t\tlevel = new CavesLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 15:\n\t\t\t\t\tlevel = new CavesBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 16:\n\t\t\t\tcase 17:\n\t\t\t\tcase 18:\n\t\t\t\tcase 19:\n\t\t\t\t\tlevel = new CityLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tlevel = new CityBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 21:\n\t\t\t\tcase 22:\n\t\t\t\tcase 23:\n\t\t\t\tcase 24:\n\t\t\t\t\tlevel = new HallsLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 25:\n\t\t\t\t\tlevel = new HallsBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 26:\n\t\t\t\tcase 27:\n\t\t\t\tcase 28:\n\t\t\t\tcase 29:\n\t\t\t\t\tlevel = new LabsLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 30:\n\t\t\t\t\tlevel = new LabsBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 31:\n\t\t\t\t\tlevel = new NewLastLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else if (branch == 1) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 11:\n\t\t\t\tcase 12:\n\t\t\t\tcase 13:\n\t\t\t\tcase 14:\n\t\t\t\t\tlevel = new MiningLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else if (branch == 2) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 16:\n\t\t\t\tcase 17:\n\t\t\t\tcase 18:\n\t\t\t\tcase 19:\n\t\t\t\t\tlevel = new TempleLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tlevel = new TempleLastLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else {\n\t\t\tlevel = new DeadEndLevel();\n\t\t}\n\n\t\t//dead end levels get cleared, don't count as generated\n\t\tif (!(level instanceof DeadEndLevel)){\n\t\t\t//this assumes that we will never have a depth value outside the range 0 to 999\n\t\t\t// or -500 to 499, etc.\n\t\t\tif (!generatedLevels.contains(depth + 1000*branch)) {\n\t\t\t\tgeneratedLevels.add(depth + 1000 * branch);\n\t\t\t}\n\n\t\t\tif (depth > Statistics.deepestFloor && branch == 0) {\n\t\t\t\tStatistics.deepestFloor = depth;\n\n\t\t\t\tif (Statistics.qualifiedForNoKilling) {\n\t\t\t\t\tStatistics.completedWithNoKilling = true;\n\t\t\t\t} else {\n\t\t\t\t\tStatistics.completedWithNoKilling = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tlevel.create();\n\t\t\n\t\tif (branch == 0) Statistics.qualifiedForNoKilling = !bossLevel();\n\t\tStatistics.qualifiedForBossChallengeBadge = false;\n\t\t\n\t\treturn level;\n\t}\n\t\n\tpublic static void resetLevel() {\n\t\t\n\t\tActor.clear();\n\t\t\n\t\tlevel.reset();\n\t\tswitchLevel( level, level.entrance() );\n\t}\n\n\tpublic static long seedCurDepth(){\n\t\treturn seedForDepth(depth, branch);\n\t}\n\n\tpublic static long seedForDepth(int depth, int branch){\n\t\tint lookAhead = depth;\n\t\tlookAhead += 30*branch; //Assumes depth is always 1-30, and branch is always 0 or higher\n\n\t\tRandom.pushGenerator( seed );\n\n\t\t\tfor (int i = 0; i < lookAhead; i ++) {\n\t\t\t\tRandom.Long(); //we don't care about these values, just need to go through them\n\t\t\t}\n\t\t\tlong result = Random.Long();\n\n\t\tRandom.popGenerator();\n\t\treturn result;\n\t}\n\t\n\tpublic static boolean shopOnLevel() {\n\t\treturn (depth == 6 || depth == 11 || depth == 16 || depth == 26) && branch == 0;\n\t}\n\t\n\tpublic static boolean bossLevel() {\n\t\treturn bossLevel( depth );\n\t}\n\t\n\tpublic static boolean bossLevel( int depth ) {\n\t\treturn depth == 5 || depth == 10 || depth == 15 || depth == 20 || depth == 25|| depth == 30;\n\t}\n\n\t//value used for scaling of damage values and other effects.\n\t//is usually the dungeon depth, but can be set to 26 when ascending\n\tpublic static int scalingDepth(){\n\t\tif (Dungeon.hero != null && Dungeon.hero.buff(AscensionChallenge.class) != null){\n\t\t\treturn 31;\n\t\t} else {\n\t\t\treturn depth;\n\t\t}\n\t}\n\n\tpublic static boolean interfloorTeleportAllowed(){\n\t\tif (Dungeon.level.locked\n\t\t\t\t|| (Dungeon.hero != null && Dungeon.hero.belongings.getItem(Amulet.class) != null)\n\t\t\t\t|| (Dungeon.hero != null && Dungeon.hero.buff(OldAmulet.TempleCurse.class) != null)){\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\n\tpublic static void switchLevel( final Level level, int pos ) {\n\n\t\t//Position of -2 specifically means trying to place the hero the exit\n\t\tif (pos == -2){\n\t\t\tLevelTransition t = level.getTransition(LevelTransition.Type.REGULAR_EXIT);\n\t\t\tif (t != null) pos = t.cell();\n\t\t}\n\n\t\t//Place hero at the entrance if they are out of the map (often used for pox = -1)\n\t\t// or if they are in solid terrain (except in the mining level, where that happens normally)\n\t\tif (pos < 0 || pos >= level.length()\n\t\t\t\t|| (!(level instanceof MiningLevel) && !level.passable[pos] && !level.avoid[pos])){\n\t\t\tpos = level.getTransition(null).cell();\n\t\t}\n\t\t\n\t\tPathFinder.setMapSize(level.width(), level.height());\n\t\t\n\t\tDungeon.level = level;\n\t\thero.pos = pos;\n\n\t\tif (hero.buff(AscensionChallenge.class) != null){\n\t\t\thero.buff(AscensionChallenge.class).onLevelSwitch();\n\t\t}\n\n\t\tif (hero.buff(OldAmulet.TempleCurse.class) != null){\n\t\t\thero.buff(OldAmulet.TempleCurse.class).onLevelSwitch();\n\t\t}\n\n\t\tMob.restoreAllies( level, pos );\n\n\t\tActor.init();\n\n\t\tlevel.addRespawner();\n\t\t\n\t\tfor(Mob m : level.mobs){\n\t\t\tif (m.pos == hero.pos && !Char.hasProp(m, Char.Property.IMMOVABLE)){\n\t\t\t\t//displace mob\n\t\t\t\tfor(int i : PathFinder.NEIGHBOURS8){\n\t\t\t\t\tif (Actor.findChar(m.pos+i) == null && level.passable[m.pos + i]){\n\t\t\t\t\t\tm.pos += i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tLight light = hero.buff( Light.class );\n\t\thero.viewDistance = light == null ? level.viewDistance : Math.max( Light.DISTANCE, level.viewDistance );\n\t\t\n\t\thero.curAction = hero.lastAction = null;\n\n\t\tobserve();\n\t\ttry {\n\t\t\tsaveAll();\n\t\t} catch (IOException e) {\n\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t\t/*This only catches IO errors. Yes, this means things can go wrong, and they can go wrong catastrophically.\n\t\t\tBut when they do the user will get a nice 'report this issue' dialogue, and I can fix the bug.*/\n\t\t}\n\t}\n\n\tpublic static void dropToChasm( Item item ) {\n\t\tint depth = Dungeon.depth + 1;\n\t\tArrayList<Item> dropped = Dungeon.droppedItems.get( depth );\n\t\tif (dropped == null) {\n\t\t\tDungeon.droppedItems.put( depth, dropped = new ArrayList<>() );\n\t\t}\n\t\tdropped.add( item );\n\t}\n\n\tpublic static boolean posNeeded() {\n\t\t//2 POS each floor set\n\t\tint posLeftThisSet = 2 - (LimitedDrops.STRENGTH_POTIONS.count - (depth / 5) * 2);\n\t\tif (posLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\n\t\t//pos drops every two floors, (numbers 1-2, and 3-4) with a 50% chance for the earlier one each time.\n\t\tint targetPOSLeft = 2 - floorThisSet/2;\n\t\tif (floorThisSet % 2 == 1 && Random.Int(2) == 0) targetPOSLeft --;\n\n\t\tif (targetPOSLeft < posLeftThisSet) return true;\n\t\telse return false;\n\n\t}\n\t\n\tpublic static boolean souNeeded() {\n\t\tint souLeftThisSet;\n\t\t//3 SOU each floor set\n\t\tsouLeftThisSet = 3 - (LimitedDrops.UPGRADE_SCROLLS.count - (depth / 5) * 3);\n\t\tif (souLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\t\t//chance is floors left / scrolls left\n\t\treturn Random.Int(5 - floorThisSet) < souLeftThisSet;\n\t}\n\t\n\tpublic static boolean asNeeded() {\n\t\t//1 AS each floor set\n\t\tint asLeftThisSet = 1 - (LimitedDrops.ARCANE_STYLI.count - (depth / 5));\n\t\tif (asLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\t\t//chance is floors left / scrolls left\n\t\treturn Random.Int(5 - floorThisSet) < asLeftThisSet;\n\t}\n\n\tprivate static final String INIT_VER\t= \"init_ver\";\n\tprivate static final String VERSION\t\t= \"version\";\n\tprivate static final String SEED\t\t= \"seed\";\n\tprivate static final String CUSTOM_SEED\t= \"custom_seed\";\n\tprivate static final String DAILY\t = \"daily\";\n\tprivate static final String DAILY_REPLAY= \"daily_replay\";\n\tprivate static final String CHALLENGES\t= \"challenges\";\n\tprivate static final String MOBS_TO_CHAMPION\t= \"mobs_to_champion\";\n\tprivate static final String HERO\t\t= \"hero\";\n\tprivate static final String DEPTH\t\t= \"depth\";\n\tprivate static final String BRANCH\t\t= \"branch\";\n\tprivate static final String GENERATED_LEVELS = \"generated_levels\";\n\tprivate static final String GOLD\t\t= \"gold\";\n\tprivate static final String ENERGY\t\t= \"energy\";\n\tprivate static final String BULLET\t\t= \"bullet\";\n\tprivate static final String DROPPED = \"dropped%d\";\n\tprivate static final String PORTED = \"ported%d\";\n\tprivate static final String LEVEL\t\t= \"level\";\n\tprivate static final String LIMDROPS = \"limited_drops\";\n\tprivate static final String CHAPTERS\t= \"chapters\";\n\tprivate static final String QUESTS\t\t= \"quests\";\n\tprivate static final String BADGES\t\t= \"badges\";\n\n\tpublic static void saveGame( int save ) {\n\t\ttry {\n\t\t\tBundle bundle = new Bundle();\n\n\t\t\tbundle.put( INIT_VER, initialVersion );\n\t\t\tbundle.put( VERSION, version = Game.versionCode );\n\t\t\tbundle.put( SEED, seed );\n\t\t\tbundle.put( CUSTOM_SEED, customSeedText );\n\t\t\tbundle.put( DAILY, daily );\n\t\t\tbundle.put( DAILY_REPLAY, dailyReplay );\n\t\t\tbundle.put( CHALLENGES, challenges );\n\t\t\tbundle.put( MOBS_TO_CHAMPION, mobsToChampion );\n\t\t\tbundle.put( HERO, hero );\n\t\t\tbundle.put( DEPTH, depth );\n\t\t\tbundle.put( BRANCH, branch );\n\n\t\t\tbundle.put( GOLD, gold );\n\t\t\tbundle.put( ENERGY, energy );\n\t\t\tbundle.put( BULLET, bullet );\n\n\t\t\tfor (int d : droppedItems.keyArray()) {\n\t\t\t\tbundle.put(Messages.format(DROPPED, d), droppedItems.get(d));\n\t\t\t}\n\n\t\t\tquickslot.storePlaceholders( bundle );\n\n\t\t\tBundle limDrops = new Bundle();\n\t\t\tLimitedDrops.store( limDrops );\n\t\t\tbundle.put ( LIMDROPS, limDrops );\n\t\t\t\n\t\t\tint count = 0;\n\t\t\tint ids[] = new int[chapters.size()];\n\t\t\tfor (Integer id : chapters) {\n\t\t\t\tids[count++] = id;\n\t\t\t}\n\t\t\tbundle.put( CHAPTERS, ids );\n\t\t\t\n\t\t\tBundle quests = new Bundle();\n\t\t\tGhost\t\t.Quest.storeInBundle( quests );\n\t\t\tWandmaker\t.Quest.storeInBundle( quests );\n\t\t\tBlacksmith\t.Quest.storeInBundle( quests );\n\t\t\tImp\t\t\t.Quest.storeInBundle( quests );\n\t\t\tbundle.put( QUESTS, quests );\n\t\t\t\n\t\t\tSpecialRoom.storeRoomsInBundle( bundle );\n\t\t\tSecretRoom.storeRoomsInBundle( bundle );\n\t\t\t\n\t\t\tStatistics.storeInBundle( bundle );\n\t\t\tNotes.storeInBundle( bundle );\n\t\t\tGenerator.storeInBundle( bundle );\n\n\t\t\tint[] bundleArr = new int[generatedLevels.size()];\n\t\t\tfor (int i = 0; i < generatedLevels.size(); i++){\n\t\t\t\tbundleArr[i] = generatedLevels.get(i);\n\t\t\t}\n\t\t\tbundle.put( GENERATED_LEVELS, bundleArr);\n\t\t\t\n\t\t\tScroll.save( bundle );\n\t\t\tPotion.save( bundle );\n\t\t\tRing.save( bundle );\n\n\t\t\tActor.storeNextID( bundle );\n\t\t\t\n\t\t\tBundle badges = new Bundle();\n\t\t\tBadges.saveLocal( badges );\n\t\t\tbundle.put( BADGES, badges );\n\t\t\t\n\t\t\tFileUtils.bundleToFile( GamesInProgress.gameFile(save), bundle);\n\t\t\t\n\t\t} catch (IOException e) {\n\t\t\tGamesInProgress.setUnknown( save );\n\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t}\n\t}\n\t\n\tpublic static void saveLevel( int save ) throws IOException {\n\t\tBundle bundle = new Bundle();\n\t\tbundle.put( LEVEL, level );\n\t\t\n\t\tFileUtils.bundleToFile(GamesInProgress.depthFile( save, depth, branch ), bundle);\n\t}\n\t\n\tpublic static void saveAll() throws IOException {\n\t\tif (hero != null && (hero.isAlive() || WndResurrect.instance != null)) {\n\t\t\t\n\t\t\tActor.fixTime();\n\t\t\tupdateLevelExplored();\n\t\t\tsaveGame( GamesInProgress.curSlot );\n\t\t\tsaveLevel( GamesInProgress.curSlot );\n\n\t\t\tGamesInProgress.set( GamesInProgress.curSlot );\n\n\t\t}\n\t}\n\t\n\tpublic static void loadGame( int save ) throws IOException {\n\t\tloadGame( save, true );\n\t}\n\t\n\tpublic static void loadGame( int save, boolean fullLoad ) throws IOException {\n\t\t\n\t\tBundle bundle = FileUtils.bundleFromFile( GamesInProgress.gameFile( save ) );\n\n\t\t//pre-1.3.0 saves\n\t\tif (bundle.contains(INIT_VER)){\n\t\t\tinitialVersion = bundle.getInt( INIT_VER );\n\t\t} else {\n\t\t\tinitialVersion = bundle.getInt( VERSION );\n\t\t}\n\n\t\tversion = bundle.getInt( VERSION );\n\n\t\tseed = bundle.contains( SEED ) ? bundle.getLong( SEED ) : DungeonSeed.randomSeed();\n\t\tcustomSeedText = bundle.getString( CUSTOM_SEED );\n\t\tdaily = bundle.getBoolean( DAILY );\n\t\tdailyReplay = bundle.getBoolean( DAILY_REPLAY );\n\n\t\tActor.clear();\n\t\tActor.restoreNextID( bundle );\n\n\t\tquickslot.reset();\n\t\tQuickSlotButton.reset();\n\t\tToolbar.swappedQuickslots = false;\n\n\t\tDungeon.challenges = bundle.getInt( CHALLENGES );\n\t\tDungeon.mobsToChampion = bundle.getInt( MOBS_TO_CHAMPION );\n\t\t\n\t\tDungeon.level = null;\n\t\tDungeon.depth = -1;\n\t\t\n\t\tScroll.restore( bundle );\n\t\tPotion.restore( bundle );\n\t\tRing.restore( bundle );\n\n\t\tquickslot.restorePlaceholders( bundle );\n\t\t\n\t\tif (fullLoad) {\n\t\t\t\n\t\t\tLimitedDrops.restore( bundle.getBundle(LIMDROPS) );\n\n\t\t\tchapters = new HashSet<>();\n\t\t\tint ids[] = bundle.getIntArray( CHAPTERS );\n\t\t\tif (ids != null) {\n\t\t\t\tfor (int id : ids) {\n\t\t\t\t\tchapters.add( id );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tBundle quests = bundle.getBundle( QUESTS );\n\t\t\tif (!quests.isNull()) {\n\t\t\t\tGhost.Quest.restoreFromBundle( quests );\n\t\t\t\tWandmaker.Quest.restoreFromBundle( quests );\n\t\t\t\tBlacksmith.Quest.restoreFromBundle( quests );\n\t\t\t\tImp.Quest.restoreFromBundle( quests );\n\t\t\t} else {\n\t\t\t\tGhost.Quest.reset();\n\t\t\t\tWandmaker.Quest.reset();\n\t\t\t\tBlacksmith.Quest.reset();\n\t\t\t\tImp.Quest.reset();\n\t\t\t}\n\t\t\t\n\t\t\tSpecialRoom.restoreRoomsFromBundle(bundle);\n\t\t\tSecretRoom.restoreRoomsFromBundle(bundle);\n\t\t}\n\t\t\n\t\tBundle badges = bundle.getBundle(BADGES);\n\t\tif (!badges.isNull()) {\n\t\t\tBadges.loadLocal( badges );\n\t\t} else {\n\t\t\tBadges.reset();\n\t\t}\n\t\t\n\t\tNotes.restoreFromBundle( bundle );\n\t\t\n\t\thero = null;\n\t\thero = (Hero)bundle.get( HERO );\n\t\t\n\t\tdepth = bundle.getInt( DEPTH );\n\t\tbranch = bundle.getInt( BRANCH );\n\n\t\tgold = bundle.getInt( GOLD );\n\t\tenergy = bundle.getInt( ENERGY );\n\t\tbullet = bundle.getInt( BULLET );\n\n\t\tStatistics.restoreFromBundle( bundle );\n\t\tGenerator.restoreFromBundle( bundle );\n\n\t\tgeneratedLevels.clear();\n\t\tif (bundle.contains(GENERATED_LEVELS)){\n\t\t\tfor (int i : bundle.getIntArray(GENERATED_LEVELS)){\n\t\t\t\tgeneratedLevels.add(i);\n\t\t\t}\n\t\t//pre-v2.1.1 saves\n\t\t} else {\n\t\t\tfor (int i = 1; i <= Statistics.deepestFloor; i++){\n\t\t\t\tgeneratedLevels.add(i);\n\t\t\t}\n\t\t}\n\n\t\tdroppedItems = new SparseArray<>();\n\t\tfor (int i=1; i <= 31; i++) {\n\t\t\t\n\t\t\t//dropped items\n\t\t\tArrayList<Item> items = new ArrayList<>();\n\t\t\tif (bundle.contains(Messages.format( DROPPED, i )))\n\t\t\t\tfor (Bundlable b : bundle.getCollection( Messages.format( DROPPED, i ) ) ) {\n\t\t\t\t\titems.add( (Item)b );\n\t\t\t\t}\n\t\t\tif (!items.isEmpty()) {\n\t\t\t\tdroppedItems.put( i, items );\n\t\t\t}\n\n\t\t}\n\t}\n\t\n\tpublic static Level loadLevel( int save ) throws IOException {\n\t\t\n\t\tDungeon.level = null;\n\t\tActor.clear();\n\n\t\tBundle bundle = FileUtils.bundleFromFile( GamesInProgress.depthFile( save, depth, branch ));\n\n\t\tLevel level = (Level)bundle.get( LEVEL );\n\n\t\tif (level == null){\n\t\t\tthrow new IOException();\n\t\t} else {\n\t\t\treturn level;\n\t\t}\n\t}\n\t\n\tpublic static void deleteGame( int save, boolean deleteLevels ) {\n\n\t\tif (deleteLevels) {\n\t\t\tString folder = GamesInProgress.gameFolder(save);\n\t\t\tfor (String file : FileUtils.filesInDir(folder)){\n\t\t\t\tif (file.contains(\"depth\")){\n\t\t\t\t\tFileUtils.deleteFile(folder + \"/\" + file);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tFileUtils.overwriteFile(GamesInProgress.gameFile(save), 1);\n\t\t\n\t\tGamesInProgress.delete( save );\n\t}\n\t\n\tpublic static void preview( GamesInProgress.Info info, Bundle bundle ) {\n\t\tinfo.depth = bundle.getInt( DEPTH );\n\t\tinfo.version = bundle.getInt( VERSION );\n\t\tinfo.challenges = bundle.getInt( CHALLENGES );\n\t\tinfo.seed = bundle.getLong( SEED );\n\t\tinfo.customSeed = bundle.getString( CUSTOM_SEED );\n\t\tinfo.daily = bundle.getBoolean( DAILY );\n\t\tinfo.dailyReplay = bundle.getBoolean( DAILY_REPLAY );\n\n\t\tHero.preview( info, bundle.getBundle( HERO ) );\n\t\tStatistics.preview( info, bundle );\n\t}\n\t\n\tpublic static void fail( Object cause ) {\n\t\tif (WndResurrect.instance == null) {\n\t\t\tupdateLevelExplored();\n\t\t\tStatistics.gameWon = false;\n\t\t\tRankings.INSTANCE.submit( false, cause );\n\t\t}\n\t}\n\t\n\tpublic static void win( Object cause ) {\n\n\t\tupdateLevelExplored();\n\t\tStatistics.gameWon = true;\n\n\t\thero.belongings.identify();\n\n\t\tRankings.INSTANCE.submit( true, cause );\n\t}\n\n\tpublic static void updateLevelExplored(){\n\t\tif (branch == 0 && level instanceof RegularLevel && !Dungeon.bossLevel()){\n\t\t\tStatistics.floorsExplored.put( depth, level.isLevelExplored(depth));\n\t\t}\n\t}\n\n\t//default to recomputing based on max hero vision, in case vision just shrank/grew\n\tpublic static void observe(){\n\t\tint dist = Math.max(Dungeon.hero.viewDistance, 8);\n\t\tdist *= 1f + 0.25f*Dungeon.hero.pointsInTalent(Talent.FARSIGHT);\n\t\tdist *= 1f + 0.25f*Dungeon.hero.pointsInTalent(Talent.TELESCOPE);\n\n\t\tif (Dungeon.hero.buff(MagicalSight.class) != null){\n\t\t\tdist = Math.max( dist, MagicalSight.DISTANCE );\n\t\t}\n\n\t\tobserve( dist+1 );\n\t}\n\t\n\tpublic static void observe( int dist ) {\n\n\t\tif (level == null) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlevel.updateFieldOfView(hero, level.heroFOV);\n\n\t\tint x = hero.pos % level.width();\n\t\tint y = hero.pos / level.width();\n\t\n\t\t//left, right, top, bottom\n\t\tint l = Math.max( 0, x - dist );\n\t\tint r = Math.min( x + dist, level.width() - 1 );\n\t\tint t = Math.max( 0, y - dist );\n\t\tint b = Math.min( y + dist, level.height() - 1 );\n\t\n\t\tint width = r - l + 1;\n\t\tint height = b - t + 1;\n\t\t\n\t\tint pos = l + t * level.width();\n\t\n\t\tfor (int i = t; i <= b; i++) {\n\t\t\tBArray.or( level.visited, level.heroFOV, pos, width, level.visited );\n\t\t\tpos+=level.width();\n\t\t}\n\t\n\t\tGameScene.updateFog(l, t, width, height);\n\n\t\tif (hero.buff(MindVision.class) != null){\n\t\t\tfor (Mob m : level.mobs.toArray(new Mob[0])){\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1 - level.width(), 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1, 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1 + level.width(), 3, level.visited );\n\t\t\t\t//updates adjacent cells too\n\t\t\t\tGameScene.updateFog(m.pos, 2);\n\t\t\t}\n\t\t}\n\n\t\tif (hero.buff(Awareness.class) != null){\n\t\t\tfor (Heap h : level.heaps.valueList()){\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 - level.width(), 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1, 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 + level.width(), 3, level.visited );\n\t\t\t\tGameScene.updateFog(h.pos, 2);\n\t\t\t}\n\t\t}\n\n\t\tfor (TalismanOfForesight.CharAwareness c : hero.buffs(TalismanOfForesight.CharAwareness.class)){\n\t\t\tChar ch = (Char) Actor.findById(c.charID);\n\t\t\tif (ch == null || !ch.isAlive()) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(ch.pos, 2);\n\t\t}\n\n\t\tfor (TalismanOfForesight.HeapAwareness h : hero.buffs(TalismanOfForesight.HeapAwareness.class)){\n\t\t\tif (Dungeon.depth != h.depth || Dungeon.branch != h.branch) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(h.pos, 2);\n\t\t}\n\n\t\tfor (RevealedArea a : hero.buffs(RevealedArea.class)){\n\t\t\tif (Dungeon.depth != a.depth || Dungeon.branch != a.branch) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(a.pos, 2);\n\t\t}\n\n\t\tfor (Char ch : Actor.chars()){\n\t\t\tif (ch instanceof WandOfWarding.Ward\n\t\t\t\t\t|| ch instanceof WandOfRegrowth.Lotus\n\t\t\t\t\t|| ch instanceof SpiritHawk.HawkAlly){\n\t\t\t\tx = ch.pos % level.width();\n\t\t\t\ty = ch.pos / level.width();\n\n\t\t\t\t//left, right, top, bottom\n\t\t\t\tdist = ch.viewDistance+1;\n\t\t\t\tl = Math.max( 0, x - dist );\n\t\t\t\tr = Math.min( x + dist, level.width() - 1 );\n\t\t\t\tt = Math.max( 0, y - dist );\n\t\t\t\tb = Math.min( y + dist, level.height() - 1 );\n\n\t\t\t\twidth = r - l + 1;\n\t\t\t\theight = b - t + 1;\n\n\t\t\t\tpos = l + t * level.width();\n\n\t\t\t\tfor (int i = t; i <= b; i++) {\n\t\t\t\t\tBArray.or( level.visited, level.heroFOV, pos, width, level.visited );\n\t\t\t\t\tpos+=level.width();\n\t\t\t\t}\n\t\t\t\tGameScene.updateFog(ch.pos, dist);\n\t\t\t}\n\t\t}\n\n\t\tGameScene.afterObserve();\n\t}\n\n\t//we store this to avoid having to re-allocate the array with each pathfind\n\tprivate static boolean[] passable;\n\n\tprivate static void setupPassable(){\n\t\tif (passable == null || passable.length != Dungeon.level.length())\n\t\t\tpassable = new boolean[Dungeon.level.length()];\n\t\telse\n\t\t\tBArray.setFalse(passable);\n\t}\n\n\tpublic static boolean[] findPassable(Char ch, boolean[] pass, boolean[] vis, boolean chars){\n\t\treturn findPassable(ch, pass, vis, chars, chars);\n\t}\n\n\tpublic static boolean[] findPassable(Char ch, boolean[] pass, boolean[] vis, boolean chars, boolean considerLarge){\n\t\tsetupPassable();\n\t\tif (ch.flying || ch.buff( Amok.class ) != null) {\n\t\t\tBArray.or( pass, Dungeon.level.avoid, passable );\n\t\t} else {\n\t\t\tSystem.arraycopy( pass, 0, passable, 0, Dungeon.level.length() );\n\t\t}\n\n\t\tif (considerLarge && Char.hasProp(ch, Char.Property.LARGE)){\n\t\t\tBArray.and( passable, Dungeon.level.openSpace, passable );\n\t\t}\n\n\t\tch.modifyPassable(passable);\n\n\t\tif (chars) {\n\t\t\tfor (Char c : Actor.chars()) {\n\t\t\t\tif (vis[c.pos]) {\n\t\t\t\t\tpassable[c.pos] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn passable;\n\t}\n\n\tpublic static PathFinder.Path findPath(Char ch, int to, boolean[] pass, boolean[] vis, boolean chars) {\n\n\t\treturn PathFinder.find( ch.pos, to, findPassable(ch, pass, vis, chars) );\n\n\t}\n\t\n\tpublic static int findStep(Char ch, int to, boolean[] pass, boolean[] visible, boolean chars ) {\n\n\t\tif (Dungeon.level.adjacent( ch.pos, to )) {\n\t\t\treturn Actor.findChar( to ) == null && pass[to] ? to : -1;\n\t\t}\n\n\t\treturn PathFinder.getStep( ch.pos, to, findPassable(ch, pass, visible, chars) );\n\n\t}\n\t\n\tpublic static int flee( Char ch, int from, boolean[] pass, boolean[] visible, boolean chars ) {\n\t\tboolean[] passable = findPassable(ch, pass, visible, false, true);\n\t\tpassable[ch.pos] = true;\n\n\t\t//only consider other chars impassable if our retreat step may collide with them\n\t\tif (chars) {\n\t\t\tfor (Char c : Actor.chars()) {\n\t\t\t\tif (c.pos == from || Dungeon.level.adjacent(c.pos, ch.pos)) {\n\t\t\t\t\tpassable[c.pos] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//chars affected by terror have a shorter lookahead and can't approach the fear source\n\t\tboolean canApproachFromPos = ch.buff(Terror.class) == null && ch.buff(Dread.class) == null;\n\t\treturn PathFinder.getStepBack( ch.pos, from, canApproachFromPos ? 8 : 4, passable, canApproachFromPos );\n\t\t\n\t}\n\n}" }, { "identifier": "Actor", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/Actor.java", "snippet": "public abstract class Actor implements Bundlable {\n\t\n\tpublic static final float TICK\t= 1f;\n\n\tprivate float time;\n\n\tprivate int id = 0;\n\n\t//default priority values for general actor categories\n\t//note that some specific actors pick more specific values\n\t//e.g. a buff acting after all normal buffs might have priority BUFF_PRIO + 1\n\tprotected static final int VFX_PRIO = 100; //visual effects take priority\n\tprotected static final int HERO_PRIO = 0; //positive is before hero, negative after\n\tprotected static final int BLOB_PRIO = -10; //blobs act after hero, before mobs\n\tprotected static final int MOB_PRIO = -20; //mobs act between buffs and blobs\n\tprotected static final int BUFF_PRIO = -30; //buffs act last in a turn\n\tprivate static final int DEFAULT = -100; //if no priority is given, act after all else\n\n\t//used to determine what order actors act in if their time is equal. Higher values act earlier.\n\tprotected int actPriority = DEFAULT;\n\n\tprotected abstract boolean act();\n\n\t//Always spends exactly the specified amount of time, regardless of time-influencing factors\n\tprotected void spendConstant( float time ){\n\t\tthis.time += time;\n\t\t//if time is very close to a whole number, round to a whole number to fix errors\n\t\tfloat ex = Math.abs(this.time % 1f);\n\t\tif (ex < .001f){\n\t\t\tthis.time = Math.round(this.time);\n\t\t}\n\t}\n\n\t//sends time, but the amount can be influenced\n\tprotected void spend( float time ) {\n\t\tspendConstant( time );\n\t}\n\n\tpublic void spendToWhole(){\n\t\ttime = (float)Math.ceil(time);\n\t}\n\t\n\tprotected void postpone( float time ) {\n\t\tif (this.time < now + time) {\n\t\t\tthis.time = now + time;\n\t\t\t//if time is very close to a whole number, round to a whole number to fix errors\n\t\t\tfloat ex = Math.abs(this.time % 1f);\n\t\t\tif (ex < .001f){\n\t\t\t\tthis.time = Math.round(this.time);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic float cooldown() {\n\t\treturn time - now;\n\t}\n\n\tpublic void clearTime() {\n\t\ttime = 0;\n\t}\n\n\tpublic void timeToNow() {\n\t\ttime = now;\n\t}\n\t\n\tprotected void diactivate() {\n\t\ttime = Float.MAX_VALUE;\n\t}\n\t\n\tprotected void onAdd() {}\n\t\n\tprotected void onRemove() {}\n\n\tprivate static final String TIME = \"time\";\n\tprivate static final String ID = \"id\";\n\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tbundle.put( TIME, time );\n\t\tbundle.put( ID, id );\n\t}\n\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\ttime = bundle.getFloat( TIME );\n\t\tint incomingID = bundle.getInt( ID );\n\t\tif (Actor.findById(incomingID) == null){\n\t\t\tid = incomingID;\n\t\t} else {\n\t\t\tid = nextID++;\n\t\t}\n\t}\n\n\tpublic int id() {\n\t\tif (id > 0) {\n\t\t\treturn id;\n\t\t} else {\n\t\t\treturn (id = nextID++);\n\t\t}\n\t}\n\n\t// **********************\n\t// *** Static members ***\n\t// **********************\n\t\n\tprivate static HashSet<Actor> all = new HashSet<>();\n\tprivate static HashSet<Char> chars = new HashSet<>();\n\tprivate static volatile Actor current;\n\n\tprivate static SparseArray<Actor> ids = new SparseArray<>();\n\tprivate static int nextID = 1;\n\n\tprivate static float now = 0;\n\t\n\tpublic static float now(){\n\t\treturn now;\n\t}\n\t\n\tpublic static synchronized void clear() {\n\t\t\n\t\tnow = 0;\n\n\t\tall.clear();\n\t\tchars.clear();\n\n\t\tids.clear();\n\t}\n\n\tpublic static synchronized void fixTime() {\n\t\t\n\t\tif (all.isEmpty()) return;\n\t\t\n\t\tfloat min = Float.MAX_VALUE;\n\t\tfor (Actor a : all) {\n\t\t\tif (a.time < min) {\n\t\t\t\tmin = a.time;\n\t\t\t}\n\t\t}\n\n\t\t//Only pull everything back by whole numbers\n\t\t//So that turns always align with a whole number\n\t\tmin = (int)min;\n\t\tfor (Actor a : all) {\n\t\t\ta.time -= min;\n\t\t}\n\n\t\tif (Dungeon.hero != null && all.contains( Dungeon.hero )) {\n\t\t\tStatistics.duration += min;\n\t\t}\n\t\tnow -= min;\n\t}\n\t\n\tpublic static void init() {\n\t\t\n\t\tadd( Dungeon.hero );\n\t\t\n\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\tadd( mob );\n\t\t}\n\n\t\t//mobs need to remember their targets after every actor is added\n\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\tmob.restoreEnemy();\n\t\t}\n\t\t\n\t\tfor (Blob blob : Dungeon.level.blobs.values()) {\n\t\t\tadd( blob );\n\t\t}\n\t\t\n\t\tcurrent = null;\n\t}\n\n\tprivate static final String NEXTID = \"nextid\";\n\n\tpublic static void storeNextID( Bundle bundle){\n\t\tbundle.put( NEXTID, nextID );\n\t}\n\n\tpublic static void restoreNextID( Bundle bundle){\n\t\tnextID = bundle.getInt( NEXTID );\n\t}\n\n\tpublic static void resetNextID(){\n\t\tnextID = 1;\n\t}\n\n\t/*protected*/public void next() {\n\t\tif (current == this) {\n\t\t\tcurrent = null;\n\t\t}\n\t}\n\n\tpublic static boolean processing(){\n\t\treturn current != null;\n\t}\n\n\tpublic static int curActorPriority() {\n\t\treturn current != null ? current.actPriority : DEFAULT;\n\t}\n\t\n\tpublic static boolean keepActorThreadAlive = true;\n\t\n\tpublic static void process() {\n\t\t\n\t\tboolean doNext;\n\t\tboolean interrupted = false;\n\n\t\tdo {\n\t\t\t\n\t\t\tcurrent = null;\n\t\t\tif (!interrupted) {\n\t\t\t\tfloat earliest = Float.MAX_VALUE;\n\n\t\t\t\tfor (Actor actor : all) {\n\t\t\t\t\t\n\t\t\t\t\t//some actors will always go before others if time is equal.\n\t\t\t\t\tif (actor.time < earliest ||\n\t\t\t\t\t\t\tactor.time == earliest && (current == null || actor.actPriority > current.actPriority)) {\n\t\t\t\t\t\tearliest = actor.time;\n\t\t\t\t\t\tcurrent = actor;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (current != null) {\n\n\t\t\t\tnow = current.time;\n\t\t\t\tActor acting = current;\n\n\t\t\t\tif (acting instanceof Char && ((Char) acting).sprite != null) {\n\t\t\t\t\t// If it's character's turn to act, but its sprite\n\t\t\t\t\t// is moving, wait till the movement is over\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsynchronized (((Char)acting).sprite) {\n\t\t\t\t\t\t\tif (((Char)acting).sprite.isMoving) {\n\t\t\t\t\t\t\t\t((Char) acting).sprite.wait();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\tinterrupted = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tinterrupted = interrupted || Thread.interrupted();\n\t\t\t\t\n\t\t\t\tif (interrupted){\n\t\t\t\t\tdoNext = false;\n\t\t\t\t\tcurrent = null;\n\t\t\t\t} else {\n\t\t\t\t\tdoNext = acting.act();\n\t\t\t\t\tif (doNext && (Dungeon.hero == null || !Dungeon.hero.isAlive())) {\n\t\t\t\t\t\tdoNext = false;\n\t\t\t\t\t\tcurrent = null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdoNext = false;\n\t\t\t}\n\n\t\t\tif (!doNext){\n\t\t\t\tsynchronized (Thread.currentThread()) {\n\t\t\t\t\t\n\t\t\t\t\tinterrupted = interrupted || Thread.interrupted();\n\t\t\t\t\t\n\t\t\t\t\tif (interrupted){\n\t\t\t\t\t\tcurrent = null;\n\t\t\t\t\t\tinterrupted = false;\n\t\t\t\t\t}\n\n\t\t\t\t\t//signals to the gamescene that actor processing is finished for now\n\t\t\t\t\tThread.currentThread().notify();\n\t\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\tThread.currentThread().wait();\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\tinterrupted = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t} while (keepActorThreadAlive);\n\t}\n\t\n\tpublic static void add( Actor actor ) {\n\t\tadd( actor, now );\n\t}\n\t\n\tpublic static void addDelayed( Actor actor, float delay ) {\n\t\tadd( actor, now + Math.max(delay, 0) );\n\t}\n\t\n\tprivate static synchronized void add( Actor actor, float time ) {\n\t\t\n\t\tif (all.contains( actor )) {\n\t\t\treturn;\n\t\t}\n\n\t\tids.put( actor.id(), actor );\n\n\t\tall.add( actor );\n\t\tactor.time += time;\n\t\tactor.onAdd();\n\t\t\n\t\tif (actor instanceof Char) {\n\t\t\tChar ch = (Char)actor;\n\t\t\tchars.add( ch );\n\t\t\tfor (Buff buff : ch.buffs()) {\n\t\t\t\tadd(buff);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static synchronized void remove( Actor actor ) {\n\t\t\n\t\tif (actor != null) {\n\t\t\tall.remove( actor );\n\t\t\tchars.remove( actor );\n\t\t\tactor.onRemove();\n\n\t\t\tif (actor.id > 0) {\n\t\t\t\tids.remove( actor.id );\n\t\t\t}\n\t\t}\n\t}\n\n\t//'freezes' a character in time for a specified amount of time\n\t//USE CAREFULLY! Manipulating time like this is useful for some gameplay effects but is tricky\n\tpublic static void delayChar( Char ch, float time ){\n\t\tch.spendConstant(time);\n\t\tfor (Buff b : ch.buffs()){\n\t\t\tb.spendConstant(time);\n\t\t}\n\t}\n\t\n\tpublic static synchronized Char findChar( int pos ) {\n\t\tfor (Char ch : chars){\n\t\t\tif (ch.pos == pos)\n\t\t\t\treturn ch;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static synchronized Actor findById( int id ) {\n\t\treturn ids.get( id );\n\t}\n\n\tpublic static synchronized HashSet<Actor> all() {\n\t\treturn new HashSet<>(all);\n\t}\n\n\tpublic static synchronized HashSet<Char> chars() { return new HashSet<>(chars); }\n}" }, { "identifier": "Char", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/Char.java", "snippet": "public abstract class Char extends Actor {\n\t\n\tpublic int pos = 0;\n\t\n\tpublic CharSprite sprite;\n\t\n\tpublic int HT;\n\tpublic int HP;\n\t\n\tprotected float baseSpeed\t= 1;\n\tprotected PathFinder.Path path;\n\n\tpublic int paralysed\t = 0;\n\tpublic boolean rooted\t\t= false;\n\tpublic boolean flying\t\t= false;\n\tpublic int invisible\t\t= 0;\n\t\n\t//these are relative to the hero\n\tpublic enum Alignment{\n\t\tENEMY,\n\t\tNEUTRAL,\n\t\tALLY\n\t}\n\tpublic Alignment alignment;\n\t\n\tpublic int viewDistance\t= 8;\n\t\n\tpublic boolean[] fieldOfView = null;\n\t\n\tprivate LinkedHashSet<Buff> buffs = new LinkedHashSet<>();\n\t\n\t@Override\n\tprotected boolean act() {\n\t\tif (fieldOfView == null || fieldOfView.length != Dungeon.level.length()){\n\t\t\tfieldOfView = new boolean[Dungeon.level.length()];\n\t\t}\n\t\tDungeon.level.updateFieldOfView( this, fieldOfView );\n\n\t\t//throw any items that are on top of an immovable char\n\t\tif (properties().contains(Property.IMMOVABLE)){\n\t\t\tthrowItems();\n\t\t}\n\t\treturn false;\n\t}\n\n\tprotected void throwItems(){\n\t\tHeap heap = Dungeon.level.heaps.get( pos );\n\t\tif (heap != null && heap.type == Heap.Type.HEAP\n\t\t\t\t&& !(heap.peek() instanceof Tengu.BombAbility.BombItem)\n\t\t\t\t&& !(heap.peek() instanceof Tengu.ShockerAbility.ShockerItem)) {\n\t\t\tArrayList<Integer> candidates = new ArrayList<>();\n\t\t\tfor (int n : PathFinder.NEIGHBOURS8){\n\t\t\t\tif (Dungeon.level.passable[pos+n]){\n\t\t\t\t\tcandidates.add(pos+n);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!candidates.isEmpty()){\n\t\t\t\tDungeon.level.drop( heap.pickUp(), Random.element(candidates) ).sprite.drop( pos );\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic String name(){\n\t\treturn Messages.get(this, \"name\");\n\t}\n\n\tpublic boolean canInteract(Char c){\n\t\tif (Dungeon.level.adjacent( pos, c.pos )){\n\t\t\treturn true;\n\t\t} else if (c instanceof Hero\n\t\t\t\t&& alignment == Alignment.ALLY\n\t\t\t\t&& Dungeon.level.distance(pos, c.pos) <= 2*Dungeon.hero.pointsInTalent(Talent.ALLY_WARP)){\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t//swaps places by default\n\tpublic boolean interact(Char c){\n\n\t\t//don't allow char to swap onto hazard unless they're flying\n\t\t//you can swap onto a hazard though, as you're not the one instigating the swap\n\t\tif (!Dungeon.level.passable[pos] && !c.flying){\n\t\t\treturn true;\n\t\t}\n\n\t\t//can't swap into a space without room\n\t\tif (properties().contains(Property.LARGE) && !Dungeon.level.openSpace[c.pos]\n\t\t\t|| c.properties().contains(Property.LARGE) && !Dungeon.level.openSpace[pos]){\n\t\t\treturn true;\n\t\t}\n\n\t\t//we do a little raw position shuffling here so that the characters are never\n\t\t// on the same cell when logic such as occupyCell() is triggered\n\t\tint oldPos = pos;\n\t\tint newPos = c.pos;\n\n\t\t//warp instantly with allies in this case\n\t\tif (c == Dungeon.hero && Dungeon.hero.hasTalent(Talent.ALLY_WARP)){\n\t\t\tPathFinder.buildDistanceMap(c.pos, BArray.or(Dungeon.level.passable, Dungeon.level.avoid, null));\n\t\t\tif (PathFinder.distance[pos] == Integer.MAX_VALUE){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tpos = newPos;\n\t\t\tc.pos = oldPos;\n\t\t\tScrollOfTeleportation.appear(this, newPos);\n\t\t\tScrollOfTeleportation.appear(c, oldPos);\n\t\t\tDungeon.observe();\n\t\t\tGameScene.updateFog();\n\t\t\treturn true;\n\t\t}\n\n\t\t//can't swap places if one char has restricted movement\n\t\tif (rooted || c.rooted || buff(Vertigo.class) != null || c.buff(Vertigo.class) != null){\n\t\t\treturn true;\n\t\t}\n\n\t\tc.pos = oldPos;\n\t\tmoveSprite( oldPos, newPos );\n\t\tmove( newPos );\n\n\t\tc.pos = newPos;\n\t\tc.sprite.move( newPos, oldPos );\n\t\tc.move( oldPos );\n\t\t\n\t\tc.spend( 1 / c.speed() );\n\n\t\tif (c == Dungeon.hero){\n\t\t\tif (Dungeon.hero.subClass == HeroSubClass.FREERUNNER){\n\t\t\t\tBuff.affect(Dungeon.hero, Momentum.class).gainStack();\n\t\t\t}\n\n\t\t\tDungeon.hero.busy();\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t\n\tprotected boolean moveSprite( int from, int to ) {\n\t\t\n\t\tif (sprite.isVisible() && sprite.parent != null && (Dungeon.level.heroFOV[from] || Dungeon.level.heroFOV[to])) {\n\t\t\tsprite.move( from, to );\n\t\t\treturn true;\n\t\t} else {\n\t\t\tsprite.turnTo(from, to);\n\t\t\tsprite.place( to );\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic void hitSound( float pitch ){\n\t\tSample.INSTANCE.play(Assets.Sounds.HIT, 1, pitch);\n\t}\n\n\tpublic boolean blockSound( float pitch ) {\n\t\treturn false;\n\t}\n\t\n\tprotected static final String POS = \"pos\";\n\tprotected static final String TAG_HP = \"HP\";\n\tprotected static final String TAG_HT = \"HT\";\n\tprotected static final String TAG_SHLD = \"SHLD\";\n\tprotected static final String BUFFS\t = \"buffs\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.storeInBundle( bundle );\n\t\t\n\t\tbundle.put( POS, pos );\n\t\tbundle.put( TAG_HP, HP );\n\t\tbundle.put( TAG_HT, HT );\n\t\tbundle.put( BUFFS, buffs );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.restoreFromBundle( bundle );\n\t\t\n\t\tpos = bundle.getInt( POS );\n\t\tHP = bundle.getInt( TAG_HP );\n\t\tHT = bundle.getInt( TAG_HT );\n\t\t\n\t\tfor (Bundlable b : bundle.getCollection( BUFFS )) {\n\t\t\tif (b != null) {\n\t\t\t\t((Buff)b).attachTo( this );\n\t\t\t}\n\t\t}\n\t}\n\n\tfinal public boolean attack( Char enemy ){\n\t\treturn attack(enemy, 1f, 0f, 1f);\n\t}\n\t\n\tpublic boolean attack( Char enemy, float dmgMulti, float dmgBonus, float accMulti ) {\n\n\t\tif (enemy == null) return false;\n\t\t\n\t\tboolean visibleFight = Dungeon.level.heroFOV[pos] || Dungeon.level.heroFOV[enemy.pos];\n\n\t\tif (enemy.isInvulnerable(getClass())) {\n\n\t\t\tif (visibleFight) {\n\t\t\t\tenemy.sprite.showStatus( CharSprite.POSITIVE, Messages.get(this, \"invulnerable\") );\n\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1f, Random.Float(0.96f, 1.05f));\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (hit( this, enemy, accMulti, false )) {\n\t\t\t\n\t\t\tint dr = Math.round(enemy.drRoll() * AscensionChallenge.statModifier(enemy));\n\t\t\t\n\t\t\tif (this instanceof Hero){\n\t\t\t\tHero h = (Hero)this;\n\t\t\t\tif (h.belongings.attackingWeapon() instanceof MissileWeapon\n\t\t\t\t\t\t&& h.subClass == HeroSubClass.SNIPER\n\t\t\t\t\t\t&& !Dungeon.level.adjacent(h.pos, enemy.pos)){\n\t\t\t\t\tdr = 0;\n\t\t\t\t}\n\n\t\t\t\tif (h.belongings.attackingWeapon() instanceof Gun.Bullet) {\n\t\t\t\t\tdr *= ((Gun.Bullet) h.belongings.attackingWeapon()).whatBullet().armorFactor();\n\t\t\t\t}\n\n\t\t\t\tif (h.buff(MonkEnergy.MonkAbility.UnarmedAbilityTracker.class) != null){\n\t\t\t\t\tdr = 0;\n\t\t\t\t} else if (h.subClass == HeroSubClass.MONK) {\n\t\t\t\t\t//3 turns with standard attack delay\n\t\t\t\t\tBuff.prolong(h, MonkEnergy.MonkAbility.JustHitTracker.class, 4f);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//we use a float here briefly so that we don't have to constantly round while\n\t\t\t// potentially applying various multiplier effects\n\t\t\tfloat dmg;\n\t\t\tPreparation prep = buff(Preparation.class);\n\t\t\tif (prep != null){\n\t\t\t\tdmg = prep.damageRoll(this);\n\t\t\t\tif (this == Dungeon.hero && Dungeon.hero.hasTalent(Talent.BOUNTY_HUNTER)) {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.BountyHunterTracker.class, 0.0f);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdmg = damageRoll();\n\t\t\t}\n\n\t\t\tdmg = Math.round(dmg*dmgMulti);\n\n\t\t\tBerserk berserk = buff(Berserk.class);\n\t\t\tif (berserk != null) dmg = berserk.damageFactor(dmg);\n\n\t\t\tif (buff( Fury.class ) != null) {\n\t\t\t\tdmg *= 1.5f;\n\t\t\t}\n\n\t\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\t\tdmg *= buff.meleeDamageFactor();\n\t\t\t}\n\n\t\t\tdmg *= AscensionChallenge.statModifier(this);\n\n\t\t\t//flat damage bonus is applied after positive multipliers, but before negative ones\n\t\t\tdmg += dmgBonus;\n\n\t\t\t//friendly endure\n\t\t\tEndure.EndureTracker endure = buff(Endure.EndureTracker.class);\n\t\t\tif (endure != null) dmg = endure.damageFactor(dmg);\n\n\t\t\t//enemy endure\n\t\t\tendure = enemy.buff(Endure.EndureTracker.class);\n\t\t\tif (endure != null){\n\t\t\t\tdmg = endure.adjustDamageTaken(dmg);\n\t\t\t}\n\n\t\t\tif (enemy.buff(ScrollOfChallenge.ChallengeArena.class) != null){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\n\t\t\tif (enemy.buff(MonkEnergy.MonkAbility.Meditate.MeditateResistance.class) != null){\n\t\t\t\tdmg *= 0.2f;\n\t\t\t}\n\n\t\t\tif ( buff(Weakness.class) != null ){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\n\t\t\tif ( buff(SoulMark.class) != null && hero.hasTalent(Talent.MARK_OF_WEAKNESS)) {\n\t\t\t\tif (this.alignment != Alignment.ALLY) {\n\t\t\t\t\tdmg *= Math.pow(0.9f, hero.pointsInTalent(Talent.MARK_OF_WEAKNESS));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tint effectiveDamage = enemy.defenseProc( this, Math.round(dmg) );\n\t\t\t//do not trigger on-hit logic if defenseProc returned a negative value\n\t\t\tif (effectiveDamage >= 0) {\n\t\t\t\teffectiveDamage = Math.max(effectiveDamage - dr, 0);\n\n\t\t\t\tif (enemy.buff(Viscosity.ViscosityTracker.class) != null) {\n\t\t\t\t\teffectiveDamage = enemy.buff(Viscosity.ViscosityTracker.class).deferDamage(effectiveDamage);\n\t\t\t\t\tenemy.buff(Viscosity.ViscosityTracker.class).detach();\n\t\t\t\t}\n\n\t\t\t\t//vulnerable specifically applies after armor reductions\n\t\t\t\tif (enemy.buff(Vulnerable.class) != null) {\n\t\t\t\t\teffectiveDamage *= 1.33f;\n\t\t\t\t}\n\n\t\t\t\teffectiveDamage = attackProc(enemy, effectiveDamage);\n\t\t\t}\n\t\t\tif (visibleFight) {\n\t\t\t\tif (effectiveDamage > 0 || !enemy.blockSound(Random.Float(0.96f, 1.05f))) {\n\t\t\t\t\thitSound(Random.Float(0.87f, 1.15f));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If the enemy is already dead, interrupt the attack.\n\t\t\t// This matters as defence procs can sometimes inflict self-damage, such as armor glyphs.\n\t\t\tif (!enemy.isAlive()){\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tenemy.damage( effectiveDamage, this );\n\n\t\t\tif (buff(FireImbue.class) != null) buff(FireImbue.class).proc(enemy);\n\t\t\tif (buff(FrostImbue.class) != null) buff(FrostImbue.class).proc(enemy);\n\t\t\tif (buff(ThunderImbue.class) != null) buff(ThunderImbue.class).proc(enemy, (int)dmg);\n\n\t\t\tif (enemy.isAlive() && enemy.alignment != alignment && prep != null && prep.canKO(enemy)){\n\t\t\t\tenemy.HP = 0;\n\t\t\t\tif (!enemy.isAlive()) {\n\t\t\t\t\tenemy.die(this);\n\t\t\t\t} else {\n\t\t\t\t\t//helps with triggering any on-damage effects that need to activate\n\t\t\t\t\tenemy.damage(-1, this);\n\t\t\t\t\tDeathMark.processFearTheReaper(enemy);\n\t\t\t\t}\n\t\t\t\tif (enemy.sprite != null) {\n\t\t\t\t\tenemy.sprite.showStatus(CharSprite.NEGATIVE, Messages.get(Preparation.class, \"assassinated\"));\n\t\t\t\t}\n\t\t\t\tif (Random.Float() < hero.pointsInTalent(Talent.ENERGY_DRAW)/3f) {\n\t\t\t\t\tCloakOfShadows cloak = hero.belongings.getItem(CloakOfShadows.class);\n\t\t\t\t\tif (cloak != null) {\n\t\t\t\t\t\tcloak.overCharge(1);\n\t\t\t\t\t\tScrollOfRecharging.charge(Dungeon.hero);\n\t\t\t\t\t\tSpellSprite.show(hero, SpellSprite.CHARGE);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tTalent.CombinedLethalityTriggerTracker combinedLethality = buff(Talent.CombinedLethalityTriggerTracker.class);\n\t\t\tif (combinedLethality != null){\n\t\t\t\tif ( enemy.isAlive() && enemy.alignment != alignment && !Char.hasProp(enemy, Property.BOSS)\n\t\t\t\t\t\t&& !Char.hasProp(enemy, Property.MINIBOSS) && this instanceof Hero &&\n\t\t\t\t\t\t(enemy.HP/(float)enemy.HT) <= 0.4f*((Hero)this).pointsInTalent(Talent.COMBINED_LETHALITY)/3f) {\n\t\t\t\t\tenemy.HP = 0;\n\t\t\t\t\tif (!enemy.isAlive()) {\n\t\t\t\t\t\tenemy.die(this);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//helps with triggering any on-damage effects that need to activate\n\t\t\t\t\t\tenemy.damage(-1, this);\n\t\t\t\t\t\tDeathMark.processFearTheReaper(enemy);\n\t\t\t\t\t}\n\t\t\t\t\tif (enemy.sprite != null) {\n\t\t\t\t\t\tenemy.sprite.showStatus(CharSprite.NEGATIVE, Messages.get(Talent.CombinedLethalityTriggerTracker.class, \"executed\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcombinedLethality.detach();\n\t\t\t}\n\n\t\t\tif (enemy.sprite != null) {\n\t\t\t\tenemy.sprite.bloodBurstA(sprite.center(), effectiveDamage);\n\t\t\t\tenemy.sprite.flash();\n\t\t\t}\n\n\t\t\tif (!enemy.isAlive() && visibleFight) {\n\t\t\t\tif (enemy == Dungeon.hero) {\n\t\t\t\t\t\n\t\t\t\t\tif (this == Dungeon.hero) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this instanceof WandOfLivingEarth.EarthGuardian\n\t\t\t\t\t\t\t|| this instanceof MirrorImage || this instanceof PrismaticImage){\n\t\t\t\t\t\tBadges.validateDeathFromFriendlyMagic();\n\t\t\t\t\t}\n\t\t\t\t\tDungeon.fail( this );\n\t\t\t\t\tGLog.n( Messages.capitalize(Messages.get(Char.class, \"kill\", name())) );\n\t\t\t\t\t\n\t\t\t\t} else if (this == Dungeon.hero) {\n\t\t\t\t\tGLog.i( Messages.capitalize(Messages.get(Char.class, \"defeat\", enemy.name())) );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t\t\n\t\t} else {\n\n\t\t\tif (enemy instanceof Hero) {\n\t\t\t\tif (hero.pointsInTalent(Talent.SWIFT_MOVEMENT) == 3) {\n\t\t\t\t\tBuff.prolong(hero, Invisibility.class, 1.0001f);\n\t\t\t\t}\n\t\t\t\tif (Random.Int(5) < hero.pointsInTalent(Talent.COUNTER_ATTACK)) {\n\t\t\t\t\tBuff.affect(hero, Talent.CounterAttackTracker.class);\n\t\t\t\t}\n\t\t\t\tif (hero.hasTalent(Talent.QUICK_PREP)) {\n\t\t\t\t\tMomentum momentum = hero.buff(Momentum.class);\n\t\t\t\t\tif (momentum != null) {\n\t\t\t\t\t\tmomentum.quickPrep(hero.pointsInTalent(Talent.QUICK_PREP));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tenemy.sprite.showStatus( CharSprite.NEUTRAL, enemy.defenseVerb() );\n\t\t\tif (visibleFight) {\n\t\t\t\t//TODO enemy.defenseSound? currently miss plays for monks/crab even when they parry\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.MISS);\n\t\t\t}\n\t\t\t\n\t\t\treturn false;\n\t\t\t\n\t\t}\n\t}\n\n\tpublic static int INFINITE_ACCURACY = 1_000_000;\n\tpublic static int INFINITE_EVASION = 1_000_000;\n\n\tfinal public static boolean hit( Char attacker, Char defender, boolean magic ) {\n\t\treturn hit(attacker, defender, magic ? 2f : 1f, magic);\n\t}\n\n\tpublic static boolean hit( Char attacker, Char defender, float accMulti, boolean magic ) {\n\t\tfloat acuStat = attacker.attackSkill( defender );\n\t\tfloat defStat = defender.defenseSkill( attacker );\n\n\t\tif (defender instanceof Hero && ((Hero) defender).damageInterrupt){\n\t\t\t((Hero) defender).interrupt();\n\t\t}\n\n\t\t//invisible chars always hit (for the hero this is surprise attacking)\n\t\tif (attacker.invisible > 0 && attacker.canSurpriseAttack()){\n\t\t\tacuStat = INFINITE_ACCURACY;\n\t\t}\n\n\t\tif (defender.buff(MonkEnergy.MonkAbility.Focus.FocusBuff.class) != null && !magic){\n\t\t\tdefStat = INFINITE_EVASION;\n\t\t\tdefender.buff(MonkEnergy.MonkAbility.Focus.FocusBuff.class).detach();\n\t\t\tBuff.affect(defender, MonkEnergy.MonkAbility.Focus.FocusActivation.class, 0);\n\t\t}\n\n\t\t//if accuracy or evasion are large enough, treat them as infinite.\n\t\t//note that infinite evasion beats infinite accuracy\n\t\tif (defStat >= INFINITE_EVASION){\n\t\t\treturn false;\n\t\t} else if (acuStat >= INFINITE_ACCURACY){\n\t\t\treturn true;\n\t\t}\n\n\t\tfloat acuRoll = Random.Float( acuStat );\n\t\tif (attacker.buff(Bless.class) != null) acuRoll *= 1.25f;\n\t\tif (attacker.buff( Hex.class) != null) acuRoll *= 0.8f;\n\t\tif (attacker.buff( Daze.class) != null) acuRoll *= 0.5f;\n\t\tfor (ChampionEnemy buff : attacker.buffs(ChampionEnemy.class)){\n\t\t\tacuRoll *= buff.evasionAndAccuracyFactor();\n\t\t}\n\t\tacuRoll *= AscensionChallenge.statModifier(attacker);\n\t\t\n\t\tfloat defRoll = Random.Float( defStat );\n\t\tif (defender.buff(Bless.class) != null) defRoll *= 1.25f;\n\t\tif (defender.buff( Hex.class) != null) defRoll *= 0.8f;\n\t\tif (defender.buff( Daze.class) != null) defRoll *= 0.5f;\n\t\tfor (ChampionEnemy buff : defender.buffs(ChampionEnemy.class)){\n\t\t\tdefRoll *= buff.evasionAndAccuracyFactor();\n\t\t}\n\t\tdefRoll *= AscensionChallenge.statModifier(defender);\n\t\t\n\t\treturn (acuRoll * accMulti) >= defRoll;\n\t}\n\t\n\tpublic int attackSkill( Char target ) {\n\t\treturn 0;\n\t}\n\t\n\tpublic int defenseSkill( Char enemy ) {\n\t\treturn 0;\n\t}\n\t\n\tpublic String defenseVerb() {\n\t\treturn Messages.get(this, \"def_verb\");\n\t}\n\t\n\tpublic int drRoll() {\n\t\tint dr = 0;\n\n\t\tdr += Random.NormalIntRange( 0 , Barkskin.currentLevel(this) );\n\n\t\treturn dr;\n\t}\n\t\n\tpublic int damageRoll() {\n\t\treturn 1;\n\t}\n\t\n\t//TODO it would be nice to have a pre-armor and post-armor proc.\n\t// atm attack is always post-armor and defence is already pre-armor\n\t\n\tpublic int attackProc( Char enemy, int damage ) {\n\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\tbuff.onAttackProc( enemy );\n\t\t}\n\t\treturn damage;\n\t}\n\t\n\tpublic int defenseProc( Char enemy, int damage ) {\n\n\t\tEarthroot.Armor armor = buff( Earthroot.Armor.class );\n\t\tif (armor != null) {\n\t\t\tdamage = armor.absorb( damage );\n\t\t}\n\n\t\treturn damage;\n\t}\n\t\n\tpublic float speed() {\n\t\tfloat speed = baseSpeed;\n\t\tif ( buff( Cripple.class ) != null ) speed /= 2f;\n\t\tif ( buff( Stamina.class ) != null) speed *= 1.5f;\n\t\tif ( buff( Adrenaline.class ) != null) speed *= 2f;\n\t\tif ( buff( Haste.class ) != null) speed *= 3f;\n\t\tif ( buff( Dread.class ) != null) speed *= 2f;\n\t\treturn speed;\n\t}\n\n\t//currently only used by invisible chars, or by the hero\n\tpublic boolean canSurpriseAttack(){\n\t\treturn true;\n\t}\n\t\n\t//used so that buffs(Shieldbuff.class) isn't called every time unnecessarily\n\tprivate int cachedShield = 0;\n\tpublic boolean needsShieldUpdate = true;\n\t\n\tpublic int shielding(){\n\t\tif (!needsShieldUpdate){\n\t\t\treturn cachedShield;\n\t\t}\n\t\t\n\t\tcachedShield = 0;\n\t\tfor (ShieldBuff s : buffs(ShieldBuff.class)){\n\t\t\tcachedShield += s.shielding();\n\t\t}\n\t\tneedsShieldUpdate = false;\n\t\treturn cachedShield;\n\t}\n\t\n\tpublic void damage( int dmg, Object src ) {\n\t\t\n\t\tif (!isAlive() || dmg < 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tif(isInvulnerable(src.getClass())){\n\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.get(this, \"invulnerable\"));\n\t\t\treturn;\n\t\t}\n\n\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\tdmg = (int) Math.ceil(dmg * buff.damageTakenFactor());\n\t\t}\n\n\t\tif (!(src instanceof LifeLink) && buff(LifeLink.class) != null){\n\t\t\tHashSet<LifeLink> links = buffs(LifeLink.class);\n\t\t\tfor (LifeLink link : links.toArray(new LifeLink[0])){\n\t\t\t\tif (Actor.findById(link.object) == null){\n\t\t\t\t\tlinks.remove(link);\n\t\t\t\t\tlink.detach();\n\t\t\t\t}\n\t\t\t}\n\t\t\tdmg = (int)Math.ceil(dmg / (float)(links.size()+1));\n\t\t\tfor (LifeLink link : links){\n\t\t\t\tChar ch = (Char)Actor.findById(link.object);\n\t\t\t\tif (ch != null) {\n\t\t\t\t\tch.damage(dmg, link);\n\t\t\t\t\tif (!ch.isAlive()) {\n\t\t\t\t\t\tlink.detach();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tTerror t = buff(Terror.class);\n\t\tif (t != null){\n\t\t\tt.recover();\n\t\t}\n\t\tDread d = buff(Dread.class);\n\t\tif (d != null){\n\t\t\td.recover();\n\t\t}\n\t\tCharm c = buff(Charm.class);\n\t\tif (c != null){\n\t\t\tc.recover(src);\n\t\t}\n\t\tif (this.buff(Frost.class) != null){\n\t\t\tBuff.detach( this, Frost.class );\n\t\t}\n\t\tif (this.buff(MagicalSleep.class) != null){\n\t\t\tBuff.detach(this, MagicalSleep.class);\n\t\t}\n\t\tif (this.buff(Doom.class) != null && !isImmune(Doom.class)){\n\t\t\tdmg *= 1.67f;\n\t\t}\n\t\tif (alignment != Alignment.ALLY && this.buff(DeathMark.DeathMarkTracker.class) != null){\n\t\t\tdmg *= 1.25f;\n\t\t}\n\t\t\n\t\tClass<?> srcClass = src.getClass();\n\t\tif (isImmune( srcClass )) {\n\t\t\tdmg = 0;\n\t\t} else {\n\t\t\tdmg = Math.round( dmg * resist( srcClass ));\n\t\t}\n\t\t\n\t\t//TODO improve this when I have proper damage source logic\n\t\tif (AntiMagic.RESISTS.contains(src.getClass()) && buff(ArcaneArmor.class) != null){\n\t\t\tdmg -= Random.NormalIntRange(0, buff(ArcaneArmor.class).level());\n\t\t\tif (dmg < 0) dmg = 0;\n\t\t}\n\n\t\tif (buff(Sickle.HarvestBleedTracker.class) != null){\n\t\t\tif (isImmune(Bleeding.class)){\n\t\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.titleCase(Messages.get(this, \"immune\")));\n\t\t\t\tbuff(Sickle.HarvestBleedTracker.class).detach();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tBleeding b = buff(Bleeding.class);\n\t\t\tif (b == null){\n\t\t\t\tb = new Bleeding();\n\t\t\t}\n\t\t\tb.announced = false;\n\t\t\tb.set(dmg*buff(Sickle.HarvestBleedTracker.class).bleedFactor, Sickle.HarvestBleedTracker.class);\n\t\t\tb.attachTo(this);\n\t\t\tsprite.showStatus(CharSprite.WARNING, Messages.titleCase(b.name()) + \" \" + (int)b.level());\n\t\t\tbuff(Sickle.HarvestBleedTracker.class).detach();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (buff( Paralysis.class ) != null) {\n\t\t\tbuff( Paralysis.class ).processDamage(dmg);\n\t\t}\n\n\t\tint shielded = dmg;\n\t\t//FIXME: when I add proper damage properties, should add an IGNORES_SHIELDS property to use here.\n\t\tif (!(src instanceof Hunger)){\n\t\t\tfor (ShieldBuff s : buffs(ShieldBuff.class)){\n\t\t\t\tdmg = s.absorbDamage(dmg);\n\t\t\t\tif (dmg == 0) break;\n\t\t\t}\n\t\t}\n\t\tshielded -= dmg;\n\t\tHP -= dmg;\n\n\t\tif (HP > 0 && buff(Grim.GrimTracker.class) != null){\n\n\t\t\tfloat finalChance = buff(Grim.GrimTracker.class).maxChance;\n\t\t\tfinalChance *= (float)Math.pow( ((HT - HP) / (float)HT), 2);\n\n\t\t\tif (Random.Float() < finalChance) {\n\t\t\t\tint extraDmg = Math.round(HP*resist(Grim.class));\n\t\t\t\tdmg += extraDmg;\n\t\t\t\tHP -= extraDmg;\n\n\t\t\t\tsprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\tif (!isAlive() && buff(Grim.GrimTracker.class).qualifiesForBadge){\n\t\t\t\t\tBadges.validateGrimWeapon();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (HP < 0 && src instanceof Char && alignment == Alignment.ENEMY){\n\t\t\tif (((Char) src).buff(Kinetic.KineticTracker.class) != null){\n\t\t\t\tint dmgToAdd = -HP;\n\t\t\t\tdmgToAdd -= ((Char) src).buff(Kinetic.KineticTracker.class).conservedDamage;\n\t\t\t\tdmgToAdd = Math.round(dmgToAdd * Weapon.Enchantment.genericProcChanceMultiplier((Char) src));\n\t\t\t\tif (dmgToAdd > 0) {\n\t\t\t\t\tBuff.affect((Char) src, Kinetic.ConservedDamage.class).setBonus(dmgToAdd);\n\t\t\t\t}\n\t\t\t\t((Char) src).buff(Kinetic.KineticTracker.class).detach();\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (sprite != null) {\n\t\t\tsprite.showStatus(HP > HT / 2 ?\n\t\t\t\t\t\t\tCharSprite.WARNING :\n\t\t\t\t\t\t\tCharSprite.NEGATIVE,\n\t\t\t\t\tInteger.toString(dmg + shielded));\n\t\t}\n\n\t\tif (HP < 0) HP = 0;\n\n\t\tif (!isAlive()) {\n\t\t\tdie( src );\n\t\t} else if (HP == 0 && buff(DeathMark.DeathMarkTracker.class) != null){\n\t\t\tDeathMark.processFearTheReaper(this);\n\t\t}\n\t}\n\t\n\tpublic void destroy() {\n\t\tHP = 0;\n\t\tActor.remove( this );\n\n\t\tfor (Char ch : Actor.chars().toArray(new Char[0])){\n\t\t\tif (ch.buff(Charm.class) != null && ch.buff(Charm.class).object == id()){\n\t\t\t\tch.buff(Charm.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Dread.class) != null && ch.buff(Dread.class).object == id()){\n\t\t\t\tch.buff(Dread.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Terror.class) != null && ch.buff(Terror.class).object == id()){\n\t\t\t\tch.buff(Terror.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(SnipersMark.class) != null && ch.buff(SnipersMark.class).object == id()){\n\t\t\t\tch.buff(SnipersMark.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Talent.FollowupStrikeTracker.class) != null\n\t\t\t\t\t&& ch.buff(Talent.FollowupStrikeTracker.class).object == id()){\n\t\t\t\tch.buff(Talent.FollowupStrikeTracker.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Talent.DeadlyFollowupTracker.class) != null\n\t\t\t\t\t&& ch.buff(Talent.DeadlyFollowupTracker.class).object == id()){\n\t\t\t\tch.buff(Talent.DeadlyFollowupTracker.class).detach();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void die( Object src ) {\n\t\tdestroy();\n\t\tif (src != Chasm.class) sprite.die();\n\t}\n\n\t//we cache this info to prevent having to call buff(...) in isAlive.\n\t//This is relevant because we call isAlive during drawing, which has both performance\n\t//and thread coordination implications\n\tpublic boolean deathMarked = false;\n\t\n\tpublic boolean isAlive() {\n\t\treturn HP > 0 || deathMarked;\n\t}\n\n\tpublic boolean isActive() {\n\t\treturn isAlive();\n\t}\n\n\t@Override\n\tprotected void spendConstant(float time) {\n\t\tTimekeepersHourglass.timeFreeze freeze = buff(TimekeepersHourglass.timeFreeze.class);\n\t\tif (freeze != null) {\n\t\t\tfreeze.processTime(time);\n\t\t\treturn;\n\t\t}\n\n\t\tSwiftthistle.TimeBubble bubble = buff(Swiftthistle.TimeBubble.class);\n\t\tif (bubble != null){\n\t\t\tbubble.processTime(time);\n\t\t\treturn;\n\t\t}\n\n\t\tsuper.spendConstant(time);\n\t}\n\n\t@Override\n\tprotected void spend( float time ) {\n\n\t\tfloat timeScale = 1f;\n\t\tif (buff( Slow.class ) != null) {\n\t\t\ttimeScale *= 0.5f;\n\t\t\t//slowed and chilled do not stack\n\t\t} else if (buff( Chill.class ) != null) {\n\t\t\ttimeScale *= buff( Chill.class ).speedFactor();\n\t\t}\n\t\tif (buff( Speed.class ) != null) {\n\t\t\ttimeScale *= 2.0f;\n\t\t}\n\t\t\n\t\tsuper.spend( time / timeScale );\n\t}\n\t\n\tpublic synchronized LinkedHashSet<Buff> buffs() {\n\t\treturn new LinkedHashSet<>(buffs);\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\t//returns all buffs assignable from the given buff class\n\tpublic synchronized <T extends Buff> HashSet<T> buffs( Class<T> c ) {\n\t\tHashSet<T> filtered = new HashSet<>();\n\t\tfor (Buff b : buffs) {\n\t\t\tif (c.isInstance( b )) {\n\t\t\t\tfiltered.add( (T)b );\n\t\t\t}\n\t\t}\n\t\treturn filtered;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t//returns an instance of the specific buff class, if it exists. Not just assignable\n\tpublic synchronized <T extends Buff> T buff( Class<T> c ) {\n\t\tfor (Buff b : buffs) {\n\t\t\tif (b.getClass() == c) {\n\t\t\t\treturn (T)b;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic synchronized boolean isCharmedBy( Char ch ) {\n\t\tint chID = ch.id();\n\t\tfor (Buff b : buffs) {\n\t\t\tif (b instanceof Charm && ((Charm)b).object == chID) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic synchronized boolean add( Buff buff ) {\n\n\t\tif (buff(PotionOfCleansing.Cleanse.class) != null) { //cleansing buff\n\t\t\tif (buff.type == Buff.buffType.NEGATIVE\n\t\t\t\t\t&& !(buff instanceof AllyBuff)\n\t\t\t\t\t&& !(buff instanceof LostInventory)){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tif (sprite != null && buff(Challenge.SpectatorFreeze.class) != null){\n\t\t\treturn false; //can't add buffs while frozen and game is loaded\n\t\t}\n\n\t\tbuffs.add( buff );\n\t\tif (Actor.chars().contains(this)) Actor.add( buff );\n\n\t\tif (sprite != null && buff.announced) {\n\t\t\tswitch (buff.type) {\n\t\t\t\tcase POSITIVE:\n\t\t\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NEGATIVE:\n\t\t\t\t\tsprite.showStatus(CharSprite.NEGATIVE, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NEUTRAL:\n\t\t\t\tdefault:\n\t\t\t\t\tsprite.showStatus(CharSprite.NEUTRAL, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\n\t}\n\t\n\tpublic synchronized boolean remove( Buff buff ) {\n\t\t\n\t\tbuffs.remove( buff );\n\t\tActor.remove( buff );\n\n\t\treturn true;\n\t}\n\t\n\tpublic synchronized void remove( Class<? extends Buff> buffClass ) {\n\t\tfor (Buff buff : buffs( buffClass )) {\n\t\t\tremove( buff );\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected synchronized void onRemove() {\n\t\tfor (Buff buff : buffs.toArray(new Buff[buffs.size()])) {\n\t\t\tbuff.detach();\n\t\t}\n\t}\n\t\n\tpublic synchronized void updateSpriteState() {\n\t\tfor (Buff buff:buffs) {\n\t\t\tbuff.fx( true );\n\t\t}\n\t}\n\t\n\tpublic float stealth() {\n\t\treturn 0;\n\t}\n\n\tpublic final void move( int step ) {\n\t\tmove( step, true );\n\t}\n\n\t//travelling may be false when a character is moving instantaneously, such as via teleportation\n\tpublic void move( int step, boolean travelling ) {\n\n\t\tif (travelling && Dungeon.level.adjacent( step, pos ) && buff( Vertigo.class ) != null) {\n\t\t\tsprite.interruptMotion();\n\t\t\tint newPos = pos + PathFinder.NEIGHBOURS8[Random.Int( 8 )];\n\t\t\tif (!(Dungeon.level.passable[newPos] || Dungeon.level.avoid[newPos])\n\t\t\t\t\t|| (properties().contains(Property.LARGE) && !Dungeon.level.openSpace[newPos])\n\t\t\t\t\t|| Actor.findChar( newPos ) != null)\n\t\t\t\treturn;\n\t\t\telse {\n\t\t\t\tsprite.move(pos, newPos);\n\t\t\t\tstep = newPos;\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.level.map[pos] == Terrain.OPEN_DOOR) {\n\t\t\tDoor.leave( pos );\n\t\t}\n\n\t\tpos = step;\n\t\t\n\t\tif (this != Dungeon.hero) {\n\t\t\tsprite.visible = Dungeon.level.heroFOV[pos];\n\t\t}\n\t\t\n\t\tDungeon.level.occupyCell(this );\n\t}\n\t\n\tpublic int distance( Char other ) {\n\t\treturn Dungeon.level.distance( pos, other.pos );\n\t}\n\n\tpublic boolean[] modifyPassable( boolean[] passable){\n\t\t//do nothing by default, but some chars can pass over terrain that others can't\n\t\treturn passable;\n\t}\n\t\n\tpublic void onMotionComplete() {\n\t\t//Does nothing by default\n\t\t//The main actor thread already accounts for motion,\n\t\t// so calling next() here isn't necessary (see Actor.process)\n\t}\n\t\n\tpublic void onAttackComplete() {\n\t\tnext();\n\t}\n\t\n\tpublic void onOperateComplete() {\n\t\tnext();\n\t}\n\t\n\tprotected final HashSet<Class> resistances = new HashSet<>();\n\t\n\t//returns percent effectiveness after resistances\n\t//TODO currently resistances reduce effectiveness by a static 50%, and do not stack.\n\tpublic float resist( Class effect ){\n\t\tHashSet<Class> resists = new HashSet<>(resistances);\n\t\tfor (Property p : properties()){\n\t\t\tresists.addAll(p.resistances());\n\t\t}\n\t\tfor (Buff b : buffs()){\n\t\t\tresists.addAll(b.resistances());\n\t\t}\n\t\t\n\t\tfloat result = 1f;\n\t\tfor (Class c : resists){\n\t\t\tif (c.isAssignableFrom(effect)){\n\t\t\t\tresult *= 0.5f;\n\t\t\t}\n\t\t}\n\t\treturn result * RingOfElements.resist(this, effect);\n\t}\n\t\n\tprotected final HashSet<Class> immunities = new HashSet<>();\n\t\n\tpublic boolean isImmune(Class effect ){\n\t\tHashSet<Class> immunes = new HashSet<>(immunities);\n\t\tfor (Property p : properties()){\n\t\t\timmunes.addAll(p.immunities());\n\t\t}\n\t\tfor (Buff b : buffs()){\n\t\t\timmunes.addAll(b.immunities());\n\t\t}\n\t\t\n\t\tfor (Class c : immunes){\n\t\t\tif (c.isAssignableFrom(effect)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t//similar to isImmune, but only factors in damage.\n\t//Is used in AI decision-making\n\tpublic boolean isInvulnerable( Class effect ){\n\t\treturn buff(Challenge.SpectatorFreeze.class) != null;\n\t}\n\n\tprotected HashSet<Property> properties = new HashSet<>();\n\n\tpublic HashSet<Property> properties() {\n\t\tHashSet<Property> props = new HashSet<>(properties);\n\t\t//TODO any more of these and we should make it a property of the buff, like with resistances/immunities\n\t\tif (buff(ChampionEnemy.Giant.class) != null) {\n\t\t\tprops.add(Property.LARGE);\n\t\t}\n\t\treturn props;\n\t}\n\n\tpublic enum Property{\n\t\tBOSS ( new HashSet<Class>( Arrays.asList(Grim.class, GrimTrap.class, ScrollOfRetribution.class, ScrollOfPsionicBlast.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(AllyBuff.class, Dread.class) )),\n\t\tMINIBOSS ( new HashSet<Class>(),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(AllyBuff.class, Dread.class) )),\n\t\tBOSS_MINION,\n\t\tUNDEAD,\n\t\tDEMONIC,\n\t\tINORGANIC ( new HashSet<Class>(),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Bleeding.class, ToxicGas.class, Poison.class) )),\n\t\tFIERY ( new HashSet<Class>( Arrays.asList(WandOfFireblast.class, Elemental.FireElemental.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Burning.class, Blazing.class))),\n\t\tICY ( new HashSet<Class>( Arrays.asList(WandOfFrost.class, Elemental.FrostElemental.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Frost.class, Chill.class))),\n\t\tACIDIC ( new HashSet<Class>( Arrays.asList(Corrosion.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Ooze.class))),\n\t\tELECTRIC ( new HashSet<Class>( Arrays.asList(WandOfLightning.class, Shocking.class, Potential.class, Electricity.class, ShockingDart.class, Elemental.ShockElemental.class )),\n\t\t\t\tnew HashSet<Class>()),\n\t\tLARGE,\n\t\tIMMOVABLE;\n\t\t\n\t\tprivate HashSet<Class> resistances;\n\t\tprivate HashSet<Class> immunities;\n\t\t\n\t\tProperty(){\n\t\t\tthis(new HashSet<Class>(), new HashSet<Class>());\n\t\t}\n\t\t\n\t\tProperty( HashSet<Class> resistances, HashSet<Class> immunities){\n\t\t\tthis.resistances = resistances;\n\t\t\tthis.immunities = immunities;\n\t\t}\n\t\t\n\t\tpublic HashSet<Class> resistances(){\n\t\t\treturn new HashSet<>(resistances);\n\t\t}\n\t\t\n\t\tpublic HashSet<Class> immunities(){\n\t\t\treturn new HashSet<>(immunities);\n\t\t}\n\n\t}\n\n\tpublic static boolean hasProp( Char ch, Property p){\n\t\treturn (ch != null && ch.properties().contains(p));\n\t}\n\n\tpublic void heal(int amount) {\n\t\tamount = Math.min( amount, this.HT - this.HP );\n\t\tif (amount > 0 && this.isAlive()) {\n\t\t\tthis.HP += amount;\n\t\t\tthis.sprite.emitter().start( Speck.factory( Speck.HEALING ), 0.4f, 1 );\n\t\t\tthis.sprite.showStatus( CharSprite.POSITIVE, Integer.toString( amount ) );\n\t\t}\n\t}\n}" }, { "identifier": "Amok", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Amok.java", "snippet": "public class Amok extends FlavourBuff {\n\n\t{\n\t\ttype = buffType.NEGATIVE;\n\t\tannounced = true;\n\t}\n\t\n\t@Override\n\tpublic int icon() {\n\t\treturn BuffIndicator.AMOK;\n\t}\n\n\t@Override\n\tpublic void detach() {\n\t\tsuper.detach();\n\t\tif (target instanceof Mob && target.isAlive()) {\n\t\t\t((Mob) target).aggro(null);\n\t\t}\n\t}\n}" }, { "identifier": "Blindness", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Blindness.java", "snippet": "public class Blindness extends FlavourBuff {\n\n\tpublic static final float DURATION = 10f;\n\n\t{\n\t\ttype = buffType.NEGATIVE;\n\t\tannounced = true;\n\t}\n\t\n\t@Override\n\tpublic void detach() {\n\t\tsuper.detach();\n\t\tDungeon.observe();\n\t}\n\t\n\t@Override\n\tpublic int icon() {\n\t\treturn BuffIndicator.BLINDNESS;\n\t}\n\n\t@Override\n\tpublic float iconFadePercent() {\n\t\treturn Math.max(0, (DURATION - visualcooldown()) / DURATION);\n\t}\n\n}" }, { "identifier": "Buff", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Buff.java", "snippet": "public class Buff extends Actor {\n\t\n\tpublic Char target;\n\n\t{\n\t\tactPriority = BUFF_PRIO; //low priority, towards the end of a turn\n\t}\n\n\t//determines how the buff is announced when it is shown.\n\tpublic enum buffType {POSITIVE, NEGATIVE, NEUTRAL}\n\tpublic buffType type = buffType.NEUTRAL;\n\t\n\t//whether or not the buff announces its name\n\tpublic boolean announced = false;\n\n\t//whether a buff should persist through revive effects for the hero\n\tpublic boolean revivePersists = false;\n\t\n\tprotected HashSet<Class> resistances = new HashSet<>();\n\t\n\tpublic HashSet<Class> resistances() {\n\t\treturn new HashSet<>(resistances);\n\t}\n\t\n\tprotected HashSet<Class> immunities = new HashSet<>();\n\t\n\tpublic HashSet<Class> immunities() {\n\t\treturn new HashSet<>(immunities);\n\t}\n\t\n\tpublic boolean attachTo( Char target ) {\n\n\t\tif (target.isImmune( getClass() )) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tthis.target = target;\n\n\t\tif (target.add( this )){\n\t\t\tif (target.sprite != null) fx( true );\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.target = null;\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic void detach() {\n\t\tif (target.remove( this ) && target.sprite != null) fx( false );\n\t}\n\t\n\t@Override\n\tpublic boolean act() {\n\t\tdiactivate();\n\t\treturn true;\n\t}\n\t\n\tpublic int icon() {\n\t\treturn BuffIndicator.NONE;\n\t}\n\n\t//some buffs may want to tint the base texture color of their icon\n\tpublic void tintIcon( Image icon ){\n\t\t//do nothing by default\n\t}\n\n\t//percent (0-1) to fade out out the buff icon, usually if buff is expiring\n\tpublic float iconFadePercent(){\n\t\treturn 0;\n\t}\n\n\t//text to display on large buff icons in the desktop UI\n\tpublic String iconTextDisplay(){\n\t\treturn \"\";\n\t}\n\n\t//visual effect usually attached to the sprite of the character the buff is attacked to\n\tpublic void fx(boolean on) {\n\t\t//do nothing by default\n\t}\n\n\tpublic String heroMessage(){\n\t\tString msg = Messages.get(this, \"heromsg\");\n\t\tif (msg.isEmpty()) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn msg;\n\t\t}\n\t}\n\n\tpublic String name() {\n\t\treturn Messages.get(this, \"name\");\n\t}\n\n\tpublic String desc(){\n\t\treturn Messages.get(this, \"desc\");\n\t}\n\n\t//to handle the common case of showing how many turns are remaining in a buff description.\n\tprotected String dispTurns(float input){\n\t\treturn Messages.decimalFormat(\"#.##\", input);\n\t}\n\n\t//buffs act after the hero, so it is often useful to use cooldown+1 when display buff time remaining\n\tpublic float visualcooldown(){\n\t\treturn cooldown()+1f;\n\t}\n\n\t//creates a fresh instance of the buff and attaches that, this allows duplication.\n\tpublic static<T extends Buff> T append( Char target, Class<T> buffClass ) {\n\t\tT buff = Reflection.newInstance(buffClass);\n\t\tbuff.attachTo( target );\n\t\treturn buff;\n\t}\n\n\tpublic static<T extends FlavourBuff> T append( Char target, Class<T> buffClass, float duration ) {\n\t\tT buff = append( target, buffClass );\n\t\tbuff.spend( duration * target.resist(buffClass) );\n\t\treturn buff;\n\t}\n\n\t//same as append, but prevents duplication.\n\tpublic static<T extends Buff> T affect( Char target, Class<T> buffClass ) {\n\t\tT buff = target.buff( buffClass );\n\t\tif (buff != null) {\n\t\t\treturn buff;\n\t\t} else {\n\t\t\treturn append( target, buffClass );\n\t\t}\n\t}\n\t\n\tpublic static<T extends FlavourBuff> T affect( Char target, Class<T> buffClass, float duration ) {\n\t\tT buff = affect( target, buffClass );\n\t\tbuff.spend( duration * target.resist(buffClass) );\n\t\treturn buff;\n\t}\n\n\t//postpones an already active buff, or creates & attaches a new buff and delays that.\n\tpublic static<T extends FlavourBuff> T prolong( Char target, Class<T> buffClass, float duration ) {\n\t\tT buff = affect( target, buffClass );\n\t\tbuff.postpone( duration * target.resist(buffClass) );\n\t\treturn buff;\n\t}\n\n\tpublic static<T extends CounterBuff> T count( Char target, Class<T> buffclass, float count ) {\n\t\tT buff = affect( target, buffclass );\n\t\tbuff.countUp( count );\n\t\treturn buff;\n\t}\n\t\n\tpublic static void detach( Char target, Class<? extends Buff> cl ) {\n\t\tfor ( Buff b : target.buffs( cl )){\n\t\t\tb.detach();\n\t\t}\n\t}\n}" }, { "identifier": "Cripple", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Cripple.java", "snippet": "public class Cripple extends FlavourBuff {\n\n\tpublic static final float DURATION\t= 10f;\n\n\t{\n\t\ttype = buffType.NEGATIVE;\n\t\tannounced = true;\n\t}\n\t\n\t@Override\n\tpublic int icon() {\n\t\treturn BuffIndicator.CRIPPLE;\n\t}\n\n\t@Override\n\tpublic float iconFadePercent() {\n\t\treturn Math.max(0, (DURATION - visualcooldown()) / DURATION);\n\t}\n}" }, { "identifier": "Dread", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Dread.java", "snippet": "public class Dread extends Buff {\n\n\tprotected int left = (int)DURATION;\n\tpublic int object = 0;\n\n\tpublic static final float DURATION = 20f;\n\n\t{\n\t\ttype = buffType.NEGATIVE;\n\t\tannounced = true;\n\t}\n\n\t//dread overrides terror\n\t@Override\n\tpublic boolean attachTo(Char target) {\n\t\tif (super.attachTo(target)){\n\t\t\tBuff.detach( target, Terror.class );\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t{\n\t\timmunities.add(Terror.class);\n\t}\n\n\t@Override\n\tpublic boolean act() {\n\n\t\tif (!Dungeon.level.heroFOV[target.pos]\n\t\t\t\t&& Dungeon.level.distance(target.pos, Dungeon.hero.pos) >= 6) {\n\t\t\tif (target instanceof Mob){\n\t\t\t\t((Mob) target).EXP /= 2;\n\t\t\t}\n\t\t\ttarget.destroy();\n\t\t\ttarget.sprite.killAndErase();\n\t\t\tDungeon.level.mobs.remove(target);\n\t\t} else {\n\t\t\tleft--;\n\t\t\tif (left <= 0){\n\t\t\t\tdetach();\n\t\t\t}\n\t\t}\n\n\t\tspend(TICK);\n\t\treturn true;\n\t}\n\n\tprivate static final String LEFT\t= \"left\";\n\tprivate static final String OBJECT = \"object\";\n\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tsuper.storeInBundle(bundle);\n\t\tbundle.put(LEFT, left);\n\t\tbundle.put(OBJECT, object);\n\t}\n\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tsuper.restoreFromBundle( bundle );\n\t\tobject = bundle.getInt( OBJECT );\n\t\tleft = bundle.getInt( LEFT );\n\t}\n\n\t@Override\n\tpublic int icon() {\n\t\treturn BuffIndicator.TERROR;\n\t}\n\n\t@Override\n\tpublic float iconFadePercent() {\n\t\treturn Math.max(0, (DURATION - left) / DURATION);\n\t}\n\n\t@Override\n\tpublic String iconTextDisplay() {\n\t\treturn Integer.toString(left);\n\t}\n\n\t@Override\n\tpublic void tintIcon(Image icon) {\n\t\ticon.hardlight(1, 0, 0);\n\t}\n\n\t@Override\n\tpublic String desc() {\n\t\treturn Messages.get(this, \"desc\", left);\n\t}\n\n\tpublic void recover() {\n\t\tleft -= 5;\n\t\tif (left <= 0){\n\t\t\tdetach();\n\t\t}\n\t}\n\n}" }, { "identifier": "Haste", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Haste.java", "snippet": "public class Haste extends FlavourBuff {\n\t\n\t{\n\t\ttype = buffType.POSITIVE;\n\t}\n\t\n\tpublic static final float DURATION\t= 20f;\n\t\n\t@Override\n\tpublic int icon() {\n\t\treturn BuffIndicator.HASTE;\n\t}\n\n\t@Override\n\tpublic void tintIcon(Image icon) {\n\t\ticon.hardlight(1f, 0.8f, 0f);\n\t}\n\n\t@Override\n\tpublic float iconFadePercent() {\n\t\treturn Math.max(0, (DURATION - visualcooldown()) / DURATION);\n\t}\n\n}" }, { "identifier": "Invisibility", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Invisibility.java", "snippet": "public class Invisibility extends FlavourBuff {\n\n\tpublic static final float DURATION\t= 20f;\n\n\t{\n\t\ttype = buffType.POSITIVE;\n\t\tannounced = true;\n\t}\n\t\n\t@Override\n\tpublic boolean attachTo( Char target ) {\n\t\tif (super.attachTo( target )) {\n\t\t\ttarget.invisible++;\n\t\t\tif (target instanceof Hero && ((Hero) target).subClass == HeroSubClass.ASSASSIN){\n\t\t\t\tBuff.affect(target, Preparation.class);\n\t\t\t}\n\t\t\tif (target instanceof Hero && ((Hero) target).hasTalent(Talent.PROTECTIVE_SHADOWS)){\n\t\t\t\tBuff.affect(target, Talent.ProtectiveShadowsTracker.class);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void detach() {\n\t\tif (target.invisible > 0)\n\t\t\ttarget.invisible--;\n\t\tsuper.detach();\n\t}\n\t\n\t@Override\n\tpublic int icon() {\n\t\treturn BuffIndicator.INVISIBLE;\n\t}\n\n\t@Override\n\tpublic float iconFadePercent() {\n\t\treturn Math.max(0, (DURATION - visualcooldown()) / DURATION);\n\t}\n\n\t@Override\n\tpublic void fx(boolean on) {\n\t\tif (on) target.sprite.add( CharSprite.State.INVISIBLE );\n\t\telse if (target.invisible == 0) target.sprite.remove( CharSprite.State.INVISIBLE );\n\t}\n\n\tpublic static void dispel() {\n\t\tif (Dungeon.hero == null) return;\n\n\t\tdispel(Dungeon.hero);\n\t}\n\n\tpublic static void dispel(Char ch){\n\n\t\tfor ( Buff invis : ch.buffs( Invisibility.class )){\n\t\t\tinvis.detach();\n\t\t}\n\t\tCloakOfShadows.cloakStealth cloakBuff = ch.buff( CloakOfShadows.cloakStealth.class );\n\t\tif (cloakBuff != null) {\n\t\t\tcloakBuff.dispel();\n\t\t}\n\n\t\t//these aren't forms of invisibility, but do dispel at the same time as it.\n\t\tTimekeepersHourglass.timeFreeze timeFreeze = ch.buff( TimekeepersHourglass.timeFreeze.class );\n\t\tif (timeFreeze != null) {\n\t\t\ttimeFreeze.detach();\n\t\t}\n\n\t\tPreparation prep = ch.buff( Preparation.class );\n\t\tif (prep != null){\n\t\t\tprep.detach();\n\t\t}\n\n\t\tSwiftthistle.TimeBubble bubble = ch.buff( Swiftthistle.TimeBubble.class );\n\t\tif (bubble != null){\n\t\t\tbubble.detach();\n\t\t}\n\t}\n}" }, { "identifier": "Paralysis", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Paralysis.java", "snippet": "public class Paralysis extends FlavourBuff {\n\n\tpublic static final float DURATION\t= 10f;\n\n\t{\n\t\ttype = buffType.NEGATIVE;\n\t\tannounced = true;\n\t}\n\t\n\t@Override\n\tpublic boolean attachTo( Char target ) {\n\t\tif (super.attachTo( target )) {\n\t\t\ttarget.paralysed++;\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic void processDamage( int damage ){\n\t\tif (target == null) return;\n\t\tParalysisResist resist = target.buff(ParalysisResist.class);\n\t\tif (resist == null){\n\t\t\tresist = Buff.affect(target, ParalysisResist.class);\n\t\t}\n\t\tresist.damage += damage;\n\t\tif (Random.NormalIntRange(0, resist.damage) >= Random.NormalIntRange(0, target.HP)){\n\t\t\tif (Dungeon.level.heroFOV[target.pos]) {\n\t\t\t\ttarget.sprite.showStatus(CharSprite.NEUTRAL, Messages.get(this, \"out\"));\n\t\t\t}\n\t\t\tdetach();\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void detach() {\n\t\tsuper.detach();\n\t\tif (target.paralysed > 0)\n\t\t\ttarget.paralysed--;\n\t}\n\t\n\t@Override\n\tpublic int icon() {\n\t\treturn BuffIndicator.PARALYSIS;\n\t}\n\n\t@Override\n\tpublic float iconFadePercent() {\n\t\treturn Math.max(0, (DURATION - visualcooldown()) / DURATION);\n\t}\n\n\t@Override\n\tpublic void fx(boolean on) {\n\t\tif (on) target.sprite.add(CharSprite.State.PARALYSED);\n\t\telse if (target.paralysed <= 1) target.sprite.remove(CharSprite.State.PARALYSED);\n\t}\n\n\tpublic static class ParalysisResist extends Buff {\n\t\t\n\t\t{\n\t\t\ttype = buffType.POSITIVE;\n\t\t}\n\t\t\n\t\tprivate int damage;\n\t\t\n\t\t@Override\n\t\tpublic boolean act() {\n\t\t\tif (target.buff(Paralysis.class) == null) {\n\t\t\t\tdamage -= Math.ceil(damage / 10f);\n\t\t\t\tif (damage >= 0) detach();\n\t\t\t}\n\t\t\tspend(TICK);\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\tprivate static final String DAMAGE = \"damage\";\n\t\t\n\t\t@Override\n\t\tpublic void storeInBundle(Bundle bundle) {\n\t\t\tsuper.storeInBundle(bundle);\n\t\t\tdamage = bundle.getInt(DAMAGE);\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void restoreFromBundle(Bundle bundle) {\n\t\t\tsuper.restoreFromBundle(bundle);\n\t\t\tbundle.put( DAMAGE, damage );\n\t\t}\n\t}\n}" }, { "identifier": "Sleep", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Sleep.java", "snippet": "public class Sleep extends FlavourBuff {\n\n\t@Override\n\tpublic void fx(boolean on) {\n\t\tif (on) target.sprite.idle();\n\t}\n\n\tpublic static final float SWS\t= 1.5f;\n\t\n}" }, { "identifier": "Terror", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Terror.java", "snippet": "public class Terror extends FlavourBuff {\n\n\tpublic int object = 0;\n\n\tprivate static final String OBJECT = \"object\";\n\n\tpublic static final float DURATION = 20f;\n\n\t{\n\t\ttype = buffType.NEGATIVE;\n\t\tannounced = true;\n\t}\n\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tsuper.storeInBundle(bundle);\n\t\tbundle.put(OBJECT, object);\n\t}\n\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tsuper.restoreFromBundle( bundle );\n\t\tobject = bundle.getInt( OBJECT );\n\t}\n\n\t@Override\n\tpublic int icon() {\n\t\treturn BuffIndicator.TERROR;\n\t}\n\n\t@Override\n\tpublic float iconFadePercent() {\n\t\treturn Math.max(0, (DURATION - visualcooldown()) / DURATION);\n\t}\n\n\tpublic boolean ignoreNextHit = false;\n\n\tpublic void recover() {\n\t\tif (ignoreNextHit){\n\t\t\tignoreNextHit = false;\n\t\t\treturn;\n\t\t}\n\t\tspend(-5f);\n\t\tif (cooldown() <= 0){\n\t\t\tdetach();\n\t\t}\n\t}\n}" }, { "identifier": "Vertigo", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Vertigo.java", "snippet": "public class Vertigo extends FlavourBuff {\n\n\tpublic static final float DURATION\t= 10f;\n\n\t{\n\t\ttype = buffType.NEGATIVE;\n\t\tannounced = true;\n\t}\n\n\t@Override\n\tpublic int icon() {\n\t\treturn BuffIndicator.VERTIGO;\n\t}\n\n\t@Override\n\tpublic float iconFadePercent() {\n\t\treturn Math.max(0, (DURATION - visualcooldown()) / DURATION);\n\t}\n\n}" }, { "identifier": "Blacksmith", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/mobs/npcs/Blacksmith.java", "snippet": "public class Blacksmith extends NPC {\n\t\n\t{\n\t\tspriteClass = BlacksmithSprite.class;\n\n\t\tproperties.add(Property.IMMOVABLE);\n\t}\n\t\n\t@Override\n\tprotected boolean act() {\n\t\tif (Dungeon.hero.buff(AscensionChallenge.class) != null){\n\t\t\tdie(null);\n\t\t\tNotes.remove( Notes.Landmark.TROLL );\n\t\t\treturn true;\n\t\t}\n\t\tif (Dungeon.level.visited[pos]){\n\t\t\tNotes.add( Notes.Landmark.TROLL );\n\t\t}\n\t\treturn super.act();\n\t}\n\t\n\t@Override\n\tpublic boolean interact(Char c) {\n\t\t\n\t\tsprite.turnTo( pos, c.pos );\n\n\t\tif (c != Dungeon.hero){\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\tif (!Quest.given) {\n\n\t\t\tString msg1 = \"\";\n\t\t\tString msg2 = \"\";\n\n\t\t\tif (Quest.type == Quest.OLD){\n\t\t\t\t//pre-v2.2.0 saves\n\t\t\t\tmsg1 = Quest.alternative ? Messages.get(Blacksmith.this, \"blood_1\") : Messages.get(Blacksmith.this, \"gold_1\");\n\t\t\t} else {\n\n\t\t\t\tswitch (Dungeon.hero.heroClass){\n\t\t\t\t\tcase WARRIOR: msg1 += Messages.get(Blacksmith.this, \"intro_quest_warrior\"); break;\n\t\t\t\t\tcase MAGE: msg1 += Messages.get(Blacksmith.this, \"intro_quest_mage\"); break;\n\t\t\t\t\tcase ROGUE: msg1 += Messages.get(Blacksmith.this, \"intro_quest_rogue\"); break;\n\t\t\t\t\tcase HUNTRESS: msg1 += Messages.get(Blacksmith.this, \"intro_quest_huntress\"); break;\n\t\t\t\t\tcase DUELIST: msg1 += Messages.get(Blacksmith.this, \"intro_quest_duelist\"); break;\n\t\t\t\t\t//case CLERIC: msg1 += Messages.get(Blacksmith.this, \"intro_quest_cleric\"); break;\n\t\t\t\t\tcase GUNNER: \tmsg1 += Messages.get(Blacksmith.this, \"intro_quest_gunner\"); break;\n//\t\t\t\t\tcase SAMURAI: msg1 += Messages.get(Blacksmith.this, \"intro_quest_samurai\"); break;\n//\t\t\t\t\tcase PLANTER: msg1 += Messages.get(Blacksmith.this, \"intro_quest_planter\"); break;\n//\t\t\t\t\tcase KNIGHT: \tmsg1 += Messages.get(Blacksmith.this, \"intro_quest_knight\"); break;\n//\t\t\t\t\tcase NURSE: \tmsg1 += Messages.get(Blacksmith.this, \"intro_quest_nurse\"); break;\n\t\t\t\t}\n\n\t\t\t\tmsg1 += \"\\n\\n\" + Messages.get(Blacksmith.this, \"intro_quest_start\");\n\n\t\t\t\tswitch (Quest.type){\n\t\t\t\t\tcase Quest.CRYSTAL: msg2 += Messages.get(Blacksmith.this, \"intro_quest_crystal\"); break;\n\t\t\t\t\tcase Quest.FUNGI: msg2 += Messages.get(Blacksmith.this, \"intro_quest_fungi\"); break;\n\t\t\t\t\tcase Quest.GNOLL: msg2 += Messages.get(Blacksmith.this, \"intro_quest_gnoll\"); break;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tfinal String msg1Final = msg1;\n\t\t\tfinal String msg2Final = msg2;\n\t\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t\t@Override\n\t\t\t\tpublic void call() {\n\t\t\t\t\tGameScene.show(new WndQuest(Blacksmith.this, msg1Final) {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void hide() {\n\t\t\t\t\t\t\tsuper.hide();\n\n\t\t\t\t\t\t\tQuest.given = true;\n\t\t\t\t\t\t\tQuest.completed = false;\n\t\t\t\t\t\t\tNotes.add( Notes.Landmark.TROLL );\n\t\t\t\t\t\t\tItem pick = Quest.pickaxe != null ? Quest.pickaxe : new Pickaxe();\n\t\t\t\t\t\t\tif (pick.doPickUp( Dungeon.hero )) {\n\t\t\t\t\t\t\t\tGLog.i( Messages.capitalize(Messages.get(Dungeon.hero, \"you_now_have\", pick.name()) ));\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tDungeon.level.drop( pick, Dungeon.hero.pos ).sprite.drop();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tQuest.pickaxe = null;\n\n\t\t\t\t\t\t\tif (msg2Final != \"\"){\n\t\t\t\t\t\t\t\tGameScene.show(new WndQuest(Blacksmith.this, msg2Final));\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\t\t\t\t\t} );\n\t\t\t\t}\n\t\t\t});\n\t\t\t\n\t\t} else if (!Quest.completed) {\n\n\t\t\tif (Quest.type == Quest.OLD) {\n\t\t\t\tif (Quest.alternative) {\n\n\t\t\t\t\tPickaxe pick = Dungeon.hero.belongings.getItem(Pickaxe.class);\n\t\t\t\t\tif (pick == null) {\n\t\t\t\t\t\ttell(Messages.get(this, \"lost_pick\"));\n\t\t\t\t\t} else if (!pick.bloodStained) {\n\t\t\t\t\t\ttell(Messages.get(this, \"blood_2\"));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (pick.isEquipped(Dungeon.hero)) {\n\t\t\t\t\t\t\tboolean wasCursed = pick.cursed;\n\t\t\t\t\t\t\tpick.cursed = false; //so that it can always be removed\n\t\t\t\t\t\t\tpick.doUnequip(Dungeon.hero, false);\n\t\t\t\t\t\t\tpick.cursed = wasCursed;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpick.detach(Dungeon.hero.belongings.backpack);\n\t\t\t\t\t\tQuest.pickaxe = pick;\n\t\t\t\t\t\ttell(Messages.get(this, \"completed\"));\n\n\t\t\t\t\t\tQuest.completed = true;\n\t\t\t\t\t\tStatistics.questScores[2] = 3000;\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\tPickaxe pick = Dungeon.hero.belongings.getItem(Pickaxe.class);\n\t\t\t\t\tDarkGold gold = Dungeon.hero.belongings.getItem(DarkGold.class);\n\t\t\t\t\tif (pick == null) {\n\t\t\t\t\t\ttell(Messages.get(this, \"lost_pick\"));\n\t\t\t\t\t} else if (gold == null || gold.quantity() < 15) {\n\t\t\t\t\t\ttell(Messages.get(this, \"gold_2\"));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (pick.isEquipped(Dungeon.hero)) {\n\t\t\t\t\t\t\tboolean wasCursed = pick.cursed;\n\t\t\t\t\t\t\tpick.cursed = false; //so that it can always be removed\n\t\t\t\t\t\t\tpick.doUnequip(Dungeon.hero, false);\n\t\t\t\t\t\t\tpick.cursed = wasCursed;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpick.detach(Dungeon.hero.belongings.backpack);\n\t\t\t\t\t\tQuest.pickaxe = pick;\n\t\t\t\t\t\tgold.detachAll(Dungeon.hero.belongings.backpack);\n\t\t\t\t\t\ttell(Messages.get(this, \"completed\"));\n\n\t\t\t\t\t\tQuest.completed = true;\n\t\t\t\t\t\tStatistics.questScores[2] = 3000;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t} else {\n\n\t\t\t\ttell(Messages.get(this, \"reminder\"));\n\n\t\t\t}\n\t\t} else if (Quest.type == Quest.OLD && Quest.reforges == 0) {\n\t\t\t\n\t\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t\t@Override\n\t\t\t\tpublic void call() {\n\t\t\t\t\tGameScene.show( new WndBlacksmith.WndReforge( Blacksmith.this, null ) );\n\t\t\t\t}\n\t\t\t});\n\n\t\t} else if (Quest.favor > 0 || Quest.pickaxe != null && Statistics.questScores[2] >= 2500) {\n\n\t\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t\t@Override\n\t\t\t\tpublic void call() {\n\t\t\t\t\t//in case game was closed during smith reward selection\n\t\t\t\t\tif (Quest.smithRewards != null && Quest.smiths > 0){\n\t\t\t\t\t\tGameScene.show( new WndBlacksmith.WndSmith( Blacksmith.this, Dungeon.hero ) );\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGameScene.show(new WndBlacksmith(Blacksmith.this, Dungeon.hero));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t} else {\n\t\t\t\n\t\t\ttell( Messages.get(this, \"get_lost\") );\n\t\t\t\n\t\t}\n\n\t\treturn true;\n\t}\n\t\n\tprivate void tell( String text ) {\n\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t@Override\n\t\t\tpublic void call() {\n\t\t\t\tGameScene.show( new WndQuest( Blacksmith.this, text ) );\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tpublic int defenseSkill( Char enemy ) {\n\t\treturn INFINITE_EVASION;\n\t}\n\t\n\t@Override\n\tpublic void damage( int dmg, Object src ) {\n\t\t//do nothing\n\t}\n\n\t@Override\n\tpublic boolean add( Buff buff ) {\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic boolean reset() {\n\t\treturn true;\n\t}\n\n\tpublic static class Quest {\n\n\t\tprivate static int type = 0;\n\t\tpublic static final int OLD = 0;\n\t\tpublic static final int CRYSTAL = 1;\n\t\tpublic static final int FUNGI = 2;\n\t\tpublic static final int GNOLL = 3;\n\t\t//pre-v2.2.0\n\t\tprivate static boolean alternative; //false for mining gold, true for bat blood\n\n\t\t//quest state information\n\t\tprivate static boolean spawned;\n\t\tprivate static boolean given;\n\t\tprivate static boolean started;\n\t\tprivate static boolean bossBeaten;\n\t\tprivate static boolean completed;\n\n\t\t//reward tracking. Stores remaining favor, the pickaxe, and how many of each reward has been chosen\n\t\tpublic static int favor;\n\t\tpublic static Item pickaxe;\n\t\tpublic static int reforges; //also used by the pre-v2.2.0 version of the quest\n\t\tpublic static int hardens;\n\t\tpublic static int upgrades;\n\t\tpublic static int smiths;\n\n\t\t//pre-generate these so they are consistent between seeds\n\t\tpublic static ArrayList<Item> smithRewards;\n\t\t\n\t\tpublic static void reset() {\n\t\t\ttype = 0;\n\t\t\talternative = false;\n\n\t\t\tspawned\t\t= false;\n\t\t\tgiven\t\t= false;\n\t\t\tstarted = false;\n\t\t\tbossBeaten = false;\n\t\t\tcompleted\t= false;\n\n\t\t\tfavor = 0;\n\t\t\tpickaxe = new Pickaxe().identify();\n\t\t\treforges = 0;\n\t\t\thardens = 0;\n\t\t\tupgrades = 0;\n\t\t\tsmiths = 0;\n\n\t\t\tsmithRewards = null;\n\t\t}\n\t\t\n\t\tprivate static final String NODE\t= \"blacksmith\";\n\n\t\tprivate static final String TYPE \t= \"type\";\n\t\tprivate static final String ALTERNATIVE\t= \"alternative\";\n\n\t\tprivate static final String SPAWNED\t\t= \"spawned\";\n\t\tprivate static final String GIVEN\t\t= \"given\";\n\t\tprivate static final String STARTED\t\t= \"started\";\n\t\tprivate static final String BOSS_BEATEN\t= \"boss_beaten\";\n\t\tprivate static final String COMPLETED\t= \"completed\";\n\n\t\tprivate static final String FAVOR\t = \"favor\";\n\t\tprivate static final String PICKAXE\t = \"pickaxe\";\n\t\tprivate static final String REFORGES\t= \"reforges\";\n\t\tprivate static final String HARDENS\t = \"hardens\";\n\t\tprivate static final String UPGRADES\t= \"upgrades\";\n\t\tprivate static final String SMITHS\t = \"smiths\";\n\t\tprivate static final String SMITH_REWARDS = \"smith_rewards\";\n\t\t\n\t\tpublic static void storeInBundle( Bundle bundle ) {\n\t\t\t\n\t\t\tBundle node = new Bundle();\n\t\t\t\n\t\t\tnode.put( SPAWNED, spawned );\n\t\t\t\n\t\t\tif (spawned) {\n\t\t\t\tnode.put( TYPE, type );\n\t\t\t\tnode.put( ALTERNATIVE, alternative );\n\n\t\t\t\tnode.put( GIVEN, given );\n\t\t\t\tnode.put( STARTED, started );\n\t\t\t\tnode.put( BOSS_BEATEN, bossBeaten );\n\t\t\t\tnode.put( COMPLETED, completed );\n\n\t\t\t\tnode.put( FAVOR, favor );\n\t\t\t\tif (pickaxe != null) node.put( PICKAXE, pickaxe );\n\t\t\t\tnode.put( REFORGES, reforges );\n\t\t\t\tnode.put( HARDENS, hardens );\n\t\t\t\tnode.put( UPGRADES, upgrades );\n\t\t\t\tnode.put( SMITHS, smiths );\n\n\t\t\t\tif (smithRewards != null) node.put( SMITH_REWARDS, smithRewards );\n\t\t\t}\n\t\t\t\n\t\t\tbundle.put( NODE, node );\n\t\t}\n\t\t\n\t\tpublic static void restoreFromBundle( Bundle bundle ) {\n\n\t\t\tBundle node = bundle.getBundle( NODE );\n\t\t\t\n\t\t\tif (!node.isNull() && (spawned = node.getBoolean( SPAWNED ))) {\n\t\t\t\ttype = node.getInt(TYPE);\n\t\t\t\talternative\t= node.getBoolean( ALTERNATIVE );\n\n\t\t\t\tgiven = node.getBoolean( GIVEN );\n\t\t\t\tstarted = node.getBoolean( STARTED );\n\t\t\t\tbossBeaten = node.getBoolean( BOSS_BEATEN );\n\t\t\t\tcompleted = node.getBoolean( COMPLETED );\n\n\t\t\t\tfavor = node.getInt( FAVOR );\n\t\t\t\tif (node.contains(PICKAXE)) {\n\t\t\t\t\tpickaxe = (Item) node.get(PICKAXE);\n\t\t\t\t} else {\n\t\t\t\t\tpickaxe = null;\n\t\t\t\t}\n\t\t\t\tif (node.contains(\"reforged\")){\n\t\t\t\t\t//pre-v2.2.0 saves\n\t\t\t\t\treforges = node.getBoolean( \"reforged\" ) ? 1 : 0;\n\t\t\t\t} else {\n\t\t\t\t\treforges = node.getInt( REFORGES );\n\t\t\t\t}\n\t\t\t\thardens = node.getInt( HARDENS );\n\t\t\t\tupgrades = node.getInt( UPGRADES );\n\t\t\t\tsmiths = node.getInt( SMITHS );\n\n\t\t\t\tif (node.contains( SMITH_REWARDS )){\n\t\t\t\t\tsmithRewards = new ArrayList<>((Collection<Item>) ((Collection<?>) node.getCollection( SMITH_REWARDS )));\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\treset();\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static ArrayList<Room> spawn( ArrayList<Room> rooms ) {\n\t\t\tif (!spawned && Dungeon.depth > 11 && Random.Int( 15 - Dungeon.depth ) == 0) {\n\t\t\t\t\n\t\t\t\trooms.add(new BlacksmithRoom());\n\t\t\t\tspawned = true;\n\n\t\t\t\t//currently only the crystal quest is ready to play\n\t\t\t\t//we still roll for quest type however, to ensure seed consistency\n\t\t\t\ttype = 1+Random.Int(1);\n\t\t\t\talternative = false;\n\t\t\t\t\n\t\t\t\tgiven = false;\n\t\t\t\tgenerateRewards( true );\n\t\t\t\t\n\t\t\t}\n\t\t\treturn rooms;\n\t\t}\n\n\t\tpublic static void generateRewards( boolean useDecks ){\n\t\t\tsmithRewards = new ArrayList<>();\n\t\t\tsmithRewards.add(Generator.randomWeapon(3, useDecks));\n\t\t\tsmithRewards.add(Generator.randomWeapon(3, useDecks));\n\t\t\tArrayList<Item> toUndo = new ArrayList<>();\n\t\t\twhile (smithRewards.get(0).getClass() == smithRewards.get(1).getClass()) {\n\t\t\t\tif (useDecks) toUndo.add(smithRewards.get(1));\n\t\t\t\tsmithRewards.remove(1);\n\t\t\t\tsmithRewards.add(Generator.randomWeapon(3, useDecks));\n\t\t\t}\n\t\t\tfor (Item i : toUndo){\n\t\t\t\tGenerator.undoDrop(i);\n\t\t\t}\n\t\t\tsmithRewards.add(Generator.randomArmor(3));\n\n\t\t\t//30%:+0, 45%:+1, 20%:+2, 5%:+3\n\t\t\tint rewardLevel;\n\t\t\tfloat itemLevelRoll = Random.Float();\n\t\t\tif (itemLevelRoll < 0.3f){\n\t\t\t\trewardLevel = 0;\n\t\t\t} else if (itemLevelRoll < 0.75f){\n\t\t\t\trewardLevel = 1;\n\t\t\t} else if (itemLevelRoll < 0.95f){\n\t\t\t\trewardLevel = 2;\n\t\t\t} else {\n\t\t\t\trewardLevel = 3;\n\t\t\t}\n\n\t\t\tfor (Item i : smithRewards){\n\t\t\t\ti.level(rewardLevel);\n\t\t\t\tif (i instanceof Weapon) {\n\t\t\t\t\t((Weapon) i).enchant(null);\n\t\t\t\t} else if (i instanceof Armor){\n\t\t\t\t\t((Armor) i).inscribe(null);\n\t\t\t\t}\n\t\t\t\ti.cursed = false;\n\t\t\t}\n\t\t}\n\n\t\tpublic static int Type(){\n\t\t\treturn type;\n\t\t}\n\n\t\tpublic static boolean given(){\n\t\t\treturn given;\n\t\t}\n\n\t\tpublic static boolean started(){\n\t\t\treturn started;\n\t\t}\n\n\t\tpublic static void start(){\n\t\t\tstarted = true;\n\t\t}\n\n\t\tpublic static boolean beatBoss(){\n\t\t\treturn bossBeaten = true;\n\t\t}\n\n\t\tpublic static boolean bossBeaten(){\n\t\t\treturn bossBeaten;\n\t\t}\n\n\t\tpublic static boolean completed(){\n\t\t\treturn given && completed;\n\t\t}\n\n\t\tpublic static void complete(){\n\t\t\tcompleted = true;\n\n\t\t\tfavor = 0;\n\t\t\tDarkGold gold = Dungeon.hero.belongings.getItem(DarkGold.class);\n\t\t\tif (gold != null){\n\t\t\t\tfavor += Math.min(2000, gold.quantity()*50);\n\t\t\t\tgold.detachAll(Dungeon.hero.belongings.backpack);\n\t\t\t}\n\n\t\t\tPickaxe pick = Dungeon.hero.belongings.getItem(Pickaxe.class);\n\t\t\tif (pick.isEquipped(Dungeon.hero)) {\n\t\t\t\tboolean wasCursed = pick.cursed;\n\t\t\t\tpick.cursed = false; //so that it can always be removed\n\t\t\t\tpick.doUnequip(Dungeon.hero, false);\n\t\t\t\tpick.cursed = wasCursed;\n\t\t\t}\n\t\t\tpick.detach(Dungeon.hero.belongings.backpack);\n\t\t\tQuest.pickaxe = pick;\n\n\t\t\tif (bossBeaten) favor += 1000;\n\n\t\t\tStatistics.questScores[2] = favor;\n\t\t}\n\n\t\t//if the blacksmith is generated pre-v2.2.0, and the player never spawned a mining test floor\n\t\tpublic static boolean oldQuestMineBlocked(){\n\t\t\treturn type == OLD && !Dungeon.levelHasBeenGenerated(Dungeon.depth, 1);\n\t\t}\n\n\t\tpublic static boolean oldBloodQuest(){\n\t\t\treturn type == OLD && alternative;\n\t\t}\n\n\t\tpublic static boolean oldMiningQuest(){\n\t\t\treturn type == OLD && !alternative;\n\t\t}\n\t}\n}" }, { "identifier": "Pushing", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/effects/Pushing.java", "snippet": "public class Pushing extends Actor {\n\n\tprivate CharSprite sprite;\n\tprivate int from;\n\tprivate int to;\n\t\n\tprivate Effect effect;\n\n\tprivate Callback callback;\n\n\t{\n\t\tactPriority = VFX_PRIO+10;\n\t}\n\t\n\tpublic Pushing( Char ch, int from, int to ) {\n\t\tsprite = ch.sprite;\n\t\tthis.from = from;\n\t\tthis.to = to;\n\t\tthis.callback = null;\n\n\t\tif (ch == Dungeon.hero){\n\t\t\tCamera.main.panFollow(ch.sprite, 20f);\n\t\t}\n\t}\n\n\tpublic Pushing( Char ch, int from, int to, Callback callback ) {\n\t\tthis(ch, from, to);\n\t\tthis.callback = callback;\n\t}\n\t\n\t@Override\n\tprotected boolean act() {\n\t\tif (sprite != null) {\n\t\t\tif (Dungeon.level.heroFOV[from] || Dungeon.level.heroFOV[to]){\n\t\t\t\tsprite.visible = true;\n\t\t\t}\n\t\t\tif (effect == null) {\n\t\t\t\tnew Effect();\n\t\t\t}\n\t\t}\n\n\t\tActor.remove( Pushing.this );\n\n\t\t//so that all pushing effects at the same time go simultaneously\n\t\tfor ( Actor actor : Actor.all() ){\n\t\t\tif (actor instanceof Pushing && actor.cooldown() == 0)\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\n\t}\n\n\tpublic class Effect extends Visual {\n\n\t\tprivate static final float DELAY = 0.15f;\n\t\t\n\t\tprivate PointF end;\n\t\t\n\t\tprivate float delay;\n\t\t\n\t\tpublic Effect() {\n\t\t\tsuper( 0, 0, 0, 0 );\n\t\t\t\n\t\t\tpoint( sprite.worldToCamera( from ) );\n\t\t\tend = sprite.worldToCamera( to );\n\t\t\t\n\t\t\tspeed.set( 2 * (end.x - x) / DELAY, 2 * (end.y - y) / DELAY );\n\t\t\tacc.set( -speed.x / DELAY, -speed.y / DELAY );\n\t\t\t\n\t\t\tdelay = 0;\n\n\t\t\tif (sprite.parent != null)\n\t\t\t\tsprite.parent.add( this );\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void update() {\n\t\t\tsuper.update();\n\t\t\t\n\t\t\tif ((delay += Game.elapsed) < DELAY) {\n\t\t\t\t\n\t\t\t\tsprite.x = x;\n\t\t\t\tsprite.y = y;\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\t\n\t\t\t\tsprite.point(end);\n\t\t\t\t\n\t\t\t\tkillAndErase();\n\t\t\t\tActor.remove(Pushing.this);\n\t\t\t\tif (callback != null) callback.call();\n\t\t\t\t\n\t\t\t\tnext();\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "Splash", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/effects/Splash.java", "snippet": "public class Splash {\n\t\n\tpublic static void at( int cell, final int color, int n ) {\n\t\tat( DungeonTilemap.tileCenterToWorld( cell ), color, n );\n\t}\n\t\n\tpublic static void at( PointF p, final int color, int n ) {\n\t\t\n\t\tif (n <= 0) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tEmitter emitter = GameScene.emitter();\n\t\tif (emitter == null) return;\n\t\temitter.pos( p );\n\t\t\n\t\tFACTORY.color = color;\n\t\tFACTORY.dir = -3.1415926f / 2;\n\t\tFACTORY.cone = 3.1415926f;\n\t\temitter.burst( FACTORY, n );\n\t}\n\t\n\tpublic static void at( PointF p, final float dir, final float cone, final int color, int n ) {\n\t\t\n\t\tif (n <= 0) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tEmitter emitter = GameScene.emitter();\n\t\tif (emitter == null) return;\n\t\temitter.pos( p );\n\t\t\n\t\tFACTORY.color = color;\n\t\tFACTORY.dir = dir;\n\t\tFACTORY.cone = cone;\n\t\temitter.burst( FACTORY, n );\n\t}\n\n\tpublic static void around(Visual v, final int color, int n ) {\n\t\tif (n <= 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tEmitter emitter = GameScene.emitter();\n\t\tif (emitter == null) return;\n\t\temitter.pos( v );\n\n\t\tFACTORY.color = color;\n\t\tFACTORY.dir = -3.1415926f / 2;\n\t\tFACTORY.cone = 3.1415926f;\n\t\temitter.burst( FACTORY, n );\n\t}\n\n\tpublic static void at( PointF p, final float dir, final float cone, final int color, int n, float interval ) {\n\n\t\tif (n <= 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tEmitter emitter = GameScene.emitter();\n\t\tif (emitter == null) return;\n\t\temitter.pos( p );\n\n\t\tFACTORY.color = color;\n\t\tFACTORY.dir = dir;\n\t\tFACTORY.cone = cone;\n\t\temitter.start( FACTORY, interval, n );\n\t}\n\t\n\tprivate static final SplashFactory FACTORY = new SplashFactory();\n\t\t\t\n\tprivate static class SplashFactory extends Emitter.Factory {\n\n\t\tpublic int color;\n\t\tpublic float dir;\n\t\tpublic float cone;\n\t\t\n\t\t@Override\n\t\tpublic void emit( Emitter emitter, int index, float x, float y ) {\n\t\t\tPixelParticle p = (PixelParticle)emitter.recycle( PixelParticle.Shrinking.class );\n\t\t\t\n\t\t\tp.reset( x, y, color, 4, Random.Float( 0.5f, 1.0f ) );\n\t\t\tp.speed.polar( Random.Float( dir - cone / 2, dir + cone / 2 ), Random.Float( 40, 80 ) );\n\t\t\tp.acc.set( 0, +100 );\n\t\t}\n\t}\n}" }, { "identifier": "TargetedCell", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/effects/TargetedCell.java", "snippet": "public class TargetedCell extends Image {\n\n\tprivate float alpha;\n\n\tpublic TargetedCell( int pos, int color ) {\n\t\tsuper(Icons.get(Icons.TARGET));\n\t\thardlight(color);\n\n\t\torigin.set( width/2f );\n\n\t\tpoint( DungeonTilemap.tileToWorld( pos ) );\n\n\t\talpha = 1f;\n\t}\n\n\t@Override\n\tpublic void update() {\n\t\tif ((alpha -= Game.elapsed/2f) > 0) {\n\t\t\talpha( alpha );\n\t\t\tscale.set( alpha );\n\t\t} else {\n\t\t\tkillAndErase();\n\t\t}\n\t}\n}" }, { "identifier": "Pickaxe", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/quest/Pickaxe.java", "snippet": "public class Pickaxe extends MeleeWeapon {\n\t\n\tpublic static final String AC_MINE\t= \"MINE\";\n\t\n\tpublic static final float TIME_TO_MINE = 2;\n\t\n\tprivate static final Glowing BLOODY = new Glowing( 0x550000 );\n\t\n\t{\n\t\timage = ItemSpriteSheet.PICKAXE;\n\n\t\tlevelKnown = true;\n\t\t\n\t\tunique = true;\n\t\tbones = false;\n\n\t\ttier = 2;\n\t}\n\t\n\tpublic boolean bloodStained = false;\n\n\t@Override\n\tpublic int STRReq(int lvl) {\n\t\treturn super.STRReq(lvl) + 2; //tier 3 strength requirement with tier 2 damage stats\n\t}\n\n\t@Override\n\tpublic ArrayList<String> actions( Hero hero ) {\n\t\tArrayList<String> actions = super.actions( hero );\n\t\tif (Blacksmith.Quest.oldMiningQuest()) {\n\t\t\tactions.add(AC_MINE);\n\t\t}\n\t\tif (Dungeon.level instanceof MiningLevel){\n\t\t\tactions.remove(AC_DROP);\n\t\t\tactions.remove(AC_THROW);\n\t\t}\n\t\treturn actions;\n\t}\n\t\n\t@Override\n\tpublic void execute( final Hero hero, String action ) {\n\n\t\tsuper.execute( hero, action );\n\t\t\n\t\tif (action.equals(AC_MINE)) {\n\t\t\t\n\t\t\tif (Dungeon.depth < 11 || Dungeon.depth > 15) {\n\t\t\t\tGLog.w( Messages.get(this, \"no_vein\") );\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tfor (int i = 0; i < PathFinder.NEIGHBOURS8.length; i++) {\n\t\t\t\t\n\t\t\t\tfinal int pos = hero.pos + PathFinder.NEIGHBOURS8[i];\n\t\t\t\tif (Dungeon.level.map[pos] == Terrain.WALL_DECO) {\n\t\t\t\t\n\t\t\t\t\thero.spend( TIME_TO_MINE );\n\t\t\t\t\thero.busy();\n\t\t\t\t\t\n\t\t\t\t\thero.sprite.attack( pos, new Callback() {\n\t\t\t\t\t\t\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void call() {\n\n\t\t\t\t\t\t\tCellEmitter.center( pos ).burst( Speck.factory( Speck.STAR ), 7 );\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.EVOKE );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tLevel.set( pos, Terrain.WALL );\n\t\t\t\t\t\t\tGameScene.updateMap( pos );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tDarkGold gold = new DarkGold();\n\t\t\t\t\t\t\tif (gold.doPickUp( Dungeon.hero )) {\n\t\t\t\t\t\t\t\tGLog.i( Messages.capitalize(Messages.get(Dungeon.hero, \"you_now_have\", gold.name())) );\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tDungeon.level.drop( gold, hero.pos ).sprite.drop();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\thero.onOperateComplete();\n\t\t\t\t\t\t}\n\t\t\t\t\t} );\n\t\t\t\t\t\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tGLog.w( Messages.get(this, \"no_vein\") );\n\t\t\t\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic int proc( Char attacker, Char defender, int damage ) {\n\t\tif (Blacksmith.Quest.oldBloodQuest() && !bloodStained && defender instanceof Bat) {\n\t\t\tActor.add(new Actor() {\n\n\t\t\t\t{\n\t\t\t\t\tactPriority = VFX_PRIO;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tprotected boolean act() {\n\t\t\t\t\tif (!defender.isAlive()){\n\t\t\t\t\t\tbloodStained = true;\n\t\t\t\t\t\tupdateQuickslot();\n\t\t\t\t\t}\n\n\t\t\t\t\tActor.remove(this);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn super.proc( attacker, defender, damage );\n\t}\n\n\t@Override\n\tpublic boolean keptThroughLostInventory() {\n\t\t//pickaxe is always kept when it's needed for the mining level\n\t\treturn super.keptThroughLostInventory() || Dungeon.level instanceof MiningLevel;\n\t}\n\n\t@Override\n\tpublic String defaultAction() {\n\t\tif (Dungeon.hero.heroClass == HeroClass.DUELIST && isEquipped(Dungeon.hero)){\n\t\t\treturn AC_ABILITY;\n\t\t} else if (Blacksmith.Quest.oldMiningQuest()) {\n\t\t\treturn AC_MINE;\n\t\t} else {\n\t\t\treturn super.defaultAction();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String targetingPrompt() {\n\t\treturn Messages.get(this, \"prompt\");\n\t}\n\n\t@Override\n\tprotected void duelistAbility(Hero hero, Integer target) {\n\t\tif (target == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tChar enemy = Actor.findChar(target);\n\t\tif (enemy == null || enemy == hero || hero.isCharmedBy(enemy) || !Dungeon.level.heroFOV[target]) {\n\t\t\tGLog.w(Messages.get(this, \"ability_no_target\"));\n\t\t\treturn;\n\t\t}\n\n\t\thero.belongings.abilityWeapon = this;\n\t\tif (!hero.canAttack(enemy)){\n\t\t\tGLog.w(Messages.get(this, \"ability_bad_position\"));\n\t\t\thero.belongings.abilityWeapon = null;\n\t\t\treturn;\n\t\t}\n\t\thero.belongings.abilityWeapon = null;\n\n\t\thero.sprite.attack(enemy.pos, new Callback() {\n\t\t\t@Override\n\t\t\tpublic void call() {\n\t\t\t\tfloat damageMulti = 1f;\n\t\t\t\tif (Char.hasProp(enemy, Char.Property.INORGANIC)\n\t\t\t\t\t\t|| enemy instanceof Swarm\n\t\t\t\t\t\t|| enemy instanceof Bee\n\t\t\t\t\t\t|| enemy instanceof Crab\n\t\t\t\t\t\t|| enemy instanceof Spinner\n\t\t\t\t\t\t|| enemy instanceof Scorpio) {\n\t\t\t\t\tdamageMulti = 2f;\n\t\t\t\t}\n\t\t\t\tbeforeAbilityUsed(hero, enemy);\n\t\t\t\tAttackIndicator.target(enemy);\n\t\t\t\tif (hero.attack(enemy, damageMulti, 0, Char.INFINITE_ACCURACY)) {\n\t\t\t\t\tif (enemy.isAlive()) {\n\t\t\t\t\t\tBuff.affect(enemy, Vulnerable.class, 3f);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tonAbilityKill(hero, enemy);\n\t\t\t\t\t}\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t\t\t}\n\t\t\t\tInvisibility.dispel();\n\t\t\t\thero.spendAndNext(hero.attackDelay());\n\t\t\t\tafterAbilityUsed(hero);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate static final String BLOODSTAINED = \"bloodStained\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tsuper.storeInBundle( bundle );\n\t\t\n\t\tbundle.put( BLOODSTAINED, bloodStained );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tsuper.restoreFromBundle( bundle );\n\t\t\n\t\tbloodStained = bundle.getBoolean( BLOODSTAINED );\n\t}\n\t\n\t@Override\n\tpublic Glowing glowing() {\n\t\tif (super.glowing() == null) {\n\t\t\treturn bloodStained ? BLOODY : null;\n\t\t} else {\n\t\t\treturn super.glowing();\n\t\t}\n\t}\n\n}" }, { "identifier": "Level", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/Level.java", "snippet": "public abstract class Level implements Bundlable {\n\t\n\tpublic static enum Feeling {\n\t\tNONE,\n\t\tCHASM,\n\t\tWATER,\n\t\tGRASS,\n\t\tDARK,\n\t\tLARGE,\n\t\tTRAPS,\n\t\tSECRETS\n\t}\n\n\tprotected int width;\n\tprotected int height;\n\tprotected int length;\n\t\n\tprotected static final float TIME_TO_RESPAWN\t= 50;\n\n\tpublic int version;\n\t\n\tpublic int[] map;\n\tpublic boolean[] visited;\n\tpublic boolean[] mapped;\n\tpublic boolean[] discoverable;\n\n\tpublic int viewDistance = Dungeon.isChallenged( Challenges.DARKNESS ) ? 2 : 8;\n\t\n\tpublic boolean[] heroFOV;\n\t\n\tpublic boolean[] passable;\n\tpublic boolean[] losBlocking;\n\tpublic boolean[] flamable;\n\tpublic boolean[] secret;\n\tpublic boolean[] solid;\n\tpublic boolean[] avoid;\n\tpublic boolean[] water;\n\tpublic boolean[] pit;\n\n\tpublic boolean[] openSpace;\n\t\n\tpublic Feeling feeling = Feeling.NONE;\n\t\n\tpublic int entrance;\n\tpublic int exit;\n\n\tpublic ArrayList<LevelTransition> transitions;\n\n\t//when a boss level has become locked.\n\tpublic boolean locked = false;\n\t\n\tpublic HashSet<Mob> mobs;\n\tpublic SparseArray<Heap> heaps;\n\tpublic HashMap<Class<? extends Blob>,Blob> blobs;\n\tpublic SparseArray<Plant> plants;\n\tpublic SparseArray<Trap> traps;\n\tpublic HashSet<CustomTilemap> customTiles;\n\tpublic HashSet<CustomTilemap> customWalls;\n\t\n\tprotected ArrayList<Item> itemsToSpawn = new ArrayList<>();\n\n\tprotected Group visuals;\n\tprotected Group wallVisuals;\n\t\n\tpublic int color1 = 0x004400;\n\tpublic int color2 = 0x88CC44;\n\n\tprivate static final String VERSION = \"version\";\n\tprivate static final String WIDTH = \"width\";\n\tprivate static final String HEIGHT = \"height\";\n\tprivate static final String MAP\t\t\t= \"map\";\n\tprivate static final String VISITED\t\t= \"visited\";\n\tprivate static final String MAPPED\t\t= \"mapped\";\n\tprivate static final String TRANSITIONS\t= \"transitions\";\n\tprivate static final String LOCKED = \"locked\";\n\tprivate static final String HEAPS\t\t= \"heaps\";\n\tprivate static final String PLANTS\t\t= \"plants\";\n\tprivate static final String TRAPS = \"traps\";\n\tprivate static final String CUSTOM_TILES= \"customTiles\";\n\tprivate static final String CUSTOM_WALLS= \"customWalls\";\n\tprivate static final String MOBS\t\t= \"mobs\";\n\tprivate static final String BLOBS\t\t= \"blobs\";\n\tprivate static final String FEELING\t\t= \"feeling\";\n\n\tpublic void create() {\n\n\t\tRandom.pushGenerator( Dungeon.seedCurDepth() );\n\n\t\tif (!Dungeon.bossLevel() && Dungeon.branch == 2) {\n\t\t\taddItemToSpawn(Generator.random(Generator.Category.FOOD));\n\t\t}\n\n\t\t//TODO maybe just make this part of RegularLevel?\n\t\tif (!Dungeon.bossLevel() && Dungeon.branch == 0) {\n\n\t\t\taddItemToSpawn(Generator.random(Generator.Category.FOOD));\n\n\t\t\tif (Dungeon.posNeeded()) {\n\t\t\t\tDungeon.LimitedDrops.STRENGTH_POTIONS.count++;\n\t\t\t\taddItemToSpawn( new PotionOfStrength() );\n\t\t\t}\n\t\t\tif (Dungeon.souNeeded()) {\n\t\t\t\tDungeon.LimitedDrops.UPGRADE_SCROLLS.count++;\n\t\t\t\t//every 2nd scroll of upgrade is removed with forbidden runes challenge on\n\t\t\t\t//TODO while this does significantly reduce this challenge's levelgen impact, it doesn't quite remove it\n\t\t\t\t//for 0 levelgen impact, we need to do something like give the player all SOU, but nerf them\n\t\t\t\t//or give a random scroll (from a separate RNG) instead of every 2nd SOU\n\t\t\t\tif (!Dungeon.isChallenged(Challenges.NO_SCROLLS) || Dungeon.LimitedDrops.UPGRADE_SCROLLS.count%2 != 0){\n\t\t\t\t\taddItemToSpawn(new ScrollOfUpgrade());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (Dungeon.asNeeded()) {\n\t\t\t\tDungeon.LimitedDrops.ARCANE_STYLI.count++;\n\t\t\t\taddItemToSpawn( new Stylus() );\n\t\t\t}\n\t\t\t//one scroll of transmutation is guaranteed to spawn somewhere on chapter 2-4\n\t\t\tint enchChapter = (int)((Dungeon.seed / 10) % 3) + 1;\n\t\t\tif ( Dungeon.depth / 5 == enchChapter &&\n\t\t\t\t\tDungeon.seed % 4 + 1 == Dungeon.depth % 5){\n\t\t\t\taddItemToSpawn( new StoneOfEnchantment() );\n\t\t\t}\n\t\t\t\n\t\t\tif ( Dungeon.depth == ((Dungeon.seed % 3) + 1)){\n\t\t\t\taddItemToSpawn( new StoneOfIntuition() );\n\t\t\t}\n\t\t\t\n\t\t\tif (Dungeon.depth > 1) {\n\t\t\t\t//50% chance of getting a level feeling\n\t\t\t\t//~7.15% chance for each feeling\n\t\t\t\tswitch (Random.Int( 14 )) {\n\t\t\t\t\tcase 0:\n\t\t\t\t\t\tfeeling = Feeling.CHASM;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tfeeling = Feeling.WATER;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\tfeeling = Feeling.GRASS;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\tfeeling = Feeling.DARK;\n\t\t\t\t\t\taddItemToSpawn(new Torch());\n\t\t\t\t\t\tviewDistance = Math.round(viewDistance/2f);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 4:\n\t\t\t\t\t\tfeeling = Feeling.LARGE;\n\t\t\t\t\t\taddItemToSpawn(Generator.random(Generator.Category.FOOD));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 5:\n\t\t\t\t\t\tfeeling = Feeling.TRAPS;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 6:\n\t\t\t\t\t\tfeeling = Feeling.SECRETS;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tdo {\n\t\t\twidth = height = length = 0;\n\n\t\t\ttransitions = new ArrayList<>();\n\n\t\t\tmobs = new HashSet<>();\n\t\t\theaps = new SparseArray<>();\n\t\t\tblobs = new HashMap<>();\n\t\t\tplants = new SparseArray<>();\n\t\t\ttraps = new SparseArray<>();\n\t\t\tcustomTiles = new HashSet<>();\n\t\t\tcustomWalls = new HashSet<>();\n\t\t\t\n\t\t} while (!build());\n\t\t\n\t\tbuildFlagMaps();\n\t\tcleanWalls();\n\t\t\n\t\tcreateMobs();\n\t\tcreateItems();\n\n\t\tRandom.popGenerator();\n\t}\n\t\n\tpublic void setSize(int w, int h){\n\t\t\n\t\twidth = w;\n\t\theight = h;\n\t\tlength = w * h;\n\t\t\n\t\tmap = new int[length];\n\t\tArrays.fill( map, feeling == Level.Feeling.CHASM ? Terrain.CHASM : Terrain.WALL );\n\t\t\n\t\tvisited = new boolean[length];\n\t\tmapped = new boolean[length];\n\t\t\n\t\theroFOV = new boolean[length];\n\t\t\n\t\tpassable\t= new boolean[length];\n\t\tlosBlocking\t= new boolean[length];\n\t\tflamable\t= new boolean[length];\n\t\tsecret\t\t= new boolean[length];\n\t\tsolid\t\t= new boolean[length];\n\t\tavoid\t\t= new boolean[length];\n\t\twater\t\t= new boolean[length];\n\t\tpit\t\t\t= new boolean[length];\n\n\t\topenSpace = new boolean[length];\n\t\t\n\t\tPathFinder.setMapSize(w, h);\n\t}\n\t\n\tpublic void reset() {\n\t\t\n\t\tfor (Mob mob : mobs.toArray( new Mob[0] )) {\n\t\t\tif (!mob.reset()) {\n\t\t\t\tmobs.remove( mob );\n\t\t\t}\n\t\t}\n\t\tcreateMobs();\n\t}\n\n\tpublic void playLevelMusic(){\n\t\t//do nothing by default\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\n\t\tversion = bundle.getInt( VERSION );\n\t\t\n\t\t//saves from before v1.2.3 are not supported\n\t\tif (version < ShatteredPixelDungeon.v1_2_3){\n\t\t\tthrow new RuntimeException(\"old save\");\n\t\t}\n\n\t\tsetSize( bundle.getInt(WIDTH), bundle.getInt(HEIGHT));\n\t\t\n\t\tmobs = new HashSet<>();\n\t\theaps = new SparseArray<>();\n\t\tblobs = new HashMap<>();\n\t\tplants = new SparseArray<>();\n\t\ttraps = new SparseArray<>();\n\t\tcustomTiles = new HashSet<>();\n\t\tcustomWalls = new HashSet<>();\n\t\t\n\t\tmap\t\t= bundle.getIntArray( MAP );\n\n\t\tvisited\t= bundle.getBooleanArray( VISITED );\n\t\tmapped\t= bundle.getBooleanArray( MAPPED );\n\n\t\ttransitions = new ArrayList<>();\n\t\tif (bundle.contains(TRANSITIONS)){\n\t\t\tfor (Bundlable b : bundle.getCollection( TRANSITIONS )){\n\t\t\t\ttransitions.add((LevelTransition) b);\n\t\t\t}\n\t\t//pre-1.3.0 saves, converts old entrance/exit to new transitions\n\t\t} else {\n\t\t\tif (bundle.contains(\"entrance\")){\n\t\t\t\ttransitions.add(new LevelTransition(\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\tbundle.getInt(\"entrance\"),\n\t\t\t\t\t\tDungeon.depth == 1 ? LevelTransition.Type.SURFACE : LevelTransition.Type.REGULAR_ENTRANCE));\n\t\t\t}\n\t\t\tif (bundle.contains(\"exit\")){\n\t\t\t\ttransitions.add(new LevelTransition(this, bundle.getInt(\"exit\"), LevelTransition.Type.REGULAR_EXIT));\n\t\t\t}\n\t\t}\n\n\t\tlocked = bundle.getBoolean( LOCKED );\n\t\t\n\t\tCollection<Bundlable> collection = bundle.getCollection( HEAPS );\n\t\tfor (Bundlable h : collection) {\n\t\t\tHeap heap = (Heap)h;\n\t\t\tif (!heap.isEmpty())\n\t\t\t\theaps.put( heap.pos, heap );\n\t\t}\n\t\t\n\t\tcollection = bundle.getCollection( PLANTS );\n\t\tfor (Bundlable p : collection) {\n\t\t\tPlant plant = (Plant)p;\n\t\t\tplants.put( plant.pos, plant );\n\t\t}\n\n\t\tcollection = bundle.getCollection( TRAPS );\n\t\tfor (Bundlable p : collection) {\n\t\t\tTrap trap = (Trap)p;\n\t\t\ttraps.put( trap.pos, trap );\n\t\t}\n\n\t\tcollection = bundle.getCollection( CUSTOM_TILES );\n\t\tfor (Bundlable p : collection) {\n\t\t\tCustomTilemap vis = (CustomTilemap)p;\n\t\t\tcustomTiles.add(vis);\n\t\t}\n\n\t\tcollection = bundle.getCollection( CUSTOM_WALLS );\n\t\tfor (Bundlable p : collection) {\n\t\t\tCustomTilemap vis = (CustomTilemap)p;\n\t\t\tcustomWalls.add(vis);\n\t\t}\n\t\t\n\t\tcollection = bundle.getCollection( MOBS );\n\t\tfor (Bundlable m : collection) {\n\t\t\tMob mob = (Mob)m;\n\t\t\tif (mob != null) {\n\t\t\t\tmobs.add( mob );\n\t\t\t}\n\t\t}\n\t\t\n\t\tcollection = bundle.getCollection( BLOBS );\n\t\tfor (Bundlable b : collection) {\n\t\t\tBlob blob = (Blob)b;\n\t\t\tblobs.put( blob.getClass(), blob );\n\t\t}\n\n\t\tfeeling = bundle.getEnum( FEELING, Feeling.class );\n\t\tif (feeling == Feeling.DARK)\n\t\t\tviewDistance = Math.round(viewDistance/2f);\n\n\t\tif (bundle.contains( \"mobs_to_spawn\" )) {\n\t\t\tfor (Class<? extends Mob> mob : bundle.getClassArray(\"mobs_to_spawn\")) {\n\t\t\t\tif (mob != null) mobsToSpawn.add(mob);\n\t\t\t}\n\t\t}\n\n\t\tif (bundle.contains( \"respawner\" )){\n\t\t\trespawner = (Respawner) bundle.get(\"respawner\");\n\t\t}\n\n\t\tbuildFlagMaps();\n\t\tcleanWalls();\n\n\t}\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tbundle.put( VERSION, Game.versionCode );\n\t\tbundle.put( WIDTH, width );\n\t\tbundle.put( HEIGHT, height );\n\t\tbundle.put( MAP, map );\n\t\tbundle.put( VISITED, visited );\n\t\tbundle.put( MAPPED, mapped );\n\t\tbundle.put( TRANSITIONS, transitions );\n\t\tbundle.put( LOCKED, locked );\n\t\tbundle.put( HEAPS, heaps.valueList() );\n\t\tbundle.put( PLANTS, plants.valueList() );\n\t\tbundle.put( TRAPS, traps.valueList() );\n\t\tbundle.put( CUSTOM_TILES, customTiles );\n\t\tbundle.put( CUSTOM_WALLS, customWalls );\n\t\tbundle.put( MOBS, mobs );\n\t\tbundle.put( BLOBS, blobs.values() );\n\t\tbundle.put( FEELING, feeling );\n\t\tbundle.put( \"mobs_to_spawn\", mobsToSpawn.toArray(new Class[0]));\n\t\tbundle.put( \"respawner\", respawner );\n\t}\n\t\n\tpublic int tunnelTile() {\n\t\treturn feeling == Feeling.CHASM ? Terrain.EMPTY_SP : Terrain.EMPTY;\n\t}\n\n\tpublic int width() {\n\t\treturn width;\n\t}\n\n\tpublic int height() {\n\t\treturn height;\n\t}\n\n\tpublic int length() {\n\t\treturn length;\n\t}\n\t\n\tpublic String tilesTex() {\n\t\treturn null;\n\t}\n\t\n\tpublic String waterTex() {\n\t\treturn null;\n\t}\n\t\n\tabstract protected boolean build();\n\t\n\tprivate ArrayList<Class<?extends Mob>> mobsToSpawn = new ArrayList<>();\n\t\n\tpublic Mob createMob() {\n\t\tif (mobsToSpawn == null || mobsToSpawn.isEmpty()) {\n\t\t\tmobsToSpawn = Bestiary.getMobRotation(Dungeon.depth);\n\t\t}\n\n\t\tMob m = Reflection.newInstance(mobsToSpawn.remove(0));\n\t\tChampionEnemy.rollForChampion(m);\n\t\treturn m;\n\t}\n\n\tabstract protected void createMobs();\n\n\tabstract protected void createItems();\n\n\tpublic int entrance(){\n\t\tLevelTransition l = getTransition(null);\n\t\tif (l != null){\n\t\t\treturn l.cell();\n\t\t}\n\t\treturn 0;\n\t}\n\n\tpublic int exit(){\n\t\tLevelTransition l = getTransition(LevelTransition.Type.REGULAR_EXIT);\n\t\tif (l != null){\n\t\t\treturn l.cell();\n\t\t}\n\t\treturn 0;\n\t}\n\n\tpublic LevelTransition getTransition(LevelTransition.Type type){\n\t\tif (transitions.isEmpty()){\n\t\t\treturn null;\n\t\t}\n\t\tfor (LevelTransition transition : transitions){\n\t\t\t//if we don't specify a type, prefer to return any entrance\n\t\t\tif (type == null &&\n\t\t\t\t\t(transition.type == LevelTransition.Type.REGULAR_ENTRANCE || transition.type == LevelTransition.Type.SURFACE)){\n\t\t\t\treturn transition;\n\t\t\t} else if (transition.type == type){\n\t\t\t\treturn transition;\n\t\t\t}\n\t\t}\n\t\treturn type != null ? getTransition(null) : transitions.get(0);\n\t}\n\n\tpublic LevelTransition getTransition(int cell){\n\t\tfor (LevelTransition transition : transitions){\n\t\t\tif (transition.inside(cell)){\n\t\t\t\treturn transition;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t//returns true if we immediately transition, false otherwise\n\tpublic boolean activateTransition(Hero hero, LevelTransition transition){\n\t\tif (locked){\n\t\t\treturn false;\n\t\t}\n\n\t\tbeforeTransition();\n\t\tInterlevelScene.curTransition = transition;\n\t\tif (transition.type == LevelTransition.Type.REGULAR_EXIT\n\t\t\t\t|| transition.type == LevelTransition.Type.BRANCH_EXIT) {\n\t\t\tInterlevelScene.mode = InterlevelScene.Mode.DESCEND;\n\t\t} else {\n\t\t\tInterlevelScene.mode = InterlevelScene.Mode.ASCEND;\n\t\t}\n\t\tGame.switchScene(InterlevelScene.class);\n\t\treturn true;\n\t}\n\n\t//some buff effects have special logic or are cancelled from the hero before transitioning levels\n\tpublic static void beforeTransition(){\n\n\t\t//time freeze effects need to resolve their pressed cells before transitioning\n\t\tTimekeepersHourglass.timeFreeze timeFreeze = Dungeon.hero.buff(TimekeepersHourglass.timeFreeze.class);\n\t\tif (timeFreeze != null) timeFreeze.disarmPresses();\n\t\tSwiftthistle.TimeBubble timeBubble = Dungeon.hero.buff(Swiftthistle.TimeBubble.class);\n\t\tif (timeBubble != null) timeBubble.disarmPresses();\n\n\t\t//iron stomach does not persist through chasm falling\n\t\tTalent.WarriorFoodImmunity foodImmune = Dungeon.hero.buff(Talent.WarriorFoodImmunity.class);\n\t\tif (foodImmune != null) foodImmune.detach();\n\n\t\tTackle.SuperArmorTracker superArmorTracker = Dungeon.hero.buff(Tackle.SuperArmorTracker.class);\n\t\tif (superArmorTracker != null) superArmorTracker.detach();\n\n\t\t//spend the hero's partial turns, so the hero cannot take partial turns between floors\n\t\tDungeon.hero.spendToWhole();\n\t\tfor (Char ch : Actor.chars()){\n\t\t\t//also adjust any mobs that are now ahead of the hero due to this\n\t\t\tif (ch.cooldown() < Dungeon.hero.cooldown()){\n\t\t\t\tch.spendToWhole();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void seal(){\n\t\tif (!locked) {\n\t\t\tlocked = true;\n\t\t\tBuff.affect(Dungeon.hero, LockedFloor.class);\n\t\t}\n\t}\n\n\tpublic void unseal(){\n\t\tif (locked) {\n\t\t\tlocked = false;\n\t\t\tif (Dungeon.hero.buff(LockedFloor.class) != null){\n\t\t\t\tDungeon.hero.buff(LockedFloor.class).detach();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic ArrayList<Item> getItemsToPreserveFromSealedResurrect(){\n\t\tArrayList<Item> items = new ArrayList<>();\n\t\tfor (Heap h : heaps.valueList()){\n\t\t\tif (h.type == Heap.Type.HEAP) items.addAll(h.items);\n\t\t}\n\t\tfor (Mob m : mobs){\n\t\t\tfor (PinCushion b : m.buffs(PinCushion.class)){\n\t\t\t\titems.addAll(b.getStuckItems());\n\t\t\t}\n\t\t}\n\t\tfor (HeavyBoomerang.CircleBack b : Dungeon.hero.buffs(HeavyBoomerang.CircleBack.class)){\n\t\t\tif (b.activeDepth() == Dungeon.depth) items.add(b.cancel());\n\t\t}\n\t\treturn items;\n\t}\n\n\tpublic Group addVisuals() {\n\t\tif (visuals == null || visuals.parent == null){\n\t\t\tvisuals = new Group();\n\t\t} else {\n\t\t\tvisuals.clear();\n\t\t\tvisuals.camera = null;\n\t\t}\n\t\tfor (int i=0; i < length(); i++) {\n\t\t\tif (pit[i]) {\n\t\t\t\tvisuals.add( new WindParticle.Wind( i ) );\n\t\t\t\tif (i >= width() && water[i-width()]) {\n\t\t\t\t\tvisuals.add( new FlowParticle.Flow( i - width() ) );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn visuals;\n\t}\n\n\t//for visual effects that should render above wall overhang tiles\n\tpublic Group addWallVisuals(){\n\t\tif (wallVisuals == null || wallVisuals.parent == null){\n\t\t\twallVisuals = new Group();\n\t\t} else {\n\t\t\twallVisuals.clear();\n\t\t\twallVisuals.camera = null;\n\t\t}\n\t\treturn wallVisuals;\n\t}\n\n\t\n\tpublic int mobLimit() {\n\t\treturn 0;\n\t}\n\n\tpublic int mobCount(){\n\t\tfloat count = 0;\n\t\tfor (Mob mob : Dungeon.level.mobs.toArray(new Mob[0])){\n\t\t\tif (mob.alignment == Char.Alignment.ENEMY && !mob.properties().contains(Char.Property.MINIBOSS)) {\n\t\t\t\tcount += mob.spawningWeight();\n\t\t\t}\n\t\t}\n\t\treturn Math.round(count);\n\t}\n\n\tpublic Mob findMob( int pos ){\n\t\tfor (Mob mob : mobs){\n\t\t\tif (mob.pos == pos){\n\t\t\t\treturn mob;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate Respawner respawner;\n\n\tpublic Actor addRespawner() {\n\t\tif (respawner == null){\n\t\t\trespawner = new Respawner();\n\t\t\tActor.addDelayed(respawner, respawnCooldown());\n\t\t} else {\n\t\t\tActor.add(respawner);\n\t\t\tif (respawner.cooldown() > respawnCooldown()){\n\t\t\t\trespawner.resetCooldown();\n\t\t\t}\n\t\t}\n\t\treturn respawner;\n\t}\n\n\tpublic static class Respawner extends Actor {\n\t\t{\n\t\t\tactPriority = BUFF_PRIO; //as if it were a buff.\n\t\t}\n\n\t\t@Override\n\t\tprotected boolean act() {\n\n\t\t\tif (Dungeon.level.mobCount() < Dungeon.level.mobLimit()) {\n\n\t\t\t\tif (Dungeon.level.spawnMob(12)){\n\t\t\t\t\tspend(Dungeon.level.respawnCooldown());\n\t\t\t\t} else {\n\t\t\t\t\t//try again in 1 turn\n\t\t\t\t\tspend(TICK);\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tspend(Dungeon.level.respawnCooldown());\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\tprotected void resetCooldown(){\n\t\t\tspend(-cooldown());\n\t\t\tspend(Dungeon.level.respawnCooldown());\n\t\t}\n\t}\n\n\tpublic float respawnCooldown(){\n\t\tif (Statistics.amuletObtained){\n\t\t\tif (Dungeon.depth == 1){\n\t\t\t\t//very fast spawns on floor 1! 0/2/4/6/8/10/12, etc.\n\t\t\t\treturn (Dungeon.level.mobCount()) * (TIME_TO_RESPAWN / 25f);\n\t\t\t} else {\n\t\t\t\t//respawn time is 5/5/10/15/20/25/25, etc.\n\t\t\t\treturn Math.round(GameMath.gate( TIME_TO_RESPAWN/10f, Dungeon.level.mobCount() * (TIME_TO_RESPAWN / 10f), TIME_TO_RESPAWN / 2f));\n\t\t\t}\n\t\t} else if (Dungeon.level.feeling == Feeling.DARK){\n\t\t\treturn 2*TIME_TO_RESPAWN/3f;\n\t\t} else {\n\t\t\treturn TIME_TO_RESPAWN;\n\t\t}\n\t}\n\n\tpublic boolean spawnMob(int disLimit){\n\t\tPathFinder.buildDistanceMap(Dungeon.hero.pos, BArray.or(passable, avoid, null));\n\n\t\tMob mob = createMob();\n\t\tmob.state = mob.WANDERING;\n\t\tint tries = 30;\n\t\tdo {\n\t\t\tmob.pos = randomRespawnCell(mob);\n\t\t\ttries--;\n\t\t} while ((mob.pos == -1 || PathFinder.distance[mob.pos] < disLimit) && tries > 0);\n\n\t\tif (Dungeon.hero.isAlive() && mob.pos != -1 && PathFinder.distance[mob.pos] >= disLimit) {\n\t\t\tGameScene.add( mob );\n\t\t\tif (!mob.buffs(ChampionEnemy.class).isEmpty()){\n\t\t\t\tGLog.w(Messages.get(ChampionEnemy.class, \"warn\"));\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic int randomRespawnCell( Char ch ) {\n\t\tint cell;\n\t\tint count = 0;\n\t\tdo {\n\n\t\t\tif (++count > 30) {\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tcell = Random.Int( length() );\n\n\t\t} while ((Dungeon.level == this && heroFOV[cell])\n\t\t\t\t|| !passable[cell]\n\t\t\t\t|| (Char.hasProp(ch, Char.Property.LARGE) && !openSpace[cell])\n\t\t\t\t|| Actor.findChar( cell ) != null);\n\t\treturn cell;\n\t}\n\t\n\tpublic int randomDestination( Char ch ) {\n\t\tint cell;\n\t\tdo {\n\t\t\tcell = Random.Int( length() );\n\t\t} while (!passable[cell]\n\t\t\t\t|| (Char.hasProp(ch, Char.Property.LARGE) && !openSpace[cell]));\n\t\treturn cell;\n\t}\n\t\n\tpublic void addItemToSpawn( Item item ) {\n\t\tif (item != null) {\n\t\t\titemsToSpawn.add( item );\n\t\t}\n\t}\n\n\tpublic Item findPrizeItem(){ return findPrizeItem(null); }\n\n\tpublic Item findPrizeItem(Class<?extends Item> match){\n\t\tif (itemsToSpawn.size() == 0)\n\t\t\treturn null;\n\n\t\tif (match == null){\n\t\t\tItem item = Random.element(itemsToSpawn);\n\t\t\titemsToSpawn.remove(item);\n\t\t\treturn item;\n\t\t}\n\n\t\tfor (Item item : itemsToSpawn){\n\t\t\tif (match.isInstance(item)){\n\t\t\t\titemsToSpawn.remove( item );\n\t\t\t\treturn item;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic void buildFlagMaps() {\n\t\t\n\t\tfor (int i=0; i < length(); i++) {\n\t\t\tint flags = Terrain.flags[map[i]];\n\t\t\tpassable[i]\t\t= (flags & Terrain.PASSABLE) != 0;\n\t\t\tlosBlocking[i]\t= (flags & Terrain.LOS_BLOCKING) != 0;\n\t\t\tflamable[i]\t\t= (flags & Terrain.FLAMABLE) != 0;\n\t\t\tsecret[i]\t\t= (flags & Terrain.SECRET) != 0;\n\t\t\tsolid[i]\t\t= (flags & Terrain.SOLID) != 0;\n\t\t\tavoid[i]\t\t= (flags & Terrain.AVOID) != 0;\n\t\t\twater[i]\t\t= (flags & Terrain.LIQUID) != 0;\n\t\t\tpit[i]\t\t\t= (flags & Terrain.PIT) != 0;\n\t\t}\n\n\t\tfor (Blob b : blobs.values()){\n\t\t\tb.onBuildFlagMaps(this);\n\t\t}\n\t\t\n\t\tint lastRow = length() - width();\n\t\tfor (int i=0; i < width(); i++) {\n\t\t\tpassable[i] = avoid[i] = false;\n\t\t\tlosBlocking[i] = solid[i] = true;\n\t\t\tpassable[lastRow + i] = avoid[lastRow + i] = false;\n\t\t\tlosBlocking[lastRow + i] = solid[lastRow + i] = true;\n\t\t}\n\t\tfor (int i=width(); i < lastRow; i += width()) {\n\t\t\tpassable[i] = avoid[i] = false;\n\t\t\tlosBlocking[i] = solid[i] = true;\n\t\t\tpassable[i + width()-1] = avoid[i + width()-1] = false;\n\t\t\tlosBlocking[i + width()-1] = solid[i + width()-1] = true;\n\t\t}\n\n\t\t//an open space is large enough to fit large mobs. A space is open when it is not solid\n\t\t// and there is an open corner with both adjacent cells opens\n\t\tfor (int i=0; i < length(); i++) {\n\t\t\tif (solid[i]){\n\t\t\t\topenSpace[i] = false;\n\t\t\t} else {\n\t\t\t\tfor (int j = 1; j < PathFinder.CIRCLE8.length; j += 2){\n\t\t\t\t\tif (solid[i+PathFinder.CIRCLE8[j]]) {\n\t\t\t\t\t\topenSpace[i] = false;\n\t\t\t\t\t} else if (!solid[i+PathFinder.CIRCLE8[(j+1)%8]]\n\t\t\t\t\t\t\t&& !solid[i+PathFinder.CIRCLE8[(j+2)%8]]){\n\t\t\t\t\t\topenSpace[i] = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void destroy( int pos ) {\n\t\tItem prize = null;\n\t\tswitch (Random.Int(10)) {\n\t\t\tcase 0: prize = new ScrollOfTransmutation();\n\t\t\t\tbreak;\n\t\t\tcase 1: prize = Generator.random(Generator.Category.SPELLBOOK);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tprize = Generator.random(Generator.Category.SCROLL);\n\t\t\t\tbreak;\n\t\t}\n\t\t//if raw tile type is flammable or empty\n\t\tint terr = map[pos];\n\t\tif (terr == Terrain.EMPTY || terr == Terrain.EMPTY_DECO\n\t\t\t\t|| (Terrain.flags[map[pos]] & Terrain.FLAMABLE) != 0) {\n\t\t\tif (terr == Terrain.BOOKSHELF && Random.Float() < (1/20f)*RingOfWealth.dropChanceMultiplier( Dungeon.hero )) {\n\t\t\t\tif (prize == null) { //this will never be activated, but this is used to prevent a crash in unpredicted case\n\t\t\t\t\tprize = Generator.random(Generator.Category.SCROLL);\n\t\t\t\t}\n\t\t\t\tDungeon.level.drop(prize, pos).sprite.drop();\n\t\t\t} //generates prize for 5% chance when a bookshelf has destroyed\n\t\t\tset(pos, Terrain.EMBERS);\n\t\t}\n\t\tBlob web = blobs.get(Web.class);\n\t\tif (web != null){\n\t\t\tweb.clear(pos);\n\t\t}\n\t}\n\n\tpublic void cleanWalls() {\n\t\tif (discoverable == null || discoverable.length != length) {\n\t\t\tdiscoverable = new boolean[length()];\n\t\t}\n\n\t\tfor (int i=0; i < length(); i++) {\n\t\t\t\n\t\t\tboolean d = false;\n\t\t\t\n\t\t\tfor (int j=0; j < PathFinder.NEIGHBOURS9.length; j++) {\n\t\t\t\tint n = i + PathFinder.NEIGHBOURS9[j];\n\t\t\t\tif (n >= 0 && n < length() && map[n] != Terrain.WALL && map[n] != Terrain.WALL_DECO) {\n\t\t\t\t\td = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tdiscoverable[i] = d;\n\t\t}\n\t}\n\t\n\tpublic static void set( int cell, int terrain ){\n\t\tset( cell, terrain, Dungeon.level );\n\t}\n\t\n\tpublic static void set( int cell, int terrain, Level level ) {\n\t\tPainter.set( level, cell, terrain );\n\n\t\tif (terrain != Terrain.TRAP && terrain != Terrain.SECRET_TRAP && terrain != Terrain.INACTIVE_TRAP){\n\t\t\tlevel.traps.remove( cell );\n\t\t}\n\n\t\tint flags = Terrain.flags[terrain];\n\t\tlevel.passable[cell]\t\t= (flags & Terrain.PASSABLE) != 0;\n\t\tlevel.losBlocking[cell]\t = (flags & Terrain.LOS_BLOCKING) != 0;\n\t\tlevel.flamable[cell]\t\t= (flags & Terrain.FLAMABLE) != 0;\n\t\tlevel.secret[cell]\t\t = (flags & Terrain.SECRET) != 0;\n\t\tlevel.solid[cell]\t\t\t= (flags & Terrain.SOLID) != 0;\n\t\tlevel.avoid[cell]\t\t\t= (flags & Terrain.AVOID) != 0;\n\t\tlevel.pit[cell]\t\t\t = (flags & Terrain.PIT) != 0;\n\t\tlevel.water[cell]\t\t\t= terrain == Terrain.WATER;\n\n\t\tfor (int i : PathFinder.NEIGHBOURS9){\n\t\t\ti = cell + i;\n\t\t\tif (level.solid[i]){\n\t\t\t\tlevel.openSpace[i] = false;\n\t\t\t} else {\n\t\t\t\tfor (int j = 1; j < PathFinder.CIRCLE8.length; j += 2){\n\t\t\t\t\tif (level.solid[i+PathFinder.CIRCLE8[j]]) {\n\t\t\t\t\t\tlevel.openSpace[i] = false;\n\t\t\t\t\t} else if (!level.solid[i+PathFinder.CIRCLE8[(j+1)%8]]\n\t\t\t\t\t\t\t&& !level.solid[i+PathFinder.CIRCLE8[(j+2)%8]]){\n\t\t\t\t\t\tlevel.openSpace[i] = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic Heap drop( Item item, int cell ) {\n\n\t\tif (item == null || Challenges.isItemBlocked(item)){\n\n\t\t\t//create a dummy heap, give it a dummy sprite, don't add it to the game, and return it.\n\t\t\t//effectively nullifies whatever the logic calling this wants to do, including dropping items.\n\t\t\tHeap heap = new Heap();\n\t\t\tItemSprite sprite = heap.sprite = new ItemSprite();\n\t\t\tsprite.link(heap);\n\t\t\treturn heap;\n\n\t\t}\n\t\t\n\t\tHeap heap = heaps.get( cell );\n\t\tif (heap == null) {\n\t\t\t\n\t\t\theap = new Heap();\n\t\t\theap.seen = Dungeon.level == this && heroFOV[cell];\n\t\t\theap.pos = cell;\n\t\t\theap.drop(item);\n\t\t\tif (map[cell] == Terrain.CHASM || (Dungeon.level != null && pit[cell])) {\n\t\t\t\tDungeon.dropToChasm( item );\n\t\t\t\tGameScene.discard( heap );\n\t\t\t} else {\n\t\t\t\theaps.put( cell, heap );\n\t\t\t\tGameScene.add( heap );\n\t\t\t}\n\t\t\t\n\t\t} else if (heap.type == Heap.Type.LOCKED_CHEST || heap.type == Heap.Type.CRYSTAL_CHEST) {\n\t\t\t\n\t\t\tint n;\n\t\t\tdo {\n\t\t\t\tn = cell + PathFinder.NEIGHBOURS8[Random.Int( 8 )];\n\t\t\t} while (!passable[n] && !avoid[n]);\n\t\t\treturn drop( item, n );\n\t\t\t\n\t\t} else {\n\t\t\theap.drop(item);\n\t\t}\n\t\t\n\t\tif (Dungeon.level != null && ShatteredPixelDungeon.scene() instanceof GameScene) {\n\t\t\tpressCell( cell );\n\t\t}\n\t\t\n\t\treturn heap;\n\t}\n\t\n\tpublic Plant plant( Plant.Seed seed, int pos ) {\n\n\t\tPlant plant = plants.get( pos );\n\t\tif (plant != null) {\n\t\t\tplant.wither();\n\t\t}\n\n\t\tif (map[pos] == Terrain.HIGH_GRASS ||\n\t\t\t\tmap[pos] == Terrain.FURROWED_GRASS ||\n\t\t\t\tmap[pos] == Terrain.EMPTY ||\n\t\t\t\tmap[pos] == Terrain.EMBERS ||\n\t\t\t\tmap[pos] == Terrain.EMPTY_DECO) {\n\t\t\tset(pos, Terrain.GRASS, this);\n\t\t\tGameScene.updateMap(pos);\n\t\t}\n\n\t\t//we have to get this far as grass placement has RNG implications in levelgen\n\t\tif (Dungeon.isChallenged(Challenges.NO_HERBALISM)){\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tplant = seed.couch( pos, this );\n\t\tplants.put( pos, plant );\n\t\t\n\t\tGameScene.plantSeed( pos );\n\n\t\tfor (Char ch : Actor.chars()){\n\t\t\tif (ch instanceof WandOfRegrowth.Lotus\n\t\t\t\t\t&& ((WandOfRegrowth.Lotus) ch).inRange(pos)\n\t\t\t\t\t&& Actor.findChar(pos) != null){\n\t\t\t\tplant.trigger();\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn plant;\n\t}\n\t\n\tpublic void uproot( int pos ) {\n\t\tplants.remove(pos);\n\t\tGameScene.updateMap( pos );\n\t}\n\n\tpublic Trap setTrap( Trap trap, int pos ){\n\t\tTrap existingTrap = traps.get(pos);\n\t\tif (existingTrap != null){\n\t\t\ttraps.remove( pos );\n\t\t}\n\t\ttrap.set( pos );\n\t\ttraps.put( pos, trap );\n\t\tGameScene.updateMap( pos );\n\t\treturn trap;\n\t}\n\n\tpublic void disarmTrap( int pos ) {\n\t\tset(pos, Terrain.INACTIVE_TRAP);\n\t\tGameScene.updateMap(pos);\n\t}\n\n\tpublic void discover( int cell ) {\n\t\tset( cell, Terrain.discover( map[cell] ) );\n\t\tTrap trap = traps.get( cell );\n\t\tif (trap != null)\n\t\t\ttrap.reveal();\n\t\tGameScene.updateMap( cell );\n\t}\n\n\tpublic boolean setCellToWater( boolean includeTraps, int cell ){\n\t\tPoint p = cellToPoint(cell);\n\n\t\t//if a custom tilemap is over that cell, don't put water there\n\t\tfor (CustomTilemap cust : customTiles){\n\t\t\tPoint custPoint = new Point(p);\n\t\t\tcustPoint.x -= cust.tileX;\n\t\t\tcustPoint.y -= cust.tileY;\n\t\t\tif (custPoint.x >= 0 && custPoint.y >= 0\n\t\t\t\t\t&& custPoint.x < cust.tileW && custPoint.y < cust.tileH){\n\t\t\t\tif (cust.image(custPoint.x, custPoint.y) != null){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tint terr = map[cell];\n\t\tif (terr == Terrain.EMPTY || terr == Terrain.GRASS ||\n\t\t\t\tterr == Terrain.EMBERS || terr == Terrain.EMPTY_SP ||\n\t\t\t\tterr == Terrain.HIGH_GRASS || terr == Terrain.FURROWED_GRASS\n\t\t\t\t|| terr == Terrain.EMPTY_DECO){\n\t\t\tset(cell, Terrain.WATER);\n\t\t\tGameScene.updateMap(cell);\n\t\t\treturn true;\n\t\t} else if (includeTraps && (terr == Terrain.SECRET_TRAP ||\n\t\t\t\tterr == Terrain.TRAP || terr == Terrain.INACTIVE_TRAP)){\n\t\t\tset(cell, Terrain.WATER);\n\t\t\tDungeon.level.traps.remove(cell);\n\t\t\tGameScene.updateMap(cell);\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\t\n\tpublic int fallCell( boolean fallIntoPit ) {\n\t\tint result;\n\t\tdo {\n\t\t\tresult = randomRespawnCell( null );\n\t\t\tif (result == -1) return -1;\n\t\t} while (traps.get(result) != null\n\t\t\t\t|| findMob(result) != null);\n\t\treturn result;\n\t}\n\t\n\tpublic void occupyCell( Char ch ){\n\t\tif (!ch.isImmune(Web.class) && Blob.volumeAt(ch.pos, Web.class) > 0){\n\t\t\tblobs.get(Web.class).clear(ch.pos);\n\t\t\tWeb.affectChar( ch );\n\t\t}\n\n\t\tif (!ch.flying){\n\n\t\t\tif ( (map[ch.pos] == Terrain.GRASS || map[ch.pos] == Terrain.EMBERS)\n\t\t\t\t\t&& ch == Dungeon.hero && Dungeon.hero.hasTalent(Talent.REJUVENATING_STEPS)\n\t\t\t\t\t&& ch.buff(Talent.RejuvenatingStepsCooldown.class) == null){\n\n\t\t\t\tif (!Regeneration.regenOn()){\n\t\t\t\t\tset(ch.pos, Terrain.FURROWED_GRASS);\n\t\t\t\t} else if (ch.buff(Talent.RejuvenatingStepsFurrow.class) != null && ch.buff(Talent.RejuvenatingStepsFurrow.class).count() >= 200) {\n\t\t\t\t\tset(ch.pos, Terrain.FURROWED_GRASS);\n\t\t\t\t} else {\n\t\t\t\t\tset(ch.pos, Terrain.HIGH_GRASS);\n\t\t\t\t\tBuff.count(ch, Talent.RejuvenatingStepsFurrow.class, 3 - Dungeon.hero.pointsInTalent(Talent.REJUVENATING_STEPS));\n\t\t\t\t}\n\t\t\t\tGameScene.updateMap(ch.pos);\n\t\t\t\tBuff.affect(ch, Talent.RejuvenatingStepsCooldown.class, 15f - 5f*Dungeon.hero.pointsInTalent(Talent.REJUVENATING_STEPS));\n\t\t\t}\n\t\t\t\n\t\t\tif (pit[ch.pos]){\n\t\t\t\tif (ch == Dungeon.hero) {\n\t\t\t\t\tChasm.heroFall(ch.pos);\n\t\t\t\t} else if (ch instanceof Mob) {\n\t\t\t\t\tChasm.mobFall( (Mob)ch );\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t//characters which are not the hero or a sheep 'soft' press cells\n\t\t\tpressCell( ch.pos, ch instanceof Hero || ch instanceof Sheep);\n\t\t} else {\n\t\t\tif (map[ch.pos] == Terrain.DOOR){\n\t\t\t\tDoor.enter( ch.pos );\n\t\t\t}\n\t\t}\n\n\t\tif (ch.isAlive() && ch instanceof Piranha && !water[ch.pos]){\n\t\t\t((Piranha) ch).dieOnLand();\n\t\t}\n\t}\n\t\n\t//public method for forcing the hard press of a cell. e.g. when an item lands on it\n\tpublic void pressCell( int cell ){\n\t\tpressCell( cell, true );\n\t}\n\t\n\t//a 'soft' press ignores hidden traps\n\t//a 'hard' press triggers all things\n\tprivate void pressCell( int cell, boolean hard ) {\n\n\t\tTrap trap = null;\n\t\t\n\t\tswitch (map[cell]) {\n\t\t\n\t\tcase Terrain.SECRET_TRAP:\n\t\t\tif (hard) {\n\t\t\t\ttrap = traps.get( cell );\n\t\t\t\tGLog.i(Messages.get(Level.class, \"hidden_trap\", trap.name()));\n\t\t\t}\n\t\t\tbreak;\n\t\t\t\n\t\tcase Terrain.TRAP:\n\t\t\ttrap = traps.get( cell );\n\t\t\tbreak;\n\t\t\t\n\t\tcase Terrain.HIGH_GRASS:\n\t\tcase Terrain.FURROWED_GRASS:\n\t\t\tHighGrass.trample( this, cell);\n\t\t\tbreak;\n\t\t\t\n\t\tcase Terrain.WELL:\n\t\t\tWellWater.affectCell( cell );\n\t\t\tbreak;\n\t\t\t\n\t\tcase Terrain.DOOR:\n\t\t\tDoor.enter( cell );\n\t\t\tbreak;\n\t\t}\n\n\t\tTimekeepersHourglass.timeFreeze timeFreeze =\n\t\t\t\tDungeon.hero.buff(TimekeepersHourglass.timeFreeze.class);\n\n\t\tSwiftthistle.TimeBubble bubble =\n\t\t\t\tDungeon.hero.buff(Swiftthistle.TimeBubble.class);\n\n\t\tif (trap != null) {\n\t\t\tif (bubble != null){\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TRAP);\n\t\t\t\tdiscover(cell);\n\t\t\t\tbubble.setDelayedPress(cell);\n\t\t\t\t\n\t\t\t} else if (timeFreeze != null){\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TRAP);\n\t\t\t\tdiscover(cell);\n\t\t\t\ttimeFreeze.setDelayedPress(cell);\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tif (Dungeon.hero.pos == cell) {\n\t\t\t\t\tDungeon.hero.interrupt();\n\t\t\t\t}\n\t\t\t\ttrap.trigger();\n\n\t\t\t}\n\t\t}\n\t\t\n\t\tPlant plant = plants.get( cell );\n\t\tif (plant != null) {\n\t\t\tif (bubble != null){\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TRAMPLE, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t\tbubble.setDelayedPress(cell);\n\n\t\t\t} else if (timeFreeze != null){\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TRAMPLE, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t\ttimeFreeze.setDelayedPress(cell);\n\n\t\t\t} else {\n\t\t\t\tplant.trigger();\n\n\t\t\t}\n\t\t}\n\n\t\tif (hard && Blob.volumeAt(cell, Web.class) > 0){\n\t\t\tblobs.get(Web.class).clear(cell);\n\t\t}\n\t}\n\n\tprivate static boolean[] heroMindFov;\n\n\tprivate static boolean[] modifiableBlocking;\n\n\tpublic void updateFieldOfView( Char c, boolean[] fieldOfView ) {\n\n\t\tint cx = c.pos % width();\n\t\tint cy = c.pos / width();\n\t\t\n\t\tboolean sighted = c.buff( Blindness.class ) == null && c.buff( Shadows.class ) == null\n\t\t\t\t\t\t&& c.buff( TimekeepersHourglass.timeStasis.class ) == null && c.isAlive();\n\t\tif (sighted) {\n\t\t\tboolean[] blocking = null;\n\n\t\t\tif (modifiableBlocking == null || modifiableBlocking.length != Dungeon.level.losBlocking.length){\n\t\t\t\tmodifiableBlocking = new boolean[Dungeon.level.losBlocking.length];\n\t\t\t}\n\t\t\t\n\t\t\tif ((c instanceof Hero && ((Hero) c).subClass == HeroSubClass.WARDEN)\n\t\t\t\t|| c instanceof YogFist.SoiledFist) {\n\t\t\t\tif (blocking == null) {\n\t\t\t\t\tSystem.arraycopy(Dungeon.level.losBlocking, 0, modifiableBlocking, 0, modifiableBlocking.length);\n\t\t\t\t\tblocking = modifiableBlocking;\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < blocking.length; i++){\n\t\t\t\t\tif (blocking[i] && (Dungeon.level.map[i] == Terrain.HIGH_GRASS || Dungeon.level.map[i] == Terrain.FURROWED_GRASS)){\n\t\t\t\t\t\tblocking[i] = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (c.alignment != Char.Alignment.ALLY\n\t\t\t\t\t&& Dungeon.level.blobs.containsKey(SmokeScreen.class)\n\t\t\t\t\t&& Dungeon.level.blobs.get(SmokeScreen.class).volume > 0) {\n\t\t\t\tif (blocking == null) {\n\t\t\t\t\tSystem.arraycopy(Dungeon.level.losBlocking, 0, modifiableBlocking, 0, modifiableBlocking.length);\n\t\t\t\t\tblocking = modifiableBlocking;\n\t\t\t\t}\n\t\t\t\tBlob s = Dungeon.level.blobs.get(SmokeScreen.class);\n\t\t\t\tfor (int i = 0; i < blocking.length; i++){\n\t\t\t\t\tif (!blocking[i] && s.cur[i] > 0){\n\t\t\t\t\t\tblocking[i] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (blocking == null){\n\t\t\t\tblocking = Dungeon.level.losBlocking;\n\t\t\t}\n\t\t\t\n\t\t\tint viewDist = c.viewDistance;\n\t\t\tif (c instanceof Hero){\n\t\t\t\tviewDist *= 1f + 0.25f*((Hero) c).pointsInTalent(Talent.FARSIGHT);\n\t\t\t\tviewDist *= 1f + 0.25f*((Hero) c).pointsInTalent(Talent.TELESCOPE);\n\t\t\t}\n\t\t\t\n\t\t\tShadowCaster.castShadow( cx, cy, fieldOfView, blocking, viewDist );\n\t\t} else {\n\t\t\tBArray.setFalse(fieldOfView);\n\t\t}\n\t\t\n\t\tint sense = 1;\n\t\t//Currently only the hero can get mind vision\n\t\tif (c.isAlive() && c == Dungeon.hero) {\n\t\t\tfor (Buff b : c.buffs( MindVision.class )) {\n\t\t\t\tsense = Math.max( ((MindVision)b).distance, sense );\n\t\t\t}\n\t\t\tif (c.buff(MagicalSight.class) != null){\n\t\t\t\tsense = Math.max( MagicalSight.DISTANCE, sense );\n\t\t\t}\n\t\t}\n\t\t\n\t\t//uses rounding\n\t\tif (!sighted || sense > 1) {\n\t\t\t\n\t\t\tint[][] rounding = ShadowCaster.rounding;\n\t\t\t\n\t\t\tint left, right;\n\t\t\tint pos;\n\t\t\tfor (int y = Math.max(0, cy - sense); y <= Math.min(height()-1, cy + sense); y++) {\n\t\t\t\tif (rounding[sense][Math.abs(cy - y)] < Math.abs(cy - y)) {\n\t\t\t\t\tleft = cx - rounding[sense][Math.abs(cy - y)];\n\t\t\t\t} else {\n\t\t\t\t\tleft = sense;\n\t\t\t\t\twhile (rounding[sense][left] < rounding[sense][Math.abs(cy - y)]){\n\t\t\t\t\t\tleft--;\n\t\t\t\t\t}\n\t\t\t\t\tleft = cx - left;\n\t\t\t\t}\n\t\t\t\tright = Math.min(width()-1, cx + cx - left);\n\t\t\t\tleft = Math.max(0, left);\n\t\t\t\tpos = left + y * width();\n\t\t\t\tSystem.arraycopy(discoverable, pos, fieldOfView, pos, right - left + 1);\n\t\t\t}\n\t\t}\n\n\t\tif (c instanceof SpiritHawk.HawkAlly && Dungeon.hero.pointsInTalent(Talent.EAGLE_EYE) >= 3){\n\t\t\tint range = 1+(Dungeon.hero.pointsInTalent(Talent.EAGLE_EYE)-2);\n\t\t\tfor (Mob mob : mobs) {\n\t\t\t\tint p = mob.pos;\n\t\t\t\tif (!fieldOfView[p] && distance(c.pos, p) <= range) {\n\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\tfieldOfView[mob.pos + i] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//Currently only the hero can get mind vision or awareness\n\t\tif (c.isAlive() && c == Dungeon.hero) {\n\n\t\t\tif (heroMindFov == null || heroMindFov.length != length()){\n\t\t\t\theroMindFov = new boolean[length];\n\t\t\t} else {\n\t\t\t\tBArray.setFalse(heroMindFov);\n\t\t\t}\n\n\t\t\tDungeon.hero.mindVisionEnemies.clear();\n\t\t\tif (c.buff( MindVision.class ) != null) {\n\t\t\t\tfor (Mob mob : mobs) {\n\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\theroMindFov[mob.pos + i] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tHero h = (Hero) c;\n\t\t\t\tint range = 0;\n\t\t\t\tif (h.hasTalent(Talent.HEIGHTENED_SENSES)) {\n\t\t\t\t\trange += 1+h.pointsInTalent(Talent.HEIGHTENED_SENSES);\n\t\t\t\t}\n\t\t\t\tif (h.hasTalent(Talent.TACTICAL_SIGHT) && Dungeon.hero.buff(ReinforcedArmor.ReinforcedArmorTracker.class) != null) {\n\t\t\t\t\trange += 1+h.pointsInTalent(Talent.TACTICAL_SIGHT);\n\t\t\t\t}\n\t\t\t\tif (range > 0) {\n\t\t\t\t\tfor (Mob mob : mobs) {\n\t\t\t\t\t\tint p = mob.pos;\n\t\t\t\t\t\tif (!fieldOfView[p] && distance(c.pos, p) <= range) {\n\t\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\t\t\theroMindFov[mob.pos + i] = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (c.buff( Awareness.class ) != null) {\n\t\t\t\tfor (Heap heap : heaps.valueList()) {\n\t\t\t\t\tint p = heap.pos;\n\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) heroMindFov[p+i] = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (TalismanOfForesight.CharAwareness a : c.buffs(TalismanOfForesight.CharAwareness.class)){\n\t\t\t\tChar ch = (Char) Actor.findById(a.charID);\n\t\t\t\tif (ch == null || !ch.isAlive()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tint p = ch.pos;\n\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) heroMindFov[p+i] = true;\n\t\t\t}\n\n\t\t\tfor (TalismanOfForesight.HeapAwareness h : c.buffs(TalismanOfForesight.HeapAwareness.class)){\n\t\t\t\tif (Dungeon.depth != h.depth || Dungeon.branch != h.branch) continue;\n\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) heroMindFov[h.pos+i] = true;\n\t\t\t}\n\n\t\t\tfor (Mob m : mobs){\n\t\t\t\tif (m instanceof WandOfWarding.Ward\n\t\t\t\t\t\t|| m instanceof WandOfRegrowth.Lotus\n\t\t\t\t\t\t|| m instanceof SpiritHawk.HawkAlly){\n\t\t\t\t\tif (m.fieldOfView == null || m.fieldOfView.length != length()){\n\t\t\t\t\t\tm.fieldOfView = new boolean[length()];\n\t\t\t\t\t\tDungeon.level.updateFieldOfView( m, m.fieldOfView );\n\t\t\t\t\t}\n\t\t\t\t\tBArray.or(heroMindFov, m.fieldOfView, heroMindFov);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (RevealedArea a : c.buffs(RevealedArea.class)){\n\t\t\t\tif (Dungeon.depth != a.depth || Dungeon.branch != a.branch) continue;\n\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) heroMindFov[a.pos+i] = true;\n\t\t\t}\n\n\t\t\t//set mind vision chars\n\t\t\tfor (Mob mob : mobs) {\n\t\t\t\tif (heroMindFov[mob.pos] && !fieldOfView[mob.pos]){\n\t\t\t\t\tDungeon.hero.mindVisionEnemies.add(mob);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tBArray.or(heroMindFov, fieldOfView, fieldOfView);\n\n\t\t}\n\n\t\tif (c == Dungeon.hero) {\n\t\t\tfor (Heap heap : heaps.valueList())\n\t\t\t\tif (!heap.seen && fieldOfView[heap.pos])\n\t\t\t\t\theap.seen = true;\n\t\t}\n\n\t}\n\n\tpublic boolean isLevelExplored( int depth ){\n\t\treturn false;\n\t}\n\t\n\tpublic int distance( int a, int b ) {\n\t\tint ax = a % width();\n\t\tint ay = a / width();\n\t\tint bx = b % width();\n\t\tint by = b / width();\n\t\treturn Math.max( Math.abs( ax - bx ), Math.abs( ay - by ) );\n\t}\n\t\n\tpublic boolean adjacent( int a, int b ) {\n\t\treturn distance( a, b ) == 1;\n\t}\n\t\n\t//uses pythagorean theorum for true distance, as if there was no movement grid\n\tpublic float trueDistance(int a, int b){\n\t\tint ax = a % width();\n\t\tint ay = a / width();\n\t\tint bx = b % width();\n\t\tint by = b / width();\n\t\treturn (float)Math.sqrt(Math.pow(Math.abs( ax - bx ), 2) + Math.pow(Math.abs( ay - by ), 2));\n\t}\n\n\t//returns true if the input is a valid tile within the level\n\tpublic boolean insideMap( int tile ){\n\t\t\t\t//top and bottom row and beyond\n\t\treturn !((tile < width || tile >= length - width) ||\n\t\t\t\t//left and right column\n\t\t\t\t(tile % width == 0 || tile % width == width-1));\n\t}\n\n\tpublic Point cellToPoint( int cell ){\n\t\treturn new Point(cell % width(), cell / width());\n\t}\n\n\tpublic int pointToCell( Point p ){\n\t\treturn p.x + p.y*width();\n\t}\n\t\n\tpublic String tileName( int tile ) {\n\t\t\n\t\tswitch (tile) {\n\t\t\tcase Terrain.CHASM:\n\t\t\t\treturn Messages.get(Level.class, \"chasm_name\");\n\t\t\tcase Terrain.EMPTY:\n\t\t\tcase Terrain.EMPTY_SP:\n\t\t\tcase Terrain.EMPTY_DECO:\n\t\t\tcase Terrain.CUSTOM_DECO_EMPTY:\n\t\t\tcase Terrain.SECRET_TRAP:\n\t\t\t\treturn Messages.get(Level.class, \"floor_name\");\n\t\t\tcase Terrain.GRASS:\n\t\t\t\treturn Messages.get(Level.class, \"grass_name\");\n\t\t\tcase Terrain.WATER:\n\t\t\t\treturn Messages.get(Level.class, \"water_name\");\n\t\t\tcase Terrain.WALL:\n\t\t\tcase Terrain.WALL_DECO:\n\t\t\tcase Terrain.SECRET_DOOR:\n\t\t\t\treturn Messages.get(Level.class, \"wall_name\");\n\t\t\tcase Terrain.DOOR:\n\t\t\t\treturn Messages.get(Level.class, \"closed_door_name\");\n\t\t\tcase Terrain.OPEN_DOOR:\n\t\t\t\treturn Messages.get(Level.class, \"open_door_name\");\n\t\t\tcase Terrain.ENTRANCE:\n\t\t\t\treturn Messages.get(Level.class, \"entrace_name\");\n\t\t\tcase Terrain.EXIT:\n\t\t\t\treturn Messages.get(Level.class, \"exit_name\");\n\t\t\tcase Terrain.EMBERS:\n\t\t\t\treturn Messages.get(Level.class, \"embers_name\");\n\t\t\tcase Terrain.FURROWED_GRASS:\n\t\t\t\treturn Messages.get(Level.class, \"furrowed_grass_name\");\n\t\t\tcase Terrain.LOCKED_DOOR:\n\t\t\t\treturn Messages.get(Level.class, \"locked_door_name\");\n\t\t\tcase Terrain.CRYSTAL_DOOR:\n\t\t\t\treturn Messages.get(Level.class, \"crystal_door_name\");\n\t\t\tcase Terrain.PEDESTAL:\n\t\t\t\treturn Messages.get(Level.class, \"pedestal_name\");\n\t\t\tcase Terrain.BARRICADE:\n\t\t\t\treturn Messages.get(Level.class, \"barricade_name\");\n\t\t\tcase Terrain.HIGH_GRASS:\n\t\t\t\treturn Messages.get(Level.class, \"high_grass_name\");\n\t\t\tcase Terrain.LOCKED_EXIT:\n\t\t\t\treturn Messages.get(Level.class, \"locked_exit_name\");\n\t\t\tcase Terrain.UNLOCKED_EXIT:\n\t\t\t\treturn Messages.get(Level.class, \"unlocked_exit_name\");\n\t\t\tcase Terrain.WELL:\n\t\t\t\treturn Messages.get(Level.class, \"well_name\");\n\t\t\tcase Terrain.EMPTY_WELL:\n\t\t\t\treturn Messages.get(Level.class, \"empty_well_name\");\n\t\t\tcase Terrain.STATUE:\n\t\t\tcase Terrain.STATUE_SP:\n\t\t\t\treturn Messages.get(Level.class, \"statue_name\");\n\t\t\tcase Terrain.INACTIVE_TRAP:\n\t\t\t\treturn Messages.get(Level.class, \"inactive_trap_name\");\n\t\t\tcase Terrain.BOOKSHELF:\n\t\t\t\treturn Messages.get(Level.class, \"bookshelf_name\");\n\t\t\tcase Terrain.ALCHEMY:\n\t\t\t\treturn Messages.get(Level.class, \"alchemy_name\");\n\t\t\tdefault:\n\t\t\t\treturn Messages.get(Level.class, \"default_name\");\n\t\t}\n\t}\n\t\n\tpublic String tileDesc( int tile ) {\n\t\t\n\t\tswitch (tile) {\n\t\t\tcase Terrain.CHASM:\n\t\t\t\treturn Messages.get(Level.class, \"chasm_desc\");\n\t\t\tcase Terrain.WATER:\n\t\t\t\treturn Messages.get(Level.class, \"water_desc\");\n\t\t\tcase Terrain.ENTRANCE:\n\t\t\t\treturn Messages.get(Level.class, \"entrance_desc\");\n\t\t\tcase Terrain.EXIT:\n\t\t\tcase Terrain.UNLOCKED_EXIT:\n\t\t\t\treturn Messages.get(Level.class, \"exit_desc\");\n\t\t\tcase Terrain.EMBERS:\n\t\t\t\treturn Messages.get(Level.class, \"embers_desc\");\n\t\t\tcase Terrain.HIGH_GRASS:\n\t\t\tcase Terrain.FURROWED_GRASS:\n\t\t\t\treturn Messages.get(Level.class, \"high_grass_desc\");\n\t\t\tcase Terrain.LOCKED_DOOR:\n\t\t\t\treturn Messages.get(Level.class, \"locked_door_desc\");\n\t\t\tcase Terrain.CRYSTAL_DOOR:\n\t\t\t\treturn Messages.get(Level.class, \"crystal_door_desc\");\n\t\t\tcase Terrain.LOCKED_EXIT:\n\t\t\t\treturn Messages.get(Level.class, \"locked_exit_desc\");\n\t\t\tcase Terrain.BARRICADE:\n\t\t\t\treturn Messages.get(Level.class, \"barricade_desc\");\n\t\t\tcase Terrain.INACTIVE_TRAP:\n\t\t\t\treturn Messages.get(Level.class, \"inactive_trap_desc\");\n\t\t\tcase Terrain.STATUE:\n\t\t\tcase Terrain.STATUE_SP:\n\t\t\t\treturn Messages.get(Level.class, \"statue_desc\");\n\t\t\tcase Terrain.ALCHEMY:\n\t\t\t\treturn Messages.get(Level.class, \"alchemy_desc\");\n\t\t\tcase Terrain.EMPTY_WELL:\n\t\t\t\treturn Messages.get(Level.class, \"empty_well_desc\");\n\t\t\tdefault:\n\t\t\t\treturn \"\";\n\t\t}\n\t}\n}" }, { "identifier": "Terrain", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/Terrain.java", "snippet": "public class Terrain {\n\n\tpublic static final int CHASM\t\t\t= 0;\n\tpublic static final int EMPTY\t\t\t= 1;\n\tpublic static final int GRASS\t\t\t= 2;\n\tpublic static final int EMPTY_WELL\t\t= 3;\n\tpublic static final int WALL\t\t\t= 4;\n\tpublic static final int DOOR\t\t\t= 5;\n\tpublic static final int OPEN_DOOR\t\t= 6;\n\tpublic static final int ENTRANCE\t\t= 7;\n\tpublic static final int EXIT\t\t\t= 8;\n\tpublic static final int EMBERS\t\t\t= 9;\n\tpublic static final int LOCKED_DOOR\t\t= 10;\n\tpublic static final int CRYSTAL_DOOR\t= 31;\n\tpublic static final int PEDESTAL\t\t= 11;\n\tpublic static final int WALL_DECO\t\t= 12;\n\tpublic static final int BARRICADE\t\t= 13;\n\tpublic static final int EMPTY_SP\t\t= 14;\n\tpublic static final int HIGH_GRASS\t\t= 15;\n\tpublic static final int FURROWED_GRASS\t= 30;\n\n\tpublic static final int SECRET_DOOR\t = 16;\n\tpublic static final int SECRET_TRAP = 17;\n\tpublic static final int TRAP = 18;\n\tpublic static final int INACTIVE_TRAP = 19;\n\n\tpublic static final int EMPTY_DECO\t\t= 20;\n\tpublic static final int LOCKED_EXIT\t\t= 21;\n\tpublic static final int UNLOCKED_EXIT\t= 22;\n\tpublic static final int WELL\t\t\t= 24;\n\tpublic static final int BOOKSHELF\t\t= 27;\n\tpublic static final int ALCHEMY\t\t\t= 28;\n\n\tpublic static final int CUSTOM_DECO_EMPTY = 32; //regular empty tile that can't be overridden, used for custom visuals mainly\n\t//solid environment decorations\n\tpublic static final int CUSTOM_DECO\t = 23; //invisible decoration that will also be a custom visual, re-uses the old terrain ID for signs\n\tpublic static final int STATUE\t\t\t= 25;\n\tpublic static final int STATUE_SP\t\t= 26;\n\t//These decorations are environment-specific\n\t//33 and 34 are reserved for future statue-like decorations\n\tpublic static final int MINE_CRYSTAL = 35;\n\tpublic static final int MINE_BOULDER = 36;\n\n\tpublic static final int WATER\t\t = 29;\n\t\n\tpublic static final int PASSABLE\t\t= 0x01;\n\tpublic static final int LOS_BLOCKING\t= 0x02;\n\tpublic static final int FLAMABLE\t\t= 0x04;\n\tpublic static final int SECRET\t\t\t= 0x08;\n\tpublic static final int SOLID\t\t\t= 0x10;\n\tpublic static final int AVOID\t\t\t= 0x20;\n\tpublic static final int LIQUID\t\t\t= 0x40;\n\tpublic static final int PIT\t\t\t\t= 0x80;\n\t\n\tpublic static final int[] flags = new int[256];\n\tstatic {\n\t\tflags[CHASM]\t\t= AVOID\t| PIT;\n\t\tflags[EMPTY]\t\t= PASSABLE;\n\t\tflags[GRASS]\t\t= PASSABLE | FLAMABLE;\n\t\tflags[EMPTY_WELL]\t= PASSABLE;\n\t\tflags[WATER]\t\t= PASSABLE | LIQUID;\n\t\tflags[WALL]\t\t\t= LOS_BLOCKING | SOLID;\n\t\tflags[DOOR]\t\t\t= PASSABLE | LOS_BLOCKING | FLAMABLE | SOLID;\n\t\tflags[OPEN_DOOR]\t= PASSABLE | FLAMABLE;\n\t\tflags[ENTRANCE]\t\t= PASSABLE/* | SOLID*/;\n\t\tflags[EXIT]\t\t\t= PASSABLE;\n\t\tflags[EMBERS]\t\t= PASSABLE;\n\t\tflags[LOCKED_DOOR]\t= LOS_BLOCKING | SOLID;\n\t\tflags[CRYSTAL_DOOR]\t= SOLID;\n\t\tflags[PEDESTAL]\t\t= PASSABLE;\n\t\tflags[WALL_DECO]\t= flags[WALL];\n\t\tflags[BARRICADE]\t= FLAMABLE | SOLID | LOS_BLOCKING;\n\t\tflags[EMPTY_SP]\t\t= flags[EMPTY];\n\t\tflags[HIGH_GRASS]\t= PASSABLE | LOS_BLOCKING | FLAMABLE;\n\t\tflags[FURROWED_GRASS]= flags[HIGH_GRASS];\n\n\t\tflags[SECRET_DOOR] = flags[WALL] | SECRET;\n\t\tflags[SECRET_TRAP] = flags[EMPTY] | SECRET;\n\t\tflags[TRAP] = AVOID;\n\t\tflags[INACTIVE_TRAP]= flags[EMPTY];\n\n\t\tflags[EMPTY_DECO]\t= flags[EMPTY];\n\t\tflags[LOCKED_EXIT]\t= SOLID;\n\t\tflags[UNLOCKED_EXIT]= PASSABLE;\n\t\tflags[WELL]\t\t\t= AVOID;\n\t\tflags[BOOKSHELF]\t= flags[BARRICADE];\n\t\tflags[ALCHEMY]\t\t= SOLID;\n\n\t\tflags[CUSTOM_DECO_EMPTY] = flags[EMPTY];\n\t\tflags[CUSTOM_DECO] = SOLID;\n\t\tflags[STATUE] = SOLID;\n\t\tflags[STATUE_SP] = flags[STATUE];\n\n\t\tflags[MINE_CRYSTAL] = SOLID;\n\t\tflags[MINE_BOULDER] = SOLID;\n\n\t}\n\n\tpublic static int discover( int terr ) {\n\t\tswitch (terr) {\n\t\tcase SECRET_DOOR:\n\t\t\treturn DOOR;\n\t\tcase SECRET_TRAP:\n\t\t\treturn TRAP;\n\t\tdefault:\n\t\t\treturn terr;\n\t\t}\n\t}\n\n}" }, { "identifier": "Ballistica", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/mechanics/Ballistica.java", "snippet": "public class Ballistica {\n\n\t//note that the path is the FULL path of the projectile, including tiles after collision.\n\t//make sure to generate a subPath for the common case of going source to collision.\n\tpublic ArrayList<Integer> path = new ArrayList<>();\n\tpublic Integer sourcePos = null;\n\tpublic Integer collisionPos = null;\n\tpublic Integer collisionProperties = null;\n\tpublic Integer dist = 0;\n\n\t//parameters to specify the colliding cell\n\tpublic static final int STOP_TARGET = 1; //ballistica will stop at the target cell\n\tpublic static final int STOP_CHARS = 2; //ballistica will stop on first char hit\n\tpublic static final int STOP_SOLID = 4; //ballistica will stop on solid terrain\n\tpublic static final int IGNORE_SOFT_SOLID = 8; //ballistica will ignore soft solid terrain, such as doors and webs\n\n\tpublic static final int PROJECTILE = \tSTOP_TARGET\t| STOP_CHARS\t| STOP_SOLID;\n\n\tpublic static final int DASH = \t\tSTOP_TARGET\t| STOP_SOLID;\n\n\tpublic static final int MAGIC_BOLT = STOP_CHARS | STOP_SOLID;\n\n\tpublic static final int WONT_STOP = 0;\n\n\n\tpublic Ballistica( int from, int to, int params ){\n\t\tsourcePos = from;\n\t\tcollisionProperties = params;\n\t\tbuild(from, to,\n\t\t\t\t(params & STOP_TARGET) > 0,\n\t\t\t\t(params & STOP_CHARS) > 0,\n\t\t\t\t(params & STOP_SOLID) > 0,\n\t\t\t\t(params & IGNORE_SOFT_SOLID) > 0);\n\n\t\tif (collisionPos != null) {\n\t\t\tdist = path.indexOf(collisionPos);\n\t\t} else if (!path.isEmpty()) {\n\t\t\tcollisionPos = path.get(dist = path.size() - 1);\n\t\t} else {\n\t\t\tpath.add(from);\n\t\t\tcollisionPos = from;\n\t\t\tdist = 0;\n\t\t}\n\t}\n\n\tprivate void build( int from, int to, boolean stopTarget, boolean stopChars, boolean stopTerrain, boolean ignoreSoftSolid ) {\n\t\tint w = Dungeon.level.width();\n\n\t\tint x0 = from % w;\n\t\tint x1 = to % w;\n\t\tint y0 = from / w;\n\t\tint y1 = to / w;\n\n\t\tint dx = x1 - x0;\n\t\tint dy = y1 - y0;\n\n\t\tint stepX = dx > 0 ? +1 : -1;\n\t\tint stepY = dy > 0 ? +1 : -1;\n\n\t\tdx = Math.abs( dx );\n\t\tdy = Math.abs( dy );\n\n\t\tint stepA;\n\t\tint stepB;\n\t\tint dA;\n\t\tint dB;\n\n\t\tif (dx > dy) {\n\n\t\t\tstepA = stepX;\n\t\t\tstepB = stepY * w;\n\t\t\tdA = dx;\n\t\t\tdB = dy;\n\n\t\t} else {\n\n\t\t\tstepA = stepY * w;\n\t\t\tstepB = stepX;\n\t\t\tdA = dy;\n\t\t\tdB = dx;\n\n\t\t}\n\n\t\tint cell = from;\n\n\t\tint err = dA / 2;\n\t\twhile (Dungeon.level.insideMap(cell)) {\n\n\t\t\t//if we're in solid terrain, and there's no char there, collide with the previous cell.\n\t\t\t// we don't use solid here because we don't want to stop short of closed doors.\n\t\t\tif (collisionPos == null\n\t\t\t\t\t&& stopTerrain\n\t\t\t\t\t&& cell != sourcePos\n\t\t\t\t\t&& !Dungeon.level.passable[cell]\n\t\t\t\t\t&& !Dungeon.level.avoid[cell]\n\t\t\t\t\t&& Actor.findChar(cell) == null) {\n\t\t\t\tcollide(path.get(path.size() - 1));\n\t\t\t}\n\n\t\t\tpath.add(cell);\n\n\t\t\tif (collisionPos == null && stopTerrain && cell != sourcePos && Dungeon.level.solid[cell]) {\n\t\t\t\tif (ignoreSoftSolid && (Dungeon.level.passable[cell] || Dungeon.level.avoid[cell])) {\n\t\t\t\t\t//do nothing\n\t\t\t\t} else {\n\t\t\t\t\tcollide(cell);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (collisionPos == null && cell != sourcePos && stopChars && Actor.findChar( cell ) != null) {\n\t\t\t\tcollide(cell);\n\t\t\t}\n\t\t\tif (collisionPos == null && cell == to && stopTarget){\n\t\t\t\tcollide(cell);\n\t\t\t}\n\n\t\t\tcell += stepA;\n\n\t\t\terr += dB;\n\t\t\tif (err >= dA) {\n\t\t\t\terr = err - dA;\n\t\t\t\tcell = cell + stepB;\n\t\t\t}\n\t\t}\n\t}\n\n\t//we only want to record the first position collision occurs at.\n\tprivate void collide(int cell){\n\t\tif (collisionPos == null) {\n\t\t\tcollisionPos = cell;\n\t\t}\n\t}\n\n\t//returns a segment of the path from start to end, inclusive.\n\t//if there is an error, returns an empty arraylist instead.\n\tpublic List<Integer> subPath(int start, int end){\n\t\ttry {\n\t\t\tend = Math.min( end, path.size()-1);\n\t\t\treturn path.subList(start, end+1);\n\t\t} catch (Exception e){\n\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t\treturn new ArrayList<>();\n\t\t}\n\t}\n}" }, { "identifier": "Messages", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/messages/Messages.java", "snippet": "public class Messages {\n\n\tprivate static ArrayList<I18NBundle> bundles;\n\tprivate static Languages lang;\n\tprivate static Locale locale;\n\n\tpublic static final String NO_TEXT_FOUND = \"!!!NO TEXT FOUND!!!\";\n\n\tpublic static Languages lang(){\n\t\treturn lang;\n\t}\n\n\tpublic static Locale locale(){\n\t\treturn locale;\n\t}\n\n\t/**\n\t * Setup Methods\n\t */\n\n\tprivate static String[] prop_files = new String[]{\n\t\t\tAssets.Messages.ACTORS,\n\t\t\tAssets.Messages.ITEMS,\n\t\t\tAssets.Messages.JOURNAL,\n\t\t\tAssets.Messages.LEVELS,\n\t\t\tAssets.Messages.MISC,\n\t\t\tAssets.Messages.PLANTS,\n\t\t\tAssets.Messages.SCENES,\n\t\t\tAssets.Messages.UI,\n\t\t\tAssets.Messages.WINDOWS\n\t};\n\n\tstatic{\n\t\tsetup(SPDSettings.language());\n\t}\n\n\tpublic static void setup( Languages lang ){\n\t\t//seeing as missing keys are part of our process, this is faster than throwing an exception\n\t\tI18NBundle.setExceptionOnMissingKey(false);\n\n\t\t//store language and locale info for various string logic\n\t\tMessages.lang = lang;\n\t\tif (lang == Languages.ENGLISH){\n\t\t\tlocale = Locale.ENGLISH;\n\t\t} else {\n\t\t\tlocale = new Locale(lang.code());\n\t\t}\n\n\t\t//strictly match the language code when fetching bundles however\n\t\tbundles = new ArrayList<>();\n\t\tLocale bundleLocal = new Locale(lang.code());\n\t\tfor (String file : prop_files) {\n\t\t\tbundles.add(I18NBundle.createBundle(Gdx.files.internal(file), bundleLocal));\n\t\t}\n\t}\n\n\n\n\t/**\n\t * Resource grabbing methods\n\t */\n\n\tpublic static String get(String key, Object...args){\n\t\treturn get(null, key, args);\n\t}\n\n\tpublic static String get(Object o, String k, Object...args){\n\t\treturn get(o.getClass(), k, args);\n\t}\n\n\tpublic static String get(Class c, String k, Object...args){\n\t\tString key;\n\t\tif (c != null){\n\t\t\tkey = c.getName().replace(\"com.shatteredpixel.shatteredpixeldungeon.\", \"\");\n\t\t\tkey += \".\" + k;\n\t\t} else\n\t\t\tkey = k;\n\n\t\tString value = getFromBundle(key.toLowerCase(Locale.ENGLISH));\n\t\tif (value != null){\n\t\t\tif (args.length > 0) return format(value, args);\n\t\t\telse return value;\n\t\t} else {\n\t\t\t//this is so child classes can inherit properties from their parents.\n\t\t\t//in cases where text is commonly grabbed as a utility from classes that aren't mean to be instantiated\n\t\t\t//(e.g. flavourbuff.dispTurns()) using .class directly is probably smarter to prevent unnecessary recursive calls.\n\t\t\tif (c != null && c.getSuperclass() != null){\n\t\t\t\treturn get(c.getSuperclass(), k, args);\n\t\t\t} else {\n\t\t\t\treturn NO_TEXT_FOUND;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static String getFromBundle(String key){\n\t\tString result;\n\t\tfor (I18NBundle b : bundles){\n\t\t\tresult = b.get(key);\n\t\t\t//if it isn't the return string for no key found, return it\n\t\t\tif (result.length() != key.length()+6 || !result.contains(key)){\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\n\n\t/**\n\t * String Utility Methods\n\t */\n\n\tpublic static String format( String format, Object...args ) {\n\t\ttry {\n\t\t\treturn String.format(Locale.ENGLISH, format, args);\n\t\t} catch (IllegalFormatException e) {\n\t\t\tShatteredPixelDungeon.reportException( new Exception(\"formatting error for the string: \" + format, e) );\n\t\t\treturn format;\n\t\t}\n\t}\n\n\tprivate static HashMap<String, DecimalFormat> formatters = new HashMap<>();\n\n\tpublic static String decimalFormat( String format, double number ){\n\t\tif (!formatters.containsKey(format)){\n\t\t\tformatters.put(format, new DecimalFormat(format, DecimalFormatSymbols.getInstance(Locale.ENGLISH)));\n\t\t}\n\t\treturn formatters.get(format).format(number);\n\t}\n\n\tpublic static String capitalize( String str ){\n\t\tif (str.length() == 0) return str;\n\t\telse return str.substring( 0, 1 ).toUpperCase(locale) + str.substring( 1 );\n\t}\n\n\t//Words which should not be capitalized in title case, mostly prepositions which appear ingame\n\t//This list is not comprehensive!\n\tprivate static final HashSet<String> noCaps = new HashSet<>(\n\t\t\tArrays.asList(\"a\", \"an\", \"and\", \"of\", \"by\", \"to\", \"the\", \"x\", \"for\")\n\t);\n\n\tpublic static String titleCase( String str ){\n\t\t//English capitalizes every word except for a few exceptions\n\t\tif (lang == Languages.ENGLISH){\n\t\t\tString result = \"\";\n\t\t\t//split by any unicode space character\n\t\t\tfor (String word : str.split(\"(?<=\\\\p{Zs})\")){\n\t\t\t\tif (noCaps.contains(word.trim().toLowerCase(Locale.ENGLISH).replaceAll(\":|[0-9]\", \"\"))){\n\t\t\t\t\tresult += word;\n\t\t\t\t} else {\n\t\t\t\t\tresult += capitalize(word);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//first character is always capitalized.\n\t\t\treturn capitalize(result);\n\t\t}\n\n\t\t//Otherwise, use sentence case\n\t\treturn capitalize(str);\n\t}\n\n\tpublic static String upperCase( String str ){\n\t\treturn str.toUpperCase(locale);\n\t}\n\n\tpublic static String lowerCase( String str ){\n\t\treturn str.toLowerCase(locale);\n\t}\n}" }, { "identifier": "GameScene", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/scenes/GameScene.java", "snippet": "public class GameScene extends PixelScene {\n\n\tstatic GameScene scene;\n\n\tprivate SkinnedBlock water;\n\tprivate DungeonTerrainTilemap tiles;\n\tprivate GridTileMap visualGrid;\n\tprivate TerrainFeaturesTilemap terrainFeatures;\n\tprivate RaisedTerrainTilemap raisedTerrain;\n\tprivate DungeonWallsTilemap walls;\n\tprivate WallBlockingTilemap wallBlocking;\n\tprivate FogOfWar fog;\n\tprivate HeroSprite hero;\n\n\tprivate MenuPane menu;\n\tprivate StatusPane status;\n\n\tprivate BossHealthBar boss;\n\n\tprivate GameLog log;\n\t\n\tprivate static CellSelector cellSelector;\n\t\n\tprivate Group terrain;\n\tprivate Group customTiles;\n\tprivate Group levelVisuals;\n\tprivate Group levelWallVisuals;\n\tprivate Group customWalls;\n\tprivate Group ripples;\n\tprivate Group plants;\n\tprivate Group traps;\n\tprivate Group heaps;\n\tprivate Group mobs;\n\tprivate Group floorEmitters;\n\tprivate Group emitters;\n\tprivate Group effects;\n\tprivate Group gases;\n\tprivate Group spells;\n\tprivate Group statuses;\n\tprivate Group emoicons;\n\tprivate Group overFogEffects;\n\tprivate Group healthIndicators;\n\n\tprivate InventoryPane inventory;\n\tprivate static boolean invVisible = true;\n\n\tprivate Toolbar toolbar;\n\tprivate Toast prompt;\n\n\tprivate AttackIndicator attack;\n\tprivate LootIndicator loot;\n\tprivate ActionIndicator action;\n\tprivate ResumeIndicator resume;\n\n\t{\n\t\tinGameScene = true;\n\t}\n\t\n\t@Override\n\tpublic void create() {\n\t\t\n\t\tif (Dungeon.hero == null || Dungeon.level == null){\n\t\t\tShatteredPixelDungeon.switchNoFade(TitleScene.class);\n\t\t\treturn;\n\t\t}\n\n\t\tDungeon.level.playLevelMusic();\n\n\t\tSPDSettings.lastClass(Dungeon.hero.heroClass.ordinal());\n\t\t\n\t\tsuper.create();\n\t\tCamera.main.zoom( GameMath.gate(minZoom, defaultZoom + SPDSettings.zoom(), maxZoom));\n\t\tCamera.main.edgeScroll.set(1);\n\n\t\tswitch (SPDSettings.cameraFollow()) {\n\t\t\tcase 4: default: Camera.main.setFollowDeadzone(0); break;\n\t\t\tcase 3: Camera.main.setFollowDeadzone(0.2f); break;\n\t\t\tcase 2: Camera.main.setFollowDeadzone(0.5f); break;\n\t\t\tcase 1: Camera.main.setFollowDeadzone(0.9f); break;\n\t\t}\n\n\t\tscene = this;\n\n\t\tterrain = new Group();\n\t\tadd( terrain );\n\n\t\twater = new SkinnedBlock(\n\t\t\tDungeon.level.width() * DungeonTilemap.SIZE,\n\t\t\tDungeon.level.height() * DungeonTilemap.SIZE,\n\t\t\tDungeon.level.waterTex() ){\n\n\t\t\t@Override\n\t\t\tprotected NoosaScript script() {\n\t\t\t\treturn NoosaScriptNoLighting.get();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void draw() {\n\t\t\t\t//water has no alpha component, this improves performance\n\t\t\t\tBlending.disable();\n\t\t\t\tsuper.draw();\n\t\t\t\tBlending.enable();\n\t\t\t}\n\t\t};\n\t\twater.autoAdjust = true;\n\t\tterrain.add( water );\n\n\t\tripples = new Group();\n\t\tterrain.add( ripples );\n\n\t\tDungeonTileSheet.setupVariance(Dungeon.level.map.length, Dungeon.seedCurDepth());\n\t\t\n\t\ttiles = new DungeonTerrainTilemap();\n\t\tterrain.add( tiles );\n\n\t\tcustomTiles = new Group();\n\t\tterrain.add(customTiles);\n\n\t\tfor( CustomTilemap visual : Dungeon.level.customTiles){\n\t\t\taddCustomTile(visual);\n\t\t}\n\n\t\tvisualGrid = new GridTileMap();\n\t\tterrain.add( visualGrid );\n\n\t\tterrainFeatures = new TerrainFeaturesTilemap(Dungeon.level.plants, Dungeon.level.traps);\n\t\tterrain.add(terrainFeatures);\n\t\t\n\t\tlevelVisuals = Dungeon.level.addVisuals();\n\t\tadd(levelVisuals);\n\n\t\tfloorEmitters = new Group();\n\t\tadd(floorEmitters);\n\n\t\theaps = new Group();\n\t\tadd( heaps );\n\t\t\n\t\tfor ( Heap heap : Dungeon.level.heaps.valueList() ) {\n\t\t\taddHeapSprite( heap );\n\t\t}\n\n\t\temitters = new Group();\n\t\teffects = new Group();\n\t\thealthIndicators = new Group();\n\t\temoicons = new Group();\n\t\toverFogEffects = new Group();\n\t\t\n\t\tmobs = new Group();\n\t\tadd( mobs );\n\n\t\thero = new HeroSprite();\n\t\thero.place( Dungeon.hero.pos );\n\t\thero.updateArmor();\n\t\tmobs.add( hero );\n\t\t\n\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\taddMobSprite( mob );\n\t\t}\n\t\t\n\t\traisedTerrain = new RaisedTerrainTilemap();\n\t\tadd( raisedTerrain );\n\n\t\twalls = new DungeonWallsTilemap();\n\t\tadd(walls);\n\n\t\tcustomWalls = new Group();\n\t\tadd(customWalls);\n\n\t\tfor( CustomTilemap visual : Dungeon.level.customWalls){\n\t\t\taddCustomWall(visual);\n\t\t}\n\n\t\tlevelWallVisuals = Dungeon.level.addWallVisuals();\n\t\tadd( levelWallVisuals );\n\n\t\twallBlocking = new WallBlockingTilemap();\n\t\tadd (wallBlocking);\n\n\t\tadd( emitters );\n\t\tadd( effects );\n\n\t\tgases = new Group();\n\t\tadd( gases );\n\n\t\tfor (Blob blob : Dungeon.level.blobs.values()) {\n\t\t\tblob.emitter = null;\n\t\t\taddBlobSprite( blob );\n\t\t}\n\n\n\t\tfog = new FogOfWar( Dungeon.level.width(), Dungeon.level.height() );\n\t\tadd( fog );\n\n\t\tspells = new Group();\n\t\tadd( spells );\n\n\t\tadd(overFogEffects);\n\t\t\n\t\tstatuses = new Group();\n\t\tadd( statuses );\n\t\t\n\t\tadd( healthIndicators );\n\t\t//always appears ontop of other health indicators\n\t\tadd( new TargetHealthIndicator() );\n\t\t\n\t\tadd( emoicons );\n\t\t\n\t\tadd( cellSelector = new CellSelector( tiles ) );\n\n\t\tint uiSize = SPDSettings.interfaceSize();\n\n\t\tmenu = new MenuPane();\n\t\tmenu.camera = uiCamera;\n\t\tmenu.setPos( uiCamera.width-MenuPane.WIDTH, uiSize > 0 ? 0 : 1);\n\t\tadd(menu);\n\n\t\tstatus = new StatusPane( SPDSettings.interfaceSize() > 0 );\n\t\tstatus.camera = uiCamera;\n\t\tstatus.setRect(0, uiSize > 0 ? uiCamera.height-39 : 0, uiCamera.width, 0 );\n\t\tadd(status);\n\n\t\tboss = new BossHealthBar();\n\t\tboss.camera = uiCamera;\n\t\tboss.setPos( 6 + (uiCamera.width - boss.width())/2, 20);\n\t\tadd(boss);\n\n\t\tresume = new ResumeIndicator();\n\t\tresume.camera = uiCamera;\n\t\tadd( resume );\n\n\t\taction = new ActionIndicator();\n\t\taction.camera = uiCamera;\n\t\tadd( action );\n\n\t\tloot = new LootIndicator();\n\t\tloot.camera = uiCamera;\n\t\tadd( loot );\n\n\t\tattack = new AttackIndicator();\n\t\tattack.camera = uiCamera;\n\t\tadd( attack );\n\n\t\tlog = new GameLog();\n\t\tlog.camera = uiCamera;\n\t\tlog.newLine();\n\t\tadd( log );\n\n\t\tif (uiSize > 0){\n\t\t\tbringToFront(status);\n\t\t}\n\n\t\ttoolbar = new Toolbar();\n\t\ttoolbar.camera = uiCamera;\n\t\tadd( toolbar );\n\n\t\tif (uiSize == 2) {\n\t\t\tinventory = new InventoryPane();\n\t\t\tinventory.camera = uiCamera;\n\t\t\tinventory.setPos(uiCamera.width - inventory.width(), uiCamera.height - inventory.height());\n\t\t\tadd(inventory);\n\n\t\t\ttoolbar.setRect( 0, uiCamera.height - toolbar.height() - inventory.height(), uiCamera.width, toolbar.height() );\n\t\t} else {\n\t\t\ttoolbar.setRect( 0, uiCamera.height - toolbar.height(), uiCamera.width, toolbar.height() );\n\t\t}\n\n\t\tlayoutTags();\n\t\t\n\t\tswitch (InterlevelScene.mode) {\n\t\t\tcase RESURRECT:\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TELEPORT);\n\t\t\t\tScrollOfTeleportation.appearVFX( Dungeon.hero );\n\t\t\t\tSpellSprite.show(Dungeon.hero, SpellSprite.ANKH);\n\t\t\t\tnew Flare( 5, 16 ).color( 0xFFFF00, true ).show( hero, 4f ) ;\n\t\t\t\tbreak;\n\t\t\tcase RETURN:\n\t\t\t\tScrollOfTeleportation.appearVFX( Dungeon.hero );\n\t\t\t\tbreak;\n\t\t\tcase DESCEND:\n\t\t\tcase FALL:\n\t\t\t\tif (Dungeon.depth == Statistics.deepestFloor){\n\t\t\t\t\tswitch (Dungeon.depth) {\n\t\t\t\t\t\tcase 1: case 6: case 11: case 16: case 21:\n\t\t\t\t\t\t\tint region = (Dungeon.depth+4)/5;\n\t\t\t\t\t\t\tif (!Document.INTROS.isPageRead(region)) {\n\t\t\t\t\t\t\t\tadd(new WndStory(Document.INTROS.pageBody(region)).setDelays(0.6f, 1.4f));\n\t\t\t\t\t\t\t\tDocument.INTROS.readPage(region);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (Dungeon.hero.isAlive()) {\n\t\t\t\t\tBadges.validateNoKilling();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\n\t\tArrayList<Item> dropped = Dungeon.droppedItems.get( Dungeon.depth );\n\t\tif (dropped != null) {\n\t\t\tfor (Item item : dropped) {\n\t\t\t\tint pos = Dungeon.level.randomRespawnCell( null );\n\t\t\t\tif (pos == -1) pos = Dungeon.level.entrance();\n\t\t\t\tif (item instanceof Potion) {\n\t\t\t\t\t((Potion) item).shatter(pos);\n\t\t\t\t} else if (item instanceof Plant.Seed && !Dungeon.isChallenged(Challenges.NO_HERBALISM)) {\n\t\t\t\t\tDungeon.level.plant((Plant.Seed) item, pos);\n\t\t\t\t} else if (item instanceof Honeypot) {\n\t\t\t\t\tDungeon.level.drop(((Honeypot) item).shatter(null, pos), pos);\n\t\t\t\t} else {\n\t\t\t\t\tDungeon.level.drop(item, pos);\n\t\t\t\t}\n\t\t\t}\n\t\t\tDungeon.droppedItems.remove( Dungeon.depth );\n\t\t}\n\n\t\tDungeon.hero.next();\n\n\t\tswitch (InterlevelScene.mode){\n\t\t\tcase FALL: case DESCEND: case CONTINUE:\n\t\t\t\tCamera.main.snapTo(hero.center().x, hero.center().y - DungeonTilemap.SIZE * (defaultZoom/Camera.main.zoom));\n\t\t\t\tbreak;\n\t\t\tcase ASCEND:\n\t\t\t\tCamera.main.snapTo(hero.center().x, hero.center().y + DungeonTilemap.SIZE * (defaultZoom/Camera.main.zoom));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tCamera.main.snapTo(hero.center().x, hero.center().y);\n\t\t}\n\t\tCamera.main.panTo(hero.center(), 2.5f);\n\n\t\tif (InterlevelScene.mode != InterlevelScene.Mode.NONE) {\n\t\t\tif (Dungeon.depth == Statistics.deepestFloor\n\t\t\t\t\t&& (InterlevelScene.mode == InterlevelScene.Mode.DESCEND || InterlevelScene.mode == InterlevelScene.Mode.FALL)) {\n\t\t\t\tGLog.h(Messages.get(this, \"descend\"), Dungeon.depth);\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.DESCEND);\n\t\t\t\t\n\t\t\t\tfor (Char ch : Actor.chars()){\n\t\t\t\t\tif (ch instanceof DriedRose.GhostHero){\n\t\t\t\t\t\t((DriedRose.GhostHero) ch).sayAppeared();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tint spawnersAbove = Statistics.spawnersAlive;\n\t\t\t\tif (spawnersAbove > 0 && Dungeon.depth <= 25) {\n\t\t\t\t\tfor (Mob m : Dungeon.level.mobs) {\n\t\t\t\t\t\tif (m instanceof DemonSpawner && ((DemonSpawner) m).spawnRecorded) {\n\t\t\t\t\t\t\tspawnersAbove--;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (spawnersAbove > 0) {\n\t\t\t\t\t\tif (Dungeon.bossLevel()) {\n\t\t\t\t\t\t\tGLog.n(Messages.get(this, \"spawner_warn_final\"));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tGLog.n(Messages.get(this, \"spawner_warn\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t} else if (InterlevelScene.mode == InterlevelScene.Mode.RESET) {\n\t\t\t\tGLog.h(Messages.get(this, \"warp\"));\n\t\t\t} else if (InterlevelScene.mode == InterlevelScene.Mode.RESURRECT) {\n\t\t\t\tGLog.h(Messages.get(this, \"resurrect\"), Dungeon.depth);\n\t\t\t} else {\n\t\t\t\tGLog.h(Messages.get(this, \"return\"), Dungeon.depth);\n\t\t\t}\n\n\t\t\tif (Dungeon.hero.hasTalent(Talent.ROGUES_FORESIGHT)\n\t\t\t\t\t&& Dungeon.level instanceof RegularLevel && Dungeon.branch == 0){\n\t\t\t\tint reqSecrets = Dungeon.level.feeling == Level.Feeling.SECRETS ? 2 : 1;\n\t\t\t\tfor (Room r : ((RegularLevel) Dungeon.level).rooms()){\n\t\t\t\t\tif (r instanceof SecretRoom) reqSecrets--;\n\t\t\t\t}\n\n\t\t\t\t//50%/75% chance, use level's seed so that we get the same result for the same level\n\t\t\t\t//offset seed slightly to avoid output patterns\n\t\t\t\tRandom.pushGenerator(Dungeon.seedCurDepth()+1);\n\t\t\t\t\tif (reqSecrets <= 0 && Random.Int(4) <= Dungeon.hero.pointsInTalent(Talent.ROGUES_FORESIGHT)){\n\t\t\t\t\t\tGLog.p(Messages.get(this, \"secret_hint\"));\n\t\t\t\t\t}\n\t\t\t\tRandom.popGenerator();\n\t\t\t}\n\n\t\t\tboolean unspentTalents = false;\n\t\t\tfor (int i = 1; i <= Dungeon.hero.talents.size(); i++){\n\t\t\t\tif (Dungeon.hero.talentPointsAvailable(i) > 0){\n\t\t\t\t\tunspentTalents = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (unspentTalents){\n\t\t\t\tGLog.newLine();\n\t\t\t\tGLog.w( Messages.get(Dungeon.hero, \"unspent\") );\n\t\t\t\tStatusPane.talentBlink = 10f;\n\t\t\t\tWndHero.lastIdx = 1;\n\t\t\t}\n\n\t\t\tswitch (Dungeon.level.feeling) {\n\t\t\t\tcase CHASM: GLog.w(Messages.get(this, \"chasm\")); break;\n\t\t\t\tcase WATER: GLog.w(Messages.get(this, \"water\")); break;\n\t\t\t\tcase GRASS: GLog.w(Messages.get(this, \"grass\")); break;\n\t\t\t\tcase DARK: GLog.w(Messages.get(this, \"dark\")); break;\n\t\t\t\tcase LARGE: GLog.w(Messages.get(this, \"large\")); break;\n\t\t\t\tcase TRAPS: GLog.w(Messages.get(this, \"traps\")); break;\n\t\t\t\tcase SECRETS: GLog.w(Messages.get(this, \"secrets\")); break;\n\t\t\t}\n\n\t\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\t\tif (!mob.buffs(ChampionEnemy.class).isEmpty()) {\n\t\t\t\t\tGLog.w(Messages.get(ChampionEnemy.class, \"warn\"));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Dungeon.hero.buff(AscensionChallenge.class) != null){\n\t\t\t\tDungeon.hero.buff(AscensionChallenge.class).saySwitch();\n\t\t\t}\n\n\t\t\tif (Dungeon.hero.buff(OldAmulet.TempleCurse.class) != null) {\n\t\t\t\tDungeon.hero.buff(OldAmulet.TempleCurse.class).saySwitch();\n\t\t\t\tif (Dungeon.branch == 0) {\n\t\t\t\t\tfor (LevelTransition transition : Dungeon.level.transitions) {\n\t\t\t\t\t\tif (transition.type == LevelTransition.Type.BRANCH_EXIT && transition.destBranch == 2) {\n\t\t\t\t\t\t\tint cell = transition.cell();\n\t\t\t\t\t\t\tLevel.set(cell, Terrain.WALL);\n\t\t\t\t\t\t\tGameScene.updateMap(cell);\n\t\t\t\t\t\t\tif (Dungeon.level.heroFOV[ cell ]) {\n\t\t\t\t\t\t\t\tCellEmitter.get( cell - Dungeon.level.width() ).start(Speck.factory(Speck.ROCK), 0.07f, 10);\n\n\t\t\t\t\t\t\t\tPixelScene.shake(3, 0.7f);\n\t\t\t\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.ROCKS);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tint targetCell = cell+Dungeon.level.width();\n\t\t\t\t\t\t\tActor.add(new Pushing(Dungeon.hero, cell, targetCell, new Callback() {\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\t\t\t\tDungeon.hero.pos = targetCell;\n\t\t\t\t\t\t\t\t\tDungeon.hero.move(targetCell);\n\t\t\t\t\t\t\t\t\tDungeon.level.occupyCell(Dungeon.hero);\n\t\t\t\t\t\t\t\t\tDungeon.observe();\n\t\t\t\t\t\t\t\t\tGameScene.updateFog();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\tDungeon.level.transitions.remove(transition);\n\n\t\t\t\t\t\t\tDungeon.hero.busy();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tDungeon.hero.buff(OldAmulet.TempleCurse.class).detach();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tInterlevelScene.mode = InterlevelScene.Mode.NONE;\n\n\t\t\t\n\t\t}\n\n\t\t//Tutorial\n\t\tif (SPDSettings.intro()){\n\n\t\t\tif (Document.ADVENTURERS_GUIDE.isPageFound(Document.GUIDE_INTRO)){\n\t\t\t\tGLog.p(Messages.get(GameScene.class, \"tutorial_guidebook\"));\n\t\t\t\tflashForDocument(Document.ADVENTURERS_GUIDE, Document.GUIDE_INTRO);\n\t\t\t} else {\n\t\t\t\tif (ControllerHandler.isControllerConnected()) {\n\t\t\t\t\tGLog.p(Messages.get(GameScene.class, \"tutorial_move_controller\"));\n\t\t\t\t} else if (SPDSettings.interfaceSize() == 0) {\n\t\t\t\t\tGLog.p(Messages.get(GameScene.class, \"tutorial_move_mobile\"));\n\t\t\t\t} else {\n\t\t\t\t\tGLog.p(Messages.get(GameScene.class, \"tutorial_move_desktop\"));\n\t\t\t\t}\n\t\t\t}\n\t\t\ttoolbar.visible = toolbar.active = false;\n\t\t\tstatus.visible = status.active = false;\n\t\t\tif (inventory != null) inventory.visible = inventory.active = false;\n\t\t}\n\n\t\tif (!SPDSettings.intro() &&\n\t\t\t\tRankings.INSTANCE.totalNumber > 0 &&\n\t\t\t\t!Document.ADVENTURERS_GUIDE.isPageRead(Document.GUIDE_DIEING)){\n\t\t\tGLog.p(Messages.get(Guidebook.class, \"hint\"));\n\t\t\tGameScene.flashForDocument(Document.ADVENTURERS_GUIDE, Document.GUIDE_DIEING);\n\t\t}\n\n\t\tif (!invVisible) toggleInvPane();\n\t\tfadeIn();\n\n\t\t//re-show WndResurrect if needed\n\t\tif (!Dungeon.hero.isAlive()){\n\t\t\t//check if hero has an unblessed ankh\n\t\t\tAnkh ankh = null;\n\t\t\tfor (Ankh i : Dungeon.hero.belongings.getAllItems(Ankh.class)){\n\t\t\t\tif (!i.isBlessed()){\n\t\t\t\t\tankh = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ankh != null && GamesInProgress.gameExists(GamesInProgress.curSlot)) {\n\t\t\t\tadd(new WndResurrect(ankh));\n\t\t\t} else {\n\t\t\t\tgameOver();\n\t\t\t}\n\t\t}\n\n\t}\n\t\n\tpublic void destroy() {\n\t\t\n\t\t//tell the actor thread to finish, then wait for it to complete any actions it may be doing.\n\t\tif (!waitForActorThread( 4500, true )){\n\t\t\tThrowable t = new Throwable();\n\t\t\tt.setStackTrace(actorThread.getStackTrace());\n\t\t\tthrow new RuntimeException(\"timeout waiting for actor thread! \", t);\n\t\t}\n\n\t\tEmitter.freezeEmitters = false;\n\t\t\n\t\tscene = null;\n\t\tBadges.saveGlobal();\n\t\tJournal.saveGlobal();\n\t\t\n\t\tsuper.destroy();\n\t}\n\t\n\tpublic static void endActorThread(){\n\t\tif (actorThread != null && actorThread.isAlive()){\n\t\t\tActor.keepActorThreadAlive = false;\n\t\t\tactorThread.interrupt();\n\t\t}\n\t}\n\n\tpublic boolean waitForActorThread(int msToWait, boolean interrupt){\n\t\tif (actorThread == null || !actorThread.isAlive()) {\n\t\t\treturn true;\n\t\t}\n\t\tsynchronized (actorThread) {\n\t\t\tif (interrupt) actorThread.interrupt();\n\t\t\ttry {\n\t\t\t\tactorThread.wait(msToWait);\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t\t}\n\t\t\treturn !Actor.processing();\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic synchronized void onPause() {\n\t\ttry {\n\t\t\tDungeon.saveAll();\n\t\t\tBadges.saveGlobal();\n\t\t\tJournal.saveGlobal();\n\t\t} catch (IOException e) {\n\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t}\n\t}\n\n\tprivate static Thread actorThread;\n\t\n\t//sometimes UI changes can be prompted by the actor thread.\n\t// We queue any removed element destruction, rather than destroying them in the actor thread.\n\tprivate ArrayList<Gizmo> toDestroy = new ArrayList<>();\n\n\t//the actor thread processes at a maximum of 60 times a second\n\t//this caps the speed of resting for higher refresh rate displays\n\tprivate float notifyDelay = 1/60f;\n\n\tpublic static boolean updateItemDisplays = false;\n\n\tpublic static boolean tagDisappeared = false;\n\tpublic static boolean updateTags = false;\n\t\n\t@Override\n\tpublic synchronized void update() {\n\t\tlastOffset = null;\n\n\t\tif (updateItemDisplays){\n\t\t\tupdateItemDisplays = false;\n\t\t\tQuickSlotButton.refresh();\n\t\t\tInventoryPane.refresh();\n\t\t}\n\n\t\tif (Dungeon.hero == null || scene == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tsuper.update();\n\n\t\tif (notifyDelay > 0) notifyDelay -= Game.elapsed;\n\n\t\tif (!Emitter.freezeEmitters) water.offset( 0, -5 * Game.elapsed );\n\n\t\tif (!Actor.processing() && Dungeon.hero.isAlive()) {\n\t\t\tif (actorThread == null || !actorThread.isAlive()) {\n\t\t\t\t\n\t\t\t\tactorThread = new Thread() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\tActor.process();\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\t//if cpu cores are limited, game should prefer drawing the current frame\n\t\t\t\tif (Runtime.getRuntime().availableProcessors() == 1) {\n\t\t\t\t\tactorThread.setPriority(Thread.NORM_PRIORITY - 1);\n\t\t\t\t}\n\t\t\t\tactorThread.setName(\"SHPD Actor Thread\");\n\t\t\t\tThread.currentThread().setName(\"SHPD Render Thread\");\n\t\t\t\tActor.keepActorThreadAlive = true;\n\t\t\t\tactorThread.start();\n\t\t\t} else if (notifyDelay <= 0f) {\n\t\t\t\tnotifyDelay += 1/60f;\n\t\t\t\tsynchronized (actorThread) {\n\t\t\t\t\tactorThread.notify();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.hero.ready && Dungeon.hero.paralysed == 0) {\n\t\t\tlog.newLine();\n\t\t}\n\n\t\tif (updateTags){\n\t\t\ttagAttack = attack.active;\n\t\t\ttagLoot = loot.visible;\n\t\t\ttagAction = action.visible;\n\t\t\ttagResume = resume.visible;\n\n\t\t\tlayoutTags();\n\n\t\t} else if (tagAttack != attack.active ||\n\t\t\t\ttagLoot != loot.visible ||\n\t\t\t\ttagAction != action.visible ||\n\t\t\t\ttagResume != resume.visible) {\n\n\t\t\tboolean tagAppearing = (attack.active && !tagAttack) ||\n\t\t\t\t\t\t\t\t\t(loot.visible && !tagLoot) ||\n\t\t\t\t\t\t\t\t\t(action.visible && !tagAction) ||\n\t\t\t\t\t\t\t\t\t(resume.visible && !tagResume);\n\n\t\t\ttagAttack = attack.active;\n\t\t\ttagLoot = loot.visible;\n\t\t\ttagAction = action.visible;\n\t\t\ttagResume = resume.visible;\n\n\t\t\t//if a new tag appears, re-layout tags immediately\n\t\t\t//otherwise, wait until the hero acts, so as to not suddenly change their position\n\t\t\tif (tagAppearing) layoutTags();\n\t\t\telse tagDisappeared = true;\n\n\t\t}\n\n\t\tcellSelector.enable(Dungeon.hero.ready);\n\t\t\n\t\tfor (Gizmo g : toDestroy){\n\t\t\tg.destroy();\n\t\t}\n\t\ttoDestroy.clear();\n\t}\n\n\tprivate static Point lastOffset = null;\n\n\t@Override\n\tpublic synchronized Gizmo erase (Gizmo g) {\n\t\tGizmo result = super.erase(g);\n\t\tif (result instanceof Window){\n\t\t\tlastOffset = ((Window) result).getOffset();\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate boolean tagAttack = false;\n\tprivate boolean tagLoot = false;\n\tprivate boolean tagAction = false;\n\tprivate boolean tagResume = false;\n\n\tpublic static void layoutTags() {\n\n\t\tupdateTags = false;\n\n\t\tif (scene == null) return;\n\n\t\t//move the camera center up a bit if we're on full UI and it is taking up lots of space\n\t\tif (scene.inventory != null && scene.inventory.visible\n\t\t\t\t&& (uiCamera.width < 460 && uiCamera.height < 300)){\n\t\t\tCamera.main.setCenterOffset(0, Math.min(300-uiCamera.height, 460-uiCamera.width) / Camera.main.zoom);\n\t\t} else {\n\t\t\tCamera.main.setCenterOffset(0, 0);\n\t\t}\n\t\t//Camera.main.panTo(Dungeon.hero.sprite.center(), 5f);\n\n\t\t//primarily for phones displays with notches\n\t\t//TODO Android never draws into notch atm, perhaps allow it for center notches?\n\t\tRectF insets = DeviceCompat.getSafeInsets();\n\t\tinsets = insets.scale(1f / uiCamera.zoom);\n\n\t\tboolean tagsOnLeft = SPDSettings.flipTags();\n\t\tfloat tagWidth = Tag.SIZE + (tagsOnLeft ? insets.left : insets.right);\n\t\tfloat tagLeft = tagsOnLeft ? 0 : uiCamera.width - tagWidth;\n\n\t\tfloat y = SPDSettings.interfaceSize() == 0 ? scene.toolbar.top()-2 : scene.status.top()-2;\n\t\tif (SPDSettings.interfaceSize() == 0){\n\t\t\tif (tagsOnLeft) {\n\t\t\t\tscene.log.setRect(tagWidth, y, uiCamera.width - tagWidth - insets.right, 0);\n\t\t\t} else {\n\t\t\t\tscene.log.setRect(insets.left, y, uiCamera.width - tagWidth - insets.left, 0);\n\t\t\t}\n\t\t} else {\n\t\t\tif (tagsOnLeft) {\n\t\t\t\tscene.log.setRect(tagWidth, y, 160 - tagWidth, 0);\n\t\t\t} else {\n\t\t\t\tscene.log.setRect(insets.left, y, 160 - insets.left, 0);\n\t\t\t}\n\t\t}\n\n\t\tfloat pos = scene.toolbar.top();\n\t\tif (tagsOnLeft && SPDSettings.interfaceSize() > 0){\n\t\t\tpos = scene.status.top();\n\t\t}\n\n\t\tif (scene.tagAttack){\n\t\t\tscene.attack.setRect( tagLeft, pos - Tag.SIZE, tagWidth, Tag.SIZE );\n\t\t\tscene.attack.flip(tagsOnLeft);\n\t\t\tpos = scene.attack.top();\n\t\t}\n\n\t\tif (scene.tagLoot) {\n\t\t\tscene.loot.setRect( tagLeft, pos - Tag.SIZE, tagWidth, Tag.SIZE );\n\t\t\tscene.loot.flip(tagsOnLeft);\n\t\t\tpos = scene.loot.top();\n\t\t}\n\n\t\tif (scene.tagAction) {\n\t\t\tscene.action.setRect( tagLeft, pos - Tag.SIZE, tagWidth, Tag.SIZE );\n\t\t\tscene.action.flip(tagsOnLeft);\n\t\t\tpos = scene.action.top();\n\t\t}\n\n\t\tif (scene.tagResume) {\n\t\t\tscene.resume.setRect( tagLeft, pos - Tag.SIZE, tagWidth, Tag.SIZE );\n\t\t\tscene.resume.flip(tagsOnLeft);\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected void onBackPressed() {\n\t\tif (!cancel()) {\n\t\t\tadd( new WndGame() );\n\t\t}\n\t}\n\n\tpublic void addCustomTile( CustomTilemap visual){\n\t\tcustomTiles.add( visual.create() );\n\t}\n\n\tpublic void addCustomWall( CustomTilemap visual){\n\t\tcustomWalls.add( visual.create() );\n\t}\n\t\n\tprivate void addHeapSprite( Heap heap ) {\n\t\tItemSprite sprite = heap.sprite = (ItemSprite)heaps.recycle( ItemSprite.class );\n\t\tsprite.revive();\n\t\tsprite.link( heap );\n\t\theaps.add( sprite );\n\t}\n\t\n\tprivate void addDiscardedSprite( Heap heap ) {\n\t\theap.sprite = (DiscardedItemSprite)heaps.recycle( DiscardedItemSprite.class );\n\t\theap.sprite.revive();\n\t\theap.sprite.link( heap );\n\t\theaps.add( heap.sprite );\n\t}\n\t\n\tprivate void addPlantSprite( Plant plant ) {\n\n\t}\n\n\tprivate void addTrapSprite( Trap trap ) {\n\n\t}\n\t\n\tprivate void addBlobSprite( final Blob gas ) {\n\t\tif (gas.emitter == null) {\n\t\t\tgases.add( new BlobEmitter( gas ) );\n\t\t}\n\t}\n\t\n\tprivate synchronized void addMobSprite( Mob mob ) {\n\t\tCharSprite sprite = mob.sprite();\n\t\tsprite.visible = Dungeon.level.heroFOV[mob.pos];\n\t\tmobs.add( sprite );\n\t\tsprite.link( mob );\n\t\tsortMobSprites();\n\t}\n\n\t//ensures that mob sprites are drawn from top to bottom, in case of overlap\n\tpublic static void sortMobSprites(){\n\t\tif (scene != null){\n\t\t\tsynchronized (scene) {\n\t\t\t\tscene.mobs.sort(new Comparator() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic int compare(Object a, Object b) {\n\t\t\t\t\t\t//elements that aren't visual go to the end of the list\n\t\t\t\t\t\tif (a instanceof Visual && b instanceof Visual) {\n\t\t\t\t\t\t\treturn (int) Math.signum((((Visual) a).y + ((Visual) a).height())\n\t\t\t\t\t\t\t\t\t- (((Visual) b).y + ((Visual) b).height()));\n\t\t\t\t\t\t} else if (a instanceof Visual){\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t} else if (b instanceof Visual){\n\t\t\t\t\t\t\treturn 1;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate synchronized void prompt( String text ) {\n\t\t\n\t\tif (prompt != null) {\n\t\t\tprompt.killAndErase();\n\t\t\ttoDestroy.add(prompt);\n\t\t\tprompt = null;\n\t\t}\n\t\t\n\t\tif (text != null) {\n\t\t\tprompt = new Toast( text ) {\n\t\t\t\t@Override\n\t\t\t\tprotected void onClose() {\n\t\t\t\t\tcancel();\n\t\t\t\t}\n\t\t\t};\n\t\t\tprompt.camera = uiCamera;\n\t\t\tprompt.setPos( (uiCamera.width - prompt.width()) / 2, uiCamera.height - 60 );\n\n\t\t\tif (inventory != null && inventory.visible && prompt.right() > inventory.left() - 10){\n\t\t\t\tprompt.setPos(inventory.left() - prompt.width() - 10, prompt.top());\n\t\t\t}\n\n\t\t\tadd( prompt );\n\t\t}\n\t}\n\t\n\tprivate void showBanner( Banner banner ) {\n\t\tbanner.camera = uiCamera;\n\n\t\tfloat offset = Camera.main.centerOffset.y;\n\t\tbanner.x = align( uiCamera, (uiCamera.width - banner.width) / 2 );\n\t\tbanner.y = align( uiCamera, (uiCamera.height - banner.height) / 2 - banner.height/2 - 16 - offset );\n\n\t\taddToFront( banner );\n\t}\n\t\n\t// -------------------------------------------------------\n\n\tpublic static void add( Plant plant ) {\n\t\tif (scene != null) {\n\t\t\tscene.addPlantSprite( plant );\n\t\t}\n\t}\n\n\tpublic static void add( Trap trap ) {\n\t\tif (scene != null) {\n\t\t\tscene.addTrapSprite( trap );\n\t\t}\n\t}\n\t\n\tpublic static void add( Blob gas ) {\n\t\tActor.add( gas );\n\t\tif (scene != null) {\n\t\t\tscene.addBlobSprite( gas );\n\t\t}\n\t}\n\t\n\tpublic static void add( Heap heap ) {\n\t\tif (scene != null) {\n\t\t\t//heaps that aren't added as part of levelgen don't count for exploration bonus\n\t\t\theap.autoExplored = true;\n\t\t\tscene.addHeapSprite( heap );\n\t\t}\n\t}\n\t\n\tpublic static void discard( Heap heap ) {\n\t\tif (scene != null) {\n\t\t\tscene.addDiscardedSprite( heap );\n\t\t}\n\t}\n\t\n\tpublic static void add( Mob mob ) {\n\t\tDungeon.level.mobs.add( mob );\n\t\tif (scene != null) {\n\t\t\tscene.addMobSprite(mob);\n\t\t\tActor.add(mob);\n\t\t}\n\t}\n\n\tpublic static void addSprite( Mob mob ) {\n\t\tscene.addMobSprite( mob );\n\t}\n\t\n\tpublic static void add( Mob mob, float delay ) {\n\t\tDungeon.level.mobs.add( mob );\n\t\tscene.addMobSprite( mob );\n\t\tActor.addDelayed( mob, delay );\n\t}\n\t\n\tpublic static void add( EmoIcon icon ) {\n\t\tscene.emoicons.add( icon );\n\t}\n\t\n\tpublic static void add( CharHealthIndicator indicator ){\n\t\tif (scene != null) scene.healthIndicators.add(indicator);\n\t}\n\t\n\tpublic static void add( CustomTilemap t, boolean wall ){\n\t\tif (scene == null) return;\n\t\tif (wall){\n\t\t\tscene.addCustomWall(t);\n\t\t} else {\n\t\t\tscene.addCustomTile(t);\n\t\t}\n\t}\n\t\n\tpublic static void effect( Visual effect ) {\n\t\tif (scene != null) scene.effects.add( effect );\n\t}\n\n\tpublic static void effectOverFog( Visual effect ) {\n\t\tscene.overFogEffects.add( effect );\n\t}\n\t\n\tpublic static Ripple ripple( int pos ) {\n\t\tif (scene != null) {\n\t\t\tRipple ripple = (Ripple) scene.ripples.recycle(Ripple.class);\n\t\t\tripple.reset(pos);\n\t\t\treturn ripple;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\tpublic static SpellSprite spellSprite() {\n\t\treturn (SpellSprite)scene.spells.recycle( SpellSprite.class );\n\t}\n\t\n\tpublic static Emitter emitter() {\n\t\tif (scene != null) {\n\t\t\tEmitter emitter = (Emitter)scene.emitters.recycle( Emitter.class );\n\t\t\temitter.revive();\n\t\t\treturn emitter;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic static Emitter floorEmitter() {\n\t\tif (scene != null) {\n\t\t\tEmitter emitter = (Emitter)scene.floorEmitters.recycle( Emitter.class );\n\t\t\temitter.revive();\n\t\t\treturn emitter;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\tpublic static FloatingText status() {\n\t\treturn scene != null ? (FloatingText)scene.statuses.recycle( FloatingText.class ) : null;\n\t}\n\t\n\tpublic static void pickUp( Item item, int pos ) {\n\t\tif (scene != null) scene.toolbar.pickup( item, pos );\n\t}\n\n\tpublic static void pickUpJournal( Item item, int pos ) {\n\t\tif (scene != null) scene.menu.pickup( item, pos );\n\t}\n\n\tpublic static void flashForDocument( Document doc, String page ){\n\t\tif (scene != null) {\n\t\t\tscene.menu.flashForPage( doc, page );\n\t\t}\n\t}\n\n\tpublic static void endIntro(){\n\t\tif (scene != null){\n\t\t\tSPDSettings.intro(false);\n\t\t\tscene.add(new Tweener(scene, 2f){\n\t\t\t\t@Override\n\t\t\t\tprotected void updateValues(float progress) {\n\t\t\t\t\tif (progress <= 0.5f) {\n\t\t\t\t\t\tscene.status.alpha(2*progress);\n\t\t\t\t\t\tscene.status.visible = scene.status.active = true;\n\t\t\t\t\t\tscene.toolbar.visible = scene.toolbar.active = false;\n\t\t\t\t\t\tif (scene.inventory != null) scene.inventory.visible = scene.inventory.active = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tscene.status.alpha(1f);\n\t\t\t\t\t\tscene.status.visible = scene.status.active = true;\n\t\t\t\t\t\tscene.toolbar.alpha((progress - 0.5f)*2);\n\t\t\t\t\t\tscene.toolbar.visible = scene.toolbar.active = true;\n\t\t\t\t\t\tif (scene.inventory != null){\n\t\t\t\t\t\t\tscene.inventory.visible = scene.inventory.active = true;\n\t\t\t\t\t\t\tscene.inventory.alpha((progress - 0.5f)*2);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\tGameLog.wipe();\n\t\t\tif (SPDSettings.interfaceSize() == 0){\n\t\t\t\tGLog.p(Messages.get(GameScene.class, \"tutorial_ui_mobile\"));\n\t\t\t} else {\n\t\t\t\tGLog.p(Messages.get(GameScene.class, \"tutorial_ui_desktop\"));\n\t\t\t}\n\n\t\t\t//clear hidden doors, it's floor 1 so there are only the entrance ones\n\t\t\tfor (int i = 0; i < Dungeon.level.length(); i++){\n\t\t\t\tif (Dungeon.level.map[i] == Terrain.SECRET_DOOR){\n\t\t\t\t\tDungeon.level.discover(i);\n\t\t\t\t\tdiscoverTile(i, Terrain.SECRET_DOOR);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void updateKeyDisplay(){\n\t\tif (scene != null) scene.menu.updateKeys();\n\t}\n\n\tpublic static void showlevelUpStars(){\n\t\tif (scene != null) scene.status.showStarParticles();\n\t}\n\n\tpublic static void resetMap() {\n\t\tif (scene != null) {\n\t\t\tscene.tiles.map(Dungeon.level.map, Dungeon.level.width() );\n\t\t\tscene.visualGrid.map(Dungeon.level.map, Dungeon.level.width() );\n\t\t\tscene.terrainFeatures.map(Dungeon.level.map, Dungeon.level.width() );\n\t\t\tscene.raisedTerrain.map(Dungeon.level.map, Dungeon.level.width() );\n\t\t\tscene.walls.map(Dungeon.level.map, Dungeon.level.width() );\n\t\t}\n\t\tupdateFog();\n\t}\n\n\t//updates the whole map\n\tpublic static void updateMap() {\n\t\tif (scene != null) {\n\t\t\tscene.tiles.updateMap();\n\t\t\tscene.visualGrid.updateMap();\n\t\t\tscene.terrainFeatures.updateMap();\n\t\t\tscene.raisedTerrain.updateMap();\n\t\t\tscene.walls.updateMap();\n\t\t\tupdateFog();\n\t\t}\n\t}\n\t\n\tpublic static void updateMap( int cell ) {\n\t\tif (scene != null) {\n\t\t\tscene.tiles.updateMapCell( cell );\n\t\t\tscene.visualGrid.updateMapCell( cell );\n\t\t\tscene.terrainFeatures.updateMapCell( cell );\n\t\t\tscene.raisedTerrain.updateMapCell( cell );\n\t\t\tscene.walls.updateMapCell( cell );\n\t\t\t//update adjacent cells too\n\t\t\tupdateFog( cell, 1 );\n\t\t}\n\t}\n\n\tpublic static void plantSeed( int cell ) {\n\t\tif (scene != null) {\n\t\t\tscene.terrainFeatures.growPlant( cell );\n\t\t}\n\t}\n\t\n\tpublic static void discoverTile( int pos, int oldValue ) {\n\t\tif (scene != null) {\n\t\t\tscene.tiles.discover( pos, oldValue );\n\t\t}\n\t}\n\t\n\tpublic static void show( Window wnd ) {\n\t\tif (scene != null) {\n\t\t\tcancel();\n\n\t\t\t//If a window is already present (or was just present)\n\t\t\t// then inherit the offset it had\n\t\t\tif (scene.inventory != null && scene.inventory.visible){\n\t\t\t\tPoint offsetToInherit = null;\n\t\t\t\tfor (Gizmo g : scene.members){\n\t\t\t\t\tif (g instanceof Window) offsetToInherit = ((Window) g).getOffset();\n\t\t\t\t}\n\t\t\t\tif (lastOffset != null) {\n\t\t\t\t\toffsetToInherit = lastOffset;\n\t\t\t\t}\n\t\t\t\tif (offsetToInherit != null) {\n\t\t\t\t\twnd.offset(offsetToInherit);\n\t\t\t\t\twnd.boundOffsetWithMargin(3);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tscene.addToFront(wnd);\n\t\t}\n\t}\n\n\tpublic static boolean showingWindow(){\n\t\tif (scene == null) return false;\n\n\t\tfor (Gizmo g : scene.members){\n\t\t\tif (g instanceof Window) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic static boolean interfaceBlockingHero(){\n\t\tif (scene == null) return false;\n\n\t\tif (showingWindow()) return true;\n\n\t\tif (scene.inventory != null && scene.inventory.isSelecting()){\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic static void toggleInvPane(){\n\t\tif (scene != null && scene.inventory != null){\n\t\t\tif (scene.inventory.visible){\n\t\t\t\tscene.inventory.visible = scene.inventory.active = invVisible = false;\n\t\t\t\tscene.toolbar.setPos(scene.toolbar.left(), uiCamera.height-scene.toolbar.height());\n\t\t\t} else {\n\t\t\t\tscene.inventory.visible = scene.inventory.active = invVisible = true;\n\t\t\t\tscene.toolbar.setPos(scene.toolbar.left(), scene.inventory.top()-scene.toolbar.height());\n\t\t\t}\n\t\t\tlayoutTags();\n\t\t}\n\t}\n\n\tpublic static void centerNextWndOnInvPane(){\n\t\tif (scene != null && scene.inventory != null && scene.inventory.visible){\n\t\t\tlastOffset = new Point((int)scene.inventory.centerX() - uiCamera.width/2,\n\t\t\t\t\t(int)scene.inventory.centerY() - uiCamera.height/2);\n\t\t}\n\t}\n\n\tpublic static void updateFog(){\n\t\tif (scene != null) {\n\t\t\tscene.fog.updateFog();\n\t\t\tscene.wallBlocking.updateMap();\n\t\t}\n\t}\n\n\tpublic static void updateFog(int x, int y, int w, int h){\n\t\tif (scene != null) {\n\t\t\tscene.fog.updateFogArea(x, y, w, h);\n\t\t\tscene.wallBlocking.updateArea(x, y, w, h);\n\t\t}\n\t}\n\t\n\tpublic static void updateFog( int cell, int radius ){\n\t\tif (scene != null) {\n\t\t\tscene.fog.updateFog( cell, radius );\n\t\t\tscene.wallBlocking.updateArea( cell, radius );\n\t\t}\n\t}\n\t\n\tpublic static void afterObserve() {\n\t\tif (scene != null) {\n\t\t\tfor (Mob mob : Dungeon.level.mobs.toArray(new Mob[0])) {\n\t\t\t\tif (mob.sprite != null) mob.sprite.visible = Dungeon.level.heroFOV[mob.pos];\n\t\t\t\tif (mob instanceof Ghoul){\n\t\t\t\t\tfor (Ghoul.GhoulLifeLink link : mob.buffs(Ghoul.GhoulLifeLink.class)){\n\t\t\t\t\t\tlink.updateVisibility();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void flash( int color ) {\n\t\tflash( color, true);\n\t}\n\n\tpublic static void flash( int color, boolean lightmode ) {\n\t\tif (scene != null) {\n\t\t\t//greater than 0 to account for negative values (which have the first bit set to 1)\n\t\t\tif (color > 0 && color < 0x01000000) {\n\t\t\t\tscene.fadeIn(0xFF000000 | color, lightmode);\n\t\t\t} else {\n\t\t\t\tscene.fadeIn(color, lightmode);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void gameOver() {\n\t\tif (scene == null) return;\n\n\t\tBanner gameOver = new Banner( BannerSprites.get( BannerSprites.Type.GAME_OVER ) );\n\t\tgameOver.show( 0x000000, 2f );\n\t\tscene.showBanner( gameOver );\n\n\t\tStyledButton restart = new StyledButton(Chrome.Type.GREY_BUTTON_TR, Messages.get(StartScene.class, \"new\"), 9){\n\t\t\t@Override\n\t\t\tprotected void onClick() {\n\t\t\t\tGamesInProgress.selectedClass = Dungeon.hero.heroClass;\n\t\t\t\tGamesInProgress.curSlot = GamesInProgress.firstEmpty();\n\t\t\t\tShatteredPixelDungeon.switchScene(HeroSelectScene.class);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void update() {\n\t\t\t\talpha(gameOver.am);\n\t\t\t\tsuper.update();\n\t\t\t}\n\t\t};\n\t\trestart.icon(Icons.get(Icons.ENTER));\n\t\trestart.alpha(0);\n\t\trestart.camera = uiCamera;\n\t\tfloat offset = Camera.main.centerOffset.y;\n\t\trestart.setSize(Math.max(80, restart.reqWidth()), 20);\n\t\trestart.setPos(\n\t\t\t\talign(uiCamera, (restart.camera.width - restart.width()) / 2),\n\t\t\t\talign(uiCamera, (restart.camera.height - restart.height()) / 2 + restart.height()/2 + 16 - offset)\n\t\t);\n\t\tscene.add(restart);\n\n\t\tStyledButton menu = new StyledButton(Chrome.Type.GREY_BUTTON_TR, Messages.get(WndKeyBindings.class, \"menu\"), 9){\n\t\t\t@Override\n\t\t\tprotected void onClick() {\n\t\t\t\tGameScene.show(new WndGame());\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void update() {\n\t\t\t\talpha(gameOver.am);\n\t\t\t\tsuper.update();\n\t\t\t}\n\t\t};\n\t\tmenu.icon(Icons.get(Icons.PREFS));\n\t\tmenu.alpha(0);\n\t\tmenu.camera = uiCamera;\n\t\tmenu.setSize(Math.max(80, menu.reqWidth()), 20);\n\t\tmenu.setPos(\n\t\t\t\talign(uiCamera, (menu.camera.width - menu.width()) / 2),\n\t\t\t\trestart.bottom() + 2\n\t\t);\n\t\tscene.add(menu);\n\t}\n\t\n\tpublic static void bossSlain() {\n\t\tif (Dungeon.hero.isAlive()) {\n\t\t\tBanner bossSlain = new Banner( BannerSprites.get( BannerSprites.Type.BOSS_SLAIN ) );\n\t\t\tbossSlain.show( 0xFFFFFF, 0.3f, 5f );\n\t\t\tscene.showBanner( bossSlain );\n\t\t\t\n\t\t\tSample.INSTANCE.play( Assets.Sounds.BOSS );\n\t\t}\n\t}\n\t\n\tpublic static void handleCell( int cell ) {\n\t\tcellSelector.select( cell, PointerEvent.LEFT );\n\t}\n\t\n\tpublic static void selectCell( CellSelector.Listener listener ) {\n\t\tif (cellSelector.listener != null && cellSelector.listener != defaultCellListener){\n\t\t\tcellSelector.listener.onSelect(null);\n\t\t}\n\t\tcellSelector.listener = listener;\n\t\tcellSelector.enabled = Dungeon.hero.ready;\n\t\tif (scene != null) {\n\t\t\tscene.prompt(listener.prompt());\n\t\t}\n\t}\n\t\n\tpublic static boolean cancelCellSelector() {\n\t\tif (cellSelector.listener != null && cellSelector.listener != defaultCellListener) {\n\t\t\tcellSelector.resetKeyHold();\n\t\t\tcellSelector.cancel();\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic static WndBag selectItem( WndBag.ItemSelector listener ) {\n\t\tcancel();\n\n\t\tif (scene != null) {\n\t\t\t//TODO can the inventory pane work in these cases? bad to fallback to mobile window\n\t\t\tif (scene.inventory != null && scene.inventory.visible && !showingWindow()){\n\t\t\t\tscene.inventory.setSelector(listener);\n\t\t\t\treturn null;\n\t\t\t} else {\n\t\t\t\tWndBag wnd = WndBag.getBag( listener );\n\t\t\t\tshow(wnd);\n\t\t\t\treturn wnd;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic static boolean cancel() {\n\t\tcellSelector.resetKeyHold();\n\t\tif (Dungeon.hero != null && (Dungeon.hero.curAction != null || Dungeon.hero.resting)) {\n\t\t\t\n\t\t\tDungeon.hero.curAction = null;\n\t\t\tDungeon.hero.resting = false;\n\t\t\treturn true;\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\treturn cancelCellSelector();\n\t\t\t\n\t\t}\n\t}\n\t\n\tpublic static void ready() {\n\t\tselectCell( defaultCellListener );\n\t\tQuickSlotButton.cancel();\n\t\tInventoryPane.cancelTargeting();\n\t\tif (scene != null && scene.toolbar != null) scene.toolbar.examining = false;\n\t\tif (tagDisappeared) {\n\t\t\ttagDisappeared = false;\n\t\t\tupdateTags = true;\n\t\t}\n\t}\n\t\n\tpublic static void checkKeyHold(){\n\t\tcellSelector.processKeyHold();\n\t}\n\t\n\tpublic static void resetKeyHold(){\n\t\tcellSelector.resetKeyHold();\n\t}\n\n\tpublic static void examineCell( Integer cell ) {\n\t\tif (cell == null\n\t\t\t\t|| cell < 0\n\t\t\t\t|| cell > Dungeon.level.length()\n\t\t\t\t|| (!Dungeon.level.visited[cell] && !Dungeon.level.mapped[cell])) {\n\t\t\treturn;\n\t\t}\n\n\t\tArrayList<Object> objects = getObjectsAtCell(cell);\n\n\t\tif (objects.isEmpty()) {\n\t\t\tGameScene.show(new WndInfoCell(cell));\n\t\t} else if (objects.size() == 1){\n\t\t\texamineObject(objects.get(0));\n\t\t} else {\n\t\t\tString[] names = getObjectNames(objects).toArray(new String[0]);\n\n\t\t\tGameScene.show(new WndOptions(Icons.get(Icons.INFO),\n\t\t\t\t\tMessages.get(GameScene.class, \"choose_examine\"),\n\t\t\t\t\tMessages.get(GameScene.class, \"multiple_examine\"),\n\t\t\t\t\tnames){\n\t\t\t\t@Override\n\t\t\t\tprotected void onSelect(int index) {\n\t\t\t\t\texamineObject(objects.get(index));\n\t\t\t\t}\n\t\t\t});\n\n\t\t}\n\t}\n\n\tprivate static ArrayList<Object> getObjectsAtCell( int cell ){\n\t\tArrayList<Object> objects = new ArrayList<>();\n\n\t\tif (cell == Dungeon.hero.pos) {\n\t\t\tobjects.add(Dungeon.hero);\n\n\t\t} else if (Dungeon.level.heroFOV[cell]) {\n\t\t\tMob mob = (Mob) Actor.findChar(cell);\n\t\t\tif (mob != null) objects.add(mob);\n\t\t}\n\n\t\tHeap heap = Dungeon.level.heaps.get(cell);\n\t\tif (heap != null && heap.seen) objects.add(heap);\n\n\t\tPlant plant = Dungeon.level.plants.get( cell );\n\t\tif (plant != null) objects.add(plant);\n\n\t\tTrap trap = Dungeon.level.traps.get( cell );\n\t\tif (trap != null && trap.visible) objects.add(trap);\n\n\t\treturn objects;\n\t}\n\n\tprivate static ArrayList<String> getObjectNames( ArrayList<Object> objects ){\n\t\tArrayList<String> names = new ArrayList<>();\n\t\tfor (Object obj : objects){\n\t\t\tif (obj instanceof Hero) names.add(((Hero) obj).className().toUpperCase(Locale.ENGLISH));\n\t\t\telse if (obj instanceof Mob) names.add(Messages.titleCase( ((Mob)obj).name() ));\n\t\t\telse if (obj instanceof Heap) names.add(Messages.titleCase( ((Heap)obj).title() ));\n\t\t\telse if (obj instanceof Plant) names.add(Messages.titleCase( ((Plant) obj).name() ));\n\t\t\telse if (obj instanceof Trap) names.add(Messages.titleCase( ((Trap) obj).name() ));\n\t\t}\n\t\treturn names;\n\t}\n\n\tpublic static void examineObject(Object o){\n\t\tif (o == Dungeon.hero){\n\t\t\tGameScene.show( new WndHero() );\n\t\t} else if ( o instanceof Mob && ((Mob) o).isActive() ){\n\t\t\tGameScene.show(new WndInfoMob((Mob) o));\n\t\t\tif (o instanceof Snake && !Document.ADVENTURERS_GUIDE.isPageRead(Document.GUIDE_SURPRISE_ATKS)){\n\t\t\t\tGLog.p(Messages.get(Guidebook.class, \"hint\"));\n\t\t\t\tGameScene.flashForDocument(Document.ADVENTURERS_GUIDE, Document.GUIDE_SURPRISE_ATKS);\n\t\t\t}\n\t\t} else if ( o instanceof Heap && !((Heap) o).isEmpty() ){\n\t\t\tGameScene.show(new WndInfoItem((Heap)o));\n\t\t} else if ( o instanceof Plant ){\n\t\t\tGameScene.show( new WndInfoPlant((Plant) o) );\n\t\t} else if ( o instanceof Trap ){\n\t\t\tGameScene.show( new WndInfoTrap((Trap) o));\n\t\t} else {\n\t\t\tGameScene.show( new WndMessage( Messages.get(GameScene.class, \"dont_know\") ) ) ;\n\t\t}\n\t}\n\n\t\n\tprivate static final CellSelector.Listener defaultCellListener = new CellSelector.Listener() {\n\t\t@Override\n\t\tpublic void onSelect( Integer cell ) {\n\t\t\tif (Dungeon.hero.handle( cell )) {\n\t\t\t\tDungeon.hero.next();\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void onRightClick(Integer cell) {\n\t\t\tif (cell == null\n\t\t\t\t\t|| cell < 0\n\t\t\t\t\t|| cell > Dungeon.level.length()\n\t\t\t\t\t|| (!Dungeon.level.visited[cell] && !Dungeon.level.mapped[cell])) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tArrayList<Object> objects = getObjectsAtCell(cell);\n\t\t\tArrayList<String> textLines = getObjectNames(objects);\n\n\t\t\t//determine title and image\n\t\t\tString title = null;\n\t\t\tImage image = null;\n\t\t\tif (objects.isEmpty()) {\n\t\t\t\ttitle = WndInfoCell.cellName(cell);\n\t\t\t\timage = WndInfoCell.cellImage(cell);\n\t\t\t} else if (objects.size() > 1){\n\t\t\t\ttitle = Messages.get(GameScene.class, \"multiple\");\n\t\t\t\timage = Icons.get(Icons.INFO);\n\t\t\t} else if (objects.get(0) instanceof Hero) {\n\t\t\t\ttitle = textLines.remove(0);\n\t\t\t\timage = HeroSprite.avatar(((Hero) objects.get(0)).heroClass, ((Hero) objects.get(0)).tier());\n\t\t\t} else if (objects.get(0) instanceof Mob) {\n\t\t\t\ttitle = textLines.remove(0);\n\t\t\t\timage = ((Mob) objects.get(0)).sprite();\n\t\t\t} else if (objects.get(0) instanceof Heap) {\n\t\t\t\ttitle = textLines.remove(0);\n\t\t\t\timage = new ItemSprite((Heap) objects.get(0));\n\t\t\t} else if (objects.get(0) instanceof Plant) {\n\t\t\t\ttitle = textLines.remove(0);\n\t\t\t\timage = TerrainFeaturesTilemap.tile(cell, Dungeon.level.map[cell]);\n\t\t\t} else if (objects.get(0) instanceof Trap) {\n\t\t\t\ttitle = textLines.remove(0);\n\t\t\t\timage = TerrainFeaturesTilemap.tile(cell, Dungeon.level.map[cell]);\n\t\t\t}\n\n\t\t\t//determine first text line\n\t\t\tif (objects.isEmpty()) {\n\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"go_here\"));\n\t\t\t} else if (objects.get(0) instanceof Hero) {\n\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"go_here\"));\n\t\t\t} else if (objects.get(0) instanceof Mob) {\n\t\t\t\tif (((Mob) objects.get(0)).alignment != Char.Alignment.ENEMY) {\n\t\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"interact\"));\n\t\t\t\t} else {\n\t\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"attack\"));\n\t\t\t\t}\n\t\t\t} else if (objects.get(0) instanceof Heap) {\n\t\t\t\tswitch (((Heap) objects.get(0)).type) {\n\t\t\t\t\tcase HEAP:\n\t\t\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"pick_up\"));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase FOR_SALE:\n\t\t\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"purchase\"));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"interact\"));\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else if (objects.get(0) instanceof Plant) {\n\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"trample\"));\n\t\t\t} else if (objects.get(0) instanceof Trap) {\n\t\t\t\ttextLines.add(0, Messages.get(GameScene.class, \"interact\"));\n\t\t\t}\n\n\t\t\t//final text formatting\n\t\t\tif (objects.size() > 1){\n\t\t\t\ttextLines.add(0, \"_\" + textLines.remove(0) + \":_ \" + textLines.get(0));\n\t\t\t\tfor (int i = 1; i < textLines.size(); i++){\n\t\t\t\t\ttextLines.add(i, \"_\" + Messages.get(GameScene.class, \"examine\") + \":_ \" + textLines.remove(i));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttextLines.add(0, \"_\" + textLines.remove(0) + \"_\");\n\t\t\t\ttextLines.add(1, \"_\" + Messages.get(GameScene.class, \"examine\") + \"_\");\n\t\t\t}\n\n\t\t\tRightClickMenu menu = new RightClickMenu(image,\n\t\t\t\t\ttitle,\n\t\t\t\t\ttextLines.toArray(new String[0])){\n\t\t\t\t@Override\n\t\t\t\tpublic void onSelect(int index) {\n\t\t\t\t\tif (index == 0){\n\t\t\t\t\t\thandleCell(cell);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (objects.size() == 0){\n\t\t\t\t\t\t\tGameScene.show(new WndInfoCell(cell));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\texamineObject(objects.get(index-1));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tscene.addToFront(menu);\n\t\t\tmenu.camera = PixelScene.uiCamera;\n\t\t\tPointF mousePos = PointerEvent.currentHoverPos();\n\t\t\tmousePos = menu.camera.screenToCamera((int)mousePos.x, (int)mousePos.y);\n\t\t\tmenu.setPos(mousePos.x-3, mousePos.y-3);\n\n\t\t}\n\n\t\t@Override\n\t\tpublic String prompt() {\n\t\t\treturn null;\n\t\t}\n\t};\n}" }, { "identifier": "PixelScene", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/scenes/PixelScene.java", "snippet": "public class PixelScene extends Scene {\n\n\t// Minimum virtual display size for mobile portrait orientation\n\tpublic static final float MIN_WIDTH_P = 135;\n\tpublic static final float MIN_HEIGHT_P = 225;\n\n\t// Minimum virtual display size for mobile landscape orientation\n\tpublic static final float MIN_WIDTH_L = 240;\n\tpublic static final float MIN_HEIGHT_L = 160;\n\n\t// Minimum virtual display size for full desktop UI (landscape only)\n\t//TODO maybe include another scale for mixed UI? might make it more accessible to mobile devices\n\t// mixed UI has similar requirements to mobile landscape tbh... Maybe just merge them?\n\t// mixed UI can possible be used on mobile portrait for tablets though.. Does that happen often?\n\tpublic static final float MIN_WIDTH_FULL = 360;\n\tpublic static final float MIN_HEIGHT_FULL = 200;\n\n\tpublic static int defaultZoom = 0;\n\tpublic static int maxDefaultZoom = 0;\n\tpublic static int maxScreenZoom = 0;\n\tpublic static float minZoom;\n\tpublic static float maxZoom;\n\n\tpublic static Camera uiCamera;\n\n\t//stylized 3x5 bitmapped pixel font. Only latin characters supported.\n\tpublic static BitmapText.Font pixelFont;\n\n\tprotected boolean inGameScene = false;\n\n\tprivate Signal.Listener<KeyEvent> fullscreenListener;\n\n\t@Override\n\tpublic void create() {\n\n\t\tsuper.create();\n\n\t\tGameScene.scene = null;\n\n\t\t//flush the texture cache whenever moving from ingame to menu, helps reduce memory load\n\t\tif (!inGameScene && InterlevelScene.lastRegion != -1){\n\t\t\tInterlevelScene.lastRegion = -1;\n\t\t\tTextureCache.clear();\n\t\t}\n\n\t\tfloat minWidth, minHeight, scaleFactor;\n\t\tif (SPDSettings.interfaceSize() > 0){\n\t\t\tminWidth = MIN_WIDTH_FULL;\n\t\t\tminHeight = MIN_HEIGHT_FULL;\n\t\t\tscaleFactor = 3.75f;\n\t\t} else if (landscape()) {\n\t\t\tminWidth = MIN_WIDTH_L;\n\t\t\tminHeight = MIN_HEIGHT_L;\n\t\t\tscaleFactor = 2.5f;\n\t\t} else {\n\t\t\tminWidth = MIN_WIDTH_P;\n\t\t\tminHeight = MIN_HEIGHT_P;\n\t\t\tscaleFactor = 2.5f;\n\t\t}\n\n\t\tmaxDefaultZoom = (int)Math.min(Game.width/minWidth, Game.height/minHeight);\n\t\tmaxScreenZoom = (int)Math.min(Game.dispWidth/minWidth, Game.dispHeight/minHeight);\n\t\tdefaultZoom = SPDSettings.scale();\n\n\t\tif (defaultZoom < Math.ceil( Game.density * 2 ) || defaultZoom > maxDefaultZoom){\n\t\t\tdefaultZoom = (int)GameMath.gate(2, (int)Math.ceil( Game.density * scaleFactor ), maxDefaultZoom);\n\n\t\t\tif (SPDSettings.interfaceSize() > 0 && defaultZoom < (maxDefaultZoom+1)/2){\n\t\t\t\tdefaultZoom = (maxDefaultZoom+1)/2;\n\t\t\t}\n\t\t}\n\n\t\tminZoom = 1;\n\t\tmaxZoom = defaultZoom * 2;\n\n\t\tCamera.reset( new PixelCamera( defaultZoom ) );\n\n\t\tfloat uiZoom = defaultZoom;\n\t\tuiCamera = Camera.createFullscreen( uiZoom );\n\t\tCamera.add( uiCamera );\n\n\t\t// 3x5 (6)\n\t\tpixelFont = Font.colorMarked(\n\t\t\tTextureCache.get( Assets.Fonts.PIXELFONT), 0x00000000, BitmapText.Font.LATIN_FULL );\n\t\tpixelFont.baseLine = 6;\n\t\tpixelFont.tracking = -1;\n\t\t\n\t\t//set up the texture size which rendered text will use for any new glyphs.\n\t\tint renderedTextPageSize;\n\t\tif (defaultZoom <= 3){\n\t\t\trenderedTextPageSize = 256;\n\t\t} else if (defaultZoom <= 8){\n\t\t\trenderedTextPageSize = 512;\n\t\t} else {\n\t\t\trenderedTextPageSize = 1024;\n\t\t}\n\t\t//asian languages have many more unique characters, so increase texture size to anticipate that\n\t\tif (Messages.lang() == Languages.KOREAN ||\n\t\t\t\tMessages.lang() == Languages.CHINESE ||\n\t\t\t\tMessages.lang() == Languages.JAPANESE){\n\t\t\trenderedTextPageSize *= 2;\n\t\t}\n\t\tGame.platform.setupFontGenerators(renderedTextPageSize, SPDSettings.systemFont());\n\n\t\tTooltip.resetLastUsedTime();\n\n\t\tCursor.setCustomCursor(Cursor.Type.DEFAULT, defaultZoom);\n\n\t}\n\n\t@Override\n\tpublic void update() {\n\t\t//we create this here so that it is last in the scene\n\t\tif (DeviceCompat.isDesktop() && fullscreenListener == null){\n\t\t\tKeyEvent.addKeyListener(fullscreenListener = new Signal.Listener<KeyEvent>() {\n\n\t\t\t\tprivate boolean alt;\n\t\t\t\tprivate boolean enter;\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean onSignal(KeyEvent keyEvent) {\n\n\t\t\t\t\t//we don't use keybindings for these as we want the user to be able to\n\t\t\t\t\t// bind these keys to other actions when pressed individually\n\t\t\t\t\tif (keyEvent.code == Input.Keys.ALT_RIGHT){\n\t\t\t\t\t\talt = keyEvent.pressed;\n\t\t\t\t\t} else if (keyEvent.code == Input.Keys.ENTER){\n\t\t\t\t\t\tenter = keyEvent.pressed;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (alt && enter){\n\t\t\t\t\t\tSPDSettings.fullscreen(!SPDSettings.fullscreen());\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tsuper.update();\n\t\t//20% deadzone\n\t\tif (!Cursor.isCursorCaptured()) {\n\t\t\tif (Math.abs(ControllerHandler.rightStickPosition.x) >= 0.2f\n\t\t\t\t\t|| Math.abs(ControllerHandler.rightStickPosition.y) >= 0.2f) {\n\t\t\t\tif (!ControllerHandler.controllerPointerActive()) {\n\t\t\t\t\tControllerHandler.setControllerPointer(true);\n\t\t\t\t}\n\n\t\t\t\tint sensitivity = SPDSettings.controllerPointerSensitivity() * 100;\n\n\t\t\t\t//cursor moves 100xsens scaled pixels per second at full speed\n\t\t\t\t//35x at 50% movement, ~9x at 20% deadzone threshold\n\t\t\t\tfloat xMove = (float) Math.pow(Math.abs(ControllerHandler.rightStickPosition.x), 1.5);\n\t\t\t\tif (ControllerHandler.rightStickPosition.x < 0) xMove = -xMove;\n\n\t\t\t\tfloat yMove = (float) Math.pow(Math.abs(ControllerHandler.rightStickPosition.y), 1.5);\n\t\t\t\tif (ControllerHandler.rightStickPosition.y < 0) yMove = -yMove;\n\n\t\t\t\tPointF virtualCursorPos = ControllerHandler.getControllerPointerPos();\n\t\t\t\tvirtualCursorPos.x += defaultZoom * sensitivity * Game.elapsed * xMove;\n\t\t\t\tvirtualCursorPos.y += defaultZoom * sensitivity * Game.elapsed * yMove;\n\n\t\t\t\tPointF cameraShift = new PointF();\n\n\t\t\t\tif (virtualCursorPos.x < 0){\n\t\t\t\t\tcameraShift.x = virtualCursorPos.x;\n\t\t\t\t\tvirtualCursorPos.x = 0;\n\t\t\t\t} else if (virtualCursorPos.x > Camera.main.screenWidth()){\n\t\t\t\t\tcameraShift.x = (virtualCursorPos.x - Camera.main.screenWidth());\n\t\t\t\t\tvirtualCursorPos.x = Camera.main.screenWidth();\n\t\t\t\t}\n\n\t\t\t\tif (virtualCursorPos.y < 0){\n\t\t\t\t\tcameraShift.y = virtualCursorPos.y;\n\t\t\t\t\tvirtualCursorPos.y = 0;\n\t\t\t\t} else if (virtualCursorPos.y > Camera.main.screenHeight()){\n\t\t\t\t\tcameraShift.y = (virtualCursorPos.y - Camera.main.screenHeight());\n\t\t\t\t\tvirtualCursorPos.y = Camera.main.screenHeight();\n\t\t\t\t}\n\n\t\t\t\tcameraShift.invScale(Camera.main.zoom);\n\t\t\t\tcameraShift.x *= Camera.main.edgeScroll.x;\n\t\t\t\tcameraShift.y *= Camera.main.edgeScroll.y;\n\t\t\t\tif (cameraShift.length() > 0){\n\t\t\t\t\tCamera.main.shift(cameraShift);\n\t\t\t\t}\n\t\t\t\tControllerHandler.updateControllerPointer(virtualCursorPos, true);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate Image cursor = null;\n\n\t@Override\n\tpublic synchronized void draw() {\n\t\tsuper.draw();\n\n\t\t//cursor is separate from the rest of the scene, always appears above\n\t\tif (ControllerHandler.controllerPointerActive()){\n\t\t\tif (cursor == null){\n\t\t\t\tcursor = new Image(Cursor.Type.CONTROLLER.file);\n\t\t\t}\n\n\t\t\tPointF virtualCursorPos = ControllerHandler.getControllerPointerPos();\n\t\t\tcursor.x = (virtualCursorPos.x / defaultZoom) - cursor.width()/2f;\n\t\t\tcursor.y = (virtualCursorPos.y / defaultZoom) - cursor.height()/2f;\n\t\t\tcursor.camera = uiCamera;\n\t\t\talign(cursor);\n\t\t\tcursor.draw();\n\t\t}\n\t}\n\n\t//FIXME this system currently only works for a subset of windows\n\tprivate static ArrayList<Class<?extends Window>> savedWindows = new ArrayList<>();\n\tprivate static Class<?extends PixelScene> savedClass = null;\n\t\n\tpublic synchronized void saveWindows(){\n\t\tif (members == null) return;\n\n\t\tsavedWindows.clear();\n\t\tsavedClass = getClass();\n\t\tfor (Gizmo g : members.toArray(new Gizmo[0])){\n\t\t\tif (g instanceof Window){\n\t\t\t\tsavedWindows.add((Class<? extends Window>) g.getClass());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic synchronized void restoreWindows(){\n\t\tif (getClass().equals(savedClass)){\n\t\t\tfor (Class<?extends Window> w : savedWindows){\n\t\t\t\ttry{\n\t\t\t\t\tadd(Reflection.newInstanceUnhandled(w));\n\t\t\t\t} catch (Exception e){\n\t\t\t\t\t//window has no public zero-arg constructor, just eat the exception\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsavedWindows.clear();\n\t}\n\n\t@Override\n\tpublic void destroy() {\n\t\tsuper.destroy();\n\t\tPointerEvent.clearListeners();\n\t\tif (fullscreenListener != null){\n\t\t\tKeyEvent.removeKeyListener(fullscreenListener);\n\t\t}\n\t\tif (cursor != null){\n\t\t\tcursor.destroy();\n\t\t}\n\t}\n\n\tpublic static boolean landscape(){\n\t\treturn SPDSettings.interfaceSize() > 0 || Game.width > Game.height;\n\t}\n\n\n\tpublic static RenderedTextBlock renderTextBlock(int size ){\n\t\treturn renderTextBlock(\"\", size);\n\t}\n\n\tpublic static RenderedTextBlock renderTextBlock(String text, int size ){\n\t\tRenderedTextBlock result = new RenderedTextBlock( text, size*defaultZoom);\n\t\tresult.zoom(1/(float)defaultZoom);\n\t\treturn result;\n\t}\n\n\t/**\n\t * These methods align UI elements to device pixels.\n\t * e.g. if we have a scale of 3x then valid positions are #.0, #.33, #.67\n\t */\n\n\tpublic static float align( float pos ) {\n\t\treturn Math.round(pos * defaultZoom) / (float)defaultZoom;\n\t}\n\n\tpublic static float align( Camera camera, float pos ) {\n\t\treturn Math.round(pos * camera.zoom) / camera.zoom;\n\t}\n\n\tpublic static void align( Visual v ) {\n\t\tv.x = align( v.x );\n\t\tv.y = align( v.y );\n\t}\n\n\tpublic static void align( Component c ){\n\t\tc.setPos(align(c.left()), align(c.top()));\n\t}\n\n\tpublic static boolean noFade = false;\n\tprotected void fadeIn() {\n\t\tif (noFade) {\n\t\t\tnoFade = false;\n\t\t} else {\n\t\t\tfadeIn( 0xFF000000, false );\n\t\t}\n\t}\n\t\n\tprotected void fadeIn( int color, boolean light ) {\n\t\tadd( new Fader( color, light ) );\n\t}\n\t\n\tpublic static void showBadge( Badges.Badge badge ) {\n\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t@Override\n\t\t\tpublic void call() {\n\t\t\t\tScene s = Game.scene();\n\t\t\t\tif (s != null) {\n\t\t\t\t\tBadgeBanner banner = BadgeBanner.show(badge.image);\n\t\t\t\t\ts.add(banner);\n\t\t\t\t\tfloat offset = Camera.main.centerOffset.y;\n\n\t\t\t\t\tint left = uiCamera.width/2 - BadgeBanner.SIZE/2;\n\t\t\t\t\tleft -= (BadgeBanner.SIZE * BadgeBanner.DEFAULT_SCALE * (BadgeBanner.showing.size()-1))/2;\n\t\t\t\t\tfor (int i = 0; i < BadgeBanner.showing.size(); i++){\n\t\t\t\t\t\tbanner = BadgeBanner.showing.get(i);\n\t\t\t\t\t\tbanner.camera = uiCamera;\n\t\t\t\t\t\tbanner.x = align(banner.camera, left);\n\t\t\t\t\t\tbanner.y = align(uiCamera, (uiCamera.height - banner.height) / 2 - banner.height / 2 - 16 - offset);\n\t\t\t\t\t\tleft += BadgeBanner.SIZE * BadgeBanner.DEFAULT_SCALE;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\t\n\tpublic static void shake( float magnitude, float duration){\n\t\tmagnitude *= SPDSettings.screenShake();\n\t\tCamera.main.shake(magnitude, duration);\n\t}\n\t\n\tprotected static class Fader extends ColorBlock {\n\t\t\n\t\tprivate static float FADE_TIME = 1f;\n\t\t\n\t\tprivate boolean light;\n\t\t\n\t\tprivate float time;\n\n\t\tprivate static Fader INSTANCE;\n\t\t\n\t\tpublic Fader( int color, boolean light ) {\n\t\t\tsuper( uiCamera.width, uiCamera.height, color );\n\t\t\t\n\t\t\tthis.light = light;\n\t\t\t\n\t\t\tcamera = uiCamera;\n\t\t\t\n\t\t\talpha( 1f );\n\t\t\ttime = FADE_TIME;\n\n\t\t\tif (INSTANCE != null){\n\t\t\t\tINSTANCE.killAndErase();\n\t\t\t}\n\t\t\tINSTANCE = this;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void update() {\n\t\t\t\n\t\t\tsuper.update();\n\t\t\t\n\t\t\tif ((time -= Game.elapsed) <= 0) {\n\t\t\t\talpha( 0f );\n\t\t\t\tparent.remove( this );\n\t\t\t\tdestroy();\n\t\t\t\tif (INSTANCE == this) {\n\t\t\t\t\tINSTANCE = null;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\talpha( time / FADE_TIME );\n\t\t\t}\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void draw() {\n\t\t\tif (light) {\n\t\t\t\tBlending.setLightMode();\n\t\t\t\tsuper.draw();\n\t\t\t\tBlending.setNormalMode();\n\t\t\t} else {\n\t\t\t\tsuper.draw();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate static class PixelCamera extends Camera {\n\t\t\n\t\tpublic PixelCamera( float zoom ) {\n\t\t\tsuper(\n\t\t\t\t(int)(Game.width - Math.ceil( Game.width / zoom ) * zoom) / 2,\n\t\t\t\t(int)(Game.height - Math.ceil( Game.height / zoom ) * zoom) / 2,\n\t\t\t\t(int)Math.ceil( Game.width / zoom ),\n\t\t\t\t(int)Math.ceil( Game.height / zoom ), zoom );\n\t\t\tfullScreen = true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected void updateMatrix() {\n\t\t\tfloat sx = align( this, scroll.x + shakeX );\n\t\t\tfloat sy = align( this, scroll.y + shakeY );\n\t\t\t\n\t\t\tmatrix[0] = +zoom * invW2;\n\t\t\tmatrix[5] = -zoom * invH2;\n\t\t\t\n\t\t\tmatrix[12] = -1 + x * invW2 - sx * matrix[0];\n\t\t\tmatrix[13] = +1 - y * invH2 - sy * matrix[5];\n\t\t\t\n\t\t}\n\t}\n}" }, { "identifier": "CrystalSpireSprite", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/sprites/CrystalSpireSprite.java", "snippet": "public abstract class CrystalSpireSprite extends MobSprite {\n\n\t{\n\t\tperspectiveRaise = 7 / 16f; //7 pixels\n\n\t\tshadowWidth = 1f;\n\t\tshadowHeight = 1f;\n\t\tshadowOffset = 1f;\n\t}\n\n\tpublic CrystalSpireSprite(){\n\t\ttexture( Assets.Sprites.CRYSTAL_SPIRE );\n\n\t\tTextureFilm frames = new TextureFilm( texture, 24, 41 );\n\n\t\tint c = texOffset();\n\n\t\tidle = new Animation(1, true);\n\t\tidle.frames( frames, 0+c );\n\n\t\trun = idle.clone();\n\t\tattack = idle.clone();\n\t\tzap = idle.clone();\n\n\t\tdie = new Animation(1, false);\n\t\tdie.frames( frames, 4+c );\n\n\t\tplay(idle);\n\t}\n\n\tpublic void updateIdle(){\n\t\tfloat hpPercent = 1f;\n\t\tif (ch != null){\n\t\t\thpPercent = ch.HP/(float)ch.HT;\n\t\t}\n\n\t\tTextureFilm frames = new TextureFilm( texture, 24, 41 );\n\n\t\tif (hpPercent > 0.9f){\n\t\t\tidle.frames( frames, 0+texOffset() );\n\t\t} else if (hpPercent > 0.67f){\n\t\t\tidle.frames( frames, 1+texOffset() );\n\t\t} else if (hpPercent > 0.33f){\n\t\t\tidle.frames( frames, 2+texOffset() );\n\t\t} else {\n\t\t\tidle.frames( frames, 3+texOffset() );\n\t\t}\n\t\tplay(idle, true);\n\t\trun = idle.clone();\n\t\tattack = idle.clone();\n\t\tzap = idle.clone();\n\t}\n\n\t@Override\n\tpublic void link(Char ch) {\n\t\tsuper.link(ch);\n\t\tupdateIdle();\n\t}\n\n\tboolean wasVisible = false;\n\n\t@Override\n\tpublic void update() {\n\t\tsuper.update();\n\t\tif (curAnim != die && ch != null && visible != wasVisible){\n\t\t\tif (visible){\n\t\t\t\tDungeonWallsTilemap.skipCells.add(ch.pos - 2*Dungeon.level.width());\n\t\t\t\tDungeonWallsTilemap.skipCells.add(ch.pos - Dungeon.level.width());\n\t\t\t} else {\n\t\t\t\tDungeonWallsTilemap.skipCells.remove(ch.pos - 2*Dungeon.level.width());\n\t\t\t\tDungeonWallsTilemap.skipCells.remove(ch.pos - Dungeon.level.width());\n\t\t\t}\n\t\t\tGameScene.updateMap(ch.pos-2*Dungeon.level.width());\n\t\t\tGameScene.updateMap(ch.pos-Dungeon.level.width());\n\t\t\twasVisible = visible;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void die() {\n\t\tsuper.die();\n\t\tSplash.around(this, blood(), 100);\n\t\tif (ch != null && visible){\n\t\t\tDungeonWallsTilemap.skipCells.remove(ch.pos - 2*Dungeon.level.width());\n\t\t\tDungeonWallsTilemap.skipCells.remove(ch.pos - Dungeon.level.width());\n\t\t\tGameScene.updateMap(ch.pos-2*Dungeon.level.width());\n\t\t\tGameScene.updateMap(ch.pos-Dungeon.level.width());\n\t\t}\n\t}\n\n\t@Override\n\tpublic void turnTo(int from, int to) {\n\t\t//do nothing\n\t}\n\n\tprotected abstract int texOffset();\n\n\tpublic static class Blue extends CrystalSpireSprite {\n\t\t@Override\n\t\tprotected int texOffset() {\n\t\t\treturn 0;\n\t\t}\n\t\t@Override\n\t\tpublic int blood() {\n\t\t\treturn 0xFF8EE3FF;\n\t\t}\n\t}\n\n\tpublic static class Green extends CrystalSpireSprite {\n\t\t@Override\n\t\tprotected int texOffset() {\n\t\t\treturn 5;\n\t\t}\n\t\t@Override\n\t\tpublic int blood() {\n\t\t\treturn 0xFF85FFC8;\n\t\t}\n\t}\n\n\tpublic static class Red extends CrystalSpireSprite {\n\t\t@Override\n\t\tprotected int texOffset() {\n\t\t\treturn 10;\n\t\t}\n\t\t@Override\n\t\tpublic int blood() {\n\t\t\treturn 0xFFFFBB33;\n\t\t}\n\t}\n\n}" }, { "identifier": "BossHealthBar", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/ui/BossHealthBar.java", "snippet": "public class BossHealthBar extends Component {\n\n\tprivate Image bar;\n\n\tprivate Image rawShielding;\n\tprivate Image shieldedHP;\n\tprivate Image hp;\n\tprivate BitmapText hpText;\n\n\tprivate Button bossInfo;\n\tprivate BuffIndicator buffs;\n\n\tprivate static Mob boss;\n\n\tprivate Image skull;\n\tprivate Emitter blood;\n\n\tprivate static String asset = Assets.Interfaces.BOSSHP;\n\n\tprivate static BossHealthBar instance;\n\tprivate static boolean bleeding;\n\n\tpublic BossHealthBar() {\n\t\tsuper();\n\t\tvisible = active = (boss != null);\n\t\tinstance = this;\n\t}\n\n\t@Override\n\tpublic synchronized void destroy() {\n\t\tsuper.destroy();\n\t\tif (instance == this) instance = null;\n\t\tif (buffs != null) BuffIndicator.setBossInstance(null);\n\t}\n\n\t@Override\n\tprotected void createChildren() {\n\t\tbar = new Image(asset, 0, 0, 64, 16);\n\t\tadd(bar);\n\n\t\twidth = bar.width;\n\t\theight = bar.height;\n\n\t\trawShielding = new Image(asset, 15, 25, 47, 4);\n\t\trawShielding.alpha(0.5f);\n\t\tadd(rawShielding);\n\n\t\tshieldedHP = new Image(asset, 15, 25, 47, 4);\n\t\tadd(shieldedHP);\n\n\t\thp = new Image(asset, 15, 19, 47, 4);\n\t\tadd(hp);\n\n\t\thpText = new BitmapText(PixelScene.pixelFont);\n\t\thpText.alpha(0.6f);\n\t\tadd(hpText);\n\n\t\tbossInfo = new Button(){\n\t\t\t@Override\n\t\t\tprotected void onClick() {\n\t\t\t\tsuper.onClick();\n\t\t\t\tif (boss != null){\n\t\t\t\t\tGameScene.show(new WndInfoMob(boss));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String hoverText() {\n\t\t\t\tif (boss != null){\n\t\t\t\t\treturn boss.name();\n\t\t\t\t}\n\t\t\t\treturn super.hoverText();\n\t\t\t}\n\t\t};\n\t\tadd(bossInfo);\n\n\t\tif (boss != null) {\n\t\t\tbuffs = new BuffIndicator(boss, false);\n\t\t\tBuffIndicator.setBossInstance(buffs);\n\t\t\tadd(buffs);\n\t\t}\n\n\t\tskull = new Image(asset, 5, 18, 6, 6);\n\t\tadd(skull);\n\n\t\tblood = new Emitter();\n\t\tblood.pos(skull);\n\t\tblood.pour(BloodParticle.FACTORY, 0.3f);\n\t\tblood.autoKill = false;\n\t\tblood.on = false;\n\t\tadd( blood );\n\t}\n\n\t@Override\n\tprotected void layout() {\n\t\tbar.x = x;\n\t\tbar.y = y;\n\n\t\thp.x = shieldedHP.x = rawShielding.x = bar.x+15;\n\t\thp.y = shieldedHP.y = rawShielding.y = bar.y+3;\n\n\t\thpText.scale.set(PixelScene.align(0.5f));\n\t\thpText.x = hp.x + 1;\n\t\thpText.y = hp.y + (hp.height - (hpText.baseLine()+hpText.scale.y))/2f;\n\t\thpText.y -= 0.001f; //prefer to be slightly higher\n\t\tPixelScene.align(hpText);\n\n\t\tbossInfo.setRect(x, y, bar.width, bar.height);\n\n\t\tif (buffs != null) {\n\t\t\tbuffs.setRect(hp.x, hp.y + 5, 47, 8);\n\t\t}\n\n\t\tskull.x = bar.x+5;\n\t\tskull.y = bar.y+5;\n\t}\n\n\t@Override\n\tpublic void update() {\n\t\tsuper.update();\n\t\tif (boss != null){\n\t\t\tif (!boss.isAlive() || !Dungeon.level.mobs.contains(boss)){\n\t\t\t\tboss = null;\n\t\t\t\tvisible = active = false;\n\t\t\t\tif (buffs != null) {\n\t\t\t\t\tBuffIndicator.setBossInstance(null);\n\t\t\t\t\tremove(buffs);\n\t\t\t\t\tbuffs.destroy();\n\t\t\t\t\tbuffs = null;\n\t\t\t\t}\n\t\t\t} else {\n\n\t\t\t\tint health = boss.HP;\n\t\t\t\tint shield = boss.shielding();\n\t\t\t\tint max = boss.HT;\n\n\t\t\t\thp.scale.x = Math.max( 0, (health-shield)/(float)max);\n\t\t\t\tshieldedHP.scale.x = health/(float)max;\n\t\t\t\trawShielding.scale.x = shield/(float)max;\n\n\t\t\t\tif (bleeding != blood.on){\n\t\t\t\t\tif (bleeding) skull.tint( 0xcc0000, 0.6f );\n\t\t\t\t\telse skull.resetColor();\n\t\t\t\t\tblood.on = bleeding;\n\t\t\t\t}\n\n\t\t\t\tif (shield <= 0){\n\t\t\t\t\thpText.text(health + \"/\" + max);\n\t\t\t\t} else {\n\t\t\t\t\thpText.text(health + \"+\" + shield + \"/\" + max);\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void assignBoss(Mob boss){\n\t\tif (BossHealthBar.boss == boss) {\n\t\t\treturn;\n\t\t}\n\t\tBossHealthBar.boss = boss;\n\t\tbleed(false);\n\t\tif (instance != null) {\n\t\t\tinstance.visible = instance.active = true;\n\t\t\tif (boss != null){\n\t\t\t\tif (instance.buffs != null){\n\t\t\t\t\tinstance.remove(instance.buffs);\n\t\t\t\t\tinstance.buffs.destroy();\n\t\t\t\t}\n\t\t\t\tinstance.buffs = new BuffIndicator(boss, false);\n\t\t\t\tBuffIndicator.setBossInstance(instance.buffs);\n\t\t\t\tinstance.add(instance.buffs);\n\t\t\t\tinstance.layout();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static boolean isAssigned(){\n\t\treturn boss != null && boss.isAlive() && Dungeon.level.mobs.contains(boss);\n\t}\n\n\tpublic static void bleed(boolean value){\n\t\tbleeding = value;\n\t}\n\n\tpublic static boolean isBleeding(){\n\t\treturn bleeding;\n\t}\n\n}" }, { "identifier": "GLog", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/utils/GLog.java", "snippet": "public class GLog {\n\n\tpublic static final String TAG = \"GAME\";\n\t\n\tpublic static final String POSITIVE\t\t= \"++ \";\n\tpublic static final String NEGATIVE\t\t= \"-- \";\n\tpublic static final String WARNING\t\t= \"** \";\n\tpublic static final String HIGHLIGHT\t= \"@@ \";\n\n\tpublic static final String NEW_LINE\t = \"\\n\";\n\t\n\tpublic static Signal<String> update = new Signal<>();\n\n\tpublic static void newLine(){\n\t\tupdate.dispatch( NEW_LINE );\n\t}\n\t\n\tpublic static void i( String text, Object... args ) {\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttext = Messages.format( text, args );\n\t\t}\n\t\t\n\t\tDeviceCompat.log( TAG, text );\n\t\tupdate.dispatch( text );\n\t}\n\t\n\tpublic static void p( String text, Object... args ) {\n\t\ti( POSITIVE + text, args );\n\t}\n\t\n\tpublic static void n( String text, Object... args ) {\n\t\ti( NEGATIVE + text, args );\n\t}\n\t\n\tpublic static void w( String text, Object... args ) {\n\t\ti( WARNING + text, args );\n\t}\n\t\n\tpublic static void h( String text, Object... args ) {\n\t\ti( HIGHLIGHT + text, args );\n\t}\n}" }, { "identifier": "Sample", "path": "SPD-classes/src/main/java/com/watabou/noosa/audio/Sample.java", "snippet": "public enum Sample {\n\n\tINSTANCE;\n\n\tprotected HashMap<Object, Sound> ids = new HashMap<>();\n\n\tprivate boolean enabled = true;\n\tprivate float globalVolume = 1f;\n\n\tpublic synchronized void reset() {\n\n\t\tfor (Sound sound : ids.values()){\n\t\t\tsound.dispose();\n\t\t}\n\t\t\n\t\tids.clear();\n\t\tdelayedSFX.clear();\n\n\t}\n\n\tpublic synchronized void pause() {\n\t\tfor (Sound sound : ids.values()) {\n\t\t\tsound.pause();\n\t\t}\n\t}\n\n\tpublic synchronized void resume() {\n\t\tfor (Sound sound : ids.values()) {\n\t\t\tsound.resume();\n\t\t}\n\t}\n\n\tpublic synchronized void load( final String... assets ) {\n\n\t\tfinal ArrayList<String> toLoad = new ArrayList<>();\n\n\t\tfor (String asset : assets){\n\t\t\tif (!ids.containsKey(asset)){\n\t\t\t\ttoLoad.add(asset);\n\t\t\t}\n\t\t}\n\n\t\t//don't make a new thread of all assets are already loaded\n\t\tif (toLoad.isEmpty()) return;\n\n\t\t//load in a separate thread to prevent this blocking the UI\n\t\tnew Thread(){\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tfor (String asset : toLoad) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tSound newSound = Gdx.audio.newSound(Gdx.files.internal(asset));\n\t\t\t\t\t\tsynchronized (INSTANCE) {\n\t\t\t\t\t\t\tids.put(asset, newSound);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (Exception e){\n\t\t\t\t\t\tGame.reportException(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}.start();\n\t\t\n\t}\n\n\tpublic synchronized void unload( Object src ) {\n\t\tif (ids.containsKey( src )) {\n\t\t\tids.get( src ).dispose();\n\t\t\tids.remove( src );\n\t\t}\n\t}\n\n\tpublic long play( Object id ) {\n\t\treturn play( id, 1 );\n\t}\n\n\tpublic long play( Object id, float volume ) {\n\t\treturn play( id, volume, volume, 1 );\n\t}\n\t\n\tpublic long play( Object id, float volume, float pitch ) {\n\t\treturn play( id, volume, volume, pitch );\n\t}\n\t\n\tpublic synchronized long play( Object id, float leftVolume, float rightVolume, float pitch ) {\n\t\tfloat volume = Math.max(leftVolume, rightVolume);\n\t\tfloat pan = rightVolume - leftVolume;\n\t\tif (enabled && ids.containsKey( id )) {\n\t\t\treturn ids.get(id).play( globalVolume*volume, pitch, pan );\n\t\t} else {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tprivate class DelayedSoundEffect{\n\t\tObject id;\n\t\tfloat delay;\n\n\t\tfloat leftVol;\n\t\tfloat rightVol;\n\t\tfloat pitch;\n\t}\n\n\tprivate static final HashSet<DelayedSoundEffect> delayedSFX = new HashSet<>();\n\n\tpublic void playDelayed( Object id, float delay ){\n\t\tplayDelayed( id, delay, 1 );\n\t}\n\n\tpublic void playDelayed( Object id, float delay, float volume ) {\n\t\tplayDelayed( id, delay, volume, volume, 1 );\n\t}\n\n\tpublic void playDelayed( Object id, float delay, float volume, float pitch ) {\n\t\tplayDelayed( id, delay, volume, volume, pitch );\n\t}\n\n\tpublic void playDelayed( Object id, float delay, float leftVolume, float rightVolume, float pitch ) {\n\t\tif (delay <= 0) {\n\t\t\tplay(id, leftVolume, rightVolume, pitch);\n\t\t\treturn;\n\t\t}\n\t\tDelayedSoundEffect sfx = new DelayedSoundEffect();\n\t\tsfx.id = id;\n\t\tsfx.delay = delay;\n\t\tsfx.leftVol = leftVolume;\n\t\tsfx.rightVol = rightVolume;\n\t\tsfx.pitch = pitch;\n\t\tsynchronized (delayedSFX) {\n\t\t\tdelayedSFX.add(sfx);\n\t\t}\n\t}\n\n\tpublic void update(){\n\t\tsynchronized (delayedSFX) {\n\t\t\tif (delayedSFX.isEmpty()) return;\n\t\t\tfor (DelayedSoundEffect sfx : delayedSFX.toArray(new DelayedSoundEffect[0])) {\n\t\t\t\tsfx.delay -= Game.elapsed;\n\t\t\t\tif (sfx.delay <= 0) {\n\t\t\t\t\tdelayedSFX.remove(sfx);\n\t\t\t\t\tplay(sfx.id, sfx.leftVol, sfx.rightVol, sfx.pitch);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void enable( boolean value ) {\n\t\tenabled = value;\n\t}\n\n\tpublic void volume( float value ) {\n\t\tglobalVolume = value;\n\t}\n\n\tpublic boolean isEnabled() {\n\t\treturn enabled;\n\t}\n\t\n}" }, { "identifier": "Bundle", "path": "SPD-classes/src/main/java/com/watabou/utils/Bundle.java", "snippet": "public class Bundle {\n\n\tprivate static final String CLASS_NAME = \"__className\";\n\n\tpublic static final String DEFAULT_KEY = \"key\";\n\n\tprivate static HashMap<String,String> aliases = new HashMap<>();\n\n\t/*\n\t\tWARNING: NOT ALL METHODS IN ORG.JSON ARE PRESENT ON ANDROID/IOS!\n\t\tMany methods which work on desktop will cause the game to crash on Android and iOS\n\n\t\tThis is because the Android runtime includes its own version of org.json which does not\n\t\timplement all methods. MobiVM uses the Android runtime and so this applies to iOS as well.\n\n\t\torg.json is very fast (~2x faster than libgdx JSON), which is why the game uses it despite\n\t\tthis dependency conflict.\n\n\t\tSee https://developer.android.com/reference/org/json/package-summary for details on\n\t\twhat methods exist in all versions of org.json. This class is also commented in places\n\t\tWhere Android/iOS force the use of unusual methods.\n\t */\n\tprivate JSONObject data;\n\n\tpublic Bundle() {\n\t\tthis( new JSONObject() );\n\t}\n\n\tpublic String toString() {\n\t\treturn data.toString();\n\t}\n\n\tprivate Bundle( JSONObject data ) {\n\t\tthis.data = data;\n\t}\n\n\tpublic boolean isNull() {\n\t\treturn data == null;\n\t}\n\n\tpublic boolean contains( String key ) {\n\t\treturn !isNull() && !data.isNull( key );\n\t}\n\n\tpublic boolean remove( String key ){\n\t\treturn data.remove(key) != null;\n\t}\n\n\t//JSONObject.keyset() doesn't exist on Android/iOS\n\tpublic ArrayList<String> getKeys(){\n\t\tIterator<String> keys = data.keys();\n\t\tArrayList<String> result = new ArrayList<>();\n\t\twhile (keys.hasNext()){\n\t\t\tresult.add(keys.next());\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic boolean getBoolean( String key ) {\n\t\treturn data.optBoolean( key );\n\t}\n\n\tpublic int getInt( String key ) {\n\t\treturn data.optInt( key );\n\t}\n\n\tpublic long getLong( String key ) {\n\t\treturn data.optLong( key );\n\t}\n\n\tpublic float getFloat( String key ) {\n\t\treturn (float)data.optDouble( key, 0.0 );\n\t}\n\n\tpublic String getString( String key ) {\n\t\treturn data.optString( key );\n\t}\n\n\tpublic Class getClass( String key ) {\n\t\tString clName = getString(key).replace(\"class \", \"\");\n\t\tif (!clName.equals(\"\")){\n\t\t\tif (aliases.containsKey( clName )) {\n\t\t\t\tclName = aliases.get( clName );\n\t\t\t}\n\n\t\t\treturn Reflection.forName( clName );\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic Bundle getBundle( String key ) {\n\t\treturn new Bundle( data.optJSONObject( key ) );\n\t}\n\n\tprivate Bundlable get() {\n\t\tif (data == null) return null;\n\n\t\tString clName = getString( CLASS_NAME );\n\t\tif (aliases.containsKey( clName )) {\n\t\t\tclName = aliases.get( clName );\n\t\t}\n\n\t\tClass<?> cl = Reflection.forName( clName );\n\t\t//Skip none-static inner classes as they can't be instantiated through bundle restoring\n\t\t//Classes which make use of none-static inner classes must manage instantiation manually\n\t\tif (cl != null && (!Reflection.isMemberClass(cl) || Reflection.isStatic(cl))) {\n\t\t\tBundlable object = (Bundlable) Reflection.newInstance(cl);\n\t\t\tif (object != null) {\n\t\t\t\tobject.restoreFromBundle(this);\n\t\t\t\treturn object;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic Bundlable get( String key ) {\n\t\treturn getBundle( key ).get();\n\t}\n\n\tpublic <E extends Enum<E>> E getEnum( String key, Class<E> enumClass ) {\n\t\ttry {\n\t\t\treturn Enum.valueOf( enumClass, data.getString( key ) );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn enumClass.getEnumConstants()[0];\n\t\t} catch (IllegalArgumentException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn enumClass.getEnumConstants()[0];\n\t\t}\n\t}\n\n\tpublic int[] getIntArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tint[] result = new int[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = array.getInt( i );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic long[] getLongArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tlong[] result = new long[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = array.getLong( i );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic float[] getFloatArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tfloat[] result = new float[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = (float)array.optDouble( i, 0.0 );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic boolean[] getBooleanArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tboolean[] result = new boolean[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = array.getBoolean( i );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic String[] getStringArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tString[] result = new String[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = array.getString( i );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Class[] getClassArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tClass[] result = new Class[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tString clName = array.getString( i ).replace(\"class \", \"\");\n\t\t\t\tif (aliases.containsKey( clName )) {\n\t\t\t\t\tclName = aliases.get( clName );\n\t\t\t\t}\n\t\t\t\tClass cl = Reflection.forName( clName );\n\t\t\t\tresult[i] = cl;\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Bundle[] getBundleArray(){\n\t\treturn getBundleArray( DEFAULT_KEY );\n\t}\n\n\tpublic Bundle[] getBundleArray( String key ){\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tBundle[] result = new Bundle[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = new Bundle( array.getJSONObject( i ) );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Collection<Bundlable> getCollection( String key ) {\n\n\t\tArrayList<Bundlable> list = new ArrayList<>();\n\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tfor (int i=0; i < array.length(); i++) {\n\t\t\t\tBundlable O = new Bundle( array.getJSONObject( i ) ).get();\n\t\t\t\tif (O != null) list.add( O );\n\t\t\t}\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\n\t\treturn list;\n\t}\n\n\tpublic void put( String key, boolean value ) {\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, int value ) {\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, long value ) {\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, float value ) {\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, String value ) {\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, Class value ){\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, Bundle bundle ) {\n\t\ttry {\n\t\t\tdata.put( key, bundle.data );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, Bundlable object ) {\n\t\tif (object != null) {\n\t\t\ttry {\n\t\t\t\tBundle bundle = new Bundle();\n\t\t\t\tbundle.put( CLASS_NAME, object.getClass().getName() );\n\t\t\t\tobject.storeInBundle( bundle );\n\t\t\t\tdata.put( key, bundle.data );\n\t\t\t} catch (JSONException e) {\n\t\t\t\tGame.reportException(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void put( String key, Enum<?> value ) {\n\t\tif (value != null) {\n\t\t\ttry {\n\t\t\t\tdata.put( key, value.name() );\n\t\t\t} catch (JSONException e) {\n\t\t\t\tGame.reportException(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void put( String key, int[] array ) {\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i] );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, long[] array ) {\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i] );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, float[] array ) {\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i] );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, boolean[] array ) {\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i] );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, String[] array ) {\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i] );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, Class[] array ){\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i].getName() );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, Collection<? extends Bundlable> collection ) {\n\t\tJSONArray array = new JSONArray();\n\t\tfor (Bundlable object : collection) {\n\t\t\t//Skip none-static inner classes as they can't be instantiated through bundle restoring\n\t\t\t//Classes which make use of none-static inner classes must manage instantiation manually\n\t\t\tif (object != null) {\n\t\t\t\tClass cl = object.getClass();\n\t\t\t\tif ((!Reflection.isMemberClass(cl) || Reflection.isStatic(cl))) {\n\t\t\t\t\tBundle bundle = new Bundle();\n\t\t\t\t\tbundle.put(CLASS_NAME, cl.getName());\n\t\t\t\t\tobject.storeInBundle(bundle);\n\t\t\t\t\tarray.put(bundle.data);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tdata.put( key, array );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\t//useful to turn this off for save data debugging.\n\tprivate static final boolean compressByDefault = true;\n\n\tprivate static final int GZIP_BUFFER = 1024*4; //4 kb\n\n\tpublic static Bundle read( InputStream stream ) throws IOException {\n\n\t\ttry {\n\t\t\tif (!stream.markSupported()){\n\t\t\t\tstream = new BufferedInputStream( stream, 2 );\n\t\t\t}\n\n\t\t\t//determines if we're reading a regular, or compressed file\n\t\t\tstream.mark( 2 );\n\t\t\tbyte[] header = new byte[2];\n\t\t\tstream.read( header );\n\t\t\tstream.reset();\n\n\t\t\t//GZIP header is 0x1f8b\n\t\t\tif( header[ 0 ] == (byte) 0x1f && header[ 1 ] == (byte) 0x8b ) {\n\t\t\t\tstream = new GZIPInputStream( stream, GZIP_BUFFER );\n\t\t\t}\n\n\t\t\t//JSONTokenizer only has a string-based constructor on Android/iOS\n\t\t\tBufferedReader reader = new BufferedReader( new InputStreamReader( stream ));\n\t\t\tStringBuilder jsonBuilder = new StringBuilder();\n\n\t\t\tString line;\n\t\t\twhile ((line = reader.readLine()) != null) {\n\t\t\t\tjsonBuilder.append(line);\n\t\t\t\tjsonBuilder.append(\"\\n\");\n\t\t\t}\n\t\t\tString jsonString = jsonBuilder.toString();\n\n\t\t\tObject json;\n\t\t\ttry {\n\t\t\t\tjson = new JSONTokener(jsonString).nextValue();\n\t\t\t} catch (Exception e){\n\t\t\t\t//if the string can't be tokenized, it may be written by v1.1.X, which used libGDX JSON.\n\t\t\t\t// Some of these are written in a 'minified' format, some have duplicate keys.\n\t\t\t\t// We read them in with the libGDX JSON code, fix duplicates, write as full JSON\n\t\t\t\t// and then try to read again with org.json\n\t\t\t\tGame.reportException(e);\n\t\t\t\tJsonValue gdxJSON = new JsonReader().parse(jsonString);\n\t\t\t\tkillDuplicateKeysInLibGDXJSON(gdxJSON);\n\t\t\t\tjson = new JSONTokener(gdxJSON.prettyPrint(JsonWriter.OutputType.json, 0)).nextValue();\n\t\t\t}\n\t\t\treader.close();\n\n\t\t\t//if the data is an array, put it in a fresh object with the default key\n\t\t\tif (json instanceof JSONArray){\n\t\t\t\tjson = new JSONObject().put( DEFAULT_KEY, json );\n\t\t\t}\n\n\t\t\treturn new Bundle( (JSONObject) json );\n\t\t} catch (Exception e) {\n\t\t\tGame.reportException(e);\n\t\t\tthrow new IOException();\n\t\t}\n\t}\n\n\tprivate static void killDuplicateKeysInLibGDXJSON(JsonValue val){\n\t\tHashSet<String> keys = new HashSet<>();\n\t\twhile(val != null) {\n\t\t\tif (val.name != null && keys.contains(val.name)){\n\t\t\t\t//delete the duplicate key\n\t\t\t\tval.prev.next = val.next;\n\t\t\t\tif (val.next != null) val.next.prev = val.prev;\n\t\t\t\tval.parent.size--;\n\t\t\t} else {\n\t\t\t\tkeys.add(val.name);\n\t\t\t\tif (val.child != null){\n\t\t\t\t\tkillDuplicateKeysInLibGDXJSON(val.child);\n\t\t\t\t}\n\t\t\t}\n\t\t\tval = val.next;\n\t\t}\n\t}\n\n\tpublic static boolean write( Bundle bundle, OutputStream stream ){\n\t\treturn write(bundle, stream, compressByDefault);\n\t}\n\n\tpublic static boolean write( Bundle bundle, OutputStream stream, boolean compressed ) {\n\t\ttry {\n\t\t\tBufferedWriter writer;\n\t\t\tif (compressed) writer = new BufferedWriter( new OutputStreamWriter( new GZIPOutputStream(stream, GZIP_BUFFER ) ) );\n\t\t\telse writer = new BufferedWriter( new OutputStreamWriter( stream ) );\n\n\t\t\t//JSONObject.write does not exist on Android/iOS\n\t\t\twriter.write(bundle.data.toString());\n\t\t\twriter.close();\n\n\t\t\treturn true;\n\t\t} catch (IOException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic static void addAlias( Class<?> cl, String alias ) {\n\t\taliases.put( alias, cl.getName() );\n\t}\n\t\n}" }, { "identifier": "Callback", "path": "SPD-classes/src/main/java/com/watabou/utils/Callback.java", "snippet": "public interface Callback {\n\n\tvoid call();\n\t\n}" }, { "identifier": "GameMath", "path": "SPD-classes/src/main/java/com/watabou/utils/GameMath.java", "snippet": "public class GameMath {\n\t\n\tpublic static float speed( float speed, float acc ) {\n\t\t\n\t\tif (acc != 0) {\n\t\t\tspeed += acc * Game.elapsed;\n\t\t}\n\t\t\n\t\treturn speed;\n\t}\n\t\n\tpublic static float gate( float min, float value, float max ) {\n\t\tif (value < min) {\n\t\t\treturn min;\n\t\t} else if (value > max) {\n\t\t\treturn max;\n\t\t} else {\n\t\t\treturn value;\n\t\t}\n\t}\n}" }, { "identifier": "PathFinder", "path": "SPD-classes/src/main/java/com/watabou/utils/PathFinder.java", "snippet": "public class PathFinder {\n\t\n\tpublic static int[] distance;\n\tprivate static int[] maxVal;\n\t\n\tprivate static boolean[] goals;\n\tprivate static int[] queue;\n\tprivate static boolean[] queued; //currently only used in getStepBack, other can piggyback on distance\n\t\n\tprivate static int size = 0;\n\tprivate static int width = 0;\n\n\tprivate static int[] dir;\n\tprivate static int[] dirLR;\n\n\t//performance-light shortcuts for some common pathfinder cases\n\t//they are in array-access order for increased memory performance\n\tpublic static int[] NEIGHBOURS4;\n\tpublic static int[] NEIGHBOURS8;\n\tpublic static int[] NEIGHBOURS9;\n\n\t//similar to their equivalent neighbour arrays, but the order is clockwise.\n\t//Useful for some logic functions, but is slower due to lack of array-access order.\n\tpublic static int[] CIRCLE4;\n\tpublic static int[] CIRCLE8;\n\t\n\tpublic static void setMapSize( int width, int height ) {\n\t\t\n\t\tPathFinder.width = width;\n\t\tPathFinder.size = width * height;\n\t\t\n\t\tdistance = new int[size];\n\t\tgoals = new boolean[size];\n\t\tqueue = new int[size];\n\t\tqueued = new boolean[size];\n\n\t\tmaxVal = new int[size];\n\t\tArrays.fill(maxVal, Integer.MAX_VALUE);\n\n\t\tdir = new int[]{-1, +1, -width, +width, -width-1, -width+1, +width-1, +width+1};\n\t\tdirLR = new int[]{-1-width, -1, -1+width, -width, +width, +1-width, +1, +1+width};\n\n\t\tNEIGHBOURS4 = new int[]{-width, -1, +1, +width};\n\t\tNEIGHBOURS8 = new int[]{-width-1, -width, -width+1, -1, +1, +width-1, +width, +width+1};\n\t\tNEIGHBOURS9 = new int[]{-width-1, -width, -width+1, -1, 0, +1, +width-1, +width, +width+1};\n\n\t\tCIRCLE4 = new int[]{-width, +1, +width, -1};\n\t\tCIRCLE8 = new int[]{-width-1, -width, -width+1, +1, +width+1, +width, +width-1, -1};\n\t}\n\n\tpublic static Path find( int from, int to, boolean[] passable ) {\n\n\t\tif (!buildDistanceMap( from, to, passable )) {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tPath result = new Path();\n\t\tint s = from;\n\n\t\t// From the starting position we are moving downwards,\n\t\t// until we reach the ending point\n\t\tdo {\n\t\t\tint minD = distance[s];\n\t\t\tint mins = s;\n\t\t\t\n\t\t\tfor (int i=0; i < dir.length; i++) {\n\t\t\t\t\n\t\t\t\tint n = s + dir[i];\n\t\t\t\t\n\t\t\t\tint thisD = distance[n];\n\t\t\t\tif (thisD < minD) {\n\t\t\t\t\tminD = thisD;\n\t\t\t\t\tmins = n;\n\t\t\t\t}\n\t\t\t}\n\t\t\ts = mins;\n\t\t\tresult.add( s );\n\t\t} while (s != to);\n\t\t\n\t\treturn result;\n\t}\n\t\n\tpublic static int getStep( int from, int to, boolean[] passable ) {\n\t\t\n\t\tif (!buildDistanceMap( from, to, passable )) {\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\t// From the starting position we are making one step downwards\n\t\tint minD = distance[from];\n\t\tint best = from;\n\t\t\n\t\tint step, stepD;\n\t\t\n\t\tfor (int i=0; i < dir.length; i++) {\n\n\t\t\tif ((stepD = distance[step = from + dir[i]]) < minD) {\n\t\t\t\tminD = stepD;\n\t\t\t\tbest = step;\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t}\n\t\n\tpublic static int getStepBack( int cur, int from, int lookahead, boolean[] passable, boolean canApproachFromPos ) {\n\n\t\tint d = buildEscapeDistanceMap( cur, from, lookahead, passable );\n\t\tif (d == 0) return -1;\n\n\t\tif (!canApproachFromPos) {\n\t\t\t//We can't approach the position we are retreating from\n\t\t\t//re-calculate based on this, and reduce the target distance if need-be\n\t\t\tint head = 0;\n\t\t\tint tail = 0;\n\n\t\t\tint newD = distance[cur];\n\t\t\tBArray.setFalse(queued);\n\n\t\t\tqueue[tail++] = cur;\n\t\t\tqueued[cur] = true;\n\n\t\t\twhile (head < tail) {\n\t\t\t\tint step = queue[head++];\n\n\t\t\t\tif (distance[step] > newD) {\n\t\t\t\t\tnewD = distance[step];\n\t\t\t\t}\n\n\t\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\t\tint end = ((step + 1) % width == 0 ? 3 : 0);\n\t\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\t\tint n = step + dirLR[i];\n\t\t\t\t\tif (n >= 0 && n < size && passable[n]) {\n\t\t\t\t\t\tif (distance[n] < distance[cur]) {\n\t\t\t\t\t\t\tpassable[n] = false;\n\t\t\t\t\t\t} else if (distance[n] >= distance[step] && !queued[n]) {\n\t\t\t\t\t\t\t// Add to queue\n\t\t\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\t\t\tqueued[n] = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\td = Math.min(newD, d);\n\t\t}\n\n\t\tfor (int i=0; i < size; i++) {\n\t\t\tgoals[i] = distance[i] == d;\n\t\t}\n\t\tif (!buildDistanceMap( cur, goals, passable )) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tint s = cur;\n\t\t\n\t\t// From the starting position we are making one step downwards\n\t\tint minD = distance[s];\n\t\tint mins = s;\n\t\t\n\t\tfor (int i=0; i < dir.length; i++) {\n\n\t\t\tint n = s + dir[i];\n\t\t\tint thisD = distance[n];\n\t\t\t\n\t\t\tif (thisD < minD) {\n\t\t\t\tminD = thisD;\n\t\t\t\tmins = n;\n\t\t\t}\n\t\t}\n\n\t\treturn mins;\n\t}\n\t\n\tprivate static boolean buildDistanceMap( int from, int to, boolean[] passable ) {\n\t\t\n\t\tif (from == to) {\n\t\t\treturn false;\n\t\t}\n\n\t\tSystem.arraycopy(maxVal, 0, distance, 0, maxVal.length);\n\t\t\n\t\tboolean pathFound = false;\n\t\t\n\t\tint head = 0;\n\t\tint tail = 0;\n\t\t\n\t\t// Add to queue\n\t\tqueue[tail++] = to;\n\t\tdistance[to] = 0;\n\t\t\n\t\twhile (head < tail) {\n\t\t\t\n\t\t\t// Remove from queue\n\t\t\tint step = queue[head++];\n\t\t\tif (step == from) {\n\t\t\t\tpathFound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tint nextDistance = distance[step] + 1;\n\t\t\t\n\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\tint end = ((step+1) % width == 0 ? 3 : 0);\n\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\tint n = step + dirLR[i];\n\t\t\t\tif (n == from || (n >= 0 && n < size && passable[n] && (distance[n] > nextDistance))) {\n\t\t\t\t\t// Add to queue\n\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\tdistance[n] = nextDistance;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn pathFound;\n\t}\n\t\n\tpublic static void buildDistanceMap( int to, boolean[] passable, int limit ) {\n\t\t\n\t\tSystem.arraycopy(maxVal, 0, distance, 0, maxVal.length);\n\t\t\n\t\tint head = 0;\n\t\tint tail = 0;\n\t\t\n\t\t// Add to queue\n\t\tqueue[tail++] = to;\n\t\tdistance[to] = 0;\n\t\t\n\t\twhile (head < tail) {\n\t\t\t\n\t\t\t// Remove from queue\n\t\t\tint step = queue[head++];\n\t\t\t\n\t\t\tint nextDistance = distance[step] + 1;\n\t\t\tif (nextDistance > limit) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\tint end = ((step+1) % width == 0 ? 3 : 0);\n\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\tint n = step + dirLR[i];\n\t\t\t\tif (n >= 0 && n < size && passable[n] && (distance[n] > nextDistance)) {\n\t\t\t\t\t// Add to queue\n\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\tdistance[n] = nextDistance;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate static boolean buildDistanceMap( int from, boolean[] to, boolean[] passable ) {\n\t\t\n\t\tif (to[from]) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tSystem.arraycopy(maxVal, 0, distance, 0, maxVal.length);\n\t\t\n\t\tboolean pathFound = false;\n\t\t\n\t\tint head = 0;\n\t\tint tail = 0;\n\t\t\n\t\t// Add to queue\n\t\tfor (int i=0; i < size; i++) {\n\t\t\tif (to[i]) {\n\t\t\t\tqueue[tail++] = i;\n\t\t\t\tdistance[i] = 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\twhile (head < tail) {\n\t\t\t\n\t\t\t// Remove from queue\n\t\t\tint step = queue[head++];\n\t\t\tif (step == from) {\n\t\t\t\tpathFound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tint nextDistance = distance[step] + 1;\n\t\t\t\n\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\tint end = ((step+1) % width == 0 ? 3 : 0);\n\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\tint n = step + dirLR[i];\n\t\t\t\tif (n == from || (n >= 0 && n < size && passable[n] && (distance[n] > nextDistance))) {\n\t\t\t\t\t// Add to queue\n\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\tdistance[n] = nextDistance;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn pathFound;\n\t}\n\n\t//the lookahead is the target number of cells to retreat toward from our current position's\n\t// distance from the position we are escaping from. Returns the highest found distance, up to the lookahead\n\tprivate static int buildEscapeDistanceMap( int cur, int from, int lookAhead, boolean[] passable ) {\n\t\t\n\t\tSystem.arraycopy(maxVal, 0, distance, 0, maxVal.length);\n\t\t\n\t\tint destDist = Integer.MAX_VALUE;\n\t\t\n\t\tint head = 0;\n\t\tint tail = 0;\n\t\t\n\t\t// Add to queue\n\t\tqueue[tail++] = from;\n\t\tdistance[from] = 0;\n\t\t\n\t\tint dist = 0;\n\t\t\n\t\twhile (head < tail) {\n\t\t\t\n\t\t\t// Remove from queue\n\t\t\tint step = queue[head++];\n\t\t\tdist = distance[step];\n\t\t\t\n\t\t\tif (dist > destDist) {\n\t\t\t\treturn destDist;\n\t\t\t}\n\t\t\t\n\t\t\tif (step == cur) {\n\t\t\t\tdestDist = dist + lookAhead;\n\t\t\t}\n\t\t\t\n\t\t\tint nextDistance = dist + 1;\n\t\t\t\n\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\tint end = ((step+1) % width == 0 ? 3 : 0);\n\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\tint n = step + dirLR[i];\n\t\t\t\tif (n >= 0 && n < size && passable[n] && distance[n] > nextDistance) {\n\t\t\t\t\t// Add to queue\n\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\tdistance[n] = nextDistance;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn dist;\n\t}\n\t\n\tpublic static void buildDistanceMap( int to, boolean[] passable ) {\n\t\t\n\t\tSystem.arraycopy(maxVal, 0, distance, 0, maxVal.length);\n\t\t\n\t\tint head = 0;\n\t\tint tail = 0;\n\t\t\n\t\t// Add to queue\n\t\tqueue[tail++] = to;\n\t\tdistance[to] = 0;\n\t\t\n\t\twhile (head < tail) {\n\t\t\t\n\t\t\t// Remove from queue\n\t\t\tint step = queue[head++];\n\t\t\tint nextDistance = distance[step] + 1;\n\t\t\t\n\t\t\tint start = (step % width == 0 ? 3 : 0);\n\t\t\tint end = ((step+1) % width == 0 ? 3 : 0);\n\t\t\tfor (int i = start; i < dirLR.length - end; i++) {\n\n\t\t\t\tint n = step + dirLR[i];\n\t\t\t\tif (n >= 0 && n < size && passable[n] && (distance[n] > nextDistance)) {\n\t\t\t\t\t// Add to queue\n\t\t\t\t\tqueue[tail++] = n;\n\t\t\t\t\tdistance[n] = nextDistance;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@SuppressWarnings(\"serial\")\n\tpublic static class Path extends LinkedList<Integer> {\n\t}\n}" }, { "identifier": "Random", "path": "SPD-classes/src/main/java/com/watabou/utils/Random.java", "snippet": "public class Random {\n\n\t//we store a stack of random number generators, which may be seeded deliberately or randomly.\n\t//top of the stack is what is currently being used to generate new numbers.\n\t//the base generator is always created with no seed, and cannot be popped.\n\tprivate static ArrayDeque<java.util.Random> generators;\n\tstatic {\n\t\tresetGenerators();\n\t}\n\n\tpublic static synchronized void resetGenerators(){\n\t\tgenerators = new ArrayDeque<>();\n\t\tgenerators.push(new java.util.Random());\n\t}\n\n\tpublic static synchronized void pushGenerator(){\n\t\tgenerators.push( new java.util.Random() );\n\t}\n\n\tpublic static synchronized void pushGenerator( long seed ){\n\t\tgenerators.push( new java.util.Random( scrambleSeed(seed) ) );\n\t}\n\n\t//scrambles a given seed, this helps eliminate patterns between the outputs of similar seeds\n\t//Algorithm used is MX3 by Jon Maiga (jonkagstrom.com), CC0 license.\n\tprivate static synchronized long scrambleSeed( long seed ){\n\t\tseed ^= seed >>> 32;\n\t\tseed *= 0xbea225f9eb34556dL;\n\t\tseed ^= seed >>> 29;\n\t\tseed *= 0xbea225f9eb34556dL;\n\t\tseed ^= seed >>> 32;\n\t\tseed *= 0xbea225f9eb34556dL;\n\t\tseed ^= seed >>> 29;\n\t\treturn seed;\n\t}\n\n\tpublic static synchronized void popGenerator(){\n\t\tif (generators.size() == 1){\n\t\t\tGame.reportException( new RuntimeException(\"tried to pop the last random number generator!\"));\n\t\t} else {\n\t\t\tgenerators.pop();\n\t\t}\n\t}\n\n\t//returns a uniformly distributed float in the range [0, 1)\n\tpublic static synchronized float Float() {\n\t\treturn generators.peek().nextFloat();\n\t}\n\n\t//returns a uniformly distributed float in the range [0, max)\n\tpublic static float Float( float max ) {\n\t\treturn Float() * max;\n\t}\n\n\t//returns a uniformly distributed float in the range [min, max)\n\tpublic static float Float( float min, float max ) {\n\t\treturn min + Float(max - min);\n\t}\n\t\n\t//returns a triangularly distributed float in the range [min, max)\n\tpublic static float NormalFloat( float min, float max ) {\n\t\treturn min + ((Float(max - min) + Float(max - min))/2f);\n\t}\n\n\t//returns a uniformly distributed int in the range [0, max)\n\tpublic static synchronized int Int( int max ) {\n\t\treturn max > 0 ? generators.peek().nextInt(max) : 0;\n\t}\n\n\t//returns a uniformly distributed int in the range [min, max)\n\tpublic static int Int( int min, int max ) {\n\t\treturn min + Int(max - min);\n\t}\n\n\t//returns a uniformly distributed int in the range [min, max]\n\tpublic static int IntRange( int min, int max ) {\n\t\treturn min + Int(max - min + 1);\n\t}\n\n\t//returns a triangularly distributed int in the range [min, max]\n\tpublic static int NormalIntRange( int min, int max ) {\n\t\treturn min + (int)((Float() + Float()) * (max - min + 1) / 2f);\n\t}\n\n\t//returns a uniformly distributed long in the range [-2^63, 2^63)\n\tpublic static synchronized long Long() {\n\t\treturn generators.peek().nextLong();\n\t}\n\n\t//returns a uniformly distributed long in the range [0, max)\n\tpublic static long Long( long max ) {\n\t\tlong result = Long();\n\t\tif (result < 0) result += Long.MAX_VALUE;\n\t\treturn result % max;\n\t}\n\n\t//returns an index from chances, the probability of each index is the weight values in changes\n\tpublic static int chances( float[] chances ) {\n\t\t\n\t\tint length = chances.length;\n\t\t\n\t\tfloat sum = 0;\n\t\tfor (int i=0; i < length; i++) {\n\t\t\tsum += chances[i];\n\t\t}\n\t\t\n\t\tfloat value = Float( sum );\n\t\tsum = 0;\n\t\tfor (int i=0; i < length; i++) {\n\t\t\tsum += chances[i];\n\t\t\tif (value < sum) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn -1;\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\t//returns a key element from chances, the probability of each key is the weight value it maps to\n\tpublic static <K> K chances( HashMap<K,Float> chances ) {\n\t\t\n\t\tint size = chances.size();\n\n\t\tObject[] values = chances.keySet().toArray();\n\t\tfloat[] probs = new float[size];\n\t\tfloat sum = 0;\n\t\tfor (int i=0; i < size; i++) {\n\t\t\tprobs[i] = chances.get( values[i] );\n\t\t\tsum += probs[i];\n\t\t}\n\t\t\n\t\tif (sum <= 0) {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tfloat value = Float( sum );\n\t\t\n\t\tsum = probs[0];\n\t\tfor (int i=0; i < size; i++) {\n\t\t\tif (value < sum) {\n\t\t\t\treturn (K)values[i];\n\t\t\t}\n\t\t\tsum += probs[i + 1];\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic static int index( Collection<?> collection ) {\n\t\treturn Int(collection.size());\n\t}\n\n\t@SafeVarargs\n\tpublic static<T> T oneOf(T... array ) {\n\t\treturn array[Int(array.length)];\n\t}\n\t\n\tpublic static<T> T element( T[] array ) {\n\t\treturn element( array, array.length );\n\t}\n\t\n\tpublic static<T> T element( T[] array, int max ) {\n\t\treturn array[Int(max)];\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static<T> T element( Collection<? extends T> collection ) {\n\t\tint size = collection.size();\n\t\treturn size > 0 ?\n\t\t\t(T)collection.toArray()[Int( size )] :\n\t\t\tnull;\n\t}\n\n\tpublic synchronized static<T> void shuffle( List<?extends T> list){\n\t\tCollections.shuffle(list, generators.peek());\n\t}\n\t\n\tpublic static<T> void shuffle( T[] array ) {\n\t\tfor (int i=0; i < array.length - 1; i++) {\n\t\t\tint j = Int( i, array.length );\n\t\t\tif (j != i) {\n\t\t\t\tT t = array[i];\n\t\t\t\tarray[i] = array[j];\n\t\t\t\tarray[j] = t;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static<U,V> void shuffle( U[] u, V[]v ) {\n\t\tfor (int i=0; i < u.length - 1; i++) {\n\t\t\tint j = Int( i, u.length );\n\t\t\tif (j != i) {\n\t\t\t\tU ut = u[i];\n\t\t\t\tu[i] = u[j];\n\t\t\t\tu[j] = ut;\n\t\t\t\t\n\t\t\t\tV vt = v[i];\n\t\t\t\tv[i] = v[j];\n\t\t\t\tv[j] = vt;\n\t\t\t}\n\t\t}\n\t}\n}" } ]
import com.shatteredpixel.shatteredpixeldungeon.Assets; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.actors.Actor; import com.shatteredpixel.shatteredpixeldungeon.actors.Char; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Amok; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Blindness; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Cripple; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Dread; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Haste; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Invisibility; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Paralysis; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Sleep; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Terror; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Vertigo; import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs.Blacksmith; import com.shatteredpixel.shatteredpixeldungeon.effects.Pushing; import com.shatteredpixel.shatteredpixeldungeon.effects.Splash; import com.shatteredpixel.shatteredpixeldungeon.effects.TargetedCell; import com.shatteredpixel.shatteredpixeldungeon.items.quest.Pickaxe; import com.shatteredpixel.shatteredpixeldungeon.levels.Level; import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain; import com.shatteredpixel.shatteredpixeldungeon.mechanics.Ballistica; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene; import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene; import com.shatteredpixel.shatteredpixeldungeon.sprites.CrystalSpireSprite; import com.shatteredpixel.shatteredpixeldungeon.ui.BossHealthBar; import com.shatteredpixel.shatteredpixeldungeon.utils.GLog; import com.watabou.noosa.audio.Sample; import com.watabou.utils.Bundle; import com.watabou.utils.Callback; import com.watabou.utils.GameMath; import com.watabou.utils.PathFinder; import com.watabou.utils.Random; import java.util.ArrayList;
88,247
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.actors.mobs; public class CrystalSpire extends Mob { { //this translates to roughly 33/27/23/20/18/16 pickaxe hits at +0/1/2/3/4/5 HP = HT = 300; spriteClass = CrystalSpireSprite.class; EXP = 20; //acts after other mobs, which makes baiting crystal guardians more consistent actPriority = MOB_PRIO-1; state = PASSIVE; alignment = Alignment.NEUTRAL; properties.add(Property.IMMOVABLE); properties.add(Property.MINIBOSS); properties.add(Property.INORGANIC); } private float abilityCooldown; private static final int ABILITY_CD = 15; private ArrayList<ArrayList<Integer>> targetedCells = new ArrayList<>(); @Override protected boolean act() { //char logic if (fieldOfView == null || fieldOfView.length != Dungeon.level.length()){ fieldOfView = new boolean[Dungeon.level.length()]; } Dungeon.level.updateFieldOfView( this, fieldOfView ); throwItems(); sprite.hideAlert(); sprite.hideLost(); //mob logic enemy = Dungeon.hero; //crystal can still track an invisible hero enemySeen = enemy.isAlive() && fieldOfView[enemy.pos]; //end of char/mob logic if (!targetedCells.isEmpty()){ ArrayList<Integer> cellsToAttack = targetedCells.remove(0); for (int i : cellsToAttack){ Char ch = Actor.findChar(i); if (ch instanceof CrystalSpire){ continue; //don't spawn crystals on itself } Level.set(i, Terrain.MINE_CRYSTAL);
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.actors.mobs; public class CrystalSpire extends Mob { { //this translates to roughly 33/27/23/20/18/16 pickaxe hits at +0/1/2/3/4/5 HP = HT = 300; spriteClass = CrystalSpireSprite.class; EXP = 20; //acts after other mobs, which makes baiting crystal guardians more consistent actPriority = MOB_PRIO-1; state = PASSIVE; alignment = Alignment.NEUTRAL; properties.add(Property.IMMOVABLE); properties.add(Property.MINIBOSS); properties.add(Property.INORGANIC); } private float abilityCooldown; private static final int ABILITY_CD = 15; private ArrayList<ArrayList<Integer>> targetedCells = new ArrayList<>(); @Override protected boolean act() { //char logic if (fieldOfView == null || fieldOfView.length != Dungeon.level.length()){ fieldOfView = new boolean[Dungeon.level.length()]; } Dungeon.level.updateFieldOfView( this, fieldOfView ); throwItems(); sprite.hideAlert(); sprite.hideLost(); //mob logic enemy = Dungeon.hero; //crystal can still track an invisible hero enemySeen = enemy.isAlive() && fieldOfView[enemy.pos]; //end of char/mob logic if (!targetedCells.isEmpty()){ ArrayList<Integer> cellsToAttack = targetedCells.remove(0); for (int i : cellsToAttack){ Char ch = Actor.findChar(i); if (ch instanceof CrystalSpire){ continue; //don't spawn crystals on itself } Level.set(i, Terrain.MINE_CRYSTAL);
GameScene.updateMap(i);
24
2023-11-27 05:56:58+00:00
128k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/swt/org/jfree/experimental/chart/swt/demo/SWTPieChartDemo1.java
[ { "identifier": "ChartFactory", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/ChartFactory.java", "snippet": "public abstract class ChartFactory {\r\n\r\n /** The chart theme. */\r\n private static ChartTheme currentTheme = new StandardChartTheme(\"JFree\");\r\n\r\n /**\r\n * Returns the current chart theme used by the factory.\r\n *\r\n * @return The chart theme.\r\n *\r\n * @see #setChartTheme(ChartTheme)\r\n * @see ChartUtilities#applyCurrentTheme(JFreeChart)\r\n *\r\n * @since 1.0.11\r\n */\r\n public static ChartTheme getChartTheme() {\r\n return currentTheme;\r\n }\r\n\r\n /**\r\n * Sets the current chart theme. This will be applied to all new charts\r\n * created via methods in this class.\r\n *\r\n * @param theme the theme (<code>null</code> not permitted).\r\n *\r\n * @see #getChartTheme()\r\n * @see ChartUtilities#applyCurrentTheme(JFreeChart)\r\n *\r\n * @since 1.0.11\r\n */\r\n public static void setChartTheme(ChartTheme theme) {\r\n ParamChecks.nullNotPermitted(theme, \"theme\");\r\n currentTheme = theme;\r\n\r\n // here we do a check to see if the user is installing the \"Legacy\"\r\n // theme, and reset the bar painters in that case...\r\n if (theme instanceof StandardChartTheme) {\r\n StandardChartTheme sct = (StandardChartTheme) theme;\r\n if (sct.getName().equals(\"Legacy\")) {\r\n BarRenderer.setDefaultBarPainter(new StandardBarPainter());\r\n XYBarRenderer.setDefaultBarPainter(new StandardXYBarPainter());\r\n }\r\n else {\r\n BarRenderer.setDefaultBarPainter(new GradientBarPainter());\r\n XYBarRenderer.setDefaultBarPainter(new GradientXYBarPainter());\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Creates a pie chart with default settings.\r\n * <P>\r\n * The chart object returned by this method uses a {@link PiePlot} instance\r\n * as the plot.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param locale the locale (<code>null</code> not permitted).\r\n *\r\n * @return A pie chart.\r\n *\r\n * @since 1.0.7\r\n */\r\n public static JFreeChart createPieChart(String title, PieDataset dataset,\r\n boolean legend, boolean tooltips, Locale locale) {\r\n\r\n PiePlot plot = new PiePlot(dataset);\r\n plot.setLabelGenerator(new StandardPieSectionLabelGenerator(locale));\r\n plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));\r\n if (tooltips) {\r\n plot.setToolTipGenerator(new StandardPieToolTipGenerator(locale));\r\n }\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a pie chart with default settings.\r\n * <P>\r\n * The chart object returned by this method uses a {@link PiePlot} instance\r\n * as the plot.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A pie chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createPieChart(String title, PieDataset dataset) {\r\n return createPieChart(title, dataset, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates a pie chart with default settings.\r\n * <P>\r\n * The chart object returned by this method uses a {@link PiePlot} instance\r\n * as the plot.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A pie chart.\r\n */\r\n public static JFreeChart createPieChart(String title, PieDataset dataset,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n PiePlot plot = new PiePlot(dataset);\r\n plot.setLabelGenerator(new StandardPieSectionLabelGenerator());\r\n plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));\r\n if (tooltips) {\r\n plot.setToolTipGenerator(new StandardPieToolTipGenerator());\r\n }\r\n if (urls) {\r\n plot.setURLGenerator(new StandardPieURLGenerator());\r\n }\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n }\r\n\r\n /**\r\n * Creates a pie chart with default settings that compares 2 datasets.\r\n * The colour of each section will be determined by the move from the value\r\n * for the same key in <code>previousDataset</code>. ie if value1 &gt; \r\n * value2 then the section will be in green (unless \r\n * <code>greenForIncrease</code> is <code>false</code>, in which case it \r\n * would be <code>red</code>). Each section can have a shade of red or \r\n * green as the difference can be tailored between 0% (black) and \r\n * percentDiffForMaxScale% (bright red/green).\r\n * <p>\r\n * For instance if <code>percentDiffForMaxScale</code> is 10 (10%), a\r\n * difference of 5% will have a half shade of red/green, a difference of\r\n * 10% or more will have a maximum shade/brightness of red/green.\r\n * <P>\r\n * The chart object returned by this method uses a {@link PiePlot} instance\r\n * as the plot.\r\n * <p>\r\n * Written by <a href=\"mailto:[email protected]\">Benoit\r\n * Xhenseval</a>.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param previousDataset the dataset for the last run, this will be used\r\n * to compare each key in the dataset\r\n * @param percentDiffForMaxScale scale goes from bright red/green to black,\r\n * percentDiffForMaxScale indicate the change\r\n * required to reach top scale.\r\n * @param greenForIncrease an increase since previousDataset will be\r\n * displayed in green (decrease red) if true.\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param locale the locale (<code>null</code> not permitted).\r\n * @param subTitle displays a subtitle with colour scheme if true\r\n * @param showDifference create a new dataset that will show the %\r\n * difference between the two datasets.\r\n *\r\n * @return A pie chart.\r\n *\r\n * @since 1.0.7\r\n */\r\n public static JFreeChart createPieChart(String title, PieDataset dataset,\r\n PieDataset previousDataset, int percentDiffForMaxScale,\r\n boolean greenForIncrease, boolean legend, boolean tooltips,\r\n Locale locale, boolean subTitle, boolean showDifference) {\r\n\r\n PiePlot plot = new PiePlot(dataset);\r\n plot.setLabelGenerator(new StandardPieSectionLabelGenerator(locale));\r\n plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));\r\n\r\n if (tooltips) {\r\n plot.setToolTipGenerator(new StandardPieToolTipGenerator(locale));\r\n }\r\n\r\n List keys = dataset.getKeys();\r\n DefaultPieDataset series = null;\r\n if (showDifference) {\r\n series = new DefaultPieDataset();\r\n }\r\n\r\n double colorPerPercent = 255.0 / percentDiffForMaxScale;\r\n for (Iterator it = keys.iterator(); it.hasNext();) {\r\n Comparable key = (Comparable) it.next();\r\n Number newValue = dataset.getValue(key);\r\n Number oldValue = previousDataset.getValue(key);\r\n\r\n if (oldValue == null) {\r\n if (greenForIncrease) {\r\n plot.setSectionPaint(key, Color.green);\r\n }\r\n else {\r\n plot.setSectionPaint(key, Color.red);\r\n }\r\n if (showDifference) {\r\n assert series != null; // suppresses compiler warning\r\n series.setValue(key + \" (+100%)\", newValue);\r\n }\r\n }\r\n else {\r\n double percentChange = (newValue.doubleValue()\r\n / oldValue.doubleValue() - 1.0) * 100.0;\r\n double shade\r\n = (Math.abs(percentChange) >= percentDiffForMaxScale ? 255\r\n : Math.abs(percentChange) * colorPerPercent);\r\n if (greenForIncrease\r\n && newValue.doubleValue() > oldValue.doubleValue()\r\n || !greenForIncrease && newValue.doubleValue()\r\n < oldValue.doubleValue()) {\r\n plot.setSectionPaint(key, new Color(0, (int) shade, 0));\r\n }\r\n else {\r\n plot.setSectionPaint(key, new Color((int) shade, 0, 0));\r\n }\r\n if (showDifference) {\r\n assert series != null; // suppresses compiler warning\r\n series.setValue(key + \" (\" + (percentChange >= 0 ? \"+\" : \"\")\r\n + NumberFormat.getPercentInstance().format(\r\n percentChange / 100.0) + \")\", newValue);\r\n }\r\n }\r\n }\r\n\r\n if (showDifference) {\r\n plot.setDataset(series);\r\n }\r\n\r\n JFreeChart chart = new JFreeChart(title,\r\n JFreeChart.DEFAULT_TITLE_FONT, plot, legend);\r\n\r\n if (subTitle) {\r\n TextTitle subtitle = new TextTitle(\"Bright \" + (greenForIncrease \r\n ? \"red\" : \"green\") + \"=change >=-\" + percentDiffForMaxScale\r\n + \"%, Bright \" + (!greenForIncrease ? \"red\" : \"green\")\r\n + \"=change >=+\" + percentDiffForMaxScale + \"%\",\r\n new Font(\"SansSerif\", Font.PLAIN, 10));\r\n chart.addSubtitle(subtitle);\r\n }\r\n currentTheme.apply(chart);\r\n return chart;\r\n }\r\n\r\n /**\r\n * Creates a pie chart with default settings that compares 2 datasets.\r\n * The colour of each section will be determined by the move from the value\r\n * for the same key in <code>previousDataset</code>. ie if value1 &gt; \r\n * value2 then the section will be in green (unless \r\n * <code>greenForIncrease</code> is <code>false</code>, in which case it \r\n * would be <code>red</code>). Each section can have a shade of red or \r\n * green as the difference can be tailored between 0% (black) and \r\n * percentDiffForMaxScale% (bright red/green).\r\n * <p>\r\n * For instance if <code>percentDiffForMaxScale</code> is 10 (10%), a\r\n * difference of 5% will have a half shade of red/green, a difference of\r\n * 10% or more will have a maximum shade/brightness of red/green.\r\n * <P>\r\n * The chart object returned by this method uses a {@link PiePlot} instance\r\n * as the plot.\r\n * <p>\r\n * Written by <a href=\"mailto:[email protected]\">Benoit\r\n * Xhenseval</a>.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param previousDataset the dataset for the last run, this will be used\r\n * to compare each key in the dataset\r\n * @param percentDiffForMaxScale scale goes from bright red/green to black,\r\n * percentDiffForMaxScale indicate the change\r\n * required to reach top scale.\r\n * @param greenForIncrease an increase since previousDataset will be\r\n * displayed in green (decrease red) if true.\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n * @param subTitle displays a subtitle with colour scheme if true\r\n * @param showDifference create a new dataset that will show the %\r\n * difference between the two datasets.\r\n *\r\n * @return A pie chart.\r\n */\r\n public static JFreeChart createPieChart(String title, PieDataset dataset,\r\n PieDataset previousDataset, int percentDiffForMaxScale,\r\n boolean greenForIncrease, boolean legend, boolean tooltips, \r\n boolean urls, boolean subTitle, boolean showDifference) {\r\n\r\n PiePlot plot = new PiePlot(dataset);\r\n plot.setLabelGenerator(new StandardPieSectionLabelGenerator());\r\n plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));\r\n\r\n if (tooltips) {\r\n plot.setToolTipGenerator(new StandardPieToolTipGenerator());\r\n }\r\n if (urls) {\r\n plot.setURLGenerator(new StandardPieURLGenerator());\r\n }\r\n\r\n List keys = dataset.getKeys();\r\n DefaultPieDataset series = null;\r\n if (showDifference) {\r\n series = new DefaultPieDataset();\r\n }\r\n\r\n double colorPerPercent = 255.0 / percentDiffForMaxScale;\r\n for (Iterator it = keys.iterator(); it.hasNext();) {\r\n Comparable key = (Comparable) it.next();\r\n Number newValue = dataset.getValue(key);\r\n Number oldValue = previousDataset.getValue(key);\r\n\r\n if (oldValue == null) {\r\n if (greenForIncrease) {\r\n plot.setSectionPaint(key, Color.green);\r\n }\r\n else {\r\n plot.setSectionPaint(key, Color.red);\r\n }\r\n if (showDifference) {\r\n assert series != null; // suppresses compiler warning\r\n series.setValue(key + \" (+100%)\", newValue);\r\n }\r\n }\r\n else {\r\n double percentChange = (newValue.doubleValue()\r\n / oldValue.doubleValue() - 1.0) * 100.0;\r\n double shade\r\n = (Math.abs(percentChange) >= percentDiffForMaxScale ? 255\r\n : Math.abs(percentChange) * colorPerPercent);\r\n if (greenForIncrease\r\n && newValue.doubleValue() > oldValue.doubleValue()\r\n || !greenForIncrease && newValue.doubleValue()\r\n < oldValue.doubleValue()) {\r\n plot.setSectionPaint(key, new Color(0, (int) shade, 0));\r\n }\r\n else {\r\n plot.setSectionPaint(key, new Color((int) shade, 0, 0));\r\n }\r\n if (showDifference) {\r\n assert series != null; // suppresses compiler warning\r\n series.setValue(key + \" (\" + (percentChange >= 0 ? \"+\" : \"\")\r\n + NumberFormat.getPercentInstance().format(\r\n percentChange / 100.0) + \")\", newValue);\r\n }\r\n }\r\n }\r\n\r\n if (showDifference) {\r\n plot.setDataset(series);\r\n }\r\n\r\n JFreeChart chart = new JFreeChart(title,\r\n JFreeChart.DEFAULT_TITLE_FONT, plot, legend);\r\n\r\n if (subTitle) {\r\n TextTitle subtitle = new TextTitle(\"Bright \" + (greenForIncrease \r\n ? \"red\" : \"green\") + \"=change >=-\" + percentDiffForMaxScale\r\n + \"%, Bright \" + (!greenForIncrease ? \"red\" : \"green\")\r\n + \"=change >=+\" + percentDiffForMaxScale + \"%\",\r\n new Font(\"SansSerif\", Font.PLAIN, 10));\r\n chart.addSubtitle(subtitle);\r\n }\r\n currentTheme.apply(chart);\r\n return chart;\r\n }\r\n\r\n /**\r\n * Creates a ring chart with default settings.\r\n * <P>\r\n * The chart object returned by this method uses a {@link RingPlot}\r\n * instance as the plot.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param locale the locale (<code>null</code> not permitted).\r\n *\r\n * @return A ring chart.\r\n *\r\n * @since 1.0.7\r\n */\r\n public static JFreeChart createRingChart(String title, PieDataset dataset,\r\n boolean legend, boolean tooltips, Locale locale) {\r\n\r\n RingPlot plot = new RingPlot(dataset);\r\n plot.setLabelGenerator(new StandardPieSectionLabelGenerator(locale));\r\n plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));\r\n if (tooltips) {\r\n plot.setToolTipGenerator(new StandardPieToolTipGenerator(locale));\r\n }\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n }\r\n\r\n /**\r\n * Creates a ring chart with default settings.\r\n * <P>\r\n * The chart object returned by this method uses a {@link RingPlot}\r\n * instance as the plot.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A ring chart.\r\n */\r\n public static JFreeChart createRingChart(String title, PieDataset dataset,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n RingPlot plot = new RingPlot(dataset);\r\n plot.setLabelGenerator(new StandardPieSectionLabelGenerator());\r\n plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));\r\n if (tooltips) {\r\n plot.setToolTipGenerator(new StandardPieToolTipGenerator());\r\n }\r\n if (urls) {\r\n plot.setURLGenerator(new StandardPieURLGenerator());\r\n }\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a chart that displays multiple pie plots. The chart object\r\n * returned by this method uses a {@link MultiplePiePlot} instance as the\r\n * plot.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n * @param order the order that the data is extracted (by row or by column)\r\n * (<code>null</code> not permitted).\r\n * @param legend include a legend?\r\n * @param tooltips generate tooltips?\r\n * @param urls generate URLs?\r\n *\r\n * @return A chart.\r\n */\r\n public static JFreeChart createMultiplePieChart(String title,\r\n CategoryDataset dataset, TableOrder order, boolean legend,\r\n boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n MultiplePiePlot plot = new MultiplePiePlot(dataset);\r\n plot.setDataExtractOrder(order);\r\n plot.setBackgroundPaint(null);\r\n plot.setOutlineStroke(null);\r\n\r\n if (tooltips) {\r\n PieToolTipGenerator tooltipGenerator\r\n = new StandardPieToolTipGenerator();\r\n PiePlot pp = (PiePlot) plot.getPieChart().getPlot();\r\n pp.setToolTipGenerator(tooltipGenerator);\r\n }\r\n\r\n if (urls) {\r\n PieURLGenerator urlGenerator = new StandardPieURLGenerator();\r\n PiePlot pp = (PiePlot) plot.getPieChart().getPlot();\r\n pp.setURLGenerator(urlGenerator);\r\n }\r\n\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a 3D pie chart using the specified dataset. The chart object\r\n * returned by this method uses a {@link PiePlot3D} instance as the\r\n * plot.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param locale the locale (<code>null</code> not permitted).\r\n *\r\n * @return A pie chart.\r\n *\r\n * @since 1.0.7\r\n */\r\n public static JFreeChart createPieChart3D(String title, PieDataset dataset,\r\n boolean legend, boolean tooltips, Locale locale) {\r\n\r\n ParamChecks.nullNotPermitted(locale, \"locale\");\r\n PiePlot3D plot = new PiePlot3D(dataset);\r\n plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));\r\n if (tooltips) {\r\n plot.setToolTipGenerator(new StandardPieToolTipGenerator(locale));\r\n }\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a 3D pie chart using the specified dataset. The chart object\r\n * returned by this method uses a {@link PiePlot3D} instance as the\r\n * plot.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A pie chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createPieChart3D(String title,\r\n PieDataset dataset) {\r\n return createPieChart3D(title, dataset, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates a 3D pie chart using the specified dataset. The chart object\r\n * returned by this method uses a {@link PiePlot3D} instance as the\r\n * plot.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A pie chart.\r\n */\r\n public static JFreeChart createPieChart3D(String title, PieDataset dataset,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n PiePlot3D plot = new PiePlot3D(dataset);\r\n plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));\r\n if (tooltips) {\r\n plot.setToolTipGenerator(new StandardPieToolTipGenerator());\r\n }\r\n if (urls) {\r\n plot.setURLGenerator(new StandardPieURLGenerator());\r\n }\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a chart that displays multiple pie plots. The chart object\r\n * returned by this method uses a {@link MultiplePiePlot} instance as the\r\n * plot.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n * @param order the order that the data is extracted (by row or by column)\r\n * (<code>null</code> not permitted).\r\n * @param legend include a legend?\r\n * @param tooltips generate tooltips?\r\n * @param urls generate URLs?\r\n *\r\n * @return A chart.\r\n */\r\n public static JFreeChart createMultiplePieChart3D(String title,\r\n CategoryDataset dataset, TableOrder order, boolean legend,\r\n boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n MultiplePiePlot plot = new MultiplePiePlot(dataset);\r\n plot.setDataExtractOrder(order);\r\n plot.setBackgroundPaint(null);\r\n plot.setOutlineStroke(null);\r\n\r\n JFreeChart pieChart = new JFreeChart(new PiePlot3D(null));\r\n TextTitle seriesTitle = new TextTitle(\"Series Title\",\r\n new Font(\"SansSerif\", Font.BOLD, 12));\r\n seriesTitle.setPosition(RectangleEdge.BOTTOM);\r\n pieChart.setTitle(seriesTitle);\r\n pieChart.removeLegend();\r\n pieChart.setBackgroundPaint(null);\r\n plot.setPieChart(pieChart);\r\n\r\n if (tooltips) {\r\n PieToolTipGenerator tooltipGenerator\r\n = new StandardPieToolTipGenerator();\r\n PiePlot pp = (PiePlot) plot.getPieChart().getPlot();\r\n pp.setToolTipGenerator(tooltipGenerator);\r\n }\r\n\r\n if (urls) {\r\n PieURLGenerator urlGenerator = new StandardPieURLGenerator();\r\n PiePlot pp = (PiePlot) plot.getPieChart().getPlot();\r\n pp.setURLGenerator(urlGenerator);\r\n }\r\n\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a bar chart with a vertical orientation. The chart object\r\n * returned by this method uses a {@link CategoryPlot} instance as the\r\n * plot, with a {@link CategoryAxis} for the domain axis, a\r\n * {@link NumberAxis} as the range axis, and a {@link BarRenderer} as the\r\n * renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel the label for the value axis\r\n * (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A bar chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createBarChart(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n CategoryDataset dataset) {\r\n return createBarChart(title, categoryAxisLabel, valueAxisLabel, dataset,\r\n PlotOrientation.VERTICAL, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates a bar chart. The chart object returned by this method uses a\r\n * {@link CategoryPlot} instance as the plot, with a {@link CategoryAxis}\r\n * for the domain axis, a {@link NumberAxis} as the range axis, and a\r\n * {@link BarRenderer} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel the label for the value axis\r\n * (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the plot orientation (horizontal or vertical)\r\n * (<code>null</code> not permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A bar chart.\r\n */\r\n public static JFreeChart createBarChart(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n CategoryDataset dataset, PlotOrientation orientation,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);\r\n ValueAxis valueAxis = new NumberAxis(valueAxisLabel);\r\n\r\n BarRenderer renderer = new BarRenderer();\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n ItemLabelPosition position1 = new ItemLabelPosition(\r\n ItemLabelAnchor.OUTSIDE3, TextAnchor.CENTER_LEFT);\r\n renderer.setBasePositiveItemLabelPosition(position1);\r\n ItemLabelPosition position2 = new ItemLabelPosition(\r\n ItemLabelAnchor.OUTSIDE9, TextAnchor.CENTER_RIGHT);\r\n renderer.setBaseNegativeItemLabelPosition(position2);\r\n } else if (orientation == PlotOrientation.VERTICAL) {\r\n ItemLabelPosition position1 = new ItemLabelPosition(\r\n ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER);\r\n renderer.setBasePositiveItemLabelPosition(position1);\r\n ItemLabelPosition position2 = new ItemLabelPosition(\r\n ItemLabelAnchor.OUTSIDE6, TextAnchor.TOP_CENTER);\r\n renderer.setBaseNegativeItemLabelPosition(position2);\r\n }\r\n if (tooltips) {\r\n renderer.setBaseToolTipGenerator(\r\n new StandardCategoryToolTipGenerator());\r\n }\r\n if (urls) {\r\n renderer.setBaseItemURLGenerator(\r\n new StandardCategoryURLGenerator());\r\n }\r\n\r\n CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,\r\n renderer);\r\n plot.setOrientation(orientation);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a stacked bar chart with default settings. The chart object\r\n * returned by this method uses a {@link CategoryPlot} instance as the\r\n * plot, with a {@link CategoryAxis} for the domain axis, a\r\n * {@link NumberAxis} as the range axis, and a {@link StackedBarRenderer}\r\n * as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param domainAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param rangeAxisLabel the label for the value axis\r\n * (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A stacked bar chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createStackedBarChart(String title,\r\n String domainAxisLabel, String rangeAxisLabel,\r\n CategoryDataset dataset) {\r\n return createStackedBarChart(title, domainAxisLabel, rangeAxisLabel,\r\n dataset, PlotOrientation.VERTICAL, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates a stacked bar chart with default settings. The chart object\r\n * returned by this method uses a {@link CategoryPlot} instance as the\r\n * plot, with a {@link CategoryAxis} for the domain axis, a\r\n * {@link NumberAxis} as the range axis, and a {@link StackedBarRenderer}\r\n * as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param domainAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param rangeAxisLabel the label for the value axis\r\n * (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the orientation of the chart (horizontal or\r\n * vertical) (<code>null</code> not permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A stacked bar chart.\r\n */\r\n public static JFreeChart createStackedBarChart(String title,\r\n String domainAxisLabel, String rangeAxisLabel,\r\n CategoryDataset dataset, PlotOrientation orientation,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n\r\n CategoryAxis categoryAxis = new CategoryAxis(domainAxisLabel);\r\n ValueAxis valueAxis = new NumberAxis(rangeAxisLabel);\r\n\r\n StackedBarRenderer renderer = new StackedBarRenderer();\r\n if (tooltips) {\r\n renderer.setBaseToolTipGenerator(\r\n new StandardCategoryToolTipGenerator());\r\n }\r\n if (urls) {\r\n renderer.setBaseItemURLGenerator(\r\n new StandardCategoryURLGenerator());\r\n }\r\n\r\n CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,\r\n renderer);\r\n plot.setOrientation(orientation);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a bar chart with a 3D effect. The chart object returned by this\r\n * method uses a {@link CategoryPlot} instance as the plot, with a\r\n * {@link CategoryAxis3D} for the domain axis, a {@link NumberAxis3D} as\r\n * the range axis, and a {@link BarRenderer3D} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel the label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A bar chart with a 3D effect.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createBarChart3D(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n CategoryDataset dataset) {\r\n return createBarChart3D(title, categoryAxisLabel, valueAxisLabel,\r\n dataset, PlotOrientation.VERTICAL, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates a bar chart with a 3D effect. The chart object returned by this\r\n * method uses a {@link CategoryPlot} instance as the plot, with a\r\n * {@link CategoryAxis3D} for the domain axis, a {@link NumberAxis3D} as\r\n * the range axis, and a {@link BarRenderer3D} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel the label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the plot orientation (horizontal or vertical)\r\n * (<code>null</code> not permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A bar chart with a 3D effect.\r\n */\r\n public static JFreeChart createBarChart3D(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n CategoryDataset dataset, PlotOrientation orientation,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n CategoryAxis categoryAxis = new CategoryAxis3D(categoryAxisLabel);\r\n ValueAxis valueAxis = new NumberAxis3D(valueAxisLabel);\r\n\r\n BarRenderer3D renderer = new BarRenderer3D();\r\n if (tooltips) {\r\n renderer.setBaseToolTipGenerator(\r\n new StandardCategoryToolTipGenerator());\r\n }\r\n if (urls) {\r\n renderer.setBaseItemURLGenerator(\r\n new StandardCategoryURLGenerator());\r\n }\r\n\r\n CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,\r\n renderer);\r\n plot.setOrientation(orientation);\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n // change rendering order to ensure that bar overlapping is the\r\n // right way around\r\n plot.setRowRenderingOrder(SortOrder.DESCENDING);\r\n plot.setColumnRenderingOrder(SortOrder.DESCENDING);\r\n }\r\n plot.setForegroundAlpha(0.75f);\r\n\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a stacked bar chart with a 3D effect and default settings. The\r\n * chart object returned by this method uses a {@link CategoryPlot}\r\n * instance as the plot, with a {@link CategoryAxis3D} for the domain axis,\r\n * a {@link NumberAxis3D} as the range axis, and a\r\n * {@link StackedBarRenderer3D} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel the label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A stacked bar chart with a 3D effect.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createStackedBarChart3D(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n CategoryDataset dataset) {\r\n return createStackedBarChart3D(title, categoryAxisLabel, valueAxisLabel,\r\n dataset, PlotOrientation.VERTICAL, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates a stacked bar chart with a 3D effect and default settings. The\r\n * chart object returned by this method uses a {@link CategoryPlot}\r\n * instance as the plot, with a {@link CategoryAxis3D} for the domain axis,\r\n * a {@link NumberAxis3D} as the range axis, and a\r\n * {@link StackedBarRenderer3D} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel the label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the orientation (horizontal or vertical)\r\n * (<code>null</code> not permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A stacked bar chart with a 3D effect.\r\n */\r\n public static JFreeChart createStackedBarChart3D(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n CategoryDataset dataset, PlotOrientation orientation,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n CategoryAxis categoryAxis = new CategoryAxis3D(categoryAxisLabel);\r\n ValueAxis valueAxis = new NumberAxis3D(valueAxisLabel);\r\n\r\n // create the renderer...\r\n CategoryItemRenderer renderer = new StackedBarRenderer3D();\r\n if (tooltips) {\r\n renderer.setBaseToolTipGenerator(\r\n new StandardCategoryToolTipGenerator());\r\n }\r\n if (urls) {\r\n renderer.setBaseItemURLGenerator(\r\n new StandardCategoryURLGenerator());\r\n }\r\n\r\n // create the plot...\r\n CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,\r\n renderer);\r\n plot.setOrientation(orientation);\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n // change rendering order to ensure that bar overlapping is the\r\n // right way around\r\n plot.setColumnRenderingOrder(SortOrder.DESCENDING);\r\n }\r\n\r\n // create the chart...\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates an area chart with default settings. The chart object returned\r\n * by this method uses a {@link CategoryPlot} instance as the plot, with a\r\n * {@link CategoryAxis} for the domain axis, a {@link NumberAxis} as the\r\n * range axis, and an {@link AreaRenderer} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel the label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return An area chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createAreaChart(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n CategoryDataset dataset) {\r\n return createAreaChart(title, categoryAxisLabel, valueAxisLabel,\r\n dataset, PlotOrientation.VERTICAL, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates an area chart with default settings. The chart object returned\r\n * by this method uses a {@link CategoryPlot} instance as the plot, with a\r\n * {@link CategoryAxis} for the domain axis, a {@link NumberAxis} as the\r\n * range axis, and an {@link AreaRenderer} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel the label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the plot orientation (<code>null</code> not\r\n * permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return An area chart.\r\n */\r\n public static JFreeChart createAreaChart(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n CategoryDataset dataset, PlotOrientation orientation,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);\r\n categoryAxis.setCategoryMargin(0.0);\r\n\r\n ValueAxis valueAxis = new NumberAxis(valueAxisLabel);\r\n\r\n AreaRenderer renderer = new AreaRenderer();\r\n if (tooltips) {\r\n renderer.setBaseToolTipGenerator(\r\n new StandardCategoryToolTipGenerator());\r\n }\r\n if (urls) {\r\n renderer.setBaseItemURLGenerator(\r\n new StandardCategoryURLGenerator());\r\n }\r\n\r\n CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,\r\n renderer);\r\n plot.setOrientation(orientation);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a stacked area chart with default settings. The chart object\r\n * returned by this method uses a {@link CategoryPlot} instance as the\r\n * plot, with a {@link CategoryAxis} for the domain axis, a\r\n * {@link NumberAxis} as the range axis, and a {@link StackedAreaRenderer}\r\n * as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel the label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A stacked area chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createStackedAreaChart(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n CategoryDataset dataset) {\r\n return createStackedAreaChart(title, categoryAxisLabel, valueAxisLabel,\r\n dataset, PlotOrientation.VERTICAL, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates a stacked area chart with default settings. The chart object\r\n * returned by this method uses a {@link CategoryPlot} instance as the\r\n * plot, with a {@link CategoryAxis} for the domain axis, a\r\n * {@link NumberAxis} as the range axis, and a {@link StackedAreaRenderer}\r\n * as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel the label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the plot orientation (horizontal or vertical)\r\n * (<code>null</code> not permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A stacked area chart.\r\n */\r\n public static JFreeChart createStackedAreaChart(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n CategoryDataset dataset, PlotOrientation orientation,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);\r\n categoryAxis.setCategoryMargin(0.0);\r\n ValueAxis valueAxis = new NumberAxis(valueAxisLabel);\r\n\r\n StackedAreaRenderer renderer = new StackedAreaRenderer();\r\n if (tooltips) {\r\n renderer.setBaseToolTipGenerator(\r\n new StandardCategoryToolTipGenerator());\r\n }\r\n if (urls) {\r\n renderer.setBaseItemURLGenerator(\r\n new StandardCategoryURLGenerator());\r\n }\r\n\r\n CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,\r\n renderer);\r\n plot.setOrientation(orientation);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a line chart with default settings. The chart object returned\r\n * by this method uses a {@link CategoryPlot} instance as the plot, with a\r\n * {@link CategoryAxis} for the domain axis, a {@link NumberAxis} as the\r\n * range axis, and a {@link LineAndShapeRenderer} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel the label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A line chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createLineChart(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n CategoryDataset dataset) {\r\n return createLineChart(title, categoryAxisLabel, valueAxisLabel,\r\n dataset, PlotOrientation.VERTICAL, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates a line chart with default settings. The chart object returned\r\n * by this method uses a {@link CategoryPlot} instance as the plot, with a\r\n * {@link CategoryAxis} for the domain axis, a {@link NumberAxis} as the\r\n * range axis, and a {@link LineAndShapeRenderer} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel the label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the chart orientation (horizontal or vertical)\r\n * (<code>null</code> not permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A line chart.\r\n */\r\n public static JFreeChart createLineChart(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n CategoryDataset dataset, PlotOrientation orientation,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);\r\n ValueAxis valueAxis = new NumberAxis(valueAxisLabel);\r\n\r\n LineAndShapeRenderer renderer = new LineAndShapeRenderer(true, false);\r\n if (tooltips) {\r\n renderer.setBaseToolTipGenerator(\r\n new StandardCategoryToolTipGenerator());\r\n }\r\n if (urls) {\r\n renderer.setBaseItemURLGenerator(\r\n new StandardCategoryURLGenerator());\r\n }\r\n CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,\r\n renderer);\r\n plot.setOrientation(orientation);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a line chart with default settings. The chart object returned by\r\n * this method uses a {@link CategoryPlot} instance as the plot, with a\r\n * {@link CategoryAxis3D} for the domain axis, a {@link NumberAxis3D} as\r\n * the range axis, and a {@link LineRenderer3D} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel the label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A line chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createLineChart3D(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n CategoryDataset dataset) {\r\n return createLineChart3D(title, categoryAxisLabel, valueAxisLabel,\r\n dataset, PlotOrientation.VERTICAL, true, true, false);\r\n } \r\n \r\n /**\r\n * Creates a line chart with default settings. The chart object returned by\r\n * this method uses a {@link CategoryPlot} instance as the plot, with a\r\n * {@link CategoryAxis3D} for the domain axis, a {@link NumberAxis3D} as\r\n * the range axis, and a {@link LineRenderer3D} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel the label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the chart orientation (horizontal or vertical)\r\n * (<code>null</code> not permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A line chart.\r\n */\r\n public static JFreeChart createLineChart3D(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n CategoryDataset dataset, PlotOrientation orientation,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n CategoryAxis categoryAxis = new CategoryAxis3D(categoryAxisLabel);\r\n ValueAxis valueAxis = new NumberAxis3D(valueAxisLabel);\r\n\r\n LineRenderer3D renderer = new LineRenderer3D();\r\n if (tooltips) {\r\n renderer.setBaseToolTipGenerator(\r\n new StandardCategoryToolTipGenerator());\r\n }\r\n if (urls) {\r\n renderer.setBaseItemURLGenerator(\r\n new StandardCategoryURLGenerator());\r\n }\r\n CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,\r\n renderer);\r\n plot.setOrientation(orientation);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a Gantt chart using the supplied attributes plus default values\r\n * where required. The chart object returned by this method uses a\r\n * {@link CategoryPlot} instance as the plot, with a {@link CategoryAxis}\r\n * for the domain axis, a {@link DateAxis} as the range axis, and a\r\n * {@link GanttRenderer} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param dateAxisLabel the label for the date axis\r\n * (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A Gantt chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createGanttChart(String title,\r\n String categoryAxisLabel, String dateAxisLabel,\r\n IntervalCategoryDataset dataset) {\r\n return createGanttChart(title, categoryAxisLabel, dateAxisLabel,\r\n dataset, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates a Gantt chart using the supplied attributes plus default values\r\n * where required. The chart object returned by this method uses a\r\n * {@link CategoryPlot} instance as the plot, with a {@link CategoryAxis}\r\n * for the domain axis, a {@link DateAxis} as the range axis, and a\r\n * {@link GanttRenderer} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param dateAxisLabel the label for the date axis\r\n * (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A Gantt chart.\r\n */\r\n public static JFreeChart createGanttChart(String title,\r\n String categoryAxisLabel, String dateAxisLabel,\r\n IntervalCategoryDataset dataset, boolean legend, boolean tooltips,\r\n boolean urls) {\r\n\r\n CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);\r\n DateAxis dateAxis = new DateAxis(dateAxisLabel);\r\n\r\n CategoryItemRenderer renderer = new GanttRenderer();\r\n if (tooltips) {\r\n renderer.setBaseToolTipGenerator(\r\n new IntervalCategoryToolTipGenerator(\r\n \"{3} - {4}\", DateFormat.getDateInstance()));\r\n }\r\n if (urls) {\r\n renderer.setBaseItemURLGenerator(\r\n new StandardCategoryURLGenerator());\r\n }\r\n\r\n CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, dateAxis,\r\n renderer);\r\n plot.setOrientation(PlotOrientation.HORIZONTAL);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a waterfall chart. The chart object returned by this method\r\n * uses a {@link CategoryPlot} instance as the plot, with a\r\n * {@link CategoryAxis} for the domain axis, a {@link NumberAxis} as the\r\n * range axis, and a {@link WaterfallBarRenderer} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel the label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel the label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the plot orientation (horizontal or vertical)\r\n * (<code>null</code> NOT permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A waterfall chart.\r\n */\r\n public static JFreeChart createWaterfallChart(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n CategoryDataset dataset, PlotOrientation orientation,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);\r\n categoryAxis.setCategoryMargin(0.0);\r\n\r\n ValueAxis valueAxis = new NumberAxis(valueAxisLabel);\r\n\r\n WaterfallBarRenderer renderer = new WaterfallBarRenderer();\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n ItemLabelPosition position = new ItemLabelPosition(\r\n ItemLabelAnchor.CENTER, TextAnchor.CENTER,\r\n TextAnchor.CENTER, Math.PI / 2.0);\r\n renderer.setBasePositiveItemLabelPosition(position);\r\n renderer.setBaseNegativeItemLabelPosition(position);\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n ItemLabelPosition position = new ItemLabelPosition(\r\n ItemLabelAnchor.CENTER, TextAnchor.CENTER,\r\n TextAnchor.CENTER, 0.0);\r\n renderer.setBasePositiveItemLabelPosition(position);\r\n renderer.setBaseNegativeItemLabelPosition(position);\r\n }\r\n if (tooltips) {\r\n StandardCategoryToolTipGenerator generator\r\n = new StandardCategoryToolTipGenerator();\r\n renderer.setBaseToolTipGenerator(generator);\r\n }\r\n if (urls) {\r\n renderer.setBaseItemURLGenerator(\r\n new StandardCategoryURLGenerator());\r\n }\r\n\r\n CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,\r\n renderer);\r\n plot.clearRangeMarkers();\r\n Marker baseline = new ValueMarker(0.0);\r\n baseline.setPaint(Color.black);\r\n plot.addRangeMarker(baseline, Layer.FOREGROUND);\r\n plot.setOrientation(orientation);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a polar plot for the specified dataset (x-values interpreted as\r\n * angles in degrees). The chart object returned by this method uses a\r\n * {@link PolarPlot} instance as the plot, with a {@link NumberAxis} for\r\n * the radial axis.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n * @param legend legend required?\r\n * @param tooltips tooltips required?\r\n * @param urls URLs required?\r\n *\r\n * @return A chart.\r\n */\r\n public static JFreeChart createPolarChart(String title, XYDataset dataset,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n PolarPlot plot = new PolarPlot();\r\n plot.setDataset(dataset);\r\n NumberAxis rangeAxis = new NumberAxis();\r\n rangeAxis.setAxisLineVisible(false);\r\n rangeAxis.setTickMarksVisible(false);\r\n rangeAxis.setTickLabelInsets(new RectangleInsets(0.0, 0.0, 0.0, 0.0));\r\n plot.setAxis(rangeAxis);\r\n plot.setRenderer(new DefaultPolarItemRenderer());\r\n JFreeChart chart = new JFreeChart(\r\n title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n \r\n /**\r\n * Creates a scatter plot with default settings. The chart object\r\n * returned by this method uses an {@link XYPlot} instance as the plot,\r\n * with a {@link NumberAxis} for the domain axis, a {@link NumberAxis}\r\n * as the range axis, and an {@link XYLineAndShapeRenderer} as the\r\n * renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A scatter plot.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createScatterPlot(String title, String xAxisLabel,\r\n String yAxisLabel, XYDataset dataset) {\r\n return createScatterPlot(title, xAxisLabel, yAxisLabel, dataset,\r\n PlotOrientation.VERTICAL, true, true, false);\r\n }\r\n\r\n /**\r\n * Creates a scatter plot with default settings. The chart object\r\n * returned by this method uses an {@link XYPlot} instance as the plot,\r\n * with a {@link NumberAxis} for the domain axis, a {@link NumberAxis}\r\n * as the range axis, and an {@link XYLineAndShapeRenderer} as the\r\n * renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the plot orientation (horizontal or vertical)\r\n * (<code>null</code> NOT permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A scatter plot.\r\n */\r\n public static JFreeChart createScatterPlot(String title, String xAxisLabel,\r\n String yAxisLabel, XYDataset dataset, PlotOrientation orientation,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n NumberAxis xAxis = new NumberAxis(xAxisLabel);\r\n xAxis.setAutoRangeIncludesZero(false);\r\n NumberAxis yAxis = new NumberAxis(yAxisLabel);\r\n yAxis.setAutoRangeIncludesZero(false);\r\n\r\n XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null);\r\n\r\n XYToolTipGenerator toolTipGenerator = null;\r\n if (tooltips) {\r\n toolTipGenerator = new StandardXYToolTipGenerator();\r\n }\r\n\r\n XYURLGenerator urlGenerator = null;\r\n if (urls) {\r\n urlGenerator = new StandardXYURLGenerator();\r\n }\r\n XYItemRenderer renderer = new XYLineAndShapeRenderer(false, true);\r\n renderer.setBaseToolTipGenerator(toolTipGenerator);\r\n renderer.setURLGenerator(urlGenerator);\r\n plot.setRenderer(renderer);\r\n plot.setOrientation(orientation);\r\n\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates and returns a default instance of an XY bar chart.\r\n * <P>\r\n * The chart object returned by this method uses an {@link XYPlot} instance\r\n * as the plot, with a {@link DateAxis} for the domain axis, a\r\n * {@link NumberAxis} as the range axis, and a {@link XYBarRenderer} as the\r\n * renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param dateAxis make the domain axis display dates?\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return An XY bar chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createXYBarChart(String title, String xAxisLabel,\r\n boolean dateAxis, String yAxisLabel, IntervalXYDataset dataset) {\r\n return createXYBarChart(title, xAxisLabel, dateAxis, yAxisLabel,\r\n dataset, PlotOrientation.VERTICAL, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates and returns a default instance of an XY bar chart.\r\n * <P>\r\n * The chart object returned by this method uses an {@link XYPlot} instance\r\n * as the plot, with a {@link DateAxis} for the domain axis, a\r\n * {@link NumberAxis} as the range axis, and a {@link XYBarRenderer} as the\r\n * renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param dateAxis make the domain axis display dates?\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the orientation (horizontal or vertical)\r\n * (<code>null</code> NOT permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return An XY bar chart.\r\n */\r\n public static JFreeChart createXYBarChart(String title, String xAxisLabel,\r\n boolean dateAxis, String yAxisLabel, IntervalXYDataset dataset,\r\n PlotOrientation orientation, boolean legend, boolean tooltips,\r\n boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n ValueAxis domainAxis;\r\n if (dateAxis) {\r\n domainAxis = new DateAxis(xAxisLabel);\r\n }\r\n else {\r\n NumberAxis axis = new NumberAxis(xAxisLabel);\r\n axis.setAutoRangeIncludesZero(false);\r\n domainAxis = axis;\r\n }\r\n ValueAxis valueAxis = new NumberAxis(yAxisLabel);\r\n\r\n XYBarRenderer renderer = new XYBarRenderer();\r\n if (tooltips) {\r\n XYToolTipGenerator tt;\r\n if (dateAxis) {\r\n tt = StandardXYToolTipGenerator.getTimeSeriesInstance();\r\n }\r\n else {\r\n tt = new StandardXYToolTipGenerator();\r\n }\r\n renderer.setBaseToolTipGenerator(tt);\r\n }\r\n if (urls) {\r\n renderer.setURLGenerator(new StandardXYURLGenerator());\r\n }\r\n\r\n XYPlot plot = new XYPlot(dataset, domainAxis, valueAxis, renderer);\r\n plot.setOrientation(orientation);\r\n\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates an area chart using an {@link XYDataset}.\r\n * <P>\r\n * The chart object returned by this method uses an {@link XYPlot} instance\r\n * as the plot, with a {@link NumberAxis} for the domain axis, a\r\n * {@link NumberAxis} as the range axis, and a {@link XYAreaRenderer} as\r\n * the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return An XY area chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createXYAreaChart(String title,String xAxisLabel,\r\n String yAxisLabel, XYDataset dataset) {\r\n return createXYAreaChart(title, xAxisLabel, yAxisLabel, dataset, \r\n PlotOrientation.VERTICAL, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates an area chart using an {@link XYDataset}.\r\n * <P>\r\n * The chart object returned by this method uses an {@link XYPlot} instance\r\n * as the plot, with a {@link NumberAxis} for the domain axis, a\r\n * {@link NumberAxis} as the range axis, and a {@link XYAreaRenderer} as\r\n * the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the plot orientation (horizontal or vertical)\r\n * (<code>null</code> NOT permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return An XY area chart.\r\n */\r\n public static JFreeChart createXYAreaChart(String title, String xAxisLabel,\r\n String yAxisLabel, XYDataset dataset, PlotOrientation orientation,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n NumberAxis xAxis = new NumberAxis(xAxisLabel);\r\n xAxis.setAutoRangeIncludesZero(false);\r\n NumberAxis yAxis = new NumberAxis(yAxisLabel);\r\n XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null);\r\n plot.setOrientation(orientation);\r\n plot.setForegroundAlpha(0.5f);\r\n\r\n XYToolTipGenerator tipGenerator = null;\r\n if (tooltips) {\r\n tipGenerator = new StandardXYToolTipGenerator();\r\n }\r\n\r\n XYURLGenerator urlGenerator = null;\r\n if (urls) {\r\n urlGenerator = new StandardXYURLGenerator();\r\n }\r\n\r\n plot.setRenderer(new XYAreaRenderer(XYAreaRenderer.AREA, tipGenerator,\r\n urlGenerator));\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a stacked XY area plot. The chart object returned by this\r\n * method uses an {@link XYPlot} instance as the plot, with a\r\n * {@link NumberAxis} for the domain axis, a {@link NumberAxis} as the\r\n * range axis, and a {@link StackedXYAreaRenderer2} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A stacked XY area chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createStackedXYAreaChart(String title,\r\n String xAxisLabel, String yAxisLabel, TableXYDataset dataset) {\r\n return createStackedXYAreaChart(title, xAxisLabel, yAxisLabel,\r\n dataset, PlotOrientation.VERTICAL, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates a stacked XY area plot. The chart object returned by this\r\n * method uses an {@link XYPlot} instance as the plot, with a\r\n * {@link NumberAxis} for the domain axis, a {@link NumberAxis} as the\r\n * range axis, and a {@link StackedXYAreaRenderer2} as the renderer.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the plot orientation (horizontal or vertical)\r\n * (<code>null</code> NOT permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A stacked XY area chart.\r\n */\r\n public static JFreeChart createStackedXYAreaChart(String title,\r\n String xAxisLabel, String yAxisLabel, TableXYDataset dataset,\r\n PlotOrientation orientation, boolean legend, boolean tooltips,\r\n boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n NumberAxis xAxis = new NumberAxis(xAxisLabel);\r\n xAxis.setAutoRangeIncludesZero(false);\r\n xAxis.setLowerMargin(0.0);\r\n xAxis.setUpperMargin(0.0);\r\n NumberAxis yAxis = new NumberAxis(yAxisLabel);\r\n XYToolTipGenerator toolTipGenerator = null;\r\n if (tooltips) {\r\n toolTipGenerator = new StandardXYToolTipGenerator();\r\n }\r\n\r\n XYURLGenerator urlGenerator = null;\r\n if (urls) {\r\n urlGenerator = new StandardXYURLGenerator();\r\n }\r\n StackedXYAreaRenderer2 renderer = new StackedXYAreaRenderer2(\r\n toolTipGenerator, urlGenerator);\r\n renderer.setOutline(true);\r\n XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);\r\n plot.setOrientation(orientation);\r\n\r\n plot.setRangeAxis(yAxis); // forces recalculation of the axis range\r\n\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a line chart (based on an {@link XYDataset}) with default\r\n * settings.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return The chart.\r\n */\r\n public static JFreeChart createXYLineChart(String title,\r\n String xAxisLabel, String yAxisLabel, XYDataset dataset) {\r\n return createXYLineChart(title, xAxisLabel, yAxisLabel, dataset,\r\n PlotOrientation.VERTICAL, true, true, false);\r\n }\r\n\r\n /**\r\n * Creates a line chart (based on an {@link XYDataset}) with default\r\n * settings.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the plot orientation (horizontal or vertical)\r\n * (<code>null</code> NOT permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return The chart.\r\n */\r\n public static JFreeChart createXYLineChart(String title, String xAxisLabel,\r\n String yAxisLabel, XYDataset dataset, PlotOrientation orientation,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n NumberAxis xAxis = new NumberAxis(xAxisLabel);\r\n xAxis.setAutoRangeIncludesZero(false);\r\n NumberAxis yAxis = new NumberAxis(yAxisLabel);\r\n XYItemRenderer renderer = new XYLineAndShapeRenderer(true, false);\r\n XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);\r\n plot.setOrientation(orientation);\r\n if (tooltips) {\r\n renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());\r\n }\r\n if (urls) {\r\n renderer.setURLGenerator(new StandardXYURLGenerator());\r\n }\r\n\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a stepped XY plot with default settings.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createXYStepChart(String title, String xAxisLabel,\r\n String yAxisLabel, XYDataset dataset) {\r\n return createXYStepChart(title, xAxisLabel, yAxisLabel, dataset,\r\n PlotOrientation.VERTICAL, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates a stepped XY plot with default settings.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the plot orientation (horizontal or vertical)\r\n * (<code>null</code> NOT permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A chart.\r\n */\r\n public static JFreeChart createXYStepChart(String title, String xAxisLabel,\r\n String yAxisLabel, XYDataset dataset, PlotOrientation orientation,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n DateAxis xAxis = new DateAxis(xAxisLabel);\r\n NumberAxis yAxis = new NumberAxis(yAxisLabel);\r\n yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());\r\n\r\n XYToolTipGenerator toolTipGenerator = null;\r\n if (tooltips) {\r\n toolTipGenerator = new StandardXYToolTipGenerator();\r\n }\r\n\r\n XYURLGenerator urlGenerator = null;\r\n if (urls) {\r\n urlGenerator = new StandardXYURLGenerator();\r\n }\r\n XYItemRenderer renderer = new XYStepRenderer(toolTipGenerator,\r\n urlGenerator);\r\n\r\n XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null);\r\n plot.setRenderer(renderer);\r\n plot.setOrientation(orientation);\r\n plot.setDomainCrosshairVisible(false);\r\n plot.setRangeCrosshairVisible(false);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a filled stepped XY plot with default settings.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createXYStepAreaChart(String title,\r\n String xAxisLabel, String yAxisLabel, XYDataset dataset) {\r\n return createXYStepAreaChart(title, xAxisLabel, yAxisLabel, dataset,\r\n PlotOrientation.VERTICAL, true, true, false); \r\n }\r\n \r\n /**\r\n * Creates a filled stepped XY plot with default settings.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the plot orientation (horizontal or vertical)\r\n * (<code>null</code> NOT permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A chart.\r\n */\r\n public static JFreeChart createXYStepAreaChart(String title, \r\n String xAxisLabel, String yAxisLabel, XYDataset dataset,\r\n PlotOrientation orientation, boolean legend, boolean tooltips,\r\n boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n NumberAxis xAxis = new NumberAxis(xAxisLabel);\r\n xAxis.setAutoRangeIncludesZero(false);\r\n NumberAxis yAxis = new NumberAxis(yAxisLabel);\r\n\r\n XYToolTipGenerator toolTipGenerator = null;\r\n if (tooltips) {\r\n toolTipGenerator = new StandardXYToolTipGenerator();\r\n }\r\n\r\n XYURLGenerator urlGenerator = null;\r\n if (urls) {\r\n urlGenerator = new StandardXYURLGenerator();\r\n }\r\n XYItemRenderer renderer = new XYStepAreaRenderer(\r\n XYStepAreaRenderer.AREA_AND_SHAPES, toolTipGenerator,\r\n urlGenerator);\r\n\r\n XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null);\r\n plot.setRenderer(renderer);\r\n plot.setOrientation(orientation);\r\n plot.setDomainCrosshairVisible(false);\r\n plot.setRangeCrosshairVisible(false);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n }\r\n\r\n /**\r\n * Creates and returns a time series chart. A time series chart is an\r\n * {@link XYPlot} with a {@link DateAxis} for the x-axis and a\r\n * {@link NumberAxis} for the y-axis. The default renderer is an\r\n * {@link XYLineAndShapeRenderer}.\r\n * <P>\r\n * A convenient dataset to use with this chart is a\r\n * {@link org.jfree.data.time.TimeSeriesCollection}.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param timeAxisLabel a label for the time axis (<code>null</code>\r\n * permitted).\r\n * @param valueAxisLabel a label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A time series chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createTimeSeriesChart(String title, \r\n String timeAxisLabel, String valueAxisLabel, XYDataset dataset) {\r\n return createTimeSeriesChart(title, timeAxisLabel, valueAxisLabel, \r\n dataset, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates and returns a time series chart. A time series chart is an\r\n * {@link XYPlot} with a {@link DateAxis} for the x-axis and a\r\n * {@link NumberAxis} for the y-axis. The default renderer is an\r\n * {@link XYLineAndShapeRenderer}.\r\n * <P>\r\n * A convenient dataset to use with this chart is a\r\n * {@link org.jfree.data.time.TimeSeriesCollection}.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param timeAxisLabel a label for the time axis (<code>null</code>\r\n * permitted).\r\n * @param valueAxisLabel a label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A time series chart.\r\n */\r\n public static JFreeChart createTimeSeriesChart(String title,\r\n String timeAxisLabel, String valueAxisLabel, XYDataset dataset,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ValueAxis timeAxis = new DateAxis(timeAxisLabel);\r\n timeAxis.setLowerMargin(0.02); // reduce the default margins\r\n timeAxis.setUpperMargin(0.02);\r\n NumberAxis valueAxis = new NumberAxis(valueAxisLabel);\r\n valueAxis.setAutoRangeIncludesZero(false); // override default\r\n XYPlot plot = new XYPlot(dataset, timeAxis, valueAxis, null);\r\n\r\n XYToolTipGenerator toolTipGenerator = null;\r\n if (tooltips) {\r\n toolTipGenerator\r\n = StandardXYToolTipGenerator.getTimeSeriesInstance();\r\n }\r\n\r\n XYURLGenerator urlGenerator = null;\r\n if (urls) {\r\n urlGenerator = new StandardXYURLGenerator();\r\n }\r\n\r\n XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true,\r\n false);\r\n renderer.setBaseToolTipGenerator(toolTipGenerator);\r\n renderer.setURLGenerator(urlGenerator);\r\n plot.setRenderer(renderer);\r\n\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates and returns a default instance of a candlesticks chart.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param timeAxisLabel a label for the time axis (<code>null</code>\r\n * permitted).\r\n * @param valueAxisLabel a label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n *\r\n * @return A candlestick chart.\r\n */\r\n public static JFreeChart createCandlestickChart(String title,\r\n String timeAxisLabel, String valueAxisLabel, OHLCDataset dataset,\r\n boolean legend) {\r\n\r\n ValueAxis timeAxis = new DateAxis(timeAxisLabel);\r\n NumberAxis valueAxis = new NumberAxis(valueAxisLabel);\r\n XYPlot plot = new XYPlot(dataset, timeAxis, valueAxis, null);\r\n plot.setRenderer(new CandlestickRenderer());\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates and returns a default instance of a high-low-open-close chart.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param timeAxisLabel a label for the time axis (<code>null</code>\r\n * permitted).\r\n * @param valueAxisLabel a label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n *\r\n * @return A high-low-open-close chart.\r\n */\r\n public static JFreeChart createHighLowChart(String title,\r\n String timeAxisLabel, String valueAxisLabel, OHLCDataset dataset,\r\n boolean legend) {\r\n\r\n ValueAxis timeAxis = new DateAxis(timeAxisLabel);\r\n NumberAxis valueAxis = new NumberAxis(valueAxisLabel);\r\n HighLowRenderer renderer = new HighLowRenderer();\r\n renderer.setBaseToolTipGenerator(new HighLowItemLabelGenerator());\r\n XYPlot plot = new XYPlot(dataset, timeAxis, valueAxis, renderer);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates and returns a default instance of a high-low-open-close chart\r\n * with a special timeline. This timeline can be a\r\n * {@link org.jfree.chart.axis.SegmentedTimeline} such as the Monday\r\n * through Friday timeline that will remove Saturdays and Sundays from\r\n * the axis.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param timeAxisLabel a label for the time axis (<code>null</code>\r\n * permitted).\r\n * @param valueAxisLabel a label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param timeline the timeline.\r\n * @param legend a flag specifying whether or not a legend is required.\r\n *\r\n * @return A high-low-open-close chart.\r\n */\r\n public static JFreeChart createHighLowChart(String title,\r\n String timeAxisLabel, String valueAxisLabel, OHLCDataset dataset,\r\n Timeline timeline, boolean legend) {\r\n\r\n DateAxis timeAxis = new DateAxis(timeAxisLabel);\r\n timeAxis.setTimeline(timeline);\r\n NumberAxis valueAxis = new NumberAxis(valueAxisLabel);\r\n HighLowRenderer renderer = new HighLowRenderer();\r\n renderer.setBaseToolTipGenerator(new HighLowItemLabelGenerator());\r\n XYPlot plot = new XYPlot(dataset, timeAxis, valueAxis, renderer);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a bubble chart with default settings. The chart is composed of\r\n * an {@link XYPlot}, with a {@link NumberAxis} for the domain axis,\r\n * a {@link NumberAxis} for the range axis, and an {@link XYBubbleRenderer}\r\n * to draw the data items.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n *\r\n * @return A bubble chart.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static JFreeChart createBubbleChart(String title, String xAxisLabel,\r\n String yAxisLabel, XYZDataset dataset) {\r\n return createBubbleChart(title, xAxisLabel, yAxisLabel, dataset,\r\n PlotOrientation.VERTICAL, true, true, false);\r\n }\r\n \r\n /**\r\n * Creates a bubble chart with default settings. The chart is composed of\r\n * an {@link XYPlot}, with a {@link NumberAxis} for the domain axis,\r\n * a {@link NumberAxis} for the range axis, and an {@link XYBubbleRenderer}\r\n * to draw the data items.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the X-axis (<code>null</code> permitted).\r\n * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param orientation the orientation (horizontal or vertical)\r\n * (<code>null</code> NOT permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A bubble chart.\r\n */\r\n public static JFreeChart createBubbleChart(String title, String xAxisLabel,\r\n String yAxisLabel, XYZDataset dataset, PlotOrientation orientation,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n NumberAxis xAxis = new NumberAxis(xAxisLabel);\r\n xAxis.setAutoRangeIncludesZero(false);\r\n NumberAxis yAxis = new NumberAxis(yAxisLabel);\r\n yAxis.setAutoRangeIncludesZero(false);\r\n\r\n XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null);\r\n\r\n XYItemRenderer renderer = new XYBubbleRenderer(\r\n XYBubbleRenderer.SCALE_ON_RANGE_AXIS);\r\n if (tooltips) {\r\n renderer.setBaseToolTipGenerator(new StandardXYZToolTipGenerator());\r\n }\r\n if (urls) {\r\n renderer.setURLGenerator(new StandardXYZURLGenerator());\r\n }\r\n plot.setRenderer(renderer);\r\n plot.setOrientation(orientation);\r\n\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a histogram chart. This chart is constructed with an\r\n * {@link XYPlot} using an {@link XYBarRenderer}. The domain and range\r\n * axes are {@link NumberAxis} instances.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel the x axis label (<code>null</code> permitted).\r\n * @param yAxisLabel the y axis label (<code>null</code> permitted).\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n * @param orientation the orientation (horizontal or vertical)\r\n * (<code>null</code> NOT permitted).\r\n * @param legend create a legend?\r\n * @param tooltips display tooltips?\r\n * @param urls generate URLs?\r\n *\r\n * @return The chart.\r\n */\r\n public static JFreeChart createHistogram(String title,\r\n String xAxisLabel, String yAxisLabel, IntervalXYDataset dataset,\r\n PlotOrientation orientation, boolean legend, boolean tooltips,\r\n boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n NumberAxis xAxis = new NumberAxis(xAxisLabel);\r\n xAxis.setAutoRangeIncludesZero(false);\r\n ValueAxis yAxis = new NumberAxis(yAxisLabel);\r\n\r\n XYItemRenderer renderer = new XYBarRenderer();\r\n if (tooltips) {\r\n renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());\r\n }\r\n if (urls) {\r\n renderer.setURLGenerator(new StandardXYURLGenerator());\r\n }\r\n\r\n XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);\r\n plot.setOrientation(orientation);\r\n plot.setDomainZeroBaselineVisible(true);\r\n plot.setRangeZeroBaselineVisible(true);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates and returns a default instance of a box and whisker chart\r\n * based on data from a {@link BoxAndWhiskerCategoryDataset}.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param categoryAxisLabel a label for the category axis\r\n * (<code>null</code> permitted).\r\n * @param valueAxisLabel a label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n *\r\n * @return A box and whisker chart.\r\n *\r\n * @since 1.0.4\r\n */\r\n public static JFreeChart createBoxAndWhiskerChart(String title,\r\n String categoryAxisLabel, String valueAxisLabel,\r\n BoxAndWhiskerCategoryDataset dataset, boolean legend) {\r\n\r\n CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);\r\n NumberAxis valueAxis = new NumberAxis(valueAxisLabel);\r\n valueAxis.setAutoRangeIncludesZero(false);\r\n\r\n BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();\r\n renderer.setBaseToolTipGenerator(new BoxAndWhiskerToolTipGenerator());\r\n\r\n CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,\r\n renderer);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n }\r\n\r\n /**\r\n * Creates and returns a default instance of a box and whisker chart.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param timeAxisLabel a label for the time axis (<code>null</code>\r\n * permitted).\r\n * @param valueAxisLabel a label for the value axis (<code>null</code>\r\n * permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param legend a flag specifying whether or not a legend is required.\r\n *\r\n * @return A box and whisker chart.\r\n */\r\n public static JFreeChart createBoxAndWhiskerChart(String title,\r\n String timeAxisLabel, String valueAxisLabel,\r\n BoxAndWhiskerXYDataset dataset, boolean legend) {\r\n\r\n ValueAxis timeAxis = new DateAxis(timeAxisLabel);\r\n NumberAxis valueAxis = new NumberAxis(valueAxisLabel);\r\n valueAxis.setAutoRangeIncludesZero(false);\r\n XYBoxAndWhiskerRenderer renderer = new XYBoxAndWhiskerRenderer(10.0);\r\n XYPlot plot = new XYPlot(dataset, timeAxis, valueAxis, renderer);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a wind plot with default settings.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param xAxisLabel a label for the x-axis (<code>null</code> permitted).\r\n * @param yAxisLabel a label for the y-axis (<code>null</code> permitted).\r\n * @param dataset the dataset for the chart (<code>null</code> permitted).\r\n * @param legend a flag that controls whether or not a legend is created.\r\n * @param tooltips configure chart to generate tool tips?\r\n * @param urls configure chart to generate URLs?\r\n *\r\n * @return A wind plot.\r\n *\r\n */\r\n public static JFreeChart createWindPlot(String title, String xAxisLabel,\r\n String yAxisLabel, WindDataset dataset, boolean legend,\r\n boolean tooltips, boolean urls) {\r\n\r\n ValueAxis xAxis = new DateAxis(xAxisLabel);\r\n ValueAxis yAxis = new NumberAxis(yAxisLabel);\r\n yAxis.setRange(-12.0, 12.0);\r\n\r\n WindItemRenderer renderer = new WindItemRenderer();\r\n if (tooltips) {\r\n renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());\r\n }\r\n if (urls) {\r\n renderer.setURLGenerator(new StandardXYURLGenerator());\r\n }\r\n XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n\r\n }\r\n\r\n /**\r\n * Creates a wafer map chart.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n * @param orientation the plot orientation (horizontal or vertical)\r\n * (<code>null</code> NOT permitted.\r\n * @param legend display a legend?\r\n * @param tooltips generate tooltips?\r\n * @param urls generate URLs?\r\n *\r\n * @return A wafer map chart.\r\n */\r\n public static JFreeChart createWaferMapChart(String title,\r\n WaferMapDataset dataset, PlotOrientation orientation,\r\n boolean legend, boolean tooltips, boolean urls) {\r\n\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n WaferMapPlot plot = new WaferMapPlot(dataset);\r\n WaferMapRenderer renderer = new WaferMapRenderer();\r\n plot.setRenderer(renderer);\r\n\r\n JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,\r\n plot, legend);\r\n currentTheme.apply(chart);\r\n return chart;\r\n }\r\n\r\n}\r" }, { "identifier": "JFreeChart", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/JFreeChart.java", "snippet": "public class JFreeChart implements Drawable, TitleChangeListener,\r\n PlotChangeListener, Serializable, Cloneable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -3470703747817429120L;\r\n\r\n /** Information about the project. */\r\n public static final ProjectInfo INFO = new JFreeChartInfo();\r\n\r\n /** The default font for titles. */\r\n public static final Font DEFAULT_TITLE_FONT\r\n = new Font(\"SansSerif\", Font.BOLD, 18);\r\n\r\n /** The default background color. */\r\n public static final Paint DEFAULT_BACKGROUND_PAINT\r\n = UIManager.getColor(\"Panel.background\");\r\n\r\n /** The default background image. */\r\n public static final Image DEFAULT_BACKGROUND_IMAGE = null;\r\n\r\n /** The default background image alignment. */\r\n public static final int DEFAULT_BACKGROUND_IMAGE_ALIGNMENT = Align.FIT;\r\n\r\n /** The default background image alpha. */\r\n public static final float DEFAULT_BACKGROUND_IMAGE_ALPHA = 0.5f;\r\n\r\n /**\r\n * The key for a rendering hint that can suppress the generation of a \r\n * shadow effect when drawing the chart. The hint value must be a \r\n * Boolean.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static final RenderingHints.Key KEY_SUPPRESS_SHADOW_GENERATION\r\n = new RenderingHints.Key(0) {\r\n @Override\r\n public boolean isCompatibleValue(Object val) {\r\n return val instanceof Boolean;\r\n }\r\n };\r\n \r\n /**\r\n * Rendering hints that will be used for chart drawing. This should never\r\n * be <code>null</code>.\r\n */\r\n private transient RenderingHints renderingHints;\r\n\r\n /** A flag that controls whether or not the chart border is drawn. */\r\n private boolean borderVisible;\r\n\r\n /** The stroke used to draw the chart border (if visible). */\r\n private transient Stroke borderStroke;\r\n\r\n /** The paint used to draw the chart border (if visible). */\r\n private transient Paint borderPaint;\r\n\r\n /** The padding between the chart border and the chart drawing area. */\r\n private RectangleInsets padding;\r\n\r\n /** The chart title (optional). */\r\n private TextTitle title;\r\n\r\n /**\r\n * The chart subtitles (zero, one or many). This field should never be\r\n * <code>null</code>.\r\n */\r\n private List subtitles;\r\n\r\n /** Draws the visual representation of the data. */\r\n private Plot plot;\r\n\r\n /** Paint used to draw the background of the chart. */\r\n private transient Paint backgroundPaint;\r\n\r\n /** An optional background image for the chart. */\r\n private transient Image backgroundImage; // todo: not serialized yet\r\n\r\n /** The alignment for the background image. */\r\n private int backgroundImageAlignment = Align.FIT;\r\n\r\n /** The alpha transparency for the background image. */\r\n private float backgroundImageAlpha = 0.5f;\r\n\r\n /** Storage for registered change listeners. */\r\n private transient EventListenerList changeListeners;\r\n\r\n /** Storage for registered progress listeners. */\r\n private transient EventListenerList progressListeners;\r\n\r\n /**\r\n * A flag that can be used to enable/disable notification of chart change\r\n * events.\r\n */\r\n private boolean notify;\r\n\r\n /**\r\n * Creates a new chart based on the supplied plot. The chart will have\r\n * a legend added automatically, but no title (although you can easily add\r\n * one later).\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(Plot plot) {\r\n this(null, null, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. A default font\r\n * ({@link #DEFAULT_TITLE_FONT}) is used for the title, and the chart will\r\n * have a legend added automatically.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(String title, Plot plot) {\r\n this(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. The\r\n * <code>createLegend</code> argument specifies whether or not a legend\r\n * should be added to the chart.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param titleFont the font for displaying the chart title\r\n * (<code>null</code> permitted).\r\n * @param plot controller of the visual representation of the data\r\n * (<code>null</code> not permitted).\r\n * @param createLegend a flag indicating whether or not a legend should\r\n * be created for the chart.\r\n */\r\n public JFreeChart(String title, Font titleFont, Plot plot,\r\n boolean createLegend) {\r\n\r\n ParamChecks.nullNotPermitted(plot, \"plot\");\r\n\r\n // create storage for listeners...\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.notify = true; // default is to notify listeners when the\r\n // chart changes\r\n\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n // added the following hint because of \r\n // http://stackoverflow.com/questions/7785082/\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n this.borderVisible = false;\r\n this.borderStroke = new BasicStroke(1.0f);\r\n this.borderPaint = Color.black;\r\n\r\n this.padding = RectangleInsets.ZERO_INSETS;\r\n\r\n this.plot = plot;\r\n plot.addChangeListener(this);\r\n\r\n this.subtitles = new ArrayList();\r\n\r\n // create a legend, if requested...\r\n if (createLegend) {\r\n LegendTitle legend = new LegendTitle(this.plot);\r\n legend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));\r\n legend.setFrame(new LineBorder());\r\n legend.setBackgroundPaint(Color.white);\r\n legend.setPosition(RectangleEdge.BOTTOM);\r\n this.subtitles.add(legend);\r\n legend.addChangeListener(this);\r\n }\r\n\r\n // add the chart title, if one has been specified...\r\n if (title != null) {\r\n if (titleFont == null) {\r\n titleFont = DEFAULT_TITLE_FONT;\r\n }\r\n this.title = new TextTitle(title, titleFont);\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n this.backgroundPaint = DEFAULT_BACKGROUND_PAINT;\r\n\r\n this.backgroundImage = DEFAULT_BACKGROUND_IMAGE;\r\n this.backgroundImageAlignment = DEFAULT_BACKGROUND_IMAGE_ALIGNMENT;\r\n this.backgroundImageAlpha = DEFAULT_BACKGROUND_IMAGE_ALPHA;\r\n\r\n }\r\n\r\n /**\r\n * Returns the collection of rendering hints for the chart.\r\n *\r\n * @return The rendering hints for the chart (never <code>null</code>).\r\n *\r\n * @see #setRenderingHints(RenderingHints)\r\n */\r\n public RenderingHints getRenderingHints() {\r\n return this.renderingHints;\r\n }\r\n\r\n /**\r\n * Sets the rendering hints for the chart. These will be added (using the\r\n * {@code Graphics2D.addRenderingHints()} method) near the start of the\r\n * {@code JFreeChart.draw()} method.\r\n *\r\n * @param renderingHints the rendering hints ({@code null} not permitted).\r\n *\r\n * @see #getRenderingHints()\r\n */\r\n public void setRenderingHints(RenderingHints renderingHints) {\r\n ParamChecks.nullNotPermitted(renderingHints, \"renderingHints\");\r\n this.renderingHints = renderingHints;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setBorderVisible(boolean)\r\n */\r\n public boolean isBorderVisible() {\r\n return this.borderVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isBorderVisible()\r\n */\r\n public void setBorderVisible(boolean visible) {\r\n this.borderVisible = visible;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the chart border (if visible).\r\n *\r\n * @return The border stroke.\r\n *\r\n * @see #setBorderStroke(Stroke)\r\n */\r\n public Stroke getBorderStroke() {\r\n return this.borderStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the chart border (if visible).\r\n *\r\n * @param stroke the stroke.\r\n *\r\n * @see #getBorderStroke()\r\n */\r\n public void setBorderStroke(Stroke stroke) {\r\n this.borderStroke = stroke;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the chart border (if visible).\r\n *\r\n * @return The border paint.\r\n *\r\n * @see #setBorderPaint(Paint)\r\n */\r\n public Paint getBorderPaint() {\r\n return this.borderPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the chart border (if visible).\r\n *\r\n * @param paint the paint.\r\n *\r\n * @see #getBorderPaint()\r\n */\r\n public void setBorderPaint(Paint paint) {\r\n this.borderPaint = paint;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the padding between the chart border and the chart drawing area.\r\n *\r\n * @return The padding (never <code>null</code>).\r\n *\r\n * @see #setPadding(RectangleInsets)\r\n */\r\n public RectangleInsets getPadding() {\r\n return this.padding;\r\n }\r\n\r\n /**\r\n * Sets the padding between the chart border and the chart drawing area,\r\n * and sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param padding the padding (<code>null</code> not permitted).\r\n *\r\n * @see #getPadding()\r\n */\r\n public void setPadding(RectangleInsets padding) {\r\n ParamChecks.nullNotPermitted(padding, \"padding\");\r\n this.padding = padding;\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the main chart title. Very often a chart will have just one\r\n * title, so we make this case simple by providing accessor methods for\r\n * the main title. However, multiple titles are supported - see the\r\n * {@link #addSubtitle(Title)} method.\r\n *\r\n * @return The chart title (possibly <code>null</code>).\r\n *\r\n * @see #setTitle(TextTitle)\r\n */\r\n public TextTitle getTitle() {\r\n return this.title;\r\n }\r\n\r\n /**\r\n * Sets the main title for the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners. If you do not want a title for the\r\n * chart, set it to <code>null</code>. If you want more than one title on\r\n * a chart, use the {@link #addSubtitle(Title)} method.\r\n *\r\n * @param title the title (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(TextTitle title) {\r\n if (this.title != null) {\r\n this.title.removeChangeListener(this);\r\n }\r\n this.title = title;\r\n if (title != null) {\r\n title.addChangeListener(this);\r\n }\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Sets the chart title and sends a {@link ChartChangeEvent} to all\r\n * registered listeners. This is a convenience method that ends up calling\r\n * the {@link #setTitle(TextTitle)} method. If there is an existing title,\r\n * its text is updated, otherwise a new title using the default font is\r\n * added to the chart. If <code>text</code> is <code>null</code> the chart\r\n * title is set to <code>null</code>.\r\n *\r\n * @param text the title text (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(String text) {\r\n if (text != null) {\r\n if (this.title == null) {\r\n setTitle(new TextTitle(text, JFreeChart.DEFAULT_TITLE_FONT));\r\n }\r\n else {\r\n this.title.setText(text);\r\n }\r\n }\r\n else {\r\n setTitle((TextTitle) null);\r\n }\r\n }\r\n\r\n /**\r\n * Adds a legend to the plot and sends a {@link ChartChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param legend the legend (<code>null</code> not permitted).\r\n *\r\n * @see #removeLegend()\r\n */\r\n public void addLegend(LegendTitle legend) {\r\n addSubtitle(legend);\r\n }\r\n\r\n /**\r\n * Returns the legend for the chart, if there is one. Note that a chart\r\n * can have more than one legend - this method returns the first.\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #getLegend(int)\r\n */\r\n public LegendTitle getLegend() {\r\n return getLegend(0);\r\n }\r\n\r\n /**\r\n * Returns the nth legend for a chart, or <code>null</code>.\r\n *\r\n * @param index the legend index (zero-based).\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #addLegend(LegendTitle)\r\n */\r\n public LegendTitle getLegend(int index) {\r\n int seen = 0;\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title subtitle = (Title) iterator.next();\r\n if (subtitle instanceof LegendTitle) {\r\n if (seen == index) {\r\n return (LegendTitle) subtitle;\r\n }\r\n else {\r\n seen++;\r\n }\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Removes the first legend in the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @see #getLegend()\r\n */\r\n public void removeLegend() {\r\n removeSubtitle(getLegend());\r\n }\r\n\r\n /**\r\n * Returns the list of subtitles for the chart.\r\n *\r\n * @return The subtitle list (possibly empty, but never <code>null</code>).\r\n *\r\n * @see #setSubtitles(List)\r\n */\r\n public List getSubtitles() {\r\n return new ArrayList(this.subtitles);\r\n }\r\n\r\n /**\r\n * Sets the title list for the chart (completely replaces any existing\r\n * titles) and sends a {@link ChartChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param subtitles the new list of subtitles (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public void setSubtitles(List subtitles) {\r\n if (subtitles == null) {\r\n throw new NullPointerException(\"Null 'subtitles' argument.\");\r\n }\r\n setNotify(false);\r\n clearSubtitles();\r\n Iterator iterator = subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n if (t != null) {\r\n addSubtitle(t);\r\n }\r\n }\r\n setNotify(true); // this fires a ChartChangeEvent\r\n }\r\n\r\n /**\r\n * Returns the number of titles for the chart.\r\n *\r\n * @return The number of titles for the chart.\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public int getSubtitleCount() {\r\n return this.subtitles.size();\r\n }\r\n\r\n /**\r\n * Returns a chart subtitle.\r\n *\r\n * @param index the index of the chart subtitle (zero based).\r\n *\r\n * @return A chart subtitle.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public Title getSubtitle(int index) {\r\n if ((index < 0) || (index >= getSubtitleCount())) {\r\n throw new IllegalArgumentException(\"Index out of range.\");\r\n }\r\n return (Title) this.subtitles.get(index);\r\n }\r\n\r\n /**\r\n * Adds a chart subtitle, and notifies registered listeners that the chart\r\n * has been modified.\r\n *\r\n * @param subtitle the subtitle (<code>null</code> not permitted).\r\n *\r\n * @see #getSubtitle(int)\r\n */\r\n public void addSubtitle(Title subtitle) {\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Adds a subtitle at a particular position in the subtitle list, and sends\r\n * a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param index the index (in the range 0 to {@link #getSubtitleCount()}).\r\n * @param subtitle the subtitle to add (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.6\r\n */\r\n public void addSubtitle(int index, Title subtitle) {\r\n if (index < 0 || index > getSubtitleCount()) {\r\n throw new IllegalArgumentException(\r\n \"The 'index' argument is out of range.\");\r\n }\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(index, subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Clears all subtitles from the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void clearSubtitles() {\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n t.removeChangeListener(this);\r\n }\r\n this.subtitles.clear();\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Removes the specified subtitle and sends a {@link ChartChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param title the title.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void removeSubtitle(Title title) {\r\n this.subtitles.remove(title);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the plot for the chart. The plot is a class responsible for\r\n * coordinating the visual representation of the data, including the axes\r\n * (if any).\r\n *\r\n * @return The plot.\r\n */\r\n public Plot getPlot() {\r\n return this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as a {@link CategoryPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link CategoryPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public CategoryPlot getCategoryPlot() {\r\n return (CategoryPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as an {@link XYPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link XYPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public XYPlot getXYPlot() {\r\n return (XYPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns a flag that indicates whether or not anti-aliasing is used when\r\n * the chart is drawn.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAntiAlias(boolean)\r\n */\r\n public boolean getAntiAlias() {\r\n Object val = this.renderingHints.get(RenderingHints.KEY_ANTIALIASING);\r\n return RenderingHints.VALUE_ANTIALIAS_ON.equals(val);\r\n }\r\n\r\n /**\r\n * Sets a flag that indicates whether or not anti-aliasing is used when the\r\n * chart is drawn.\r\n * <P>\r\n * Anti-aliasing usually improves the appearance of charts, but is slower.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #getAntiAlias()\r\n */\r\n public void setAntiAlias(boolean flag) {\r\n Object hint = flag ? RenderingHints.VALUE_ANTIALIAS_ON \r\n : RenderingHints.VALUE_ANTIALIAS_OFF;\r\n this.renderingHints.put(RenderingHints.KEY_ANTIALIASING, hint);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the current value stored in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING}.\r\n *\r\n * @return The hint value (possibly <code>null</code>).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public Object getTextAntiAlias() {\r\n return this.renderingHints.get(RenderingHints.KEY_TEXT_ANTIALIASING);\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} to either\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_ON} or\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_OFF}, then sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public void setTextAntiAlias(boolean flag) {\r\n if (flag) {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\r\n }\r\n else {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);\r\n }\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param val the new value (<code>null</code> permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(boolean)\r\n */\r\n public void setTextAntiAlias(Object val) {\r\n this.renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, val);\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the paint used for the chart background.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundPaint(Paint)\r\n */\r\n public Paint getBackgroundPaint() {\r\n return this.backgroundPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to fill the chart background and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundPaint()\r\n */\r\n public void setBackgroundPaint(Paint paint) {\r\n\r\n if (this.backgroundPaint != null) {\r\n if (!this.backgroundPaint.equals(paint)) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (paint != null) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image for the chart, or <code>null</code> if\r\n * there is no image.\r\n *\r\n * @return The image (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundImage(Image)\r\n */\r\n public Image getBackgroundImage() {\r\n return this.backgroundImage;\r\n }\r\n\r\n /**\r\n * Sets the background image for the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param image the image (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundImage()\r\n */\r\n public void setBackgroundImage(Image image) {\r\n\r\n if (this.backgroundImage != null) {\r\n if (!this.backgroundImage.equals(image)) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (image != null) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image alignment. Alignment constants are defined\r\n * in the <code>org.jfree.ui.Align</code> class in the JCommon class\r\n * library.\r\n *\r\n * @return The alignment.\r\n *\r\n * @see #setBackgroundImageAlignment(int)\r\n */\r\n public int getBackgroundImageAlignment() {\r\n return this.backgroundImageAlignment;\r\n }\r\n\r\n /**\r\n * Sets the background alignment. Alignment options are defined by the\r\n * {@link org.jfree.ui.Align} class.\r\n *\r\n * @param alignment the alignment.\r\n *\r\n * @see #getBackgroundImageAlignment()\r\n */\r\n public void setBackgroundImageAlignment(int alignment) {\r\n if (this.backgroundImageAlignment != alignment) {\r\n this.backgroundImageAlignment = alignment;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha-transparency for the chart's background image.\r\n *\r\n * @return The alpha-transparency.\r\n *\r\n * @see #setBackgroundImageAlpha(float)\r\n */\r\n public float getBackgroundImageAlpha() {\r\n return this.backgroundImageAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha-transparency for the chart's background image.\r\n * Registered listeners are notified that the chart has been changed.\r\n *\r\n * @param alpha the alpha value.\r\n *\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void setBackgroundImageAlpha(float alpha) {\r\n\r\n if (this.backgroundImageAlpha != alpha) {\r\n this.backgroundImageAlpha = alpha;\r\n fireChartChanged();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not change events are sent to\r\n * registered listeners.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNotify(boolean)\r\n */\r\n public boolean isNotify() {\r\n return this.notify;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not listeners receive\r\n * {@link ChartChangeEvent} notifications.\r\n *\r\n * @param notify a boolean.\r\n *\r\n * @see #isNotify()\r\n */\r\n public void setNotify(boolean notify) {\r\n this.notify = notify;\r\n // if the flag is being set to true, there may be queued up changes...\r\n if (notify) {\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area) {\r\n draw(g2, area, null, null);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer). This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D area, ChartRenderingInfo info) {\r\n draw(g2, area, null, info);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param chartArea the area within which the chart should be drawn.\r\n * @param anchor the anchor point (in Java2D space) for the chart\r\n * (<code>null</code> permitted).\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D chartArea, Point2D anchor,\r\n ChartRenderingInfo info) {\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_STARTED, 0));\r\n \r\n EntityCollection entities = null;\r\n // record the chart area, if info is requested...\r\n if (info != null) {\r\n info.clear();\r\n info.setChartArea(chartArea);\r\n entities = info.getEntityCollection();\r\n }\r\n if (entities != null) {\r\n entities.add(new JFreeChartEntity((Rectangle2D) chartArea.clone(),\r\n this));\r\n }\r\n\r\n // ensure no drawing occurs outside chart area...\r\n Shape savedClip = g2.getClip();\r\n g2.clip(chartArea);\r\n\r\n g2.addRenderingHints(this.renderingHints);\r\n\r\n // draw the chart background...\r\n if (this.backgroundPaint != null) {\r\n g2.setPaint(this.backgroundPaint);\r\n g2.fill(chartArea);\r\n }\r\n\r\n if (this.backgroundImage != null) {\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundImageAlpha));\r\n Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,\r\n this.backgroundImage.getWidth(null),\r\n this.backgroundImage.getHeight(null));\r\n Align.align(dest, chartArea, this.backgroundImageAlignment);\r\n g2.drawImage(this.backgroundImage, (int) dest.getX(),\r\n (int) dest.getY(), (int) dest.getWidth(),\r\n (int) dest.getHeight(), null);\r\n g2.setComposite(originalComposite);\r\n }\r\n\r\n if (isBorderVisible()) {\r\n Paint paint = getBorderPaint();\r\n Stroke stroke = getBorderStroke();\r\n if (paint != null && stroke != null) {\r\n Rectangle2D borderArea = new Rectangle2D.Double(\r\n chartArea.getX(), chartArea.getY(),\r\n chartArea.getWidth() - 1.0, chartArea.getHeight()\r\n - 1.0);\r\n g2.setPaint(paint);\r\n g2.setStroke(stroke);\r\n g2.draw(borderArea);\r\n }\r\n }\r\n\r\n // draw the title and subtitles...\r\n Rectangle2D nonTitleArea = new Rectangle2D.Double();\r\n nonTitleArea.setRect(chartArea);\r\n this.padding.trim(nonTitleArea);\r\n\r\n if (this.title != null && this.title.isVisible()) {\r\n EntityCollection e = drawTitle(this.title, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title currentTitle = (Title) iterator.next();\r\n if (currentTitle.isVisible()) {\r\n EntityCollection e = drawTitle(currentTitle, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n }\r\n\r\n Rectangle2D plotArea = nonTitleArea;\r\n\r\n // draw the plot (axes and data visualisation)\r\n PlotRenderingInfo plotInfo = null;\r\n if (info != null) {\r\n plotInfo = info.getPlotInfo();\r\n }\r\n this.plot.draw(g2, plotArea, anchor, null, plotInfo);\r\n\r\n g2.setClip(savedClip);\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_FINISHED, 100));\r\n }\r\n\r\n /**\r\n * Creates a rectangle that is aligned to the frame.\r\n *\r\n * @param dimensions the dimensions for the rectangle.\r\n * @param frame the frame to align to.\r\n * @param hAlign the horizontal alignment.\r\n * @param vAlign the vertical alignment.\r\n *\r\n * @return A rectangle.\r\n */\r\n private Rectangle2D createAlignedRectangle2D(Size2D dimensions,\r\n Rectangle2D frame, HorizontalAlignment hAlign,\r\n VerticalAlignment vAlign) {\r\n double x = Double.NaN;\r\n double y = Double.NaN;\r\n if (hAlign == HorizontalAlignment.LEFT) {\r\n x = frame.getX();\r\n }\r\n else if (hAlign == HorizontalAlignment.CENTER) {\r\n x = frame.getCenterX() - (dimensions.width / 2.0);\r\n }\r\n else if (hAlign == HorizontalAlignment.RIGHT) {\r\n x = frame.getMaxX() - dimensions.width;\r\n }\r\n if (vAlign == VerticalAlignment.TOP) {\r\n y = frame.getY();\r\n }\r\n else if (vAlign == VerticalAlignment.CENTER) {\r\n y = frame.getCenterY() - (dimensions.height / 2.0);\r\n }\r\n else if (vAlign == VerticalAlignment.BOTTOM) {\r\n y = frame.getMaxY() - dimensions.height;\r\n }\r\n\r\n return new Rectangle2D.Double(x, y, dimensions.width,\r\n dimensions.height);\r\n }\r\n\r\n /**\r\n * Draws a title. The title should be drawn at the top, bottom, left or\r\n * right of the specified area, and the area should be updated to reflect\r\n * the amount of space used by the title.\r\n *\r\n * @param t the title (<code>null</code> not permitted).\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param area the chart area, excluding any existing titles\r\n * (<code>null</code> not permitted).\r\n * @param entities a flag that controls whether or not an entity\r\n * collection is returned for the title.\r\n *\r\n * @return An entity collection for the title (possibly <code>null</code>).\r\n */\r\n protected EntityCollection drawTitle(Title t, Graphics2D g2,\r\n Rectangle2D area, boolean entities) {\r\n\r\n ParamChecks.nullNotPermitted(t, \"t\");\r\n ParamChecks.nullNotPermitted(area, \"area\");\r\n Rectangle2D titleArea;\r\n RectangleEdge position = t.getPosition();\r\n double ww = area.getWidth();\r\n if (ww <= 0.0) {\r\n return null;\r\n }\r\n double hh = area.getHeight();\r\n if (hh <= 0.0) {\r\n return null;\r\n }\r\n RectangleConstraint constraint = new RectangleConstraint(ww,\r\n new Range(0.0, ww), LengthConstraintType.RANGE, hh,\r\n new Range(0.0, hh), LengthConstraintType.RANGE);\r\n Object retValue = null;\r\n BlockParams p = new BlockParams();\r\n p.setGenerateEntities(entities);\r\n if (position == RectangleEdge.TOP) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.TOP);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), Math.min(area.getY() + size.height,\r\n area.getMaxY()), area.getWidth(), Math.max(area.getHeight()\r\n - size.height, 0));\r\n }\r\n else if (position == RectangleEdge.BOTTOM) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.BOTTOM);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth(),\r\n area.getHeight() - size.height);\r\n }\r\n else if (position == RectangleEdge.RIGHT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.RIGHT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n\r\n else if (position == RectangleEdge.LEFT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.LEFT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX() + size.width, area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n else {\r\n throw new RuntimeException(\"Unrecognised title position.\");\r\n }\r\n EntityCollection result = null;\r\n if (retValue instanceof EntityBlockResult) {\r\n EntityBlockResult ebr = (EntityBlockResult) retValue;\r\n result = ebr.getEntityCollection();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height) {\r\n return createBufferedImage(width, height, null);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n ChartRenderingInfo info) {\r\n return createBufferedImage(width, height, BufferedImage.TYPE_INT_ARGB,\r\n info);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param imageType the image type.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n int imageType,\r\n ChartRenderingInfo info) {\r\n BufferedImage image = new BufferedImage(width, height, imageType);\r\n Graphics2D g2 = image.createGraphics();\r\n draw(g2, new Rectangle2D.Double(0, 0, width, height), null, info);\r\n g2.dispose();\r\n return image;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param imageWidth the image width.\r\n * @param imageHeight the image height.\r\n * @param drawWidth the width for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param drawHeight the height for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param info optional object for collection chart dimension and entity\r\n * information.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int imageWidth,\r\n int imageHeight,\r\n double drawWidth,\r\n double drawHeight,\r\n ChartRenderingInfo info) {\r\n\r\n BufferedImage image = new BufferedImage(imageWidth, imageHeight,\r\n BufferedImage.TYPE_INT_ARGB);\r\n Graphics2D g2 = image.createGraphics();\r\n double scaleX = imageWidth / drawWidth;\r\n double scaleY = imageHeight / drawHeight;\r\n AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);\r\n g2.transform(st);\r\n draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,\r\n info);\r\n g2.dispose();\r\n return image;\r\n\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the chart. JFreeChart is not a UI component, so\r\n * some other object (for example, {@link ChartPanel}) needs to capture\r\n * the click event and pass it onto the JFreeChart object.\r\n * If you are not using JFreeChart in a client application, then this\r\n * method is not required.\r\n *\r\n * @param x x-coordinate of the click (in Java2D space).\r\n * @param y y-coordinate of the click (in Java2D space).\r\n * @param info contains chart dimension and entity information\r\n * (<code>null</code> not permitted).\r\n */\r\n public void handleClick(int x, int y, ChartRenderingInfo info) {\r\n\r\n // pass the click on to the plot...\r\n // rely on the plot to post a plot change event and redraw the chart...\r\n this.plot.handleClick(x, y, info.getPlotInfo());\r\n\r\n }\r\n\r\n /**\r\n * Registers an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted).\r\n *\r\n * @see #removeChangeListener(ChartChangeListener)\r\n */\r\n public void addChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.add(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted)\r\n *\r\n * @see #addChangeListener(ChartChangeListener)\r\n */\r\n public void removeChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.remove(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a default {@link ChartChangeEvent} to all registered listeners.\r\n * <P>\r\n * This method is for convenience only.\r\n */\r\n public void fireChartChanged() {\r\n ChartChangeEvent event = new ChartChangeEvent(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartChangeEvent event) {\r\n if (this.notify) {\r\n Object[] listeners = this.changeListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartChangeListener.class) {\r\n ((ChartChangeListener) listeners[i + 1]).chartChanged(\r\n event);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Registers an object for notification of progress events relating to the\r\n * chart.\r\n *\r\n * @param listener the object being registered.\r\n *\r\n * @see #removeProgressListener(ChartProgressListener)\r\n */\r\n public void addProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.add(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the object being deregistered.\r\n *\r\n * @see #addProgressListener(ChartProgressListener)\r\n */\r\n public void removeProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.remove(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartProgressEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartProgressEvent event) {\r\n\r\n Object[] listeners = this.progressListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartProgressListener.class) {\r\n ((ChartProgressListener) listeners[i + 1]).chartProgress(event);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Receives notification that a chart title has changed, and passes this\r\n * on to registered listeners.\r\n *\r\n * @param event information about the chart title change.\r\n */\r\n @Override\r\n public void titleChanged(TitleChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Receives notification that the plot has changed, and passes this on to\r\n * registered listeners.\r\n *\r\n * @param event information about the plot change.\r\n */\r\n @Override\r\n public void plotChanged(PlotChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Tests this chart for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof JFreeChart)) {\r\n return false;\r\n }\r\n JFreeChart that = (JFreeChart) obj;\r\n if (!this.renderingHints.equals(that.renderingHints)) {\r\n return false;\r\n }\r\n if (this.borderVisible != that.borderVisible) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.borderStroke, that.borderStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.borderPaint, that.borderPaint)) {\r\n return false;\r\n }\r\n if (!this.padding.equals(that.padding)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.title, that.title)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.subtitles, that.subtitles)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.plot, that.plot)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(\r\n this.backgroundPaint, that.backgroundPaint\r\n )) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundImage,\r\n that.backgroundImage)) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlignment != that.backgroundImageAlignment) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlpha != that.backgroundImageAlpha) {\r\n return false;\r\n }\r\n if (this.notify != that.notify) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.borderStroke, stream);\r\n SerialUtilities.writePaint(this.borderPaint, stream);\r\n SerialUtilities.writePaint(this.backgroundPaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.borderStroke = SerialUtilities.readStroke(stream);\r\n this.borderPaint = SerialUtilities.readPaint(stream);\r\n this.backgroundPaint = SerialUtilities.readPaint(stream);\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n // register as a listener with sub-components...\r\n if (this.title != null) {\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n getSubtitle(i).addChangeListener(this);\r\n }\r\n this.plot.addChangeListener(this);\r\n }\r\n\r\n /**\r\n * Prints information about JFreeChart to standard output.\r\n *\r\n * @param args no arguments are honored.\r\n */\r\n public static void main(String[] args) {\r\n System.out.println(JFreeChart.INFO.toString());\r\n }\r\n\r\n /**\r\n * Clones the object, and takes care of listeners.\r\n * Note: caller shall register its own listeners on cloned graph.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the chart is not cloneable.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n JFreeChart chart = (JFreeChart) super.clone();\r\n\r\n chart.renderingHints = (RenderingHints) this.renderingHints.clone();\r\n // private boolean borderVisible;\r\n // private transient Stroke borderStroke;\r\n // private transient Paint borderPaint;\r\n\r\n if (this.title != null) {\r\n chart.title = (TextTitle) this.title.clone();\r\n chart.title.addChangeListener(chart);\r\n }\r\n\r\n chart.subtitles = new ArrayList();\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n Title subtitle = (Title) getSubtitle(i).clone();\r\n chart.subtitles.add(subtitle);\r\n subtitle.addChangeListener(chart);\r\n }\r\n\r\n if (this.plot != null) {\r\n chart.plot = (Plot) this.plot.clone();\r\n chart.plot.addChangeListener(chart);\r\n }\r\n\r\n chart.progressListeners = new EventListenerList();\r\n chart.changeListeners = new EventListenerList();\r\n return chart;\r\n }\r\n\r\n}\r" }, { "identifier": "PiePlot", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/PiePlot.java", "snippet": "public class PiePlot extends Plot implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -795612466005590431L;\r\n\r\n /** The default interior gap. */\r\n public static final double DEFAULT_INTERIOR_GAP = 0.08;\r\n\r\n /** The maximum interior gap (currently 40%). */\r\n public static final double MAX_INTERIOR_GAP = 0.40;\r\n\r\n /** The default starting angle for the pie chart. */\r\n public static final double DEFAULT_START_ANGLE = 90.0;\r\n\r\n /** The default section label font. */\r\n public static final Font DEFAULT_LABEL_FONT = new Font(\"SansSerif\",\r\n Font.PLAIN, 10);\r\n\r\n /** The default section label paint. */\r\n public static final Paint DEFAULT_LABEL_PAINT = Color.black;\r\n\r\n /** The default section label background paint. */\r\n public static final Paint DEFAULT_LABEL_BACKGROUND_PAINT = new Color(255,\r\n 255, 192);\r\n\r\n /** The default section label outline paint. */\r\n public static final Paint DEFAULT_LABEL_OUTLINE_PAINT = Color.black;\r\n\r\n /** The default section label outline stroke. */\r\n public static final Stroke DEFAULT_LABEL_OUTLINE_STROKE = new BasicStroke(\r\n 0.5f);\r\n\r\n /** The default section label shadow paint. */\r\n public static final Paint DEFAULT_LABEL_SHADOW_PAINT = new Color(151, 151,\r\n 151, 128);\r\n\r\n /** The default minimum arc angle to draw. */\r\n public static final double DEFAULT_MINIMUM_ARC_ANGLE_TO_DRAW = 0.00001;\r\n\r\n /** The dataset for the pie chart. */\r\n private PieDataset dataset;\r\n\r\n /** The pie index (used by the {@link MultiplePiePlot} class). */\r\n private int pieIndex;\r\n\r\n /**\r\n * The amount of space left around the outside of the pie plot, expressed\r\n * as a percentage of the plot area width and height.\r\n */\r\n private double interiorGap;\r\n\r\n /** Flag determining whether to draw an ellipse or a perfect circle. */\r\n private boolean circular;\r\n\r\n /** The starting angle. */\r\n private double startAngle;\r\n\r\n /** The direction for the pie segments. */\r\n private Rotation direction;\r\n\r\n /** The section paint map. */\r\n private PaintMap sectionPaintMap;\r\n\r\n /** The base section paint (fallback). */\r\n private transient Paint baseSectionPaint;\r\n\r\n /**\r\n * A flag that controls whether or not the section paint is auto-populated\r\n * from the drawing supplier.\r\n *\r\n * @since 1.0.11\r\n */\r\n private boolean autoPopulateSectionPaint;\r\n\r\n /**\r\n * A flag that controls whether or not an outline is drawn for each\r\n * section in the plot.\r\n */\r\n private boolean sectionOutlinesVisible;\r\n\r\n /** The section outline paint map. */\r\n private PaintMap sectionOutlinePaintMap;\r\n\r\n /** The base section outline paint (fallback). */\r\n private transient Paint baseSectionOutlinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not the section outline paint is\r\n * auto-populated from the drawing supplier.\r\n *\r\n * @since 1.0.11\r\n */\r\n private boolean autoPopulateSectionOutlinePaint;\r\n\r\n /** The section outline stroke map. */\r\n private StrokeMap sectionOutlineStrokeMap;\r\n\r\n /** The base section outline stroke (fallback). */\r\n private transient Stroke baseSectionOutlineStroke;\r\n\r\n /**\r\n * A flag that controls whether or not the section outline stroke is\r\n * auto-populated from the drawing supplier.\r\n *\r\n * @since 1.0.11\r\n */\r\n private boolean autoPopulateSectionOutlineStroke;\r\n\r\n /** The shadow paint. */\r\n private transient Paint shadowPaint = Color.gray;\r\n\r\n /** The x-offset for the shadow effect. */\r\n private double shadowXOffset = 4.0f;\r\n\r\n /** The y-offset for the shadow effect. */\r\n private double shadowYOffset = 4.0f;\r\n\r\n /** The percentage amount to explode each pie section. */\r\n private Map explodePercentages;\r\n\r\n /** The section label generator. */\r\n private PieSectionLabelGenerator labelGenerator;\r\n\r\n /** The font used to display the section labels. */\r\n private Font labelFont;\r\n\r\n /** The color used to draw the section labels. */\r\n private transient Paint labelPaint;\r\n\r\n /**\r\n * The color used to draw the background of the section labels. If this\r\n * is <code>null</code>, the background is not filled.\r\n */\r\n private transient Paint labelBackgroundPaint;\r\n\r\n /**\r\n * The paint used to draw the outline of the section labels\r\n * (<code>null</code> permitted).\r\n */\r\n private transient Paint labelOutlinePaint;\r\n\r\n /**\r\n * The stroke used to draw the outline of the section labels\r\n * (<code>null</code> permitted).\r\n */\r\n private transient Stroke labelOutlineStroke;\r\n\r\n /**\r\n * The paint used to draw the shadow for the section labels\r\n * (<code>null</code> permitted).\r\n */\r\n private transient Paint labelShadowPaint;\r\n\r\n /**\r\n * A flag that controls whether simple or extended labels are used.\r\n *\r\n * @since 1.0.7\r\n */\r\n private boolean simpleLabels = true;\r\n\r\n /**\r\n * The padding between the labels and the label outlines. This is not\r\n * allowed to be <code>null</code>.\r\n *\r\n * @since 1.0.7\r\n */\r\n private RectangleInsets labelPadding;\r\n\r\n /**\r\n * The simple label offset.\r\n *\r\n * @since 1.0.7\r\n */\r\n private RectangleInsets simpleLabelOffset;\r\n\r\n /** The maximum label width as a percentage of the plot width. */\r\n private double maximumLabelWidth = 0.14;\r\n\r\n /**\r\n * The gap between the labels and the link corner, as a percentage of the\r\n * plot width.\r\n */\r\n private double labelGap = 0.025;\r\n\r\n /** A flag that controls whether or not the label links are drawn. */\r\n private boolean labelLinksVisible;\r\n\r\n /**\r\n * The label link style.\r\n *\r\n * @since 1.0.10\r\n */\r\n private PieLabelLinkStyle labelLinkStyle = PieLabelLinkStyle.STANDARD;\r\n\r\n /** The link margin. */\r\n private double labelLinkMargin = 0.025;\r\n\r\n /** The paint used for the label linking lines. */\r\n private transient Paint labelLinkPaint = Color.black;\r\n\r\n /** The stroke used for the label linking lines. */\r\n private transient Stroke labelLinkStroke = new BasicStroke(0.5f);\r\n\r\n /**\r\n * The pie section label distributor.\r\n *\r\n * @since 1.0.6\r\n */\r\n private AbstractPieLabelDistributor labelDistributor;\r\n\r\n /** The tooltip generator. */\r\n private PieToolTipGenerator toolTipGenerator;\r\n\r\n /** The URL generator. */\r\n private PieURLGenerator urlGenerator;\r\n\r\n /** The legend label generator. */\r\n private PieSectionLabelGenerator legendLabelGenerator;\r\n\r\n /** A tool tip generator for the legend. */\r\n private PieSectionLabelGenerator legendLabelToolTipGenerator;\r\n\r\n /**\r\n * A URL generator for the legend items (optional).\r\n *\r\n * @since 1.0.4.\r\n */\r\n private PieURLGenerator legendLabelURLGenerator;\r\n\r\n /**\r\n * A flag that controls whether <code>null</code> values are ignored.\r\n */\r\n private boolean ignoreNullValues;\r\n\r\n /**\r\n * A flag that controls whether zero values are ignored.\r\n */\r\n private boolean ignoreZeroValues;\r\n\r\n /** The legend item shape. */\r\n private transient Shape legendItemShape;\r\n\r\n /**\r\n * The smallest arc angle that will get drawn (this is to avoid a bug in\r\n * various Java implementations that causes the JVM to crash). See this\r\n * link for details:\r\n *\r\n * http://www.jfree.org/phpBB2/viewtopic.php?t=2707\r\n *\r\n * ...and this bug report in the Java Bug Parade:\r\n *\r\n * http://developer.java.sun.com/developer/bugParade/bugs/4836495.html\r\n */\r\n private double minimumArcAngleToDraw;\r\n\r\n /**\r\n * The shadow generator for the plot (<code>null</code> permitted).\r\n * \r\n * @since 1.0.14\r\n */\r\n private ShadowGenerator shadowGenerator;\r\n\r\n /** The resourceBundle for the localization. */\r\n protected static ResourceBundle localizationResources\r\n = ResourceBundleWrapper.getBundle(\r\n \"org.jfree.chart.plot.LocalizationBundle\");\r\n\r\n /**\r\n * This debug flag controls whether or not an outline is drawn showing the\r\n * interior of the plot region. This is drawn as a lightGray rectangle\r\n * showing the padding provided by the 'interiorGap' setting.\r\n */\r\n static final boolean DEBUG_DRAW_INTERIOR = false;\r\n\r\n /**\r\n * This debug flag controls whether or not an outline is drawn showing the\r\n * link area (in blue) and link ellipse (in yellow). This controls where\r\n * the label links have 'elbow' points.\r\n */\r\n static final boolean DEBUG_DRAW_LINK_AREA = false;\r\n\r\n /**\r\n * This debug flag controls whether or not an outline is drawn showing\r\n * the pie area (in green).\r\n */\r\n static final boolean DEBUG_DRAW_PIE_AREA = false;\r\n\r\n /**\r\n * Creates a new plot. The dataset is initially set to <code>null</code>.\r\n */\r\n public PiePlot() {\r\n this(null);\r\n }\r\n\r\n /**\r\n * Creates a plot that will draw a pie chart for the specified dataset.\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n */\r\n public PiePlot(PieDataset dataset) {\r\n super();\r\n this.dataset = dataset;\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n this.pieIndex = 0;\r\n\r\n this.interiorGap = DEFAULT_INTERIOR_GAP;\r\n this.circular = true;\r\n this.startAngle = DEFAULT_START_ANGLE;\r\n this.direction = Rotation.CLOCKWISE;\r\n this.minimumArcAngleToDraw = DEFAULT_MINIMUM_ARC_ANGLE_TO_DRAW;\r\n\r\n this.sectionPaint = null;\r\n this.sectionPaintMap = new PaintMap();\r\n this.baseSectionPaint = Color.gray;\r\n this.autoPopulateSectionPaint = true;\r\n\r\n this.sectionOutlinesVisible = true;\r\n this.sectionOutlinePaint = null;\r\n this.sectionOutlinePaintMap = new PaintMap();\r\n this.baseSectionOutlinePaint = DEFAULT_OUTLINE_PAINT;\r\n this.autoPopulateSectionOutlinePaint = false;\r\n\r\n this.sectionOutlineStroke = null;\r\n this.sectionOutlineStrokeMap = new StrokeMap();\r\n this.baseSectionOutlineStroke = DEFAULT_OUTLINE_STROKE;\r\n this.autoPopulateSectionOutlineStroke = false;\r\n\r\n this.explodePercentages = new TreeMap();\r\n\r\n this.labelGenerator = new StandardPieSectionLabelGenerator();\r\n this.labelFont = DEFAULT_LABEL_FONT;\r\n this.labelPaint = DEFAULT_LABEL_PAINT;\r\n this.labelBackgroundPaint = DEFAULT_LABEL_BACKGROUND_PAINT;\r\n this.labelOutlinePaint = DEFAULT_LABEL_OUTLINE_PAINT;\r\n this.labelOutlineStroke = DEFAULT_LABEL_OUTLINE_STROKE;\r\n this.labelShadowPaint = DEFAULT_LABEL_SHADOW_PAINT;\r\n this.labelLinksVisible = true;\r\n this.labelDistributor = new PieLabelDistributor(0);\r\n\r\n this.simpleLabels = false;\r\n this.simpleLabelOffset = new RectangleInsets(UnitType.RELATIVE, 0.18,\r\n 0.18, 0.18, 0.18);\r\n this.labelPadding = new RectangleInsets(2, 2, 2, 2);\r\n\r\n this.toolTipGenerator = null;\r\n this.urlGenerator = null;\r\n this.legendLabelGenerator = new StandardPieSectionLabelGenerator();\r\n this.legendLabelToolTipGenerator = null;\r\n this.legendLabelURLGenerator = null;\r\n this.legendItemShape = Plot.DEFAULT_LEGEND_ITEM_CIRCLE;\r\n\r\n this.ignoreNullValues = false;\r\n this.ignoreZeroValues = false;\r\n\r\n this.shadowGenerator = null;\r\n }\r\n\r\n /**\r\n * Returns the dataset.\r\n *\r\n * @return The dataset (possibly <code>null</code>).\r\n *\r\n * @see #setDataset(PieDataset)\r\n */\r\n public PieDataset getDataset() {\r\n return this.dataset;\r\n }\r\n\r\n /**\r\n * Sets the dataset and sends a {@link DatasetChangeEvent} to 'this'.\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n *\r\n * @see #getDataset()\r\n */\r\n public void setDataset(PieDataset dataset) {\r\n // if there is an existing dataset, remove the plot from the list of\r\n // change listeners...\r\n PieDataset existing = this.dataset;\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n\r\n // set the new dataset, and register the chart as a change listener...\r\n this.dataset = dataset;\r\n if (dataset != null) {\r\n setDatasetGroup(dataset.getGroup());\r\n dataset.addChangeListener(this);\r\n }\r\n\r\n // send a dataset change event to self...\r\n DatasetChangeEvent event = new DatasetChangeEvent(this, dataset);\r\n datasetChanged(event);\r\n }\r\n\r\n /**\r\n * Returns the pie index (this is used by the {@link MultiplePiePlot} class\r\n * to track subplots).\r\n *\r\n * @return The pie index.\r\n *\r\n * @see #setPieIndex(int)\r\n */\r\n public int getPieIndex() {\r\n return this.pieIndex;\r\n }\r\n\r\n /**\r\n * Sets the pie index (this is used by the {@link MultiplePiePlot} class to\r\n * track subplots).\r\n *\r\n * @param index the index.\r\n *\r\n * @see #getPieIndex()\r\n */\r\n public void setPieIndex(int index) {\r\n this.pieIndex = index;\r\n }\r\n\r\n /**\r\n * Returns the start angle for the first pie section. This is measured in\r\n * degrees starting from 3 o'clock and measuring anti-clockwise.\r\n *\r\n * @return The start angle.\r\n *\r\n * @see #setStartAngle(double)\r\n */\r\n public double getStartAngle() {\r\n return this.startAngle;\r\n }\r\n\r\n /**\r\n * Sets the starting angle and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. The initial default value is 90 degrees, which\r\n * corresponds to 12 o'clock. A value of zero corresponds to 3 o'clock...\r\n * this is the encoding used by Java's Arc2D class.\r\n *\r\n * @param angle the angle (in degrees).\r\n *\r\n * @see #getStartAngle()\r\n */\r\n public void setStartAngle(double angle) {\r\n this.startAngle = angle;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the direction in which the pie sections are drawn (clockwise or\r\n * anti-clockwise).\r\n *\r\n * @return The direction (never <code>null</code>).\r\n *\r\n * @see #setDirection(Rotation)\r\n */\r\n public Rotation getDirection() {\r\n return this.direction;\r\n }\r\n\r\n /**\r\n * Sets the direction in which the pie sections are drawn and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param direction the direction (<code>null</code> not permitted).\r\n *\r\n * @see #getDirection()\r\n */\r\n public void setDirection(Rotation direction) {\r\n ParamChecks.nullNotPermitted(direction, \"direction\");\r\n this.direction = direction;\r\n fireChangeEvent();\r\n\r\n }\r\n\r\n /**\r\n * Returns the interior gap, measured as a percentage of the available\r\n * drawing space.\r\n *\r\n * @return The gap (as a percentage of the available drawing space).\r\n *\r\n * @see #setInteriorGap(double)\r\n */\r\n public double getInteriorGap() {\r\n return this.interiorGap;\r\n }\r\n\r\n /**\r\n * Sets the interior gap and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. This controls the space between the edges of the\r\n * pie plot and the plot area itself (the region where the section labels\r\n * appear).\r\n *\r\n * @param percent the gap (as a percentage of the available drawing space).\r\n *\r\n * @see #getInteriorGap()\r\n */\r\n public void setInteriorGap(double percent) {\r\n\r\n if ((percent < 0.0) || (percent > MAX_INTERIOR_GAP)) {\r\n throw new IllegalArgumentException(\r\n \"Invalid 'percent' (\" + percent + \") argument.\");\r\n }\r\n\r\n if (this.interiorGap != percent) {\r\n this.interiorGap = percent;\r\n fireChangeEvent();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether the pie chart is circular, or\r\n * stretched into an elliptical shape.\r\n *\r\n * @return A flag indicating whether the pie chart is circular.\r\n *\r\n * @see #setCircular(boolean)\r\n */\r\n public boolean isCircular() {\r\n return this.circular;\r\n }\r\n\r\n /**\r\n * A flag indicating whether the pie chart is circular, or stretched into\r\n * an elliptical shape.\r\n *\r\n * @param flag the new value.\r\n *\r\n * @see #isCircular()\r\n */\r\n public void setCircular(boolean flag) {\r\n setCircular(flag, true);\r\n }\r\n\r\n /**\r\n * Sets the circular attribute and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param circular the new value of the flag.\r\n * @param notify notify listeners?\r\n *\r\n * @see #isCircular()\r\n */\r\n public void setCircular(boolean circular, boolean notify) {\r\n this.circular = circular;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether <code>null</code> values in the\r\n * dataset are ignored.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setIgnoreNullValues(boolean)\r\n */\r\n public boolean getIgnoreNullValues() {\r\n return this.ignoreNullValues;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether <code>null</code> values are ignored,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners. At\r\n * present, this only affects whether or not the key is presented in the\r\n * legend.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #getIgnoreNullValues()\r\n * @see #setIgnoreZeroValues(boolean)\r\n */\r\n public void setIgnoreNullValues(boolean flag) {\r\n this.ignoreNullValues = flag;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether zero values in the\r\n * dataset are ignored.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setIgnoreZeroValues(boolean)\r\n */\r\n public boolean getIgnoreZeroValues() {\r\n return this.ignoreZeroValues;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether zero values are ignored,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners. This\r\n * only affects whether or not a label appears for the non-visible\r\n * pie section.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #getIgnoreZeroValues()\r\n * @see #setIgnoreNullValues(boolean)\r\n */\r\n public void setIgnoreZeroValues(boolean flag) {\r\n this.ignoreZeroValues = flag;\r\n fireChangeEvent();\r\n }\r\n\r\n //// SECTION PAINT ////////////////////////////////////////////////////////\r\n\r\n /**\r\n * Returns the paint for the specified section. This is equivalent to\r\n * <code>lookupSectionPaint(section, getAutoPopulateSectionPaint())</code>.\r\n *\r\n * @param key the section key.\r\n *\r\n * @return The paint for the specified section.\r\n *\r\n * @since 1.0.3\r\n *\r\n * @see #lookupSectionPaint(Comparable, boolean)\r\n */\r\n protected Paint lookupSectionPaint(Comparable key) {\r\n return lookupSectionPaint(key, getAutoPopulateSectionPaint());\r\n }\r\n\r\n /**\r\n * Returns the paint for the specified section. The lookup involves these\r\n * steps:\r\n * <ul>\r\n * <li>if {@link #getSectionPaint()} is non-<code>null</code>, return\r\n * it;</li>\r\n * <li>if {@link #getSectionPaint(int)} is non-<code>null</code> return\r\n * it;</li>\r\n * <li>if {@link #getSectionPaint(int)} is <code>null</code> but\r\n * <code>autoPopulate</code> is <code>true</code>, attempt to fetch\r\n * a new paint from the drawing supplier\r\n * ({@link #getDrawingSupplier()});\r\n * <li>if all else fails, return {@link #getBaseSectionPaint()}.\r\n * </ul>\r\n *\r\n * @param key the section key.\r\n * @param autoPopulate a flag that controls whether the drawing supplier\r\n * is used to auto-populate the section paint settings.\r\n *\r\n * @return The paint.\r\n *\r\n * @since 1.0.3\r\n */\r\n protected Paint lookupSectionPaint(Comparable key, boolean autoPopulate) {\r\n\r\n // is there an override?\r\n Paint result = getSectionPaint();\r\n if (result != null) {\r\n return result;\r\n }\r\n\r\n // if not, check if there is a paint defined for the specified key\r\n result = this.sectionPaintMap.getPaint(key);\r\n if (result != null) {\r\n return result;\r\n }\r\n\r\n // nothing defined - do we autoPopulate?\r\n if (autoPopulate) {\r\n DrawingSupplier ds = getDrawingSupplier();\r\n if (ds != null) {\r\n result = ds.getNextPaint();\r\n this.sectionPaintMap.put(key, result);\r\n }\r\n else {\r\n result = this.baseSectionPaint;\r\n }\r\n }\r\n else {\r\n result = this.baseSectionPaint;\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the paint for ALL sections in the plot.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setSectionPaint(Paint)\r\n *\r\n * @deprecated Use {@link #getSectionPaint(Comparable)} and\r\n * {@link #getBaseSectionPaint()}. Deprecated as of version 1.0.6.\r\n */\r\n public Paint getSectionPaint() {\r\n return this.sectionPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for ALL sections in the plot. If this is set to\r\n * {@code null}, then a list of paints is used instead (to allow\r\n * different colors to be used for each section).\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getSectionPaint()\r\n *\r\n * @deprecated Use {@link #setSectionPaint(Comparable, Paint)} and\r\n * {@link #setBaseSectionPaint(Paint)}. Deprecated as of version 1.0.6.\r\n */\r\n public void setSectionPaint(Paint paint) {\r\n this.sectionPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a key for the specified section. If there is no such section\r\n * in the dataset, we generate a key. This is to provide some backward\r\n * compatibility for the (now deprecated) methods that get/set attributes\r\n * based on section indices. The preferred way of doing this now is to\r\n * link the attributes directly to the section key (there are new methods\r\n * for this, starting from version 1.0.3).\r\n *\r\n * @param section the section index.\r\n *\r\n * @return The key.\r\n *\r\n * @since 1.0.3\r\n */\r\n protected Comparable getSectionKey(int section) {\r\n Comparable key = null;\r\n if (this.dataset != null) {\r\n if (section >= 0 && section < this.dataset.getItemCount()) {\r\n key = this.dataset.getKey(section);\r\n }\r\n }\r\n if (key == null) {\r\n key = new Integer(section);\r\n }\r\n return key;\r\n }\r\n\r\n /**\r\n * Returns the paint associated with the specified key, or\r\n * <code>null</code> if there is no paint associated with the key.\r\n *\r\n * @param key the key (<code>null</code> not permitted).\r\n *\r\n * @return The paint associated with the specified key, or\r\n * <code>null</code>.\r\n *\r\n * @throws IllegalArgumentException if <code>key</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #setSectionPaint(Comparable, Paint)\r\n *\r\n * @since 1.0.3\r\n */\r\n public Paint getSectionPaint(Comparable key) {\r\n // null argument check delegated...\r\n return this.sectionPaintMap.getPaint(key);\r\n }\r\n\r\n /**\r\n * Sets the paint associated with the specified key, and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param key the key (<code>null</code> not permitted).\r\n * @param paint the paint.\r\n *\r\n * @throws IllegalArgumentException if <code>key</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getSectionPaint(Comparable)\r\n *\r\n * @since 1.0.3\r\n */\r\n public void setSectionPaint(Comparable key, Paint paint) {\r\n // null argument check delegated...\r\n this.sectionPaintMap.put(key, paint);\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Clears the section paint settings for this plot and, if requested, sends\r\n * a {@link PlotChangeEvent} to all registered listeners. Be aware that\r\n * if the <code>autoPopulateSectionPaint</code> flag is set, the section\r\n * paints may be repopulated using the same colours as before.\r\n *\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #autoPopulateSectionPaint\r\n */\r\n public void clearSectionPaints(boolean notify) {\r\n this.sectionPaintMap.clear();\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the base section paint. This is used when no other paint is\r\n * defined, which is rare. The default value is <code>Color.gray</code>.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setBaseSectionPaint(Paint)\r\n */\r\n public Paint getBaseSectionPaint() {\r\n return this.baseSectionPaint;\r\n }\r\n\r\n /**\r\n * Sets the base section paint and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getBaseSectionPaint()\r\n */\r\n public void setBaseSectionPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.baseSectionPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the section paint is\r\n * auto-populated by the {@link #lookupSectionPaint(Comparable)} method.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.11\r\n */\r\n public boolean getAutoPopulateSectionPaint() {\r\n return this.autoPopulateSectionPaint;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the section paint is\r\n * auto-populated by the {@link #lookupSectionPaint(Comparable)} method,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param auto auto-populate?\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setAutoPopulateSectionPaint(boolean auto) {\r\n this.autoPopulateSectionPaint = auto;\r\n fireChangeEvent();\r\n }\r\n\r\n //// SECTION OUTLINE PAINT ////////////////////////////////////////////////\r\n\r\n /**\r\n * Returns the flag that controls whether or not the outline is drawn for\r\n * each pie section.\r\n *\r\n * @return The flag that controls whether or not the outline is drawn for\r\n * each pie section.\r\n *\r\n * @see #setSectionOutlinesVisible(boolean)\r\n */\r\n public boolean getSectionOutlinesVisible() {\r\n return this.sectionOutlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the outline is drawn for\r\n * each pie section, and sends a {@link PlotChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #getSectionOutlinesVisible()\r\n */\r\n public void setSectionOutlinesVisible(boolean visible) {\r\n this.sectionOutlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the outline paint for the specified section. This is equivalent\r\n * to <code>lookupSectionPaint(section,\r\n * getAutoPopulateSectionOutlinePaint())</code>.\r\n *\r\n * @param key the section key.\r\n *\r\n * @return The paint for the specified section.\r\n *\r\n * @since 1.0.3\r\n *\r\n * @see #lookupSectionOutlinePaint(Comparable, boolean)\r\n */\r\n protected Paint lookupSectionOutlinePaint(Comparable key) {\r\n return lookupSectionOutlinePaint(key,\r\n getAutoPopulateSectionOutlinePaint());\r\n }\r\n\r\n /**\r\n * Returns the outline paint for the specified section. The lookup\r\n * involves these steps:\r\n * <ul>\r\n * <li>if {@link #getSectionOutlinePaint()} is non-<code>null</code>,\r\n * return it;</li>\r\n * <li>otherwise, if {@link #getSectionOutlinePaint(int)} is\r\n * non-<code>null</code> return it;</li>\r\n * <li>if {@link #getSectionOutlinePaint(int)} is <code>null</code> but\r\n * <code>autoPopulate</code> is <code>true</code>, attempt to fetch\r\n * a new outline paint from the drawing supplier\r\n * ({@link #getDrawingSupplier()});\r\n * <li>if all else fails, return {@link #getBaseSectionOutlinePaint()}.\r\n * </ul>\r\n *\r\n * @param key the section key.\r\n * @param autoPopulate a flag that controls whether the drawing supplier\r\n * is used to auto-populate the section outline paint settings.\r\n *\r\n * @return The paint.\r\n *\r\n * @since 1.0.3\r\n */\r\n protected Paint lookupSectionOutlinePaint(Comparable key,\r\n boolean autoPopulate) {\r\n\r\n // is there an override?\r\n Paint result = getSectionOutlinePaint();\r\n if (result != null) {\r\n return result;\r\n }\r\n\r\n // if not, check if there is a paint defined for the specified key\r\n result = this.sectionOutlinePaintMap.getPaint(key);\r\n if (result != null) {\r\n return result;\r\n }\r\n\r\n // nothing defined - do we autoPopulate?\r\n if (autoPopulate) {\r\n DrawingSupplier ds = getDrawingSupplier();\r\n if (ds != null) {\r\n result = ds.getNextOutlinePaint();\r\n this.sectionOutlinePaintMap.put(key, result);\r\n }\r\n else {\r\n result = this.baseSectionOutlinePaint;\r\n }\r\n }\r\n else {\r\n result = this.baseSectionOutlinePaint;\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the outline paint associated with the specified key, or\r\n * <code>null</code> if there is no paint associated with the key.\r\n *\r\n * @param key the key (<code>null</code> not permitted).\r\n *\r\n * @return The paint associated with the specified key, or\r\n * <code>null</code>.\r\n *\r\n * @throws IllegalArgumentException if <code>key</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #setSectionOutlinePaint(Comparable, Paint)\r\n *\r\n * @since 1.0.3\r\n */\r\n public Paint getSectionOutlinePaint(Comparable key) {\r\n // null argument check delegated...\r\n return this.sectionOutlinePaintMap.getPaint(key);\r\n }\r\n\r\n /**\r\n * Sets the outline paint associated with the specified key, and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param key the key (<code>null</code> not permitted).\r\n * @param paint the paint.\r\n *\r\n * @throws IllegalArgumentException if <code>key</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getSectionOutlinePaint(Comparable)\r\n *\r\n * @since 1.0.3\r\n */\r\n public void setSectionOutlinePaint(Comparable key, Paint paint) {\r\n // null argument check delegated...\r\n this.sectionOutlinePaintMap.put(key, paint);\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Clears the section outline paint settings for this plot and, if\r\n * requested, sends a {@link PlotChangeEvent} to all registered listeners.\r\n * Be aware that if the <code>autoPopulateSectionPaint</code> flag is set,\r\n * the section paints may be repopulated using the same colours as before.\r\n *\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #autoPopulateSectionOutlinePaint\r\n */\r\n public void clearSectionOutlinePaints(boolean notify) {\r\n this.sectionOutlinePaintMap.clear();\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the base section paint. This is used when no other paint is\r\n * available.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setBaseSectionOutlinePaint(Paint)\r\n */\r\n public Paint getBaseSectionOutlinePaint() {\r\n return this.baseSectionOutlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the base section paint.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getBaseSectionOutlinePaint()\r\n */\r\n public void setBaseSectionOutlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.baseSectionOutlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the section outline paint\r\n * is auto-populated by the {@link #lookupSectionOutlinePaint(Comparable)}\r\n * method.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.11\r\n */\r\n public boolean getAutoPopulateSectionOutlinePaint() {\r\n return this.autoPopulateSectionOutlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the section outline paint is\r\n * auto-populated by the {@link #lookupSectionOutlinePaint(Comparable)}\r\n * method, and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param auto auto-populate?\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setAutoPopulateSectionOutlinePaint(boolean auto) {\r\n this.autoPopulateSectionOutlinePaint = auto;\r\n fireChangeEvent();\r\n }\r\n\r\n //// SECTION OUTLINE STROKE ///////////////////////////////////////////////\r\n\r\n /**\r\n * Returns the outline stroke for the specified section. This is\r\n * equivalent to <code>lookupSectionOutlineStroke(section,\r\n * getAutoPopulateSectionOutlineStroke())</code>.\r\n *\r\n * @param key the section key.\r\n *\r\n * @return The stroke for the specified section.\r\n *\r\n * @since 1.0.3\r\n *\r\n * @see #lookupSectionOutlineStroke(Comparable, boolean)\r\n */\r\n protected Stroke lookupSectionOutlineStroke(Comparable key) {\r\n return lookupSectionOutlineStroke(key,\r\n getAutoPopulateSectionOutlineStroke());\r\n }\r\n\r\n /**\r\n * Returns the outline stroke for the specified section. The lookup\r\n * involves these steps:\r\n * <ul>\r\n * <li>if {@link #getSectionOutlineStroke()} is non-<code>null</code>,\r\n * return it;</li>\r\n * <li>otherwise, if {@link #getSectionOutlineStroke(int)} is\r\n * non-<code>null</code> return it;</li>\r\n * <li>if {@link #getSectionOutlineStroke(int)} is <code>null</code> but\r\n * <code>autoPopulate</code> is <code>true</code>, attempt to fetch\r\n * a new outline stroke from the drawing supplier\r\n * ({@link #getDrawingSupplier()});\r\n * <li>if all else fails, return {@link #getBaseSectionOutlineStroke()}.\r\n * </ul>\r\n *\r\n * @param key the section key.\r\n * @param autoPopulate a flag that controls whether the drawing supplier\r\n * is used to auto-populate the section outline stroke settings.\r\n *\r\n * @return The stroke.\r\n *\r\n * @since 1.0.3\r\n */\r\n protected Stroke lookupSectionOutlineStroke(Comparable key,\r\n boolean autoPopulate) {\r\n\r\n // is there an override?\r\n Stroke result = getSectionOutlineStroke();\r\n if (result != null) {\r\n return result;\r\n }\r\n\r\n // if not, check if there is a stroke defined for the specified key\r\n result = this.sectionOutlineStrokeMap.getStroke(key);\r\n if (result != null) {\r\n return result;\r\n }\r\n\r\n // nothing defined - do we autoPopulate?\r\n if (autoPopulate) {\r\n DrawingSupplier ds = getDrawingSupplier();\r\n if (ds != null) {\r\n result = ds.getNextOutlineStroke();\r\n this.sectionOutlineStrokeMap.put(key, result);\r\n }\r\n else {\r\n result = this.baseSectionOutlineStroke;\r\n }\r\n }\r\n else {\r\n result = this.baseSectionOutlineStroke;\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the outline stroke associated with the specified key, or\r\n * <code>null</code> if there is no stroke associated with the key.\r\n *\r\n * @param key the key (<code>null</code> not permitted).\r\n *\r\n * @return The stroke associated with the specified key, or\r\n * <code>null</code>.\r\n *\r\n * @throws IllegalArgumentException if <code>key</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #setSectionOutlineStroke(Comparable, Stroke)\r\n *\r\n * @since 1.0.3\r\n */\r\n public Stroke getSectionOutlineStroke(Comparable key) {\r\n // null argument check delegated...\r\n return this.sectionOutlineStrokeMap.getStroke(key);\r\n }\r\n\r\n /**\r\n * Sets the outline stroke associated with the specified key, and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param key the key (<code>null</code> not permitted).\r\n * @param stroke the stroke.\r\n *\r\n * @throws IllegalArgumentException if <code>key</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getSectionOutlineStroke(Comparable)\r\n *\r\n * @since 1.0.3\r\n */\r\n public void setSectionOutlineStroke(Comparable key, Stroke stroke) {\r\n // null argument check delegated...\r\n this.sectionOutlineStrokeMap.put(key, stroke);\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Clears the section outline stroke settings for this plot and, if\r\n * requested, sends a {@link PlotChangeEvent} to all registered listeners.\r\n * Be aware that if the <code>autoPopulateSectionPaint</code> flag is set,\r\n * the section paints may be repopulated using the same colours as before.\r\n *\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #autoPopulateSectionOutlineStroke\r\n */\r\n public void clearSectionOutlineStrokes(boolean notify) {\r\n this.sectionOutlineStrokeMap.clear();\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the base section stroke. This is used when no other stroke is\r\n * available.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setBaseSectionOutlineStroke(Stroke)\r\n */\r\n public Stroke getBaseSectionOutlineStroke() {\r\n return this.baseSectionOutlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the base section stroke.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getBaseSectionOutlineStroke()\r\n */\r\n public void setBaseSectionOutlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.baseSectionOutlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the section outline stroke\r\n * is auto-populated by the {@link #lookupSectionOutlinePaint(Comparable)}\r\n * method.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.11\r\n */\r\n public boolean getAutoPopulateSectionOutlineStroke() {\r\n return this.autoPopulateSectionOutlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the section outline stroke is\r\n * auto-populated by the {@link #lookupSectionOutlineStroke(Comparable)}\r\n * method, and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param auto auto-populate?\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setAutoPopulateSectionOutlineStroke(boolean auto) {\r\n this.autoPopulateSectionOutlineStroke = auto;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the shadow paint.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setShadowPaint(Paint)\r\n */\r\n public Paint getShadowPaint() {\r\n return this.shadowPaint;\r\n }\r\n\r\n /**\r\n * Sets the shadow paint and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getShadowPaint()\r\n */\r\n public void setShadowPaint(Paint paint) {\r\n this.shadowPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the x-offset for the shadow effect.\r\n *\r\n * @return The offset (in Java2D units).\r\n *\r\n * @see #setShadowXOffset(double)\r\n */\r\n public double getShadowXOffset() {\r\n return this.shadowXOffset;\r\n }\r\n\r\n /**\r\n * Sets the x-offset for the shadow effect and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param offset the offset (in Java2D units).\r\n *\r\n * @see #getShadowXOffset()\r\n */\r\n public void setShadowXOffset(double offset) {\r\n this.shadowXOffset = offset;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the y-offset for the shadow effect.\r\n *\r\n * @return The offset (in Java2D units).\r\n *\r\n * @see #setShadowYOffset(double)\r\n */\r\n public double getShadowYOffset() {\r\n return this.shadowYOffset;\r\n }\r\n\r\n /**\r\n * Sets the y-offset for the shadow effect and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param offset the offset (in Java2D units).\r\n *\r\n * @see #getShadowYOffset()\r\n */\r\n public void setShadowYOffset(double offset) {\r\n this.shadowYOffset = offset;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the amount that the section with the specified key should be\r\n * exploded.\r\n *\r\n * @param key the key (<code>null</code> not permitted).\r\n *\r\n * @return The amount that the section with the specified key should be\r\n * exploded.\r\n *\r\n * @throws IllegalArgumentException if <code>key</code> is\r\n * <code>null</code>.\r\n *\r\n * @since 1.0.3\r\n *\r\n * @see #setExplodePercent(Comparable, double)\r\n */\r\n public double getExplodePercent(Comparable key) {\r\n double result = 0.0;\r\n if (this.explodePercentages != null) {\r\n Number percent = (Number) this.explodePercentages.get(key);\r\n if (percent != null) {\r\n result = percent.doubleValue();\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the amount that a pie section should be exploded and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param key the section key (<code>null</code> not permitted).\r\n * @param percent the explode percentage (0.30 = 30 percent).\r\n *\r\n * @since 1.0.3\r\n *\r\n * @see #getExplodePercent(Comparable)\r\n */\r\n public void setExplodePercent(Comparable key, double percent) {\r\n ParamChecks.nullNotPermitted(key, \"key\");\r\n if (this.explodePercentages == null) {\r\n this.explodePercentages = new TreeMap();\r\n }\r\n this.explodePercentages.put(key, new Double(percent));\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the maximum explode percent.\r\n *\r\n * @return The percent.\r\n */\r\n public double getMaximumExplodePercent() {\r\n if (this.dataset == null) {\r\n return 0.0;\r\n }\r\n double result = 0.0;\r\n Iterator iterator = this.dataset.getKeys().iterator();\r\n while (iterator.hasNext()) {\r\n Comparable key = (Comparable) iterator.next();\r\n Number explode = (Number) this.explodePercentages.get(key);\r\n if (explode != null) {\r\n result = Math.max(result, explode.doubleValue());\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the section label generator.\r\n *\r\n * @return The generator (possibly <code>null</code>).\r\n *\r\n * @see #setLabelGenerator(PieSectionLabelGenerator)\r\n */\r\n public PieSectionLabelGenerator getLabelGenerator() {\r\n return this.labelGenerator;\r\n }\r\n\r\n /**\r\n * Sets the section label generator and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @see #getLabelGenerator()\r\n */\r\n public void setLabelGenerator(PieSectionLabelGenerator generator) {\r\n this.labelGenerator = generator;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the gap between the edge of the pie and the labels, expressed as\r\n * a percentage of the plot width.\r\n *\r\n * @return The gap (a percentage, where 0.05 = five percent).\r\n *\r\n * @see #setLabelGap(double)\r\n */\r\n public double getLabelGap() {\r\n return this.labelGap;\r\n }\r\n\r\n /**\r\n * Sets the gap between the edge of the pie and the labels (expressed as a\r\n * percentage of the plot width) and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param gap the gap (a percentage, where 0.05 = five percent).\r\n *\r\n * @see #getLabelGap()\r\n */\r\n public void setLabelGap(double gap) {\r\n this.labelGap = gap;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the maximum label width as a percentage of the plot width.\r\n *\r\n * @return The width (a percentage, where 0.20 = 20 percent).\r\n *\r\n * @see #setMaximumLabelWidth(double)\r\n */\r\n public double getMaximumLabelWidth() {\r\n return this.maximumLabelWidth;\r\n }\r\n\r\n /**\r\n * Sets the maximum label width as a percentage of the plot width and sends\r\n * a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param width the width (a percentage, where 0.20 = 20 percent).\r\n *\r\n * @see #getMaximumLabelWidth()\r\n */\r\n public void setMaximumLabelWidth(double width) {\r\n this.maximumLabelWidth = width;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not label linking lines are\r\n * visible.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setLabelLinksVisible(boolean)\r\n */\r\n public boolean getLabelLinksVisible() {\r\n return this.labelLinksVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not label linking lines are\r\n * visible and sends a {@link PlotChangeEvent} to all registered listeners.\r\n * Please take care when hiding the linking lines - depending on the data\r\n * values, the labels can be displayed some distance away from the\r\n * corresponding pie section.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #getLabelLinksVisible()\r\n */\r\n public void setLabelLinksVisible(boolean visible) {\r\n this.labelLinksVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the label link style.\r\n *\r\n * @return The label link style (never <code>null</code>).\r\n *\r\n * @see #setLabelLinkStyle(PieLabelLinkStyle)\r\n *\r\n * @since 1.0.10\r\n */\r\n public PieLabelLinkStyle getLabelLinkStyle() {\r\n return this.labelLinkStyle;\r\n }\r\n\r\n /**\r\n * Sets the label link style and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param style the new style (<code>null</code> not permitted).\r\n *\r\n * @see #getLabelLinkStyle()\r\n *\r\n * @since 1.0.10\r\n */\r\n public void setLabelLinkStyle(PieLabelLinkStyle style) {\r\n ParamChecks.nullNotPermitted(style, \"style\");\r\n this.labelLinkStyle = style;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the margin (expressed as a percentage of the width or height)\r\n * between the edge of the pie and the link point.\r\n *\r\n * @return The link margin (as a percentage, where 0.05 is five percent).\r\n *\r\n * @see #setLabelLinkMargin(double)\r\n */\r\n public double getLabelLinkMargin() {\r\n return this.labelLinkMargin;\r\n }\r\n\r\n /**\r\n * Sets the link margin and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param margin the margin.\r\n *\r\n * @see #getLabelLinkMargin()\r\n */\r\n public void setLabelLinkMargin(double margin) {\r\n this.labelLinkMargin = margin;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the lines that connect pie sections to their\r\n * corresponding labels.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setLabelLinkPaint(Paint)\r\n */\r\n public Paint getLabelLinkPaint() {\r\n return this.labelLinkPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used for the lines that connect pie sections to their\r\n * corresponding labels, and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getLabelLinkPaint()\r\n */\r\n public void setLabelLinkPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.labelLinkPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used for the label linking lines.\r\n *\r\n * @return The stroke.\r\n *\r\n * @see #setLabelLinkStroke(Stroke)\r\n */\r\n public Stroke getLabelLinkStroke() {\r\n return this.labelLinkStroke;\r\n }\r\n\r\n /**\r\n * Sets the link stroke and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param stroke the stroke.\r\n *\r\n * @see #getLabelLinkStroke()\r\n */\r\n public void setLabelLinkStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.labelLinkStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the distance that the end of the label link is embedded into\r\n * the plot, expressed as a percentage of the plot's radius.\r\n * <br><br>\r\n * This method is overridden in the {@link RingPlot} class to resolve\r\n * bug 2121818.\r\n *\r\n * @return <code>0.10</code>.\r\n *\r\n * @since 1.0.12\r\n */\r\n protected double getLabelLinkDepth() {\r\n return 0.1;\r\n }\r\n\r\n /**\r\n * Returns the section label font.\r\n *\r\n * @return The font (never <code>null</code>).\r\n *\r\n * @see #setLabelFont(Font)\r\n */\r\n public Font getLabelFont() {\r\n return this.labelFont;\r\n }\r\n\r\n /**\r\n * Sets the section label font and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param font the font (<code>null</code> not permitted).\r\n *\r\n * @see #getLabelFont()\r\n */\r\n public void setLabelFont(Font font) {\r\n ParamChecks.nullNotPermitted(font, \"font\");\r\n this.labelFont = font;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the section label paint.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setLabelPaint(Paint)\r\n */\r\n public Paint getLabelPaint() {\r\n return this.labelPaint;\r\n }\r\n\r\n /**\r\n * Sets the section label paint and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getLabelPaint()\r\n */\r\n public void setLabelPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.labelPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the section label background paint.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setLabelBackgroundPaint(Paint)\r\n */\r\n public Paint getLabelBackgroundPaint() {\r\n return this.labelBackgroundPaint;\r\n }\r\n\r\n /**\r\n * Sets the section label background paint and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getLabelBackgroundPaint()\r\n */\r\n public void setLabelBackgroundPaint(Paint paint) {\r\n this.labelBackgroundPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the section label outline paint.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setLabelOutlinePaint(Paint)\r\n */\r\n public Paint getLabelOutlinePaint() {\r\n return this.labelOutlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the section label outline paint and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getLabelOutlinePaint()\r\n */\r\n public void setLabelOutlinePaint(Paint paint) {\r\n this.labelOutlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the section label outline stroke.\r\n *\r\n * @return The stroke (possibly <code>null</code>).\r\n *\r\n * @see #setLabelOutlineStroke(Stroke)\r\n */\r\n public Stroke getLabelOutlineStroke() {\r\n return this.labelOutlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the section label outline stroke and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> permitted).\r\n *\r\n * @see #getLabelOutlineStroke()\r\n */\r\n public void setLabelOutlineStroke(Stroke stroke) {\r\n this.labelOutlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the section label shadow paint.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setLabelShadowPaint(Paint)\r\n */\r\n public Paint getLabelShadowPaint() {\r\n return this.labelShadowPaint;\r\n }\r\n\r\n /**\r\n * Sets the section label shadow paint and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getLabelShadowPaint()\r\n */\r\n public void setLabelShadowPaint(Paint paint) {\r\n this.labelShadowPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the label padding.\r\n *\r\n * @return The label padding (never <code>null</code>).\r\n *\r\n * @since 1.0.7\r\n *\r\n * @see #setLabelPadding(RectangleInsets)\r\n */\r\n public RectangleInsets getLabelPadding() {\r\n return this.labelPadding;\r\n }\r\n\r\n /**\r\n * Sets the padding between each label and its outline and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param padding the padding (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.7\r\n *\r\n * @see #getLabelPadding()\r\n */\r\n public void setLabelPadding(RectangleInsets padding) {\r\n ParamChecks.nullNotPermitted(padding, \"padding\");\r\n this.labelPadding = padding;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether simple or extended labels are\r\n * displayed on the plot.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean getSimpleLabels() {\r\n return this.simpleLabels;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether simple or extended labels are\r\n * displayed on the plot, and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param simple the new flag value.\r\n *\r\n * @since 1.0.7\r\n */\r\n public void setSimpleLabels(boolean simple) {\r\n this.simpleLabels = simple;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the offset used for the simple labels, if they are displayed.\r\n *\r\n * @return The offset (never <code>null</code>).\r\n *\r\n * @since 1.0.7\r\n *\r\n * @see #setSimpleLabelOffset(RectangleInsets)\r\n */\r\n public RectangleInsets getSimpleLabelOffset() {\r\n return this.simpleLabelOffset;\r\n }\r\n\r\n /**\r\n * Sets the offset for the simple labels and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param offset the offset (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.7\r\n *\r\n * @see #getSimpleLabelOffset()\r\n */\r\n public void setSimpleLabelOffset(RectangleInsets offset) {\r\n ParamChecks.nullNotPermitted(offset, \"offset\");\r\n this.simpleLabelOffset = offset;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the object responsible for the vertical layout of the pie\r\n * section labels.\r\n *\r\n * @return The label distributor (never <code>null</code>).\r\n *\r\n * @since 1.0.6\r\n */\r\n public AbstractPieLabelDistributor getLabelDistributor() {\r\n return this.labelDistributor;\r\n }\r\n\r\n /**\r\n * Sets the label distributor and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param distributor the distributor (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.6\r\n */\r\n public void setLabelDistributor(AbstractPieLabelDistributor distributor) {\r\n ParamChecks.nullNotPermitted(distributor, \"distributor\");\r\n this.labelDistributor = distributor;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the tool tip generator, an object that is responsible for\r\n * generating the text items used for tool tips by the plot. If the\r\n * generator is <code>null</code>, no tool tips will be created.\r\n *\r\n * @return The generator (possibly <code>null</code>).\r\n *\r\n * @see #setToolTipGenerator(PieToolTipGenerator)\r\n */\r\n public PieToolTipGenerator getToolTipGenerator() {\r\n return this.toolTipGenerator;\r\n }\r\n\r\n /**\r\n * Sets the tool tip generator and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. Set the generator to <code>null</code> if you\r\n * don't want any tool tips.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @see #getToolTipGenerator()\r\n */\r\n public void setToolTipGenerator(PieToolTipGenerator generator) {\r\n this.toolTipGenerator = generator;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the URL generator.\r\n *\r\n * @return The generator (possibly <code>null</code>).\r\n *\r\n * @see #setURLGenerator(PieURLGenerator)\r\n */\r\n public PieURLGenerator getURLGenerator() {\r\n return this.urlGenerator;\r\n }\r\n\r\n /**\r\n * Sets the URL generator and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @see #getURLGenerator()\r\n */\r\n public void setURLGenerator(PieURLGenerator generator) {\r\n this.urlGenerator = generator;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the minimum arc angle that will be drawn. Pie sections for an\r\n * angle smaller than this are not drawn, to avoid a JDK bug.\r\n *\r\n * @return The minimum angle.\r\n *\r\n * @see #setMinimumArcAngleToDraw(double)\r\n */\r\n public double getMinimumArcAngleToDraw() {\r\n return this.minimumArcAngleToDraw;\r\n }\r\n\r\n /**\r\n * Sets the minimum arc angle that will be drawn. Pie sections for an\r\n * angle smaller than this are not drawn, to avoid a JDK bug. See this\r\n * link for details:\r\n * <br><br>\r\n * <a href=\"http://www.jfree.org/phpBB2/viewtopic.php?t=2707\">\r\n * http://www.jfree.org/phpBB2/viewtopic.php?t=2707</a>\r\n * <br><br>\r\n * ...and this bug report in the Java Bug Parade:\r\n * <br><br>\r\n * <a href=\r\n * \"http://developer.java.sun.com/developer/bugParade/bugs/4836495.html\">\r\n * http://developer.java.sun.com/developer/bugParade/bugs/4836495.html</a>\r\n *\r\n * @param angle the minimum angle.\r\n *\r\n * @see #getMinimumArcAngleToDraw()\r\n */\r\n public void setMinimumArcAngleToDraw(double angle) {\r\n this.minimumArcAngleToDraw = angle;\r\n }\r\n\r\n /**\r\n * Returns the shape used for legend items.\r\n *\r\n * @return The shape (never <code>null</code>).\r\n *\r\n * @see #setLegendItemShape(Shape)\r\n */\r\n public Shape getLegendItemShape() {\r\n return this.legendItemShape;\r\n }\r\n\r\n /**\r\n * Sets the shape used for legend items and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param shape the shape (<code>null</code> not permitted).\r\n *\r\n * @see #getLegendItemShape()\r\n */\r\n public void setLegendItemShape(Shape shape) {\r\n ParamChecks.nullNotPermitted(shape, \"shape\");\r\n this.legendItemShape = shape;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the legend label generator.\r\n *\r\n * @return The legend label generator (never <code>null</code>).\r\n *\r\n * @see #setLegendLabelGenerator(PieSectionLabelGenerator)\r\n */\r\n public PieSectionLabelGenerator getLegendLabelGenerator() {\r\n return this.legendLabelGenerator;\r\n }\r\n\r\n /**\r\n * Sets the legend label generator and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param generator the generator (<code>null</code> not permitted).\r\n *\r\n * @see #getLegendLabelGenerator()\r\n */\r\n public void setLegendLabelGenerator(PieSectionLabelGenerator generator) {\r\n ParamChecks.nullNotPermitted(generator, \"generator\");\r\n this.legendLabelGenerator = generator;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the legend label tool tip generator.\r\n *\r\n * @return The legend label tool tip generator (possibly <code>null</code>).\r\n *\r\n * @see #setLegendLabelToolTipGenerator(PieSectionLabelGenerator)\r\n */\r\n public PieSectionLabelGenerator getLegendLabelToolTipGenerator() {\r\n return this.legendLabelToolTipGenerator;\r\n }\r\n\r\n /**\r\n * Sets the legend label tool tip generator and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @see #getLegendLabelToolTipGenerator()\r\n */\r\n public void setLegendLabelToolTipGenerator(\r\n PieSectionLabelGenerator generator) {\r\n this.legendLabelToolTipGenerator = generator;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the legend label URL generator.\r\n *\r\n * @return The legend label URL generator (possibly <code>null</code>).\r\n *\r\n * @see #setLegendLabelURLGenerator(PieURLGenerator)\r\n *\r\n * @since 1.0.4\r\n */\r\n public PieURLGenerator getLegendLabelURLGenerator() {\r\n return this.legendLabelURLGenerator;\r\n }\r\n\r\n /**\r\n * Sets the legend label URL generator and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @see #getLegendLabelURLGenerator()\r\n *\r\n * @since 1.0.4\r\n */\r\n public void setLegendLabelURLGenerator(PieURLGenerator generator) {\r\n this.legendLabelURLGenerator = generator;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the shadow generator for the plot, if any.\r\n * \r\n * @return The shadow generator (possibly <code>null</code>).\r\n * \r\n * @since 1.0.14\r\n */\r\n public ShadowGenerator getShadowGenerator() {\r\n return this.shadowGenerator;\r\n }\r\n\r\n /**\r\n * Sets the shadow generator for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. Note that this is\r\n * a bitmap drop-shadow generation facility and is separate from the\r\n * vector based show option that is controlled via the\r\n * {@link #setShadowPaint(java.awt.Paint)} method.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setShadowGenerator(ShadowGenerator generator) {\r\n this.shadowGenerator = generator;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Handles a mouse wheel rotation (this method is intended for use by the\r\n * {@code MouseWheelHandler} class).\r\n *\r\n * @param rotateClicks the number of rotate clicks on the the mouse wheel.\r\n *\r\n * @since 1.0.14\r\n */\r\n public void handleMouseWheelRotation(int rotateClicks) {\r\n setStartAngle(this.startAngle + rotateClicks * 4.0);\r\n }\r\n\r\n /**\r\n * Initialises the drawing procedure. This method will be called before\r\n * the first item is rendered, giving the plot an opportunity to initialise\r\n * any state information it wants to maintain.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area (<code>null</code> not permitted).\r\n * @param plot the plot.\r\n * @param index the secondary index (<code>null</code> for primary\r\n * renderer).\r\n * @param info collects chart rendering information for return to caller.\r\n *\r\n * @return A state object (maintains state information relevant to one\r\n * chart drawing).\r\n */\r\n public PiePlotState initialise(Graphics2D g2, Rectangle2D plotArea,\r\n PiePlot plot, Integer index, PlotRenderingInfo info) {\r\n\r\n PiePlotState state = new PiePlotState(info);\r\n state.setPassesRequired(2);\r\n if (this.dataset != null) {\r\n state.setTotal(DatasetUtilities.calculatePieDatasetTotal(\r\n plot.getDataset()));\r\n }\r\n state.setLatestAngle(plot.getStartAngle());\r\n return state;\r\n\r\n }\r\n\r\n /**\r\n * Draws the plot on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot should be drawn.\r\n * @param anchor the anchor point (<code>null</code> permitted).\r\n * @param parentState the state from the parent plot, if there is one.\r\n * @param info collects info about the drawing\r\n * (<code>null</code> permitted).\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor,\r\n PlotState parentState, PlotRenderingInfo info) {\r\n\r\n // adjust for insets...\r\n RectangleInsets insets = getInsets();\r\n insets.trim(area);\r\n\r\n if (info != null) {\r\n info.setPlotArea(area);\r\n info.setDataArea(area);\r\n }\r\n\r\n drawBackground(g2, area);\r\n drawOutline(g2, area);\r\n\r\n Shape savedClip = g2.getClip();\r\n g2.clip(area);\r\n\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n getForegroundAlpha()));\r\n\r\n if (!DatasetUtilities.isEmptyOrNull(this.dataset)) {\r\n Graphics2D savedG2 = g2;\r\n boolean suppressShadow = Boolean.TRUE.equals(g2.getRenderingHint(\r\n JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION));\r\n BufferedImage dataImage = null;\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n dataImage = new BufferedImage((int) area.getWidth(),\r\n (int) area.getHeight(), BufferedImage.TYPE_INT_ARGB);\r\n g2 = dataImage.createGraphics();\r\n g2.translate(-area.getX(), -area.getY());\r\n g2.setRenderingHints(savedG2.getRenderingHints());\r\n }\r\n drawPie(g2, area, info);\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n BufferedImage shadowImage \r\n = this.shadowGenerator.createDropShadow(dataImage);\r\n g2 = savedG2;\r\n g2.drawImage(shadowImage, (int) area.getX() \r\n + this.shadowGenerator.calculateOffsetX(), \r\n (int) area.getY()\r\n + this.shadowGenerator.calculateOffsetY(), null);\r\n g2.drawImage(dataImage, (int) area.getX(), (int) area.getY(), \r\n null);\r\n }\r\n }\r\n else {\r\n drawNoDataMessage(g2, area);\r\n }\r\n\r\n g2.setClip(savedClip);\r\n g2.setComposite(originalComposite);\r\n\r\n drawOutline(g2, area);\r\n\r\n }\r\n\r\n /**\r\n * Draws the pie.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param info chart rendering info.\r\n */\r\n protected void drawPie(Graphics2D g2, Rectangle2D plotArea,\r\n PlotRenderingInfo info) {\r\n\r\n PiePlotState state = initialise(g2, plotArea, this, null, info);\r\n\r\n // adjust the plot area for interior spacing and labels...\r\n double labelReserve = 0.0;\r\n if (this.labelGenerator != null && !this.simpleLabels) {\r\n labelReserve = this.labelGap + this.maximumLabelWidth;\r\n }\r\n double gapHorizontal = plotArea.getWidth() * labelReserve * 2.0;\r\n double gapVertical = plotArea.getHeight() * this.interiorGap * 2.0;\r\n\r\n\r\n if (DEBUG_DRAW_INTERIOR) {\r\n double hGap = plotArea.getWidth() * this.interiorGap;\r\n double vGap = plotArea.getHeight() * this.interiorGap;\r\n\r\n double igx1 = plotArea.getX() + hGap;\r\n double igx2 = plotArea.getMaxX() - hGap;\r\n double igy1 = plotArea.getY() + vGap;\r\n double igy2 = plotArea.getMaxY() - vGap;\r\n g2.setPaint(Color.gray);\r\n g2.draw(new Rectangle2D.Double(igx1, igy1, igx2 - igx1,\r\n igy2 - igy1));\r\n }\r\n\r\n double linkX = plotArea.getX() + gapHorizontal / 2;\r\n double linkY = plotArea.getY() + gapVertical / 2;\r\n double linkW = plotArea.getWidth() - gapHorizontal;\r\n double linkH = plotArea.getHeight() - gapVertical;\r\n\r\n // make the link area a square if the pie chart is to be circular...\r\n if (this.circular) {\r\n double min = Math.min(linkW, linkH) / 2;\r\n linkX = (linkX + linkX + linkW) / 2 - min;\r\n linkY = (linkY + linkY + linkH) / 2 - min;\r\n linkW = 2 * min;\r\n linkH = 2 * min;\r\n }\r\n\r\n // the link area defines the dog leg points for the linking lines to\r\n // the labels\r\n Rectangle2D linkArea = new Rectangle2D.Double(linkX, linkY, linkW,\r\n linkH);\r\n state.setLinkArea(linkArea);\r\n\r\n if (DEBUG_DRAW_LINK_AREA) {\r\n g2.setPaint(Color.blue);\r\n g2.draw(linkArea);\r\n g2.setPaint(Color.yellow);\r\n g2.draw(new Ellipse2D.Double(linkArea.getX(), linkArea.getY(),\r\n linkArea.getWidth(), linkArea.getHeight()));\r\n }\r\n\r\n // the explode area defines the max circle/ellipse for the exploded\r\n // pie sections. it is defined by shrinking the linkArea by the\r\n // linkMargin factor.\r\n double lm = 0.0;\r\n if (!this.simpleLabels) {\r\n lm = this.labelLinkMargin;\r\n }\r\n double hh = linkArea.getWidth() * lm * 2.0;\r\n double vv = linkArea.getHeight() * lm * 2.0;\r\n Rectangle2D explodeArea = new Rectangle2D.Double(linkX + hh / 2.0,\r\n linkY + vv / 2.0, linkW - hh, linkH - vv);\r\n\r\n state.setExplodedPieArea(explodeArea);\r\n\r\n // the pie area defines the circle/ellipse for regular pie sections.\r\n // it is defined by shrinking the explodeArea by the explodeMargin\r\n // factor.\r\n double maximumExplodePercent = getMaximumExplodePercent();\r\n double percent = maximumExplodePercent / (1.0 + maximumExplodePercent);\r\n\r\n double h1 = explodeArea.getWidth() * percent;\r\n double v1 = explodeArea.getHeight() * percent;\r\n Rectangle2D pieArea = new Rectangle2D.Double(explodeArea.getX()\r\n + h1 / 2.0, explodeArea.getY() + v1 / 2.0,\r\n explodeArea.getWidth() - h1, explodeArea.getHeight() - v1);\r\n\r\n if (DEBUG_DRAW_PIE_AREA) {\r\n g2.setPaint(Color.green);\r\n g2.draw(pieArea);\r\n }\r\n state.setPieArea(pieArea);\r\n state.setPieCenterX(pieArea.getCenterX());\r\n state.setPieCenterY(pieArea.getCenterY());\r\n state.setPieWRadius(pieArea.getWidth() / 2.0);\r\n state.setPieHRadius(pieArea.getHeight() / 2.0);\r\n\r\n // plot the data (unless the dataset is null)...\r\n if ((this.dataset != null) && (this.dataset.getKeys().size() > 0)) {\r\n\r\n List keys = this.dataset.getKeys();\r\n double totalValue = DatasetUtilities.calculatePieDatasetTotal(\r\n this.dataset);\r\n\r\n int passesRequired = state.getPassesRequired();\r\n for (int pass = 0; pass < passesRequired; pass++) {\r\n double runningTotal = 0.0;\r\n for (int section = 0; section < keys.size(); section++) {\r\n Number n = this.dataset.getValue(section);\r\n if (n != null) {\r\n double value = n.doubleValue();\r\n if (value > 0.0) {\r\n runningTotal += value;\r\n drawItem(g2, section, explodeArea, state, pass);\r\n }\r\n }\r\n }\r\n }\r\n if (this.simpleLabels) {\r\n drawSimpleLabels(g2, keys, totalValue, plotArea, linkArea,\r\n state);\r\n }\r\n else {\r\n drawLabels(g2, keys, totalValue, plotArea, linkArea, state);\r\n }\r\n\r\n }\r\n else {\r\n drawNoDataMessage(g2, plotArea);\r\n }\r\n }\r\n\r\n /**\r\n * Draws a single data item.\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param section the section index.\r\n * @param dataArea the data plot area.\r\n * @param state state information for one chart.\r\n * @param currentPass the current pass index.\r\n */\r\n protected void drawItem(Graphics2D g2, int section, Rectangle2D dataArea,\r\n PiePlotState state, int currentPass) {\r\n\r\n Number n = this.dataset.getValue(section);\r\n if (n == null) {\r\n return;\r\n }\r\n double value = n.doubleValue();\r\n double angle1 = 0.0;\r\n double angle2 = 0.0;\r\n\r\n if (this.direction == Rotation.CLOCKWISE) {\r\n angle1 = state.getLatestAngle();\r\n angle2 = angle1 - value / state.getTotal() * 360.0;\r\n }\r\n else if (this.direction == Rotation.ANTICLOCKWISE) {\r\n angle1 = state.getLatestAngle();\r\n angle2 = angle1 + value / state.getTotal() * 360.0;\r\n }\r\n else {\r\n throw new IllegalStateException(\"Rotation type not recognised.\");\r\n }\r\n\r\n double angle = (angle2 - angle1);\r\n if (Math.abs(angle) > getMinimumArcAngleToDraw()) {\r\n double ep = 0.0;\r\n double mep = getMaximumExplodePercent();\r\n if (mep > 0.0) {\r\n ep = getExplodePercent(section) / mep;\r\n }\r\n Rectangle2D arcBounds = getArcBounds(state.getPieArea(),\r\n state.getExplodedPieArea(), angle1, angle, ep);\r\n Arc2D.Double arc = new Arc2D.Double(arcBounds, angle1, angle,\r\n Arc2D.PIE);\r\n\r\n if (currentPass == 0) {\r\n if (this.shadowPaint != null && this.shadowGenerator == null) {\r\n Shape shadowArc = ShapeUtilities.createTranslatedShape(\r\n arc, (float) this.shadowXOffset,\r\n (float) this.shadowYOffset);\r\n g2.setPaint(this.shadowPaint);\r\n g2.fill(shadowArc);\r\n }\r\n }\r\n else if (currentPass == 1) {\r\n Comparable key = getSectionKey(section);\r\n Paint paint = lookupSectionPaint(key, state);\r\n g2.setPaint(paint);\r\n g2.fill(arc);\r\n\r\n Paint outlinePaint = lookupSectionOutlinePaint(key);\r\n Stroke outlineStroke = lookupSectionOutlineStroke(key);\r\n if (this.sectionOutlinesVisible) {\r\n g2.setPaint(outlinePaint);\r\n g2.setStroke(outlineStroke);\r\n g2.draw(arc);\r\n }\r\n\r\n // update the linking line target for later\r\n // add an entity for the pie section\r\n if (state.getInfo() != null) {\r\n EntityCollection entities = state.getEntityCollection();\r\n if (entities != null) {\r\n String tip = null;\r\n if (this.toolTipGenerator != null) {\r\n tip = this.toolTipGenerator.generateToolTip(\r\n this.dataset, key);\r\n }\r\n String url = null;\r\n if (this.urlGenerator != null) {\r\n url = this.urlGenerator.generateURL(this.dataset,\r\n key, this.pieIndex);\r\n }\r\n PieSectionEntity entity = new PieSectionEntity(\r\n arc, this.dataset, this.pieIndex, section, key,\r\n tip, url);\r\n entities.add(entity);\r\n }\r\n }\r\n }\r\n }\r\n state.setLatestAngle(angle2);\r\n }\r\n\r\n /**\r\n * Draws the pie section labels in the simple form.\r\n *\r\n * @param g2 the graphics device.\r\n * @param keys the section keys.\r\n * @param totalValue the total value for all sections in the pie.\r\n * @param plotArea the plot area.\r\n * @param pieArea the area containing the pie.\r\n * @param state the plot state.\r\n *\r\n * @since 1.0.7\r\n */\r\n protected void drawSimpleLabels(Graphics2D g2, List keys,\r\n double totalValue, Rectangle2D plotArea, Rectangle2D pieArea,\r\n PiePlotState state) {\r\n\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n 1.0f));\r\n\r\n Rectangle2D labelsArea = this.simpleLabelOffset.createInsetRectangle(\r\n pieArea);\r\n double runningTotal = 0.0;\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable key = (Comparable) iterator.next();\r\n boolean include;\r\n double v = 0.0;\r\n Number n = getDataset().getValue(key);\r\n if (n == null) {\r\n include = !getIgnoreNullValues();\r\n }\r\n else {\r\n v = n.doubleValue();\r\n include = getIgnoreZeroValues() ? v > 0.0 : v >= 0.0;\r\n }\r\n\r\n if (include) {\r\n runningTotal = runningTotal + v;\r\n // work out the mid angle (0 - 90 and 270 - 360) = right,\r\n // otherwise left\r\n double mid = getStartAngle() + (getDirection().getFactor()\r\n * ((runningTotal - v / 2.0) * 360) / totalValue);\r\n\r\n Arc2D arc = new Arc2D.Double(labelsArea, getStartAngle(),\r\n mid - getStartAngle(), Arc2D.OPEN);\r\n int x = (int) arc.getEndPoint().getX();\r\n int y = (int) arc.getEndPoint().getY();\r\n\r\n PieSectionLabelGenerator myLabelGenerator = getLabelGenerator();\r\n if (myLabelGenerator == null) {\r\n continue;\r\n }\r\n String label = myLabelGenerator.generateSectionLabel(\r\n this.dataset, key);\r\n if (label == null) {\r\n continue;\r\n }\r\n g2.setFont(this.labelFont);\r\n FontMetrics fm = g2.getFontMetrics();\r\n Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);\r\n Rectangle2D out = this.labelPadding.createOutsetRectangle(\r\n bounds);\r\n Shape bg = ShapeUtilities.createTranslatedShape(out,\r\n x - bounds.getCenterX(), y - bounds.getCenterY());\r\n if (this.labelShadowPaint != null\r\n && this.shadowGenerator == null) {\r\n Shape shadow = ShapeUtilities.createTranslatedShape(bg,\r\n this.shadowXOffset, this.shadowYOffset);\r\n g2.setPaint(this.labelShadowPaint);\r\n g2.fill(shadow);\r\n }\r\n if (this.labelBackgroundPaint != null) {\r\n g2.setPaint(this.labelBackgroundPaint);\r\n g2.fill(bg);\r\n }\r\n if (this.labelOutlinePaint != null\r\n && this.labelOutlineStroke != null) {\r\n g2.setPaint(this.labelOutlinePaint);\r\n g2.setStroke(this.labelOutlineStroke);\r\n g2.draw(bg);\r\n }\r\n\r\n g2.setPaint(this.labelPaint);\r\n g2.setFont(this.labelFont);\r\n TextUtilities.drawAlignedString(label, g2, x, y,\r\n TextAnchor.CENTER);\r\n\r\n }\r\n }\r\n\r\n g2.setComposite(originalComposite);\r\n\r\n }\r\n\r\n /**\r\n * Draws the labels for the pie sections.\r\n *\r\n * @param g2 the graphics device.\r\n * @param keys the keys.\r\n * @param totalValue the total value.\r\n * @param plotArea the plot area.\r\n * @param linkArea the link area.\r\n * @param state the state.\r\n */\r\n protected void drawLabels(Graphics2D g2, List keys, double totalValue,\r\n Rectangle2D plotArea, Rectangle2D linkArea,\r\n PiePlotState state) {\r\n\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n 1.0f));\r\n\r\n // classify the keys according to which side the label will appear...\r\n DefaultKeyedValues leftKeys = new DefaultKeyedValues();\r\n DefaultKeyedValues rightKeys = new DefaultKeyedValues();\r\n\r\n double runningTotal = 0.0;\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable key = (Comparable) iterator.next();\r\n boolean include;\r\n double v = 0.0;\r\n Number n = this.dataset.getValue(key);\r\n if (n == null) {\r\n include = !this.ignoreNullValues;\r\n }\r\n else {\r\n v = n.doubleValue();\r\n include = this.ignoreZeroValues ? v > 0.0 : v >= 0.0;\r\n }\r\n\r\n if (include) {\r\n runningTotal = runningTotal + v;\r\n // work out the mid angle (0 - 90 and 270 - 360) = right,\r\n // otherwise left\r\n double mid = this.startAngle + (this.direction.getFactor()\r\n * ((runningTotal - v / 2.0) * 360) / totalValue);\r\n if (Math.cos(Math.toRadians(mid)) < 0.0) {\r\n leftKeys.addValue(key, new Double(mid));\r\n }\r\n else {\r\n rightKeys.addValue(key, new Double(mid));\r\n }\r\n }\r\n }\r\n\r\n g2.setFont(getLabelFont());\r\n\r\n // calculate the max label width from the plot dimensions, because\r\n // a circular pie can leave a lot more room for labels...\r\n double marginX = plotArea.getX();\r\n double gap = plotArea.getWidth() * this.labelGap;\r\n double ww = linkArea.getX() - gap - marginX;\r\n float labelWidth = (float) this.labelPadding.trimWidth(ww);\r\n\r\n // draw the labels...\r\n if (this.labelGenerator != null) {\r\n drawLeftLabels(leftKeys, g2, plotArea, linkArea, labelWidth,\r\n state);\r\n drawRightLabels(rightKeys, g2, plotArea, linkArea, labelWidth,\r\n state);\r\n }\r\n g2.setComposite(originalComposite);\r\n\r\n }\r\n\r\n /**\r\n * Draws the left labels.\r\n *\r\n * @param leftKeys a collection of keys and angles (to the middle of the\r\n * section, in degrees) for the sections on the left side of the\r\n * plot.\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param linkArea the link area.\r\n * @param maxLabelWidth the maximum label width.\r\n * @param state the state.\r\n */\r\n protected void drawLeftLabels(KeyedValues leftKeys, Graphics2D g2,\r\n Rectangle2D plotArea, Rectangle2D linkArea,\r\n float maxLabelWidth, PiePlotState state) {\r\n\r\n this.labelDistributor.clear();\r\n double lGap = plotArea.getWidth() * this.labelGap;\r\n double verticalLinkRadius = state.getLinkArea().getHeight() / 2.0;\r\n for (int i = 0; i < leftKeys.getItemCount(); i++) {\r\n String label = this.labelGenerator.generateSectionLabel(\r\n this.dataset, leftKeys.getKey(i));\r\n if (label != null) {\r\n TextBlock block = TextUtilities.createTextBlock(label,\r\n this.labelFont, this.labelPaint, maxLabelWidth,\r\n new G2TextMeasurer(g2));\r\n TextBox labelBox = new TextBox(block);\r\n labelBox.setBackgroundPaint(this.labelBackgroundPaint);\r\n labelBox.setOutlinePaint(this.labelOutlinePaint);\r\n labelBox.setOutlineStroke(this.labelOutlineStroke);\r\n if (this.shadowGenerator == null) {\r\n labelBox.setShadowPaint(this.labelShadowPaint);\r\n }\r\n else {\r\n labelBox.setShadowPaint(null);\r\n }\r\n labelBox.setInteriorGap(this.labelPadding);\r\n double theta = Math.toRadians(\r\n leftKeys.getValue(i).doubleValue());\r\n double baseY = state.getPieCenterY() - Math.sin(theta)\r\n * verticalLinkRadius;\r\n double hh = labelBox.getHeight(g2);\r\n\r\n this.labelDistributor.addPieLabelRecord(new PieLabelRecord(\r\n leftKeys.getKey(i), theta, baseY, labelBox, hh,\r\n lGap / 2.0 + lGap / 2.0 * -Math.cos(theta), 1.0\r\n - getLabelLinkDepth()\r\n + getExplodePercent(leftKeys.getKey(i))));\r\n }\r\n }\r\n double hh = plotArea.getHeight();\r\n double gap = hh * getInteriorGap();\r\n this.labelDistributor.distributeLabels(plotArea.getMinY() + gap,\r\n hh - 2 * gap);\r\n for (int i = 0; i < this.labelDistributor.getItemCount(); i++) {\r\n drawLeftLabel(g2, state,\r\n this.labelDistributor.getPieLabelRecord(i));\r\n }\r\n }\r\n\r\n /**\r\n * Draws the right labels.\r\n *\r\n * @param keys the keys.\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param linkArea the link area.\r\n * @param maxLabelWidth the maximum label width.\r\n * @param state the state.\r\n */\r\n protected void drawRightLabels(KeyedValues keys, Graphics2D g2,\r\n Rectangle2D plotArea, Rectangle2D linkArea,\r\n float maxLabelWidth, PiePlotState state) {\r\n\r\n // draw the right labels...\r\n this.labelDistributor.clear();\r\n double lGap = plotArea.getWidth() * this.labelGap;\r\n double verticalLinkRadius = state.getLinkArea().getHeight() / 2.0;\r\n\r\n for (int i = 0; i < keys.getItemCount(); i++) {\r\n String label = this.labelGenerator.generateSectionLabel(\r\n this.dataset, keys.getKey(i));\r\n\r\n if (label != null) {\r\n TextBlock block = TextUtilities.createTextBlock(label,\r\n this.labelFont, this.labelPaint, maxLabelWidth,\r\n new G2TextMeasurer(g2));\r\n TextBox labelBox = new TextBox(block);\r\n labelBox.setBackgroundPaint(this.labelBackgroundPaint);\r\n labelBox.setOutlinePaint(this.labelOutlinePaint);\r\n labelBox.setOutlineStroke(this.labelOutlineStroke);\r\n if (this.shadowGenerator == null) {\r\n labelBox.setShadowPaint(this.labelShadowPaint);\r\n }\r\n else {\r\n labelBox.setShadowPaint(null);\r\n }\r\n labelBox.setInteriorGap(this.labelPadding);\r\n double theta = Math.toRadians(keys.getValue(i).doubleValue());\r\n double baseY = state.getPieCenterY()\r\n - Math.sin(theta) * verticalLinkRadius;\r\n double hh = labelBox.getHeight(g2);\r\n this.labelDistributor.addPieLabelRecord(new PieLabelRecord(\r\n keys.getKey(i), theta, baseY, labelBox, hh,\r\n lGap / 2.0 + lGap / 2.0 * Math.cos(theta),\r\n 1.0 - getLabelLinkDepth()\r\n + getExplodePercent(keys.getKey(i))));\r\n }\r\n }\r\n double hh = plotArea.getHeight();\r\n double gap = 0.00; //hh * getInteriorGap();\r\n this.labelDistributor.distributeLabels(plotArea.getMinY() + gap,\r\n hh - 2 * gap);\r\n for (int i = 0; i < this.labelDistributor.getItemCount(); i++) {\r\n drawRightLabel(g2, state,\r\n this.labelDistributor.getPieLabelRecord(i));\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns a collection of legend items for the pie chart.\r\n *\r\n * @return The legend items (never <code>null</code>).\r\n */\r\n @Override\r\n public LegendItemCollection getLegendItems() {\r\n\r\n LegendItemCollection result = new LegendItemCollection();\r\n if (this.dataset == null) {\r\n return result;\r\n }\r\n List keys = this.dataset.getKeys();\r\n int section = 0;\r\n Shape shape = getLegendItemShape();\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable key = (Comparable) iterator.next();\r\n Number n = this.dataset.getValue(key);\r\n boolean include;\r\n if (n == null) {\r\n include = !this.ignoreNullValues;\r\n }\r\n else {\r\n double v = n.doubleValue();\r\n if (v == 0.0) {\r\n include = !this.ignoreZeroValues;\r\n }\r\n else {\r\n include = v > 0.0;\r\n }\r\n }\r\n if (include) {\r\n String label = this.legendLabelGenerator.generateSectionLabel(\r\n this.dataset, key);\r\n if (label != null) {\r\n String description = label;\r\n String toolTipText = null;\r\n if (this.legendLabelToolTipGenerator != null) {\r\n toolTipText = this.legendLabelToolTipGenerator\r\n .generateSectionLabel(this.dataset, key);\r\n }\r\n String urlText = null;\r\n if (this.legendLabelURLGenerator != null) {\r\n urlText = this.legendLabelURLGenerator.generateURL(\r\n this.dataset, key, this.pieIndex);\r\n }\r\n Paint paint = lookupSectionPaint(key);\r\n Paint outlinePaint = lookupSectionOutlinePaint(key);\r\n Stroke outlineStroke = lookupSectionOutlineStroke(key);\r\n LegendItem item = new LegendItem(label, description,\r\n toolTipText, urlText, true, shape, true, paint,\r\n true, outlinePaint, outlineStroke,\r\n false, // line not visible\r\n new Line2D.Float(), new BasicStroke(), Color.black);\r\n item.setDataset(getDataset());\r\n item.setSeriesIndex(this.dataset.getIndex(key));\r\n item.setSeriesKey(key);\r\n result.add(item);\r\n }\r\n section++;\r\n }\r\n else {\r\n section++;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a short string describing the type of plot.\r\n *\r\n * @return The plot type.\r\n */\r\n @Override\r\n public String getPlotType() {\r\n return localizationResources.getString(\"Pie_Plot\");\r\n }\r\n\r\n /**\r\n * Returns a rectangle that can be used to create a pie section (taking\r\n * into account the amount by which the pie section is 'exploded').\r\n *\r\n * @param unexploded the area inside which the unexploded pie sections are\r\n * drawn.\r\n * @param exploded the area inside which the exploded pie sections are\r\n * drawn.\r\n * @param angle the start angle.\r\n * @param extent the extent of the arc.\r\n * @param explodePercent the amount by which the pie section is exploded.\r\n *\r\n * @return A rectangle that can be used to create a pie section.\r\n */\r\n protected Rectangle2D getArcBounds(Rectangle2D unexploded,\r\n Rectangle2D exploded,\r\n double angle, double extent,\r\n double explodePercent) {\r\n\r\n if (explodePercent == 0.0) {\r\n return unexploded;\r\n }\r\n Arc2D arc1 = new Arc2D.Double(unexploded, angle, extent / 2,\r\n Arc2D.OPEN);\r\n Point2D point1 = arc1.getEndPoint();\r\n Arc2D.Double arc2 = new Arc2D.Double(exploded, angle, extent / 2,\r\n Arc2D.OPEN);\r\n Point2D point2 = arc2.getEndPoint();\r\n double deltaX = (point1.getX() - point2.getX()) * explodePercent;\r\n double deltaY = (point1.getY() - point2.getY()) * explodePercent;\r\n return new Rectangle2D.Double(unexploded.getX() - deltaX,\r\n unexploded.getY() - deltaY, unexploded.getWidth(),\r\n unexploded.getHeight());\r\n }\r\n\r\n /**\r\n * Draws a section label on the left side of the pie chart.\r\n *\r\n * @param g2 the graphics device.\r\n * @param state the state.\r\n * @param record the label record.\r\n */\r\n protected void drawLeftLabel(Graphics2D g2, PiePlotState state,\r\n PieLabelRecord record) {\r\n\r\n double anchorX = state.getLinkArea().getMinX();\r\n double targetX = anchorX - record.getGap();\r\n double targetY = record.getAllocatedY();\r\n\r\n if (this.labelLinksVisible) {\r\n double theta = record.getAngle();\r\n double linkX = state.getPieCenterX() + Math.cos(theta)\r\n * state.getPieWRadius() * record.getLinkPercent();\r\n double linkY = state.getPieCenterY() - Math.sin(theta)\r\n * state.getPieHRadius() * record.getLinkPercent();\r\n double elbowX = state.getPieCenterX() + Math.cos(theta)\r\n * state.getLinkArea().getWidth() / 2.0;\r\n double elbowY = state.getPieCenterY() - Math.sin(theta)\r\n * state.getLinkArea().getHeight() / 2.0;\r\n double anchorY = elbowY;\r\n g2.setPaint(this.labelLinkPaint);\r\n g2.setStroke(this.labelLinkStroke);\r\n PieLabelLinkStyle style = getLabelLinkStyle();\r\n if (style.equals(PieLabelLinkStyle.STANDARD)) {\r\n g2.draw(new Line2D.Double(linkX, linkY, elbowX, elbowY));\r\n g2.draw(new Line2D.Double(anchorX, anchorY, elbowX, elbowY));\r\n g2.draw(new Line2D.Double(anchorX, anchorY, targetX, targetY));\r\n }\r\n else if (style.equals(PieLabelLinkStyle.QUAD_CURVE)) {\r\n QuadCurve2D q = new QuadCurve2D.Float();\r\n q.setCurve(targetX, targetY, anchorX, anchorY, elbowX, elbowY);\r\n g2.draw(q);\r\n g2.draw(new Line2D.Double(elbowX, elbowY, linkX, linkY));\r\n }\r\n else if (style.equals(PieLabelLinkStyle.CUBIC_CURVE)) {\r\n CubicCurve2D c = new CubicCurve2D .Float();\r\n c.setCurve(targetX, targetY, anchorX, anchorY, elbowX, elbowY,\r\n linkX, linkY);\r\n g2.draw(c);\r\n }\r\n }\r\n TextBox tb = record.getLabel();\r\n tb.draw(g2, (float) targetX, (float) targetY, RectangleAnchor.RIGHT);\r\n\r\n }\r\n\r\n /**\r\n * Draws a section label on the right side of the pie chart.\r\n *\r\n * @param g2 the graphics device.\r\n * @param state the state.\r\n * @param record the label record.\r\n */\r\n protected void drawRightLabel(Graphics2D g2, PiePlotState state,\r\n PieLabelRecord record) {\r\n\r\n double anchorX = state.getLinkArea().getMaxX();\r\n double targetX = anchorX + record.getGap();\r\n double targetY = record.getAllocatedY();\r\n\r\n if (this.labelLinksVisible) {\r\n double theta = record.getAngle();\r\n double linkX = state.getPieCenterX() + Math.cos(theta)\r\n * state.getPieWRadius() * record.getLinkPercent();\r\n double linkY = state.getPieCenterY() - Math.sin(theta)\r\n * state.getPieHRadius() * record.getLinkPercent();\r\n double elbowX = state.getPieCenterX() + Math.cos(theta)\r\n * state.getLinkArea().getWidth() / 2.0;\r\n double elbowY = state.getPieCenterY() - Math.sin(theta)\r\n * state.getLinkArea().getHeight() / 2.0;\r\n double anchorY = elbowY;\r\n g2.setPaint(this.labelLinkPaint);\r\n g2.setStroke(this.labelLinkStroke);\r\n PieLabelLinkStyle style = getLabelLinkStyle();\r\n if (style.equals(PieLabelLinkStyle.STANDARD)) {\r\n g2.draw(new Line2D.Double(linkX, linkY, elbowX, elbowY));\r\n g2.draw(new Line2D.Double(anchorX, anchorY, elbowX, elbowY));\r\n g2.draw(new Line2D.Double(anchorX, anchorY, targetX, targetY));\r\n }\r\n else if (style.equals(PieLabelLinkStyle.QUAD_CURVE)) {\r\n QuadCurve2D q = new QuadCurve2D.Float();\r\n q.setCurve(targetX, targetY, anchorX, anchorY, elbowX, elbowY);\r\n g2.draw(q);\r\n g2.draw(new Line2D.Double(elbowX, elbowY, linkX, linkY));\r\n }\r\n else if (style.equals(PieLabelLinkStyle.CUBIC_CURVE)) {\r\n CubicCurve2D c = new CubicCurve2D .Float();\r\n c.setCurve(targetX, targetY, anchorX, anchorY, elbowX, elbowY,\r\n linkX, linkY);\r\n g2.draw(c);\r\n }\r\n }\r\n\r\n TextBox tb = record.getLabel();\r\n tb.draw(g2, (float) targetX, (float) targetY, RectangleAnchor.LEFT);\r\n\r\n }\r\n\r\n /**\r\n * Returns the center for the specified section.\r\n * Checks to see if the section is exploded and recalculates the\r\n * new center if so.\r\n *\r\n * @param state PiePlotState\r\n * @param key section key.\r\n *\r\n * @return The center for the specified section.\r\n *\r\n * @since 1.0.14\r\n */\r\n protected Point2D getArcCenter(PiePlotState state, Comparable key) {\r\n Point2D center = new Point2D.Double(state.getPieCenterX(), state\r\n .getPieCenterY());\r\n\r\n double ep = getExplodePercent(key);\r\n double mep = getMaximumExplodePercent();\r\n if (mep > 0.0) {\r\n ep = ep / mep;\r\n }\r\n if (ep != 0) {\r\n Rectangle2D pieArea = state.getPieArea();\r\n Rectangle2D expPieArea = state.getExplodedPieArea();\r\n double angle1, angle2;\r\n Number n = this.dataset.getValue(key);\r\n double value = n.doubleValue();\r\n\r\n if (this.direction == Rotation.CLOCKWISE) {\r\n angle1 = state.getLatestAngle();\r\n angle2 = angle1 - value / state.getTotal() * 360.0;\r\n } else if (this.direction == Rotation.ANTICLOCKWISE) {\r\n angle1 = state.getLatestAngle();\r\n angle2 = angle1 + value / state.getTotal() * 360.0;\r\n } else {\r\n throw new IllegalStateException(\"Rotation type not recognised.\");\r\n }\r\n double angle = (angle2 - angle1);\r\n\r\n Arc2D arc1 = new Arc2D.Double(pieArea, angle1, angle / 2,\r\n Arc2D.OPEN);\r\n Point2D point1 = arc1.getEndPoint();\r\n Arc2D.Double arc2 = new Arc2D.Double(expPieArea, angle1, angle / 2,\r\n Arc2D.OPEN);\r\n Point2D point2 = arc2.getEndPoint();\r\n double deltaX = (point1.getX() - point2.getX()) * ep;\r\n double deltaY = (point1.getY() - point2.getY()) * ep;\r\n\r\n center = new Point2D.Double(state.getPieCenterX() - deltaX,\r\n state.getPieCenterY() - deltaY);\r\n\r\n }\r\n return center;\r\n }\r\n\r\n /**\r\n * Returns the paint for the specified section. This is equivalent to\r\n * <code>lookupSectionPaint(section)</code>.\r\n * Checks to see if the user set the Paint to be of type RadialGradientPaint\r\n * If so it adjusts the center and radius to match the Pie\r\n *\r\n * @param key the section key.\r\n * @param state PiePlotState.\r\n *\r\n * @return The paint for the specified section.\r\n *\r\n * @since 1.0.14\r\n */\r\n protected Paint lookupSectionPaint(Comparable key, PiePlotState state) {\r\n Paint paint = lookupSectionPaint(key, getAutoPopulateSectionPaint());\r\n // for a RadialGradientPaint we adjust the center and radius to match\r\n // the current pie segment...\r\n if (paint instanceof RadialGradientPaint) {\r\n RadialGradientPaint rgp = (RadialGradientPaint) paint;\r\n Point2D center = getArcCenter(state, key);\r\n float radius = (float) Math.max(state.getPieHRadius(), \r\n state.getPieWRadius());\r\n float[] fractions = rgp.getFractions();\r\n Color[] colors = rgp.getColors();\r\n paint = new RadialGradientPaint(center, radius, fractions, colors);\r\n }\r\n return paint;\r\n }\r\n\r\n /**\r\n * Tests this plot for equality with an arbitrary object. Note that the\r\n * plot's dataset is NOT included in the test for equality.\r\n *\r\n * @param obj the object to test against (<code>null</code> permitted).\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof PiePlot)) {\r\n return false;\r\n }\r\n if (!super.equals(obj)) {\r\n return false;\r\n }\r\n PiePlot that = (PiePlot) obj;\r\n if (this.pieIndex != that.pieIndex) {\r\n return false;\r\n }\r\n if (this.interiorGap != that.interiorGap) {\r\n return false;\r\n }\r\n if (this.circular != that.circular) {\r\n return false;\r\n }\r\n if (this.startAngle != that.startAngle) {\r\n return false;\r\n }\r\n if (this.direction != that.direction) {\r\n return false;\r\n }\r\n if (this.ignoreZeroValues != that.ignoreZeroValues) {\r\n return false;\r\n }\r\n if (this.ignoreNullValues != that.ignoreNullValues) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.sectionPaint, that.sectionPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.sectionPaintMap,\r\n that.sectionPaintMap)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.baseSectionPaint,\r\n that.baseSectionPaint)) {\r\n return false;\r\n }\r\n if (this.sectionOutlinesVisible != that.sectionOutlinesVisible) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.sectionOutlinePaint,\r\n that.sectionOutlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.sectionOutlinePaintMap,\r\n that.sectionOutlinePaintMap)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.baseSectionOutlinePaint,\r\n that.baseSectionOutlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.sectionOutlineStroke,\r\n that.sectionOutlineStroke)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.sectionOutlineStrokeMap,\r\n that.sectionOutlineStrokeMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.baseSectionOutlineStroke,\r\n that.baseSectionOutlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.shadowPaint, that.shadowPaint)) {\r\n return false;\r\n }\r\n if (!(this.shadowXOffset == that.shadowXOffset)) {\r\n return false;\r\n }\r\n if (!(this.shadowYOffset == that.shadowYOffset)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.explodePercentages,\r\n that.explodePercentages)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.labelGenerator,\r\n that.labelGenerator)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.labelFont, that.labelFont)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.labelPaint, that.labelPaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.labelBackgroundPaint,\r\n that.labelBackgroundPaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.labelOutlinePaint,\r\n that.labelOutlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.labelOutlineStroke,\r\n that.labelOutlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.labelShadowPaint,\r\n that.labelShadowPaint)) {\r\n return false;\r\n }\r\n if (this.simpleLabels != that.simpleLabels) {\r\n return false;\r\n }\r\n if (!this.simpleLabelOffset.equals(that.simpleLabelOffset)) {\r\n return false;\r\n }\r\n if (!this.labelPadding.equals(that.labelPadding)) {\r\n return false;\r\n }\r\n if (!(this.maximumLabelWidth == that.maximumLabelWidth)) {\r\n return false;\r\n }\r\n if (!(this.labelGap == that.labelGap)) {\r\n return false;\r\n }\r\n if (!(this.labelLinkMargin == that.labelLinkMargin)) {\r\n return false;\r\n }\r\n if (this.labelLinksVisible != that.labelLinksVisible) {\r\n return false;\r\n }\r\n if (!this.labelLinkStyle.equals(that.labelLinkStyle)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.labelLinkPaint, that.labelLinkPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.labelLinkStroke,\r\n that.labelLinkStroke)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.toolTipGenerator,\r\n that.toolTipGenerator)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.urlGenerator, that.urlGenerator)) {\r\n return false;\r\n }\r\n if (!(this.minimumArcAngleToDraw == that.minimumArcAngleToDraw)) {\r\n return false;\r\n }\r\n if (!ShapeUtilities.equal(this.legendItemShape, that.legendItemShape)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.legendLabelGenerator,\r\n that.legendLabelGenerator)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.legendLabelToolTipGenerator,\r\n that.legendLabelToolTipGenerator)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.legendLabelURLGenerator,\r\n that.legendLabelURLGenerator)) {\r\n return false;\r\n }\r\n if (this.autoPopulateSectionPaint != that.autoPopulateSectionPaint) {\r\n return false;\r\n }\r\n if (this.autoPopulateSectionOutlinePaint\r\n != that.autoPopulateSectionOutlinePaint) {\r\n return false;\r\n }\r\n if (this.autoPopulateSectionOutlineStroke\r\n != that.autoPopulateSectionOutlineStroke) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.shadowGenerator,\r\n that.shadowGenerator)) {\r\n return false;\r\n }\r\n // can't find any difference...\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a clone of the plot.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if some component of the plot does\r\n * not support cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n PiePlot clone = (PiePlot) super.clone();\r\n clone.sectionPaintMap = (PaintMap) this.sectionPaintMap.clone();\r\n clone.sectionOutlinePaintMap \r\n = (PaintMap) this.sectionOutlinePaintMap.clone();\r\n clone.sectionOutlineStrokeMap \r\n = (StrokeMap) this.sectionOutlineStrokeMap.clone();\r\n clone.explodePercentages \r\n = new TreeMap<Comparable<?>, Number>(this.explodePercentages);\r\n if (this.labelGenerator != null) {\r\n clone.labelGenerator = (PieSectionLabelGenerator) \r\n ObjectUtilities.clone(this.labelGenerator);\r\n }\r\n if (clone.dataset != null) {\r\n clone.dataset.addChangeListener(clone);\r\n }\r\n if (this.urlGenerator instanceof PublicCloneable) {\r\n clone.urlGenerator = (PieURLGenerator) ObjectUtilities.clone(\r\n this.urlGenerator);\r\n }\r\n clone.legendItemShape = ShapeUtilities.clone(this.legendItemShape);\r\n if (this.legendLabelGenerator != null) {\r\n clone.legendLabelGenerator = (PieSectionLabelGenerator)\r\n ObjectUtilities.clone(this.legendLabelGenerator);\r\n }\r\n if (this.legendLabelToolTipGenerator != null) {\r\n clone.legendLabelToolTipGenerator = (PieSectionLabelGenerator)\r\n ObjectUtilities.clone(this.legendLabelToolTipGenerator);\r\n }\r\n if (this.legendLabelURLGenerator instanceof PublicCloneable) {\r\n clone.legendLabelURLGenerator = (PieURLGenerator)\r\n ObjectUtilities.clone(this.legendLabelURLGenerator);\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writePaint(this.sectionPaint, stream);\r\n SerialUtilities.writePaint(this.baseSectionPaint, stream);\r\n SerialUtilities.writePaint(this.sectionOutlinePaint, stream);\r\n SerialUtilities.writePaint(this.baseSectionOutlinePaint, stream);\r\n SerialUtilities.writeStroke(this.sectionOutlineStroke, stream);\r\n SerialUtilities.writeStroke(this.baseSectionOutlineStroke, stream);\r\n SerialUtilities.writePaint(this.shadowPaint, stream);\r\n SerialUtilities.writePaint(this.labelPaint, stream);\r\n SerialUtilities.writePaint(this.labelBackgroundPaint, stream);\r\n SerialUtilities.writePaint(this.labelOutlinePaint, stream);\r\n SerialUtilities.writeStroke(this.labelOutlineStroke, stream);\r\n SerialUtilities.writePaint(this.labelShadowPaint, stream);\r\n SerialUtilities.writePaint(this.labelLinkPaint, stream);\r\n SerialUtilities.writeStroke(this.labelLinkStroke, stream);\r\n SerialUtilities.writeShape(this.legendItemShape, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.sectionPaint = SerialUtilities.readPaint(stream);\r\n this.baseSectionPaint = SerialUtilities.readPaint(stream);\r\n this.sectionOutlinePaint = SerialUtilities.readPaint(stream);\r\n this.baseSectionOutlinePaint = SerialUtilities.readPaint(stream);\r\n this.sectionOutlineStroke = SerialUtilities.readStroke(stream);\r\n this.baseSectionOutlineStroke = SerialUtilities.readStroke(stream);\r\n this.shadowPaint = SerialUtilities.readPaint(stream);\r\n this.labelPaint = SerialUtilities.readPaint(stream);\r\n this.labelBackgroundPaint = SerialUtilities.readPaint(stream);\r\n this.labelOutlinePaint = SerialUtilities.readPaint(stream);\r\n this.labelOutlineStroke = SerialUtilities.readStroke(stream);\r\n this.labelShadowPaint = SerialUtilities.readPaint(stream);\r\n this.labelLinkPaint = SerialUtilities.readPaint(stream);\r\n this.labelLinkStroke = SerialUtilities.readStroke(stream);\r\n this.legendItemShape = SerialUtilities.readShape(stream);\r\n }\r\n\r\n // DEPRECATED FIELDS AND METHODS...\r\n\r\n /**\r\n * The paint for ALL sections (overrides list).\r\n *\r\n * @deprecated This field is redundant, it is sufficient to use\r\n * sectionPaintMap and baseSectionPaint. Deprecated as of version\r\n * 1.0.6.\r\n */\r\n private transient Paint sectionPaint;\r\n\r\n /**\r\n * The outline paint for ALL sections (overrides list).\r\n *\r\n * @deprecated This field is redundant, it is sufficient to use\r\n * sectionOutlinePaintMap and baseSectionOutlinePaint. Deprecated as\r\n * of version 1.0.6.\r\n */\r\n private transient Paint sectionOutlinePaint;\r\n\r\n /**\r\n * The outline stroke for ALL sections (overrides list).\r\n *\r\n * @deprecated This field is redundant, it is sufficient to use\r\n * sectionOutlineStrokeMap and baseSectionOutlineStroke. Deprecated as\r\n * of version 1.0.6.\r\n */\r\n private transient Stroke sectionOutlineStroke;\r\n\r\n /**\r\n * Returns the paint for the specified section.\r\n *\r\n * @param section the section index (zero-based).\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @deprecated Use {@link #getSectionPaint(Comparable)} instead.\r\n */\r\n public Paint getSectionPaint(int section) {\r\n Comparable key = getSectionKey(section);\r\n return getSectionPaint(key);\r\n }\r\n\r\n /**\r\n * Sets the paint used to fill a section of the pie and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param section the section index (zero-based).\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @deprecated Use {@link #setSectionPaint(Comparable, Paint)} instead.\r\n */\r\n public void setSectionPaint(int section, Paint paint) {\r\n Comparable key = getSectionKey(section);\r\n setSectionPaint(key, paint);\r\n }\r\n\r\n /**\r\n * Returns the outline paint for ALL sections in the plot.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setSectionOutlinePaint(Paint)\r\n *\r\n * @deprecated Use {@link #getSectionOutlinePaint(Comparable)} and\r\n * {@link #getBaseSectionOutlinePaint()}. Deprecated as of version\r\n * 1.0.6.\r\n */\r\n public Paint getSectionOutlinePaint() {\r\n return this.sectionOutlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the outline paint for ALL sections in the plot. If this is set to\r\n * {@code null}, then a list of paints is used instead (to allow\r\n * different colors to be used for each section).\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getSectionOutlinePaint()\r\n *\r\n * @deprecated Use {@link #setSectionOutlinePaint(Comparable, Paint)} and\r\n * {@link #setBaseSectionOutlinePaint(Paint)}. Deprecated as of\r\n * version 1.0.6.\r\n */\r\n public void setSectionOutlinePaint(Paint paint) {\r\n this.sectionOutlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the specified section.\r\n *\r\n * @param section the section index (zero-based).\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @deprecated Use {@link #getSectionOutlinePaint(Comparable)} instead.\r\n */\r\n public Paint getSectionOutlinePaint(int section) {\r\n Comparable key = getSectionKey(section);\r\n return getSectionOutlinePaint(key);\r\n }\r\n\r\n /**\r\n * Sets the paint used to fill a section of the pie and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param section the section index (zero-based).\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @deprecated Use {@link #setSectionOutlinePaint(Comparable, Paint)}\r\n * instead.\r\n */\r\n public void setSectionOutlinePaint(int section, Paint paint) {\r\n Comparable key = getSectionKey(section);\r\n setSectionOutlinePaint(key, paint);\r\n }\r\n\r\n /**\r\n * Returns the outline stroke for ALL sections in the plot.\r\n *\r\n * @return The stroke (possibly <code>null</code>).\r\n *\r\n * @see #setSectionOutlineStroke(Stroke)\r\n *\r\n * @deprecated Use {@link #getSectionOutlineStroke(Comparable)} and\r\n * {@link #getBaseSectionOutlineStroke()}. Deprecated as of version\r\n * 1.0.6.\r\n */\r\n public Stroke getSectionOutlineStroke() {\r\n return this.sectionOutlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the outline stroke for ALL sections in the plot. If this is set to\r\n * {@code null}, then a list of paints is used instead (to allow\r\n * different colors to be used for each section).\r\n *\r\n * @param stroke the stroke (<code>null</code> permitted).\r\n *\r\n * @see #getSectionOutlineStroke()\r\n *\r\n * @deprecated Use {@link #setSectionOutlineStroke(Comparable, Stroke)} and\r\n * {@link #setBaseSectionOutlineStroke(Stroke)}. Deprecated as of\r\n * version 1.0.6.\r\n */\r\n public void setSectionOutlineStroke(Stroke stroke) {\r\n this.sectionOutlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke for the specified section.\r\n *\r\n * @param section the section index (zero-based).\r\n *\r\n * @return The stroke (possibly <code>null</code>).\r\n *\r\n * @deprecated Use {@link #getSectionOutlineStroke(Comparable)} instead.\r\n */\r\n public Stroke getSectionOutlineStroke(int section) {\r\n Comparable key = getSectionKey(section);\r\n return getSectionOutlineStroke(key);\r\n }\r\n\r\n /**\r\n * Sets the stroke used to fill a section of the pie and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param section the section index (zero-based).\r\n * @param stroke the stroke (<code>null</code> permitted).\r\n *\r\n * @deprecated Use {@link #setSectionOutlineStroke(Comparable, Stroke)}\r\n * instead.\r\n */\r\n public void setSectionOutlineStroke(int section, Stroke stroke) {\r\n Comparable key = getSectionKey(section);\r\n setSectionOutlineStroke(key, stroke);\r\n }\r\n\r\n /**\r\n * Returns the amount that a section should be 'exploded'.\r\n *\r\n * @param section the section number.\r\n *\r\n * @return The amount that a section should be 'exploded'.\r\n *\r\n * @deprecated Use {@link #getExplodePercent(Comparable)} instead.\r\n */\r\n public double getExplodePercent(int section) {\r\n Comparable key = getSectionKey(section);\r\n return getExplodePercent(key);\r\n }\r\n\r\n /**\r\n * Sets the amount that a pie section should be exploded and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param section the section index.\r\n * @param percent the explode percentage (0.30 = 30 percent).\r\n *\r\n * @deprecated Use {@link #setExplodePercent(Comparable, double)} instead.\r\n */\r\n public void setExplodePercent(int section, double percent) {\r\n Comparable key = getSectionKey(section);\r\n setExplodePercent(key, percent);\r\n }\r\n\r\n}\r" }, { "identifier": "DefaultPieDataset", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/general/DefaultPieDataset.java", "snippet": "public class DefaultPieDataset extends AbstractDataset\r\n implements PieDataset, Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 2904745139106540618L;\r\n\r\n /** Storage for the data. */\r\n private DefaultKeyedValues data;\r\n\r\n /**\r\n * Constructs a new dataset, initially empty.\r\n */\r\n public DefaultPieDataset() {\r\n this.data = new DefaultKeyedValues();\r\n }\r\n\r\n /**\r\n * Creates a new dataset by copying data from a {@link KeyedValues}\r\n * instance.\r\n *\r\n * @param data the data (<code>null</code> not permitted).\r\n */\r\n public DefaultPieDataset(KeyedValues data) {\r\n ParamChecks.nullNotPermitted(data, \"data\");\r\n this.data = new DefaultKeyedValues();\r\n for (int i = 0; i < data.getItemCount(); i++) {\r\n this.data.addValue(data.getKey(i), data.getValue(i));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the number of items in the dataset.\r\n *\r\n * @return The item count.\r\n */\r\n @Override\r\n public int getItemCount() {\r\n return this.data.getItemCount();\r\n }\r\n\r\n /**\r\n * Returns the categories in the dataset. The returned list is\r\n * unmodifiable.\r\n *\r\n * @return The categories in the dataset.\r\n */\r\n @Override\r\n public List getKeys() {\r\n return Collections.unmodifiableList(this.data.getKeys());\r\n }\r\n\r\n /**\r\n * Returns the key for the specified item, or <code>null</code>.\r\n *\r\n * @param item the item index (in the range <code>0</code> to\r\n * <code>getItemCount() - 1</code>).\r\n *\r\n * @return The key, or <code>null</code>.\r\n *\r\n * @throws IndexOutOfBoundsException if <code>item</code> is not in the\r\n * specified range.\r\n */\r\n @Override\r\n public Comparable getKey(int item) {\r\n return this.data.getKey(item);\r\n }\r\n\r\n /**\r\n * Returns the index for a key, or -1 if the key is not recognised.\r\n *\r\n * @param key the key (<code>null</code> not permitted).\r\n *\r\n * @return The index, or <code>-1</code> if the key is unrecognised.\r\n *\r\n * @throws IllegalArgumentException if <code>key</code> is\r\n * <code>null</code>.\r\n */\r\n @Override\r\n public int getIndex(Comparable key) {\r\n return this.data.getIndex(key);\r\n }\r\n\r\n /**\r\n * Returns a value.\r\n *\r\n * @param item the value index.\r\n *\r\n * @return The value (possibly <code>null</code>).\r\n */\r\n @Override\r\n public Number getValue(int item) {\r\n Number result = null;\r\n if (getItemCount() > item) {\r\n result = this.data.getValue(item);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the data value associated with a key.\r\n *\r\n * @param key the key (<code>null</code> not permitted).\r\n *\r\n * @return The value (possibly <code>null</code>).\r\n *\r\n * @throws UnknownKeyException if the key is not recognised.\r\n */\r\n @Override\r\n public Number getValue(Comparable key) {\r\n ParamChecks.nullNotPermitted(key, \"key\");\r\n return this.data.getValue(key);\r\n }\r\n\r\n /**\r\n * Sets the data value for a key and sends a {@link DatasetChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param key the key (<code>null</code> not permitted).\r\n * @param value the value.\r\n *\r\n * @throws IllegalArgumentException if <code>key</code> is\r\n * <code>null</code>.\r\n */\r\n public void setValue(Comparable key, Number value) {\r\n this.data.setValue(key, value);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Sets the data value for a key and sends a {@link DatasetChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param key the key (<code>null</code> not permitted).\r\n * @param value the value.\r\n *\r\n * @throws IllegalArgumentException if <code>key</code> is\r\n * <code>null</code>.\r\n */\r\n public void setValue(Comparable key, double value) {\r\n setValue(key, new Double(value));\r\n }\r\n\r\n /**\r\n * Inserts a new value at the specified position in the dataset or, if\r\n * there is an existing item with the specified key, updates the value\r\n * for that item and moves it to the specified position. After the change\r\n * is made, this methods sends a {@link DatasetChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param position the position (in the range 0 to getItemCount()).\r\n * @param key the key (<code>null</code> not permitted).\r\n * @param value the value (<code>null</code> permitted).\r\n *\r\n * @since 1.0.6\r\n */\r\n public void insertValue(int position, Comparable key, double value) {\r\n insertValue(position, key, new Double(value));\r\n }\r\n\r\n /**\r\n * Inserts a new value at the specified position in the dataset or, if\r\n * there is an existing item with the specified key, updates the value\r\n * for that item and moves it to the specified position. After the change\r\n * is made, this methods sends a {@link DatasetChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param position the position (in the range 0 to getItemCount()).\r\n * @param key the key (<code>null</code> not permitted).\r\n * @param value the value (<code>null</code> permitted).\r\n *\r\n * @since 1.0.6\r\n */\r\n public void insertValue(int position, Comparable key, Number value) {\r\n this.data.insertValue(position, key, value);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes an item from the dataset and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param key the key (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>key</code> is\r\n * <code>null</code>.\r\n */\r\n public void remove(Comparable key) {\r\n this.data.removeValue(key);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Clears all data from this dataset and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners (unless the dataset was already empty).\r\n *\r\n * @since 1.0.2\r\n */\r\n public void clear() {\r\n if (getItemCount() > 0) {\r\n this.data.clear();\r\n fireDatasetChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Sorts the dataset's items by key and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param order the sort order (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.3\r\n */\r\n public void sortByKeys(SortOrder order) {\r\n this.data.sortByKeys(order);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Sorts the dataset's items by value and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param order the sort order (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.3\r\n */\r\n public void sortByValues(SortOrder order) {\r\n this.data.sortByValues(order);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Tests if this object is equal to another.\r\n *\r\n * @param obj the other object.\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n\r\n if (!(obj instanceof PieDataset)) {\r\n return false;\r\n }\r\n PieDataset that = (PieDataset) obj;\r\n int count = getItemCount();\r\n if (that.getItemCount() != count) {\r\n return false;\r\n }\r\n\r\n for (int i = 0; i < count; i++) {\r\n Comparable k1 = getKey(i);\r\n Comparable k2 = that.getKey(i);\r\n if (!k1.equals(k2)) {\r\n return false;\r\n }\r\n\r\n Number v1 = getValue(i);\r\n Number v2 = that.getValue(i);\r\n if (v1 == null) {\r\n if (v2 != null) {\r\n return false;\r\n }\r\n }\r\n else {\r\n if (!v1.equals(v2)) {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n\r\n }\r\n\r\n /**\r\n * Returns a hash code.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n return this.data.hashCode();\r\n }\r\n\r\n /**\r\n * Returns a clone of the dataset.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException This class will not throw this\r\n * exception, but subclasses (if any) might.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n DefaultPieDataset clone = (DefaultPieDataset) super.clone();\r\n clone.data = (DefaultKeyedValues) this.data.clone();\r\n return clone;\r\n }\r\n\r\n}\r" }, { "identifier": "PieDataset", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/general/PieDataset.java", "snippet": "public interface PieDataset extends KeyedValues, Dataset {\r\n\r\n // no new methods added.\r\n\r\n}\r" }, { "identifier": "ChartComposite", "path": "lib/jfreechart-1.0.19/swt/org/jfree/experimental/chart/swt/ChartComposite.java", "snippet": "public class ChartComposite extends Composite implements ChartChangeListener,\n ChartProgressListener, PaintListener, SelectionListener,\n MouseListener, MouseMoveListener, Printable {\n\n /** Default setting for buffer usage. */\n public static final boolean DEFAULT_BUFFER_USED = false;\n\n /** The default panel width. */\n public static final int DEFAULT_WIDTH = 680;\n\n /** The default panel height. */\n public static final int DEFAULT_HEIGHT = 420;\n\n /** The default limit below which chart scaling kicks in. */\n public static final int DEFAULT_MINIMUM_DRAW_WIDTH = 300;\n\n /** The default limit below which chart scaling kicks in. */\n public static final int DEFAULT_MINIMUM_DRAW_HEIGHT = 200;\n\n /** The default limit below which chart scaling kicks in. */\n public static final int DEFAULT_MAXIMUM_DRAW_WIDTH = 800;\n\n /** The default limit below which chart scaling kicks in. */\n public static final int DEFAULT_MAXIMUM_DRAW_HEIGHT = 600;\n\n /** The minimum size required to perform a zoom on a rectangle */\n public static final int DEFAULT_ZOOM_TRIGGER_DISTANCE = 10;\n\n /** Properties action command. */\n public static final String PROPERTIES_COMMAND = \"PROPERTIES\";\n\n /** Save action command. */\n public static final String SAVE_COMMAND = \"SAVE\";\n\n /** Print action command. */\n public static final String PRINT_COMMAND = \"PRINT\";\n\n /** Zoom in (both axes) action command. */\n public static final String ZOOM_IN_BOTH_COMMAND = \"ZOOM_IN_BOTH\";\n\n /** Zoom in (domain axis only) action command. */\n public static final String ZOOM_IN_DOMAIN_COMMAND = \"ZOOM_IN_DOMAIN\";\n\n /** Zoom in (range axis only) action command. */\n public static final String ZOOM_IN_RANGE_COMMAND = \"ZOOM_IN_RANGE\";\n\n /** Zoom out (both axes) action command. */\n public static final String ZOOM_OUT_BOTH_COMMAND = \"ZOOM_OUT_BOTH\";\n\n /** Zoom out (domain axis only) action command. */\n public static final String ZOOM_OUT_DOMAIN_COMMAND = \"ZOOM_DOMAIN_BOTH\";\n\n /** Zoom out (range axis only) action command. */\n public static final String ZOOM_OUT_RANGE_COMMAND = \"ZOOM_RANGE_BOTH\";\n\n /** Zoom reset (both axes) action command. */\n public static final String ZOOM_RESET_BOTH_COMMAND = \"ZOOM_RESET_BOTH\";\n\n /** Zoom reset (domain axis only) action command. */\n public static final String ZOOM_RESET_DOMAIN_COMMAND = \"ZOOM_RESET_DOMAIN\";\n\n /** Zoom reset (range axis only) action command. */\n public static final String ZOOM_RESET_RANGE_COMMAND = \"ZOOM_RESET_RANGE\";\n\n /** The chart that is displayed in the panel. */\n private JFreeChart chart;\n\n /** The canvas to display the chart. */\n private Canvas canvas;\n\n /** Storage for registered (chart) mouse listeners. */\n private EventListenerList chartMouseListeners;\n\n /** A flag that controls whether or not the off-screen buffer is used. */\n private boolean useBuffer;\n\n /** A flag that indicates that the buffer should be refreshed. */\n private boolean refreshBuffer;\n\n /** A flag that indicates that the tooltips should be displayed. */\n private boolean displayToolTips;\n\n /** A buffer for the rendered chart. */\n private org.eclipse.swt.graphics.Image chartBuffer;\n\n /** The height of the chart buffer. */\n private int chartBufferHeight;\n\n /** The width of the chart buffer. */\n private int chartBufferWidth;\n\n /**\n * The minimum width for drawing a chart (uses scaling for smaller widths).\n */\n private int minimumDrawWidth;\n\n /**\n * The minimum height for drawing a chart (uses scaling for smaller\n * heights).\n */\n private int minimumDrawHeight;\n\n /**\n * The maximum width for drawing a chart (uses scaling for bigger\n * widths).\n */\n private int maximumDrawWidth;\n\n /**\n * The maximum height for drawing a chart (uses scaling for bigger\n * heights).\n */\n private int maximumDrawHeight;\n\n /** The popup menu for the frame. */\n private Menu popup;\n\n /** The drawing info collected the last time the chart was drawn. */\n private ChartRenderingInfo info;\n\n /** The chart anchor point. */\n private Point2D anchor;\n\n /** The scale factor used to draw the chart. */\n private double scaleX;\n\n /** The scale factor used to draw the chart. */\n private double scaleY;\n\n /** The plot orientation. */\n private PlotOrientation orientation = PlotOrientation.VERTICAL;\n\n /** A flag that controls whether or not domain zooming is enabled. */\n private boolean domainZoomable = false;\n\n /** A flag that controls whether or not range zooming is enabled. */\n private boolean rangeZoomable = false;\n\n /**\n * The zoom rectangle starting point (selected by the user with a mouse\n * click). This is a point on the screen, not the chart (which may have\n * been scaled up or down to fit the panel).\n */\n private org.eclipse.swt.graphics.Point zoomPoint = null;\n\n /** The zoom rectangle (selected by the user with the mouse). */\n private transient Rectangle zoomRectangle = null;\n\n /** Controls if the zoom rectangle is drawn as an outline or filled. */\n //TODO private boolean fillZoomRectangle = true;\n\n /** The minimum distance required to drag the mouse to trigger a zoom. */\n private int zoomTriggerDistance;\n\n /** A flag that controls whether or not horizontal tracing is enabled. */\n private boolean horizontalAxisTrace = false;\n\n /** A flag that controls whether or not vertical tracing is enabled. */\n private boolean verticalAxisTrace = false;\n\n /** A vertical trace line. */\n private transient int verticalTraceLineX;\n\n /** A horizontal trace line. */\n private transient int horizontalTraceLineY;\n\n /** Menu item for zooming in on a chart (both axes). */\n private MenuItem zoomInBothMenuItem;\n\n /** Menu item for zooming in on a chart (domain axis). */\n private MenuItem zoomInDomainMenuItem;\n\n /** Menu item for zooming in on a chart (range axis). */\n private MenuItem zoomInRangeMenuItem;\n\n /** Menu item for zooming out on a chart. */\n private MenuItem zoomOutBothMenuItem;\n\n /** Menu item for zooming out on a chart (domain axis). */\n private MenuItem zoomOutDomainMenuItem;\n\n /** Menu item for zooming out on a chart (range axis). */\n private MenuItem zoomOutRangeMenuItem;\n\n /** Menu item for resetting the zoom (both axes). */\n private MenuItem zoomResetBothMenuItem;\n\n /** Menu item for resetting the zoom (domain axis only). */\n private MenuItem zoomResetDomainMenuItem;\n\n /** Menu item for resetting the zoom (range axis only). */\n private MenuItem zoomResetRangeMenuItem;\n\n /** A flag that controls whether or not file extensions are enforced. */\n private boolean enforceFileExtensions;\n\n /** The factor used to zoom in on an axis range. */\n private double zoomInFactor = 0.5;\n\n /** The factor used to zoom out on an axis range. */\n private double zoomOutFactor = 2.0;\n\n /** The resourceBundle for the localization. */\n protected static ResourceBundle localizationResources\n = ResourceBundleWrapper.getBundle(\n \"org.jfree.chart.LocalizationBundle\");\n\n /**\n * Create a new chart composite with a default FillLayout.\n * This way, when drawn, the chart will fill all the space.\n * @param comp The parent.\n * @param style The style of the composite.\n */\n public ChartComposite(Composite comp, int style) {\n this(comp,\n style,\n null,\n DEFAULT_WIDTH,\n DEFAULT_HEIGHT,\n DEFAULT_MINIMUM_DRAW_WIDTH,\n DEFAULT_MINIMUM_DRAW_HEIGHT,\n DEFAULT_MAXIMUM_DRAW_WIDTH,\n DEFAULT_MAXIMUM_DRAW_HEIGHT,\n DEFAULT_BUFFER_USED,\n true, // properties\n true, // save\n true, // print\n true, // zoom\n true // tooltips\n );\n }\n\n /**\n * Constructs a panel that displays the specified chart.\n *\n * @param comp The parent.\n * @param style The style of the composite.\n * @param chart the chart.\n */\n public ChartComposite(Composite comp, int style, JFreeChart chart) {\n this(comp,\n style,\n chart,\n DEFAULT_WIDTH,\n DEFAULT_HEIGHT,\n DEFAULT_MINIMUM_DRAW_WIDTH,\n DEFAULT_MINIMUM_DRAW_HEIGHT,\n DEFAULT_MAXIMUM_DRAW_WIDTH,\n DEFAULT_MAXIMUM_DRAW_HEIGHT,\n DEFAULT_BUFFER_USED,\n true, // properties\n true, // save\n true, // print\n true, // zoom\n true // tooltips\n );\n }\n\n /**\n * Constructs a panel containing a chart.\n *\n * @param comp The parent.\n * @param style The style of the composite.\n * @param chart the chart.\n * @param useBuffer a flag controlling whether or not an off-screen buffer\n * is used.\n */\n public ChartComposite(Composite comp, int style, JFreeChart chart,\n boolean useBuffer) {\n\n this(comp, style, chart,\n DEFAULT_WIDTH,\n DEFAULT_HEIGHT,\n DEFAULT_MINIMUM_DRAW_WIDTH,\n DEFAULT_MINIMUM_DRAW_HEIGHT,\n DEFAULT_MAXIMUM_DRAW_WIDTH,\n DEFAULT_MAXIMUM_DRAW_HEIGHT,\n useBuffer,\n true, // properties\n true, // save\n true, // print\n true, // zoom\n true // tooltips\n );\n }\n\n /**\n * Constructs a JFreeChart panel.\n *\n * @param comp The parent.\n * @param style The style of the composite.\n * @param chart the chart.\n * @param properties a flag indicating whether or not the chart property\n * editor should be available via the popup menu.\n * @param save a flag indicating whether or not save options should be\n * available via the popup menu.\n * @param print a flag indicating whether or not the print option\n * should be available via the popup menu.\n * @param zoom a flag indicating whether or not zoom options should\n * be added to the popup menu.\n * @param tooltips a flag indicating whether or not tooltips should be\n * enabled for the chart.\n */\n public ChartComposite(\n Composite comp,\n int style,\n JFreeChart chart,\n boolean properties,\n boolean save,\n boolean print,\n boolean zoom,\n boolean tooltips) {\n this(\n comp,\n style,\n chart,\n DEFAULT_WIDTH,\n DEFAULT_HEIGHT,\n DEFAULT_MINIMUM_DRAW_WIDTH,\n DEFAULT_MINIMUM_DRAW_HEIGHT,\n DEFAULT_MAXIMUM_DRAW_WIDTH,\n DEFAULT_MAXIMUM_DRAW_HEIGHT,\n DEFAULT_BUFFER_USED,\n properties,\n save,\n print,\n zoom,\n tooltips\n );\n }\n\n /**\n * Constructs a JFreeChart panel.\n *\n * @param comp The parent.\n * @param style The style of the composite.\n * @param jfreechart the chart.\n * @param width the preferred width of the panel.\n * @param height the preferred height of the panel.\n * @param minimumDrawW the minimum drawing width.\n * @param minimumDrawH the minimum drawing height.\n * @param maximumDrawW the maximum drawing width.\n * @param maximumDrawH the maximum drawing height.\n * @param usingBuffer a flag that indicates whether to use the off-screen\n * buffer to improve performance (at the expense of\n * memory).\n * @param properties a flag indicating whether or not the chart property\n * editor should be available via the popup menu.\n * @param save a flag indicating whether or not save options should be\n * available via the popup menu.\n * @param print a flag indicating whether or not the print option\n * should be available via the popup menu.\n * @param zoom a flag indicating whether or not zoom options should be\n * added to the popup menu.\n * @param tooltips a flag indicating whether or not tooltips should be\n * enabled for the chart.\n */\n public ChartComposite(Composite comp,\n int style,\n JFreeChart jfreechart,\n int width,\n int height,\n int minimumDrawW,\n int minimumDrawH,\n int maximumDrawW,\n int maximumDrawH,\n boolean usingBuffer,\n boolean properties,\n boolean save,\n boolean print,\n boolean zoom,\n boolean tooltips) {\n super(comp, style);\n setChart(jfreechart);\n this.chartMouseListeners = new EventListenerList();\n setLayout(new FillLayout());\n this.info = new ChartRenderingInfo();\n this.useBuffer = usingBuffer;\n this.refreshBuffer = false;\n this.minimumDrawWidth = minimumDrawW;\n this.minimumDrawHeight = minimumDrawH;\n this.maximumDrawWidth = maximumDrawW;\n this.maximumDrawHeight = maximumDrawH;\n this.zoomTriggerDistance = DEFAULT_ZOOM_TRIGGER_DISTANCE;\n setDisplayToolTips(tooltips);\n // create the canvas and add the required listeners\n this.canvas = new Canvas(this, SWT.DOUBLE_BUFFERED | SWT.NO_BACKGROUND);\n this.canvas.addPaintListener(this);\n this.canvas.addMouseListener(this);\n this.canvas.addMouseMoveListener(this);\n this.canvas.addDisposeListener(new DisposeListener() {\n public void widgetDisposed(DisposeEvent e) {\n org.eclipse.swt.graphics.Image img;\n img = (org.eclipse.swt.graphics.Image) canvas.getData(\"double-buffer-image\");\n if (img != null) {\n img.dispose();\n }\n }\n });\n\n // set up popup menu...\n this.popup = null;\n if (properties || save || print || zoom)\n this.popup = createPopupMenu(properties, save, print, zoom);\n\n this.enforceFileExtensions = true;\n }\n\n /**\n * Returns the X scale factor for the chart. This will be 1.0 if no\n * scaling has been used.\n *\n * @return The scale factor.\n */\n public double getScaleX() {\n return this.scaleX;\n }\n\n /**\n * Returns the Y scale factory for the chart. This will be 1.0 if no\n * scaling has been used.\n *\n * @return The scale factor.\n */\n public double getScaleY() {\n return this.scaleY;\n }\n\n /**\n * Returns the anchor point.\n *\n * @return The anchor point (possibly <code>null</code>).\n */\n public Point2D getAnchor() {\n return this.anchor;\n }\n\n /**\n * Sets the anchor point. This method is provided for the use of\n * subclasses, not end users.\n *\n * @param anchor the anchor point (<code>null</code> permitted).\n */\n protected void setAnchor(Point2D anchor) {\n this.anchor = anchor;\n }\n\n /**\n * Returns the chart contained in the panel.\n *\n * @return The chart (possibly <code>null</code>).\n */\n public JFreeChart getChart() {\n return this.chart;\n }\n\n /**\n * Sets the chart that is displayed in the panel.\n *\n * @param chart the chart (<code>null</code> permitted).\n */\n public void setChart(JFreeChart chart) {\n // stop listening for changes to the existing chart\n if (this.chart != null) {\n this.chart.removeChangeListener(this);\n this.chart.removeProgressListener(this);\n }\n\n // add the new chart\n this.chart = chart;\n if (chart != null) {\n this.chart.addChangeListener(this);\n this.chart.addProgressListener(this);\n Plot plot = chart.getPlot();\n this.domainZoomable = false;\n this.rangeZoomable = false;\n if (plot instanceof Zoomable) {\n Zoomable z = (Zoomable) plot;\n this.domainZoomable = z.isDomainZoomable();\n this.rangeZoomable = z.isRangeZoomable();\n this.orientation = z.getOrientation();\n }\n }\n else {\n this.domainZoomable = false;\n this.rangeZoomable = false;\n }\n if (this.useBuffer) {\n this.refreshBuffer = true;\n }\n }\n\n /**\n * Returns the chart rendering info from the most recent chart redraw.\n *\n * @return The chart rendering info (possibly <code>null</code>).\n */\n public ChartRenderingInfo getChartRenderingInfo() {\n return this.info;\n }\n\n /**\n * Returns the flag that determines whether or not zooming is enabled for\n * the domain axis.\n *\n * @return A boolean.\n */\n public boolean isDomainZoomable() {\n return this.domainZoomable;\n }\n\n /**\n * Sets the flag that controls whether or not zooming is enable for the\n * domain axis. A check is made to ensure that the current plot supports\n * zooming for the domain values.\n *\n * @param flag <code>true</code> enables zooming if possible.\n */\n public void setDomainZoomable(boolean flag) {\n if (flag) {\n Plot plot = this.chart.getPlot();\n if (plot instanceof Zoomable) {\n Zoomable z = (Zoomable) plot;\n this.domainZoomable = flag && (z.isDomainZoomable());\n }\n }\n else {\n this.domainZoomable = false;\n }\n }\n\n /**\n * Returns the flag that determines whether or not zooming is enabled for\n * the range axis.\n *\n * @return A boolean.\n */\n public boolean isRangeZoomable() {\n return this.rangeZoomable;\n }\n\n /**\n * A flag that controls mouse-based zooming on the vertical axis.\n *\n * @param flag <code>true</code> enables zooming.\n */\n public void setRangeZoomable(boolean flag) {\n if (flag) {\n Plot plot = this.chart.getPlot();\n if (plot instanceof Zoomable) {\n Zoomable z = (Zoomable) plot;\n this.rangeZoomable = flag && (z.isRangeZoomable());\n }\n }\n else {\n this.rangeZoomable = false;\n }\n }\n\n /**\n * Returns the zoom in factor.\n *\n * @return The zoom in factor.\n *\n * @see #setZoomInFactor(double)\n */\n public double getZoomInFactor() {\n return this.zoomInFactor;\n }\n\n /**\n * Sets the zoom in factor.\n *\n * @param factor the factor.\n *\n * @see #getZoomInFactor()\n */\n public void setZoomInFactor(double factor) {\n this.zoomInFactor = factor;\n }\n\n /**\n * Returns the zoom out factor.\n *\n * @return The zoom out factor.\n *\n * @see #setZoomOutFactor(double)\n */\n public double getZoomOutFactor() {\n return this.zoomOutFactor;\n }\n\n /**\n * Sets the zoom out factor.\n *\n * @param factor the factor.\n *\n * @see #getZoomOutFactor()\n */\n public void setZoomOutFactor(double factor) {\n this.zoomOutFactor = factor;\n }\n\n /**\n * Displays a dialog that allows the user to edit the properties for the\n * current chart.\n */\n private void attemptEditChartProperties() {\n SWTChartEditor editor = new SWTChartEditor(this.canvas.getDisplay(),\n this.chart);\n //ChartEditorManager.getChartEditor(canvas.getDisplay(), this.chart);\n editor.open();\n }\n\n /**\n * Returns <code>true</code> if file extensions should be enforced, and\n * <code>false</code> otherwise.\n *\n * @return The flag.\n */\n public boolean isEnforceFileExtensions() {\n return this.enforceFileExtensions;\n }\n\n /**\n * Sets a flag that controls whether or not file extensions are enforced.\n *\n * @param enforce the new flag value.\n */\n public void setEnforceFileExtensions(boolean enforce) {\n this.enforceFileExtensions = enforce;\n }\n\n /**\n * Opens a file chooser and gives the user an opportunity to save the chart\n * in PNG format.\n *\n * @throws IOException if there is an I/O error.\n */\n public void doSaveAs() throws IOException {\n FileDialog fileDialog = new FileDialog(this.canvas.getShell(),\n SWT.SAVE);\n String[] extensions = {\"*.png\"};\n fileDialog.setFilterExtensions(extensions);\n String filename = fileDialog.open();\n if (filename != null) {\n if (isEnforceFileExtensions()) {\n if (!filename.endsWith(\".png\")) {\n filename = filename + \".png\";\n }\n }\n //TODO replace getSize by getBounds ?\n ChartUtilities.saveChartAsPNG(new File(filename), this.chart,\n this.canvas.getSize().x, this.canvas.getSize().y);\n }\n }\n\n /**\n * Returns a point based on (x, y) but constrained to be within the bounds\n * of the given rectangle. This method could be moved to JCommon.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param area the rectangle (<code>null</code> not permitted).\n *\n * @return A point within the rectangle.\n */\n private org.eclipse.swt.graphics.Point getPointInRectangle(int x, int y,\n Rectangle area) {\n x = Math.max(area.x, Math.min(x, area.x + area.width));\n y = Math.max(area.y, Math.min(y, area.y + area.height));\n return new org.eclipse.swt.graphics.Point(x, y);\n }\n\n /**\n * Zooms in on an anchor point (specified in screen coordinate space).\n *\n * @param x the x value (in screen coordinates).\n * @param y the y value (in screen coordinates).\n */\n public void zoomInBoth(double x, double y) {\n zoomInDomain(x, y);\n zoomInRange(x, y);\n }\n\n /**\n * Decreases the length of the domain axis, centered about the given\n * coordinate on the screen. The length of the domain axis is reduced\n * by the value of {@link #getZoomInFactor()}.\n *\n * @param x the x coordinate (in screen coordinates).\n * @param y the y-coordinate (in screen coordinates).\n */\n public void zoomInDomain(double x, double y) {\n Plot p = this.chart.getPlot();\n if (p instanceof Zoomable)\n {\n Zoomable plot = (Zoomable) p;\n plot.zoomDomainAxes(this.zoomInFactor, this.info.getPlotInfo(),\n translateScreenToJava2D(new Point((int) x, (int) y)));\n }\n }\n\n /**\n * Decreases the length of the range axis, centered about the given\n * coordinate on the screen. The length of the range axis is reduced by\n * the value of {@link #getZoomInFactor()}.\n *\n * @param x the x-coordinate (in screen coordinates).\n * @param y the y coordinate (in screen coordinates).\n */\n public void zoomInRange(double x, double y) {\n Plot p = this.chart.getPlot();\n if (p instanceof Zoomable) {\n Zoomable z = (Zoomable) p;\n z.zoomRangeAxes(this.zoomInFactor, this.info.getPlotInfo(),\n translateScreenToJava2D(new Point((int) x, (int) y)));\n }\n }\n\n /**\n * Zooms out on an anchor point (specified in screen coordinate space).\n *\n * @param x the x value (in screen coordinates).\n * @param y the y value (in screen coordinates).\n */\n public void zoomOutBoth(double x, double y) {\n zoomOutDomain(x, y);\n zoomOutRange(x, y);\n }\n\n /**\n * Increases the length of the domain axis, centered about the given\n * coordinate on the screen. The length of the domain axis is increased\n * by the value of {@link #getZoomOutFactor()}.\n *\n * @param x the x coordinate (in screen coordinates).\n * @param y the y-coordinate (in screen coordinates).\n */\n public void zoomOutDomain(double x, double y) {\n Plot p = this.chart.getPlot();\n if (p instanceof Zoomable) {\n Zoomable z = (Zoomable) p;\n z.zoomDomainAxes(this.zoomOutFactor, this.info.getPlotInfo(),\n translateScreenToJava2D(new Point((int) x, (int) y)));\n }\n }\n\n /**\n * Increases the length the range axis, centered about the given\n * coordinate on the screen. The length of the range axis is increased\n * by the value of {@link #getZoomOutFactor()}.\n *\n * @param x the x coordinate (in screen coordinates).\n * @param y the y-coordinate (in screen coordinates).\n */\n public void zoomOutRange(double x, double y) {\n Plot p = this.chart.getPlot();\n if (p instanceof Zoomable) {\n Zoomable z = (Zoomable) p;\n z.zoomRangeAxes(this.zoomOutFactor, this.info.getPlotInfo(),\n translateScreenToJava2D(new Point((int) x, (int) y)));\n }\n }\n\n /**\n * Zooms in on a selected region.\n *\n * @param selection the selected region.\n */\n public void zoom(Rectangle selection) {\n\n // get the origin of the zoom selection in the Java2D space used for\n // drawing the chart (that is, before any scaling to fit the panel)\n Point2D selectOrigin = translateScreenToJava2D(\n new Point(selection.x, selection.y));\n PlotRenderingInfo plotInfo = this.info.getPlotInfo();\n Rectangle scaledDataArea = getScreenDataArea(\n (selection.x + selection.width / 2),\n (selection.y + selection.height / 2));\n if ((selection.height > 0) && (selection.width > 0)) {\n\n double hLower = (selection.x - scaledDataArea.x)\n / (double) scaledDataArea.width;\n double hUpper = (selection.x + selection.width - scaledDataArea.x)\n / (double) scaledDataArea.width;\n double vLower = (scaledDataArea.y + scaledDataArea.height\n - selection.y - selection.height)\n / (double) scaledDataArea.height;\n double vUpper = (scaledDataArea.y + scaledDataArea.height\n - selection.y) / (double) scaledDataArea.height;\n Plot p = this.chart.getPlot();\n if (p instanceof Zoomable) {\n Zoomable z = (Zoomable) p;\n if (z.getOrientation() == PlotOrientation.HORIZONTAL) {\n z.zoomDomainAxes(vLower, vUpper, plotInfo, selectOrigin);\n z.zoomRangeAxes(hLower, hUpper, plotInfo, selectOrigin);\n }\n else {\n z.zoomDomainAxes(hLower, hUpper, plotInfo, selectOrigin);\n z.zoomRangeAxes(vLower, vUpper, plotInfo, selectOrigin);\n }\n }\n\n }\n\n }\n\n /**\n * Receives notification of changes to the chart, and redraws the chart.\n *\n * @param event details of the chart change event.\n */\n public void chartChanged(ChartChangeEvent event) {\n this.refreshBuffer = true;\n Plot plot = this.chart.getPlot();\n if (plot instanceof Zoomable) {\n Zoomable z = (Zoomable) plot;\n this.orientation = z.getOrientation();\n }\n this.canvas.redraw();\n }\n\n /**\n * Forces a redraw of the canvas by invoking a new PaintEvent.\n */\n public void forceRedraw() {\n Event ev = new Event();\n ev.gc = new GC(this.canvas);\n ev.x = 0;\n ev.y = 0;\n ev.width = this.canvas.getBounds().width;\n ev.height = this.canvas.getBounds().height;\n ev.count = 0;\n this.canvas.notifyListeners(SWT.Paint, ev);\n ev.gc.dispose();\n }\n\n /**\n * Adds a listener to the list of objects listening for chart mouse events.\n *\n * @param listener the listener (<code>null</code> not permitted).\n */\n public void addChartMouseListener(ChartMouseListener listener) {\n this.chartMouseListeners.add(ChartMouseListener.class, listener);\n }\n\n /**\n * Removes a listener from the list of objects listening for chart mouse\n * events.\n *\n * @param listener the listener.\n */\n public void removeChartMouseListener(ChartMouseListener listener) {\n this.chartMouseListeners.remove(ChartMouseListener.class, listener);\n }\n\n /**\n * Receives notification of a chart progress event.\n *\n * @param event the event.\n */\n public void chartProgress(ChartProgressEvent event) {\n // does nothing - override if necessary\n }\n\n /**\n * Restores the auto-range calculation on both axes.\n */\n public void restoreAutoBounds() {\n restoreAutoDomainBounds();\n restoreAutoRangeBounds();\n }\n\n /**\n * Restores the auto-range calculation on the domain axis.\n */\n public void restoreAutoDomainBounds() {\n Plot p = this.chart.getPlot();\n if (p instanceof Zoomable) {\n Zoomable z = (Zoomable) p;\n // we need to guard against this.zoomPoint being null\n org.eclipse.swt.graphics.Point zp =\n (this.zoomPoint != null ? this.zoomPoint\n : new org.eclipse.swt.graphics.Point(0, 0));\n z.zoomDomainAxes(0.0, this.info.getPlotInfo(),\n SWTUtils.toAwtPoint(zp));\n }\n }\n\n /**\n * Restores the auto-range calculation on the range axis.\n */\n public void restoreAutoRangeBounds() {\n Plot p = this.chart.getPlot();\n if (p instanceof ValueAxisPlot) {\n Zoomable z = (Zoomable) p;\n // we need to guard against this.zoomPoint being null\n org.eclipse.swt.graphics.Point zp =\n (this.zoomPoint != null ? this.zoomPoint\n : new org.eclipse.swt.graphics.Point(0, 0));\n z.zoomRangeAxes(0.0, this.info.getPlotInfo(),\n SWTUtils.toAwtPoint(zp));\n }\n }\n\n /**\n * Applies any scaling that is in effect for the chart drawing to the\n * given rectangle.\n *\n * @param rect the rectangle.\n *\n * @return A new scaled rectangle.\n */\n public Rectangle scale(Rectangle2D rect) {\n Rectangle insets = this.getClientArea();\n int x = (int) Math.round(rect.getX() * getScaleX()) + insets.x;\n int y = (int) Math.round(rect.getY() * this.getScaleY()) + insets.y;\n int w = (int) Math.round(rect.getWidth() * this.getScaleX());\n int h = (int) Math.round(rect.getHeight() * this.getScaleY());\n return new Rectangle(x, y, w, h);\n }\n\n /**\n * Returns the data area for the chart (the area inside the axes) with the\n * current scaling applied (that is, the area as it appears on screen).\n *\n * @return The scaled data area.\n */\n public Rectangle getScreenDataArea() {\n Rectangle2D dataArea = this.info.getPlotInfo().getDataArea();\n Rectangle clientArea = this.getClientArea();\n int x = (int) (dataArea.getX() * this.scaleX + clientArea.x);\n int y = (int) (dataArea.getY() * this.scaleY + clientArea.y);\n int w = (int) (dataArea.getWidth() * this.scaleX);\n int h = (int) (dataArea.getHeight() * this.scaleY);\n return new Rectangle(x, y, w, h);\n }\n\n /**\n * Returns the data area (the area inside the axes) for the plot or subplot,\n * with the current scaling applied.\n *\n * @param x the x-coordinate (for subplot selection).\n * @param y the y-coordinate (for subplot selection).\n *\n * @return The scaled data area.\n */\n public Rectangle getScreenDataArea(int x, int y) {\n PlotRenderingInfo plotInfo = this.info.getPlotInfo();\n Rectangle result;\n if (plotInfo.getSubplotCount() == 0)\n result = getScreenDataArea();\n else {\n // get the origin of the zoom selection in the Java2D space used for\n // drawing the chart (that is, before any scaling to fit the panel)\n Point2D selectOrigin = translateScreenToJava2D(new Point(x, y));\n int subplotIndex = plotInfo.getSubplotIndex(selectOrigin);\n if (subplotIndex == -1) {\n return null;\n }\n result = scale(plotInfo.getSubplotInfo(subplotIndex).getDataArea());\n }\n return result;\n }\n\n /**\n * Translates a Java2D point on the chart to a screen location.\n *\n * @param java2DPoint the Java2D point.\n *\n * @return The screen location.\n */\n public Point translateJava2DToScreen(Point2D java2DPoint) {\n Rectangle insets = this.getClientArea();\n int x = (int) (java2DPoint.getX() * this.scaleX + insets.x);\n int y = (int) (java2DPoint.getY() * this.scaleY + insets.y);\n return new Point(x, y);\n }\n\n /**\n * Translates a screen location to a Java SWT point.\n *\n * @param screenPoint the screen location.\n *\n * @return The Java2D coordinates.\n */\n public Point translateScreenToJavaSWT(Point screenPoint) {\n Rectangle insets = this.getClientArea();\n int x = (int) ((screenPoint.x - insets.x) / this.scaleX);\n int y = (int) ((screenPoint.y - insets.y) / this.scaleY);\n return new Point(x, y);\n }\n\n /**\n * Translates a screen location to a Java2D point.\n *\n * @param screenPoint the screen location.\n *\n * @return The Java2D coordinates.\n */\n public Point2D translateScreenToJava2D(Point screenPoint) {\n Rectangle insets = this.getClientArea();\n int x = (int) ((screenPoint.x - insets.x) / this.scaleX);\n int y = (int) ((screenPoint.y - insets.y) / this.scaleY);\n return new Point2D.Double(x, y);\n }\n\n /**\n * Returns the flag that controls whether or not a horizontal axis trace\n * line is drawn over the plot area at the current mouse location.\n *\n * @return A boolean.\n */\n public boolean getHorizontalAxisTrace() {\n return this.horizontalAxisTrace;\n }\n\n /**\n * A flag that controls trace lines on the horizontal axis.\n *\n * @param flag <code>true</code> enables trace lines for the mouse\n * pointer on the horizontal axis.\n */\n public void setHorizontalAxisTrace(boolean flag) {\n this.horizontalAxisTrace = flag;\n }\n\n /**\n * Returns the flag that controls whether or not a vertical axis trace\n * line is drawn over the plot area at the current mouse location.\n *\n * @return A boolean.\n */\n public boolean getVerticalAxisTrace() {\n return this.verticalAxisTrace;\n }\n\n /**\n * A flag that controls trace lines on the vertical axis.\n *\n * @param flag <code>true</code> enables trace lines for the mouse\n * pointer on the vertical axis.\n */\n public void setVerticalAxisTrace(boolean flag) {\n this.verticalAxisTrace = flag;\n }\n\n /**\n * @param displayToolTips the displayToolTips to set\n */\n public void setDisplayToolTips(boolean displayToolTips) {\n this.displayToolTips = displayToolTips;\n }\n\n /**\n * Returns a string for the tooltip.\n *\n * @param e the mouse event.\n *\n * @return A tool tip or <code>null</code> if no tooltip is available.\n */\n public String getToolTipText(org.eclipse.swt.events.MouseEvent e) {\n String result = null;\n if (this.info != null) {\n EntityCollection entities = this.info.getEntityCollection();\n if (entities != null) {\n Rectangle insets = getClientArea();\n ChartEntity entity = entities.getEntity(\n (int) ((e.x - insets.x) / this.scaleX),\n (int) ((e.y - insets.y) / this.scaleY));\n if (entity != null) {\n result = entity.getToolTipText();\n }\n }\n }\n return result;\n\n }\n\n /**\n * The idea is to modify the zooming options depending on the type of chart\n * being displayed by the panel.\n *\n * @param x horizontal position of the popup.\n * @param y vertical position of the popup.\n */\n protected void displayPopupMenu(int x, int y) {\n if (this.popup != null) {\n // go through each zoom menu item and decide whether or not to\n // enable it...\n Plot plot = this.chart.getPlot();\n boolean isDomainZoomable = false;\n boolean isRangeZoomable = false;\n if (plot instanceof Zoomable) {\n Zoomable z = (Zoomable) plot;\n isDomainZoomable = z.isDomainZoomable();\n isRangeZoomable = z.isRangeZoomable();\n }\n if (this.zoomInDomainMenuItem != null) {\n this.zoomInDomainMenuItem.setEnabled(isDomainZoomable);\n }\n if (this.zoomOutDomainMenuItem != null) {\n this.zoomOutDomainMenuItem.setEnabled(isDomainZoomable);\n }\n if (this.zoomResetDomainMenuItem != null) {\n this.zoomResetDomainMenuItem.setEnabled(isDomainZoomable);\n }\n\n if (this.zoomInRangeMenuItem != null) {\n this.zoomInRangeMenuItem.setEnabled(isRangeZoomable);\n }\n if (this.zoomOutRangeMenuItem != null) {\n this.zoomOutRangeMenuItem.setEnabled(isRangeZoomable);\n }\n\n if (this.zoomResetRangeMenuItem != null) {\n this.zoomResetRangeMenuItem.setEnabled(isRangeZoomable);\n }\n\n if (this.zoomInBothMenuItem != null) {\n this.zoomInBothMenuItem.setEnabled(isDomainZoomable\n & isRangeZoomable);\n }\n if (this.zoomOutBothMenuItem != null) {\n this.zoomOutBothMenuItem.setEnabled(isDomainZoomable\n & isRangeZoomable);\n }\n if (this.zoomResetBothMenuItem != null) {\n this.zoomResetBothMenuItem.setEnabled(isDomainZoomable\n & isRangeZoomable);\n }\n\n this.popup.setLocation(x, y);\n this.popup.setVisible(true);\n }\n\n }\n\n /**\n * Creates a print job for the chart.\n */\n public void createChartPrintJob() {\n new ChartPrintJob(\"PlotPrint\").print(this);\n }\n\n /**\n * Creates a popup menu for the canvas.\n *\n * @param properties include a menu item for the chart property editor.\n * @param save include a menu item for saving the chart.\n * @param print include a menu item for printing the chart.\n * @param zoom include menu items for zooming.\n *\n * @return The popup menu.\n */\n protected Menu createPopupMenu(boolean properties, boolean save,\n boolean print, boolean zoom) {\n\n Menu result = new Menu(this);\n boolean separator = false;\n\n if (properties) {\n MenuItem propertiesItem = new MenuItem(result, SWT.PUSH);\n propertiesItem.setText(localizationResources.getString(\n \"Properties...\"));\n propertiesItem.setData(PROPERTIES_COMMAND);\n propertiesItem.addSelectionListener(this);\n separator = true;\n }\n if (save) {\n if (separator) {\n new MenuItem(result, SWT.SEPARATOR);\n separator = false;\n }\n MenuItem saveItem = new MenuItem(result, SWT.NONE);\n saveItem.setText(localizationResources.getString(\"Save_as...\"));\n saveItem.setData(SAVE_COMMAND);\n saveItem.addSelectionListener(this);\n separator = true;\n }\n if (print) {\n if (separator) {\n new MenuItem(result, SWT.SEPARATOR);\n separator = false;\n }\n MenuItem printItem = new MenuItem(result, SWT.NONE);\n printItem.setText(localizationResources.getString(\"Print...\"));\n printItem.setData(PRINT_COMMAND);\n printItem.addSelectionListener(this);\n separator = true;\n }\n if (zoom) {\n if (separator) {\n new MenuItem(result, SWT.SEPARATOR);\n separator = false;\n }\n\n Menu zoomInMenu = new Menu(result);\n MenuItem zoomInMenuItem = new MenuItem(result, SWT.CASCADE);\n zoomInMenuItem.setText(localizationResources.getString(\"Zoom_In\"));\n zoomInMenuItem.setMenu(zoomInMenu);\n\n this.zoomInBothMenuItem = new MenuItem(zoomInMenu, SWT.PUSH);\n this.zoomInBothMenuItem.setText(localizationResources.getString(\n \"All_Axes\"));\n this.zoomInBothMenuItem.setData(ZOOM_IN_BOTH_COMMAND);\n this.zoomInBothMenuItem.addSelectionListener(this);\n\n new MenuItem(zoomInMenu, SWT.SEPARATOR);\n\n this.zoomInDomainMenuItem = new MenuItem(zoomInMenu, SWT.PUSH);\n this.zoomInDomainMenuItem.setText(localizationResources.getString(\n \"Domain_Axis\"));\n this.zoomInDomainMenuItem.setData(ZOOM_IN_DOMAIN_COMMAND);\n this.zoomInDomainMenuItem.addSelectionListener(this);\n\n this.zoomInRangeMenuItem = new MenuItem(zoomInMenu, SWT.PUSH);\n this.zoomInRangeMenuItem.setText(localizationResources.getString(\n \"Range_Axis\"));\n this.zoomInRangeMenuItem.setData(ZOOM_IN_RANGE_COMMAND);\n this.zoomInRangeMenuItem.addSelectionListener(this);\n\n Menu zoomOutMenu = new Menu(result);\n MenuItem zoomOutMenuItem = new MenuItem(result, SWT.CASCADE);\n zoomOutMenuItem.setText(localizationResources.getString(\n \"Zoom_Out\"));\n zoomOutMenuItem.setMenu(zoomOutMenu);\n\n this.zoomOutBothMenuItem = new MenuItem(zoomOutMenu, SWT.PUSH);\n this.zoomOutBothMenuItem.setText(localizationResources.getString(\n \"All_Axes\"));\n this.zoomOutBothMenuItem.setData(ZOOM_OUT_BOTH_COMMAND);\n this.zoomOutBothMenuItem.addSelectionListener(this);\n\n new MenuItem(zoomOutMenu, SWT.SEPARATOR);\n\n this.zoomOutDomainMenuItem = new MenuItem(zoomOutMenu, SWT.PUSH);\n this.zoomOutDomainMenuItem.setText(localizationResources.getString(\n \"Domain_Axis\"));\n this.zoomOutDomainMenuItem.setData(ZOOM_OUT_DOMAIN_COMMAND);\n this.zoomOutDomainMenuItem.addSelectionListener(this);\n\n this.zoomOutRangeMenuItem = new MenuItem(zoomOutMenu, SWT.PUSH);\n this.zoomOutRangeMenuItem.setText(\n localizationResources.getString(\"Range_Axis\"));\n this.zoomOutRangeMenuItem.setData(ZOOM_OUT_RANGE_COMMAND);\n this.zoomOutRangeMenuItem.addSelectionListener(this);\n\n Menu autoRangeMenu = new Menu(result);\n MenuItem autoRangeMenuItem = new MenuItem(result, SWT.CASCADE);\n autoRangeMenuItem.setText(localizationResources.getString(\n \"Auto_Range\"));\n autoRangeMenuItem.setMenu(autoRangeMenu);\n\n this.zoomResetBothMenuItem = new MenuItem(autoRangeMenu, SWT.PUSH);\n this.zoomResetBothMenuItem.setText(localizationResources.getString(\n \"All_Axes\"));\n this.zoomResetBothMenuItem.setData(ZOOM_RESET_BOTH_COMMAND);\n this.zoomResetBothMenuItem.addSelectionListener(this);\n\n new MenuItem(autoRangeMenu, SWT.SEPARATOR);\n\n this.zoomResetDomainMenuItem = new MenuItem(autoRangeMenu,\n SWT.PUSH);\n this.zoomResetDomainMenuItem.setText(\n localizationResources.getString(\"Domain_Axis\"));\n this.zoomResetDomainMenuItem.setData(ZOOM_RESET_DOMAIN_COMMAND);\n this.zoomResetDomainMenuItem.addSelectionListener(this);\n\n this.zoomResetRangeMenuItem = new MenuItem(autoRangeMenu, SWT.PUSH);\n this.zoomResetRangeMenuItem.setText(\n localizationResources.getString(\"Range_Axis\"));\n this.zoomResetRangeMenuItem.setData(ZOOM_RESET_RANGE_COMMAND);\n this.zoomResetRangeMenuItem.addSelectionListener(this);\n }\n\n return result;\n }\n\n /**\n * Handles action events generated by the popup menu.\n *\n * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(\n * org.eclipse.swt.events.SelectionEvent)\n */\n public void widgetDefaultSelected(SelectionEvent e) {\n widgetSelected(e);\n }\n\n /**\n * Handles action events generated by the popup menu.\n *\n * @see org.eclipse.swt.events.SelectionListener#widgetSelected(\n * org.eclipse.swt.events.SelectionEvent)\n */\n public void widgetSelected(SelectionEvent e) {\n String command = (String) ((MenuItem) e.getSource()).getData();\n if (command.equals(PROPERTIES_COMMAND)) {\n attemptEditChartProperties();\n }\n else if (command.equals(SAVE_COMMAND)) {\n try {\n doSaveAs();\n }\n catch (IOException ex) {\n ex.printStackTrace();\n }\n }\n else if (command.equals(PRINT_COMMAND)) {\n createChartPrintJob();\n }\n /* in the next zoomPoint.x and y replace by e.x and y for now.\n * this helps to handle the mouse events and besides,\n * those values are unused AFAIK. */\n else if (command.equals(ZOOM_IN_BOTH_COMMAND)) {\n zoomInBoth(e.x, e.y);\n }\n else if (command.equals(ZOOM_IN_DOMAIN_COMMAND)) {\n zoomInDomain(e.x, e.y);\n }\n else if (command.equals(ZOOM_IN_RANGE_COMMAND)) {\n zoomInRange(e.x, e.y);\n }\n else if (command.equals(ZOOM_OUT_BOTH_COMMAND)) {\n zoomOutBoth(e.x, e.y);\n }\n else if (command.equals(ZOOM_OUT_DOMAIN_COMMAND)) {\n zoomOutDomain(e.x, e.y);\n }\n else if (command.equals(ZOOM_OUT_RANGE_COMMAND)) {\n zoomOutRange(e.x, e.y);\n }\n else if (command.equals(ZOOM_RESET_BOTH_COMMAND)) {\n restoreAutoBounds();\n }\n else if (command.equals(ZOOM_RESET_DOMAIN_COMMAND)) {\n restoreAutoDomainBounds();\n }\n else if (command.equals(ZOOM_RESET_RANGE_COMMAND)) {\n restoreAutoRangeBounds();\n }\n this.forceRedraw();\n }\n\n /**\n * Not implemented.\n *\n * @param graphics the graphics.\n * @param pageFormat the page format.\n * @param pageIndex the page index.\n *\n * @return ?.\n *\n * @throws PrinterException if there is a problem.\n */\n public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)\n throws PrinterException {\n if (pageIndex != 0) {\n return NO_SUCH_PAGE;\n }\n /*\n CairoImage image = new CairoImage(\n this.getBounds().width, this.getBounds().height);\n Graphics2D g2 = image.createGraphics2D();\n double x = pageFormat.getImageableX();\n double y = pageFormat.getImageableY();\n double w = pageFormat.getImageableWidth();\n double h = pageFormat.getImageableHeight();\n this.chart.draw(\n g2, new Rectangle2D.Double(x, y, w, h), this.anchor, null\n );\n */\n return PAGE_EXISTS;\n }\n\n /**\n * Hook an SWT listener on the canvas where the chart is drawn.\n * The purpose of this method is to allow some degree of customization.\n *\n * @param listener The SWT listener to attach to the canvas.\n */\n public void addSWTListener(EventListener listener) {\n if (listener instanceof ControlListener) {\n this.canvas.addControlListener((ControlListener) listener);\n }\n else if (listener instanceof DisposeListener) {\n this.canvas.addDisposeListener((DisposeListener) listener);\n// }\n// else if (listener instanceof DragDetectListener) {\n// this.canvas.addDragDetectListener((DragDetectListener) listener);\n }\n else if (listener instanceof FocusListener) {\n this.canvas.addFocusListener((FocusListener) listener);\n }\n else if (listener instanceof HelpListener) {\n this.canvas.addHelpListener((HelpListener) listener);\n }\n else if (listener instanceof KeyListener) {\n this.canvas.addKeyListener((KeyListener) listener);\n// }\n// else if (listener instanceof MenuDetectListener) {\n// this.canvas.addMenuDetectListener((MenuDetectListener) listener);\n }\n else if (listener instanceof MouseListener) {\n this.canvas.addMouseListener((MouseListener) listener);\n }\n else if (listener instanceof MouseMoveListener) {\n this.canvas.addMouseMoveListener((MouseMoveListener) listener);\n }\n else if (listener instanceof MouseTrackListener) {\n this.canvas.addMouseTrackListener((MouseTrackListener) listener);\n// } else if (listener instanceof MouseWheelListener) {\n// this.canvas.addMouseWheelListener((MouseWheelListener) listener);\n }\n else if (listener instanceof PaintListener) {\n this.canvas.addPaintListener((PaintListener) listener);\n }\n else if (listener instanceof TraverseListener) {\n this.canvas.addTraverseListener((TraverseListener) listener);\n }\n }\n\n /**\n * Does nothing - override if necessary.\n *\n * @param event the mouse event.\n */\n public void mouseDoubleClick(MouseEvent event) {\n // do nothing, override if necessary\n }\n\n /**\n * Handles a mouse down event.\n *\n * @param event the event.\n */\n public void mouseDown(MouseEvent event) {\n\n Rectangle scaledDataArea = getScreenDataArea(event.x, event.y);\n if (scaledDataArea == null) return;\n this.zoomPoint = getPointInRectangle(event.x, event.y, scaledDataArea);\n int x = (int) ((event.x - getClientArea().x) / this.scaleX);\n int y = (int) ((event.y - getClientArea().y) / this.scaleY);\n\n this.anchor = new Point2D.Double(x, y);\n this.chart.setNotify(true); // force a redraw\n this.canvas.redraw();\n\n // new entity code\n ChartEntity entity = null;\n if (this.info != null) {\n EntityCollection entities = this.info.getEntityCollection();\n if (entities != null) {\n entity = entities.getEntity(x, y);\n }\n }\n\n Object[] listeners = this.chartMouseListeners.getListeners(\n ChartMouseListener.class);\n if (listeners.length == 0) {\n return;\n }\n\n // pass mouse down event if some ChartMouseListener are listening\n java.awt.event.MouseEvent mouseEvent = SWTUtils.toAwtMouseEvent(event);\n ChartMouseEvent chartEvent = new ChartMouseEvent(getChart(),\n mouseEvent, entity);\n for (int i = listeners.length - 1; i >= 0; i -= 1) {\n ((ChartMouseListener) listeners[i]).chartMouseClicked(chartEvent);\n }\n }\n\n /**\n * Handles a mouse up event.\n *\n * @param event the event.\n */\n public void mouseUp(MouseEvent event) {\n\n boolean hZoom, vZoom;\n if (this.zoomRectangle == null) {\n Rectangle screenDataArea = getScreenDataArea(event.x, event.y);\n if (screenDataArea != null) {\n this.zoomPoint = getPointInRectangle(event.x, event.y,\n screenDataArea);\n }\n if (this.popup != null && event.button == 3) {\n org.eclipse.swt.graphics.Point pt = this.canvas.toDisplay(\n event.x, event.y);\n displayPopupMenu(pt.x, pt.y);\n }\n }\n else {\n hZoom = false;\n vZoom = false;\n if (this.orientation == PlotOrientation.HORIZONTAL) {\n hZoom = this.rangeZoomable;\n vZoom = this.domainZoomable;\n }\n else {\n hZoom = this.domainZoomable;\n vZoom = this.rangeZoomable;\n }\n boolean zoomTrigger1 = hZoom && Math.abs(this.zoomRectangle.width)\n >= this.zoomTriggerDistance;\n boolean zoomTrigger2 = vZoom\n && Math.abs(this.zoomRectangle.height)\n >= this.zoomTriggerDistance;\n if (zoomTrigger1 || zoomTrigger2) {\n // if the box has been drawn backwards, restore the auto bounds\n if ((hZoom && (this.zoomRectangle.x + this.zoomRectangle.width\n < this.zoomPoint.x)) || (vZoom && (this.zoomRectangle.y\n + this.zoomRectangle.height < this.zoomPoint.y)))\n restoreAutoBounds();\n else {\n zoom(this.zoomRectangle);\n }\n this.canvas.redraw();\n }\n }\n this.zoomPoint = null;\n this.zoomRectangle = null;\n }\n\n /**\n * Handles a mouse move event.\n *\n * @param event the mouse event.\n */\n public void mouseMove(MouseEvent event) {\n\n // handle axis trace\n if (this.horizontalAxisTrace || this.verticalAxisTrace) {\n this.horizontalTraceLineY = event.y;\n this.verticalTraceLineX = event.x;\n this.canvas.redraw();\n }\n\n // handle tool tips in a simple way\n if (this.displayToolTips) {\n String s = getToolTipText(event);\n if (s == null && this.canvas.getToolTipText() != null\n || s != null && !s.equals(this.canvas.getToolTipText()))\n this.canvas.setToolTipText(s);\n }\n\n // handle zoom box\n boolean hZoom, vZoom;\n if (this.zoomPoint != null) {\n Rectangle scaledDataArea = getScreenDataArea(this.zoomPoint.x,\n this.zoomPoint.y);\n org.eclipse.swt.graphics.Point movingPoint\n = getPointInRectangle(event.x, event.y, scaledDataArea);\n if (this.orientation == PlotOrientation.HORIZONTAL) {\n hZoom = this.rangeZoomable;\n vZoom = this.domainZoomable;\n }\n else {\n hZoom = this.domainZoomable;\n vZoom = this.rangeZoomable;\n }\n if (hZoom && vZoom) {\n // selected rectangle shouldn't extend outside the data area...\n this.zoomRectangle = new Rectangle(this.zoomPoint.x,\n this.zoomPoint.y, movingPoint.x - this.zoomPoint.x,\n movingPoint.y - this.zoomPoint.y);\n }\n else if (hZoom) {\n this.zoomRectangle = new Rectangle(this.zoomPoint.x,\n scaledDataArea.y, movingPoint.x - this.zoomPoint.x,\n scaledDataArea.height);\n }\n else if (vZoom) {\n int ymax = Math.max(movingPoint.y, scaledDataArea.y);\n this.zoomRectangle = new Rectangle(\n scaledDataArea.x, this.zoomPoint.y,\n scaledDataArea.width, ymax - this.zoomPoint.y);\n }\n this.canvas.redraw();\n }\n\n // new entity code\n ChartEntity entity = null;\n int x = (int) ((event.x - getClientArea().x) / this.scaleX);\n int y = (int) ((event.y - getClientArea().y) / this.scaleY);\n\n if (this.info != null) {\n EntityCollection entities = this.info.getEntityCollection();\n if (entities != null) {\n entity = entities.getEntity(x, y);\n }\n }\n\n Object[] listeners = this.chartMouseListeners.getListeners(\n ChartMouseListener.class);\n if (listeners.length == 0) {\n return;\n }\n\n // pass mouse move event if some ChartMouseListener are listening\n java.awt.event.MouseEvent mouseEvent = SWTUtils.toAwtMouseEvent(event);\n ChartMouseEvent chartEvent = new ChartMouseEvent(getChart(),\n mouseEvent, entity);\n for (int i = listeners.length - 1; i >= 0; i -= 1) {\n ((ChartMouseListener) listeners[i]).chartMouseMoved(chartEvent);\n }\n }\n\n /**\n * Paints the control.\n *\n * @param e the paint event.\n */\n public void paintControl(PaintEvent e) {\n // first determine the size of the chart rendering area...\n // TODO workout insets for SWT\n Rectangle available = getBounds();\n // skip if chart is null\n if (this.chart == null) {\n this.canvas.drawBackground(e.gc, available.x, available.y,\n available.width, available.height);\n return;\n }\n SWTGraphics2D sg2 = new SWTGraphics2D(e.gc);\n\n // work out if scaling is required...\n boolean scale = false;\n int drawWidth = available.width;\n int drawHeight = available.height;\n if (drawWidth == 0.0 || drawHeight == 0.0) return;\n this.scaleX = 1.0;\n this.scaleY = 1.0;\n if (drawWidth < this.minimumDrawWidth) {\n this.scaleX = (double) drawWidth / this.minimumDrawWidth;\n drawWidth = this.minimumDrawWidth;\n scale = true;\n }\n else if (drawWidth > this.maximumDrawWidth) {\n this.scaleX = (double) drawWidth / this.maximumDrawWidth;\n drawWidth = this.maximumDrawWidth;\n scale = true;\n }\n if (drawHeight < this.minimumDrawHeight) {\n this.scaleY = (double) drawHeight / this.minimumDrawHeight;\n drawHeight = this.minimumDrawHeight;\n scale = true;\n }\n else if (drawHeight > this.maximumDrawHeight) {\n this.scaleY = (double) drawHeight / this.maximumDrawHeight;\n drawHeight = this.maximumDrawHeight;\n scale = true;\n }\n // are we using the chart buffer?\n if (this.useBuffer) {\n //SwtGraphics2D sg2 = new SwtGraphics2D(e.gc);\n this.chartBuffer = (org.eclipse.swt.graphics.Image)\n this.canvas.getData(\"double-buffer-image\");\n // do we need to fill the buffer?\n if (this.chartBuffer == null\n || this.chartBufferWidth != available.width\n || this.chartBufferHeight != available.height) {\n this.chartBufferWidth = available.width;\n this.chartBufferHeight = available.height;\n if (this.chartBuffer != null) {\n this.chartBuffer.dispose();\n }\n this.chartBuffer = new org.eclipse.swt.graphics.Image(\n getDisplay(), this.chartBufferWidth,\n this.chartBufferHeight);\n this.refreshBuffer = true;\n }\n\n // do we need to redraw the buffer?\n if (this.refreshBuffer) {\n // Performs the actual drawing here ...\n GC gci = new GC(this.chartBuffer);\n // anti-aliasing\n if (this.chart.getAntiAlias()) {\n gci.setAntialias(SWT.ON);\n }\n if (this.chart.getTextAntiAlias()\n == RenderingHints.KEY_TEXT_ANTIALIASING) {\n gci.setTextAntialias(SWT.ON);\n }\n SWTGraphics2D sg2d = new SWTGraphics2D(gci);\n if (scale) {\n sg2d.scale(this.scaleX, this.scaleY);\n this.chart.draw(sg2d, new Rectangle2D.Double(0, 0,\n drawWidth, drawHeight), getAnchor(), this.info);\n }\n else {\n this.chart.draw(sg2d, new Rectangle2D.Double(0, 0,\n drawWidth, drawHeight), getAnchor(), this.info);\n }\n this.canvas.setData(\"double-buffer-image\", this.chartBuffer);\n sg2d.dispose();\n gci.dispose();\n this.refreshBuffer = false;\n }\n\n // zap the buffer onto the canvas...\n sg2.drawImage(this.chartBuffer, 0, 0);\n }\n // or redrawing the chart every time...\n else {\n if (this.chart.getAntiAlias()) {\n e.gc.setAntialias(SWT.ON);\n }\n if (this.chart.getTextAntiAlias()\n == RenderingHints.KEY_TEXT_ANTIALIASING) {\n e.gc.setTextAntialias(SWT.ON);\n }\n this.chart.draw(sg2, new Rectangle2D.Double(0, 0,\n getBounds().width, getBounds().height), getAnchor(),\n this.info);\n }\n Rectangle area = getScreenDataArea();\n // TODO see if we need to apply some line color and style to the\n // axis traces\n if (this.horizontalAxisTrace && area.x < this.verticalTraceLineX\n && area.x + area.width > this.verticalTraceLineX) {\n e.gc.drawLine(this.verticalTraceLineX, area.y,\n this.verticalTraceLineX, area.y + area.height);\n }\n if (this.verticalAxisTrace && area.y < this.horizontalTraceLineY\n && area.y + area.height > this.horizontalTraceLineY) {\n e.gc.drawLine(area.x, this.horizontalTraceLineY,\n area.x + area.width, this.horizontalTraceLineY);\n }\n this.verticalTraceLineX = 0;\n this.horizontalTraceLineY = 0;\n if (this.zoomRectangle != null) {\n e.gc.drawRectangle(this.zoomRectangle);\n }\n sg2.dispose();\n }\n\n /**\n * Disposes the control.\n */\n public void dispose() {\n // de-register the composite as a listener for the chart.\n if (this.chart != null) {\n this.chart.removeChangeListener(this);\n this.chart.removeProgressListener(this);\n }\n\n if (this.chartBuffer != null) {\n this.chartBuffer.dispose();\n }\n\n if (this.popup != null) {\n this.popup.dispose();\n }\n super.dispose();\n }\n\n}" } ]
import java.awt.Font; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PiePlot; import org.jfree.data.general.DefaultPieDataset; import org.jfree.data.general.PieDataset; import org.jfree.experimental.chart.swt.ChartComposite;
85,017
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------- * SWTPieChartDemo1.java * --------------------- * (C) Copyright 2006, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): * * Changes * ------- * 23-Aug-2006 : New class (DG); * */ package org.jfree.experimental.chart.swt.demo; /** * This demo shows a time series chart that has multiple range axes. */ public class SWTPieChartDemo1 { /** * Creates a sample dataset. * * @return A sample dataset. */ private static PieDataset createDataset() { DefaultPieDataset dataset = new DefaultPieDataset(); dataset.setValue("One", new Double(43.2)); dataset.setValue("Two", new Double(10.0)); dataset.setValue("Three", new Double(27.5)); dataset.setValue("Four", new Double(17.5)); dataset.setValue("Five", new Double(11.0)); dataset.setValue("Six", new Double(19.4)); return dataset; } /** * Creates a chart. * * @param dataset the dataset. * * @return A chart. */ private static JFreeChart createChart(PieDataset dataset) {
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------- * SWTPieChartDemo1.java * --------------------- * (C) Copyright 2006, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): * * Changes * ------- * 23-Aug-2006 : New class (DG); * */ package org.jfree.experimental.chart.swt.demo; /** * This demo shows a time series chart that has multiple range axes. */ public class SWTPieChartDemo1 { /** * Creates a sample dataset. * * @return A sample dataset. */ private static PieDataset createDataset() { DefaultPieDataset dataset = new DefaultPieDataset(); dataset.setValue("One", new Double(43.2)); dataset.setValue("Two", new Double(10.0)); dataset.setValue("Three", new Double(27.5)); dataset.setValue("Four", new Double(17.5)); dataset.setValue("Five", new Double(11.0)); dataset.setValue("Six", new Double(19.4)); return dataset; } /** * Creates a chart. * * @param dataset the dataset. * * @return A chart. */ private static JFreeChart createChart(PieDataset dataset) {
JFreeChart chart = ChartFactory.createPieChart(
0
2023-12-24 12:36:47+00:00
128k
Hoto-Mocha/Re-ARranged-Pixel-Dungeon
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/Rankings.java
[ { "identifier": "Actor", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/Actor.java", "snippet": "public abstract class Actor implements Bundlable {\n\t\n\tpublic static final float TICK\t= 1f;\n\n\tprivate float time;\n\n\tprivate int id = 0;\n\n\t//default priority values for general actor categories\n\t//note that some specific actors pick more specific values\n\t//e.g. a buff acting after all normal buffs might have priority BUFF_PRIO + 1\n\tprotected static final int VFX_PRIO = 100; //visual effects take priority\n\tprotected static final int HERO_PRIO = 0; //positive is before hero, negative after\n\tprotected static final int BLOB_PRIO = -10; //blobs act after hero, before mobs\n\tprotected static final int MOB_PRIO = -20; //mobs act between buffs and blobs\n\tprotected static final int BUFF_PRIO = -30; //buffs act last in a turn\n\tprivate static final int DEFAULT = -100; //if no priority is given, act after all else\n\n\t//used to determine what order actors act in if their time is equal. Higher values act earlier.\n\tprotected int actPriority = DEFAULT;\n\n\tprotected abstract boolean act();\n\n\t//Always spends exactly the specified amount of time, regardless of time-influencing factors\n\tprotected void spendConstant( float time ){\n\t\tthis.time += time;\n\t\t//if time is very close to a whole number, round to a whole number to fix errors\n\t\tfloat ex = Math.abs(this.time % 1f);\n\t\tif (ex < .001f){\n\t\t\tthis.time = Math.round(this.time);\n\t\t}\n\t}\n\n\t//sends time, but the amount can be influenced\n\tprotected void spend( float time ) {\n\t\tspendConstant( time );\n\t}\n\n\tpublic void spendToWhole(){\n\t\ttime = (float)Math.ceil(time);\n\t}\n\t\n\tprotected void postpone( float time ) {\n\t\tif (this.time < now + time) {\n\t\t\tthis.time = now + time;\n\t\t\t//if time is very close to a whole number, round to a whole number to fix errors\n\t\t\tfloat ex = Math.abs(this.time % 1f);\n\t\t\tif (ex < .001f){\n\t\t\t\tthis.time = Math.round(this.time);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic float cooldown() {\n\t\treturn time - now;\n\t}\n\n\tpublic void clearTime() {\n\t\ttime = 0;\n\t}\n\n\tpublic void timeToNow() {\n\t\ttime = now;\n\t}\n\t\n\tprotected void diactivate() {\n\t\ttime = Float.MAX_VALUE;\n\t}\n\t\n\tprotected void onAdd() {}\n\t\n\tprotected void onRemove() {}\n\n\tprivate static final String TIME = \"time\";\n\tprivate static final String ID = \"id\";\n\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tbundle.put( TIME, time );\n\t\tbundle.put( ID, id );\n\t}\n\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\ttime = bundle.getFloat( TIME );\n\t\tint incomingID = bundle.getInt( ID );\n\t\tif (Actor.findById(incomingID) == null){\n\t\t\tid = incomingID;\n\t\t} else {\n\t\t\tid = nextID++;\n\t\t}\n\t}\n\n\tpublic int id() {\n\t\tif (id > 0) {\n\t\t\treturn id;\n\t\t} else {\n\t\t\treturn (id = nextID++);\n\t\t}\n\t}\n\n\t// **********************\n\t// *** Static members ***\n\t// **********************\n\t\n\tprivate static HashSet<Actor> all = new HashSet<>();\n\tprivate static HashSet<Char> chars = new HashSet<>();\n\tprivate static volatile Actor current;\n\n\tprivate static SparseArray<Actor> ids = new SparseArray<>();\n\tprivate static int nextID = 1;\n\n\tprivate static float now = 0;\n\t\n\tpublic static float now(){\n\t\treturn now;\n\t}\n\t\n\tpublic static synchronized void clear() {\n\t\t\n\t\tnow = 0;\n\n\t\tall.clear();\n\t\tchars.clear();\n\n\t\tids.clear();\n\t}\n\n\tpublic static synchronized void fixTime() {\n\t\t\n\t\tif (all.isEmpty()) return;\n\t\t\n\t\tfloat min = Float.MAX_VALUE;\n\t\tfor (Actor a : all) {\n\t\t\tif (a.time < min) {\n\t\t\t\tmin = a.time;\n\t\t\t}\n\t\t}\n\n\t\t//Only pull everything back by whole numbers\n\t\t//So that turns always align with a whole number\n\t\tmin = (int)min;\n\t\tfor (Actor a : all) {\n\t\t\ta.time -= min;\n\t\t}\n\n\t\tif (Dungeon.hero != null && all.contains( Dungeon.hero )) {\n\t\t\tStatistics.duration += min;\n\t\t}\n\t\tnow -= min;\n\t}\n\t\n\tpublic static void init() {\n\t\t\n\t\tadd( Dungeon.hero );\n\t\t\n\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\tadd( mob );\n\t\t}\n\n\t\t//mobs need to remember their targets after every actor is added\n\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\tmob.restoreEnemy();\n\t\t}\n\t\t\n\t\tfor (Blob blob : Dungeon.level.blobs.values()) {\n\t\t\tadd( blob );\n\t\t}\n\t\t\n\t\tcurrent = null;\n\t}\n\n\tprivate static final String NEXTID = \"nextid\";\n\n\tpublic static void storeNextID( Bundle bundle){\n\t\tbundle.put( NEXTID, nextID );\n\t}\n\n\tpublic static void restoreNextID( Bundle bundle){\n\t\tnextID = bundle.getInt( NEXTID );\n\t}\n\n\tpublic static void resetNextID(){\n\t\tnextID = 1;\n\t}\n\n\t/*protected*/public void next() {\n\t\tif (current == this) {\n\t\t\tcurrent = null;\n\t\t}\n\t}\n\n\tpublic static boolean processing(){\n\t\treturn current != null;\n\t}\n\n\tpublic static int curActorPriority() {\n\t\treturn current != null ? current.actPriority : DEFAULT;\n\t}\n\t\n\tpublic static boolean keepActorThreadAlive = true;\n\t\n\tpublic static void process() {\n\t\t\n\t\tboolean doNext;\n\t\tboolean interrupted = false;\n\n\t\tdo {\n\t\t\t\n\t\t\tcurrent = null;\n\t\t\tif (!interrupted) {\n\t\t\t\tfloat earliest = Float.MAX_VALUE;\n\n\t\t\t\tfor (Actor actor : all) {\n\t\t\t\t\t\n\t\t\t\t\t//some actors will always go before others if time is equal.\n\t\t\t\t\tif (actor.time < earliest ||\n\t\t\t\t\t\t\tactor.time == earliest && (current == null || actor.actPriority > current.actPriority)) {\n\t\t\t\t\t\tearliest = actor.time;\n\t\t\t\t\t\tcurrent = actor;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (current != null) {\n\n\t\t\t\tnow = current.time;\n\t\t\t\tActor acting = current;\n\n\t\t\t\tif (acting instanceof Char && ((Char) acting).sprite != null) {\n\t\t\t\t\t// If it's character's turn to act, but its sprite\n\t\t\t\t\t// is moving, wait till the movement is over\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsynchronized (((Char)acting).sprite) {\n\t\t\t\t\t\t\tif (((Char)acting).sprite.isMoving) {\n\t\t\t\t\t\t\t\t((Char) acting).sprite.wait();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\tinterrupted = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tinterrupted = interrupted || Thread.interrupted();\n\t\t\t\t\n\t\t\t\tif (interrupted){\n\t\t\t\t\tdoNext = false;\n\t\t\t\t\tcurrent = null;\n\t\t\t\t} else {\n\t\t\t\t\tdoNext = acting.act();\n\t\t\t\t\tif (doNext && (Dungeon.hero == null || !Dungeon.hero.isAlive())) {\n\t\t\t\t\t\tdoNext = false;\n\t\t\t\t\t\tcurrent = null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdoNext = false;\n\t\t\t}\n\n\t\t\tif (!doNext){\n\t\t\t\tsynchronized (Thread.currentThread()) {\n\t\t\t\t\t\n\t\t\t\t\tinterrupted = interrupted || Thread.interrupted();\n\t\t\t\t\t\n\t\t\t\t\tif (interrupted){\n\t\t\t\t\t\tcurrent = null;\n\t\t\t\t\t\tinterrupted = false;\n\t\t\t\t\t}\n\n\t\t\t\t\t//signals to the gamescene that actor processing is finished for now\n\t\t\t\t\tThread.currentThread().notify();\n\t\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\tThread.currentThread().wait();\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\tinterrupted = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t} while (keepActorThreadAlive);\n\t}\n\t\n\tpublic static void add( Actor actor ) {\n\t\tadd( actor, now );\n\t}\n\t\n\tpublic static void addDelayed( Actor actor, float delay ) {\n\t\tadd( actor, now + Math.max(delay, 0) );\n\t}\n\t\n\tprivate static synchronized void add( Actor actor, float time ) {\n\t\t\n\t\tif (all.contains( actor )) {\n\t\t\treturn;\n\t\t}\n\n\t\tids.put( actor.id(), actor );\n\n\t\tall.add( actor );\n\t\tactor.time += time;\n\t\tactor.onAdd();\n\t\t\n\t\tif (actor instanceof Char) {\n\t\t\tChar ch = (Char)actor;\n\t\t\tchars.add( ch );\n\t\t\tfor (Buff buff : ch.buffs()) {\n\t\t\t\tadd(buff);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static synchronized void remove( Actor actor ) {\n\t\t\n\t\tif (actor != null) {\n\t\t\tall.remove( actor );\n\t\t\tchars.remove( actor );\n\t\t\tactor.onRemove();\n\n\t\t\tif (actor.id > 0) {\n\t\t\t\tids.remove( actor.id );\n\t\t\t}\n\t\t}\n\t}\n\n\t//'freezes' a character in time for a specified amount of time\n\t//USE CAREFULLY! Manipulating time like this is useful for some gameplay effects but is tricky\n\tpublic static void delayChar( Char ch, float time ){\n\t\tch.spendConstant(time);\n\t\tfor (Buff b : ch.buffs()){\n\t\t\tb.spendConstant(time);\n\t\t}\n\t}\n\t\n\tpublic static synchronized Char findChar( int pos ) {\n\t\tfor (Char ch : chars){\n\t\t\tif (ch.pos == pos)\n\t\t\t\treturn ch;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static synchronized Actor findById( int id ) {\n\t\treturn ids.get( id );\n\t}\n\n\tpublic static synchronized HashSet<Actor> all() {\n\t\treturn new HashSet<>(all);\n\t}\n\n\tpublic static synchronized HashSet<Char> chars() { return new HashSet<>(chars); }\n}" }, { "identifier": "Buff", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Buff.java", "snippet": "public class Buff extends Actor {\n\t\n\tpublic Char target;\n\n\t{\n\t\tactPriority = BUFF_PRIO; //low priority, towards the end of a turn\n\t}\n\n\t//determines how the buff is announced when it is shown.\n\tpublic enum buffType {POSITIVE, NEGATIVE, NEUTRAL}\n\tpublic buffType type = buffType.NEUTRAL;\n\t\n\t//whether or not the buff announces its name\n\tpublic boolean announced = false;\n\n\t//whether a buff should persist through revive effects for the hero\n\tpublic boolean revivePersists = false;\n\t\n\tprotected HashSet<Class> resistances = new HashSet<>();\n\t\n\tpublic HashSet<Class> resistances() {\n\t\treturn new HashSet<>(resistances);\n\t}\n\t\n\tprotected HashSet<Class> immunities = new HashSet<>();\n\t\n\tpublic HashSet<Class> immunities() {\n\t\treturn new HashSet<>(immunities);\n\t}\n\t\n\tpublic boolean attachTo( Char target ) {\n\n\t\tif (target.isImmune( getClass() )) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tthis.target = target;\n\n\t\tif (target.add( this )){\n\t\t\tif (target.sprite != null) fx( true );\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.target = null;\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic void detach() {\n\t\tif (target.remove( this ) && target.sprite != null) fx( false );\n\t}\n\t\n\t@Override\n\tpublic boolean act() {\n\t\tdiactivate();\n\t\treturn true;\n\t}\n\t\n\tpublic int icon() {\n\t\treturn BuffIndicator.NONE;\n\t}\n\n\t//some buffs may want to tint the base texture color of their icon\n\tpublic void tintIcon( Image icon ){\n\t\t//do nothing by default\n\t}\n\n\t//percent (0-1) to fade out out the buff icon, usually if buff is expiring\n\tpublic float iconFadePercent(){\n\t\treturn 0;\n\t}\n\n\t//text to display on large buff icons in the desktop UI\n\tpublic String iconTextDisplay(){\n\t\treturn \"\";\n\t}\n\n\t//visual effect usually attached to the sprite of the character the buff is attacked to\n\tpublic void fx(boolean on) {\n\t\t//do nothing by default\n\t}\n\n\tpublic String heroMessage(){\n\t\tString msg = Messages.get(this, \"heromsg\");\n\t\tif (msg.isEmpty()) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn msg;\n\t\t}\n\t}\n\n\tpublic String name() {\n\t\treturn Messages.get(this, \"name\");\n\t}\n\n\tpublic String desc(){\n\t\treturn Messages.get(this, \"desc\");\n\t}\n\n\t//to handle the common case of showing how many turns are remaining in a buff description.\n\tprotected String dispTurns(float input){\n\t\treturn Messages.decimalFormat(\"#.##\", input);\n\t}\n\n\t//buffs act after the hero, so it is often useful to use cooldown+1 when display buff time remaining\n\tpublic float visualcooldown(){\n\t\treturn cooldown()+1f;\n\t}\n\n\t//creates a fresh instance of the buff and attaches that, this allows duplication.\n\tpublic static<T extends Buff> T append( Char target, Class<T> buffClass ) {\n\t\tT buff = Reflection.newInstance(buffClass);\n\t\tbuff.attachTo( target );\n\t\treturn buff;\n\t}\n\n\tpublic static<T extends FlavourBuff> T append( Char target, Class<T> buffClass, float duration ) {\n\t\tT buff = append( target, buffClass );\n\t\tbuff.spend( duration * target.resist(buffClass) );\n\t\treturn buff;\n\t}\n\n\t//same as append, but prevents duplication.\n\tpublic static<T extends Buff> T affect( Char target, Class<T> buffClass ) {\n\t\tT buff = target.buff( buffClass );\n\t\tif (buff != null) {\n\t\t\treturn buff;\n\t\t} else {\n\t\t\treturn append( target, buffClass );\n\t\t}\n\t}\n\t\n\tpublic static<T extends FlavourBuff> T affect( Char target, Class<T> buffClass, float duration ) {\n\t\tT buff = affect( target, buffClass );\n\t\tbuff.spend( duration * target.resist(buffClass) );\n\t\treturn buff;\n\t}\n\n\t//postpones an already active buff, or creates & attaches a new buff and delays that.\n\tpublic static<T extends FlavourBuff> T prolong( Char target, Class<T> buffClass, float duration ) {\n\t\tT buff = affect( target, buffClass );\n\t\tbuff.postpone( duration * target.resist(buffClass) );\n\t\treturn buff;\n\t}\n\n\tpublic static<T extends CounterBuff> T count( Char target, Class<T> buffclass, float count ) {\n\t\tT buff = affect( target, buffclass );\n\t\tbuff.countUp( count );\n\t\treturn buff;\n\t}\n\t\n\tpublic static void detach( Char target, Class<? extends Buff> cl ) {\n\t\tfor ( Buff b : target.buffs( cl )){\n\t\t\tb.detach();\n\t\t}\n\t}\n}" }, { "identifier": "Belongings", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/hero/Belongings.java", "snippet": "public class Belongings implements Iterable<Item> {\n\n\tprivate Hero owner;\n\n\tpublic static class Backpack extends Bag {\n\t\t{\n\t\t\timage = ItemSpriteSheet.BACKPACK;\n\t\t}\n\t\tpublic int capacity(){\n\t\t\tint cap = super.capacity();\n\t\t\tfor (Item item : items){\n\t\t\t\tif (item instanceof Bag){\n\t\t\t\t\tcap++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (Dungeon.hero != null && Dungeon.hero.belongings.secondWep != null){\n\t\t\t\t//secondary weapons still occupy an inv. slot\n\t\t\t\tcap--;\n\t\t\t}\n\t\t\treturn cap;\n\t\t}\n\t}\n\n\tpublic Backpack backpack;\n\t\n\tpublic Belongings( Hero owner ) {\n\t\tthis.owner = owner;\n\t\t\n\t\tbackpack = new Backpack();\n\t\tbackpack.owner = owner;\n\t}\n\n\tpublic KindOfWeapon weapon = null;\n\tpublic Armor armor = null;\n\tpublic Artifact artifact = null;\n\tpublic KindofMisc misc = null;\n\tpublic Ring ring = null;\n\n\t//used when thrown weapons temporary become the current weapon\n\tpublic KindOfWeapon thrownWeapon = null;\n\n\t//used to ensure that the duelist always uses the weapon she's using the ability of\n\tpublic KindOfWeapon abilityWeapon = null;\n\n\t//used by the champion subclass\n\tpublic KindOfWeapon secondWep = null;\n\n\t//*** these accessor methods are so that worn items can be affected by various effects/debuffs\n\t// we still want to access the raw equipped items in cases where effects should be ignored though,\n\t// such as when equipping something, showing an interface, or dealing with items from a dead hero\n\n\t//normally the primary equipped weapon, but can also be a thrown weapon or an ability's weapon\n\tpublic KindOfWeapon attackingWeapon(){\n\t\tif (thrownWeapon != null) return thrownWeapon;\n\t\tif (abilityWeapon != null) return abilityWeapon;\n\t\treturn weapon();\n\t}\n\n\tpublic KindOfWeapon weapon(){\n\t\tboolean lostInvent = owner != null && owner.buff(LostInventory.class) != null;\n\t\tif (!lostInvent || (weapon != null && weapon.keptThroughLostInventory())){\n\t\t\treturn weapon;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Armor armor(){\n\t\tboolean lostInvent = owner != null && owner.buff(LostInventory.class) != null;\n\t\tif (!lostInvent || (armor != null && armor.keptThroughLostInventory())){\n\t\t\treturn armor;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Artifact artifact(){\n\t\tboolean lostInvent = owner != null && owner.buff(LostInventory.class) != null;\n\t\tif (!lostInvent || (artifact != null && artifact.keptThroughLostInventory())){\n\t\t\treturn artifact;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic KindofMisc misc(){\n\t\tboolean lostInvent = owner != null && owner.buff(LostInventory.class) != null;\n\t\tif (!lostInvent || (misc != null && misc.keptThroughLostInventory())){\n\t\t\treturn misc;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Ring ring(){\n\t\tboolean lostInvent = owner != null && owner.buff(LostInventory.class) != null;\n\t\tif (!lostInvent || (ring != null && ring.keptThroughLostInventory())){\n\t\t\treturn ring;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic KindOfWeapon secondWep(){\n\t\tboolean lostInvent = owner != null && owner.buff(LostInventory.class) != null;\n\t\tif (!lostInvent || (secondWep != null && secondWep.keptThroughLostInventory())){\n\t\t\treturn secondWep;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t// ***\n\t\n\tprivate static final String WEAPON\t\t= \"weapon\";\n\tprivate static final String ARMOR\t\t= \"armor\";\n\tprivate static final String ARTIFACT = \"artifact\";\n\tprivate static final String MISC = \"misc\";\n\tprivate static final String RING = \"ring\";\n\n\tprivate static final String SECOND_WEP = \"second_wep\";\n\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\t\n\t\tbackpack.storeInBundle( bundle );\n\t\t\n\t\tbundle.put( WEAPON, weapon );\n\t\tbundle.put( ARMOR, armor );\n\t\tbundle.put( ARTIFACT, artifact );\n\t\tbundle.put( MISC, misc );\n\t\tbundle.put( RING, ring );\n\t\tbundle.put( SECOND_WEP, secondWep );\n\t}\n\t\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\t\n\t\tbackpack.clear();\n\t\tbackpack.restoreFromBundle( bundle );\n\t\t\n\t\tweapon = (KindOfWeapon) bundle.get(WEAPON);\n\t\tif (weapon() != null) weapon().activate(owner);\n\t\t\n\t\tarmor = (Armor)bundle.get( ARMOR );\n\t\tif (armor() != null) armor().activate( owner );\n\n\t\tartifact = (Artifact) bundle.get(ARTIFACT);\n\t\tif (artifact() != null) artifact().activate(owner);\n\n\t\tmisc = (KindofMisc) bundle.get(MISC);\n\t\tif (misc() != null) misc().activate( owner );\n\n\t\tring = (Ring) bundle.get(RING);\n\t\tif (ring() != null) ring().activate( owner );\n\n\t\tsecondWep = (KindOfWeapon) bundle.get(SECOND_WEP);\n\t\tif (secondWep() != null) secondWep().activate(owner);\n\t}\n\t\n\tpublic static void preview( GamesInProgress.Info info, Bundle bundle ) {\n\t\tif (bundle.contains( ARMOR )){\n\t\t\tArmor armor = ((Armor)bundle.get( ARMOR ));\n\t\t\tif (armor instanceof ClassArmor){\n\t\t\t\tinfo.armorTier = 6;\n\t\t\t} else {\n\t\t\t\tinfo.armorTier = armor.tier;\n\t\t\t}\n\t\t} else {\n\t\t\tinfo.armorTier = 0;\n\t\t}\n\t}\n\n\t//ignores lost inventory debuff\n\tpublic ArrayList<Bag> getBags(){\n\t\tArrayList<Bag> result = new ArrayList<>();\n\n\t\tresult.add(backpack);\n\n\t\tfor (Item i : this){\n\t\t\tif (i instanceof Bag){\n\t\t\t\tresult.add((Bag)i);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic<T extends Item> T getItem( Class<T> itemClass ) {\n\n\t\tboolean lostInvent = owner != null && owner.buff(LostInventory.class) != null;\n\n\t\tfor (Item item : this) {\n\t\t\tif (itemClass.isInstance( item )) {\n\t\t\t\tif (!lostInvent || item.keptThroughLostInventory()) {\n\t\t\t\t\treturn (T) item;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\n\tpublic<T extends Item> ArrayList<T> getAllItems( Class<T> itemClass ) {\n\t\tArrayList<T> result = new ArrayList<>();\n\n\t\tboolean lostInvent = owner != null && owner.buff(LostInventory.class) != null;\n\n\t\tfor (Item item : this) {\n\t\t\tif (itemClass.isInstance( item )) {\n\t\t\t\tif (!lostInvent || item.keptThroughLostInventory()) {\n\t\t\t\t\tresult.add((T) item);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\t\n\tpublic boolean contains( Item contains ){\n\n\t\tboolean lostInvent = owner != null && owner.buff(LostInventory.class) != null;\n\t\t\n\t\tfor (Item item : this) {\n\t\t\tif (contains == item) {\n\t\t\t\tif (!lostInvent || item.keptThroughLostInventory()) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tpublic Item getSimilar( Item similar ){\n\n\t\tboolean lostInvent = owner != null && owner.buff(LostInventory.class) != null;\n\t\t\n\t\tfor (Item item : this) {\n\t\t\tif (similar != item && similar.isSimilar(item)) {\n\t\t\t\tif (!lostInvent || item.keptThroughLostInventory()) {\n\t\t\t\t\treturn item;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic ArrayList<Item> getAllSimilar( Item similar ){\n\t\tArrayList<Item> result = new ArrayList<>();\n\n\t\tboolean lostInvent = owner != null && owner.buff(LostInventory.class) != null;\n\t\t\n\t\tfor (Item item : this) {\n\t\t\tif (item != similar && similar.isSimilar(item)) {\n\t\t\t\tif (!lostInvent || item.keptThroughLostInventory()) {\n\t\t\t\t\tresult.add(item);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n\n\t//triggers when a run ends, so ignores lost inventory effects\n\tpublic void identify() {\n\t\tfor (Item item : this) {\n\t\t\titem.identify(false);\n\t\t}\n\t}\n\t\n\tpublic void observe() {\n\t\tif (weapon() != null) {\n\t\t\tweapon().identify();\n\t\t\tBadges.validateItemLevelAquired(weapon());\n\t\t}\n\t\tif (armor() != null) {\n\t\t\tarmor().identify();\n\t\t\tBadges.validateItemLevelAquired(armor());\n\t\t}\n\t\tif (artifact() != null) {\n\t\t\tartifact().identify();\n\t\t\tBadges.validateItemLevelAquired(artifact());\n\t\t}\n\t\tif (misc() != null) {\n\t\t\tmisc().identify();\n\t\t\tBadges.validateItemLevelAquired(misc());\n\t\t}\n\t\tif (ring() != null) {\n\t\t\tring().identify();\n\t\t\tBadges.validateItemLevelAquired(ring());\n\t\t}\n\t\tif (secondWep() != null){\n\t\t\tsecondWep().identify();\n\t\t\tBadges.validateItemLevelAquired(secondWep());\n\t\t}\n\t\tfor (Item item : backpack) {\n\t\t\tif (item instanceof EquipableItem || item instanceof Wand) {\n\t\t\t\titem.cursedKnown = true;\n\t\t\t}\n\t\t}\n\t\tItem.updateQuickslot();\n\t}\n\t\n\tpublic void uncurseEquipped() {\n\t\tScrollOfRemoveCurse.uncurse( owner, armor(), weapon(), artifact(), misc(), ring(), secondWep());\n\t}\n\t\n\tpublic Item randomUnequipped() {\n\t\tif (owner.buff(LostInventory.class) != null) return null;\n\n\t\treturn Random.element( backpack.items );\n\t}\n\t\n\tpublic int charge( float charge ) {\n\t\t\n\t\tint count = 0;\n\t\t\n\t\tfor (Wand.Charger charger : owner.buffs(Wand.Charger.class)){\n\t\t\tcharger.gainCharge(charge);\n\t\t\tcount++;\n\t\t}\n\t\t\n\t\treturn count;\n\t}\n\n\t@Override\n\tpublic Iterator<Item> iterator() {\n\t\treturn new ItemIterator();\n\t}\n\t\n\tprivate class ItemIterator implements Iterator<Item> {\n\n\t\tprivate int index = 0;\n\t\t\n\t\tprivate Iterator<Item> backpackIterator = backpack.iterator();\n\t\t\n\t\tprivate Item[] equipped = {weapon, armor, artifact, misc, ring, secondWep};\n\t\tprivate int backpackIndex = equipped.length;\n\t\t\n\t\t@Override\n\t\tpublic boolean hasNext() {\n\t\t\t\n\t\t\tfor (int i=index; i < backpackIndex; i++) {\n\t\t\t\tif (equipped[i] != null) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn backpackIterator.hasNext();\n\t\t}\n\n\t\t@Override\n\t\tpublic Item next() {\n\t\t\t\n\t\t\twhile (index < backpackIndex) {\n\t\t\t\tItem item = equipped[index++];\n\t\t\t\tif (item != null) {\n\t\t\t\t\treturn item;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn backpackIterator.next();\n\t\t}\n\n\t\t@Override\n\t\tpublic void remove() {\n\t\t\tswitch (index) {\n\t\t\tcase 0:\n\t\t\t\tequipped[0] = weapon = null;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tequipped[1] = armor = null;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tequipped[2] = artifact = null;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tequipped[3] = misc = null;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tequipped[4] = ring = null;\n\t\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\tequipped[5] = secondWep = null;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbackpackIterator.remove();\n\t\t\t}\n\t\t}\n\t}\n}" }, { "identifier": "Hero", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/hero/Hero.java", "snippet": "public class Hero extends Char {\n\n\t{\n\t\tactPriority = HERO_PRIO;\n\t\t\n\t\talignment = Alignment.ALLY;\n\t}\n\t\n\tpublic static final int MAX_LEVEL = 30;\n\n\tpublic static final int STARTING_STR = 10;\n\t\n\tprivate static final float TIME_TO_REST\t\t = 1f;\n\tprivate static final float TIME_TO_SEARCH\t = 2f;\n\tprivate static final float HUNGER_FOR_SEARCH\t= 6f;\n\t\n\tpublic HeroClass heroClass = HeroClass.ROGUE;\n\tpublic HeroSubClass subClass = HeroSubClass.NONE;\n\tpublic ArmorAbility armorAbility = null;\n\tpublic ArrayList<LinkedHashMap<Talent, Integer>> talents = new ArrayList<>();\n\tpublic LinkedHashMap<Talent, Talent> metamorphedTalents = new LinkedHashMap<>();\n\t\n\tprivate int attackSkill = 10;\n\tprivate int defenseSkill = 5;\n\n\tpublic boolean ready = false;\n\tpublic boolean damageInterrupt = true;\n\tpublic HeroAction curAction = null;\n\tpublic HeroAction lastAction = null;\n\n\tprivate Char enemy;\n\t\n\tpublic boolean resting = false;\n\t\n\tpublic Belongings belongings;\n\t\n\tpublic int STR;\n\t\n\tpublic float awareness;\n\t\n\tpublic int lvl = 1;\n\tpublic int exp = 0;\n\t\n\tpublic int HTBoost = 0;\n\t\n\tprivate ArrayList<Mob> visibleEnemies;\n\n\t//This list is maintained so that some logic checks can be skipped\n\t// for enemies we know we aren't seeing normally, resulting in better performance\n\tpublic ArrayList<Mob> mindVisionEnemies = new ArrayList<>();\n\n\tpublic Hero() {\n\t\tsuper();\n\n\t\tHP = HT = (Dungeon.isChallenged(Challenges.SUPERMAN)) ? 10 : 20;\n\t\tSTR = STARTING_STR;\n\t\t\n\t\tbelongings = new Belongings( this );\n\t\t\n\t\tvisibleEnemies = new ArrayList<>();\n\t}\n\t\n\tpublic void updateHT( boolean boostHP ){\n\t\tint curHT = HT;\n\n\t\tHT = (Dungeon.isChallenged(Challenges.SUPERMAN)) ? 10 : 20 + 5 * (lvl-1) + HTBoost;\n\t\tif (this.hasTalent(Talent.MAX_HEALTH)) {\n\t\t\tHT += 5*this.pointsInTalent(Talent.MAX_HEALTH);\n\t\t}\n\t\tfloat multiplier = RingOfMight.HTMultiplier(this);\n\t\tHT = Math.round(multiplier * HT);\n\t\t\n\t\tif (buff(ElixirOfMight.HTBoost.class) != null){\n\t\t\tHT += buff(ElixirOfMight.HTBoost.class).boost();\n\t\t}\n\n\t\tif (buff(ElixirOfTalent.ElixirOfTalentHTBoost.class) != null){\n\t\t\tHT += buff(ElixirOfTalent.ElixirOfTalentHTBoost.class).boost();\n\t\t}\n\t\t\n\t\tif (boostHP){\n\t\t\tHP += Math.max(HT - curHT, 0);\n\t\t}\n\t\tHP = Math.min(HP, HT);\n\t}\n\n\tpublic int STR() {\n\t\tint strBonus = 0;\n\n\t\tstrBonus += RingOfMight.strengthBonus( this );\n\t\t\n\t\tAdrenalineSurge buff = buff(AdrenalineSurge.class);\n\t\tif (buff != null){\n\t\t\tstrBonus += buff.boost();\n\t\t}\n\n\t\tif (hasTalent(Talent.STRONGMAN)){\n\t\t\tstrBonus += (int)Math.floor(STR * (0.03f + 0.05f*pointsInTalent(Talent.STRONGMAN)));\n\t\t}\n\n\t\treturn STR + strBonus;\n\t}\n\n\tpublic void onSTRGained() {\n\n\t}\n\n\tpublic void onSTRLost() {\n\n\t}\n\n\tprivate static final String CLASS = \"class\";\n\tprivate static final String SUBCLASS = \"subClass\";\n\tprivate static final String ABILITY = \"armorAbility\";\n\n\tprivate static final String ATTACK\t\t= \"attackSkill\";\n\tprivate static final String DEFENSE\t\t= \"defenseSkill\";\n\tprivate static final String STRENGTH\t= \"STR\";\n\tprivate static final String LEVEL\t\t= \"lvl\";\n\tprivate static final String EXPERIENCE\t= \"exp\";\n\tprivate static final String HTBOOST = \"htboost\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\n\t\tsuper.storeInBundle( bundle );\n\n\t\tbundle.put( CLASS, heroClass );\n\t\tbundle.put( SUBCLASS, subClass );\n\t\tbundle.put( ABILITY, armorAbility );\n\t\tTalent.storeTalentsInBundle( bundle, this );\n\t\t\n\t\tbundle.put( ATTACK, attackSkill );\n\t\tbundle.put( DEFENSE, defenseSkill );\n\t\t\n\t\tbundle.put( STRENGTH, STR );\n\t\t\n\t\tbundle.put( LEVEL, lvl );\n\t\tbundle.put( EXPERIENCE, exp );\n\t\t\n\t\tbundle.put( HTBOOST, HTBoost );\n\n\t\tbelongings.storeInBundle( bundle );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\n\t\tlvl = bundle.getInt( LEVEL );\n\t\texp = bundle.getInt( EXPERIENCE );\n\n\t\tHTBoost = bundle.getInt(HTBOOST);\n\n\t\tsuper.restoreFromBundle( bundle );\n\n\t\theroClass = bundle.getEnum( CLASS, HeroClass.class );\n\t\tsubClass = bundle.getEnum( SUBCLASS, HeroSubClass.class );\n\t\tarmorAbility = (ArmorAbility)bundle.get( ABILITY );\n\t\tTalent.restoreTalentsFromBundle( bundle, this );\n\t\t\n\t\tattackSkill = bundle.getInt( ATTACK );\n\t\tdefenseSkill = bundle.getInt( DEFENSE );\n\t\t\n\t\tSTR = bundle.getInt( STRENGTH );\n\n\t\tbelongings.restoreFromBundle( bundle );\n\t}\n\t\n\tpublic static void preview( GamesInProgress.Info info, Bundle bundle ) {\n\t\tinfo.level = bundle.getInt( LEVEL );\n\t\tinfo.str = bundle.getInt( STRENGTH );\n\t\tinfo.exp = bundle.getInt( EXPERIENCE );\n\t\tinfo.hp = bundle.getInt( Char.TAG_HP );\n\t\tinfo.ht = bundle.getInt( Char.TAG_HT );\n\t\tinfo.shld = bundle.getInt( Char.TAG_SHLD );\n\t\tinfo.heroClass = bundle.getEnum( CLASS, HeroClass.class );\n\t\tinfo.subClass = bundle.getEnum( SUBCLASS, HeroSubClass.class );\n\t\tBelongings.preview( info, bundle );\n\t}\n\n\tpublic boolean hasTalent( Talent talent ){\n\t\treturn pointsInTalent(talent) > 0;\n\t}\n\n\tpublic int pointsInTalent( Talent talent ){\n\t\tfor (LinkedHashMap<Talent, Integer> tier : talents){\n\t\t\tfor (Talent f : tier.keySet()){\n\t\t\t\tif (f == talent) return tier.get(f);\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\n\tpublic void upgradeTalent( Talent talent ){\n\t\tfor (LinkedHashMap<Talent, Integer> tier : talents){\n\t\t\tfor (Talent f : tier.keySet()){\n\t\t\t\tif (f == talent) tier.put(talent, tier.get(talent)+1);\n\t\t\t}\n\t\t}\n\t\tTalent.onTalentUpgraded(this, talent);\n\t}\n\n\tpublic int talentPointsSpent(int tier){\n\t\tint total = 0;\n\t\tfor (int i : talents.get(tier-1).values()){\n\t\t\ttotal += i;\n\t\t}\n\t\treturn total;\n\t}\n\n\tpublic int talentPointsAvailable(int tier){\n\t\tif (lvl < (Talent.tierLevelThresholds[tier] - 1)\n\t\t\t|| (tier == 3 && subClass == HeroSubClass.NONE)\n\t\t\t|| (tier == 4 && armorAbility == null)) {\n\t\t\treturn 0;\n\t\t} else if (lvl >= Talent.tierLevelThresholds[tier+1]){\n\t\t\treturn Talent.tierLevelThresholds[tier+1] - Talent.tierLevelThresholds[tier] - talentPointsSpent(tier) + bonusTalentPoints(tier);\n\t\t} else {\n\t\t\treturn 1 + lvl - Talent.tierLevelThresholds[tier] - talentPointsSpent(tier) + bonusTalentPoints(tier);\n\t\t}\n\t}\n\n\tpublic int bonusTalentPoints(int tier){\n\t\tint bonusPoints = 0;\n\t\tif (lvl < (Talent.tierLevelThresholds[tier]-1)\n\t\t\t\t|| (tier == 3 && subClass == HeroSubClass.NONE)\n\t\t\t\t|| (tier == 4 && armorAbility == null)) {\n\t\t\treturn 0;\n\t\t} else if (buff(PotionOfDivineInspiration.DivineInspirationTracker.class) != null\n\t\t\t\t\t&& buff(PotionOfDivineInspiration.DivineInspirationTracker.class).isBoosted(tier)) {\n\t\t\tbonusPoints += 2;\n\t\t}\n\t\tif (tier == 3 && buff(ElixirOfTalent.BonusTalentTracker.class) != null) {\n\t\t\tbonusPoints += 4;\n\t\t}\n\t\treturn bonusPoints;\n\t}\n\t\n\tpublic String className() {\n\t\treturn subClass == null || subClass == HeroSubClass.NONE ? heroClass.title() : subClass.title();\n\t}\n\n\t@Override\n\tpublic String name(){\n\t\treturn className();\n\t}\n\n\t@Override\n\tpublic void hitSound(float pitch) {\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\tbelongings.attackingWeapon().hitSound(pitch);\n\t\t} else if (RingOfForce.getBuffedBonus(this, RingOfForce.Force.class) > 0) {\n\t\t\t//pitch deepens by 2.5% (additive) per point of strength, down to 75%\n\t\t\tsuper.hitSound( pitch * GameMath.gate( 0.75f, 1.25f - 0.025f*STR(), 1f) );\n\t\t} else {\n\t\t\tsuper.hitSound(pitch * 1.1f);\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean blockSound(float pitch) {\n\t\tif ( belongings.weapon() != null && belongings.weapon().defenseFactor(this) >= 4 ){\n\t\t\tSample.INSTANCE.play( Assets.Sounds.HIT_PARRY, 1, pitch);\n\t\t\treturn true;\n\t\t}\n\t\treturn super.blockSound(pitch);\n\t}\n\n\tpublic void live() {\n\t\tfor (Buff b : buffs()){\n\t\t\tif (!b.revivePersists) b.detach();\n\t\t}\n\t\tBuff.affect( this, Regeneration.class );\n\t\tBuff.affect( this, Hunger.class );\n\t}\n\t\n\tpublic int tier() {\n\t\tArmor armor = belongings.armor();\n\t\tif (armor instanceof ClassArmor){\n\t\t\treturn 6;\n\t\t} else if (armor != null){\n\t\t\treturn armor.tier;\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tpublic boolean shoot( Char enemy, MissileWeapon wep ) {\n\n\t\tthis.enemy = enemy;\n\t\tboolean wasEnemy = enemy.alignment == Alignment.ENEMY\n\t\t\t\t|| (enemy instanceof Mimic && enemy.alignment == Alignment.NEUTRAL);\n\n\t\t//temporarily set the hero's weapon to the missile weapon being used\n\t\t//TODO improve this!\n\t\tbelongings.thrownWeapon = wep;\n\t\tboolean hit = attack( enemy );\n\t\tInvisibility.dispel();\n\t\tbelongings.thrownWeapon = null;\n\n\t\tif (hit && subClass == HeroSubClass.GLADIATOR && wasEnemy){\n\t\t\tBuff.affect( this, Combo.class ).hit( enemy );\n\t\t}\n\n\t\tif (hit && heroClass == HeroClass.DUELIST && wasEnemy){\n\t\t\tBuff.affect( this, Sai.ComboStrikeTracker.class).addHit();\n\t\t}\n\n\t\treturn hit;\n\t}\n\t\n\t@Override\n\tpublic int attackSkill( Char target ) {\n\t\tKindOfWeapon wep = belongings.attackingWeapon();\n\t\t\n\t\tfloat accuracy = 1;\n\t\taccuracy *= RingOfAccuracy.accuracyMultiplier( this );\n\n\t\tif (Dungeon.isChallenged(Challenges.SUPERMAN)) {\n\t\t\taccuracy *= 2;\n\t\t}\n\t\t\n\t\tif (wep instanceof MissileWeapon && !(wep instanceof Gun.Bullet)){ //총탄을 제외한 투척 무기의 정확성\n\t\t\tif (Dungeon.level.adjacent( pos, target.pos )) {\n\t\t\t\taccuracy *= (0.5f + 0.2f*pointsInTalent(Talent.POINT_BLANK));\n\t\t\t} else {\n\t\t\t\taccuracy *= 1.5f;\n\t\t\t}\n\t\t}\n\n\t\tif (wep instanceof Gun.Bullet) {\t//총탄의 정확성\n\t\t\tif (Dungeon.level.adjacent( pos, target.pos )) {\n\t\t\t\tif (wep instanceof SG.SGBullet) {\n\t\t\t\t\taccuracy *= 10f; //산탄총은 기본적으로 0.2배의 명중률 보정이 있으며, 이를 10배함으로써 2배의 명중률을 가짐\n\t\t\t\t} else {\n\t\t\t\t\taccuracy *= (0.5f + 0.2f*pointsInTalent(Talent.POINT_BLANK));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hero.hasTalent(Talent.INEVITABLE_DEATH) && hero.buff(RouletteOfDeath.class) != null && hero.buff(RouletteOfDeath.class).timeToDeath()) {\n\t\t\t\taccuracy *= 1 + hero.pointsInTalent(Talent.INEVITABLE_DEATH);\n\t\t\t}\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.GUNSLINGER && hero.justMoved && wep instanceof MissileWeapon) {\n\t\t\taccuracy *= 0.25f*(1+0.5f*hero.pointsInTalent(Talent.MOVING_SHOT));\n\t\t}\n\n\t\tif (buff(Scimitar.SwordDance.class) != null){\n\t\t\taccuracy *= 1.25f;\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.ACC_ENHANCE)) {\n\t\t\taccuracy *= 1 + 0.05f * hero.pointsInTalent(Talent.ACC_ENHANCE);\n\t\t}\n\n\t\tif (hero.buff(LargeSword.LargeSwordBuff.class) != null) {\n\t\t\taccuracy *= hero.buff(LargeSword.LargeSwordBuff.class).getAccuracyFactor();\n\t\t}\n\n\t\tif (hero.buff(UnholyBible.Demon.class) != null) {\n\t\t\taccuracy = INFINITE_ACCURACY;\n\t\t}\n\n\t\tif (hero.buff(MeleeWeapon.DashAttack.class) != null) {\n\t\t\taccuracy = INFINITE_ACCURACY;\n\t\t}\n\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\treturn (int)(attackSkill * accuracy * wep.accuracyFactor( this, target ));\n\t\t} else {\n\t\t\treturn (int)(attackSkill * accuracy);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic int defenseSkill( Char enemy ) {\n\n\t\tif (buff(Combo.ParryTracker.class) != null){\n\t\t\tif (canAttack(enemy) && !isCharmedBy(enemy)){\n\t\t\t\tBuff.affect(this, Combo.RiposteTracker.class).enemy = enemy;\n\t\t\t}\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\n\t\tif (buff(RoundShield.GuardTracker.class) != null){\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\n\t\tif (buff(Talent.ParryTracker.class) != null){\n\t\t\tif (canAttack(enemy) && !isCharmedBy(enemy)){\n\t\t\t\tBuff.affect(this, Talent.RiposteTracker.class).enemy = enemy;\n\t\t\t}\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\n\t\tif (buff(Nunchaku.ParryTracker.class) != null){\n\t\t\tif (canAttack(enemy) && !isCharmedBy(enemy)){\n\t\t\t\tBuff.affect(this, Nunchaku.RiposteTracker.class).enemy = enemy;\n\t\t\t}\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\t\t\n\t\tfloat evasion = defenseSkill;\n\t\t\n\t\tevasion *= RingOfEvasion.evasionMultiplier( this );\n\n\t\tif (hero.hasTalent(Talent.SWIFT_MOVEMENT)) {\n\t\t\tevasion += hero.STR()-10;\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.SUPERMAN)) {\n\t\t\tevasion *= 3;\n\t\t}\n\n\t\tif (buff(Talent.RestoredAgilityTracker.class) != null){\n\t\t\tif (pointsInTalent(Talent.LIQUID_AGILITY) == 1){\n\t\t\t\tevasion *= 4f;\n\t\t\t} else if (pointsInTalent(Talent.LIQUID_AGILITY) == 2){\n\t\t\t\treturn INFINITE_EVASION;\n\t\t\t}\n\t\t}\n\n\t\tif (buff(Quarterstaff.DefensiveStance.class) != null){\n\t\t\tevasion *= 3;\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.EVA_ENHANCE)) {\n\t\t\tevasion *= 1 + 0.05f * hero.pointsInTalent(Talent.EVA_ENHANCE);\n\t\t}\n\n\t\tif (hero.buff(UnholyBible.Demon.class) != null) {\n\t\t\tevasion /= 2;\n\t\t}\n\t\t\n\t\tif (paralysed > 0) {\n\t\t\tevasion /= 2;\n\t\t}\n\n\t\tif (belongings.armor() != null) {\n\t\t\tevasion = belongings.armor().evasionFactor(this, evasion);\n\t\t}\n\n\t\treturn Math.round(evasion);\n\t}\n\n\t@Override\n\tpublic String defenseVerb() {\n\t\tCombo.ParryTracker parry = buff(Combo.ParryTracker.class);\n\t\tif (parry != null){\n\t\t\tparry.parried = true;\n\t\t\tif (buff(Combo.class).getComboCount() < 9 || pointsInTalent(Talent.ENHANCED_COMBO) < 2){\n\t\t\t\tparry.detach();\n\t\t\t}\n\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t}\n\n\t\tif (buff(RoundShield.GuardTracker.class) != null){\n\t\t\tbuff(RoundShield.GuardTracker.class).detach();\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1, Random.Float(0.96f, 1.05f));\n\t\t\treturn Messages.get(RoundShield.GuardTracker.class, \"guarded\");\n\t\t}\n\n\t\tif (buff(MonkEnergy.MonkAbility.Focus.FocusActivation.class) != null){\n\t\t\tbuff(MonkEnergy.MonkAbility.Focus.FocusActivation.class).detach();\n\t\t\tif (sprite != null && sprite.visible) {\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1, Random.Float(0.96f, 1.05f));\n\t\t\t}\n\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t}\n\n\t\tTalent.ParryTracker parryTracker = buff(Talent.ParryTracker.class);\n\t\tif (hasTalent(Talent.PARRY)) {\n\t\t\tif (parryTracker != null) {\n\t\t\t\tparryTracker.detach();\n\t\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t\t}\n\t\t}\n\n\t\tNunchaku.ParryTracker nunchakuParry = buff(Nunchaku.ParryTracker.class);\n\t\tif (nunchakuParry != null){\n\t\t\tnunchakuParry.parried = true;\n\t\t\tif (sprite != null && sprite.visible) {\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1, Random.Float(0.96f, 1.05f));\n\t\t\t}\n\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t}\n\n\t\tRouletteOfDeath roulette = buff(RouletteOfDeath.class);\n\t\tif (hasTalent(Talent.HONORABLE_SHOT) && roulette != null && roulette.overHalf()) {\n\t\t\tBuff.prolong(hero, Talent.HonorableShotTracker.class, 1f);\n\t\t}\n\n\t\treturn super.defenseVerb();\n\t}\n\n\t@Override\n\tpublic int drRoll() {\n\t\tint dr = super.drRoll();\n\n\t\tif (belongings.armor() != null) {\n\t\t\tint armDr = Random.NormalIntRange( belongings.armor().DRMin(), belongings.armor().DRMax());\n\t\t\tif (STR() < belongings.armor().STRReq()){\n\t\t\t\tarmDr -= 2*(belongings.armor().STRReq() - STR());\n\t\t\t}\n\t\t\tif (armDr > 0) dr += armDr;\n\t\t}\n\t\tif (belongings.weapon() != null && !RingOfForce.fightingUnarmed(this)) {\n\t\t\tint wepDr = Random.NormalIntRange( 0 , belongings.weapon().defenseFactor( this ) );\n\t\t\tif (STR() < ((Weapon)belongings.weapon()).STRReq()){\n\t\t\t\twepDr -= 2*(((Weapon)belongings.weapon()).STRReq() - STR());\n\t\t\t}\n\t\t\tif (wepDr > 0) dr += wepDr;\n\t\t}\n\n\t\tif (buff(HoldFast.class) != null){\n\t\t\tdr += buff(HoldFast.class).armorBonus();\n\t\t}\n\n\t\tReinforcedArmor.ReinforcedArmorTracker rearmor = hero.buff(ReinforcedArmor.ReinforcedArmorTracker.class);\n\t\tif (rearmor != null) dr += rearmor.blockingRoll();\n\t\t\n\t\treturn dr;\n\t}\n\t\n\t@Override\n\tpublic int damageRoll() {\n\t\tKindOfWeapon wep = belongings.attackingWeapon();\n\t\tint dmg;\n\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\tdmg = wep.damageRoll( this );\n\n\t\t\tif (!(wep instanceof MissileWeapon)) dmg += RingOfForce.armedDamageBonus(this);\n\t\t} else {\n\t\t\tdmg = RingOfForce.damageRoll(this);\n\t\t\tif (RingOfForce.unarmedGetsWeaponAugment(this)){\n\t\t\t\tdmg = ((Weapon)belongings.attackingWeapon()).augment.damageFactor(dmg);\n\t\t\t}\n\t\t}\n\n\t\tPhysicalEmpower emp = buff(PhysicalEmpower.class);\n\t\tif (emp != null){\n\t\t\tdmg += emp.dmgBoost;\n\t\t\temp.left--;\n\t\t\tif (emp.left <= 0) {\n\t\t\t\temp.detach();\n\t\t\t}\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG, 0.75f, 1.2f);\n\t\t}\n\n\t\tif (heroClass != HeroClass.DUELIST\n\t\t\t\t&& hasTalent(Talent.WEAPON_RECHARGING)\n\t\t\t\t&& (buff(Recharging.class) != null || buff(ArtifactRecharge.class) != null)){\n\t\t\tdmg = Math.round(dmg * 1.025f + (.025f*pointsInTalent(Talent.WEAPON_RECHARGING)));\n\t\t}\n\n\t\tif (dmg < 0) dmg = 0;\n\t\treturn dmg;\n\t}\n\t\n\t@Override\n\tpublic float speed() {\n\n\t\tfloat speed = super.speed();\n\n\t\tspeed *= RingOfHaste.speedMultiplier(this);\n\t\t\n\t\tif (belongings.armor() != null) {\n\t\t\tspeed = belongings.armor().speedFactor(this, speed);\n\t\t}\n\t\t\n\t\tMomentum momentum = buff(Momentum.class);\n\t\tif (momentum != null){\n\t\t\t((HeroSprite)sprite).sprint( momentum.freerunning() ? 1.5f : 1f );\n\t\t\tspeed *= momentum.speedMultiplier();\n\t\t} else {\n\t\t\t((HeroSprite)sprite).sprint( 1f );\n\t\t}\n\n\t\tNaturesPower.naturesPowerTracker natStrength = buff(NaturesPower.naturesPowerTracker.class);\n\t\tif (natStrength != null){\n\t\t\tspeed *= (2f + 0.25f*pointsInTalent(Talent.GROWING_POWER));\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.MOVESPEED_ENHANCE)) {\n\t\t\tspeed *= 1 + 0.1*hero.pointsInTalent(Talent.MOVESPEED_ENHANCE);\n\t\t}\n\n\t\tif (subClass == HeroSubClass.MONK && buff(MonkEnergy.class) != null && buff(MonkEnergy.class).harmonized(this)) {\n\t\t\tspeed *= 1.5f;\n\t\t}\n\n\t\tif (hero.buff(ReinforcedArmor.ReinforcedArmorTracker.class) != null && hero.hasTalent(Talent.PLATE_ADD)) {\n\t\t\tspeed *= (1 - hero.pointsInTalent(Talent.PLATE_ADD)/8f);\n\t\t}\n\n\t\tif (hero.buff(Riot.RiotTracker.class) != null && hero.hasTalent(Talent.HASTE_MOVE)) {\n\t\t\tspeed *= 1f + 0.25f * hero.pointsInTalent(Talent.HASTE_MOVE);\n\t\t}\n\n\t\tspeed = AscensionChallenge.modifyHeroSpeed(speed);\n\t\t\n\t\treturn speed;\n\t\t\n\t}\n\n\t@Override\n\tpublic boolean canSurpriseAttack(){\n\t\tKindOfWeapon w = belongings.attackingWeapon();\n\t\tif (!(w instanceof Weapon)) return true;\n\t\tif (RingOfForce.fightingUnarmed(this)) return true;\n\t\tif (STR() < ((Weapon)w).STRReq()) return false;\n\t\tif (w instanceof Flail) return false;\n\t\tif (w instanceof ChainFlail) return false;\n\t\tif (w instanceof SG.SGBullet) return false;\n\n\t\treturn super.canSurpriseAttack();\n\t}\n\n\tpublic boolean canAttack(Char enemy){\n\t\tif (enemy == null || pos == enemy.pos || !Actor.chars().contains(enemy)) {\n\t\t\treturn false;\n\t\t}\n\n\t\t//can always attack adjacent enemies\n\t\tif (Dungeon.level.adjacent(pos, enemy.pos)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tKindOfWeapon wep = Dungeon.hero.belongings.attackingWeapon();\n\n\t\tif (wep != null){\n\t\t\treturn wep.canReach(this, enemy.pos);\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic float attackDelay() {\n\t\tif (buff(Talent.LethalMomentumTracker.class) != null){\n\t\t\tbuff(Talent.LethalMomentumTracker.class).detach();\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (buff(Talent.CounterAttackTracker.class) != null && hero.belongings.weapon == null) {\n\t\t\tbuff(Talent.CounterAttackTracker.class).detach();\n\t\t\treturn 0;\n\t\t}\n\n\t\tfloat delay = 1f;\n\n\t\tif ( buff(Adrenaline.class) != null) delay /= 1.5f;\n\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\t\n\t\t\treturn delay * belongings.attackingWeapon().delayFactor( this );\n\t\t\t\n\t\t} else {\n\t\t\t//Normally putting furor speed on unarmed attacks would be unnecessary\n\t\t\t//But there's going to be that one guy who gets a furor+force ring combo\n\t\t\t//This is for that one guy, you shall get your fists of fury!\n\t\t\tfloat speed = RingOfFuror.attackSpeedMultiplier(this);\n\n\t\t\tif (hero.hasTalent(Talent.LESS_RESIST)) {\n\t\t\t\tint aEnc = hero.belongings.armor.STRReq() - hero.STR();\n\t\t\t\tif (aEnc < 0) {\n\t\t\t\t\tspeed *= 1 + 0.05f * hero.pointsInTalent(Talent.LESS_RESIST) * (-aEnc);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.QUICK_FOLLOWUP) && hero.buff(Talent.QuickFollowupTracker.class) != null) {\n\t\t\t\tspeed *= 1+hero.pointsInTalent(Talent.QUICK_FOLLOWUP)/3f;\n\t\t\t}\n\n\t\t\tif (hero.subClass == HeroSubClass.MONK && hero.buff(MonkEnergy.class) != null && hero.buff(MonkEnergy.class).harmonized(hero)) {\n\t\t\t\tspeed *= 1.5f;\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.ATK_SPEED_ENHANCE)) {\n\t\t\t\tspeed *= 1 + 0.05f * hero.pointsInTalent(Talent.ATK_SPEED_ENHANCE);\n\t\t\t}\n\n\t\t\t//ditto for furor + sword dance!\n\t\t\tif (buff(Scimitar.SwordDance.class) != null){\n\t\t\t\tspeed += 0.6f;\n\t\t\t}\n\n\t\t\t//and augments + brawler's stance! My goodness, so many options now compared to 2014!\n\t\t\tif (RingOfForce.unarmedGetsWeaponAugment(this)){\n\t\t\t\tdelay = ((Weapon)belongings.weapon).augment.delayFactor(delay);\n\t\t\t}\n\n\t\t\treturn delay/speed;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void spend( float time ) {\n\t\tsuper.spend(time);\n\t}\n\n\t@Override\n\tpublic void spendConstant(float time) {\n\t\tjustMoved = false;\n\t\tsuper.spendConstant(time);\n\t}\n\n\tpublic void spendAndNextConstant(float time ) {\n\t\tbusy();\n\t\tspendConstant( time );\n\t\tnext();\n\t}\n\n\tpublic void spendAndNext( float time ) {\n\t\tbusy();\n\t\tspend( time );\n\t\tnext();\n\t}\n\t\n\t@Override\n\tpublic boolean act() {\n\t\t\n\t\t//calls to dungeon.observe will also update hero's local FOV.\n\t\tfieldOfView = Dungeon.level.heroFOV;\n\n\t\tif (buff(Endure.EndureTracker.class) != null){\n\t\t\tbuff(Endure.EndureTracker.class).endEnduring();\n\t\t}\n\t\t\n\t\tif (!ready) {\n\t\t\t//do a full observe (including fog update) if not resting.\n\t\t\tif (!resting || buff(MindVision.class) != null || buff(Awareness.class) != null) {\n\t\t\t\tDungeon.observe();\n\t\t\t} else {\n\t\t\t\t//otherwise just directly re-calculate FOV\n\t\t\t\tDungeon.level.updateFieldOfView(this, fieldOfView);\n\t\t\t}\n\t\t}\n\t\t\n\t\tcheckVisibleMobs();\n\t\tBuffIndicator.refreshHero();\n\t\tBuffIndicator.refreshBoss();\n\t\t\n\t\tif (paralysed > 0) {\n\t\t\t\n\t\t\tcurAction = null;\n\t\t\t\n\t\t\tspendAndNext( TICK );\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tboolean actResult;\n\t\tif (curAction == null) {\n\t\t\t\n\t\t\tif (resting) {\n\t\t\t\tspendConstant( TIME_TO_REST );\n\t\t\t\tnext();\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\t\t\t\n\t\t\tactResult = false;\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tresting = false;\n\t\t\t\n\t\t\tready = false;\n\t\t\t\n\t\t\tif (curAction instanceof HeroAction.Move) {\n\t\t\t\tactResult = actMove( (HeroAction.Move)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Interact) {\n\t\t\t\tactResult = actInteract( (HeroAction.Interact)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Buy) {\n\t\t\t\tactResult = actBuy( (HeroAction.Buy)curAction );\n\t\t\t\t\n\t\t\t}else if (curAction instanceof HeroAction.PickUp) {\n\t\t\t\tactResult = actPickUp( (HeroAction.PickUp)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.OpenChest) {\n\t\t\t\tactResult = actOpenChest( (HeroAction.OpenChest)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Unlock) {\n\t\t\t\tactResult = actUnlock((HeroAction.Unlock) curAction);\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Mine) {\n\t\t\t\tactResult = actMine( (HeroAction.Mine)curAction );\n\n\t\t\t}else if (curAction instanceof HeroAction.LvlTransition) {\n\t\t\t\tactResult = actTransition( (HeroAction.LvlTransition)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Attack) {\n\t\t\t\tactResult = actAttack( (HeroAction.Attack)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Alchemy) {\n\t\t\t\tactResult = actAlchemy( (HeroAction.Alchemy)curAction );\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tactResult = false;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(hasTalent(Talent.BARKSKIN) && Dungeon.level.map[pos] == Terrain.FURROWED_GRASS){\n\t\t\tBarkskin.conditionallyAppend(this, (lvl*pointsInTalent(Talent.BARKSKIN))/2, 1 );\n\t\t}\n\n\t\tif (hasTalent(Talent.PARRY) && buff(Talent.ParryCooldown.class) == null){\n\t\t\tBuff.affect(this, Talent.ParryTracker.class);\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.CURSED_DUNGEON) && hero.buff(GhostSpawner.class) == null) {\n\t\t\tBuff.affect(hero, GhostSpawner.class);\n\t\t}\n\t\t\n\t\treturn actResult;\n\t}\n\t\n\tpublic void busy() {\n\t\tready = false;\n\t}\n\t\n\tprivate void ready() {\n\t\tif (sprite.looping()) sprite.idle();\n\t\tcurAction = null;\n\t\tdamageInterrupt = true;\n\t\twaitOrPickup = false;\n\t\tready = true;\n\t\tcanSelfTrample = true;\n\n\t\tAttackIndicator.updateState();\n\t\t\n\t\tGameScene.ready();\n\t}\n\t\n\tpublic void interrupt() {\n\t\tif (isAlive() && curAction != null &&\n\t\t\t((curAction instanceof HeroAction.Move && curAction.dst != pos) ||\n\t\t\t(curAction instanceof HeroAction.LvlTransition))) {\n\t\t\tlastAction = curAction;\n\t\t}\n\t\tcurAction = null;\n\t\tGameScene.resetKeyHold();\n\t}\n\t\n\tpublic void resume() {\n\t\tcurAction = lastAction;\n\t\tlastAction = null;\n\t\tdamageInterrupt = false;\n\t\tnext();\n\t}\n\n\tprivate boolean canSelfTrample = false;\n\tpublic boolean canSelfTrample(){\n\t\treturn canSelfTrample && !rooted && !flying &&\n\t\t\t\t//standing in high grass\n\t\t\t\t(Dungeon.level.map[pos] == Terrain.HIGH_GRASS ||\n\t\t\t\t//standing in furrowed grass and not huntress\n\t\t\t\t((heroClass != HeroClass.HUNTRESS && hero.subClass != HeroSubClass.SPECIALIST) && Dungeon.level.map[pos] == Terrain.FURROWED_GRASS) ||\n\t\t\t\t//standing on a plant\n\t\t\t\tDungeon.level.plants.get(pos) != null);\n\t}\n\t\n\tprivate boolean actMove( HeroAction.Move action ) {\n\n\t\tif (getCloser( action.dst )) {\n\t\t\tcanSelfTrample = false;\n\t\t\treturn true;\n\n\t\t//Hero moves in place if there is grass to trample\n\t\t} else if (pos == action.dst && canSelfTrample()){\n\t\t\tcanSelfTrample = false;\n\t\t\tDungeon.level.pressCell(pos);\n\t\t\tspendAndNext( 1 / speed() );\n\t\t\treturn false;\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actInteract( HeroAction.Interact action ) {\n\t\t\n\t\tChar ch = action.ch;\n\n\t\tif (ch.isAlive() && ch.canInteract(this)) {\n\t\t\t\n\t\t\tready();\n\t\t\tsprite.turnTo( pos, ch.pos );\n\t\t\treturn ch.interact(this);\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tif (fieldOfView[ch.pos] && getCloser( ch.pos )) {\n\n\t\t\t\treturn true;\n\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\t\n\tprivate boolean actBuy( HeroAction.Buy action ) {\n\t\tint dst = action.dst;\n\t\tif (pos == dst) {\n\n\t\t\tready();\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( dst );\n\t\t\tif (heap != null && heap.type == Type.FOR_SALE && heap.size() == 1) {\n\t\t\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\tGameScene.show( new WndTradeItem( heap ) );\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate boolean actAlchemy( HeroAction.Alchemy action ) {\n\t\tint dst = action.dst;\n\t\tif (Dungeon.level.distance(dst, pos) <= 1) {\n\n\t\t\tready();\n\t\t\t\n\t\t\tAlchemistsToolkit.kitEnergy kit = buff(AlchemistsToolkit.kitEnergy.class);\n\t\t\tif (kit != null && kit.isCursed()){\n\t\t\t\tGLog.w( Messages.get(AlchemistsToolkit.class, \"cursed\"));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tAlchemyScene.clearToolkit();\n\t\t\tShatteredPixelDungeon.switchScene(AlchemyScene.class);\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t//used to keep track if the wait/pickup action was used\n\t// so that the hero spends a turn even if the fail to pick up an item\n\tpublic boolean waitOrPickup = false;\n\n\tprivate boolean actPickUp( HeroAction.PickUp action ) {\n\t\tint dst = action.dst;\n\t\tif (pos == dst) {\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( pos );\n\t\t\tif (heap != null) {\n\t\t\t\tItem item = heap.peek();\n\t\t\t\tif (item.doPickUp( this )) {\n\t\t\t\t\theap.pickUp();\n\n\t\t\t\t\tif (item instanceof Dewdrop\n\t\t\t\t\t\t\t|| item instanceof TimekeepersHourglass.sandBag\n\t\t\t\t\t\t\t|| item instanceof DriedRose.Petal\n\t\t\t\t\t\t\t|| item instanceof Key\n\t\t\t\t\t\t\t|| item instanceof Guidebook) {\n\t\t\t\t\t\t//Do Nothing\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t//TODO make all unique items important? or just POS / SOU?\n\t\t\t\t\t\tboolean important = item.unique && item.isIdentified() &&\n\t\t\t\t\t\t\t\t(item instanceof Scroll || item instanceof Potion);\n\t\t\t\t\t\tif (important) {\n\t\t\t\t\t\t\tGLog.p( Messages.capitalize(Messages.get(this, \"you_now_have\", item.name())) );\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tGLog.i( Messages.capitalize(Messages.get(this, \"you_now_have\", item.name())) );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tcurAction = null;\n\t\t\t\t} else {\n\n\t\t\t\t\tif (waitOrPickup) {\n\t\t\t\t\t\tspendAndNextConstant(TIME_TO_REST);\n\t\t\t\t\t}\n\n\t\t\t\t\t//allow the hero to move between levels even if they can't collect the item\n\t\t\t\t\tif (Dungeon.level.getTransition(pos) != null){\n\t\t\t\t\t\tthrowItems();\n\t\t\t\t\t} else {\n\t\t\t\t\t\theap.sprite.drop();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (item instanceof Dewdrop\n\t\t\t\t\t\t\t|| item instanceof TimekeepersHourglass.sandBag\n\t\t\t\t\t\t\t|| item instanceof DriedRose.Petal\n\t\t\t\t\t\t\t|| item instanceof Key) {\n\t\t\t\t\t\t//Do Nothing\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGLog.newLine();\n\t\t\t\t\t\tGLog.n(Messages.capitalize(Messages.get(this, \"you_cant_have\", item.name())));\n\t\t\t\t\t}\n\n\t\t\t\t\tready();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actOpenChest( HeroAction.OpenChest action ) {\n\t\tint dst = action.dst;\n\t\tif (Dungeon.level.adjacent( pos, dst ) || pos == dst) {\n\t\t\tpath = null;\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( dst );\n\t\t\tif (heap != null && (heap.type != Type.HEAP && heap.type != Type.FOR_SALE)) {\n\t\t\t\t\n\t\t\t\tif ((heap.type == Type.LOCKED_CHEST && Notes.keyCount(new GoldenKey(Dungeon.depth)) < 1)\n\t\t\t\t\t|| (heap.type == Type.CRYSTAL_CHEST && Notes.keyCount(new CrystalKey(Dungeon.depth)) < 1)){\n\n\t\t\t\t\t\tGLog.w( Messages.get(this, \"locked_chest\") );\n\t\t\t\t\t\tready();\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tswitch (heap.type) {\n\t\t\t\tcase TOMB:\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.TOMB );\n\t\t\t\t\tPixelScene.shake( 1, 0.5f );\n\t\t\t\t\tbreak;\n\t\t\t\tcase SKELETON:\n\t\t\t\tcase REMAINS:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.UNLOCK );\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tsprite.operate( dst );\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actUnlock( HeroAction.Unlock action ) {\n\t\tint doorCell = action.dst;\n\t\tif (Dungeon.level.adjacent( pos, doorCell )) {\n\t\t\tpath = null;\n\t\t\t\n\t\t\tboolean hasKey = false;\n\t\t\tint door = Dungeon.level.map[doorCell];\n\t\t\t\n\t\t\tif (door == Terrain.LOCKED_DOOR\n\t\t\t\t\t&& Notes.keyCount(new IronKey(Dungeon.depth)) > 0) {\n\t\t\t\t\n\t\t\t\thasKey = true;\n\t\t\t\t\n\t\t\t} else if (door == Terrain.CRYSTAL_DOOR\n\t\t\t\t\t&& Notes.keyCount(new CrystalKey(Dungeon.depth, Dungeon.branch)) > 0) {\n\n\t\t\t\thasKey = true;\n\n\t\t\t} else if (door == Terrain.LOCKED_EXIT\n\t\t\t\t\t&& Notes.keyCount(new SkeletonKey(Dungeon.depth)) > 0) {\n\n\t\t\t\thasKey = true;\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tif (hasKey) {\n\t\t\t\t\n\t\t\t\tsprite.operate( doorCell );\n\t\t\t\t\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.UNLOCK );\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tGLog.w( Messages.get(this, \"locked_door\") );\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( doorCell )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic boolean actMine(HeroAction.Mine action){\n\t\tif (Dungeon.level.adjacent(pos, action.dst)){\n\t\t\tpath = null;\n\t\t\tif ((Dungeon.level.map[action.dst] == Terrain.WALL\n\t\t\t\t\t|| Dungeon.level.map[action.dst] == Terrain.WALL_DECO\n\t\t\t\t\t|| Dungeon.level.map[action.dst] == Terrain.MINE_CRYSTAL\n\t\t\t\t\t|| Dungeon.level.map[action.dst] == Terrain.MINE_BOULDER)\n\t\t\t\t&& Dungeon.level.insideMap(action.dst)){\n\t\t\t\tsprite.attack(action.dst, new Callback() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void call() {\n\n\t\t\t\t\t\tboolean crystalAdjacent = false;\n\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS8) {\n\t\t\t\t\t\t\tif (Dungeon.level.map[action.dst + i] == Terrain.MINE_CRYSTAL){\n\t\t\t\t\t\t\t\tcrystalAdjacent = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//1 hunger spent total\n\t\t\t\t\t\tif (Dungeon.level.map[action.dst] == Terrain.WALL_DECO){\n\t\t\t\t\t\t\tDarkGold gold = new DarkGold();\n\t\t\t\t\t\t\tif (gold.doPickUp( Dungeon.hero )) {\n\t\t\t\t\t\t\t\tDarkGold existing = Dungeon.hero.belongings.getItem(DarkGold.class);\n\t\t\t\t\t\t\t\tif (existing != null && existing.quantity()%5 == 0){\n\t\t\t\t\t\t\t\t\tif (existing.quantity() >= 40) {\n\t\t\t\t\t\t\t\t\t\tGLog.p(Messages.get(DarkGold.class, \"you_now_have\", existing.quantity()));\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tGLog.i(Messages.get(DarkGold.class, \"you_now_have\", existing.quantity()));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tspend(-Actor.TICK); //picking up the gold doesn't spend a turn here\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tDungeon.level.drop( gold, pos ).sprite.drop();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tPixelScene.shake(0.5f, 0.5f);\n\t\t\t\t\t\t\tCellEmitter.center( action.dst ).burst( Speck.factory( Speck.STAR ), 7 );\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.EVOKE );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY_DECO );\n\n\t\t\t\t\t\t\t//mining gold doesn't break crystals\n\t\t\t\t\t\t\tcrystalAdjacent = false;\n\n\t\t\t\t\t\t//4 hunger spent total\n\t\t\t\t\t\t} else if (Dungeon.level.map[action.dst] == Terrain.WALL){\n\t\t\t\t\t\t\tbuff(Hunger.class).affectHunger(-3);\n\t\t\t\t\t\t\tPixelScene.shake(0.5f, 0.5f);\n\t\t\t\t\t\t\tCellEmitter.get( action.dst ).burst( Speck.factory( Speck.ROCK ), 2 );\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.MINE );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY_DECO );\n\n\t\t\t\t\t\t//1 hunger spent total\n\t\t\t\t\t\t} else if (Dungeon.level.map[action.dst] == Terrain.MINE_CRYSTAL){\n\t\t\t\t\t\t\tSplash.at(action.dst, 0xFFFFFF, 5);\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.SHATTER );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY );\n\n\t\t\t\t\t\t//1 hunger spent total\n\t\t\t\t\t\t} else if (Dungeon.level.map[action.dst] == Terrain.MINE_BOULDER){\n\t\t\t\t\t\t\tSplash.at(action.dst, ColorMath.random( 0x444444, 0x777766 ), 5);\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.MINE, 0.6f );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\t\tDungeon.level.discoverable[action.dst + i] = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\t\tGameScene.updateMap( action.dst+i );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (crystalAdjacent){\n\t\t\t\t\t\t\tsprite.parent.add(new Delayer(0.2f){\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tprotected void onComplete() {\n\t\t\t\t\t\t\t\t\tboolean broke = false;\n\t\t\t\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS8) {\n\t\t\t\t\t\t\t\t\t\tif (Dungeon.level.map[action.dst+i] == Terrain.MINE_CRYSTAL){\n\t\t\t\t\t\t\t\t\t\t\tSplash.at(action.dst+i, 0xFFFFFF, 5);\n\t\t\t\t\t\t\t\t\t\t\tLevel.set( action.dst+i, Terrain.EMPTY );\n\t\t\t\t\t\t\t\t\t\t\tbroke = true;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (broke){\n\t\t\t\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.SHATTER );\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\t\t\t\t\tGameScene.updateMap( action.dst+i );\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tspendAndNext(TICK);\n\t\t\t\t\t\t\t\t\tready();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tspendAndNext(TICK);\n\t\t\t\t\t\t\tready();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tDungeon.observe();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\t\t\treturn false;\n\t\t} else if (getCloser( action.dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actTransition(HeroAction.LvlTransition action ) {\n\t\tint stairs = action.dst;\n\t\tLevelTransition transition = Dungeon.level.getTransition(stairs);\n\n\t\tif (rooted) {\n\t\t\tPixelScene.shake(1, 1f);\n\t\t\tready();\n\t\t\treturn false;\n\n\t\t} else if (!Dungeon.level.locked && transition != null && transition.inside(pos)) {\n\n\t\t\tif (Dungeon.level.activateTransition(this, transition)){\n\t\t\t\tcurAction = null;\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( stairs )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actAttack( HeroAction.Attack action ) {\n\n\t\tenemy = action.target;\n\n\t\tif (enemy.isAlive() && canAttack( enemy ) && !isCharmedBy( enemy ) && enemy.invisible == 0) {\n\n\t\t\tif (heroClass != HeroClass.DUELIST\n\t\t\t\t\t&& hasTalent(Talent.AGGRESSIVE_BARRIER)\n\t\t\t\t\t&& buff(Talent.AggressiveBarrierCooldown.class) == null\n\t\t\t\t\t&& (HP / (float)HT) < 0.20f*(1+pointsInTalent(Talent.AGGRESSIVE_BARRIER))){\n\t\t\t\tBuff.affect(this, Barrier.class).setShield(3);\n\t\t\t\tBuff.affect(this, Talent.AggressiveBarrierCooldown.class, 50f);\n\t\t\t}\n\t\t\tsprite.attack( enemy.pos );\n\n\t\t\treturn false;\n\n\t\t} else {\n\n\t\t\tif (fieldOfView[enemy.pos] && getCloser( enemy.pos )) {\n\n\t\t\t\treturn true;\n\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t}\n\t}\n\n\tpublic Char enemy(){\n\t\treturn enemy;\n\t}\n\t\n\tpublic void rest( boolean fullRest ) {\n\t\tspendAndNextConstant( TIME_TO_REST );\n\t\tif (hasTalent(Talent.HOLD_FAST)){\n\t\t\tBuff.affect(this, HoldFast.class).pos = pos;\n\t\t}\n\t\tif (hasTalent(Talent.PATIENT_STRIKE)){\n\t\t\tBuff.affect(Dungeon.hero, Talent.PatientStrikeTracker.class).pos = Dungeon.hero.pos;\n\t\t}\n\t\tif (!fullRest) {\n\t\t\tif (sprite != null) {\n\t\t\t\tsprite.showStatus(CharSprite.DEFAULT, Messages.get(this, \"wait\"));\n\t\t\t}\n\n\t\t\tif (belongings.weapon instanceof LargeSword || belongings.secondWep instanceof LargeSword){\n\t\t\t\tBuff.affect(this, LargeSword.LargeSwordBuff.class).setDamageFactor(belongings.weapon.buffedLvl(), (belongings.secondWep instanceof LargeSword));\n\t\t\t\tif (hero.sprite != null) {\n\t\t\t\t\tEmitter e = hero.sprite.centerEmitter();\n\t\t\t\t\tif (e != null) e.burst(EnergyParticle.FACTORY, 15);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Dungeon.hero.subClass == HeroSubClass.CHASER\n\t\t\t\t\t&& hero.buff(Talent.ChaseCooldown.class) == null\n\t\t\t\t\t&& hero.buff(Invisibility.class) == null\n\t\t\t\t\t&& hero.buff(CloakOfShadows.cloakStealth.class) == null ) {\n\t\t\t\tif (hero.hasTalent(Talent.MASTER_OF_CLOAKING)) {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Invisibility.class, 6f);\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Invisibility.class, 5f);\n\t\t\t\t}\n\t\t\t\tif (hero.pointsInTalent(Talent.MASTER_OF_CLOAKING) > 1) {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.ChaseCooldown.class, 10f);\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.ChaseCooldown.class, 15f);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Dungeon.level.map[pos] == Terrain.FURROWED_GRASS && hero.subClass == HeroSubClass.SPECIALIST) {\n\t\t\t\tboolean adjacentMob = false;\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] )) {\n\t\t\t\t\tif (level.adjacent(hero.pos, mob.pos)) {\n\t\t\t\t\t\tadjacentMob = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (hero.pointsInTalent(Talent.STEALTH_MASTER) > 1) {\n\t\t\t\t\tadjacentMob = false;\n\t\t\t\t}\n\t\t\t\tif (!adjacentMob && hero.hasTalent(Talent.INTO_THE_SHADOW) && hero.buff(Talent.IntoTheShadowCooldown.class) == null) {\n\t\t\t\t\tBuff.affect(this, Invisibility.class, 3f*hero.pointsInTalent(Talent.INTO_THE_SHADOW));\n\t\t\t\t\tBuff.affect(this, Talent.IntoTheShadowCooldown.class, 15);\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(this, Cloaking.class);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresting = fullRest;\n\t}\n\t\n\t@Override\n\tpublic int attackProc( final Char enemy, int damage ) {\n\t\tdamage = super.attackProc( enemy, damage );\n\n\t\tKindOfWeapon wep;\n\t\tif (RingOfForce.fightingUnarmed(this) && !RingOfForce.unarmedGetsWeaponEnchantment(this)){\n\t\t\twep = null;\n\t\t} else {\n\t\t\twep = belongings.attackingWeapon();\n\t\t}\n\n\t\tif (hero.buff(MeleeWeapon.DashAttack.class) != null) {\n\t\t\tdamage *= hero.buff(MeleeWeapon.DashAttack.class).getDmgMulti();\n\t\t\thero.buff(MeleeWeapon.DashAttack.class).detach();\n\t\t}\n\n\t\tif (wep != null) damage = wep.proc( this, enemy, damage );\n\n\t\tdamage = Talent.onAttackProc( this, enemy, damage );\n\t\t\n\t\tswitch (subClass) {\n\t\t\tcase SNIPER:\n\t\t\t\tif (wep instanceof MissileWeapon && !(wep instanceof SpiritBow.SpiritArrow) && enemy != this) {\n\t\t\t\t\tActor.add(new Actor() {\n\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tactPriority = VFX_PRIO;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tprotected boolean act() {\n\t\t\t\t\t\t\tif (enemy.isAlive()) {\n\t\t\t\t\t\t\t\tint bonusTurns = hasTalent(Talent.SHARED_UPGRADES) ? wep.buffedLvl() : 0;\n\t\t\t\t\t\t\t\tBuff.prolong(Hero.this, SnipersMark.class, SnipersMark.DURATION + bonusTurns).set(enemy.id(), bonusTurns);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tActor.remove(this);\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (hero.hasTalent(Talent.KICK)\n\t\t\t\t\t\t&& enemy.buff(PinCushion.class) != null\n\t\t\t\t\t\t&& level.adjacent(hero.pos, enemy.pos)\n\t\t\t\t\t\t&& hero.buff(Talent.KickCooldown.class) == null) {\n\t\t\t\t\tItem item = enemy.buff(PinCushion.class).grabOne();\n\t\t\t\t\tif (item.doPickUp(hero, enemy.pos)){\n\t\t\t\t\t\thero.spend(-1); //attacking enemy already takes a turn\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGLog.w(Messages.get(this, \"cant_grab\"));\n\t\t\t\t\t\tDungeon.level.drop(item, enemy.pos).sprite.drop();\n\t\t\t\t\t}\n\t\t\t\t\tBallistica trajectory = new Ballistica(hero.pos, enemy.pos, Ballistica.STOP_TARGET);\n\t\t\t\t\ttrajectory = new Ballistica(trajectory.collisionPos, trajectory.path.get(trajectory.path.size() - 1), Ballistica.PROJECTILE);\n\t\t\t\t\tint dist = hero.pointsInTalent(Talent.KICK);\n\t\t\t\t\tWandOfBlastWave.throwChar(enemy, trajectory, dist, true, false ,hero.getClass());\n\t\t\t\t\tBuff.affect(hero, Talent.KickCooldown.class, 10f);\n\t\t\t\t}\n\t\t\t\tif (wep instanceof MissileWeapon\n\t\t\t\t\t\t&& hero.hasTalent(Talent.SHOOTING_EYES)\n\t\t\t\t\t\t&& enemy.buff(Talent.ShootingEyesTracker.class) == null) {\n\t\t\t\t\tif (Random.Float() < hero.pointsInTalent(Talent.SHOOTING_EYES)/3f) {\n\t\t\t\t\t\tBuff.affect(enemy, Blindness.class, 2f);\n\t\t\t\t\t}\n\t\t\t\t\tBuff.affect(enemy, Talent.ShootingEyesTracker.class);\n\t\t\t\t}\n\t\t\t\tif (wep instanceof MissileWeapon\n\t\t\t\t\t\t&& hero.hasTalent(Talent.TARGET_SPOTTING)\n\t\t\t\t\t\t&& hero.buff(SnipersMark.class) != null\n\t\t\t\t\t\t&& hero.buff(SnipersMark.class).object == enemy.id()) {\n\t\t\t\t\tdamage *= 1+0.1f*hero.pointsInTalent(Talent.TARGET_SPOTTING);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase FIGHTER:\n\t\t\t\tif (wep == null && Random.Int(3) < hero.pointsInTalent(Talent.QUICK_STEP)) {\n\t\t\t\t\tBuff.prolong(hero, Talent.QuickStep.class, 1.0001f);\n\t\t\t\t}\n\t\t\t\tif (wep == null && hero.hasTalent(Talent.RING_KNUCKLE) && hero.buff(RingOfForce.Force.class) == null) {\n\t\t\t\t\tBuff.prolong(hero, EnhancedRingsCombo.class, (Dungeon.hero.pointsInTalent(Talent.RING_KNUCKLE) >= 2) ? 2f : 1f).hit();\n\t\t\t\t\thero.updateHT(false);\n\t\t\t\t\tupdateQuickslot();\n\t\t\t\t}\n\t\t\t\tif (wep == null && Random.Float() < hero.pointsInTalent(Talent.MYSTICAL_PUNCH)/3f) {\n\t\t\t\t\tif (hero.belongings.ring != null) {\n\t\t\t\t\t\tdamage *= Ring.onHit(hero, enemy, damage, Ring.ringTypes.get(hero.belongings.ring.getClass()));\n\t\t\t\t\t}\n\t\t\t\t\tif (hero.belongings.misc instanceof Ring) {\n\t\t\t\t\t\tdamage *= Ring.onHit(hero, enemy, damage, Ring.ringTypes.get(hero.belongings.misc.getClass()));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CHAMPION:\n\t\t\t\tif (hero.belongings.weapon != null && hero.belongings.secondWep != null\n\t\t\t\t\t\t&& hero.pointsInTalent(Talent.TWIN_SWORD) > 1\n\t\t\t\t\t\t&& hero.belongings.weapon.getClass() == hero.belongings.secondWep.getClass()) {\n\t\t\t\t\tKindOfWeapon other = hero.belongings.secondWep;\n\t\t\t\t\tif (hero.belongings.secondWep == wep) {\n\t\t\t\t\t\tother = hero.belongings.weapon;\n\t\t\t\t\t}\n\t\t\t\t\tdamage = other.proc( this, enemy, damage );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase VETERAN:\n\t\t\t\tif (level.adjacent(enemy.pos, pos) && hero.buff(Tackle.TackleTracker.class) == null) {\n\t\t\t\t\tActor.add(new Actor() {\n\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tactPriority = VFX_PRIO;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tprotected boolean act() {\n\t\t\t\t\t\t\tif (enemy.isAlive()) {\n\t\t\t\t\t\t\t\tBuff.prolong(Hero.this, Tackle.class, 1).set(enemy.id());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tActor.remove(this);\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OUTLAW:\n\t\t\t\tif (wep instanceof Gun.Bullet) {\n\t\t\t\t\tif (hero.hasTalent(Talent.HEADSHOT) && Random.Float() < 0.01f*hero.pointsInTalent(Talent.HEADSHOT)) {\n\t\t\t\t\t\tif (!Char.hasProp(enemy, Property.BOSS) && !Char.hasProp(enemy, Property.MINIBOSS)) {\n\t\t\t\t\t\t\tdamage = enemy.HP;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdamage *= 1.2f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemy.sprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\t\t}\n\n\t\t\t\t\tif (hero.buff(Talent.HonorableShotTracker.class) != null\n\t\t\t\t\t\t\t&& (enemy.HP/(float)enemy.HT) <= 0.4f*hero.pointsInTalent(Talent.HONORABLE_SHOT)/3f) {\n\t\t\t\t\t\tif (!Char.hasProp(enemy, Property.BOSS) && !Char.hasProp(enemy, Property.MINIBOSS)) {\n\t\t\t\t\t\t\tdamage = enemy.HP;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdamage *= 1.2f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemy.sprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\t\t\thero.buff(Talent.HonorableShotTracker.class).detach();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (hero.buff(RouletteOfDeath.class) == null || !hero.buff(RouletteOfDeath.class).timeToDeath()) {\n\t\t\t\t\t\tBuff.affect(this, RouletteOfDeath.class).hit();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (!Char.hasProp(enemy, Property.BOSS) && !Char.hasProp(enemy, Property.MINIBOSS)) {\n\t\t\t\t\t\t\tdamage = enemy.HP;\n\t\t\t\t\t\t\tif (hero.belongings.weapon instanceof Gun) {\n\t\t\t\t\t\t\t\t((Gun)hero.belongings.weapon).quickReload();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (hero.hasTalent(Talent.BULLET_TIME)) {\n\t\t\t\t\t\t\t\tfor (Char ch : Actor.chars()) {\n\t\t\t\t\t\t\t\t\tif (level.heroFOV[ch.pos]) {\n\t\t\t\t\t\t\t\t\t\tBuff.affect(ch, Slow.class, 4*hero.pointsInTalent(Talent.BULLET_TIME));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdamage *= 1.2f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemy.sprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\t\t\thero.buff(RouletteOfDeath.class).detach();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.WATER_FRIENDLY) && Dungeon.level.map[hero.pos] == Terrain.WATER) {\n\t\t\tdamage += Random.NormalIntRange(1, hero.pointsInTalent(Talent.WATER_FRIENDLY));\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t}\n\n\t\tif (hero.buff(Talent.SkilledHandTracker.class) != null) {\n\t\t\tdamage += 1+hero.pointsInTalent(Talent.SKILLED_HAND);\n\t\t\thero.buff(Talent.SkilledHandTracker.class).detach();\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t}\n\n\t\tif (Random.Float() < hero.pointsInTalent(Talent.MADNESS)/10f) {\n\t\t\tBuff.prolong(enemy, Amok.class, 3f);\n\t\t}\n\n\t\tSpellBook.SpellBookCoolDown spellBookCoolDown = buff(SpellBook.SpellBookCoolDown.class);\n\t\tif (hero.hasTalent(Talent.BRIG_BOOST) && spellBookCoolDown != null) {\n\t\t\tspellBookCoolDown.hit(hero.pointsInTalent(Talent.BRIG_BOOST));\n\t\t}\n\n\t\tif (hero.buff(Bible.Angel.class) != null) {\n\t\t\thero.heal(Math.max(Math.round(0.2f*damage), 1));\n\t\t}\n\n\t\tif (hero.buff(UnholyBible.Demon.class) != null) {\n\t\t\tdamage *= 1.33f;\n\t\t}\n\n\t\tif (hero.buff(DualDagger.ReverseBlade.class) != null) {\n\t\t\tdamage *= 0.5f;\n\t\t\tBuff.affect(enemy, Bleeding.class).add(Random.NormalIntRange(1, 3));\n\t\t\tif (enemy.sprite.visible) {\n\t\t\t\tSplash.at( enemy.sprite.center(), -PointF.PI / 2, PointF.PI / 6,\n\t\t\t\t\t\tenemy.sprite.blood(), Math.min( 10 * Random.NormalIntRange(1, 3) / enemy.HT, 10 ) );\n\t\t\t}\n\t\t}\n\n\t\tif (enemy instanceof Mob && ((Mob) enemy).surprisedBy(hero)) {\n\t\t\tif (hero.hasTalent(Talent.POISONOUS_BLADE)) {\n\t\t\t\tBuff.affect(enemy, Poison.class).set(2+hero.pointsInTalent(Talent.POISONOUS_BLADE));\n\t\t\t}\n\t\t\tif (hero.hasTalent(Talent.SOUL_COLLECT) && damage >= enemy.HP) {\n\t\t\t\tint healAmt = 3*hero.pointsInTalent(Talent.SOUL_COLLECT);\n\t\t\t\thealAmt = Math.min( healAmt, hero.HT - hero.HP );\n\t\t\t\tif (healAmt > 0 && hero.isAlive()) {\n\t\t\t\t\thero.HP += healAmt;\n\t\t\t\t\thero.sprite.emitter().start( Speck.factory( Speck.HEALING ), 0.4f, 2 );\n\t\t\t\t\thero.sprite.showStatus( CharSprite.POSITIVE, Integer.toString( healAmt ) );\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hero.hasTalent(Talent.TRAIL_TRACKING) && damage >= enemy.HP) {\n\t\t\t\tBuff.affect(hero, MindVision.class, hero.pointsInTalent(Talent.TRAIL_TRACKING));\n\t\t\t}\n\n\t\t\tif (hero.pointsInTalent(Talent.MASTER_OF_CLOAKING) == 3) {\n\t\t\t\tif (hero.buff(Talent.ChaseCooldown.class) != null) {\n\t\t\t\t\thero.buff(Talent.ChaseCooldown.class).spendTime();\n\t\t\t\t}\n\t\t\t\tif (hero.buff(Talent.ChainCooldown.class) != null) {\n\t\t\t\t\thero.buff(Talent.ChainCooldown.class).spendTime();\n\t\t\t\t}\n\t\t\t\tif (hero.buff(Talent.LethalCooldown.class) != null) {\n\t\t\t\t\thero.buff(Talent.LethalCooldown.class).spendTime();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.BAYONET) && hero.buff(ReinforcedArmor.ReinforcedArmorTracker.class) != null){\n\t\t\tif (wep instanceof Gun) {\n\t\t\t\tBuff.affect( enemy, Bleeding.class ).set( 4 + hero.pointsInTalent(Talent.BAYONET));\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.SUPERMAN)) {\n\t\t\tdamage *= 3f;\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.PYRO)) {\n\t\t\tBuff.affect(enemy, Burning.class).reignite(enemy, 8f);\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.FATIGUE)) {\n\t\t\tBuff.affect(this, Fatigue.class).hit(true);\n\t\t}\n\t\t\n\t\treturn damage;\n\t}\n\t\n\t@Override\n\tpublic int defenseProc( Char enemy, int damage ) {\n\t\t\n\t\tif (damage > 0 && subClass == HeroSubClass.BERSERKER){\n\t\t\tBerserk berserk = Buff.affect(this, Berserk.class);\n\t\t\tberserk.damage(damage);\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.GLADIATOR && Random.Float() < hero.pointsInTalent(Talent.OFFENSIVE_DEFENSE)/3f) {\n\t\t\tCombo combo = Buff.affect(this, Combo.class);\n\t\t\tcombo.hit(enemy);\n\t\t}\n\t\t\n\t\tif (belongings.armor() != null) {\n\t\t\tdamage = belongings.armor().proc( enemy, this, damage );\n\t\t}\n\n\t\tWandOfLivingEarth.RockArmor rockArmor = buff(WandOfLivingEarth.RockArmor.class);\n\t\tif (rockArmor != null) {\n\t\t\tdamage = rockArmor.absorb(damage);\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.EMERGENCY_ESCAPE) && Random.Float() < hero.pointsInTalent(Talent.EMERGENCY_ESCAPE)/50f) {\n\t\t\tBuff.prolong(this, Invisibility.class, 3f);\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.OVERCOMING)) {\n\t\t\tMomentum momentum = buff(Momentum.class);\n\t\t\tif (momentum != null && momentum.freerunning()) {\n\t\t\t\tBuff.affect(this, Haste.class, 2f);\n\t\t\t\tif (hero.pointsInTalent(Talent.OVERCOMING) > 1) Buff.affect(this, Adrenaline.class, 2f);\n\t\t\t\tif (hero.pointsInTalent(Talent.OVERCOMING) > 2) Buff.affect(this, EvasiveMove.class, 2f);\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.FATIGUE)) {\n\t\t\tBuff.affect(this, Fatigue.class).hit(false);\n\t\t}\n\t\t\n\t\treturn super.defenseProc( enemy, damage );\n\t}\n\t\n\t@Override\n\tpublic void damage( int dmg, Object src ) {\n\t\tif (buff(TimekeepersHourglass.timeStasis.class) != null)\n\t\t\treturn;\n\n\t\t//regular damage interrupt, triggers on any damage except specific mild DOT effects\n\t\t// unless the player recently hit 'continue moving', in which case this is ignored\n\t\tif (!(src instanceof Hunger || src instanceof Viscosity.DeferedDamage) && damageInterrupt) {\n\t\t\tinterrupt();\n\t\t\tresting = false;\n\t\t}\n\n\t\tif (this.buff(Drowsy.class) != null){\n\t\t\tBuff.detach(this, Drowsy.class);\n\t\t\tGLog.w( Messages.get(this, \"pain_resist\") );\n\t\t}\n\n\t\tEndure.EndureTracker endure = buff(Endure.EndureTracker.class);\n\t\tif (!(src instanceof Char)){\n\t\t\t//reduce damage here if it isn't coming from a character (if it is we already reduced it)\n\t\t\tif (endure != null){\n\t\t\t\tdmg = Math.round(endure.adjustDamageTaken(dmg));\n\t\t\t}\n\t\t\t//the same also applies to challenge scroll damage reduction\n\t\t\tif (buff(ScrollOfChallenge.ChallengeArena.class) != null){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\t\t\t//and to monk meditate damage reduction\n\t\t\tif (buff(MonkEnergy.MonkAbility.Meditate.MeditateResistance.class) != null){\n\t\t\t\tdmg *= 0.2f;\n\t\t\t}\n\t\t}\n\n\t\tCapeOfThorns.Thorns thorns = buff( CapeOfThorns.Thorns.class );\n\t\tif (thorns != null) {\n\t\t\tdmg = thorns.proc(dmg, (src instanceof Char ? (Char)src : null), this);\n\t\t}\n\n\t\tdmg = (int)Math.ceil(dmg * RingOfTenacity.damageMultiplier( this ));\n\n\t\tLargeSword.LargeSwordBuff largeSwordBuff = hero.buff(LargeSword.LargeSwordBuff.class);\n\t\tif (largeSwordBuff != null) {\n\t\t\tdmg = (int)Math.ceil(dmg * largeSwordBuff.getDefenseFactor());\n\t\t}\n\n\t\t//TODO improve this when I have proper damage source logic\n\t\tif (belongings.armor() != null && belongings.armor().hasGlyph(AntiMagic.class, this)\n\t\t\t\t&& AntiMagic.RESISTS.contains(src.getClass())){\n\t\t\tdmg -= AntiMagic.drRoll(this, belongings.armor().buffedLvl());\n\t\t}\n\n\t\tif (buff(Talent.WarriorFoodImmunity.class) != null){\n\t\t\tif (pointsInTalent(Talent.IRON_STOMACH) == 1) dmg = Math.round(dmg*0.25f);\n\t\t\telse if (pointsInTalent(Talent.IRON_STOMACH) == 2) dmg = Math.round(dmg*0.00f);\n\t\t}\n\n\t\tif (buff(Tackle.SuperArmorTracker.class) != null) {\n\t\t\tswitch (pointsInTalent(Talent.SUPER_ARMOR)) {\n\t\t\t\tcase 1:\n\t\t\t\t\tdmg = Math.round(dmg*0.67f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tdmg = Math.round(dmg*0.33f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tdmg = Math.round(dmg*0.00f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0: default:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tint preHP = HP + shielding();\n\t\tif (src instanceof Hunger) preHP -= shielding();\n\t\tsuper.damage( dmg, src );\n\t\tint postHP = HP + shielding();\n\t\tif (src instanceof Hunger) postHP -= shielding();\n\t\tint effectiveDamage = preHP - postHP;\n\n\t\tif (effectiveDamage <= 0) return;\n\n\t\tif (buff(Challenge.DuelParticipant.class) != null){\n\t\t\tbuff(Challenge.DuelParticipant.class).addDamage(effectiveDamage);\n\t\t}\n\n\t\t//flash red when hit for serious damage.\n\t\tfloat percentDMG = effectiveDamage / (float)preHP; //percent of current HP that was taken\n\t\tfloat percentHP = 1 - ((HT - postHP) / (float)HT); //percent health after damage was taken\n\t\t// The flash intensity increases primarily based on damage taken and secondarily on missing HP.\n\t\tfloat flashIntensity = 0.25f * (percentDMG * percentDMG) / percentHP;\n\t\t//if the intensity is very low don't flash at all\n\t\tif (flashIntensity >= 0.05f){\n\t\t\tflashIntensity = Math.min(1/3f, flashIntensity); //cap intensity at 1/3\n\t\t\tGameScene.flash( (int)(0xFF*flashIntensity) << 16 );\n\t\t\tif (isAlive()) {\n\t\t\t\tif (flashIntensity >= 1/6f) {\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HEALTH_CRITICAL, 1/3f + flashIntensity * 2f);\n\t\t\t\t} else {\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HEALTH_WARN, 1/3f + flashIntensity * 4f);\n\t\t\t\t}\n\t\t\t\t//hero gets interrupted on taking serious damage, regardless of any other factor\n\t\t\t\tinterrupt();\n\t\t\t\tresting = false;\n\t\t\t\tdamageInterrupt = true;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void checkVisibleMobs() {\n\t\tArrayList<Mob> visible = new ArrayList<>();\n\n\t\tboolean newMob = false;\n\n\t\tMob target = null;\n\t\tfor (Mob m : Dungeon.level.mobs.toArray(new Mob[0])) {\n\t\t\tif (fieldOfView[ m.pos ] && m.alignment == Alignment.ENEMY) {\n\t\t\t\tvisible.add(m);\n\t\t\t\tif (!visibleEnemies.contains( m )) {\n\t\t\t\t\tnewMob = true;\n\t\t\t\t}\n\n\t\t\t\tif (!mindVisionEnemies.contains(m) && QuickSlotButton.autoAim(m) != -1){\n\t\t\t\t\tif (target == null){\n\t\t\t\t\t\ttarget = m;\n\t\t\t\t\t} else if (distance(target) > distance(m)) {\n\t\t\t\t\t\ttarget = m;\n\t\t\t\t\t}\n\t\t\t\t\tif (m instanceof Snake && Dungeon.level.distance(m.pos, pos) <= 4\n\t\t\t\t\t\t\t&& !Document.ADVENTURERS_GUIDE.isPageRead(Document.GUIDE_EXAMINING)){\n\t\t\t\t\t\tGLog.p(Messages.get(Guidebook.class, \"hint\"));\n\t\t\t\t\t\tGameScene.flashForDocument(Document.ADVENTURERS_GUIDE, Document.GUIDE_EXAMINING);\n\t\t\t\t\t\t//we set to read here to prevent this message popping up a bunch\n\t\t\t\t\t\tDocument.ADVENTURERS_GUIDE.readPage(Document.GUIDE_EXAMINING);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tChar lastTarget = QuickSlotButton.lastTarget;\n\t\tif (target != null && (lastTarget == null ||\n\t\t\t\t\t\t\t!lastTarget.isAlive() || !lastTarget.isActive() ||\n\t\t\t\t\t\t\tlastTarget.alignment == Alignment.ALLY ||\n\t\t\t\t\t\t\t!fieldOfView[lastTarget.pos])){\n\t\t\tQuickSlotButton.target(target);\n\t\t}\n\t\t\n\t\tif (newMob) {\n\t\t\tinterrupt();\n\t\t\tif (resting){\n\t\t\t\tDungeon.observe();\n\t\t\t\tresting = false;\n\t\t\t}\n\t\t}\n\n\t\tvisibleEnemies = visible;\n\t}\n\t\n\tpublic int visibleEnemies() {\n\t\treturn visibleEnemies.size();\n\t}\n\t\n\tpublic Mob visibleEnemy( int index ) {\n\t\treturn visibleEnemies.get(index % visibleEnemies.size());\n\t}\n\n\tpublic ArrayList<Mob> getVisibleEnemies(){\n\t\treturn new ArrayList<>(visibleEnemies);\n\t}\n\t\n\tprivate boolean walkingToVisibleTrapInFog = false;\n\t\n\t//FIXME this is a fairly crude way to track this, really it would be nice to have a short\n\t//history of hero actions\n\tpublic boolean justMoved = false;\n\t\n\tprivate boolean getCloser( final int target ) {\n\n\t\tif (target == pos)\n\t\t\treturn false;\n\n\t\tif (rooted) {\n\t\t\tPixelScene.shake( 1, 1f );\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tint step = -1;\n\t\t\n\t\tif (Dungeon.level.adjacent( pos, target )) {\n\n\t\t\tpath = null;\n\n\t\t\tif (Actor.findChar( target ) == null) {\n\t\t\t\tif (Dungeon.level.passable[target] || Dungeon.level.avoid[target]) {\n\t\t\t\t\tstep = target;\n\t\t\t\t}\n\t\t\t\tif (walkingToVisibleTrapInFog\n\t\t\t\t\t\t&& Dungeon.level.traps.get(target) != null\n\t\t\t\t\t\t&& Dungeon.level.traps.get(target).visible){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t} else {\n\n\t\t\tboolean newPath = false;\n\t\t\tif (path == null || path.isEmpty() || !Dungeon.level.adjacent(pos, path.getFirst()))\n\t\t\t\tnewPath = true;\n\t\t\telse if (path.getLast() != target)\n\t\t\t\tnewPath = true;\n\t\t\telse {\n\t\t\t\tif (!Dungeon.level.passable[path.get(0)] || Actor.findChar(path.get(0)) != null) {\n\t\t\t\t\tnewPath = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (newPath) {\n\n\t\t\t\tint len = Dungeon.level.length();\n\t\t\t\tboolean[] p = Dungeon.level.passable;\n\t\t\t\tboolean[] v = Dungeon.level.visited;\n\t\t\t\tboolean[] m = Dungeon.level.mapped;\n\t\t\t\tboolean[] passable = new boolean[len];\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\tpassable[i] = p[i] && (v[i] || m[i]);\n\t\t\t\t}\n\n\t\t\t\tPathFinder.Path newpath = Dungeon.findPath(this, target, passable, fieldOfView, true);\n\t\t\t\tif (newpath != null && path != null && newpath.size() > 2*path.size()){\n\t\t\t\t\tpath = null;\n\t\t\t\t} else {\n\t\t\t\t\tpath = newpath;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (path == null) return false;\n\t\t\tstep = path.removeFirst();\n\n\t\t}\n\n\t\tif (step != -1) {\n\n\t\t\tfloat delay = 1 / speed();\n\n\t\t\tif (Dungeon.level.pit[step] && !Dungeon.level.solid[step]\n\t\t\t\t\t&& (!flying || buff(Levitation.class) != null && buff(Levitation.class).detachesWithinDelay(delay))){\n\t\t\t\tif (!Chasm.jumpConfirmed){\n\t\t\t\t\tChasm.heroJump(this);\n\t\t\t\t\tinterrupt();\n\t\t\t\t} else {\n\t\t\t\t\tflying = false;\n\t\t\t\t\tremove(buff(Levitation.class)); //directly remove to prevent cell pressing\n\t\t\t\t\tChasm.heroFall(target);\n\t\t\t\t}\n\t\t\t\tcanSelfTrample = false;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif ((hero.belongings.weapon instanceof Lance ||\n\t\t\t\t\thero.belongings.secondWep instanceof Lance ||\n\t\t\t\t\t(hero.belongings.weapon instanceof LanceNShield && ((LanceNShield)hero.belongings.weapon).stance) ||\n\t\t\t\t\t(hero.belongings.secondWep instanceof LanceNShield && ((LanceNShield)hero.belongings.secondWep).stance))) {\n\t\t\t\tBuff.affect(this, Lance.LanceBuff.class).setDamageFactor(1 + (hero.speed()), hero.belongings.secondWep instanceof Lance || (hero.belongings.secondWep instanceof LanceNShield && ((LanceNShield) hero.belongings.secondWep).stance));\n\t\t\t}\n\n\t\t\tif (subClass == HeroSubClass.FREERUNNER){\n\t\t\t\tBuff.affect(this, Momentum.class).gainStack();\n\t\t\t}\n\n\t\t\tif (hero.buff(Talent.RollingTracker.class) != null && hero.belongings.weapon instanceof Gun && Dungeon.bullet > 1) {\n\t\t\t\tDungeon.bullet --;\n\t\t\t\t((Gun)hero.belongings.weapon).manualReload();\n\t\t\t\thero.buff(Talent.RollingTracker.class).detach();\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.QUICK_RELOAD) && hero.belongings.weapon instanceof Gun && Random.Float() < 0.03f * hero.pointsInTalent(Talent.QUICK_RELOAD) && Dungeon.bullet > 1) {\n\t\t\t\tDungeon.bullet --;\n\t\t\t\t((Gun)hero.belongings.weapon).manualReload();\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.MIND_VISION) && Random.Float() < 0.01f*hero.pointsInTalent(Talent.MIND_VISION)) {\n\t\t\t\tBuff.affect(this, MindVision.class, 1f);\n\t\t\t}\n\t\t\t\n\t\t\tsprite.move(pos, step);\n\t\t\tmove(step);\n\n\t\t\tif (buff(Talent.QuickStep.class) != null) {\n\t\t\t\tspend(-delay);\n\t\t\t\tbuff(Talent.QuickStep.class).detach();\n\t\t\t}\n\n\t\t\tspend( delay );\n\t\t\tjustMoved = true;\n\t\t\t\n\t\t\tsearch(false);\n\n\t\t\treturn true;\n\n\t\t} else {\n\n\t\t\treturn false;\n\t\t\t\n\t\t}\n\n\t}\n\t\n\tpublic boolean handle( int cell ) {\n\t\t\n\t\tif (cell == -1) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (fieldOfView == null || fieldOfView.length != Dungeon.level.length()){\n\t\t\tfieldOfView = new boolean[Dungeon.level.length()];\n\t\t\tDungeon.level.updateFieldOfView( this, fieldOfView );\n\t\t}\n\t\t\n\t\tChar ch = Actor.findChar( cell );\n\t\tHeap heap = Dungeon.level.heaps.get( cell );\n\n\t\tif (Dungeon.level.map[cell] == Terrain.ALCHEMY && cell != pos) {\n\t\t\t\n\t\t\tcurAction = new HeroAction.Alchemy( cell );\n\t\t\t\n\t\t} else if (fieldOfView[cell] && ch instanceof Mob) {\n\n\t\t\tif (ch.alignment != Alignment.ENEMY && ch.buff(Amok.class) == null) {\n\t\t\t\tcurAction = new HeroAction.Interact( ch );\n\t\t\t} else {\n\t\t\t\tcurAction = new HeroAction.Attack( ch );\n\t\t\t}\n\n\t\t//TODO perhaps only trigger this if hero is already adjacent? reducing mistaps\n\t\t} else if (Dungeon.level instanceof MiningLevel &&\n\t\t\t\t\tbelongings.getItem(Pickaxe.class) != null &&\n\t\t\t\t(Dungeon.level.map[cell] == Terrain.WALL\n\t\t\t\t\t\t|| Dungeon.level.map[cell] == Terrain.WALL_DECO\n\t\t\t\t\t\t|| Dungeon.level.map[cell] == Terrain.MINE_CRYSTAL\n\t\t\t\t\t\t|| Dungeon.level.map[cell] == Terrain.MINE_BOULDER)){\n\n\t\t\tcurAction = new HeroAction.Mine( cell );\n\n\t\t} else if (heap != null\n\t\t\t\t//moving to an item doesn't auto-pickup when enemies are near...\n\t\t\t\t&& (visibleEnemies.size() == 0 || cell == pos ||\n\t\t\t\t//...but only for standard heaps. Chests and similar open as normal.\n\t\t\t\t(heap.type != Type.HEAP && heap.type != Type.FOR_SALE))) {\n\n\t\t\tswitch (heap.type) {\n\t\t\tcase HEAP:\n\t\t\t\tcurAction = new HeroAction.PickUp( cell );\n\t\t\t\tbreak;\n\t\t\tcase FOR_SALE:\n\t\t\t\tcurAction = heap.size() == 1 && heap.peek().value() > 0 ?\n\t\t\t\t\tnew HeroAction.Buy( cell ) :\n\t\t\t\t\tnew HeroAction.PickUp( cell );\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tcurAction = new HeroAction.OpenChest( cell );\n\t\t\t}\n\t\t\t\n\t\t} else if (Dungeon.level.map[cell] == Terrain.LOCKED_DOOR || Dungeon.level.map[cell] == Terrain.CRYSTAL_DOOR || Dungeon.level.map[cell] == Terrain.LOCKED_EXIT) {\n\t\t\t\n\t\t\tcurAction = new HeroAction.Unlock( cell );\n\t\t\t\n\t\t} else if (Dungeon.level.getTransition(cell) != null\n\t\t\t\t//moving to a transition doesn't automatically trigger it when enemies are near\n\t\t\t\t&& (visibleEnemies.size() == 0 || cell == pos)\n\t\t\t\t&& !Dungeon.level.locked\n\t\t\t\t&& (Dungeon.depth < 31 || Dungeon.level.getTransition(cell).type == LevelTransition.Type.REGULAR_ENTRANCE) ) {\n\n\t\t\tcurAction = new HeroAction.LvlTransition( cell );\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tif (!Dungeon.level.visited[cell] && !Dungeon.level.mapped[cell]\n\t\t\t\t\t&& Dungeon.level.traps.get(cell) != null && Dungeon.level.traps.get(cell).visible) {\n\t\t\t\twalkingToVisibleTrapInFog = true;\n\t\t\t} else {\n\t\t\t\twalkingToVisibleTrapInFog = false;\n\t\t\t}\n\t\t\t\n\t\t\tcurAction = new HeroAction.Move( cell );\n\t\t\tlastAction = null;\n\t\t\t\n\t\t}\n\n\t\treturn true;\n\t}\n\t\n\tpublic void earnExp( int exp, Class source ) {\n\n\t\t//xp granted by ascension challenge is only for on-exp gain effects\n\t\tif (source != AscensionChallenge.class) {\n\t\t\tthis.exp += exp;\n\t\t}\n\t\tfloat percent = exp/(float)maxExp();\n\n\t\tEtherealChains.chainsRecharge chains = buff(EtherealChains.chainsRecharge.class);\n\t\tif (chains != null) chains.gainExp(percent);\n\n\t\tHornOfPlenty.hornRecharge horn = buff(HornOfPlenty.hornRecharge.class);\n\t\tif (horn != null) horn.gainCharge(percent);\n\t\t\n\t\tAlchemistsToolkit.kitEnergy kit = buff(AlchemistsToolkit.kitEnergy.class);\n\t\tif (kit != null) kit.gainCharge(percent);\n\n\t\tMasterThievesArmband.Thievery armband = buff(MasterThievesArmband.Thievery.class);\n\t\tif (armband != null) armband.gainCharge(percent);\n\t\t\n\t\tBerserk berserk = buff(Berserk.class);\n\t\tif (berserk != null) berserk.recover(percent);\n\t\t\n\t\tif (source != PotionOfExperience.class) {\n\t\t\tfor (Item i : belongings) {\n\t\t\t\ti.onHeroGainExp(percent, this);\n\t\t\t}\n\t\t\tif (buff(Talent.RejuvenatingStepsFurrow.class) != null){\n\t\t\t\tbuff(Talent.RejuvenatingStepsFurrow.class).countDown(percent*200f);\n\t\t\t\tif (buff(Talent.RejuvenatingStepsFurrow.class).count() <= 0){\n\t\t\t\t\tbuff(Talent.RejuvenatingStepsFurrow.class).detach();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (buff(ElementalStrike.ElementalStrikeFurrowCounter.class) != null){\n\t\t\t\tbuff(ElementalStrike.ElementalStrikeFurrowCounter.class).countDown(percent*20f);\n\t\t\t\tif (buff(ElementalStrike.ElementalStrikeFurrowCounter.class).count() <= 0){\n\t\t\t\t\tbuff(ElementalStrike.ElementalStrikeFurrowCounter.class).detach();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tboolean levelUp = false;\n\t\twhile (this.exp >= maxExp()) {\n\t\t\tthis.exp -= maxExp();\n\t\t\tif (lvl < MAX_LEVEL) {\n\t\t\t\tlvl++;\n\t\t\t\tlevelUp = true;\n\t\t\t\t\n\t\t\t\tif (buff(ElixirOfMight.HTBoost.class) != null){\n\t\t\t\t\tbuff(ElixirOfMight.HTBoost.class).onLevelUp();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tupdateHT( true );\n\t\t\t\tattackSkill++;\n\t\t\t\tdefenseSkill++;\n\n\t\t\t} else {\n\t\t\t\tBuff.prolong(this, Bless.class, Bless.DURATION);\n\t\t\t\tthis.exp = 0;\n\n\t\t\t\tGLog.newLine();\n\t\t\t\tGLog.p( Messages.get(this, \"level_cap\"));\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.LEVELUP );\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tif (levelUp) {\n\t\t\t\n\t\t\tif (sprite != null) {\n\t\t\t\tGLog.newLine();\n\t\t\t\tGLog.p( Messages.get(this, \"new_level\") );\n\t\t\t\tsprite.showStatus( CharSprite.POSITIVE, Messages.get(Hero.class, \"level_up\") );\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.LEVELUP );\n\t\t\t\tif (lvl < Talent.tierLevelThresholds[Talent.MAX_TALENT_TIERS+1]){\n\t\t\t\t\tGLog.newLine();\n\t\t\t\t\tGLog.p( Messages.get(this, \"new_talent\") );\n\t\t\t\t\tStatusPane.talentBlink = 10f;\n\t\t\t\t\tWndHero.lastIdx = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tItem.updateQuickslot();\n\t\t\t\n\t\t\tBadges.validateLevelReached();\n\t\t}\n\t}\n\t\n\tpublic int maxExp() {\n\t\treturn maxExp( lvl );\n\t}\n\t\n\tpublic static int maxExp( int lvl ){\n\t\treturn 5 + lvl * 5;\n\t}\n\t\n\tpublic boolean isStarving() {\n\t\treturn Buff.affect(this, Hunger.class).isStarving();\n\t}\n\t\n\t@Override\n\tpublic boolean add( Buff buff ) {\n\n\t\tif (buff(TimekeepersHourglass.timeStasis.class) != null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tboolean added = super.add( buff );\n\n\t\tif (sprite != null && added) {\n\t\t\tString msg = buff.heroMessage();\n\t\t\tif (msg != null){\n\t\t\t\tGLog.w(msg);\n\t\t\t}\n\n\t\t\tif (buff instanceof Paralysis || buff instanceof Vertigo) {\n\t\t\t\tinterrupt();\n\t\t\t}\n\n\t\t}\n\t\t\n\t\tBuffIndicator.refreshHero();\n\n\t\treturn added;\n\t}\n\t\n\t@Override\n\tpublic boolean remove( Buff buff ) {\n\t\tif (super.remove( buff )) {\n\t\t\tBuffIndicator.refreshHero();\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic float stealth() {\n\t\tfloat stealth = super.stealth();\n\t\t\n\t\tif (belongings.armor() != null){\n\t\t\tstealth = belongings.armor().stealthFactor(this, stealth);\n\t\t}\n\t\t\n\t\treturn stealth;\n\t}\n\t\n\t@Override\n\tpublic void die( Object cause ) {\n\n\t\tif (buff(Enduring.class) != null) {\n\t\t\tthis.HP = 1;\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tcurAction = null;\n\n\t\tAnkh ankh = null;\n\n\t\t//look for ankhs in player inventory, prioritize ones which are blessed.\n\t\tfor (Ankh i : belongings.getAllItems(Ankh.class)){\n\t\t\tif (ankh == null || i.isBlessed()) {\n\t\t\t\tankh = i;\n\t\t\t}\n\t\t}\n\n\t\tif (ankh != null) {\n\t\t\tinterrupt();\n\t\t\tresting = false;\n\n\t\t\tif (ankh.isBlessed()) {\n\t\t\t\tthis.HP = HT / 4;\n\n\t\t\t\tPotionOfHealing.cure(this);\n\t\t\t\tBuff.prolong(this, AnkhInvulnerability.class, AnkhInvulnerability.DURATION);\n\n\t\t\t\tSpellSprite.show(this, SpellSprite.ANKH);\n\t\t\t\tGameScene.flash(0x80FFFF40);\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TELEPORT);\n\t\t\t\tGLog.w(Messages.get(this, \"revive\"));\n\t\t\t\tStatistics.ankhsUsed++;\n\n\t\t\t\tankh.detach(belongings.backpack);\n\n\t\t\t\tfor (Char ch : Actor.chars()) {\n\t\t\t\t\tif (ch instanceof DriedRose.GhostHero) {\n\t\t\t\t\t\t((DriedRose.GhostHero) ch).sayAnhk();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\n\t\t\t\t//this is hacky, basically we want to declare that a wndResurrect exists before\n\t\t\t\t//it actually gets created. This is important so that the game knows to not\n\t\t\t\t//delete the run or submit it to rankings, because a WndResurrect is about to exist\n\t\t\t\t//this is needed because the actual creation of the window is delayed here\n\t\t\t\tWndResurrect.instance = new Object();\n\t\t\t\tAnkh finalAnkh = ankh;\n\t\t\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\tGameScene.show( new WndResurrect(finalAnkh) );\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (cause instanceof Hero.Doom) {\n\t\t\t\t\t((Hero.Doom)cause).onDeath();\n\t\t\t\t}\n\n\t\t\t\tSacrificialFire.Marked sacMark = buff(SacrificialFire.Marked.class);\n\t\t\t\tif (sacMark != null){\n\t\t\t\t\tsacMark.detach();\n\t\t\t\t}\n\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tActor.fixTime();\n\t\tsuper.die( cause );\n\t\treallyDie( cause );\n\t}\n\t\n\tpublic static void reallyDie( Object cause ) {\n\t\t\n\t\tint length = Dungeon.level.length();\n\t\tint[] map = Dungeon.level.map;\n\t\tboolean[] visited = Dungeon.level.visited;\n\t\tboolean[] discoverable = Dungeon.level.discoverable;\n\t\t\n\t\tfor (int i=0; i < length; i++) {\n\t\t\t\n\t\t\tint terr = map[i];\n\t\t\t\n\t\t\tif (discoverable[i]) {\n\t\t\t\t\n\t\t\t\tvisited[i] = true;\n\t\t\t\tif ((Terrain.flags[terr] & Terrain.SECRET) != 0) {\n\t\t\t\t\tDungeon.level.discover( i );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tBones.leave();\n\t\t\n\t\tDungeon.observe();\n\t\tGameScene.updateFog();\n\t\t\t\t\n\t\tDungeon.hero.belongings.identify();\n\n\t\tint pos = Dungeon.hero.pos;\n\n\t\tArrayList<Integer> passable = new ArrayList<>();\n\t\tfor (Integer ofs : PathFinder.NEIGHBOURS8) {\n\t\t\tint cell = pos + ofs;\n\t\t\tif ((Dungeon.level.passable[cell] || Dungeon.level.avoid[cell]) && Dungeon.level.heaps.get( cell ) == null) {\n\t\t\t\tpassable.add( cell );\n\t\t\t}\n\t\t}\n\t\tCollections.shuffle( passable );\n\n\t\tArrayList<Item> items = new ArrayList<>(Dungeon.hero.belongings.backpack.items);\n\t\tfor (Integer cell : passable) {\n\t\t\tif (items.isEmpty()) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tItem item = Random.element( items );\n\t\t\tDungeon.level.drop( item, cell ).sprite.drop( pos );\n\t\t\titems.remove( item );\n\t\t}\n\n\t\tfor (Char c : Actor.chars()){\n\t\t\tif (c instanceof DriedRose.GhostHero){\n\t\t\t\t((DriedRose.GhostHero) c).sayHeroKilled();\n\t\t\t}\n\t\t}\n\n\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t@Override\n\t\t\tpublic void call() {\n\t\t\t\tGameScene.gameOver();\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.DEATH );\n\t\t\t}\n\t\t});\n\n\t\tif (cause instanceof Hero.Doom) {\n\t\t\t((Hero.Doom)cause).onDeath();\n\t\t}\n\n\t\tDungeon.deleteGame( GamesInProgress.curSlot, true );\n\t}\n\n\t//effectively cache this buff to prevent having to call buff(...) a bunch.\n\t//This is relevant because we call isAlive during drawing, which has both performance\n\t//and thread coordination implications if that method calls buff(...) frequently\n\tprivate Berserk berserk;\n\n\t@Override\n\tpublic boolean isAlive() {\n\t\t\n\t\tif (HP <= 0){\n\t\t\tif (berserk == null) berserk = buff(Berserk.class);\n\t\t\treturn berserk != null && berserk.berserking();\n\t\t} else {\n\t\t\tberserk = null;\n\t\t\treturn super.isAlive();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void move(int step, boolean travelling) {\n\t\tboolean wasHighGrass = Dungeon.level.map[step] == Terrain.HIGH_GRASS;\n\n\t\tsuper.move( step, travelling);\n\t\t\n\t\tif (!flying && travelling) {\n\t\t\tif (Dungeon.level.water[pos]) {\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.WATER, 1, Random.Float( 0.8f, 1.25f ) );\n\t\t\t} else if (Dungeon.level.map[pos] == Terrain.EMPTY_SP) {\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.STURDY, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t} else if (Dungeon.level.map[pos] == Terrain.GRASS\n\t\t\t\t\t|| Dungeon.level.map[pos] == Terrain.EMBERS\n\t\t\t\t\t|| Dungeon.level.map[pos] == Terrain.FURROWED_GRASS){\n\t\t\t\tif (step == pos && wasHighGrass) {\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TRAMPLE, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t\t} else {\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.GRASS, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.STEP, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void onAttackComplete() {\n\n\t\tif (enemy == null){\n\t\t\tcurAction = null;\n\t\t\tsuper.onAttackComplete();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tAttackIndicator.target(enemy);\n\t\tboolean wasEnemy = enemy.alignment == Alignment.ENEMY\n\t\t\t\t|| (enemy instanceof Mimic && enemy.alignment == Alignment.NEUTRAL);\n\n\t\tboolean hit = attack( enemy );\n\t\t\n\t\tInvisibility.dispel();\n\t\tspend( attackDelay() );\n\n\t\tif (hit && subClass == HeroSubClass.GLADIATOR && wasEnemy){\n\t\t\tBuff.affect( this, Combo.class ).hit( enemy );\n\t\t}\n\n\t\tif (hit && subClass == HeroSubClass.BATTLEMAGE && hero.belongings.attackingWeapon() instanceof MagesStaff && hero.hasTalent(Talent.BATTLE_MAGIC) && wasEnemy) {\n\t\t\tBuff.affect( this, MagicalCombo.class).hit( enemy );\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.CHASER\n\t\t\t\t&& hero.hasTalent(Talent.CHAIN_CLOCK)\n\t\t\t\t&& ((Mob) enemy).surprisedBy(hero)\n\t\t\t\t&& hero.buff(Talent.ChainCooldown.class) == null){\n\t\t\tBuff.affect( this, Invisibility.class, 1f * hero.pointsInTalent(Talent.CHAIN_CLOCK));\n\t\t\tBuff.affect( this, Haste.class, 1f * hero.pointsInTalent(Talent.CHAIN_CLOCK));\n\t\t\tBuff.affect( this, Talent.ChainCooldown.class, 10f);\n\t\t\tSample.INSTANCE.play( Assets.Sounds.MELD );\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.CHASER\n\t\t\t\t&& hero.hasTalent(Talent.LETHAL_SURPRISE)\n\t\t\t\t&& ((Mob) enemy).surprisedBy(hero)\n\t\t\t\t&& !enemy.isAlive()\n\t\t\t\t&& hero.buff(Talent.LethalCooldown.class) == null) {\n\t\t\tif (hero.pointsInTalent(Talent.LETHAL_SURPRISE) >= 1) {\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] )) {\n\t\t\t\t\tif (mob.alignment != Char.Alignment.ALLY && Dungeon.level.heroFOV[mob.pos]) {\n\t\t\t\t\t\tBuff.affect( mob, Vulnerable.class, 1f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tBuff.affect(hero, Talent.LethalCooldown.class, 5f);\n\t\t\t}\n\t\t\tif (hero.pointsInTalent(Talent.LETHAL_SURPRISE) >= 2) {\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] )) {\n\t\t\t\t\tif (mob.alignment != Char.Alignment.ALLY && Dungeon.level.heroFOV[mob.pos]) {\n\t\t\t\t\t\tBuff.affect( mob, Paralysis.class, 1f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hero.pointsInTalent(Talent.LETHAL_SURPRISE) == 3) {\n\t\t\t\tBuff.affect(hero, Swiftthistle.TimeBubble.class).twoTurns();\n\t\t\t}\n\t\t}\n\n\t\tif (hit && heroClass == HeroClass.DUELIST && wasEnemy){\n\t\t\tBuff.affect( this, Sai.ComboStrikeTracker.class).addHit();\n\t\t}\n\n\t\tRingOfForce.BrawlersStance brawlStance = buff(RingOfForce.BrawlersStance.class);\n\t\tif (brawlStance != null && brawlStance.hitsLeft() > 0){\n\t\t\tMeleeWeapon.Charger charger = Buff.affect(this, MeleeWeapon.Charger.class);\n\t\t\tcharger.partialCharge -= RingOfForce.BrawlersStance.HIT_CHARGE_USE;\n\t\t\twhile (charger.partialCharge < 0) {\n\t\t\t\tcharger.charges--;\n\t\t\t\tcharger.partialCharge++;\n\t\t\t}\n\t\t\tBuffIndicator.refreshHero();\n\t\t\tItem.updateQuickslot();\n\t\t}\n\n\t\tif (!hit && hero.belongings.weapon == null && hero.subClass == HeroSubClass.FIGHTER && Random.Int(5) == 0 && hero.pointsInTalent(Talent.SWIFT_MOVEMENT) > 1) {\n\t\t\tBuff.prolong(hero, EvasiveMove.class, 0.9999f);\n\t\t}\n\n\t\tcurAction = null;\n\n\t\tsuper.onAttackComplete();\n\t}\n\t\n\t@Override\n\tpublic void onMotionComplete() {\n\t\tGameScene.checkKeyHold();\n\t}\n\t\n\t@Override\n\tpublic void onOperateComplete() {\n\t\t\n\t\tif (curAction instanceof HeroAction.Unlock) {\n\n\t\t\tint doorCell = ((HeroAction.Unlock)curAction).dst;\n\t\t\tint door = Dungeon.level.map[doorCell];\n\t\t\t\n\t\t\tif (Dungeon.level.distance(pos, doorCell) <= 1) {\n\t\t\t\tboolean hasKey = true;\n\t\t\t\tif (door == Terrain.LOCKED_DOOR) {\n\t\t\t\t\thasKey = Notes.remove(new IronKey(Dungeon.depth));\n\t\t\t\t\tif (hasKey) Level.set(doorCell, Terrain.DOOR);\n\t\t\t\t} else if (door == Terrain.CRYSTAL_DOOR) {\n\t\t\t\t\thasKey = Notes.remove(new CrystalKey(Dungeon.depth, Dungeon.branch));\n\t\t\t\t\tif (hasKey) {\n\t\t\t\t\t\tLevel.set(doorCell, Terrain.EMPTY);\n\t\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TELEPORT);\n\t\t\t\t\t\tCellEmitter.get( doorCell ).start( Speck.factory( Speck.DISCOVER ), 0.025f, 20 );\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\thasKey = Notes.remove(new SkeletonKey(Dungeon.depth));\n\t\t\t\t\tif (hasKey) Level.set(doorCell, Terrain.UNLOCKED_EXIT);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (hasKey) {\n\t\t\t\t\tGameScene.updateKeyDisplay();\n\t\t\t\t\tGameScene.updateMap(doorCell);\n\t\t\t\t\tspend(Key.TIME_TO_UNLOCK);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t} else if (curAction instanceof HeroAction.OpenChest) {\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( ((HeroAction.OpenChest)curAction).dst );\n\t\t\t\n\t\t\tif (Dungeon.level.distance(pos, heap.pos) <= 1){\n\t\t\t\tboolean hasKey = true;\n\t\t\t\tif (heap.type == Type.SKELETON || heap.type == Type.REMAINS) {\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.BONES );\n\t\t\t\t} else if (heap.type == Type.LOCKED_CHEST){\n\t\t\t\t\thasKey = Notes.remove(new GoldenKey(Dungeon.depth));\n\t\t\t\t} else if (heap.type == Type.CRYSTAL_CHEST){\n\t\t\t\t\thasKey = Notes.remove(new CrystalKey(Dungeon.depth));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (hasKey) {\n\t\t\t\t\tGameScene.updateKeyDisplay();\n\t\t\t\t\theap.open(this);\n\t\t\t\t\tspend(Key.TIME_TO_UNLOCK);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t\tcurAction = null;\n\n\t\tif (!ready) {\n\t\t\tsuper.onOperateComplete();\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean isImmune(Class effect) {\n\t\tif (effect == Burning.class\n\t\t\t\t&& belongings.armor() != null\n\t\t\t\t&& belongings.armor().hasGlyph(Brimstone.class, this)){\n\t\t\treturn true;\n\t\t}\n\t\treturn super.isImmune(effect);\n\t}\n\n\t@Override\n\tpublic boolean isInvulnerable(Class effect) {\n\t\treturn super.isInvulnerable(effect) || buff(AnkhInvulnerability.class) != null;\n\t}\n\n\tpublic boolean search( boolean intentional ) {\n\t\t\n\t\tif (!isAlive()) return false;\n\t\t\n\t\tboolean smthFound = false;\n\n\t\tboolean circular = pointsInTalent(Talent.WIDE_SEARCH) == 1;\n\t\tint distance = heroClass == HeroClass.ROGUE ? 2 : 1;\n\t\tif (hasTalent(Talent.WIDE_SEARCH)) distance++;\n\t\t\n\t\tboolean foresight = buff(Foresight.class) != null;\n\t\tboolean foresightScan = foresight && !Dungeon.level.mapped[pos];\n\n\t\tif (foresightScan){\n\t\t\tDungeon.level.mapped[pos] = true;\n\t\t}\n\n\t\tif (foresight) {\n\t\t\tdistance = Foresight.DISTANCE;\n\t\t\tcircular = true;\n\t\t}\n\n\t\tPoint c = Dungeon.level.cellToPoint(pos);\n\n\t\tTalismanOfForesight.Foresight talisman = buff( TalismanOfForesight.Foresight.class );\n\t\tboolean cursed = talisman != null && talisman.isCursed();\n\n\t\tint[] rounding = ShadowCaster.rounding[distance];\n\n\t\tint left, right;\n\t\tint curr;\n\t\tfor (int y = Math.max(0, c.y - distance); y <= Math.min(Dungeon.level.height()-1, c.y + distance); y++) {\n\t\t\tif (!circular){\n\t\t\t\tleft = c.x - distance;\n\t\t\t} else if (rounding[Math.abs(c.y - y)] < Math.abs(c.y - y)) {\n\t\t\t\tleft = c.x - rounding[Math.abs(c.y - y)];\n\t\t\t} else {\n\t\t\t\tleft = distance;\n\t\t\t\twhile (rounding[left] < rounding[Math.abs(c.y - y)]){\n\t\t\t\t\tleft--;\n\t\t\t\t}\n\t\t\t\tleft = c.x - left;\n\t\t\t}\n\t\t\tright = Math.min(Dungeon.level.width()-1, c.x + c.x - left);\n\t\t\tleft = Math.max(0, left);\n\t\t\tfor (curr = left + y * Dungeon.level.width(); curr <= right + y * Dungeon.level.width(); curr++){\n\n\t\t\t\tif ((foresight || fieldOfView[curr]) && curr != pos) {\n\n\t\t\t\t\tif ((foresight && (!Dungeon.level.mapped[curr] || foresightScan))){\n\t\t\t\t\t\tGameScene.effectOverFog(new CheckedCell(curr, foresightScan ? pos : curr));\n\t\t\t\t\t} else if (intentional) {\n\t\t\t\t\t\tGameScene.effectOverFog(new CheckedCell(curr, pos));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (foresight){\n\t\t\t\t\t\tDungeon.level.mapped[curr] = true;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (Dungeon.level.secret[curr]){\n\t\t\t\t\t\t\n\t\t\t\t\t\tTrap trap = Dungeon.level.traps.get( curr );\n\t\t\t\t\t\tfloat chance;\n\n\t\t\t\t\t\t//searches aided by foresight always succeed, even if trap isn't searchable\n\t\t\t\t\t\tif (foresight){\n\t\t\t\t\t\t\tchance = 1f;\n\n\t\t\t\t\t\t//otherwise if the trap isn't searchable, searching always fails\n\t\t\t\t\t\t} else if (trap != null && !trap.canBeSearched){\n\t\t\t\t\t\t\tchance = 0f;\n\n\t\t\t\t\t\t//intentional searches always succeed against regular traps and doors\n\t\t\t\t\t\t} else if (intentional){\n\t\t\t\t\t\t\tchance = 1f;\n\t\t\t\t\t\t\n\t\t\t\t\t\t//unintentional searches always fail with a cursed talisman\n\t\t\t\t\t\t} else if (cursed) {\n\t\t\t\t\t\t\tchance = 0f;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t//unintentional trap detection scales from 40% at floor 0 to 30% at floor 25\n\t\t\t\t\t\t} else if (Dungeon.level.map[curr] == Terrain.SECRET_TRAP) {\n\t\t\t\t\t\t\tchance = 0.4f - (Dungeon.depth / 250f);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t//unintentional door detection scales from 20% at floor 0 to 0% at floor 20\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tchance = 0.2f - (Dungeon.depth / 100f);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//don't want to let the player search though hidden doors in tutorial\n\t\t\t\t\t\tif (SPDSettings.intro()){\n\t\t\t\t\t\t\tchance = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (Random.Float() < chance) {\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tint oldValue = Dungeon.level.map[curr];\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tGameScene.discoverTile( curr, oldValue );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tDungeon.level.discover( curr );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tScrollOfMagicMapping.discover( curr );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (fieldOfView[curr]) smthFound = true;\n\t\n\t\t\t\t\t\t\tif (talisman != null){\n\t\t\t\t\t\t\t\tif (oldValue == Terrain.SECRET_TRAP){\n\t\t\t\t\t\t\t\t\ttalisman.charge(2);\n\t\t\t\t\t\t\t\t} else if (oldValue == Terrain.SECRET_DOOR){\n\t\t\t\t\t\t\t\t\ttalisman.charge(10);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (intentional) {\n\t\t\tsprite.showStatus( CharSprite.DEFAULT, Messages.get(this, \"search\") );\n\t\t\tsprite.operate( pos );\n\t\t\tif (!Dungeon.level.locked) {\n\t\t\t\tif (cursed) {\n\t\t\t\t\tGLog.n(Messages.get(this, \"search_distracted\"));\n\t\t\t\t\tBuff.affect(this, Hunger.class).affectHunger(TIME_TO_SEARCH - (2 * HUNGER_FOR_SEARCH));\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(this, Hunger.class).affectHunger(TIME_TO_SEARCH - HUNGER_FOR_SEARCH);\n\t\t\t\t}\n\t\t\t}\n\t\t\tspendAndNext(TIME_TO_SEARCH);\n\t\t\t\n\t\t}\n\t\t\n\t\tif (smthFound) {\n\t\t\tGLog.w( Messages.get(this, \"noticed_smth\") );\n\t\t\tSample.INSTANCE.play( Assets.Sounds.SECRET );\n\t\t\tinterrupt();\n\t\t}\n\n\t\tif (foresight){\n\t\t\tGameScene.updateFog(pos, Foresight.DISTANCE+1);\n\t\t}\n\t\t\n\t\treturn smthFound;\n\t}\n\t\n\tpublic void resurrect() {\n\t\tHP = HT;\n\t\tlive();\n\n\t\tMagicalHolster holster = belongings.getItem(MagicalHolster.class);\n\n\t\tBuff.affect(this, LostInventory.class);\n\t\tBuff.affect(this, Invisibility.class, 3f);\n\t\t//lost inventory is dropped in interlevelscene\n\n\t\t//activate items that persist after lost inventory\n\t\t//FIXME this is very messy, maybe it would be better to just have one buff that\n\t\t// handled all items that recharge over time?\n\t\tfor (Item i : belongings){\n\t\t\tif (i instanceof EquipableItem && i.isEquipped(this)){\n\t\t\t\t((EquipableItem) i).activate(this);\n\t\t\t} else if (i instanceof CloakOfShadows && i.keptThroughLostInventory() && hasTalent(Talent.LIGHT_CLOAK)){\n\t\t\t\t((CloakOfShadows) i).activate(this);\n\t\t\t} else if (i instanceof Wand && i.keptThroughLostInventory()){\n\t\t\t\tif (holster != null && holster.contains(i)){\n\t\t\t\t\t((Wand) i).charge(this, MagicalHolster.HOLSTER_SCALE_FACTOR);\n\t\t\t\t} else {\n\t\t\t\t\t((Wand) i).charge(this);\n\t\t\t\t}\n\t\t\t} else if (i instanceof MagesStaff && i.keptThroughLostInventory()){\n\t\t\t\t((MagesStaff) i).applyWandChargeBuff(this);\n\t\t\t}\n\t\t}\n\n\t\tupdateHT(false);\n\t}\n\n\t@Override\n\tpublic void next() {\n\t\tif (isAlive())\n\t\t\tsuper.next();\n\t}\n\n\tpublic static interface Doom {\n\t\tpublic void onDeath();\n\t}\n}" }, { "identifier": "HeroClass", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/hero/HeroClass.java", "snippet": "public enum HeroClass {\n\n\tWARRIOR( HeroSubClass.BERSERKER, HeroSubClass.GLADIATOR, HeroSubClass.VETERAN ),\n\tMAGE( HeroSubClass.BATTLEMAGE, HeroSubClass.WARLOCK, HeroSubClass.WIZARD ),\n\tROGUE( HeroSubClass.ASSASSIN, HeroSubClass.FREERUNNER, HeroSubClass.CHASER ),\n\tHUNTRESS( HeroSubClass.SNIPER, HeroSubClass.WARDEN, HeroSubClass.FIGHTER ),\n\tDUELIST( HeroSubClass.CHAMPION, HeroSubClass.MONK, HeroSubClass.FENCER ),\n\tGUNNER( HeroSubClass.OUTLAW, HeroSubClass.GUNSLINGER, HeroSubClass.SPECIALIST );\n\n\tprivate HeroSubClass[] subClasses;\n\n\tHeroClass( HeroSubClass...subClasses ) {\n\t\tthis.subClasses = subClasses;\n\t}\n\n\tpublic void initHero( Hero hero ) {\n\n\t\thero.heroClass = this;\n\t\tTalent.initClassTalents(hero);\n\n\t\tItem i = new ClothArmor().identify();\n\t\tif (!Challenges.isItemBlocked(i)) hero.belongings.armor = (ClothArmor)i;\n\n\t\ti = new Food();\n\t\tif (!Challenges.isItemBlocked(i)) i.collect();\n\n\t\tnew VelvetPouch().collect();\n\t\tDungeon.LimitedDrops.VELVET_POUCH.drop();\n\n\t\tWaterskin waterskin = new Waterskin();\n\t\twaterskin.collect();\n\n\t\tnew ScrollOfIdentify().identify();\n\n\t\tif (DeviceCompat.isDebug()) {\n//\t\t\tnew RingOfMight().identify().upgrade(10).collect();\n//\t\t\tnew AR_T5().identify().upgrade(100).collect();\n\t\t\tnew RingOfHaste().identify().upgrade(100).collect();\n\t\t\tnew RingOfAccuracy().identify().upgrade(100).collect();\n//\t\t\tnew BulletBelt().quantity(20).collect();\n//\t\t\tnew GunSmithingTool().quantity(20).collect();\n\t\t\tnew AlchemistsToolkit().identify().upgrade(10).collect();\n//\t\t\tnew Evolution().quantity(200).collect();\n//\t\t\tnew PotionOfHealing().identify().quantity(500).collect();\n//\t\t\tnew ScrollOfUpgrade().identify().quantity(500).collect();\n\t\t\tnew Glaive().identify().collect();\n\t\t\tnew Glaive().identify().collect();\n\t\t\tnew Glaive().identify().collect();\n\t\t\tnew Glaive().identify().collect();\n\t\t\tnew Glaive().identify().collect();\n\t\t\tnew Glaive().identify().collect();\n\t\t\tnew Glaive().identify().collect();\n\t\t\tnew BluePrint(new Lance()).collect();\n\t\t\tnew BluePrint(new Lance()).collect();\n\t\t\tnew BluePrint(new Lance()).collect();\n//\t\t\tnew ScrollOfMetamorphosis().identify().quantity(500).collect();\n//\t\t\tnew PotionOfExperience().identify().quantity(29).collect();\n//\t\t\tnew PotionOfStrength().identify().quantity(29).collect();\n//\t\t\tnew PlateArmor().identify().upgrade(100).collect();\n//\t\t\tnew TacticalShield().identify().upgrade(100).collect();\n//\t\t\tnew AR_T1().identify().collect();\n//\t\t\tnew HolySword().identify().collect();\n//\t\t\tnew GunSmithingTool().quantity(200).collect();\n//\t\t\tnew BookOfTransfusion().collect();\n//\t\t\tnew BeamSaber().identify().collect();\n\t\t\tnew Teleporter().collect();\n\t\t\tnew TengusMask().collect();\n\t\t\tnew Pasty().quantity(100).collect();\n//\t\t\tnew ScrollOfPassage().identify().collect();\n//\t\t\tnew LiquidMetal().quantity(500).collect();\n//\t\t\tnew ArcaneResin().quantity(500).collect();\n\t\t\tnew Evolution().quantity(500).collect();\n\t\t\tnew UpgradeDust().quantity(500).collect();\n//\t\t\tnew Spear().identify().collect();\n//\t\t\tnew RoundShield().identify().collect();\n//\t\t\tnew ScrollOfMagicMapping().identify().quantity(100).collect();\n//\t\t\tnew OldAmulet().collect();\n//\t\t\tnew PotionOfMindVision().identify().quantity(100).collect();\n\t\t}\n\n\t\tswitch (this) {\n\t\t\tcase WARRIOR:\n\t\t\t\tinitWarrior( hero );\n\t\t\t\tbreak;\n\n\t\t\tcase MAGE:\n\t\t\t\tinitMage( hero );\n\t\t\t\tbreak;\n\n\t\t\tcase ROGUE:\n\t\t\t\tinitRogue( hero );\n\t\t\t\tbreak;\n\n\t\t\tcase HUNTRESS:\n\t\t\t\tinitHuntress( hero );\n\t\t\t\tbreak;\n\n\t\t\tcase DUELIST:\n\t\t\t\tinitDuelist( hero );\n\t\t\t\tbreak;\n\n\t\t\tcase GUNNER:\n\t\t\t\tinitGunner( hero );\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif (SPDSettings.quickslotWaterskin()) {\n\t\t\tfor (int s = 0; s < QuickSlot.SIZE; s++) {\n\t\t\t\tif (Dungeon.quickslot.getItem(s) == null) {\n\t\t\t\t\tDungeon.quickslot.setSlot(s, waterskin);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic Badges.Badge masteryBadge() {\n\t\tswitch (this) {\n\t\t\tcase WARRIOR:\n\t\t\t\treturn Badges.Badge.MASTERY_WARRIOR;\n\t\t\tcase MAGE:\n\t\t\t\treturn Badges.Badge.MASTERY_MAGE;\n\t\t\tcase ROGUE:\n\t\t\t\treturn Badges.Badge.MASTERY_ROGUE;\n\t\t\tcase HUNTRESS:\n\t\t\t\treturn Badges.Badge.MASTERY_HUNTRESS;\n\t\t\tcase DUELIST:\n\t\t\t\treturn Badges.Badge.MASTERY_DUELIST;\n\t\t\tcase GUNNER:\n\t\t\t\treturn Badges.Badge.MASTERY_GUNNER;\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate static void initWarrior( Hero hero ) {\n\t\t(hero.belongings.weapon = new WornShortsword()).identify();\n\t\tThrowingStone stones = new ThrowingStone();\n\t\tstones.quantity(3).collect();\n\t\tDungeon.quickslot.setSlot(0, stones);\n\n\t\tif (hero.belongings.armor != null){\n\t\t\thero.belongings.armor.affixSeal(new BrokenSeal());\n\t\t}\n\n\t\tnew PotionOfHealing().identify();\n\t\tnew ScrollOfRage().identify();\n\t}\n\n\tprivate static void initMage( Hero hero ) {\n\t\tMagesStaff staff;\n\n\t\tstaff = new MagesStaff(new WandOfMagicMissile());\n\n\t\t(hero.belongings.weapon = staff).identify();\n\t\thero.belongings.weapon.activate(hero);\n\n\t\tDungeon.quickslot.setSlot(0, staff);\n\n\t\tnew ScrollOfUpgrade().identify();\n\t\tnew PotionOfLiquidFlame().identify();\n\t}\n\n\tprivate static void initRogue( Hero hero ) {\n\t\t(hero.belongings.weapon = new Dagger()).identify();\n\n\t\tCloakOfShadows cloak = new CloakOfShadows();\n\t\t(hero.belongings.artifact = cloak).identify();\n\t\thero.belongings.artifact.activate( hero );\n\n\t\tThrowingKnife knives = new ThrowingKnife();\n\t\tknives.quantity(3).collect();\n\n\t\tDungeon.quickslot.setSlot(0, cloak);\n\t\tDungeon.quickslot.setSlot(1, knives);\n\n\t\tnew ScrollOfMagicMapping().identify();\n\t\tnew PotionOfInvisibility().identify();\n\t}\n\n\tprivate static void initHuntress( Hero hero ) {\n\n\t\t(hero.belongings.weapon = new Gloves()).identify();\n\t\tSpiritBow bow = new SpiritBow();\n\t\tbow.identify().collect();\n\n\t\tDungeon.quickslot.setSlot(0, bow);\n\n\t\tnew PotionOfMindVision().identify();\n\t\tnew ScrollOfLullaby().identify();\n\t}\n\n\tprivate static void initDuelist( Hero hero ) {\n\n\t\t(hero.belongings.weapon = new Rapier()).identify();\n\t\thero.belongings.weapon.activate(hero);\n\n\t\tThrowingSpike spikes = new ThrowingSpike();\n\t\tspikes.quantity(2).collect();\n\n\t\tDungeon.quickslot.setSlot(0, hero.belongings.weapon);\n\t\tDungeon.quickslot.setSlot(1, spikes);\n\n\t\tnew PotionOfStrength().identify();\n\t\tnew ScrollOfMirrorImage().identify();\n\t}\n\n\tprivate static void initGunner( Hero hero ) {\n\t\t(hero.belongings.weapon = new AR_T1()).identify();\n\t\thero.belongings.weapon.activate(hero);\n\n\t\tBulletBelt bulletBelt = new BulletBelt();\n\t\tbulletBelt.quantity(5).collect();\n\n\t\tDungeon.quickslot.setSlot(0, hero.belongings.weapon);\n\t\tDungeon.quickslot.setSlot(1, bulletBelt);\n\n\t\tnew PotionOfHaste().identify();\n\t\tnew ScrollOfTeleportation().identify();\n\t}\n\n//\tprivate static void initSamurai( Hero hero ) {\n//\n//\t\t//hero.STR = 8;\n//\n//\t\tWornKatana wornKatana = new WornKatana();\n//\t\t(hero.belongings.weapon = wornKatana).identify();\n//\n//\t\tRingOfVorpal vorpal = new RingOfVorpal();\n//\t\tvorpal.start = true;\n//\t\t(hero.belongings.ring = vorpal).identify();\n//\t\thero.belongings.ring.activate( hero );\n//\n//\t\tThrowingKnife knives = new ThrowingKnife();\n//\t\tknives.quantity(3).collect();\n//\n//\t\tif (Dungeon.isChallenged(Challenges.GAMBLER)) {\n//\t\t\tRingOfWealth wealth = new RingOfWealth();\n//\t\t\t(hero.belongings.misc = wealth).identify();\n//\t\t\thero.belongings.misc.activate( hero );\n//\t\t}\n//\n//\t\tDungeon.quickslot.setSlot(0, knives);\n//\n//\t\tnew ScrollOfRetribution().identify();\n//\t\tnew PotionOfStrength().identify();\n//\t}\n//\n//\tprivate static void initPlanter( Hero hero ) {\n//\t\tShovel shovel = new Shovel();\n//\t\t(hero.belongings.weapon = shovel).identify();\n//\t\thero.belongings.weapon.activate(hero);\n//\t\tThrowingStone stones = new ThrowingStone();\n//\t\tstones.quantity(3).collect();\n//\t\tDungeon.quickslot.setSlot(0, stones);\n//\n//\t\tSandalsOfNature sandals = new SandalsOfNature();\n//\t\tsandals.start = true;\n//\t\tGenerator.Category cat = Generator.Category.ARTIFACT;\n//\t\tcat.probs[7]--; //removes SandalsOfNature in pool\n//\t\t(hero.belongings.artifact = sandals).identify();\n//\t\thero.belongings.artifact.activate(hero);\n//\n//\t\tif (Dungeon.isChallenged(Challenges.GAMBLER)) {\n//\t\t\tRingOfWealth wealth = new RingOfWealth();\n//\t\t\t(hero.belongings.ring = wealth).identify();\n//\t\t\thero.belongings.ring.activate(hero);\n//\t\t}\n//\n//\t\tDungeon.quickslot.setSlot(0, shovel);\n//\t\tDungeon.quickslot.setSlot(1, stones);\n//\n//\t\tnew ScrollOfMirrorImage().identify();\n//\t\tnew PotionOfPurity().identify();\n//\n//\t\t//new Teleporter().collect();\n//\t\t//new MinersTool().identify().collect();\n//\t\t//new RingOfMight().identify().upgrade(10).collect();\n//\t\t//new PlateArmor().identify().upgrade(100).collect();\n//\t}\n//\n//\tprivate static void initKnight( Hero hero ) {\n//\t\tSaber saber = new Saber();\n//\t\t(hero.belongings.weapon = saber).identify();\n//\t\thero.belongings.weapon.activate(hero);\n//\t\tKnightsShield shield = new KnightsShield();\n//\t\tshield.collect();\n//\t\tDungeon.quickslot.setSlot(0, shield);\n//\t\tThrowingStone stones = new ThrowingStone();\n//\t\tstones.quantity(3).collect();\n//\t\tDungeon.quickslot.setSlot(1, stones);\n//\n//\t\tif (Dungeon.isChallenged(Challenges.GAMBLER)) {\n//\t\t\tRingOfWealth wealth = new RingOfWealth();\n//\t\t\t(hero.belongings.ring = wealth).identify();\n//\t\t\thero.belongings.ring.activate( hero );\n//\t\t}\n//\n//\t\tnew ScrollOfRemoveCurse().identify();\n//\t\tnew PotionOfParalyticGas().identify();\n//\t}\n//\n//\tprivate static void initNurse( Hero hero ) {\n//\t\tHealBook healBook = new HealBook();\n//\t\t(hero.belongings.weapon = healBook).identify();\n//\t\thero.belongings.weapon.activate(hero);\n//\n//\t\tGammaRayGun gammaRayGun = new GammaRayGun();\n//\t\tgammaRayGun.collect();\n//\t\tDungeon.quickslot.setSlot(0, gammaRayGun);\n//\n//\t\tHandMirror handMirror = new HandMirror();\n//\t\thandMirror.collect();\n//\t\tDungeon.quickslot.setSlot(1, handMirror);\n//\n//\t\tHealingDart healingDart = new HealingDart();\n//\t\thealingDart.quantity(2).collect();\n//\t\tDungeon.quickslot.setSlot(2, healingDart);\n//\n//\t\tif (Dungeon.isChallenged(Challenges.GAMBLER)) {\n//\t\t\tRingOfWealth wealth = new RingOfWealth();\n//\t\t\t(hero.belongings.ring = wealth).identify();\n//\t\t\thero.belongings.ring.activate(hero);\n//\t\t}\n//\n//\t\tnew ScrollOfMirrorImage().identify();\n//\t\tnew PotionOfHealing().identify();\n//\t}\n\n\tpublic String title() {\n\t\treturn Messages.get(HeroClass.class, name());\n\t}\n\n\tpublic String desc(){\n\t\treturn Messages.get(HeroClass.class, name()+\"_desc\");\n\t}\n\n\tpublic String shortDesc(){\n\t\treturn Messages.get(HeroClass.class, name()+\"_desc_short\");\n\t}\n\n\tpublic HeroSubClass[] subClasses() {\n\t\treturn subClasses;\n\t}\n\n\tpublic ArmorAbility[] armorAbilities(){\n\t\tswitch (this) {\n\t\t\tcase WARRIOR: default:\n\t\t\t\treturn new ArmorAbility[]{new HeroicLeap(), new Shockwave(), new Endure()};\n\t\t\tcase MAGE:\n\t\t\t\treturn new ArmorAbility[]{new ElementalBlast(), new WildMagic(), new WarpBeacon()};\n\t\t\tcase ROGUE:\n\t\t\t\treturn new ArmorAbility[]{new SmokeBomb(), new DeathMark(), new ShadowClone()};\n\t\t\tcase HUNTRESS:\n\t\t\t\treturn new ArmorAbility[]{new SpectralBlades(), new NaturesPower(), new SpiritHawk()};\n\t\t\tcase DUELIST:\n\t\t\t\treturn new ArmorAbility[]{new Challenge(), new ElementalStrike(), new Feint()};\n\t\t\tcase GUNNER:\n\t\t\t\treturn new ArmorAbility[]{new Riot(), new ReinforcedArmor(), new FirstAidKit()};\n//\t\t\tcase SAMURAI:\n//\t\t\t\treturn new ArmorAbility[]{new Awake(), new ShadowBlade(), new Abil_Kunai()};\n//\t\t\tcase PLANTER:\n//\t\t\t\treturn new ArmorAbility[]{new Sprout(), new TreasureMap(), new Root()};\n//\t\t\tcase KNIGHT:\n//\t\t\t\treturn new ArmorAbility[]{new HolyShield(), new StimPack(), new UnstableAnkh()};\n//\t\t\tcase NURSE:\n//\t\t\t\treturn new ArmorAbility[]{new HealareaGenerator(), new AngelWing(), new GammaRayEmmit()};\n\t\t}\n\t}\n\n\tpublic String spritesheet() {\n\t\tswitch (this) {\n\t\t\tcase WARRIOR: default:\n\t\t\t\treturn Assets.Sprites.WARRIOR;\n\t\t\tcase MAGE:\n\t\t\t\treturn Assets.Sprites.MAGE;\n\t\t\tcase ROGUE:\n\t\t\t\treturn Assets.Sprites.ROGUE;\n\t\t\tcase HUNTRESS:\n\t\t\t\treturn Assets.Sprites.HUNTRESS;\n\t\t\tcase DUELIST:\n\t\t\t\treturn Assets.Sprites.DUELIST;\n\t\t\tcase GUNNER:\n\t\t\t\treturn Assets.Sprites.GUNNER;\n//\t\t\tcase SAMURAI:\n//\t\t\t\treturn Assets.Sprites.SAMURAI;\n//\t\t\tcase PLANTER:\n//\t\t\t\treturn Assets.Sprites.PLANTER;\n//\t\t\tcase KNIGHT:\n//\t\t\t\treturn Assets.Sprites.KNIGHT;\n//\t\t\tcase NURSE:\n//\t\t\t\treturn Assets.Sprites.NURSE;\n\t\t}\n\t}\n\n\tpublic String splashArt(){\n\t\tswitch (this) {\n\t\t\tcase WARRIOR: default:\n\t\t\t\treturn Assets.Splashes.WARRIOR;\n\t\t\tcase MAGE:\n\t\t\t\treturn Assets.Splashes.MAGE;\n\t\t\tcase ROGUE:\n\t\t\t\treturn Assets.Splashes.ROGUE;\n\t\t\tcase HUNTRESS:\n\t\t\t\treturn Assets.Splashes.HUNTRESS;\n\t\t\tcase DUELIST:\n\t\t\t\treturn Assets.Splashes.DUELIST;\n\t\t\tcase GUNNER:\n\t\t\t\treturn Assets.Splashes.GUNNER;\n//\t\t\tcase SAMURAI:\n//\t\t\t\treturn Assets.Splashes.SAMURAI;\n//\t\t\tcase PLANTER:\n//\t\t\t\treturn Assets.Splashes.PLANTER;\n//\t\t\tcase KNIGHT:\n//\t\t\t\treturn Assets.Splashes.KNIGHT;\n//\t\t\tcase NURSE:\n//\t\t\t\treturn Assets.Splashes.NURSE;\n\t\t}\n\t}\n\t\n\tpublic boolean isUnlocked(){\n\t\t//always unlock on debug builds\n\t\tif (DeviceCompat.isDebug()) return true;\n\n\t\tswitch (this){\n\t\t\tcase WARRIOR: default:\n\t\t\t\treturn true;\n\t\t\tcase MAGE:\n\t\t\t\treturn Badges.isUnlocked(Badges.Badge.UNLOCK_MAGE);\n\t\t\tcase ROGUE:\n\t\t\t\treturn Badges.isUnlocked(Badges.Badge.UNLOCK_ROGUE);\n\t\t\tcase HUNTRESS:\n\t\t\t\treturn Badges.isUnlocked(Badges.Badge.UNLOCK_HUNTRESS);\n\t\t\tcase DUELIST:\n\t\t\t\treturn Badges.isUnlocked(Badges.Badge.UNLOCK_DUELIST);\n\t\t\tcase GUNNER:\n\t\t\t\treturn Badges.isUnlocked(Badges.Badge.UNLOCK_GUNNER);\n//\t\t\tcase SAMURAI:\n//\t\t\t\treturn Badges.isUnlocked(Badges.Badge.UNLOCK_SAMURAI);\n//\t\t\tcase PLANTER:\n//\t\t\t\treturn Badges.isUnlocked(Badges.Badge.UNLOCK_PLANTER);\n//\t\t\tcase KNIGHT:\n//\t\t\t\treturn Badges.isUnlocked(Badges.Badge.UNLOCK_KNIGHT);\n//\t\t\tcase NURSE:\n//\t\t\t\treturn Badges.isUnlocked(Badges.Badge.UNLOCK_NURSE);\n\t\t}\n\t}\n\t\n\tpublic String unlockMsg() {\n\t\treturn shortDesc() + \"\\n\\n\" + Messages.get(HeroClass.class, name()+\"_unlock\");\n\t}\n\n}" }, { "identifier": "Generator", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/Generator.java", "snippet": "public class Generator {\n\n\tpublic enum Category {\n\t\tWEAPON\t( 2, 2, MeleeWeapon.class),\n\t\tWEP_T1\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_T2\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_T3\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_T4\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_T5\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_AL_T3\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_AL_T4\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_AL_T5\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_AL_T6\t( 0, 0, MeleeWeapon.class),\n\t\tWEP_AL_T7\t( 0, 0, MeleeWeapon.class),\n\n\t\tARMOR\t( 2, 1, Armor.class ),\n\t\t\n\t\tMISSILE ( 1, 2, MissileWeapon.class ),\n\t\tMIS_T1 ( 0, 0, MissileWeapon.class ),\n\t\tMIS_T2 ( 0, 0, MissileWeapon.class ),\n\t\tMIS_T3 ( 0, 0, MissileWeapon.class ),\n\t\tMIS_T4 ( 0, 0, MissileWeapon.class ),\n\t\tMIS_T5 ( 0, 0, MissileWeapon.class ),\n\t\t\n\t\tWAND\t( 1, 1, Wand.class ),\n\t\tSPELLBOOK\t( 0, 0, SpellBook.class ),\n\t\tRING\t( 1, 0, Ring.class ),\n\t\tARTIFACT( 0, 1, Artifact.class),\n\t\t\n\t\tFOOD\t( 0, 0, Food.class ),\n\t\t\n\t\tPOTION\t( 8, 8, Potion.class ),\n\t\tSEED\t( 1, 1, Plant.Seed.class ),\n\t\t\n\t\tSCROLL\t( 8, 8, Scroll.class ),\n\t\tSTONE ( 1, 1, Runestone.class),\n\t\t\n\t\tGOLD\t( 10, 10, Gold.class );\n\t\t\n\t\tpublic Class<?>[] classes;\n\n\t\t//some item types use a deck-based system, where the probs decrement as items are picked\n\t\t// until they are all 0, and then they reset. Those generator classes should define\n\t\t// defaultProbs. If defaultProbs is null then a deck system isn't used.\n\t\t//Artifacts in particular don't reset, no duplicates!\n\t\tpublic float[] probs;\n\t\tpublic float[] defaultProbs = null;\n\t\t//These variables are used as a part of the deck system, to ensure that drops are consistent\n\t\t// regardless of when they occur (either as part of seeded levelgen, or random item drops)\n\t\tpublic Long seed = null;\n\t\tpublic int dropped = 0;\n\n\t\t//game has two decks of 35 items for overall category probs\n\t\t//one deck has a ring and extra armor, the other has an artifact and extra thrown weapon\n\t\t//Note that pure random drops only happen as part of levelgen atm, so no seed is needed here\n\t\tpublic float firstProb;\n\t\tpublic float secondProb;\n\t\tpublic Class<? extends Item> superClass;\n\t\t\n\t\tprivate Category( float firstProb, float secondProb, Class<? extends Item> superClass ) {\n\t\t\tthis.firstProb = firstProb;\n\t\t\tthis.secondProb = secondProb;\n\t\t\tthis.superClass = superClass;\n\t\t}\n\t\t\n\t\tpublic static int order( Item item ) {\n\t\t\tfor (int i=0; i < values().length; i++) {\n\t\t\t\tif (values()[i].superClass.isInstance( item )) {\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//items without a category-defined order are sorted based on the spritesheet\n\t\t\treturn Short.MAX_VALUE+item.image();\n\t\t}\n\n\t\tstatic {\n\t\t\tGOLD.classes = new Class<?>[]{\n\t\t\t\t\tGold.class };\n\t\t\tGOLD.probs = new float[]{ 1 };\n\t\t\t\n\t\t\tPOTION.classes = new Class<?>[]{\n\t\t\t\t\tPotionOfStrength.class, //2 drop every chapter, see Dungeon.posNeeded()\n\t\t\t\t\tPotionOfHealing.class,\n\t\t\t\t\tPotionOfMindVision.class,\n\t\t\t\t\tPotionOfFrost.class,\n\t\t\t\t\tPotionOfLiquidFlame.class,\n\t\t\t\t\tPotionOfToxicGas.class,\n\t\t\t\t\tPotionOfHaste.class,\n\t\t\t\t\tPotionOfInvisibility.class,\n\t\t\t\t\tPotionOfLevitation.class,\n\t\t\t\t\tPotionOfParalyticGas.class,\n\t\t\t\t\tPotionOfPurity.class,\n\t\t\t\t\tPotionOfExperience.class};\n\t\t\tPOTION.defaultProbs = new float[]{ 0, 6, 4, 3, 3, 3, 2, 2, 2, 2, 2, 1 };\n\t\t\tPOTION.probs = POTION.defaultProbs.clone();\n\t\t\t\n\t\t\tSEED.classes = new Class<?>[]{\n\t\t\t\t\tRotberry.Seed.class, //quest item\n\t\t\t\t\tSungrass.Seed.class,\n\t\t\t\t\tFadeleaf.Seed.class,\n\t\t\t\t\tIcecap.Seed.class,\n\t\t\t\t\tFirebloom.Seed.class,\n\t\t\t\t\tSorrowmoss.Seed.class,\n\t\t\t\t\tSwiftthistle.Seed.class,\n\t\t\t\t\tBlindweed.Seed.class,\n\t\t\t\t\tStormvine.Seed.class,\n\t\t\t\t\tEarthroot.Seed.class,\n\t\t\t\t\tMageroyal.Seed.class,\n\t\t\t\t\tStarflower.Seed.class};\n\t\t\tSEED.defaultProbs = new float[]{ 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 2 };\n\t\t\tSEED.probs = SEED.defaultProbs.clone();\n\t\t\t\n\t\t\tSCROLL.classes = new Class<?>[]{\n\t\t\t\t\tScrollOfUpgrade.class, //3 drop every chapter, see Dungeon.souNeeded()\n\t\t\t\t\tScrollOfIdentify.class,\n\t\t\t\t\tScrollOfRemoveCurse.class,\n\t\t\t\t\tScrollOfMirrorImage.class,\n\t\t\t\t\tScrollOfRecharging.class,\n\t\t\t\t\tScrollOfTeleportation.class,\n\t\t\t\t\tScrollOfLullaby.class,\n\t\t\t\t\tScrollOfMagicMapping.class,\n\t\t\t\t\tScrollOfRage.class,\n\t\t\t\t\tScrollOfRetribution.class,\n\t\t\t\t\tScrollOfTerror.class,\n\t\t\t\t\tScrollOfTransmutation.class\n\t\t\t};\n\t\t\tSCROLL.defaultProbs = new float[]{ 0, 6, 4, 3, 3, 3, 2, 2, 2, 2, 2, 1 };\n\t\t\tSCROLL.probs = SCROLL.defaultProbs.clone();\n\t\t\t\n\t\t\tSTONE.classes = new Class<?>[]{\n\t\t\t\t\tStoneOfEnchantment.class, //1 is guaranteed to drop on floors 6-19\n\t\t\t\t\tStoneOfIntuition.class, //1 additional stone is also dropped on floors 1-3\n\t\t\t\t\tStoneOfDisarming.class,\n\t\t\t\t\tStoneOfFlock.class,\n\t\t\t\t\tStoneOfShock.class,\n\t\t\t\t\tStoneOfBlink.class,\n\t\t\t\t\tStoneOfDeepSleep.class,\n\t\t\t\t\tStoneOfClairvoyance.class,\n\t\t\t\t\tStoneOfAggression.class,\n\t\t\t\t\tStoneOfBlast.class,\n\t\t\t\t\tStoneOfFear.class,\n\t\t\t\t\tStoneOfAugmentation.class //1 is sold in each shop\n\t\t\t};\n\t\t\tSTONE.defaultProbs = new float[]{ 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0 };\n\t\t\tSTONE.probs = STONE.defaultProbs.clone();\n\n\t\t\tWAND.classes = new Class<?>[]{\n\t\t\t\t\tWandOfMagicMissile.class,\n\t\t\t\t\tWandOfLightning.class,\n\t\t\t\t\tWandOfDisintegration.class,\n\t\t\t\t\tWandOfFireblast.class,\n\t\t\t\t\tWandOfCorrosion.class,\n\t\t\t\t\tWandOfBlastWave.class,\n\t\t\t\t\tWandOfLivingEarth.class,\n\t\t\t\t\tWandOfFrost.class,\n\t\t\t\t\tWandOfPrismaticLight.class,\n\t\t\t\t\tWandOfWarding.class,\n\t\t\t\t\tWandOfTransfusion.class,\n\t\t\t\t\tWandOfCorruption.class,\n\t\t\t\t\tWandOfRegrowth.class };\n\t\t\tWAND.defaultProbs = new float[]{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };\n\t\t\tWAND.probs = WAND.defaultProbs.clone();\n\n\t\t\tSPELLBOOK.classes = new Class<?>[]{\n\t\t\t\t\tBookOfMagic.class,\n\t\t\t\t\tBookOfThunderBolt.class,\n\t\t\t\t\tBookOfDisintegration.class,\n\t\t\t\t\tBookOfFire.class,\n\t\t\t\t\tBookOfCorrosion.class,\n\t\t\t\t\tBookOfBlast.class,\n\t\t\t\t\tBookOfEarth.class,\n\t\t\t\t\tBookOfFrost.class,\n\t\t\t\t\tBookOfLight.class,\n\t\t\t\t\tBookOfWarding.class,\n\t\t\t\t\tBookOfTransfusion.class,\n\t\t\t\t\tBookOfCorruption.class,\n\t\t\t\t\tBookOfRegrowth.class };\n\t\t\tSPELLBOOK.defaultProbs = new float[]{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };\n\t\t\tSPELLBOOK.probs = SPELLBOOK.defaultProbs.clone();\n\t\t\t\n\t\t\t//see generator.randomWeapon\n\t\t\tWEAPON.classes = new Class<?>[]{};\n\t\t\tWEAPON.probs = new float[]{};\n\t\t\t\n\t\t\tWEP_T1.classes = new Class<?>[]{\n\t\t\t\t\tWornShortsword.class,\n\t\t\t\t\tMagesStaff.class,\n\t\t\t\t\tDagger.class,\n\t\t\t\t\tGloves.class,\n\t\t\t\t\tRapier.class,\n\t\t\t\t\tWornKatana.class,\n\t\t\t\t\tAR_T1.class\n\t\t\t};\n\t\t\tWEP_T1.defaultProbs = new float[]{ 2, 0, 2, 2, 2, 2, 2 };\n\t\t\tWEP_T1.probs = WEP_T1.defaultProbs.clone();\n\t\t\t\n\t\t\tWEP_T2.classes = new Class<?>[]{\n\t\t\t\t\tShortsword.class,\n\t\t\t\t\tHandAxe.class,\n\t\t\t\t\tSpear.class,\n\t\t\t\t\tQuarterstaff.class,\n\t\t\t\t\tDirk.class,\n\t\t\t\t\tSickle.class,\n\t\t\t\t\tNunchaku.class,\n\t\t\t\t\tDualDagger.class,\n\t\t\t\t\tKnife.class,\n\t\t\t\t\tShortKatana.class,\n\t\t\t\t\tAR_T2.class,\n\t\t\t\t\tHG_T2.class,\n\t\t\t\t\tSMG_T2.class\n\t\t\t};\n\t\t\tWEP_T2.defaultProbs = new float[]{ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };\n\t\t\tWEP_T2.probs = WEP_T2.defaultProbs.clone();\n\t\t\t\n\t\t\tWEP_T3.classes = new Class<?>[]{\n\t\t\t\t\tSword.class,\n\t\t\t\t\tMace.class,\n\t\t\t\t\tScimitar.class,\n\t\t\t\t\tRoundShield.class,\n\t\t\t\t\tSai.class,\n\t\t\t\t\tBible.class,\n\t\t\t\t\tNormalKatana.class,\n\t\t\t\t\tWhip.class,\n\t\t\t\t\tAR_T3.class,\n\t\t\t\t\tMG_T3.class,\n\t\t\t\t\tSG_T3.class,\n\t\t\t\t\tSR_T3.class\n\t\t\t};\n\t\t\tWEP_T3.defaultProbs = new float[]{ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };\n\t\t\tWEP_T3.probs = WEP_T1.defaultProbs.clone();\n\t\t\t\n\t\t\tWEP_T4.classes = new Class<?>[]{\n\t\t\t\t\tLongsword.class,\n\t\t\t\t\tBattleAxe.class,\n\t\t\t\t\tFlail.class,\n\t\t\t\t\tRunicBlade.class,\n\t\t\t\t\tAssassinsBlade.class,\n\t\t\t\t\tCrossbow.class,\n\t\t\t\t\tKatana.class,\n\t\t\t\t\tLongKatana.class,\n\t\t\t\t\tAR_T4.class\n\t\t\t};\n\t\t\tWEP_T4.defaultProbs = new float[]{ 2, 2, 2, 2, 2, 2, 2, 2, 2 };\n\t\t\tWEP_T4.probs = WEP_T4.defaultProbs.clone();\n\t\t\t\n\t\t\tWEP_T5.classes = new Class<?>[]{\n\t\t\t\t\tGreatsword.class,\n\t\t\t\t\tWarHammer.class,\n\t\t\t\t\tGlaive.class,\n\t\t\t\t\tGreataxe.class,\n\t\t\t\t\tGreatshield.class,\n\t\t\t\t\tGauntlet.class,\n\t\t\t\t\tWarScythe.class,\n\t\t\t\t\tLargeSword.class,\n\t\t\t\t\tLargeKatana.class,\n\t\t\t\t\tAR_T5.class,\n\t\t\t\t\tHG_T5.class,\n\t\t\t\t\tSMG_T5.class,\n\t\t\t\t\tMG_T5.class,\n\t\t\t\t\tSG_T5.class,\n\t\t\t\t\tSR_T5.class\n\t\t\t};\n\t\t\tWEP_T5.defaultProbs = new float[]{ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };\n\t\t\tWEP_T5.probs = WEP_T5.defaultProbs.clone();\n\n\t\t\tWEP_AL_T3.classes = new Class<?>[]{\n\t\t\t\t\tSpearNShield.class\n\t\t\t};\n\t\t\tWEP_AL_T3.defaultProbs = new float[]{ 0 };\n\t\t\tWEP_AL_T3.probs = WEP_AL_T3.defaultProbs.clone();\n\n\t\t\tWEP_AL_T4.classes = new Class<?>[]{\n\t\t\t\t\tUnholyBible.class\n\t\t\t};\n\t\t\tWEP_AL_T4.defaultProbs = new float[]{ 0 };\n\t\t\tWEP_AL_T4.probs = WEP_AL_T4.defaultProbs.clone();\n\n\t\t\tWEP_AL_T5.classes = new Class<?>[]{\n\t\t\t\t\tTrueRunicBlade.class,\n\t\t\t\t\tAssassinsSpear.class,\n\t\t\t\t\tChainWhip.class,\n\t\t\t\t\tUnformedBlade.class\n\t\t\t};\n\t\t\tWEP_AL_T5.defaultProbs = new float[]{ 0, 0, 0, 0 };\n\t\t\tWEP_AL_T5.probs = WEP_AL_T5.defaultProbs.clone();\n\n\t\t\tWEP_AL_T6.classes = new Class<?>[]{\n\t\t\t\t\tAR_T6.class,\n\t\t\t\t\tSR_T6.class,\n\t\t\t\t\tHG_T6.class,\n\t\t\t\t\tChainFlail.class,\n\t\t\t\t\tForceGlove.class,\n\t\t\t\t\tLance.class,\n\t\t\t\t\tObsidianShield.class,\n\t\t\t\t\tDualGreatSword.class,\n\t\t\t\t\tHugeSword.class,\n\t\t\t\t\tMeisterHammer.class,\n\t\t\t\t\tBeamSaber.class,\n\t\t\t\t\tSharpKatana.class\n\t\t\t};\n\t\t\tWEP_AL_T6.defaultProbs = new float[]{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };\n\t\t\tWEP_AL_T6.probs = WEP_AL_T6.defaultProbs.clone();\n\n\t\t\tWEP_AL_T7.classes = new Class<?>[]{\n\t\t\t\t\tLanceNShield.class,\n\t\t\t\t\tTacticalShield.class,\n\t\t\t\t\tHolySword.class\n\t\t\t};\n\t\t\tWEP_AL_T7.defaultProbs = new float[]{ 0, 0, 0 };\n\t\t\tWEP_AL_T7.probs = WEP_AL_T7.defaultProbs.clone();\n\t\t\t\n\t\t\t//see Generator.randomArmor\n\t\t\tARMOR.classes = new Class<?>[]{\n\t\t\t\t\tClothArmor.class,\n\t\t\t\t\tLeatherArmor.class,\n\t\t\t\t\tMailArmor.class,\n\t\t\t\t\tScaleArmor.class,\n\t\t\t\t\tPlateArmor.class,\n\t\t\t\t\tWarriorArmor.class,\n\t\t\t\t\tMageArmor.class,\n\t\t\t\t\tRogueArmor.class,\n\t\t\t\t\tHuntressArmor.class,\n\t\t\t\t\tDuelistArmor.class\n\t\t\t};\n\t\t\tARMOR.probs = new float[]{ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };\n\t\t\t\n\t\t\t//see Generator.randomMissile\n\t\t\tMISSILE.classes = new Class<?>[]{};\n\t\t\tMISSILE.probs = new float[]{};\n\t\t\t\n\t\t\tMIS_T1.classes = new Class<?>[]{\n\t\t\t\t\tThrowingStone.class,\n\t\t\t\t\tThrowingKnife.class,\n\t\t\t\t\tThrowingSpike.class\n\t\t\t};\n\t\t\tMIS_T1.defaultProbs = new float[]{ 3, 3, 3 };\n\t\t\tMIS_T1.probs = MIS_T1.defaultProbs.clone();\n\t\t\t\n\t\t\tMIS_T2.classes = new Class<?>[]{\n\t\t\t\t\tFishingSpear.class,\n\t\t\t\t\tThrowingClub.class,\n\t\t\t\t\tShuriken.class\n\t\t\t};\n\t\t\tMIS_T2.defaultProbs = new float[]{ 3, 3, 3 };\n\t\t\tMIS_T2.probs = MIS_T2.defaultProbs.clone();\n\t\t\t\n\t\t\tMIS_T3.classes = new Class<?>[]{\n\t\t\t\t\tThrowingSpear.class,\n\t\t\t\t\tKunai.class,\n\t\t\t\t\tBolas.class\n\t\t\t};\n\t\t\tMIS_T3.defaultProbs = new float[]{ 3, 3, 3 };\n\t\t\tMIS_T3.probs = MIS_T3.defaultProbs.clone();\n\t\t\t\n\t\t\tMIS_T4.classes = new Class<?>[]{\n\t\t\t\t\tJavelin.class,\n\t\t\t\t\tTomahawk.class,\n\t\t\t\t\tHeavyBoomerang.class\n\t\t\t};\n\t\t\tMIS_T4.defaultProbs = new float[]{ 3, 3, 3 };\n\t\t\tMIS_T4.probs = MIS_T4.defaultProbs.clone();\n\t\t\t\n\t\t\tMIS_T5.classes = new Class<?>[]{\n\t\t\t\t\tTrident.class,\n\t\t\t\t\tThrowingHammer.class,\n\t\t\t\t\tForceCube.class\n\t\t\t};\n\t\t\tMIS_T5.defaultProbs = new float[]{ 3, 3, 3 };\n\t\t\tMIS_T5.probs = MIS_T5.defaultProbs.clone();\n\t\t\t\n\t\t\tFOOD.classes = new Class<?>[]{\n\t\t\t\t\tFood.class,\n\t\t\t\t\tPasty.class,\n\t\t\t\t\tMysteryMeat.class };\n\t\t\tFOOD.defaultProbs = new float[]{ 4, 1, 0 };\n\t\t\tFOOD.probs = FOOD.defaultProbs.clone();\n\t\t\t\n\t\t\tRING.classes = new Class<?>[]{\n\t\t\t\t\tRingOfAccuracy.class,\n\t\t\t\t\tRingOfArcana.class,\n\t\t\t\t\tRingOfElements.class,\n\t\t\t\t\tRingOfEnergy.class,\n\t\t\t\t\tRingOfEvasion.class,\n\t\t\t\t\tRingOfForce.class,\n\t\t\t\t\tRingOfFuror.class,\n\t\t\t\t\tRingOfHaste.class,\n\t\t\t\t\tRingOfMight.class,\n\t\t\t\t\tRingOfSharpshooting.class,\n\t\t\t\t\tRingOfTenacity.class,\n\t\t\t\t\tRingOfWealth.class};\n\t\t\tRING.defaultProbs = new float[]{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };\n\t\t\tRING.probs = RING.defaultProbs.clone();\n\t\t\t\n\t\t\tARTIFACT.classes = new Class<?>[]{\n\t\t\t\t\tAlchemistsToolkit.class,\n\t\t\t\t\tChaliceOfBlood.class,\n\t\t\t\t\tCloakOfShadows.class,\n\t\t\t\t\tDriedRose.class,\n\t\t\t\t\tEtherealChains.class,\n\t\t\t\t\tHornOfPlenty.class,\n\t\t\t\t\tMasterThievesArmband.class,\n\t\t\t\t\tSandalsOfNature.class,\n\t\t\t\t\tTalismanOfForesight.class,\n\t\t\t\t\tTimekeepersHourglass.class,\n\t\t\t\t\tUnstableSpellbook.class\n\t\t\t};\n\t\t\tARTIFACT.defaultProbs = new float[]{ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 };\n\t\t\tARTIFACT.probs = ARTIFACT.defaultProbs.clone();\n\t\t}\n\t}\n\n\tprivate static final float[][] floorSetTierProbs = new float[][] {\n\t\t\t{0, 75, 20, 4, 1},\n\t\t\t{0, 25, 50, 20, 5},\n\t\t\t{0, 0, 40, 50, 10},\n\t\t\t{0, 0, 20, 40, 40},\n\t\t\t{0, 0, 0, 20, 80},\n\t\t\t{0, 0, 0, 0, 100}\n\t};\n\n\tprivate static boolean usingFirstDeck = false;\n\tprivate static HashMap<Category,Float> defaultCatProbs = new LinkedHashMap<>();\n\tprivate static HashMap<Category,Float> categoryProbs = new LinkedHashMap<>();\n\n\tpublic static void fullReset() {\n\t\tusingFirstDeck = Random.Int(2) == 0;\n\t\tgeneralReset();\n\t\tfor (Category cat : Category.values()) {\n\t\t\treset(cat);\n\t\t\tif (cat.defaultProbs != null) {\n\t\t\t\tcat.seed = Random.Long();\n\t\t\t\tcat.dropped = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void generalReset(){\n\t\tfor (Category cat : Category.values()) {\n\t\t\tcategoryProbs.put( cat, usingFirstDeck ? cat.firstProb : cat.secondProb );\n\t\t\tdefaultCatProbs.put( cat, cat.firstProb + cat.secondProb );\n\t\t}\n\t}\n\n\tpublic static void reset(Category cat){\n\t\tif (cat.defaultProbs != null) cat.probs = cat.defaultProbs.clone();\n\t}\n\n\t//reverts changes to drop chances generates by this item\n\t//equivalent of shuffling the card back into the deck, does not preserve order!\n\tpublic static void undoDrop(Item item){\n\t\tfor (Category cat : Category.values()){\n\t\t\tif (item.getClass().isAssignableFrom(cat.superClass)){\n\t\t\t\tif (cat.defaultProbs == null) continue;\n\t\t\t\tfor (int i = 0; i < cat.classes.length; i++){\n\t\t\t\t\tif (item.getClass() == cat.classes[i]){\n\t\t\t\t\t\tcat.probs[i]++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static Item random() {\n\t\tCategory cat = Random.chances( categoryProbs );\n\t\tif (cat == null){\n\t\t\tusingFirstDeck = !usingFirstDeck;\n\t\t\tgeneralReset();\n\t\t\tcat = Random.chances( categoryProbs );\n\t\t}\n\t\tcategoryProbs.put( cat, categoryProbs.get( cat ) - 1);\n\n\t\tif (cat == Category.SEED) {\n\t\t\t//We specifically use defaults for seeds here because, unlike other item categories\n\t\t\t// their predominant source of drops is grass, not levelgen. This way the majority\n\t\t\t// of seed drops still use a deck, but the few that are spawned by levelgen are consistent\n\t\t\treturn randomUsingDefaults(cat);\n\t\t} else {\n\t\t\treturn random(cat);\n\t\t}\n\t}\n\n\tpublic static Item randomUsingDefaults(){\n\t\treturn randomUsingDefaults(Random.chances( defaultCatProbs ));\n\t}\n\t\n\tpublic static Item random( Category cat ) {\n\t\tswitch (cat) {\n\t\t\tcase ARMOR:\n\t\t\t\treturn randomArmor();\n\t\t\tcase WEAPON:\n\t\t\t\treturn randomWeapon();\n\t\t\tcase MISSILE:\n\t\t\t\treturn randomMissile();\n\t\t\tcase ARTIFACT:\n\t\t\t\tItem item = randomArtifact();\n\t\t\t\t//if we're out of artifacts, return a ring instead.\n\t\t\t\treturn item != null ? item : random(Category.RING);\n\t\t\tdefault:\n\t\t\t\tif (cat.defaultProbs != null && cat.seed != null){\n\t\t\t\t\tRandom.pushGenerator(cat.seed);\n\t\t\t\t\tfor (int i = 0; i < cat.dropped; i++) Random.Long();\n\t\t\t\t}\n\n\t\t\t\tint i = Random.chances(cat.probs);\n\t\t\t\tif (i == -1) {\n\t\t\t\t\treset(cat);\n\t\t\t\t\ti = Random.chances(cat.probs);\n\t\t\t\t}\n\t\t\t\tif (cat.defaultProbs != null) cat.probs[i]--;\n\n\t\t\t\tif (cat.defaultProbs != null && cat.seed != null){\n\t\t\t\t\tRandom.popGenerator();\n\t\t\t\t\tcat.dropped++;\n\t\t\t\t}\n\n\t\t\t\treturn ((Item) Reflection.newInstance(cat.classes[i])).random();\n\t\t}\n\t}\n\n\t//overrides any deck systems and always uses default probs\n\t// except for artifacts, which must always use a deck\n\tpublic static Item randomUsingDefaults( Category cat ){\n\t\tif (cat == Category.WEAPON){\n\t\t\treturn randomWeapon(true);\n\t\t} else if (cat == Category.MISSILE){\n\t\t\treturn randomMissile(true);\n\t\t} else if (cat.defaultProbs == null || cat == Category.ARTIFACT) {\n\t\t\treturn random(cat);\n\t\t} else {\n\t\t\treturn ((Item) Reflection.newInstance(cat.classes[Random.chances(cat.defaultProbs)])).random();\n\t\t}\n\t}\n\t\n\tpublic static Item random( Class<? extends Item> cl ) {\n\t\treturn Reflection.newInstance(cl).random();\n\t}\n\n\tpublic static Armor randomArmor(){\n\t\treturn randomArmor(Dungeon.depth / 5);\n\t}\n\t\n\tpublic static Armor randomArmor(int floorSet) {\n\n\t\tfloorSet = (int)GameMath.gate(0, floorSet, floorSetTierProbs.length-1);\n\t\t\n\t\tArmor a = (Armor)Reflection.newInstance(Category.ARMOR.classes[Random.chances(floorSetTierProbs[floorSet])]);\n\t\ta.random();\n\t\treturn a;\n\t}\n\n\tpublic static final Category[] wepTiers = new Category[]{\n\t\t\tCategory.WEP_T1,\n\t\t\tCategory.WEP_T2,\n\t\t\tCategory.WEP_T3,\n\t\t\tCategory.WEP_T4,\n\t\t\tCategory.WEP_T5\n\t};\n\n\tpublic static MeleeWeapon randomWeapon(){\n\t\treturn randomWeapon(Dungeon.depth / 5);\n\t}\n\n\tpublic static MeleeWeapon randomWeapon(int floorSet) {\n\t\treturn randomWeapon(floorSet, false);\n\t}\n\n\tpublic static MeleeWeapon randomWeapon(boolean useDefaults) {\n\t\treturn randomWeapon(Dungeon.depth / 5, useDefaults);\n\t}\n\t\n\tpublic static MeleeWeapon randomWeapon(int floorSet, boolean useDefaults) {\n\n\t\tfloorSet = (int)GameMath.gate(0, floorSet, floorSetTierProbs.length-1);\n\n\t\tMeleeWeapon w;\n\t\tif (useDefaults){\n\t\t\tw = (MeleeWeapon) randomUsingDefaults(wepTiers[Random.chances(floorSetTierProbs[floorSet])]);\n\t\t} else {\n\t\t\tw = (MeleeWeapon) random(wepTiers[Random.chances(floorSetTierProbs[floorSet])]);\n\t\t}\n\t\treturn w;\n\t}\n\t\n\tpublic static final Category[] misTiers = new Category[]{\n\t\t\tCategory.MIS_T1,\n\t\t\tCategory.MIS_T2,\n\t\t\tCategory.MIS_T3,\n\t\t\tCategory.MIS_T4,\n\t\t\tCategory.MIS_T5\n\t};\n\t\n\tpublic static MissileWeapon randomMissile(){\n\t\treturn randomMissile(Dungeon.depth / 5);\n\t}\n\n\tpublic static MissileWeapon randomMissile(int floorSet) {\n\t\treturn randomMissile(floorSet, false);\n\t}\n\n\tpublic static MissileWeapon randomMissile(boolean useDefaults) {\n\t\treturn randomMissile(Dungeon.depth / 5, useDefaults);\n\t}\n\n\tpublic static MissileWeapon randomMissile(int floorSet, boolean useDefaults) {\n\t\t\n\t\tfloorSet = (int)GameMath.gate(0, floorSet, floorSetTierProbs.length-1);\n\n\t\tMissileWeapon w;\n\t\tif (useDefaults){\n\t\t\tw = (MissileWeapon)randomUsingDefaults(misTiers[Random.chances(floorSetTierProbs[floorSet])]);\n\t\t} else {\n\t\t\tw = (MissileWeapon)random(misTiers[Random.chances(floorSetTierProbs[floorSet])]);\n\t\t}\n\t\treturn w;\n\t}\n\n\t//enforces uniqueness of artifacts throughout a run.\n\tpublic static Artifact randomArtifact() {\n\n\t\tCategory cat = Category.ARTIFACT;\n\n\t\tif (cat.defaultProbs != null && cat.seed != null){\n\t\t\tRandom.pushGenerator(cat.seed);\n\t\t\tfor (int i = 0; i < cat.dropped; i++) Random.Long();\n\t\t}\n\n\t\tint i = Random.chances( cat.probs );\n\n\t\tif (cat.defaultProbs != null && cat.seed != null){\n\t\t\tRandom.popGenerator();\n\t\t\tcat.dropped++;\n\t\t}\n\n\t\t//if no artifacts are left, return null\n\t\tif (i == -1){\n\t\t\treturn null;\n\t\t}\n\n\t\tcat.probs[i]--;\n\t\treturn (Artifact) Reflection.newInstance((Class<? extends Artifact>) cat.classes[i]).random();\n\n\t}\n\n\tpublic static boolean removeArtifact(Class<?extends Artifact> artifact) {\n\t\tCategory cat = Category.ARTIFACT;\n\t\tfor (int i = 0; i < cat.classes.length; i++){\n\t\t\tif (cat.classes[i].equals(artifact) && cat.probs[i] > 0) {\n\t\t\t\tcat.probs[i] = 0;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate static final String FIRST_DECK = \"first_deck\";\n\tprivate static final String GENERAL_PROBS = \"general_probs\";\n\tprivate static final String CATEGORY_PROBS = \"_probs\";\n\tprivate static final String CATEGORY_SEED = \"_seed\";\n\tprivate static final String CATEGORY_DROPPED = \"_dropped\";\n\n\tpublic static void storeInBundle(Bundle bundle) {\n\t\tbundle.put(FIRST_DECK, usingFirstDeck);\n\n\t\tFloat[] genProbs = categoryProbs.values().toArray(new Float[0]);\n\t\tfloat[] storeProbs = new float[genProbs.length];\n\t\tfor (int i = 0; i < storeProbs.length; i++){\n\t\t\tstoreProbs[i] = genProbs[i];\n\t\t}\n\t\tbundle.put( GENERAL_PROBS, storeProbs);\n\n\t\tfor (Category cat : Category.values()){\n\t\t\tif (cat.defaultProbs == null) continue;\n\n\t\t\tbundle.put(cat.name().toLowerCase() + CATEGORY_PROBS, cat.probs);\n\t\t\tif (cat.seed != null) {\n\t\t\t\tbundle.put(cat.name().toLowerCase() + CATEGORY_SEED, cat.seed);\n\t\t\t\tbundle.put(cat.name().toLowerCase() + CATEGORY_DROPPED, cat.dropped);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void restoreFromBundle(Bundle bundle) {\n\t\tfullReset();\n\n\t\tusingFirstDeck = bundle.getBoolean(FIRST_DECK);\n\n\t\tif (bundle.contains(GENERAL_PROBS)){\n\t\t\tfloat[] probs = bundle.getFloatArray(GENERAL_PROBS);\n\t\t\tfor (int i = 0; i < probs.length; i++){\n\t\t\t\tcategoryProbs.put(Category.values()[i], probs[i]);\n\t\t\t}\n\t\t}\n\n\t\tfor (Category cat : Category.values()){\n\t\t\tif (bundle.contains(cat.name().toLowerCase() + CATEGORY_PROBS)){\n\t\t\t\tfloat[] probs = bundle.getFloatArray(cat.name().toLowerCase() + CATEGORY_PROBS);\n\t\t\t\tif (cat.defaultProbs != null && probs.length == cat.defaultProbs.length){\n\t\t\t\t\tcat.probs = probs;\n\t\t\t\t}\n\t\t\t\tif (bundle.contains(cat.name().toLowerCase() + CATEGORY_SEED)){\n\t\t\t\t\tcat.seed = bundle.getLong(cat.name().toLowerCase() + CATEGORY_SEED);\n\t\t\t\t\tcat.dropped = bundle.getInt(cat.name().toLowerCase() + CATEGORY_DROPPED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n}" }, { "identifier": "Item", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/Item.java", "snippet": "public class Item implements Bundlable {\n\n\tprotected static final String TXT_TO_STRING_LVL\t\t= \"%s %+d\";\n\tprotected static final String TXT_TO_STRING_X\t\t= \"%s x%d\";\n\t\n\tprotected static final float TIME_TO_THROW\t\t= 1.0f;\n\tprotected static final float TIME_TO_PICK_UP\t= 1.0f;\n\tprotected static final float TIME_TO_DROP\t\t= 1.0f;\n\t\n\tpublic static final String AC_DROP\t\t= \"DROP\";\n\tpublic static final String AC_THROW\t\t= \"THROW\";\n\t\n\tprotected String defaultAction;\n\tpublic boolean usesTargeting;\n\n\t//TODO should these be private and accessed through methods?\n\tpublic int image = 0;\n\tpublic int icon = -1; //used as an identifier for items with randomized images\n\t\n\tpublic boolean stackable = false;\n\tprotected int quantity = 1;\n\tpublic boolean dropsDownHeap = false;\n\t\n\tprivate int level = 0;\n\n\tpublic boolean levelKnown = false;\n\t\n\tpublic boolean cursed;\n\tpublic boolean cursedKnown;\n\t\n\t// Unique items persist through revival\n\tpublic boolean unique = false;\n\n\t// These items are preserved even if the hero's inventory is lost via unblessed ankh\n\t// this is largely set by the resurrection window, items can override this to always be kept\n\tpublic boolean keptThoughLostInvent = false;\n\n\t// whether an item can be included in heroes remains\n\tpublic boolean bones = false;\n\t\n\tpublic static final Comparator<Item> itemComparator = new Comparator<Item>() {\n\t\t@Override\n\t\tpublic int compare( Item lhs, Item rhs ) {\n\t\t\treturn Generator.Category.order( lhs ) - Generator.Category.order( rhs );\n\t\t}\n\t};\n\t\n\tpublic ArrayList<String> actions( Hero hero ) {\n\t\tArrayList<String> actions = new ArrayList<>();\n\t\tactions.add( AC_DROP );\n\t\tactions.add( AC_THROW );\n\t\treturn actions;\n\t}\n\n\tpublic String actionName(String action, Hero hero){\n\t\treturn Messages.get(this, \"ac_\" + action);\n\t}\n\n\tpublic final boolean doPickUp( Hero hero ) {\n\t\treturn doPickUp( hero, hero.pos );\n\t}\n\n\tpublic boolean doPickUp(Hero hero, int pos) {\n\t\tif (collect( hero.belongings.backpack )) {\n\t\t\t\n\t\t\tGameScene.pickUp( this, pos );\n\t\t\tSample.INSTANCE.play( Assets.Sounds.ITEM );\n\t\t\thero.spendAndNext( TIME_TO_PICK_UP );\n\t\t\treturn true;\n\t\t\t\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic void doDrop( Hero hero ) {\n\t\thero.spendAndNext(TIME_TO_DROP);\n\t\tint pos = hero.pos;\n\t\tDungeon.level.drop(detachAll(hero.belongings.backpack), pos).sprite.drop(pos);\n\t}\n\n\t//resets an item's properties, to ensure consistency between runs\n\tpublic void reset(){\n\t\tkeptThoughLostInvent = false;\n\t}\n\n\tpublic boolean keptThroughLostInventory(){\n\t\treturn keptThoughLostInvent;\n\t}\n\n\tpublic void doThrow( Hero hero ) {\n\t\tGameScene.selectCell(thrower);\n\t}\n\t\n\tpublic void execute( Hero hero, String action ) {\n\n\t\tGameScene.cancel();\n\t\tcurUser = hero;\n\t\tcurItem = this;\n\t\t\n\t\tif (action.equals( AC_DROP )) {\n\t\t\t\n\t\t\tif (hero.belongings.backpack.contains(this) || isEquipped(hero)) {\n\t\t\t\tdoDrop(hero);\n\t\t\t}\n\t\t\t\n\t\t} else if (action.equals( AC_THROW )) {\n\t\t\t\n\t\t\tif (hero.belongings.backpack.contains(this) || isEquipped(hero)) {\n\t\t\t\tdoThrow(hero);\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\n\t//can be overridden if default action is variable\n\tpublic String defaultAction(){\n\t\treturn defaultAction;\n\t}\n\t\n\tpublic void execute( Hero hero ) {\n\t\tString action = defaultAction();\n\t\tif (action != null) {\n\t\t\texecute(hero, defaultAction());\n\t\t}\n\t}\n\t\n\tprotected void onThrow( int cell ) {\n\t\tHeap heap = Dungeon.level.drop( this, cell );\n\t\tif (!heap.isEmpty()) {\n\t\t\theap.sprite.drop( cell );\n\t\t}\n\t}\n\t\n\t//takes two items and merges them (if possible)\n\tpublic Item merge( Item other ){\n\t\tif (isSimilar( other )){\n\t\t\tquantity += other.quantity;\n\t\t\tother.quantity = 0;\n\t\t}\n\t\treturn this;\n\t}\n\t\n\tpublic boolean collect( Bag container ) {\n\n\t\tif (quantity <= 0){\n\t\t\treturn true;\n\t\t}\n\n\t\tArrayList<Item> items = container.items;\n\n\t\tif (items.contains( this )) {\n\t\t\treturn true;\n\t\t}\n\n\t\tfor (Item item:items) {\n\t\t\tif (item instanceof Bag && ((Bag)item).canHold( this )) {\n\t\t\t\tif (collect( (Bag)item )){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!container.canHold(this)){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif (stackable) {\n\t\t\tfor (Item item:items) {\n\t\t\t\tif (isSimilar( item )) {\n\t\t\t\t\titem.merge( this );\n\t\t\t\t\titem.updateQuickslot();\n\t\t\t\t\tif (Dungeon.hero != null && Dungeon.hero.isAlive()) {\n\t\t\t\t\t\tBadges.validateItemLevelAquired( this );\n\t\t\t\t\t\tTalent.onItemCollected(Dungeon.hero, item);\n\t\t\t\t\t\tif (isIdentified()) Catalog.setSeen(getClass());\n\t\t\t\t\t}\n\t\t\t\t\tif (TippedDart.lostDarts > 0){\n\t\t\t\t\t\tDart d = new Dart();\n\t\t\t\t\t\td.quantity(TippedDart.lostDarts);\n\t\t\t\t\t\tTippedDart.lostDarts = 0;\n\t\t\t\t\t\tif (!d.collect()){\n\t\t\t\t\t\t\t//have to handle this in an actor as we can't manipulate the heap during pickup\n\t\t\t\t\t\t\tActor.add(new Actor() {\n\t\t\t\t\t\t\t\t{ actPriority = VFX_PRIO; }\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tprotected boolean act() {\n\t\t\t\t\t\t\t\t\tDungeon.level.drop(d, Dungeon.hero.pos).sprite.drop();\n\t\t\t\t\t\t\t\t\tActor.remove(this);\n\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.hero != null && Dungeon.hero.isAlive()) {\n\t\t\tBadges.validateItemLevelAquired( this );\n\t\t\tTalent.onItemCollected( Dungeon.hero, this );\n\t\t\tif (isIdentified()) Catalog.setSeen(getClass());\n\t\t}\n\n\t\titems.add( this );\n\t\tDungeon.quickslot.replacePlaceholder(this);\n\t\tCollections.sort( items, itemComparator );\n\t\tupdateQuickslot();\n\t\treturn true;\n\n\t}\n\t\n\tpublic boolean collect() {\n\t\treturn collect( Dungeon.hero.belongings.backpack );\n\t}\n\t\n\t//returns a new item if the split was sucessful and there are now 2 items, otherwise null\n\tpublic Item split( int amount ){\n\t\tif (amount <= 0 || amount >= quantity()) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\t//pssh, who needs copy constructors?\n\t\t\tItem split = Reflection.newInstance(getClass());\n\t\t\t\n\t\t\tif (split == null){\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t\n\t\t\tBundle copy = new Bundle();\n\t\t\tthis.storeInBundle(copy);\n\t\t\tsplit.restoreFromBundle(copy);\n\t\t\tsplit.quantity(amount);\n\t\t\tquantity -= amount;\n\t\t\t\n\t\t\treturn split;\n\t\t}\n\t}\n\t\n\tpublic final Item detach( Bag container ) {\n\t\t\n\t\tif (quantity <= 0) {\n\t\t\t\n\t\t\treturn null;\n\t\t\t\n\t\t} else\n\t\tif (quantity == 1) {\n\n\t\t\tif (stackable){\n\t\t\t\tDungeon.quickslot.convertToPlaceholder(this);\n\t\t\t}\n\n\t\t\treturn detachAll( container );\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t\tItem detached = split(1);\n\t\t\tupdateQuickslot();\n\t\t\tif (detached != null) detached.onDetach( );\n\t\t\treturn detached;\n\t\t\t\n\t\t}\n\t}\n\t\n\tpublic final Item detachAll( Bag container ) {\n\t\tDungeon.quickslot.clearItem( this );\n\n\t\tfor (Item item : container.items) {\n\t\t\tif (item == this) {\n\t\t\t\tcontainer.items.remove(this);\n\t\t\t\titem.onDetach();\n\t\t\t\tcontainer.grabItems(); //try to put more items into the bag as it now has free space\n\t\t\t\tupdateQuickslot();\n\t\t\t\treturn this;\n\t\t\t} else if (item instanceof Bag) {\n\t\t\t\tBag bag = (Bag)item;\n\t\t\t\tif (bag.contains( this )) {\n\t\t\t\t\treturn detachAll( bag );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdateQuickslot();\n\t\treturn this;\n\t}\n\t\n\tpublic boolean isSimilar( Item item ) {\n\t\treturn level == item.level && getClass() == item.getClass();\n\t}\n\n\tprotected void onDetach(){}\n\n\t//returns the true level of the item, ignoring all modifiers aside from upgrades\n\tpublic final int trueLevel(){\n\t\treturn level;\n\t}\n\n\t//returns the persistant level of the item, only affected by modifiers which are persistent (e.g. curse infusion)\n\tpublic int level(){\n\t\treturn level;\n\t}\n\t\n\t//returns the level of the item, after it may have been modified by temporary boosts/reductions\n\t//note that not all item properties should care about buffs/debuffs! (e.g. str requirement)\n\tpublic int buffedLvl(){\n\t\t//only the hero can be affected by Degradation\n\t\tif (Dungeon.hero.buff( Degrade.class ) != null\n\t\t\t&& (isEquipped( Dungeon.hero ) || Dungeon.hero.belongings.contains( this ))) {\n\t\t\treturn Degrade.reduceLevel(level());\n\t\t} else {\n\t\t\treturn level();\n\t\t}\n\t}\n\n\tpublic void level( int value ){\n\t\tlevel = value;\n\n\t\tupdateQuickslot();\n\t}\n\t\n\tpublic Item upgrade() {\n\t\t\n\t\tthis.level++;\n\n\t\tupdateQuickslot();\n\t\t\n\t\treturn this;\n\t}\n\t\n\tfinal public Item upgrade( int n ) {\n\t\tfor (int i=0; i < n; i++) {\n\t\t\tupgrade();\n\t\t}\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic Item degrade() {\n\t\t\n\t\tthis.level--;\n\t\t\n\t\treturn this;\n\t}\n\t\n\tfinal public Item degrade( int n ) {\n\t\tfor (int i=0; i < n; i++) {\n\t\t\tdegrade();\n\t\t}\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic int visiblyUpgraded() {\n\t\treturn levelKnown ? level() : 0;\n\t}\n\n\tpublic int buffedVisiblyUpgraded() {\n\t\treturn levelKnown ? buffedLvl() : 0;\n\t}\n\t\n\tpublic boolean visiblyCursed() {\n\t\treturn cursed && cursedKnown;\n\t}\n\t\n\tpublic boolean isUpgradable() {\n\t\treturn true;\n\t}\n\t\n\tpublic boolean isIdentified() {\n\t\treturn levelKnown && cursedKnown;\n\t}\n\t\n\tpublic boolean isEquipped( Hero hero ) {\n\t\treturn false;\n\t}\n\n\tpublic final Item identify(){\n\t\treturn identify(true);\n\t}\n\n\tpublic Item identify( boolean byHero ) {\n\n\t\tif (byHero && Dungeon.hero != null && Dungeon.hero.isAlive()){\n\t\t\tCatalog.setSeen(getClass());\n\t\t\tif (!isIdentified()) Talent.onItemIdentified(Dungeon.hero, this);\n\t\t}\n\n\t\tlevelKnown = true;\n\t\tcursedKnown = true;\n\t\tItem.updateQuickslot();\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic void onHeroGainExp( float levelPercent, Hero hero ){\n\t\t//do nothing by default\n\t}\n\t\n\tpublic static void evoke( Hero hero ) {\n\t\thero.sprite.emitter().burst( Speck.factory( Speck.EVOKE ), 5 );\n\t}\n\n\tpublic String title() {\n\n\t\tString name = name();\n\n\t\tif (visiblyUpgraded() != 0)\n\t\t\tname = Messages.format( TXT_TO_STRING_LVL, name, visiblyUpgraded() );\n\n\t\tif (quantity > 1)\n\t\t\tname = Messages.format( TXT_TO_STRING_X, name, quantity );\n\n\t\treturn name;\n\n\t}\n\t\n\tpublic String name() {\n\t\treturn trueName();\n\t}\n\t\n\tpublic final String trueName() {\n\t\treturn Messages.get(this, \"name\");\n\t}\n\t\n\tpublic int image() {\n\t\treturn image;\n\t}\n\t\n\tpublic ItemSprite.Glowing glowing() {\n\t\treturn null;\n\t}\n\n\tpublic Emitter emitter() { return null; }\n\t\n\tpublic String info() {\n\t\treturn desc();\n\t}\n\t\n\tpublic String desc() {\n\t\treturn Messages.get(this, \"desc\");\n\t}\n\t\n\tpublic int quantity() {\n\t\treturn quantity;\n\t}\n\t\n\tpublic Item quantity( int value ) {\n\t\tquantity = value;\n\t\treturn this;\n\t}\n\n\t//item's value in gold coins\n\tpublic int value() {\n\t\treturn 0;\n\t}\n\n\t//item's value in energy crystals\n\tpublic int energyVal() {\n\t\treturn 0;\n\t}\n\t\n\tpublic Item virtual(){\n\t\tItem item = Reflection.newInstance(getClass());\n\t\tif (item == null) return null;\n\t\t\n\t\titem.quantity = 0;\n\t\titem.level = level;\n\t\treturn item;\n\t}\n\t\n\tpublic Item random() {\n\t\treturn this;\n\t}\n\t\n\tpublic String status() {\n\t\treturn quantity != 1 ? Integer.toString( quantity ) : null;\n\t}\n\n\tpublic static void updateQuickslot() {\n\t\tGameScene.updateItemDisplays = true;\n\t}\n\t\n\tprivate static final String QUANTITY\t\t= \"quantity\";\n\tprivate static final String LEVEL\t\t\t= \"level\";\n\tprivate static final String LEVEL_KNOWN\t\t= \"levelKnown\";\n\tprivate static final String CURSED\t\t\t= \"cursed\";\n\tprivate static final String CURSED_KNOWN\t= \"cursedKnown\";\n\tprivate static final String QUICKSLOT\t\t= \"quickslotpos\";\n\tprivate static final String KEPT_LOST = \"kept_lost\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tbundle.put( QUANTITY, quantity );\n\t\tbundle.put( LEVEL, level );\n\t\tbundle.put( LEVEL_KNOWN, levelKnown );\n\t\tbundle.put( CURSED, cursed );\n\t\tbundle.put( CURSED_KNOWN, cursedKnown );\n\t\tif (Dungeon.quickslot.contains(this)) {\n\t\t\tbundle.put( QUICKSLOT, Dungeon.quickslot.getSlot(this) );\n\t\t}\n\t\tbundle.put( KEPT_LOST, keptThoughLostInvent );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tquantity\t= bundle.getInt( QUANTITY );\n\t\tlevelKnown\t= bundle.getBoolean( LEVEL_KNOWN );\n\t\tcursedKnown\t= bundle.getBoolean( CURSED_KNOWN );\n\t\t\n\t\tint level = bundle.getInt( LEVEL );\n\t\tif (level > 0) {\n\t\t\tupgrade( level );\n\t\t} else if (level < 0) {\n\t\t\tdegrade( -level );\n\t\t}\n\t\t\n\t\tcursed\t= bundle.getBoolean( CURSED );\n\n\t\t//only want to populate slot on first load.\n\t\tif (Dungeon.hero == null) {\n\t\t\tif (bundle.contains(QUICKSLOT)) {\n\t\t\t\tDungeon.quickslot.setSlot(bundle.getInt(QUICKSLOT), this);\n\t\t\t}\n\t\t}\n\n\t\tkeptThoughLostInvent = bundle.getBoolean( KEPT_LOST );\n\t}\n\n\tpublic int targetingPos( Hero user, int dst ){\n\t\treturn throwPos( user, dst );\n\t}\n\n\tpublic int throwPos( Hero user, int dst){\n\t\treturn new Ballistica( user.pos, dst, Ballistica.PROJECTILE ).collisionPos;\n\t}\n\n\tpublic void throwSound(){\n\t\tSample.INSTANCE.play(Assets.Sounds.MISS, 0.6f, 0.6f, 1.5f);\n\t}\n\t\n\tpublic void cast( final Hero user, final int dst ) {\n\t\t\n\t\tfinal int cell = throwPos( user, dst );\n\t\tuser.sprite.zap( cell );\n\t\tuser.busy();\n\n\t\tthrowSound();\n\n\t\tChar enemy = Actor.findChar( cell );\n\t\tQuickSlotButton.target(enemy);\n\t\t\n\t\tfinal float delay = castDelay(user, dst);\n\n\t\tif (enemy != null) {\n\t\t\t((MissileSprite) user.sprite.parent.recycle(MissileSprite.class)).\n\t\t\t\t\treset(user.sprite,\n\t\t\t\t\t\t\tenemy.sprite,\n\t\t\t\t\t\t\tthis,\n\t\t\t\t\t\t\tnew Callback() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\t\tcurUser = user;\n\t\t\t\t\t\t\tItem i = Item.this.detach(user.belongings.backpack);\n\t\t\t\t\t\t\tif (i != null) i.onThrow(cell);\n\t\t\t\t\t\t\tif (curUser.hasTalent(Talent.IMPROVISED_PROJECTILES)\n\t\t\t\t\t\t\t\t\t&& !(Item.this instanceof MissileWeapon)\n\t\t\t\t\t\t\t\t\t&& curUser.buff(Talent.ImprovisedProjectileCooldown.class) == null){\n\t\t\t\t\t\t\t\tif (enemy != null && enemy.alignment != curUser.alignment){\n\t\t\t\t\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT);\n\t\t\t\t\t\t\t\t\tBuff.affect(enemy, Blindness.class, 1f + curUser.pointsInTalent(Talent.IMPROVISED_PROJECTILES));\n\t\t\t\t\t\t\t\t\tBuff.affect(curUser, Talent.ImprovisedProjectileCooldown.class, 50f);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (user.buff(Talent.LethalMomentumTracker.class) != null){\n\t\t\t\t\t\t\t\tuser.buff(Talent.LethalMomentumTracker.class).detach();\n\t\t\t\t\t\t\t\tuser.next();\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tuser.spendAndNext(delay);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t} else {\n\t\t\t((MissileSprite) user.sprite.parent.recycle(MissileSprite.class)).\n\t\t\t\t\treset(user.sprite,\n\t\t\t\t\t\t\tcell,\n\t\t\t\t\t\t\tthis,\n\t\t\t\t\t\t\tnew Callback() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\t\tcurUser = user;\n\t\t\t\t\t\t\tItem i = Item.this.detach(user.belongings.backpack);\n\t\t\t\t\t\t\tif (i != null) i.onThrow(cell);\n\t\t\t\t\t\t\tuser.spendAndNext(delay);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t}\n\t}\n\t\n\tpublic float castDelay( Char user, int dst ){\n\t\treturn TIME_TO_THROW;\n\t}\n\t\n\tprotected static Hero curUser = null;\n\tprotected static Item curItem = null;\n\tprotected static CellSelector.Listener thrower = new CellSelector.Listener() {\n\t\t@Override\n\t\tpublic void onSelect( Integer target ) {\n\t\t\tif (target != null) {\n\t\t\t\tcurItem.cast( curUser, target );\n\t\t\t}\n\t\t}\n\t\t@Override\n\t\tpublic String prompt() {\n\t\t\treturn Messages.get(Item.class, \"prompt\");\n\t\t}\n\t};\n}" }, { "identifier": "Bag", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/bags/Bag.java", "snippet": "public class Bag extends Item implements Iterable<Item> {\n\n\tpublic static final String AC_OPEN\t= \"OPEN\";\n\t\n\t{\n\t\timage = 11;\n\t\t\n\t\tdefaultAction = AC_OPEN;\n\n\t\tunique = true;\n\t}\n\t\n\tpublic Char owner;\n\t\n\tpublic ArrayList<Item> items = new ArrayList<>();\n\n\tpublic int capacity(){\n\t\treturn 20; // default container size\n\t}\n\t\n\t@Override\n\tpublic void execute( Hero hero, String action ) {\n\n\t\tsuper.execute( hero, action );\n\n\t\tif (action.equals( AC_OPEN ) && !items.isEmpty()) {\n\t\t\t\n\t\t\tGameScene.show( new WndQuickBag( this ) );\n\t\t\t\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic boolean collect( Bag container ) {\n\n\t\tgrabItems(container);\n\n\t\tif (super.collect( container )) {\n\t\t\t\n\t\t\towner = container.owner;\n\t\t\t\n\t\t\tBadges.validateAllBagsBought( this );\n\t\t\t\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onDetach( ) {\n\t\tthis.owner = null;\n\t\tfor (Item item : items)\n\t\t\tDungeon.quickslot.clearItem(item);\n\t\tupdateQuickslot();\n\t}\n\n\tpublic void grabItems(){\n\t\tif (owner != null && owner instanceof Hero && this != ((Hero) owner).belongings.backpack) {\n\t\t\tgrabItems(((Hero) owner).belongings.backpack);\n\t\t}\n\t}\n\n\tpublic void grabItems( Bag container ){\n\t\tfor (Item item : container.items.toArray( new Item[0] )) {\n\t\t\tif (canHold( item )) {\n\t\t\t\tint slot = Dungeon.quickslot.getSlot(item);\n\t\t\t\titem.detachAll(container);\n\t\t\t\tif (!item.collect(this)) {\n\t\t\t\t\titem.collect(container);\n\t\t\t\t}\n\t\t\t\tif (slot != -1) {\n\t\t\t\t\tDungeon.quickslot.setSlot(slot, item);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean isUpgradable() {\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic boolean isIdentified() {\n\t\treturn true;\n\t}\n\t\n\tpublic void clear() {\n\t\titems.clear();\n\t}\n\t\n\tpublic void resurrect() {\n\t\tfor (Item item : items.toArray(new Item[0])){\n\t\t\tif (!item.unique) items.remove(item);\n\t\t}\n\t}\n\t\n\tprivate static final String ITEMS\t= \"inventory\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tsuper.storeInBundle( bundle );\n\t\tbundle.put( ITEMS, items );\n\t}\n\n\t//temp variable so that bags can load contents even with lost inventory debuff\n\tprivate boolean loading;\n\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tsuper.restoreFromBundle( bundle );\n\n\t\tloading = true;\n\t\tfor (Bundlable item : bundle.getCollection( ITEMS )) {\n\t\t\tif (item != null) ((Item)item).collect( this );\n\t\t}\n\t\tloading = false;\n\t}\n\t\n\tpublic boolean contains( Item item ) {\n\t\tfor (Item i : items) {\n\t\t\tif (i == item) {\n\t\t\t\treturn true;\n\t\t\t} else if (i instanceof Bag && ((Bag)i).contains( item )) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean canHold( Item item ){\n\t\tif (!loading && owner != null && owner.buff(LostInventory.class) != null\n\t\t\t&& !item.keptThroughLostInventory()){\n\t\t\treturn false;\n\t\t}\n\n\t\tif (items.contains(item) || item instanceof Bag || items.size() < capacity()){\n\t\t\treturn true;\n\t\t} else if (item.stackable) {\n\t\t\tfor (Item i : items) {\n\t\t\t\tif (item.isSimilar( i )) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic Iterator<Item> iterator() {\n\t\treturn new ItemIterator();\n\t}\n\t\n\tprivate class ItemIterator implements Iterator<Item> {\n\n\t\tprivate int index = 0;\n\t\tprivate Iterator<Item> nested = null;\n\t\t\n\t\t@Override\n\t\tpublic boolean hasNext() {\n\t\t\tif (nested != null) {\n\t\t\t\treturn nested.hasNext() || index < items.size();\n\t\t\t} else {\n\t\t\t\treturn index < items.size();\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic Item next() {\n\t\t\tif (nested != null && nested.hasNext()) {\n\t\t\t\t\n\t\t\t\treturn nested.next();\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\t\n\t\t\t\tnested = null;\n\t\t\t\t\n\t\t\t\tItem item = items.get( index++ );\n\t\t\t\tif (item instanceof Bag) {\n\t\t\t\t\tnested = ((Bag)item).iterator();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn item;\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void remove() {\n\t\t\tif (nested != null) {\n\t\t\t\tnested.remove();\n\t\t\t} else {\n\t\t\t\titems.remove( index );\n\t\t\t}\n\t\t}\n\t}\n}" }, { "identifier": "Potion", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/potions/Potion.java", "snippet": "public class Potion extends Item {\n\n\tpublic static final String AC_DRINK = \"DRINK\";\n\t\n\t//used internally for potions that can be drunk or thrown\n\tpublic static final String AC_CHOOSE = \"CHOOSE\";\n\n\tprivate static final float TIME_TO_DRINK = 1f;\n\n\tprivate static final LinkedHashMap<String, Integer> colors = new LinkedHashMap<String, Integer>() {\n\t\t{\n\t\t\tput(\"crimson\",ItemSpriteSheet.POTION_CRIMSON);\n\t\t\tput(\"amber\",ItemSpriteSheet.POTION_AMBER);\n\t\t\tput(\"golden\",ItemSpriteSheet.POTION_GOLDEN);\n\t\t\tput(\"jade\",ItemSpriteSheet.POTION_JADE);\n\t\t\tput(\"turquoise\",ItemSpriteSheet.POTION_TURQUOISE);\n\t\t\tput(\"azure\",ItemSpriteSheet.POTION_AZURE);\n\t\t\tput(\"indigo\",ItemSpriteSheet.POTION_INDIGO);\n\t\t\tput(\"magenta\",ItemSpriteSheet.POTION_MAGENTA);\n\t\t\tput(\"bistre\",ItemSpriteSheet.POTION_BISTRE);\n\t\t\tput(\"charcoal\",ItemSpriteSheet.POTION_CHARCOAL);\n\t\t\tput(\"silver\",ItemSpriteSheet.POTION_SILVER);\n\t\t\tput(\"ivory\",ItemSpriteSheet.POTION_IVORY);\n\t\t}\n\t};\n\t\n\tprivate static final HashSet<Class<?extends Potion>> mustThrowPots = new HashSet<>();\n\tstatic{\n\t\tmustThrowPots.add(PotionOfToxicGas.class);\n\t\tmustThrowPots.add(PotionOfLiquidFlame.class);\n\t\tmustThrowPots.add(PotionOfParalyticGas.class);\n\t\tmustThrowPots.add(PotionOfFrost.class);\n\t\t\n\t\t//exotic\n\t\tmustThrowPots.add(PotionOfCorrosiveGas.class);\n\t\tmustThrowPots.add(PotionOfSnapFreeze.class);\n\t\tmustThrowPots.add(PotionOfShroudingFog.class);\n\t\tmustThrowPots.add(PotionOfStormClouds.class);\n\t\t\n\t\t//also all brews, hardcoded\n\t}\n\t\n\tprivate static final HashSet<Class<?extends Potion>> canThrowPots = new HashSet<>();\n\tstatic{\n\t\tcanThrowPots.add(AlchemicalCatalyst.class);\n\t\t\n\t\tcanThrowPots.add(PotionOfPurity.class);\n\t\tcanThrowPots.add(PotionOfLevitation.class);\n\t\t\n\t\t//exotic\n\t\tcanThrowPots.add(PotionOfCleansing.class);\n\t\t\n\t\t//elixirs\n\t\tcanThrowPots.add(ElixirOfHoneyedHealing.class);\n\t}\n\t\n\tprotected static ItemStatusHandler<Potion> handler;\n\t\n\tprotected String color;\n\n\t//affects how strongly on-potion talents trigger from this potion\n\tprotected float talentFactor = 1;\n\t\n\t{\n\t\tstackable = true;\n\t\tdefaultAction = AC_DRINK;\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static void initColors() {\n\t\thandler = new ItemStatusHandler<>( (Class<? extends Potion>[])Generator.Category.POTION.classes, colors );\n\t}\n\t\n\tpublic static void save( Bundle bundle ) {\n\t\thandler.save( bundle );\n\t}\n\n\tpublic static void saveSelectively( Bundle bundle, ArrayList<Item> items ) {\n\t\tArrayList<Class<?extends Item>> classes = new ArrayList<>();\n\t\tfor (Item i : items){\n\t\t\tif (i instanceof ExoticPotion){\n\t\t\t\tif (!classes.contains(ExoticPotion.exoToReg.get(i.getClass()))){\n\t\t\t\t\tclasses.add(ExoticPotion.exoToReg.get(i.getClass()));\n\t\t\t\t}\n\t\t\t} else if (i instanceof Potion){\n\t\t\t\tif (!classes.contains(i.getClass())){\n\t\t\t\t\tclasses.add(i.getClass());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\thandler.saveClassesSelectively( bundle, classes );\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static void restore( Bundle bundle ) {\n\t\thandler = new ItemStatusHandler<>( (Class<? extends Potion>[])Generator.Category.POTION.classes, colors, bundle );\n\t}\n\t\n\tpublic Potion() {\n\t\tsuper();\n\t\treset();\n\t}\n\t\n\t//anonymous potions are always IDed, do not affect ID status,\n\t//and their sprite is replaced by a placeholder if they are not known,\n\t//useful for items that appear in UIs, or which are only spawned for their effects\n\tprotected boolean anonymous = false;\n\tpublic void anonymize(){\n\t\tif (!isKnown()) image = ItemSpriteSheet.POTION_HOLDER;\n\t\tanonymous = true;\n\t}\n\n\t@Override\n\tpublic void reset(){\n\t\tsuper.reset();\n\t\tif (handler != null && handler.contains(this)) {\n\t\t\timage = handler.image(this);\n\t\t\tcolor = handler.label(this);\n\t\t}\n\t}\n\n\t@Override\n\tpublic String defaultAction() {\n\t\tif (isKnown() && mustThrowPots.contains(this.getClass())) {\n\t\t\treturn AC_THROW;\n\t\t} else if (isKnown() &&canThrowPots.contains(this.getClass())){\n\t\t\treturn AC_CHOOSE;\n\t\t} else {\n\t\t\treturn AC_DRINK;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic ArrayList<String> actions( Hero hero ) {\n\t\tArrayList<String> actions = super.actions( hero );\n\t\tactions.add( AC_DRINK );\n\t\treturn actions;\n\t}\n\t\n\t@Override\n\tpublic void execute( final Hero hero, String action ) {\n\n\t\tsuper.execute( hero, action );\n\t\t\n\t\tif (action.equals( AC_CHOOSE )){\n\t\t\t\n\t\t\tGameScene.show(new WndUseItem(null, this) );\n\t\t\t\n\t\t} else if (action.equals( AC_DRINK )) {\n\t\t\t\n\t\t\tif (isKnown() && mustThrowPots.contains(getClass())) {\n\t\t\t\t\n\t\t\t\t\tGameScene.show(\n\t\t\t\t\t\tnew WndOptions(new ItemSprite(this),\n\t\t\t\t\t\t\t\tMessages.get(Potion.class, \"harmful\"),\n\t\t\t\t\t\t\t\tMessages.get(Potion.class, \"sure_drink\"),\n\t\t\t\t\t\t\t\tMessages.get(Potion.class, \"yes\"), Messages.get(Potion.class, \"no\") ) {\n\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\tprotected void onSelect(int index) {\n\t\t\t\t\t\t\t\tif (index == 0) {\n\t\t\t\t\t\t\t\t\tdrink( hero );\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t\t\n\t\t\t\t} else {\n\t\t\t\t\tdrink( hero );\n\t\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void doThrow( final Hero hero ) {\n\n\t\tif (isKnown()\n\t\t\t\t&& !mustThrowPots.contains(this.getClass())\n\t\t\t\t&& !canThrowPots.contains(this.getClass())) {\n\t\t\n\t\t\tGameScene.show(\n\t\t\t\tnew WndOptions(new ItemSprite(this),\n\t\t\t\t\t\tMessages.get(Potion.class, \"beneficial\"),\n\t\t\t\t\t\tMessages.get(Potion.class, \"sure_throw\"),\n\t\t\t\t\t\tMessages.get(Potion.class, \"yes\"), Messages.get(Potion.class, \"no\") ) {\n\t\t\t\t\t@Override\n\t\t\t\t\tprotected void onSelect(int index) {\n\t\t\t\t\t\tif (index == 0) {\n\t\t\t\t\t\t\tPotion.super.doThrow( hero );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t\t\n\t\t} else {\n\t\t\tsuper.doThrow( hero );\n\t\t}\n\t}\n\t\n\tprotected void drink( Hero hero ) {\n\t\t\n\t\tdetach( hero.belongings.backpack );\n\t\t\n\t\thero.spend( TIME_TO_DRINK );\n\t\thero.busy();\n\t\tapply( hero );\n\t\t\n\t\tSample.INSTANCE.play( Assets.Sounds.DRINK );\n\t\t\n\t\thero.sprite.operate( hero.pos );\n\n\t\tif (!anonymous){\n\t\t\tTalent.onPotionUsed(curUser, curUser.pos, talentFactor);\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected void onThrow( int cell ) {\n\t\tif (Dungeon.level.map[cell] == Terrain.WELL || Dungeon.level.pit[cell]) {\n\t\t\t\n\t\t\tsuper.onThrow( cell );\n\t\t\t\n\t\t} else {\n\n\t\t\tDungeon.level.pressCell( cell );\n\t\t\tshatter( cell );\n\n\t\t\tif (!anonymous){\n\t\t\t\tTalent.onPotionUsed(curUser, cell, talentFactor);\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\t\n\tpublic void apply( Hero hero ) {\n\t\tshatter( hero.pos );\n\t}\n\t\n\tpublic void shatter( int cell ) {\n\t\tif (Dungeon.level.heroFOV[cell]) {\n\t\t\tGLog.i( Messages.get(Potion.class, \"shatter\") );\n\t\t\tSample.INSTANCE.play( Assets.Sounds.SHATTER );\n\t\t\tsplash( cell );\n\t\t}\n\t}\n\n\t@Override\n\tpublic void cast( final Hero user, int dst ) {\n\t\t\tsuper.cast(user, dst);\n\t}\n\t\n\tpublic boolean isKnown() {\n\t\treturn anonymous || (handler != null && handler.isKnown( this ));\n\t}\n\t\n\tpublic void setKnown() {\n\t\tif (!anonymous) {\n\t\t\tif (!isKnown()) {\n\t\t\t\thandler.know(this);\n\t\t\t\tupdateQuickslot();\n\t\t\t}\n\t\t\t\n\t\t\tif (Dungeon.hero.isAlive()) {\n\t\t\t\tCatalog.setSeen(getClass());\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic Item identify( boolean byHero ) {\n\t\tsuper.identify(byHero);\n\n\t\tif (!isKnown()) {\n\t\t\tsetKnown();\n\t\t}\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic String name() {\n\t\treturn isKnown() ? super.name() : Messages.get(this, color);\n\t}\n\t\n\t@Override\n\tpublic String info() {\n\t\treturn isKnown() ? desc() : Messages.get(this, \"unknown_desc\");\n\t}\n\t\n\t@Override\n\tpublic boolean isIdentified() {\n\t\treturn isKnown();\n\t}\n\t\n\t@Override\n\tpublic boolean isUpgradable() {\n\t\treturn false;\n\t}\n\t\n\tpublic static HashSet<Class<? extends Potion>> getKnown() {\n\t\treturn handler.known();\n\t}\n\t\n\tpublic static HashSet<Class<? extends Potion>> getUnknown() {\n\t\treturn handler.unknown();\n\t}\n\t\n\tpublic static boolean allKnown() {\n\t\treturn handler.known().size() == Generator.Category.POTION.classes.length;\n\t}\n\t\n\tprotected int splashColor(){\n\t\treturn anonymous ? 0x00AAFF : ItemSprite.pick( image, 5, 9 );\n\t}\n\t\n\tprotected void splash( int cell ) {\n\n\t\tFire fire = (Fire)Dungeon.level.blobs.get( Fire.class );\n\t\tif (fire != null)\n\t\t\tfire.clear( cell );\n\n\t\tfinal int color = splashColor();\n\n\t\tChar ch = Actor.findChar(cell);\n\t\tif (ch != null && ch.alignment == Char.Alignment.ALLY) {\n\t\t\tBuff.detach(ch, Burning.class);\n\t\t\tBuff.detach(ch, Ooze.class);\n\t\t\tSplash.at( ch.sprite.center(), color, 5 );\n\t\t} else {\n\t\t\tSplash.at( cell, color, 5 );\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic int value() {\n\t\treturn 30 * quantity;\n\t}\n\n\t@Override\n\tpublic int energyVal() {\n\t\treturn 6 * quantity;\n\t}\n\n\tpublic static class PlaceHolder extends Potion {\n\t\t\n\t\t{\n\t\t\timage = ItemSpriteSheet.POTION_HOLDER;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean isSimilar(Item item) {\n\t\t\treturn ExoticPotion.regToExo.containsKey(item.getClass())\n\t\t\t\t\t|| ExoticPotion.regToExo.containsValue(item.getClass());\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String info() {\n\t\t\treturn \"\";\n\t\t}\n\t}\n\t\n\tpublic static class SeedToPotion extends Recipe {\n\t\t\n\t\tpublic static HashMap<Class<?extends Plant.Seed>, Class<?extends Potion>> types = new HashMap<>();\n\t\tstatic {\n\t\t\ttypes.put(Blindweed.Seed.class, PotionOfInvisibility.class);\n\t\t\ttypes.put(Mageroyal.Seed.class, PotionOfPurity.class);\n\t\t\ttypes.put(Earthroot.Seed.class, PotionOfParalyticGas.class);\n\t\t\ttypes.put(Fadeleaf.Seed.class, PotionOfMindVision.class);\n\t\t\ttypes.put(Firebloom.Seed.class, PotionOfLiquidFlame.class);\n\t\t\ttypes.put(Icecap.Seed.class, PotionOfFrost.class);\n\t\t\ttypes.put(Rotberry.Seed.class, PotionOfStrength.class);\n\t\t\ttypes.put(Sorrowmoss.Seed.class, PotionOfToxicGas.class);\n\t\t\ttypes.put(Starflower.Seed.class, PotionOfExperience.class);\n\t\t\ttypes.put(Stormvine.Seed.class, PotionOfLevitation.class);\n\t\t\ttypes.put(Sungrass.Seed.class, PotionOfHealing.class);\n\t\t\ttypes.put(Swiftthistle.Seed.class, PotionOfHaste.class);\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean testIngredients(ArrayList<Item> ingredients) {\n\t\t\tif (ingredients.size() != 3) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tfor (Item ingredient : ingredients){\n\t\t\t\tif (!(ingredient instanceof Plant.Seed\n\t\t\t\t\t\t&& ingredient.quantity() >= 1\n\t\t\t\t\t\t&& types.containsKey(ingredient.getClass()))){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic int cost(ArrayList<Item> ingredients) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic Item brew(ArrayList<Item> ingredients) {\n\t\t\tif (!testIngredients(ingredients)) return null;\n\t\t\t\n\t\t\tfor (Item ingredient : ingredients){\n\t\t\t\tingredient.quantity(ingredient.quantity() - 1);\n\t\t\t}\n\t\t\t\n\t\t\tArrayList<Class<?extends Plant.Seed>> seeds = new ArrayList<>();\n\t\t\tfor (Item i : ingredients) {\n\t\t\t\tif (!seeds.contains(i.getClass())) {\n\t\t\t\t\tseeds.add((Class<? extends Plant.Seed>) i.getClass());\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tPotion result;\n\t\t\t\n\t\t\tif ( (seeds.size() == 2 && Random.Int(4) == 0)\n\t\t\t\t\t|| (seeds.size() == 3 && Random.Int(2) == 0)) {\n\t\t\t\t\n\t\t\t\tresult = (Potion) Generator.randomUsingDefaults( Generator.Category.POTION );\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tresult = Reflection.newInstance(types.get(Random.element(ingredients).getClass()));\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tif (seeds.size() == 1){\n\t\t\t\tresult.identify();\n\t\t\t}\n\n\t\t\twhile (result instanceof PotionOfHealing\n\t\t\t\t\t&& Random.Int(10) < Dungeon.LimitedDrops.COOKING_HP.count) {\n\n\t\t\t\tresult = (Potion) Generator.randomUsingDefaults(Generator.Category.POTION);\n\t\t\t}\n\t\t\t\n\t\t\tif (result instanceof PotionOfHealing) {\n\t\t\t\tDungeon.LimitedDrops.COOKING_HP.count++;\n\t\t\t}\n\t\t\t\n\t\t\treturn result;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic Item sampleOutput(ArrayList<Item> ingredients) {\n\t\t\treturn new WndBag.Placeholder(ItemSpriteSheet.POTION_HOLDER){\n\n\t\t\t\t@Override\n\t\t\t\tpublic String name() {\n\t\t\t\t\treturn Messages.get(Potion.SeedToPotion.class, \"name\");\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t@Override\n\t\t\t\tpublic String info() {\n\t\t\t\t\treturn \"\";\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n}" }, { "identifier": "CorpseDust", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/quest/CorpseDust.java", "snippet": "public class CorpseDust extends Item {\n\t\n\t{\n\t\timage = ItemSpriteSheet.DUST;\n\t\t\n\t\tcursed = true;\n\t\tcursedKnown = true;\n\t\t\n\t\tunique = true;\n\t}\n\n\t@Override\n\tpublic ArrayList<String> actions(Hero hero) {\n\t\treturn new ArrayList<>(); //yup, no dropping this one\n\t}\n\n\t@Override\n\tpublic boolean isUpgradable() {\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic boolean isIdentified() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean doPickUp(Hero hero, int pos) {\n\t\tif (super.doPickUp(hero, pos)){\n\t\t\tGLog.n( Messages.get( this, \"chill\") );\n\t\t\tBuff.affect(hero, DustGhostSpawner.class);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tprotected void onDetach() {\n\t\tDustGhostSpawner spawner = Dungeon.hero.buff(DustGhostSpawner.class);\n\t\tif (spawner != null){\n\t\t\tspawner.dispel();\n\t\t}\n\t}\n\n\tpublic static class DustGhostSpawner extends Buff {\n\n\t\tint spawnPower = 0;\n\n\t\t{\n\t\t\t//not cleansed by reviving, but does check to ensure the dust is still present\n\t\t\trevivePersists = true;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean act() {\n\t\t\tif (target instanceof Hero && ((Hero) target).belongings.getItem(CorpseDust.class) == null){\n\t\t\t\tspawnPower = 0;\n\t\t\t\tspend(TICK);\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tspawnPower++;\n\t\t\tint wraiths = 1; //we include the wraith we're trying to spawn\n\t\t\tfor (Mob mob : Dungeon.level.mobs){\n\t\t\t\tif (mob instanceof Wraith){\n\t\t\t\t\twraiths++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//summoning a new wraith requires 1/4/9/16/25/36/49/49/... turns of energy\n\t\t\t//note that logic for summoning wraiths kind of has an odd, undocumented balance history:\n\t\t\t//v0.3.1-v0.6.5: wraith every 1/4/9/16/25/25... turns, basically guaranteed\n\t\t\t//v0.7.0-v2.1.4: bugged, same rate as above but high (often >50%) chance that spawning fails. failed spawning resets delay!\n\t\t\t//v2.2.0+: fixed bug, increased summon delay cap to counteract a bit, wraiths also now have to spawn at a slight distance\n\t\t\tint powerNeeded = Math.min(49, wraiths*wraiths);\n\t\t\tif (powerNeeded <= spawnPower){\n\t\t\t\tArrayList<Integer> candidates = new ArrayList<>();\n\t\t\t\t//min distance scales based on hero's view distance\n\t\t\t\t// wraiths must spawn at least 4/3/2/1 tiles away at view distance of 8(default)/7/4/1\n\t\t\t\tint minDist = Math.round(Dungeon.hero.viewDistance/3f);\n\t\t\t\tfor (int i = 0; i < Dungeon.level.length(); i++){\n\t\t\t\t\tif (Dungeon.level.heroFOV[i]\n\t\t\t\t\t\t\t&& !Dungeon.level.solid[i]\n\t\t\t\t\t\t\t&& Actor.findChar( i ) == null\n\t\t\t\t\t\t\t&& Dungeon.level.distance(i, Dungeon.hero.pos) > minDist){\n\t\t\t\t\t\tcandidates.add(i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!candidates.isEmpty()){\n\t\t\t\t\tWraith.spawnAt(Random.element(candidates), false);\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.CURSED);\n\t\t\t\t\tspawnPower -= powerNeeded;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tspend(TICK);\n\t\t\treturn true;\n\t\t}\n\n\t\tpublic void dispel(){\n\t\t\tdetach();\n\t\t\tfor (Mob mob : Dungeon.level.mobs.toArray(new Mob[0])){\n\t\t\t\tif (mob instanceof Wraith){\n\t\t\t\t\tmob.die(null);\n\t\t\t\t}\n\t\t\t}\n\t\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t\t@Override\n\t\t\t\tpublic void call() {\n\t\t\t\t\tMusic.INSTANCE.fadeOut(1f, new Callback() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\t\tif (Dungeon.level != null) {\n\t\t\t\t\t\t\t\tDungeon.level.playLevelMusic();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tprivate static String SPAWNPOWER = \"spawnpower\";\n\n\t\t@Override\n\t\tpublic void storeInBundle(Bundle bundle) {\n\t\t\tsuper.storeInBundle(bundle);\n\t\t\tbundle.put( SPAWNPOWER, spawnPower );\n\t\t}\n\n\t\t@Override\n\t\tpublic void restoreFromBundle(Bundle bundle) {\n\t\t\tsuper.restoreFromBundle(bundle);\n\t\t\tspawnPower = bundle.getInt( SPAWNPOWER );\n\t\t}\n\t}\n\n}" }, { "identifier": "Ring", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/rings/Ring.java", "snippet": "public class Ring extends KindofMisc {\n\t\n\tprotected Buff buff;\n\n\tprivate static final LinkedHashMap<String, Integer> gems = new LinkedHashMap<String, Integer>() {\n\t\t{\n\t\t\tput(\"garnet\",ItemSpriteSheet.RING_GARNET);\n\t\t\tput(\"ruby\",ItemSpriteSheet.RING_RUBY);\n\t\t\tput(\"topaz\",ItemSpriteSheet.RING_TOPAZ);\n\t\t\tput(\"emerald\",ItemSpriteSheet.RING_EMERALD);\n\t\t\tput(\"onyx\",ItemSpriteSheet.RING_ONYX);\n\t\t\tput(\"opal\",ItemSpriteSheet.RING_OPAL);\n\t\t\tput(\"tourmaline\",ItemSpriteSheet.RING_TOURMALINE);\n\t\t\tput(\"sapphire\",ItemSpriteSheet.RING_SAPPHIRE);\n\t\t\tput(\"amethyst\",ItemSpriteSheet.RING_AMETHYST);\n\t\t\tput(\"quartz\",ItemSpriteSheet.RING_QUARTZ);\n\t\t\tput(\"agate\",ItemSpriteSheet.RING_AGATE);\n\t\t\tput(\"diamond\",ItemSpriteSheet.RING_DIAMOND);\n\t\t}\n\t};\n\n\tpublic static final int RING_ACCURACY \t\t= 0;\n\tpublic static final int RING_ARCANA \t\t= 1;\n\tpublic static final int RING_ELEMENTS \t\t= 2;\n\tpublic static final int RING_ENERGY \t\t= 3;\n\tpublic static final int RING_EVASION \t\t= 4;\n\tpublic static final int RING_FORCE \t\t= 5;\n\tpublic static final int RING_FUROR \t\t= 6;\n\tpublic static final int RING_HASTE \t\t= 7;\n\tpublic static final int RING_MIGHT \t\t= 8;\n\tpublic static final int RING_SHARPSHOOTING = 9;\n\tpublic static final int RING_TENACITY \t\t= 10;\n\tpublic static final int RING_WEALTH\t\t\t= 11;\n\n\tpublic static final HashMap<Class<?extends Ring>, Integer> ringTypes = new HashMap<>();\n\tstatic {\n\t\tringTypes.put(RingOfAccuracy.class,\t\t\tRING_ACCURACY\t\t);\n\t\tringTypes.put(RingOfArcana.class,\t\t\tRING_ARCANA \t\t);\n\t\tringTypes.put(RingOfElements.class,\t\t\tRING_ELEMENTS \t\t);\n\t\tringTypes.put(RingOfEnergy.class,\t\t\tRING_ENERGY \t\t);\n\t\tringTypes.put(RingOfEvasion.class,\t\t\tRING_EVASION \t\t);\n\t\tringTypes.put(RingOfForce.class,\t\t\tRING_FORCE \t\t);\n\t\tringTypes.put(RingOfFuror.class,\t\t\tRING_FUROR \t\t);\n\t\tringTypes.put(RingOfHaste.class,\t\t\tRING_HASTE \t\t);\n\t\tringTypes.put(RingOfMight.class,\t\t\tRING_MIGHT \t\t);\n\t\tringTypes.put(RingOfSharpshooting.class,\tRING_SHARPSHOOTING );\n\t\tringTypes.put(RingOfTenacity.class, \t\tRING_TENACITY \t\t);\n\t\tringTypes.put(RingOfWealth.class,\t\t\tRING_WEALTH\t\t\t);\n\t}\n\t\n\tprivate static ItemStatusHandler<Ring> handler;\n\t\n\tprivate String gem;\n\t\n\t//rings cannot be 'used' like other equipment, so they ID purely based on exp\n\tprivate float levelsToID = 1;\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static void initGems() {\n\t\thandler = new ItemStatusHandler<>( (Class<? extends Ring>[])Generator.Category.RING.classes, gems );\n\t}\n\t\n\tpublic static void save( Bundle bundle ) {\n\t\thandler.save( bundle );\n\t}\n\n\tpublic static void saveSelectively( Bundle bundle, ArrayList<Item> items ) {\n\t\thandler.saveSelectively( bundle, items );\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static void restore( Bundle bundle ) {\n\t\thandler = new ItemStatusHandler<>( (Class<? extends Ring>[])Generator.Category.RING.classes, gems, bundle );\n\t}\n\t\n\tpublic Ring() {\n\t\tsuper();\n\t\treset();\n\t}\n\n\t//anonymous rings are always IDed, do not affect ID status,\n\t//and their sprite is replaced by a placeholder if they are not known,\n\t//useful for items that appear in UIs, or which are only spawned for their effects\n\tprotected boolean anonymous = false;\n\tpublic void anonymize(){\n\t\tif (!isKnown()) image = ItemSpriteSheet.RING_HOLDER;\n\t\tanonymous = true;\n\t}\n\t\n\tpublic void reset() {\n\t\tsuper.reset();\n\t\tlevelsToID = 1;\n\t\tif (handler != null && handler.contains(this)){\n\t\t\timage = handler.image(this);\n\t\t\tgem = handler.label(this);\n\t\t}\n\t}\n\t\n\tpublic void activate( Char ch ) {\n\t\tif (buff != null){\n\t\t\tbuff.detach();\n\t\t\tbuff = null;\n\t\t}\n\t\tbuff = buff();\n\t\tbuff.attachTo( ch );\n\t}\n\n\t@Override\n\tpublic boolean doUnequip( Hero hero, boolean collect, boolean single ) {\n\t\tif (super.doUnequip( hero, collect, single )) {\n\n\t\t\tif (buff != null) {\n\t\t\t\tbuff.detach();\n\t\t\t\tbuff = null;\n\t\t\t}\n\n\t\t\treturn true;\n\n\t\t} else {\n\n\t\t\treturn false;\n\n\t\t}\n\t}\n\t\n\tpublic boolean isKnown() {\n\t\treturn anonymous || (handler != null && handler.isKnown( this ));\n\t}\n\t\n\tpublic void setKnown() {\n\t\tif (!anonymous) {\n\t\t\tif (!isKnown()) {\n\t\t\t\thandler.know(this);\n\t\t\t}\n\n\t\t\tif (Dungeon.hero.isAlive()) {\n\t\t\t\tCatalog.setSeen(getClass());\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic String name() {\n\t\treturn isKnown() ? super.name() : Messages.get(Ring.class, gem);\n\t}\n\t\n\t@Override\n\tpublic String info(){\n\n\t\tString desc = isKnown() ? super.desc() : Messages.get(this, \"unknown_desc\");\n\t\t\n\t\tif (cursed && isEquipped( Dungeon.hero )) {\n\t\t\tdesc += \"\\n\\n\" + Messages.get(Ring.class, \"cursed_worn\");\n\t\t\t\n\t\t} else if (cursed && cursedKnown) {\n\t\t\tdesc += \"\\n\\n\" + Messages.get(Ring.class, \"curse_known\");\n\t\t\t\n\t\t} else if (!isIdentified() && cursedKnown){\n\t\t\tdesc += \"\\n\\n\" + Messages.get(Ring.class, \"not_cursed\");\n\t\t\t\n\t\t}\n\t\t\n\t\tif (isKnown()) {\n\t\t\tdesc += \"\\n\\n\" + statsInfo();\n\t\t}\n\t\t\n\t\treturn desc;\n\t}\n\t\n\tprotected String statsInfo(){\n\t\treturn \"\";\n\t}\n\t\n\t@Override\n\tpublic Item upgrade() {\n\t\tsuper.upgrade();\n\t\t\n\t\tif (Random.Int(3) == 0) {\n\t\t\tcursed = false;\n\t\t}\n\t\t\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic boolean isIdentified() {\n\t\treturn super.isIdentified() && isKnown();\n\t}\n\t\n\t@Override\n\tpublic Item identify( boolean byHero ) {\n\t\tsetKnown();\n\t\tlevelsToID = 0;\n\t\treturn super.identify(byHero);\n\t}\n\t\n\t@Override\n\tpublic Item random() {\n\t\t//+0: 66.67% (2/3)\n\t\t//+1: 26.67% (4/15)\n\t\t//+2: 6.67% (1/15)\n\t\tint n = 0;\n\t\tif (Random.Int(3) == 0) {\n\t\t\tn++;\n\t\t\tif (Random.Int(5) == 0){\n\t\t\t\tn++;\n\t\t\t}\n\t\t}\n\t\tlevel(n);\n\t\t\n\t\t//30% chance to be cursed\n\t\tif (Random.Float() < 0.3f) {\n\t\t\tcursed = true;\n\t\t}\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic static HashSet<Class<? extends Ring>> getKnown() {\n\t\treturn handler.known();\n\t}\n\t\n\tpublic static HashSet<Class<? extends Ring>> getUnknown() {\n\t\treturn handler.unknown();\n\t}\n\t\n\tpublic static boolean allKnown() {\n\t\treturn handler.known().size() == Generator.Category.RING.classes.length;\n\t}\n\t\n\t@Override\n\tpublic int value() {\n\t\tint price = 75;\n\t\tif (cursed && cursedKnown) {\n\t\t\tprice /= 2;\n\t\t}\n\t\tif (levelKnown) {\n\t\t\tif (level() > 0) {\n\t\t\t\tprice *= (level() + 1);\n\t\t\t} else if (level() < 0) {\n\t\t\t\tprice /= (1 - level());\n\t\t\t}\n\t\t}\n\t\tif (price < 1) {\n\t\t\tprice = 1;\n\t\t}\n\t\treturn price;\n\t}\n\t\n\tprotected RingBuff buff() {\n\t\treturn null;\n\t}\n\n\tprivate static final String LEVELS_TO_ID = \"levels_to_ID\";\n\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tsuper.storeInBundle( bundle );\n\t\tbundle.put( LEVELS_TO_ID, levelsToID );\n\t}\n\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tsuper.restoreFromBundle( bundle );\n\t\tlevelsToID = bundle.getFloat( LEVELS_TO_ID );\n\t}\n\t\n\tpublic void onHeroGainExp( float levelPercent, Hero hero ){\n\t\tif (isIdentified() || !isEquipped(hero)) return;\n\t\tlevelPercent *= Talent.itemIDSpeedFactor(hero, this);\n\t\t//becomes IDed after 1 level\n\t\tlevelsToID -= levelPercent;\n\t\tif (levelsToID <= 0){\n\t\t\tidentify();\n\t\t\tGLog.p( Messages.get(Ring.class, \"identify\") );\n\t\t\tBadges.validateItemLevelAquired( this );\n\t\t}\n\t}\n\n\t@Override\n\tpublic int buffedLvl() {\n\t\tint lvl = super.buffedLvl();\n\t\tif (Dungeon.hero.buff(EnhancedRings.class) != null){\n\t\t\tlvl++;\n\t\t}\n\t\tEnhancedRingsCombo enhancedRingsCombo = Dungeon.hero.buff(EnhancedRingsCombo.class);\n\t\tif (enhancedRingsCombo != null){\n\t\t\tlvl += enhancedRingsCombo.getCombo();\n\t\t}\n\t\treturn lvl;\n\t}\n\n\tpublic static int getBonus(Char target, Class<?extends RingBuff> type){\n\t\tif (target.buff(MagicImmune.class) != null) return 0;\n\t\tint bonus = 0;\n\t\tfor (RingBuff buff : target.buffs(type)) {\n\t\t\tbonus += buff.level();\n\t\t}\n\t\treturn bonus;\n\t}\n\n\tpublic static int getBuffedBonus(Char target, Class<?extends RingBuff> type){\n\t\tif (target.buff(MagicImmune.class) != null) return 0;\n\t\tint bonus = 0;\n\t\tfor (RingBuff buff : target.buffs(type)) {\n\t\t\tbonus += buff.buffedLvl();\n\t\t}\n\t\treturn bonus;\n\t}\n\n\t//just used for ring descriptions\n\tpublic int soloBonus(){\n\t\tif (cursed){\n\t\t\treturn Math.min( 0, Ring.this.level()-2 );\n\t\t} else {\n\t\t\treturn Ring.this.buffedLvl()+1;\n\t\t}\n\t}\n\n\t//just used for ring descriptions\n\tpublic int soloBuffedBonus(){\n\t\tif (cursed){\n\t\t\treturn Math.min( 0, Ring.this.buffedLvl()-2 );\n\t\t} else {\n\t\t\treturn Ring.this.buffedLvl()+1;\n\t\t}\n\t}\n\n\t//just used for ring descriptions\n\tpublic static int combinedBuffedBonus(Char target, Class<?extends RingBuff> type){\n\t\tint bonus = 0;\n\t\tfor (RingBuff buff : target.buffs(type)) {\n\t\t\tbonus += buff.buffedLvl();\n\t\t}\n\t\treturn bonus;\n\t}\n\n\tpublic static float onHit (Hero hero, Char enemy, int damage, int ring) {\n\t\tfloat damageMulti = 1;\n\t\tswitch (ring) {\n\t\t\tcase RING_ACCURACY:\t//명중률에 비례한 확률과 데미지 배율로 강력한 일격을 날림. 영웅의 명중이 적 회피의 2배를 넘으면 100% 확률로 작동하며, 명중/회피*2(최소 1, 최대 2)의 데미지 배율이 적용된다.\n\t\t\t\tfloat heroAcc = hero.attackSkill(enemy);\n\t\t\t\tfloat enemyEva = enemy.defenseSkill(hero)*2; //적의 회피에 2배의 보정이 붙음\n\t\t\t\tif (Random.Float() < heroAcc/enemyEva) {\n\t\t\t\t\tdamageMulti = GameMath.gate(1, heroAcc/enemyEva, 2);\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t\t\t\tif (Random.Float() < 0.1f) {\n\t\t\t\t\t\tBuff.affect(enemy, Paralysis.class, 1f);\n\t\t\t\t\t}\n\t\t\t\t\tif (Random.Float() < 0.1f) {\n\t\t\t\t\t\tBuff.affect(enemy, Daze.class, 2f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn damageMulti;\n\t\t\tcase RING_ARCANA:\t//무작위 무기 마법 효과 발동. 무기의 레벨은 영웅 레벨/5(올림)으로 가정하여 성능을 계산한다.\n\t\t\t\tint level = (int)Math.ceil(hero.lvl / 5f);\n\t\t\t\tfloat powerMulti = Math.max(1f, RingOfArcana.enchantPowerMultiplier(hero));\n\t\t\t\tfloat procChance = 0;\n\t\t\t\tswitch (Random.Int(11)) {\n\t\t\t\t\tcase 0: default:\n\t\t\t\t\t\t//Blazing Effect\n\t\t\t\t\t\tprocChance = (level+1f)/(level+3f) * powerMulti;\n\t\t\t\t\t\tif (Random.Float() < procChance) {\n\t\t\t\t\t\t\tif (enemy.buff(Burning.class) != null){\n\t\t\t\t\t\t\t\tBuff.affect(enemy, Burning.class).reignite(enemy, 8f);\n\t\t\t\t\t\t\t\tint burnDamage = Random.NormalIntRange( 1, 3 + Dungeon.scalingDepth()/4 );\n\t\t\t\t\t\t\t\tenemy.damage( Math.round(burnDamage * 0.67f * powerMulti), hero );\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tBuff.affect(enemy, Burning.class).reignite(enemy, 8f);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tenemy.sprite.emitter().burst( FlameParticle.FACTORY, level + 1 );\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\t//Blocking Effect\n\t\t\t\t\t\tprocChance = (level+4f)/(level+40f) * powerMulti;\n\n\t\t\t\t\t\tif (Random.Float() < procChance){\n\t\t\t\t\t\t\tfloat powerLeft = Math.max(1f, procChance);\n\n\t\t\t\t\t\t\tBlocking.BlockBuff b = Buff.affect(hero, Blocking.BlockBuff.class);\n\t\t\t\t\t\t\tb.setShield(Math.round(powerLeft * (2 + level)));\n\t\t\t\t\t\t\thero.sprite.emitter().burst(Speck.factory(Speck.LIGHT), 5);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\t//Blooming Effect\n\t\t\t\t\t\tprocChance = (level+1f)/(level+3f) * powerMulti;\n\t\t\t\t\t\tif (Random.Float() < procChance) {\n\t\t\t\t\t\t\tfloat plants = (1f + 0.1f*level) * powerMulti;\n\t\t\t\t\t\t\tif (Random.Float() < plants%1){\n\t\t\t\t\t\t\t\tplants = (float)Math.ceil(plants);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tplants = (float)Math.floor(plants);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tBlooming blooming = new Blooming();\n\t\t\t\t\t\t\tif (blooming.plantGrass(enemy.pos)){\n\t\t\t\t\t\t\t\tplants--;\n\t\t\t\t\t\t\t\tif (plants <= 0){\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tArrayList<Integer> positions = new ArrayList<>();\n\t\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS8){\n\t\t\t\t\t\t\t\tif (enemy.pos + i != hero.pos) {\n\t\t\t\t\t\t\t\t\tpositions.add(enemy.pos + i);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tRandom.shuffle( positions );\n\n\t\t\t\t\t\t\t//The attacker's position is always lowest priority\n\t\t\t\t\t\t\tif (Dungeon.level.adjacent(hero.pos, enemy.pos)){\n\t\t\t\t\t\t\t\tpositions.add(hero.pos);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfor (int i : positions){\n\t\t\t\t\t\t\t\tif (blooming.plantGrass(i)){\n\t\t\t\t\t\t\t\t\tplants--;\n\t\t\t\t\t\t\t\t\tif (plants <= 0) {\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\t//Chilling Effect\n\t\t\t\t\t\tprocChance = (level+1f)/(level+4f) * powerMulti;\n\t\t\t\t\t\tif (Random.Float() < procChance) {\n\t\t\t\t\t\t\tfloat durationToAdd = 3f * powerMulti;\n\t\t\t\t\t\t\tChill existing = enemy.buff(Chill.class);\n\t\t\t\t\t\t\tif (existing != null){\n\t\t\t\t\t\t\t\tdurationToAdd = Math.min(durationToAdd, (6f*powerMulti)-existing.cooldown());\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tBuff.affect( enemy, Chill.class, durationToAdd );\n\t\t\t\t\t\t\tSplash.at( enemy.sprite.center(), 0xFFB2D6FF, 5);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 4:\n\t\t\t\t\t\t//Kinetic Effect, See RingOfForce.damageRoll too\n\t\t\t\t\t\tint conservedDamage = 0;\n\t\t\t\t\t\tif (hero.buff(Kinetic.ConservedDamage.class) != null) {\n\t\t\t\t\t\t\tconservedDamage = hero.buff(Kinetic.ConservedDamage.class).damageBonus();\n\t\t\t\t\t\t\thero.buff(Kinetic.ConservedDamage.class).detach();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tBuff.affect(hero, Kinetic.KineticTracker.class).conservedDamage = conservedDamage;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 5:\n\t\t\t\t\t\t//Corrupting Effect\n\t\t\t\t\t\tprocChance = (level+5f)/(level+25f) * powerMulti;\n\t\t\t\t\t\tif (damage >= enemy.HP\n\t\t\t\t\t\t\t\t&& Random.Float() < procChance\n\t\t\t\t\t\t\t\t&& !enemy.isImmune(Corruption.class)\n\t\t\t\t\t\t\t\t&& enemy.buff(Corruption.class) == null\n\t\t\t\t\t\t\t\t&& enemy instanceof Mob\n\t\t\t\t\t\t\t\t&& enemy.isAlive()){\n\t\t\t\t\t\t\tCorruption.corruptionHeal(enemy);\n\n\t\t\t\t\t\t\tAllyBuff.affectAndLoot((Mob)enemy, hero, Corruption.class);\n\n\t\t\t\t\t\t\tfloat powerLeft = Math.max(1f, procChance);\n\t\t\t\t\t\t\tif (powerLeft > 1.1f){\n\t\t\t\t\t\t\t\t//1 turn of adrenaline for each 20% above 100% proc rate\n\t\t\t\t\t\t\t\tBuff.affect(enemy, Adrenaline.class, Math.round(5*(powerLeft-1f)));\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 6:\n\t\t\t\t\t\t//Elastic Effect\n\t\t\t\t\t\tprocChance = (level+1f)/(level+5f) * powerMulti;\n\t\t\t\t\t\tif (Random.Float() < procChance) {\n\t\t\t\t\t\t\t//trace a ballistica to our target (which will also extend past them\n\t\t\t\t\t\t\tBallistica trajectory = new Ballistica(hero.pos, enemy.pos, Ballistica.STOP_TARGET);\n\t\t\t\t\t\t\t//trim it to just be the part that goes past them\n\t\t\t\t\t\t\ttrajectory = new Ballistica(trajectory.collisionPos, trajectory.path.get(trajectory.path.size()-1), Ballistica.PROJECTILE);\n\t\t\t\t\t\t\t//knock them back along that ballistica\n\t\t\t\t\t\t\tWandOfBlastWave.throwChar(enemy,\n\t\t\t\t\t\t\t\t\ttrajectory,\n\t\t\t\t\t\t\t\t\tMath.round(2 * powerMulti),\n\t\t\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\t\t\thero);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 7:\n\t\t\t\t\t\t//Grim Effect\n\t\t\t\t\t\tif (enemy.isImmune(Grim.class)) {\n\t\t\t\t\t\t\treturn damageMulti;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlevel = Math.max( 0, level );\n\t\t\t\t\t\t//scales from 0 - 50% based on how low hp the enemy is, plus 0-5% per level\n\t\t\t\t\t\tfloat maxChance = 0.5f + .05f*level;\n\t\t\t\t\t\tmaxChance *= powerMulti;\n\n\t\t\t\t\t\t//we defer logic using an actor here so we can know the true final damage\n\t\t\t\t\t\t//see Char.damage\n\t\t\t\t\t\tBuff.affect(enemy, Grim.GrimTracker.class).maxChance = maxChance;\n\n\t\t\t\t\t\tif (enemy.buff(Grim.GrimTracker.class) != null){\n\t\t\t\t\t\t\tenemy.buff(Grim.GrimTracker.class).qualifiesForBadge = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 8:\n\t\t\t\t\t\t//Lucky Effect\n\t\t\t\t\t\tprocChance = (level+4f)/(level+40f) * powerMulti;\n\t\t\t\t\t\tif (enemy.HP <= damage && Random.Float() < procChance){\n\n\t\t\t\t\t\t\tfloat powerLeft = Math.max(1f, procChance);\n\n\t\t\t\t\t\t\t//default is -5: 80% common, 20% uncommon, 0% rare\n\t\t\t\t\t\t\t//ring level increases by 1 for each 20% above 100% proc rate\n\t\t\t\t\t\t\tBuff.affect(enemy, Lucky.LuckProc.class).ringLevel = -10 + Math.round(5*powerLeft);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 9:\n\t\t\t\t\t\t//Shocking Effect\n\t\t\t\t\t\tprocChance = (level+1f)/(level+4f) * powerMulti;\n\t\t\t\t\t\tif (Random.Float() < procChance) {\n\t\t\t\t\t\t\tArrayList<Lightning.Arc> arcs = new ArrayList<>();\n\t\t\t\t\t\t\tArrayList<Char> affected = new ArrayList<>();\n\t\t\t\t\t\t\taffected.clear();\n\t\t\t\t\t\t\tarcs.clear();\n\n\t\t\t\t\t\t\tShocking.arc(hero, enemy, 2, affected, arcs);\n\n\t\t\t\t\t\t\taffected.remove(enemy); //defender isn't hurt by lightning\n\t\t\t\t\t\t\tfor (Char ch : affected) {\n\t\t\t\t\t\t\t\tif (ch.alignment != hero.alignment) {\n\t\t\t\t\t\t\t\t\tch.damage(Math.round(damage * 0.4f * powerMulti), hero);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 10:\n\t\t\t\t\t\t//Vampiric Effect\n\t\t\t\t\t\tfloat missingPercent = (hero.HT - hero.HP) / (float)hero.HT;\n\t\t\t\t\t\tfloat healChance = 0.05f + .25f*missingPercent;\n\n\t\t\t\t\t\thealChance *= powerMulti;\n\n\t\t\t\t\t\tif (Random.Float() < healChance){\n\n\t\t\t\t\t\t\tfloat powerLeft = Math.max(1f, healChance);\n\n\t\t\t\t\t\t\t//heals for 50% of damage dealt\n\t\t\t\t\t\t\tint healAmt = Math.round(damage * 0.5f * powerLeft);\n\t\t\t\t\t\t\thero.heal(healAmt);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n//\t\t\t\t\tcase 11:\n//\t\t\t\t\t\t//Shiny Effect\n//\t\t\t\t\t\tBuff.prolong( enemy, Blindness.class, Random.Float( 1f, (1f + level) * RingOfArcana.enchantPowerMultiplier(hero) ) );\n//\t\t\t\t\t\tBuff.prolong( enemy, Cripple.class, Random.Float( 1f, (1f + level/2f) * RingOfArcana.enchantPowerMultiplier(hero) ) );\n//\t\t\t\t\t\tenemy.sprite.emitter().burst(Speck.factory(Speck.LIGHT), 6 );\n//\t\t\t\t\t\tbreak;\n//\t\t\t\t\tcase 12:\n//\t\t\t\t\t\t//Eldritch Effect\n//\t\t\t\t\t\tBuff.prolong( enemy, Terror.class, 10f*powerMulti + 5f ).object = hero.id();\n//\t\t\t\t\t\tbreak;\n//\t\t\t\t\tcase 13:\n//\t\t\t\t\t\t//Stunning Effect\n//\t\t\t\t\t\tBuff.prolong( enemy, Paralysis.class, 1f * powerMulti );\n//\t\t\t\t\t\tenemy.sprite.emitter().burst(Speck.factory(Speck.LIGHT), 12 );\n//\t\t\t\t\t\tbreak;\n//\t\t\t\t\tcase 14:\n//\t\t\t\t\t\t//Venomous Effect\n//\t\t\t\t\t\tBuff.affect( enemy, Poison.class ).extend( ((int)(level/2) + 1) * powerMulti );\n//\t\t\t\t\t\tCellEmitter.center(enemy.pos).burst( PoisonParticle.SPLASH, 5 );\n//\t\t\t\t\t\tbreak;\n//\t\t\t\t\tcase 15:\n//\t\t\t\t\t\t//Vorpal Effect\n//\t\t\t\t\t\tBuff.affect(enemy, Bleeding.class).set((damage/10f) * powerMulti);\n//\t\t\t\t\t\tSplash.at( enemy.sprite.center(), -PointF.PI / 2, PointF.PI / 6, enemy.sprite.blood(), 10 );\n//\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\treturn damageMulti;\n\t\t\tcase RING_ELEMENTS:\t//20% 확률로 가진 디버프 전부 제거\n\t\t\t\tif (Random.Float() < 0.2f) {\n\t\t\t\t\tfor (Buff buff : hero.buffs()) {\n\t\t\t\t\t\tif (buff.type == Buff.buffType.NEGATIVE){\n\t\t\t\t\t\t\tbuff.detach();\n\t\t\t\t\t\t}\n\t\t\t\t\t\thero.sprite.emitter().burst(Speck.factory(Speck.LIGHT), 12 );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn damageMulti;\n\t\t\tcase RING_ENERGY:\t//25% 확률로 0.5턴의 유물 충전 효과를 얻음\n\t\t\t\tif (Random.Float() < 0.25f) {\n\t\t\t\t\tfor (Buff b : hero.buffs()){\n\t\t\t\t\t\tif (b instanceof Artifact.ArtifactBuff && !((Artifact.ArtifactBuff) b).isCursed() ) {\n\t\t\t\t\t\t\t((Artifact.ArtifactBuff) b).charge(hero, 0.5f);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tScrollOfRecharging.charge(hero);\n\t\t\t\t}\n\t\t\t\treturn damageMulti;\n\t\t\tcase RING_EVASION:\t//회피율에 비례한 확률로 1턴의 회피 기동을 얻음. 영웅의 회피가 적 명중의 4배를 넘으면 100% 확률로 작동한다.\n\t\t\t\tfloat enemyAcc = enemy.attackSkill(hero)*4;\t//적의 명중률에 4배의 보정이 붙음\n\t\t\t\tint heroEva = hero.defenseSkill(enemy);\n\t\t\t\tif (Random.Float() < heroEva/enemyAcc) {\n\t\t\t\t\tBuff.prolong(hero, EvasiveMove.class, 1.0001f);\n\t\t\t\t}\n\t\t\t\treturn damageMulti;\n\t\t\tcase RING_FORCE:\t//25% 확률로 마비 1턴, 멍해짐, 불구, 현기증, 약화 3턴 중 하나를 걸음\n\t\t\t\tswitch (Random.Int(20)) {\n\t\t\t\t\tcase 0:\n\t\t\t\t\t\tBuff.affect(enemy, Paralysis.class, 1f);\n\t\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tBuff.affect(enemy, Daze.class, 3f);\n\t\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\tBuff.affect(enemy, Cripple.class, 3f);\n\t\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\tBuff.affect(enemy, Vertigo.class, 3f);\n\t\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 4:\n\t\t\t\t\t\tBuff.affect(enemy, Weakness.class, 3f);\n\t\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\treturn damageMulti;\n\t\t\tcase RING_FUROR:\t//20% 확률로 공격에 턴 소모 X\n\t\t\t\tif (Random.Float() < 0.2f) {\n\t\t\t\t\thero.spend(-hero.attackDelay());\t//공격에 소모하는 턴 X\n\t\t\t\t}\n\t\t\t\treturn damageMulti;\n\t\t\tcase RING_HASTE:\t//20% 확률로 2턴의 신속을 얻음\n\t\t\t\tif (Random.Float() < 0.2f) {\n\t\t\t\t\tBuff.affect(hero, Haste.class, 2f);\n\t\t\t\t}\n\t\t\t\treturn damageMulti;\n\t\t\tcase RING_MIGHT:\t//공격력 (현재 힘-10)*5%배\n\t\t\t\treturn damageMulti*(1+0.05f*(hero.STR()-10));\n\t\t\tcase RING_SHARPSHOOTING:\t//대상에게 박힌 투척 무기 중 하나를 가져오고 내구도를 1만큼 수리함\n\t\t\t\tif (enemy.buff(PinCushion.class) != null) {\n\t\t\t\t\tItem item = enemy.buff(PinCushion.class).grabOne();\n\t\t\t\t\tif (item instanceof MissileWeapon) {\n\t\t\t\t\t\t((MissileWeapon) item).repair(1);\n\t\t\t\t\t}\n\t\t\t\t\tif (item.doPickUp(hero, enemy.pos)) {\n\t\t\t\t\t\thero.spend(-Item.TIME_TO_PICK_UP); //casting the spell already takes a turn\n\t\t\t\t\t\tGLog.i( Messages.capitalize(Messages.get(hero, \"you_now_have\", item.name())) );\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGLog.w(Messages.get(TelekineticGrab.class, \"cant_grab\"));\n\t\t\t\t\t\tDungeon.level.drop(item, enemy.pos).sprite.drop();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn damageMulti;\n\t\t\tcase RING_TENACITY: //이번 턴에 체력이 1밑으로 내려가지 않음\n\t\t\t\tBuff.prolong(hero, Enduring.class, 1.0001f);\n\t\t\t\treturn damageMulti;\n\t\t\tcase RING_WEALTH:\t//1%*(드랍 확률 증가 효과) 확률로 무작위 흔한 등급 보상이 떨어짐\n\t\t\t\tif (Random.Float() < 0.01f*RingOfWealth.dropChanceMultiplier(hero)) {\n\t\t\t\t\tItem prize = RingOfWealth.genConsumableDrop(-10);\n\t\t\t\t\tDungeon.level.drop(prize, enemy.pos).sprite.drop();\n\t\t\t\t\tRingOfWealth.showFlareForBonusDrop(enemy.sprite);\n\t\t\t\t}\n\t\t\t\treturn damageMulti;\n\t\t}\n\n\t\treturn damageMulti;\n\t}\n\n\n\tpublic class RingBuff extends Buff {\n\n\t\t@Override\n\t\tpublic boolean attachTo( Char target ) {\n\t\t\tif (super.attachTo( target )) {\n\t\t\t\t//if we're loading in and the hero has partially spent a turn, delay for 1 turn\n\t\t\t\tif (target instanceof Hero && Dungeon.hero == null && cooldown() == 0 && target.cooldown() > 0) {\n\t\t\t\t\tspend(TICK);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean act() {\n\t\t\tspend( TICK );\n\t\t\treturn true;\n\t\t}\n\n\t\tpublic int level(){\n\t\t\treturn Ring.this.soloBonus();\n\t\t}\n\n\t\tpublic int buffedLvl(){\n\t\t\treturn Ring.this.soloBuffedBonus();\n\t\t}\n\n\t}\n}" }, { "identifier": "Scroll", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/scrolls/Scroll.java", "snippet": "public abstract class Scroll extends Item {\n\t\n\tpublic static final String AC_READ\t= \"READ\";\n\t\n\tprotected static final float TIME_TO_READ\t= 1f;\n\n\tprivate static final LinkedHashMap<String, Integer> runes = new LinkedHashMap<String, Integer>() {\n\t\t{\n\t\t\tput(\"KAUNAN\",ItemSpriteSheet.SCROLL_KAUNAN);\n\t\t\tput(\"SOWILO\",ItemSpriteSheet.SCROLL_SOWILO);\n\t\t\tput(\"LAGUZ\",ItemSpriteSheet.SCROLL_LAGUZ);\n\t\t\tput(\"YNGVI\",ItemSpriteSheet.SCROLL_YNGVI);\n\t\t\tput(\"GYFU\",ItemSpriteSheet.SCROLL_GYFU);\n\t\t\tput(\"RAIDO\",ItemSpriteSheet.SCROLL_RAIDO);\n\t\t\tput(\"ISAZ\",ItemSpriteSheet.SCROLL_ISAZ);\n\t\t\tput(\"MANNAZ\",ItemSpriteSheet.SCROLL_MANNAZ);\n\t\t\tput(\"NAUDIZ\",ItemSpriteSheet.SCROLL_NAUDIZ);\n\t\t\tput(\"BERKANAN\",ItemSpriteSheet.SCROLL_BERKANAN);\n\t\t\tput(\"ODAL\",ItemSpriteSheet.SCROLL_ODAL);\n\t\t\tput(\"TIWAZ\",ItemSpriteSheet.SCROLL_TIWAZ);\n\t\t}\n\t};\n\t\n\tprotected static ItemStatusHandler<Scroll> handler;\n\t\n\tprotected String rune;\n\n\t//affects how strongly on-scroll talents trigger from this scroll\n\tprotected float talentFactor = 1;\n\t\n\t{\n\t\tstackable = true;\n\t\tdefaultAction = AC_READ;\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static void initLabels() {\n\t\thandler = new ItemStatusHandler<>( (Class<? extends Scroll>[])Generator.Category.SCROLL.classes, runes );\n\t}\n\t\n\tpublic static void save( Bundle bundle ) {\n\t\thandler.save( bundle );\n\t}\n\n\tpublic static void saveSelectively( Bundle bundle, ArrayList<Item> items ) {\n\t\tArrayList<Class<?extends Item>> classes = new ArrayList<>();\n\t\tfor (Item i : items){\n\t\t\tif (i instanceof ExoticScroll){\n\t\t\t\tif (!classes.contains(ExoticScroll.exoToReg.get(i.getClass()))){\n\t\t\t\t\tclasses.add(ExoticScroll.exoToReg.get(i.getClass()));\n\t\t\t\t}\n\t\t\t} else if (i instanceof Scroll){\n\t\t\t\tif (!classes.contains(i.getClass())){\n\t\t\t\t\tclasses.add(i.getClass());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\thandler.saveClassesSelectively( bundle, classes );\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static void restore( Bundle bundle ) {\n\t\thandler = new ItemStatusHandler<>( (Class<? extends Scroll>[])Generator.Category.SCROLL.classes, runes, bundle );\n\t}\n\t\n\tpublic Scroll() {\n\t\tsuper();\n\t\treset();\n\t}\n\t\n\t//anonymous scrolls are always IDed, do not affect ID status,\n\t//and their sprite is replaced by a placeholder if they are not known,\n\t//useful for items that appear in UIs, or which are only spawned for their effects\n\tprotected boolean anonymous = false;\n\tpublic void anonymize(){\n\t\tif (!isKnown()) image = ItemSpriteSheet.SCROLL_HOLDER;\n\t\tanonymous = true;\n\t}\n\t\n\t\n\t@Override\n\tpublic void reset(){\n\t\tsuper.reset();\n\t\tif (handler != null && handler.contains(this)) {\n\t\t\timage = handler.image(this);\n\t\t\trune = handler.label(this);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic ArrayList<String> actions( Hero hero ) {\n\t\tArrayList<String> actions = super.actions( hero );\n\t\tactions.add( AC_READ );\n\t\treturn actions;\n\t}\n\t\n\t@Override\n\tpublic void execute( Hero hero, String action ) {\n\n\t\tsuper.execute( hero, action );\n\n\t\tif (action.equals( AC_READ )) {\n\t\t\t\n\t\t\tif (hero.buff(MagicImmune.class) != null){\n\t\t\t\tGLog.w( Messages.get(this, \"no_magic\") );\n\t\t\t} else if (hero.buff( Blindness.class ) != null) {\n\t\t\t\tGLog.w( Messages.get(this, \"blinded\") );\n\t\t\t} else if (hero.buff(UnstableSpellbook.bookRecharge.class) != null\n\t\t\t\t\t&& hero.buff(UnstableSpellbook.bookRecharge.class).isCursed()\n\t\t\t\t\t&& !(this instanceof ScrollOfRemoveCurse || this instanceof ScrollOfAntiMagic)){\n\t\t\t\tGLog.n( Messages.get(this, \"cursed\") );\n\t\t\t} else {\n\t\t\t\tdoRead();\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\t\n\tpublic abstract void doRead();\n\n\tprotected void readAnimation() {\n\t\tInvisibility.dispel();\n\t\tcurUser.spend( TIME_TO_READ );\n\t\tcurUser.busy();\n\t\t((HeroSprite)curUser.sprite).read();\n\n\t\tif (!anonymous) {\n\t\t\tTalent.onScrollUsed(curUser, curUser.pos, talentFactor);\n\t\t}\n\n\t}\n\t\n\tpublic boolean isKnown() {\n\t\treturn anonymous || (handler != null && handler.isKnown( this ));\n\t}\n\t\n\tpublic void setKnown() {\n\t\tif (!anonymous) {\n\t\t\tif (!isKnown()) {\n\t\t\t\thandler.know(this);\n\t\t\t\tupdateQuickslot();\n\t\t\t}\n\t\t\t\n\t\t\tif (Dungeon.hero.isAlive()) {\n\t\t\t\tCatalog.setSeen(getClass());\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic Item identify( boolean byHero ) {\n\t\tsuper.identify(byHero);\n\n\t\tif (!isKnown()) {\n\t\t\tsetKnown();\n\t\t}\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic String name() {\n\t\treturn isKnown() ? super.name() : Messages.get(this, rune);\n\t}\n\t\n\t@Override\n\tpublic String info() {\n\t\treturn isKnown() ?\n\t\t\tdesc() :\n\t\t\tMessages.get(this, \"unknown_desc\");\n\t}\n\t\n\t@Override\n\tpublic boolean isUpgradable() {\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic boolean isIdentified() {\n\t\treturn isKnown();\n\t}\n\t\n\tpublic static HashSet<Class<? extends Scroll>> getKnown() {\n\t\treturn handler.known();\n\t}\n\t\n\tpublic static HashSet<Class<? extends Scroll>> getUnknown() {\n\t\treturn handler.unknown();\n\t}\n\t\n\tpublic static boolean allKnown() {\n\t\treturn handler.known().size() == Generator.Category.SCROLL.classes.length;\n\t}\n\t\n\t@Override\n\tpublic int value() {\n\t\treturn 30 * quantity;\n\t}\n\n\t@Override\n\tpublic int energyVal() {\n\t\treturn 6 * quantity;\n\t}\n\t\n\tpublic static class PlaceHolder extends Scroll {\n\t\t\n\t\t{\n\t\t\timage = ItemSpriteSheet.SCROLL_HOLDER;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean isSimilar(Item item) {\n\t\t\treturn ExoticScroll.regToExo.containsKey(item.getClass())\n\t\t\t\t\t|| ExoticScroll.regToExo.containsValue(item.getClass());\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void doRead() {}\n\t\t\n\t\t@Override\n\t\tpublic String info() {\n\t\t\treturn \"\";\n\t\t}\n\t}\n\t\n\tpublic static class ScrollToStone extends Recipe {\n\t\t\n\t\tprivate static HashMap<Class<?extends Scroll>, Class<?extends Runestone>> stones = new HashMap<>();\n\t\tstatic {\n\t\t\tstones.put(ScrollOfIdentify.class, StoneOfIntuition.class);\n\t\t\tstones.put(ScrollOfLullaby.class, StoneOfDeepSleep.class);\n\t\t\tstones.put(ScrollOfMagicMapping.class, StoneOfClairvoyance.class);\n\t\t\tstones.put(ScrollOfMirrorImage.class, StoneOfFlock.class);\n\t\t\tstones.put(ScrollOfRetribution.class, StoneOfBlast.class);\n\t\t\tstones.put(ScrollOfRage.class, StoneOfAggression.class);\n\t\t\tstones.put(ScrollOfRecharging.class, StoneOfShock.class);\n\t\t\tstones.put(ScrollOfRemoveCurse.class, StoneOfDisarming.class);\n\t\t\tstones.put(ScrollOfTeleportation.class, StoneOfBlink.class);\n\t\t\tstones.put(ScrollOfTerror.class, StoneOfFear.class);\n\t\t\tstones.put(ScrollOfTransmutation.class, StoneOfAugmentation.class);\n\t\t\tstones.put(ScrollOfUpgrade.class, StoneOfEnchantment.class);\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean testIngredients(ArrayList<Item> ingredients) {\n\t\t\tif (ingredients.size() != 1\n\t\t\t\t\t|| !(ingredients.get(0) instanceof Scroll)\n\t\t\t\t\t|| !stones.containsKey(ingredients.get(0).getClass())){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic int cost(ArrayList<Item> ingredients) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic Item brew(ArrayList<Item> ingredients) {\n\t\t\tif (!testIngredients(ingredients)) return null;\n\t\t\t\n\t\t\tScroll s = (Scroll) ingredients.get(0);\n\t\t\t\n\t\t\ts.quantity(s.quantity() - 1);\n\t\t\ts.identify();\n\t\t\t\n\t\t\treturn Reflection.newInstance(stones.get(s.getClass())).quantity(2);\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic Item sampleOutput(ArrayList<Item> ingredients) {\n\t\t\tif (!testIngredients(ingredients)) return null;\n\t\t\t\n\t\t\tScroll s = (Scroll) ingredients.get(0);\n\n\t\t\tif (!s.isKnown()){\n\t\t\t\treturn new Runestone.PlaceHolder().quantity(2);\n\t\t\t} else {\n\t\t\t\treturn Reflection.newInstance(stones.get(s.getClass())).quantity(2);\n\t\t\t}\n\t\t}\n\t}\n}" }, { "identifier": "Notes", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/journal/Notes.java", "snippet": "public class Notes {\n\t\n\tpublic static abstract class Record implements Comparable<Record>, Bundlable {\n\n\t\t//TODO currently notes can only relate to branch = 0, add branch support here if that changes\n\t\tprotected int depth;\n\n\t\tpublic int depth(){\n\t\t\treturn depth;\n\t\t}\n\t\t\n\t\tpublic abstract String desc();\n\t\t\n\t\t@Override\n\t\tpublic abstract boolean equals(Object obj);\n\t\t\n\t\t@Override\n\t\tpublic int compareTo( Record another ) {\n\t\t\treturn another.depth() - depth();\n\t\t}\n\t\t\n\t\tprivate static final String DEPTH\t= \"depth\";\n\t\t\n\t\t@Override\n\t\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\t\tdepth = bundle.getInt( DEPTH );\n\t\t}\n\n\t\t@Override\n\t\tpublic void storeInBundle( Bundle bundle ) {\n\t\t\tbundle.put( DEPTH, depth );\n\t\t}\n\t}\n\t\n\tpublic enum Landmark {\n\t\tWELL_OF_HEALTH,\n\t\tWELL_OF_AWARENESS,\n\t\tALCHEMY,\n\t\tGARDEN,\n\t\tSTATUE,\n\t\tSACRIFICIAL_FIRE,\n\t\tSHOP,\n\t\t\n\t\tGHOST,\n\t\tWANDMAKER,\n\t\tTROLL,\n\t\tIMP,\n\n\t\tDEMON_SPAWNER;\n\t\t\n\t\tpublic String desc() {\n\t\t\treturn Messages.get(this, name());\n\t\t}\n\t}\n\t\n\tpublic static class LandmarkRecord extends Record {\n\t\t\n\t\tprotected Landmark landmark;\n\t\t\n\t\tpublic LandmarkRecord() {}\n\t\t\n\t\tpublic LandmarkRecord(Landmark landmark, int depth ) {\n\t\t\tthis.landmark = landmark;\n\t\t\tthis.depth = depth;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String desc() {\n\t\t\treturn landmark.desc();\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\treturn (obj instanceof LandmarkRecord)\n\t\t\t\t\t&& landmark == ((LandmarkRecord) obj).landmark\n\t\t\t\t\t&& depth() == ((LandmarkRecord) obj).depth();\n\t\t}\n\t\t\n\t\tprivate static final String LANDMARK\t= \"landmark\";\n\t\t\n\t\t@Override\n\t\tpublic void restoreFromBundle(Bundle bundle) {\n\t\t\tsuper.restoreFromBundle(bundle);\n\t\t\tlandmark = Landmark.valueOf(bundle.getString(LANDMARK));\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void storeInBundle(Bundle bundle) {\n\t\t\tsuper.storeInBundle(bundle);\n\t\t\tbundle.put( LANDMARK, landmark.name() );\n\t\t}\n\t}\n\t\n\tpublic static class KeyRecord extends Record {\n\t\t\n\t\tprotected Key key;\n\t\t\n\t\tpublic KeyRecord() {}\n\t\t\n\t\tpublic KeyRecord( Key key ){\n\t\t\tthis.key = key;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic int depth() {\n\t\t\treturn key.depth;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String desc() {\n\t\t\treturn key.title();\n\t\t}\n\t\t\n\t\tpublic Class<? extends Key> type(){\n\t\t\treturn key.getClass();\n\t\t}\n\t\t\n\t\tpublic int quantity(){\n\t\t\treturn key.quantity();\n\t\t}\n\t\t\n\t\tpublic void quantity(int num){\n\t\t\tkey.quantity(num);\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\treturn (obj instanceof KeyRecord)\n\t\t\t\t\t&& key.isSimilar(((KeyRecord) obj).key);\n\t\t}\n\t\t\n\t\tprivate static final String KEY\t= \"key\";\n\t\t\n\t\t@Override\n\t\tpublic void restoreFromBundle(Bundle bundle) {\n\t\t\tsuper.restoreFromBundle(bundle);\n\t\t\tkey = (Key) bundle.get(KEY);\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void storeInBundle(Bundle bundle) {\n\t\t\tsuper.storeInBundle(bundle);\n\t\t\tbundle.put( KEY, key );\n\t\t}\n\t}\n\t\n\tprivate static ArrayList<Record> records;\n\t\n\tpublic static void reset() {\n\t\trecords = new ArrayList<>();\n\t}\n\t\n\tprivate static final String RECORDS\t= \"records\";\n\t\n\tpublic static void storeInBundle( Bundle bundle ) {\n\t\tbundle.put( RECORDS, records );\n\t}\n\t\n\tpublic static void restoreFromBundle( Bundle bundle ) {\n\t\trecords = new ArrayList<>();\n\t\tfor (Bundlable rec : bundle.getCollection( RECORDS ) ) {\n\t\t\trecords.add( (Record) rec );\n\t\t}\n\t}\n\t\n\tpublic static boolean add( Landmark landmark ) {\n\t\tLandmarkRecord l = new LandmarkRecord( landmark, Dungeon.depth );\n\t\tif (!records.contains(l)) {\n\t\t\tboolean result = records.add(new LandmarkRecord(landmark, Dungeon.depth));\n\t\t\tCollections.sort(records);\n\t\t\treturn result;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic static boolean remove( Landmark landmark ) {\n\t\treturn records.remove( new LandmarkRecord(landmark, Dungeon.depth) );\n\t}\n\t\n\tpublic static boolean add( Key key ){\n\t\tKeyRecord k = new KeyRecord(key);\n\t\tif (!records.contains(k)){\n\t\t\tboolean result = records.add(k);\n\t\t\tCollections.sort(records);\n\t\t\treturn result;\n\t\t} else {\n\t\t\tk = (KeyRecord) records.get(records.indexOf(k));\n\t\t\tk.quantity(k.quantity() + key.quantity());\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\tpublic static boolean remove( Key key ){\n\t\tKeyRecord k = new KeyRecord( key );\n\t\tif (records.contains(k)){\n\t\t\tk = (KeyRecord) records.get(records.indexOf(k));\n\t\t\tk.quantity(k.quantity() - key.quantity());\n\t\t\tif (k.quantity() <= 0){\n\t\t\t\trecords.remove(k);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic static int keyCount( Key key ){\n\t\tKeyRecord k = new KeyRecord( key );\n\t\tif (records.contains(k)){\n\t\t\tk = (KeyRecord) records.get(records.indexOf(k));\n\t\t\treturn k.quantity();\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tpublic static ArrayList<Record> getRecords(){\n\t\treturn getRecords(Record.class);\n\t}\n\t\n\tpublic static <T extends Record> ArrayList<T> getRecords( Class<T> recordType ){\n\t\tArrayList<T> filtered = new ArrayList<>();\n\t\tfor (Record rec : records){\n\t\t\tif (recordType.isInstance(rec)){\n\t\t\t\tfiltered.add((T)rec);\n\t\t\t}\n\t\t}\n\t\treturn filtered;\n\t}\n\t\n\tpublic static void remove( Record rec ){\n\t\trecords.remove(rec);\n\t}\n\t\n}" }, { "identifier": "Messages", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/messages/Messages.java", "snippet": "public class Messages {\n\n\tprivate static ArrayList<I18NBundle> bundles;\n\tprivate static Languages lang;\n\tprivate static Locale locale;\n\n\tpublic static final String NO_TEXT_FOUND = \"!!!NO TEXT FOUND!!!\";\n\n\tpublic static Languages lang(){\n\t\treturn lang;\n\t}\n\n\tpublic static Locale locale(){\n\t\treturn locale;\n\t}\n\n\t/**\n\t * Setup Methods\n\t */\n\n\tprivate static String[] prop_files = new String[]{\n\t\t\tAssets.Messages.ACTORS,\n\t\t\tAssets.Messages.ITEMS,\n\t\t\tAssets.Messages.JOURNAL,\n\t\t\tAssets.Messages.LEVELS,\n\t\t\tAssets.Messages.MISC,\n\t\t\tAssets.Messages.PLANTS,\n\t\t\tAssets.Messages.SCENES,\n\t\t\tAssets.Messages.UI,\n\t\t\tAssets.Messages.WINDOWS\n\t};\n\n\tstatic{\n\t\tsetup(SPDSettings.language());\n\t}\n\n\tpublic static void setup( Languages lang ){\n\t\t//seeing as missing keys are part of our process, this is faster than throwing an exception\n\t\tI18NBundle.setExceptionOnMissingKey(false);\n\n\t\t//store language and locale info for various string logic\n\t\tMessages.lang = lang;\n\t\tif (lang == Languages.ENGLISH){\n\t\t\tlocale = Locale.ENGLISH;\n\t\t} else {\n\t\t\tlocale = new Locale(lang.code());\n\t\t}\n\n\t\t//strictly match the language code when fetching bundles however\n\t\tbundles = new ArrayList<>();\n\t\tLocale bundleLocal = new Locale(lang.code());\n\t\tfor (String file : prop_files) {\n\t\t\tbundles.add(I18NBundle.createBundle(Gdx.files.internal(file), bundleLocal));\n\t\t}\n\t}\n\n\n\n\t/**\n\t * Resource grabbing methods\n\t */\n\n\tpublic static String get(String key, Object...args){\n\t\treturn get(null, key, args);\n\t}\n\n\tpublic static String get(Object o, String k, Object...args){\n\t\treturn get(o.getClass(), k, args);\n\t}\n\n\tpublic static String get(Class c, String k, Object...args){\n\t\tString key;\n\t\tif (c != null){\n\t\t\tkey = c.getName().replace(\"com.shatteredpixel.shatteredpixeldungeon.\", \"\");\n\t\t\tkey += \".\" + k;\n\t\t} else\n\t\t\tkey = k;\n\n\t\tString value = getFromBundle(key.toLowerCase(Locale.ENGLISH));\n\t\tif (value != null){\n\t\t\tif (args.length > 0) return format(value, args);\n\t\t\telse return value;\n\t\t} else {\n\t\t\t//this is so child classes can inherit properties from their parents.\n\t\t\t//in cases where text is commonly grabbed as a utility from classes that aren't mean to be instantiated\n\t\t\t//(e.g. flavourbuff.dispTurns()) using .class directly is probably smarter to prevent unnecessary recursive calls.\n\t\t\tif (c != null && c.getSuperclass() != null){\n\t\t\t\treturn get(c.getSuperclass(), k, args);\n\t\t\t} else {\n\t\t\t\treturn NO_TEXT_FOUND;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static String getFromBundle(String key){\n\t\tString result;\n\t\tfor (I18NBundle b : bundles){\n\t\t\tresult = b.get(key);\n\t\t\t//if it isn't the return string for no key found, return it\n\t\t\tif (result.length() != key.length()+6 || !result.contains(key)){\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\n\n\t/**\n\t * String Utility Methods\n\t */\n\n\tpublic static String format( String format, Object...args ) {\n\t\ttry {\n\t\t\treturn String.format(Locale.ENGLISH, format, args);\n\t\t} catch (IllegalFormatException e) {\n\t\t\tShatteredPixelDungeon.reportException( new Exception(\"formatting error for the string: \" + format, e) );\n\t\t\treturn format;\n\t\t}\n\t}\n\n\tprivate static HashMap<String, DecimalFormat> formatters = new HashMap<>();\n\n\tpublic static String decimalFormat( String format, double number ){\n\t\tif (!formatters.containsKey(format)){\n\t\t\tformatters.put(format, new DecimalFormat(format, DecimalFormatSymbols.getInstance(Locale.ENGLISH)));\n\t\t}\n\t\treturn formatters.get(format).format(number);\n\t}\n\n\tpublic static String capitalize( String str ){\n\t\tif (str.length() == 0) return str;\n\t\telse return str.substring( 0, 1 ).toUpperCase(locale) + str.substring( 1 );\n\t}\n\n\t//Words which should not be capitalized in title case, mostly prepositions which appear ingame\n\t//This list is not comprehensive!\n\tprivate static final HashSet<String> noCaps = new HashSet<>(\n\t\t\tArrays.asList(\"a\", \"an\", \"and\", \"of\", \"by\", \"to\", \"the\", \"x\", \"for\")\n\t);\n\n\tpublic static String titleCase( String str ){\n\t\t//English capitalizes every word except for a few exceptions\n\t\tif (lang == Languages.ENGLISH){\n\t\t\tString result = \"\";\n\t\t\t//split by any unicode space character\n\t\t\tfor (String word : str.split(\"(?<=\\\\p{Zs})\")){\n\t\t\t\tif (noCaps.contains(word.trim().toLowerCase(Locale.ENGLISH).replaceAll(\":|[0-9]\", \"\"))){\n\t\t\t\t\tresult += word;\n\t\t\t\t} else {\n\t\t\t\t\tresult += capitalize(word);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//first character is always capitalized.\n\t\t\treturn capitalize(result);\n\t\t}\n\n\t\t//Otherwise, use sentence case\n\t\treturn capitalize(str);\n\t}\n\n\tpublic static String upperCase( String str ){\n\t\treturn str.toUpperCase(locale);\n\t}\n\n\tpublic static String lowerCase( String str ){\n\t\treturn str.toLowerCase(locale);\n\t}\n}" }, { "identifier": "QuickSlotButton", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/ui/QuickSlotButton.java", "snippet": "public class QuickSlotButton extends Button {\n\t\n\tprivate static QuickSlotButton[] instance = new QuickSlotButton[QuickSlot.SIZE];\n\tprivate int slotNum;\n\n\tprivate ItemSlot slot;\n\t\n\tprivate Image crossB;\n\tprivate Image crossM;\n\t\n\tpublic static int targetingSlot = -1;\n\tpublic static Char lastTarget = null;\n\t\n\tpublic QuickSlotButton( int slotNum ) {\n\t\tsuper();\n\t\tthis.slotNum = slotNum;\n\t\titem( select( slotNum ) );\n\t\t\n\t\tinstance[slotNum] = this;\n\t}\n\t\n\t@Override\n\tpublic void destroy() {\n\t\tsuper.destroy();\n\t\t\n\t\treset();\n\t}\n\n\tpublic static void reset() {\n\t\tinstance = new QuickSlotButton[QuickSlot.SIZE];\n\n\t\tlastTarget = null;\n\t}\n\t\n\t@Override\n\tprotected void createChildren() {\n\t\tsuper.createChildren();\n\t\t\n\t\tslot = new ItemSlot() {\n\t\t\t@Override\n\t\t\tprotected void onClick() {\n\t\t\t\tif (!Dungeon.hero.isAlive() || !Dungeon.hero.ready){\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (targetingSlot == slotNum) {\n\t\t\t\t\tint cell = autoAim(lastTarget, select(slotNum));\n\n\t\t\t\t\tif (cell != -1){\n\t\t\t\t\t\tGameScene.handleCell(cell);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//couldn't auto-aim, just target the position and hope for the best.\n\t\t\t\t\t\tGameScene.handleCell( lastTarget.pos );\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tItem item = select(slotNum);\n\t\t\t\t\tif (Dungeon.hero.belongings.contains(item) && !GameScene.cancel()) {\n\t\t\t\t\t\tGameScene.centerNextWndOnInvPane();\n\t\t\t\t\t\titem.execute(Dungeon.hero);\n\t\t\t\t\t\tif (item.usesTargeting) {\n\t\t\t\t\t\t\tuseTargeting();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected void onRightClick() {\n\t\t\t\tQuickSlotButton.this.onLongClick();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected void onMiddleClick() {\n\t\t\t\tonClick();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic GameAction keyAction() {\n\t\t\t\treturn QuickSlotButton.this.keyAction();\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic GameAction secondaryTooltipAction(){\n\t\t\t\treturn QuickSlotButton.this.secondaryTooltipAction();\n\t\t\t}\n\t\t\t@Override\n\t\t\tprotected boolean onLongClick() {\n\t\t\t\treturn QuickSlotButton.this.onLongClick();\n\t\t\t}\n\t\t\t@Override\n\t\t\tprotected void onPointerDown() {\n\t\t\t\tsprite.lightness( 0.7f );\n\t\t\t}\n\t\t\t@Override\n\t\t\tprotected void onPointerUp() {\n\t\t\t\tsprite.resetColor();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String hoverText() {\n\t\t\t\tif (item == null){\n\t\t\t\t\treturn Messages.titleCase(Messages.get(WndKeyBindings.class, \"quickslot_\" + (slotNum+1)));\n\t\t\t\t} else {\n\t\t\t\t\treturn super.hoverText();\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tslot.showExtraInfo( false );\n\t\tadd( slot );\n\t\t\n\t\tcrossB = Icons.TARGET.get();\n\t\tcrossB.visible = false;\n\t\tadd( crossB );\n\t\t\n\t\tcrossM = new Image();\n\t\tcrossM.copy( crossB );\n\t}\n\t\n\t@Override\n\tprotected void layout() {\n\t\tsuper.layout();\n\t\t\n\t\tslot.fill( this );\n\t\t\n\t\tcrossB.x = x + (width - crossB.width) / 2;\n\t\tcrossB.y = y + (height - crossB.height) / 2;\n\t\tPixelScene.align(crossB);\n\t}\n\n\tpublic void alpha( float value ){\n\t\tslot.alpha(value);\n\t}\n\n\t@Override\n\tpublic void update() {\n\t\tsuper.update();\n\t\tif (targetingSlot != -1 && lastTarget != null && lastTarget.sprite != null){\n\t\t\tcrossM.point(lastTarget.sprite.center(crossM));\n\t\t}\n\t}\n\n\t@Override\n\tpublic GameAction keyAction() {\n\t\tswitch (slotNum){\n\t\t\tcase 0:\n\t\t\t\treturn SPDAction.QUICKSLOT_1;\n\t\t\tcase 1:\n\t\t\t\treturn SPDAction.QUICKSLOT_2;\n\t\t\tcase 2:\n\t\t\t\treturn SPDAction.QUICKSLOT_3;\n\t\t\tcase 3:\n\t\t\t\treturn SPDAction.QUICKSLOT_4;\n\t\t\tcase 4:\n\t\t\t\treturn SPDAction.QUICKSLOT_5;\n\t\t\tcase 5:\n\t\t\t\treturn SPDAction.QUICKSLOT_6;\n\t\t\tdefault:\n\t\t\t\treturn super.keyAction();\n\t\t}\n\t}\n\n\t@Override\n\tpublic GameAction secondaryTooltipAction() {\n\t\treturn SPDAction.QUICKSLOT_SELECTOR;\n\t}\n\n\t@Override\n\tprotected String hoverText() {\n\t\tif (slot.item == null){\n\t\t\treturn Messages.titleCase(Messages.get(WndKeyBindings.class, \"quickslot_\" + (slotNum+1)));\n\t\t} else {\n\t\t\treturn super.hoverText();\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected void onClick() {\n\t\tif (Dungeon.hero.ready && !GameScene.cancel()) {\n\t\t\tGameScene.selectItem(itemSelector);\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onRightClick() {\n\t\tonClick();\n\t}\n\n\t@Override\n\tprotected void onMiddleClick() {\n\t\tonClick();\n\t}\n\n\t@Override\n\tprotected boolean onLongClick() {\n\t\tonClick();\n\t\treturn true;\n\t}\n\n\tprivate WndBag.ItemSelector itemSelector = new WndBag.ItemSelector() {\n\n\t\t@Override\n\t\tpublic String textPrompt() {\n\t\t\treturn Messages.get(QuickSlotButton.class, \"select_item\");\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean itemSelectable(Item item) {\n\t\t\treturn item.defaultAction() != null;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onSelect(Item item) {\n\t\t\tif (item != null) {\n\t\t\t\tset( slotNum , item );\n\t\t\t}\n\t\t}\n\t};\n\n\tpublic static void set(Item item){\n\t\tfor (int i = 0; i < instance.length; i++) {\n\t\t\tif (select(i) == null || select(i) == item) {\n\t\t\t\tset(i, item);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tset(0, item);\n\t}\n\n\tpublic static void set(int slotNum, Item item){\n\t\tDungeon.quickslot.setSlot( slotNum , item );\n\t\trefresh();\n\n\t\t//Remember if the player adds the waterskin as one of their first actions.\n\t\tif (Statistics.duration + Actor.now() <= 10){\n\t\t\tboolean containsWaterskin = false;\n\t\t\tfor (int i = 0; i < instance.length; i++) {\n\t\t\t\tif (select(i) instanceof Waterskin) containsWaterskin = true;\n\t\t\t}\n\t\t\tif (containsWaterskin) SPDSettings.quickslotWaterskin(true);\n\t\t}\n\t}\n\n\tprivate static Item select(int slotNum){\n\t\treturn Dungeon.quickslot.getItem( slotNum );\n\t}\n\t\n\tpublic void item( Item item ) {\n\t\tslot.item( item );\n\t\tenableSlot();\n\t}\n\n\tpublic void enable( boolean value ) {\n\t\tactive = value;\n\t\tif (value) {\n\t\t\tenableSlot();\n\t\t} else {\n\t\t\tslot.enable( false );\n\t\t}\n\t}\n\t\n\tprivate void enableSlot() {\n\t\tslot.enable(Dungeon.quickslot.isNonePlaceholder( slotNum )\n\t\t\t\t&& (Dungeon.hero.buff(LostInventory.class) == null || Dungeon.quickslot.getItem(slotNum).keptThroughLostInventory()));\n\t}\n\n\tpublic void slotMargins( int left, int top, int right, int bottom){\n\t\tslot.setMargins(left, top, right, bottom);\n\t}\n\n\tpublic static void useTargeting(int idx){\n\t\tinstance[idx].useTargeting();\n\t}\n\n\tprivate void useTargeting() {\n\n\t\tif (lastTarget != null &&\n\t\t\t\tActor.chars().contains( lastTarget ) &&\n\t\t\t\tlastTarget.isAlive() &&\n\t\t\t\tlastTarget.alignment != Char.Alignment.ALLY &&\n\t\t\t\tDungeon.level.heroFOV[lastTarget.pos]) {\n\n\t\t\ttargetingSlot = slotNum;\n\t\t\tCharSprite sprite = lastTarget.sprite;\n\n\t\t\tif (sprite.parent != null) {\n\t\t\t\tsprite.parent.addToFront(crossM);\n\t\t\t\tcrossM.point(sprite.center(crossM));\n\t\t\t}\n\n\t\t\tcrossB.point(slot.sprite.center(crossB));\n\t\t\tcrossB.visible = true;\n\n\t\t} else {\n\n\t\t\tlastTarget = null;\n\t\t\ttargetingSlot = -1;\n\n\t\t}\n\n\t}\n\n\tpublic static int autoAim(Char target){\n\t\t//will use generic projectile logic if no item is specified\n\t\treturn autoAim(target, new Item());\n\t}\n\n\t//FIXME: this is currently very expensive, should either optimize ballistica or this, or both\n\tpublic static int autoAim(Char target, Item item){\n\n\t\t//first try to directly target\n\t\tif (item.targetingPos(Dungeon.hero, target.pos) == target.pos) {\n\t\t\treturn target.pos;\n\t\t}\n\n\t\t//Otherwise pick nearby tiles to try and 'angle' the shot, auto-aim basically.\n\t\tPathFinder.buildDistanceMap( target.pos, BArray.not( new boolean[Dungeon.level.length()], null ), 2 );\n\t\tfor (int i = 0; i < PathFinder.distance.length; i++) {\n\t\t\tif (PathFinder.distance[i] < Integer.MAX_VALUE\n\t\t\t\t\t&& item.targetingPos(Dungeon.hero, i) == target.pos)\n\t\t\t\treturn i;\n\t\t}\n\n\t\t//couldn't find a cell, give up.\n\t\treturn -1;\n\t}\n\n\tpublic static void refresh() {\n\t\tfor (int i = 0; i < instance.length; i++) {\n\t\t\tif (instance[i] != null) {\n\t\t\t\tinstance[i].item(select(i));\n\t\t\t\tinstance[i].enable(instance[i].active);\n\t\t\t}\n\t\t}\n\t\tif (Toolbar.SWAP_INSTANCE != null){\n\t\t\tToolbar.SWAP_INSTANCE.updateVisuals();\n\t\t}\n\t\t//Remember if the player removes the waterskin as one of their first actions.\n\t\tif (Statistics.duration + Actor.now() <= 10){\n\t\t\tboolean containsWaterskin = false;\n\t\t\tfor (int i = 0; i < instance.length; i++) {\n\t\t\t\tif (select(i) instanceof Waterskin) containsWaterskin = true;\n\t\t\t}\n\t\t\tif (!containsWaterskin) SPDSettings.quickslotWaterskin(false);\n\t\t}\n\t}\n\t\n\tpublic static void target( Char target ) {\n\t\tif (target != null && target.alignment != Char.Alignment.ALLY) {\n\t\t\tlastTarget = target;\n\t\t\t\n\t\t\tTargetHealthIndicator.instance.target( target );\n\t\t\tInventoryPane.lastTarget = target;\n\t\t}\n\t}\n\t\n\tpublic static void cancel() {\n\t\tif (targetingSlot != -1) {\n\t\t\tfor (QuickSlotButton btn : instance) {\n\t\t\t\tbtn.crossB.visible = false;\n\t\t\t\tbtn.crossM.remove();\n\t\t\t\ttargetingSlot = -1;\n\t\t\t}\n\t\t}\n\t}\n}" }, { "identifier": "Toolbar", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/ui/Toolbar.java", "snippet": "public class Toolbar extends Component {\n\n\tprivate Tool btnWait;\n\tprivate Tool btnSearch;\n\tprivate Tool btnInventory;\n\tprivate QuickslotTool[] btnQuick;\n\tprivate SlotSwapTool btnSwap;\n\t\n\tprivate PickedUpItem pickedUp;\n\t\n\tprivate boolean lastEnabled = true;\n\tpublic boolean examining = false;\n\n\tprivate static Toolbar instance;\n\n\tpublic enum Mode {\n\t\tSPLIT,\n\t\tGROUP,\n\t\tCENTER\n\t}\n\t\n\tpublic Toolbar() {\n\t\tsuper();\n\n\t\tinstance = this;\n\n\t\theight = btnInventory.height();\n\t}\n\n\t@Override\n\tpublic synchronized void destroy() {\n\t\tsuper.destroy();\n\t\tif (instance == this) instance = null;\n\t}\n\n\t@Override\n\tprotected void createChildren() {\n\n\t\tadd(btnSwap = new SlotSwapTool(128, 0, 21, 23));\n\n\t\tbtnQuick = new QuickslotTool[QuickSlot.SIZE];\n\t\tfor (int i = 0; i < btnQuick.length; i++){\n\t\t\tadd( btnQuick[i] = new QuickslotTool(64, 0, 22, 24, i) );\n\t\t}\n\n\t\t//hidden button for quickslot selector keybind\n\t\tadd(new Button(){\n\t\t\t@Override\n\t\t\tprotected void onClick() {\n\t\t\t\tif (QuickSlotButton.targetingSlot != -1){\n\t\t\t\t\tint cell = QuickSlotButton.autoAim(QuickSlotButton.lastTarget, Dungeon.quickslot.getItem(QuickSlotButton.targetingSlot));\n\n\t\t\t\t\tif (cell != -1){\n\t\t\t\t\t\tGameScene.handleCell(cell);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//couldn't auto-aim, just target the position and hope for the best.\n\t\t\t\t\t\tGameScene.handleCell( QuickSlotButton.lastTarget.pos );\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (Dungeon.hero != null && Dungeon.hero.ready && !GameScene.cancel()) {\n\n\t\t\t\t\tString[] slotNames = new String[6];\n\t\t\t\t\tImage[] slotIcons = new Image[6];\n\t\t\t\t\tfor (int i = 0; i < 6; i++){\n\t\t\t\t\t\tItem item = Dungeon.quickslot.getItem(i);\n\n\t\t\t\t\t\tif (item != null && !Dungeon.quickslot.isPlaceholder(i) &&\n\t\t\t\t\t\t\t\t(Dungeon.hero.buff(LostInventory.class) == null || item.keptThroughLostInventory())){\n\t\t\t\t\t\t\tslotNames[i] = Messages.titleCase(item.name());\n\t\t\t\t\t\t\tslotIcons[i] = new ItemSprite(item);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tslotNames[i] = Messages.get(Toolbar.class, \"quickslot_assign\");\n\t\t\t\t\t\t\tslotIcons[i] = new ItemSprite(ItemSpriteSheet.SOMETHING);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tString info = \"\";\n\t\t\t\t\tif (ControllerHandler.controllerActive){\n\t\t\t\t\t\tinfo += KeyBindings.getKeyName(KeyBindings.getFirstKeyForAction(GameAction.LEFT_CLICK, true)) + \": \" + Messages.get(Toolbar.class, \"quickslot_select\") + \"\\n\";\n\t\t\t\t\t\tinfo += KeyBindings.getKeyName(KeyBindings.getFirstKeyForAction(GameAction.RIGHT_CLICK, true)) + \": \" + Messages.get(Toolbar.class, \"quickslot_assign\") + \"\\n\";\n\t\t\t\t\t\tinfo += KeyBindings.getKeyName(KeyBindings.getFirstKeyForAction(GameAction.BACK, true)) + \": \" + Messages.get(Toolbar.class, \"quickslot_cancel\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tinfo += Messages.get(WndKeyBindings.class, SPDAction.LEFT_CLICK.name()) + \": \" + Messages.get(Toolbar.class, \"quickslot_select\") + \"\\n\";\n\t\t\t\t\t\tinfo += Messages.get(WndKeyBindings.class, SPDAction.RIGHT_CLICK.name()) + \": \" + Messages.get(Toolbar.class, \"quickslot_assign\") + \"\\n\";\n\t\t\t\t\t\tinfo += KeyBindings.getKeyName(KeyBindings.getFirstKeyForAction(GameAction.BACK, false)) + \": \" + Messages.get(Toolbar.class, \"quickslot_cancel\");\n\t\t\t\t\t}\n\n\t\t\t\t\tGame.scene().addToFront(new RadialMenu(Messages.get(Toolbar.class, \"quickslot_prompt\"), info, slotNames, slotIcons) {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onSelect(int idx, boolean alt) {\n\t\t\t\t\t\t\tItem item = Dungeon.quickslot.getItem(idx);\n\n\t\t\t\t\t\t\tif (item == null || Dungeon.quickslot.isPlaceholder(idx)\n\t\t\t\t\t\t\t\t\t|| (Dungeon.hero.buff(LostInventory.class) != null && !item.keptThroughLostInventory())\n\t\t\t\t\t\t\t\t\t|| alt){\n\t\t\t\t\t\t\t\t//TODO would be nice to use a radial menu for this too\n\t\t\t\t\t\t\t\t// Also a bunch of code could be moved out of here into subclasses of RadialMenu\n\t\t\t\t\t\t\t\tGameScene.selectItem(new WndBag.ItemSelector() {\n\t\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\t\tpublic String textPrompt() {\n\t\t\t\t\t\t\t\t\t\treturn Messages.get(QuickSlotButton.class, \"select_item\");\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\t\tpublic boolean itemSelectable(Item item) {\n\t\t\t\t\t\t\t\t\t\treturn item.defaultAction() != null;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\t\tpublic void onSelect(Item item) {\n\t\t\t\t\t\t\t\t\t\tif (item != null) {\n\t\t\t\t\t\t\t\t\t\t\tQuickSlotButton.set(idx, item);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\titem.execute(Dungeon.hero);\n\t\t\t\t\t\t\t\tif (item.usesTargeting) {\n\t\t\t\t\t\t\t\t\tQuickSlotButton.useTargeting(idx);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsuper.onSelect(idx, alt);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic GameAction keyAction() {\n\t\t\t\tif (btnWait.active) return SPDAction.QUICKSLOT_SELECTOR;\n\t\t\t\telse\t\t\t\treturn null;\n\t\t\t}\n\t\t});\n\t\t\n\t\tadd(btnWait = new Tool(24, 0, 20, 26) {\n\t\t\t@Override\n\t\t\tprotected void onClick() {\n\t\t\t\tif (Dungeon.hero != null && Dungeon.hero.ready && !GameScene.cancel()) {\n\t\t\t\t\texamining = false;\n\t\t\t\t\tDungeon.hero.rest(false);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic GameAction keyAction() {\n\t\t\t\treturn SPDAction.WAIT;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic GameAction secondaryTooltipAction() {\n\t\t\t\treturn SPDAction.WAIT_OR_PICKUP;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String hoverText() {\n\t\t\t\treturn Messages.titleCase(Messages.get(WndKeyBindings.class, \"wait\"));\n\t\t\t}\n\n\t\t\tprotected boolean onLongClick() {\n\t\t\t\tif (Dungeon.hero != null && Dungeon.hero.ready && !GameScene.cancel()) {\n\t\t\t\t\texamining = false;\n\t\t\t\t\tDungeon.hero.rest(true);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t});\n\t\tbtnWait.icon( 176, 0, 16, 16 );\n\n\t\t//hidden button for rest keybind\n\t\tadd(new Button(){\n\t\t\t@Override\n\t\t\tprotected void onClick() {\n\t\t\t\tif (Dungeon.hero != null && Dungeon.hero.ready && !GameScene.cancel()) {\n\t\t\t\t\texamining = false;\n\t\t\t\t\tDungeon.hero.rest(true);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic GameAction keyAction() {\n\t\t\t\tif (btnWait.active) return SPDAction.REST;\n\t\t\t\telse\t\t\t\treturn null;\n\t\t\t}\n\t\t});\n\n\t\t//hidden button for wait / pickup keybind\n\t\tadd(new Button(){\n\t\t\t@Override\n\t\t\tprotected void onClick() {\n\t\t\t\tif (Dungeon.hero != null && Dungeon.hero.ready && !GameScene.cancel()) {\n\t\t\t\t\tDungeon.hero.waitOrPickup = true;\n\t\t\t\t\tif ((Dungeon.level.heaps.get(Dungeon.hero.pos) != null || Dungeon.hero.canSelfTrample())\n\t\t\t\t\t\t&& Dungeon.hero.handle(Dungeon.hero.pos)){\n\t\t\t\t\t\t//trigger hold fast and patient strike here, even if the hero didn't specifically wait\n\t\t\t\t\t\tif (Dungeon.hero.hasTalent(Talent.HOLD_FAST)){\n\t\t\t\t\t\t\tBuff.affect(Dungeon.hero, HoldFast.class).pos = Dungeon.hero.pos;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (Dungeon.hero.hasTalent(Talent.PATIENT_STRIKE)){\n\t\t\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.PatientStrikeTracker.class).pos = Dungeon.hero.pos;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tDungeon.hero.next();\n\t\t\t\t\t} else {\n\t\t\t\t\t\texamining = false;\n\t\t\t\t\t\tDungeon.hero.rest(false);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprotected boolean onLongClick() {\n\t\t\t\tif (Dungeon.hero != null && Dungeon.hero.ready && !GameScene.cancel()) {\n\t\t\t\t\texamining = false;\n\t\t\t\t\tDungeon.hero.rest(true);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic GameAction keyAction() {\n\t\t\t\tif (btnWait.active) return SPDAction.WAIT_OR_PICKUP;\n\t\t\t\telse\t\t\t\treturn null;\n\t\t\t}\n\t\t});\n\t\t\n\t\tadd(btnSearch = new Tool(44, 0, 20, 26) {\n\t\t\t@Override\n\t\t\tprotected void onClick() {\n\t\t\t\tif (Dungeon.hero != null && Dungeon.hero.ready) {\n\t\t\t\t\tif (!examining && !GameScene.cancel()) {\n\t\t\t\t\t\tGameScene.selectCell(informer);\n\t\t\t\t\t\texamining = true;\n\t\t\t\t\t} else if (examining) {\n\t\t\t\t\t\tinformer.onSelect(null);\n\t\t\t\t\t\tDungeon.hero.search(true);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic GameAction keyAction() {\n\t\t\t\treturn SPDAction.EXAMINE;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String hoverText() {\n\t\t\t\treturn Messages.titleCase(Messages.get(WndKeyBindings.class, \"examine\"));\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tprotected boolean onLongClick() {\n\t\t\t\tDungeon.hero.search(true);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t});\n\t\tbtnSearch.icon( 192, 0, 16, 16 );\n\t\t\n\t\tadd(btnInventory = new Tool(0, 0, 24, 26) {\n\t\t\tprivate CurrencyIndicator ind;\n\n\t\t\tprivate Image arrow;\n\n\t\t\t@Override\n\t\t\tprotected void onClick() {\n\t\t\t\tif (Dungeon.hero != null && (Dungeon.hero.ready || !Dungeon.hero.isAlive())) {\n\t\t\t\t\tif (SPDSettings.interfaceSize() == 2) {\n\t\t\t\t\t\tGameScene.toggleInvPane();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (!GameScene.cancel()) {\n\t\t\t\t\t\t\tGameScene.show(new WndBag(Dungeon.hero.belongings.backpack));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic GameAction keyAction() {\n\t\t\t\treturn SPDAction.INVENTORY;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic GameAction secondaryTooltipAction() {\n\t\t\t\treturn SPDAction.INVENTORY_SELECTOR;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String hoverText() {\n\t\t\t\treturn Messages.titleCase(Messages.get(WndKeyBindings.class, \"inventory\"));\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tprotected boolean onLongClick() {\n\t\t\t\tGameScene.show(new WndQuickBag(null));\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected void createChildren() {\n\t\t\t\tsuper.createChildren();\n\t\t\t\tarrow = Icons.get(Icons.COMPASS);\n\t\t\t\tarrow.originToCenter();\n\t\t\t\tarrow.visible = SPDSettings.interfaceSize() == 2;\n\t\t\t\tarrow.tint(0x3D2E18, 1f);\n\t\t\t\tadd(arrow);\n\n\t\t\t\tind = new CurrencyIndicator();\n\t\t\t\tadd(ind);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected void layout() {\n\t\t\t\tsuper.layout();\n\t\t\t\tind.fill(this);\n\t\t\t\tbringToFront(ind);\n\n\t\t\t\tarrow.x = left() + (width - arrow.width())/2;\n\t\t\t\tarrow.y = bottom()-arrow.height-1;\n\t\t\t\tarrow.angle = bottom() == camera().height ? 0 : 180;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void enable(boolean value) {\n\t\t\t\tif (value != active){\n\t\t\t\t\tarrow.alpha( value ? 1f : 0.4f );\n\t\t\t\t}\n\t\t\t\tsuper.enable(value);\n\t\t\t}\n\t\t});\n\t\tbtnInventory.icon( 160, 0, 16, 16 );\n\n\t\t//hidden button for inventory selector keybind\n\t\tadd(new Button(){\n\t\t\t@Override\n\t\t\tprotected void onClick() {\n\t\t\t\tif (Dungeon.hero != null && Dungeon.hero.ready && !GameScene.cancel()) {\n\t\t\t\t\tArrayList<Bag> bags = Dungeon.hero.belongings.getBags();\n\t\t\t\t\tString[] names = new String[bags.size()];\n\t\t\t\t\tImage[] images = new Image[bags.size()];\n\t\t\t\t\tfor (int i = 0; i < bags.size(); i++){\n\t\t\t\t\t\tnames[i] = Messages.titleCase(bags.get(i).name());\n\t\t\t\t\t\timages[i] = new ItemSprite(bags.get(i));\n\t\t\t\t\t}\n\t\t\t\t\tString info = \"\";\n\t\t\t\t\tif (ControllerHandler.controllerActive){\n\t\t\t\t\t\tinfo += KeyBindings.getKeyName(KeyBindings.getFirstKeyForAction(GameAction.LEFT_CLICK, true)) + \": \" + Messages.get(Toolbar.class, \"container_select\") + \"\\n\";\n\t\t\t\t\t\tinfo += KeyBindings.getKeyName(KeyBindings.getFirstKeyForAction(GameAction.BACK, true)) + \": \" + Messages.get(Toolbar.class, \"container_cancel\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tinfo += Messages.get(WndKeyBindings.class, SPDAction.LEFT_CLICK.name()) + \": \" + Messages.get(Toolbar.class, \"container_select\") + \"\\n\";\n\t\t\t\t\t\tinfo += KeyBindings.getKeyName(KeyBindings.getFirstKeyForAction(GameAction.BACK, false)) + \": \" + Messages.get(Toolbar.class, \"container_cancel\");\n\t\t\t\t\t}\n\n\t\t\t\t\tGame.scene().addToFront(new RadialMenu(Messages.get(Toolbar.class, \"container_prompt\"), info, names, images){\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onSelect(int idx, boolean alt) {\n\t\t\t\t\t\t\tsuper.onSelect(idx, alt);\n\t\t\t\t\t\t\tBag bag = bags.get(idx);\n\t\t\t\t\t\t\tArrayList<Item> items = (ArrayList<Item>) bag.items.clone();\n\n\t\t\t\t\t\t\tfor(Item i : bag.items){\n\t\t\t\t\t\t\t\tif (i instanceof Bag) items.remove(i);\n\t\t\t\t\t\t\t\tif (Dungeon.hero.buff(LostInventory.class) != null && !i.keptThroughLostInventory()) items.remove(i);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (idx == 0){\n\t\t\t\t\t\t\t\tBelongings b = Dungeon.hero.belongings;\n\t\t\t\t\t\t\t\tif (b.ring() != null) items.add(0, b.ring());\n\t\t\t\t\t\t\t\tif (b.misc() != null) items.add(0, b.misc());\n\t\t\t\t\t\t\t\tif (b.artifact() != null) items.add(0, b.artifact());\n\t\t\t\t\t\t\t\tif (b.armor() != null) items.add(0, b.armor());\n\t\t\t\t\t\t\t\tif (b.weapon() != null) items.add(0, b.weapon());\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (items.size() == 0){\n\t\t\t\t\t\t\t\tGameScene.show(new WndMessage(Messages.get(Toolbar.class, \"container_empty\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString[] itemNames = new String[items.size()];\n\t\t\t\t\t\t\tImage[] itemIcons = new Image[items.size()];\n\t\t\t\t\t\t\tfor (int i = 0; i < items.size(); i++){\n\t\t\t\t\t\t\t\titemNames[i] = Messages.titleCase(items.get(i).name());\n\t\t\t\t\t\t\t\titemIcons[i] = new ItemSprite(items.get(i));\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString info = \"\";\n\t\t\t\t\t\t\tif (ControllerHandler.controllerActive){\n\t\t\t\t\t\t\t\tinfo += KeyBindings.getKeyName(KeyBindings.getFirstKeyForAction(GameAction.LEFT_CLICK, true)) + \": \" + Messages.get(Toolbar.class, \"item_select\") + \"\\n\";\n\t\t\t\t\t\t\t\tinfo += KeyBindings.getKeyName(KeyBindings.getFirstKeyForAction(GameAction.RIGHT_CLICK, true)) + \": \" + Messages.get(Toolbar.class, \"item_use\") + \"\\n\";\n\t\t\t\t\t\t\t\tinfo += KeyBindings.getKeyName(KeyBindings.getFirstKeyForAction(GameAction.BACK, true)) + \": \" + Messages.get(Toolbar.class, \"item_cancel\");\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tinfo += Messages.get(WndKeyBindings.class, SPDAction.LEFT_CLICK.name()) + \": \" + Messages.get(Toolbar.class, \"item_select\") + \"\\n\";\n\t\t\t\t\t\t\t\tinfo += Messages.get(WndKeyBindings.class, SPDAction.RIGHT_CLICK.name()) + \": \" + Messages.get(Toolbar.class, \"item_use\") + \"\\n\";\n\t\t\t\t\t\t\t\tinfo += KeyBindings.getKeyName(KeyBindings.getFirstKeyForAction(GameAction.BACK, false)) + \": \" + Messages.get(Toolbar.class, \"item_cancel\");\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tGame.scene().addToFront(new RadialMenu(Messages.get(Toolbar.class, \"item_prompt\"), info, itemNames, itemIcons){\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tpublic void onSelect(int idx, boolean alt) {\n\t\t\t\t\t\t\t\t\tsuper.onSelect(idx, alt);\n\t\t\t\t\t\t\t\t\tItem item = items.get(idx);\n\t\t\t\t\t\t\t\t\tif (alt && item.defaultAction() != null) {\n\t\t\t\t\t\t\t\t\t\titem.execute(Dungeon.hero);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tInventoryPane.clearTargetingSlot();\n\t\t\t\t\t\t\t\t\t\tGame.scene().addToFront(new WndUseItem(null, item));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic GameAction keyAction() {\n\t\t\t\tif (btnWait.active) return SPDAction.INVENTORY_SELECTOR;\n\t\t\t\telse\t\t\t\treturn null;\n\t\t\t}\n\t\t});\n\n\t\tadd(pickedUp = new PickedUpItem());\n\t}\n\t\n\t@Override\n\tprotected void layout() {\n\n\t\tfloat right = width;\n\n\t\tint quickslotsToShow = 4;\n\t\tif (PixelScene.uiCamera.width > 152) quickslotsToShow ++;\n\t\tif (PixelScene.uiCamera.width > 170) quickslotsToShow ++;\n\n\t\tint startingSlot;\n\t\tif (SPDSettings.quickSwapper() && quickslotsToShow < 6){\n\t\t\tquickslotsToShow = 3;\n\t\t\tstartingSlot = swappedQuickslots ? 3 : 0;\n\t\t\tbtnSwap.visible = true;\n\t\t\tbtnSwap.active = lastEnabled;\n\t\t} else {\n\t\t\tstartingSlot = 0;\n\t\t\tbtnSwap.visible = btnSwap.active = false;\n\t\t\tbtnSwap.setPos(0, PixelScene.uiCamera.height);\n\t\t}\n\t\tint endingSlot = startingSlot+quickslotsToShow-1;\n\n\t\tfor (int i = 0; i < btnQuick.length; i++){\n\t\t\tbtnQuick[i].visible = i >= startingSlot && i <= endingSlot;\n\t\t\tbtnQuick[i].enable(btnQuick[i].visible && lastEnabled);\n\t\t\tif (i < startingSlot || i > endingSlot){\n\t\t\t\tbtnQuick[i].setPos(btnQuick[i].left(), PixelScene.uiCamera.height);\n\t\t\t}\n\t\t}\n\n\t\tif (SPDSettings.interfaceSize() > 0){\n\t\t\tbtnInventory.setPos(right - btnInventory.width(), y);\n\t\t\tbtnWait.setPos(btnInventory.left() - btnWait.width(), y);\n\t\t\tbtnSearch.setPos(btnWait.left() - btnSearch.width(), y);\n\n\t\t\tright = btnSearch.left();\n\t\t\tfor(int i = endingSlot; i >= startingSlot; i--) {\n\t\t\t\tif (i == endingSlot){\n\t\t\t\t\tbtnQuick[i].border(0, 2);\n\t\t\t\t\tbtnQuick[i].frame(106, 0, 19, 24);\n\t\t\t\t} else if (i == 0){\n\t\t\t\t\tbtnQuick[i].border(2, 1);\n\t\t\t\t\tbtnQuick[i].frame(86, 0, 20, 24);\n\t\t\t\t} else {\n\t\t\t\t\tbtnQuick[i].border(0, 1);\n\t\t\t\t\tbtnQuick[i].frame(88, 0, 18, 24);\n\t\t\t\t}\n\t\t\t\tbtnQuick[i].setPos(right-btnQuick[i].width(), y+2);\n\t\t\t\tright = btnQuick[i].left();\n\t\t\t}\n\n\t\t\t//swap button never appears on larger interface sizes\n\n\t\t\treturn;\n\t\t}\n\n\t\tfor(int i = startingSlot; i <= endingSlot; i++) {\n\t\t\tif (i == startingSlot && !SPDSettings.flipToolbar() ||\n\t\t\t\ti == endingSlot && SPDSettings.flipToolbar()){\n\t\t\t\tbtnQuick[i].border(0, 2);\n\t\t\t\tbtnQuick[i].frame(106, 0, 19, 24);\n\t\t\t} else if (i == startingSlot && SPDSettings.flipToolbar() ||\n\t\t\t\t\ti == endingSlot && !SPDSettings.flipToolbar()){\n\t\t\t\tbtnQuick[i].border(2, 1);\n\t\t\t\tbtnQuick[i].frame(86, 0, 20, 24);\n\t\t\t} else {\n\t\t\t\tbtnQuick[i].border(0, 1);\n\t\t\t\tbtnQuick[i].frame(88, 0, 18, 24);\n\t\t\t}\n\t\t}\n\n\t\tfloat shift = 0;\n\t\tswitch(Mode.valueOf(SPDSettings.toolbarMode())){\n\t\t\tcase SPLIT:\n\t\t\t\tbtnWait.setPos(x, y);\n\t\t\t\tbtnSearch.setPos(btnWait.right(), y);\n\n\t\t\t\tbtnInventory.setPos(right - btnInventory.width(), y);\n\n\t\t\t\tfloat left = 0;\n\n\t\t\t\tbtnQuick[startingSlot].setPos(btnInventory.left() - btnQuick[startingSlot].width(), y + 2);\n\t\t\t\tfor (int i = startingSlot+1; i <= endingSlot; i++) {\n\t\t\t\t\tbtnQuick[i].setPos(btnQuick[i-1].left() - btnQuick[i].width(), y + 2);\n\t\t\t\t\tshift = btnSearch.right() - btnQuick[i].left();\n\t\t\t\t}\n\n\t\t\t\tif (btnSwap.visible){\n\t\t\t\t\tbtnSwap.setPos(btnQuick[endingSlot].left() - (btnSwap.width()-2), y+3);\n\t\t\t\t\tshift = btnSearch.right() - btnSwap.left();\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\t//center = group but.. well.. centered, so all we need to do is pre-emptively set the right side further in.\n\t\t\tcase CENTER:\n\t\t\t\tfloat toolbarWidth = btnWait.width() + btnSearch.width() + btnInventory.width();\n\t\t\t\tfor(Button slot : btnQuick){\n\t\t\t\t\tif (slot.visible) toolbarWidth += slot.width();\n\t\t\t\t}\n\t\t\t\tif (btnSwap.visible) toolbarWidth += btnSwap.width()-2;\n\t\t\t\tright = (width + toolbarWidth)/2;\n\n\t\t\tcase GROUP:\n\t\t\t\tbtnWait.setPos(right - btnWait.width(), y);\n\t\t\t\tbtnSearch.setPos(btnWait.left() - btnSearch.width(), y);\n\t\t\t\tbtnInventory.setPos(btnSearch.left() - btnInventory.width(), y);\n\n\t\t\t\tbtnQuick[startingSlot].setPos(btnInventory.left() - btnQuick[startingSlot].width(), y + 2);\n\t\t\t\tfor (int i = startingSlot+1; i <= endingSlot; i++) {\n\t\t\t\t\tbtnQuick[i].setPos(btnQuick[i-1].left() - btnQuick[i].width(), y + 2);\n\t\t\t\t\tshift = -btnQuick[i].left();\n\t\t\t\t}\n\n\t\t\t\tif (btnSwap.visible){\n\t\t\t\t\tbtnSwap.setPos(btnQuick[endingSlot].left() - (btnSwap.width()-2), y+3);\n\t\t\t\t\tshift = -btnSwap.left();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif (shift > 0){\n\t\t\tshift /= 2; //we want to center;\n\t\t\tfor (int i = startingSlot; i <= endingSlot; i++) {\n\t\t\t\tbtnQuick[i].setPos(btnQuick[i].left()+shift, btnQuick[i].top());\n\t\t\t}\n\t\t\tif (btnSwap.visible){\n\t\t\t\tbtnSwap.setPos(btnSwap.left()+shift, btnSwap.top());\n\t\t\t}\n\t\t}\n\n\t\tright = width;\n\n\t\tif (SPDSettings.flipToolbar()) {\n\n\t\t\tbtnWait.setPos( (right - btnWait.right()), y);\n\t\t\tbtnSearch.setPos( (right - btnSearch.right()), y);\n\t\t\tbtnInventory.setPos( (right - btnInventory.right()), y);\n\n\t\t\tfor(int i = startingSlot; i <= endingSlot; i++) {\n\t\t\t\tbtnQuick[i].setPos( right - btnQuick[i].right(), y+2);\n\t\t\t}\n\n\t\t\tif (btnSwap.visible){\n\t\t\t\tbtnSwap.setPos( right - btnSwap.right(), y+3);\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tpublic static void updateLayout(){\n\t\tif (instance != null) instance.layout();\n\t}\n\t\n\t@Override\n\tpublic void update() {\n\t\tsuper.update();\n\t\t\n\t\tif (lastEnabled != (Dungeon.hero.ready && Dungeon.hero.isAlive())) {\n\t\t\tlastEnabled = (Dungeon.hero.ready && Dungeon.hero.isAlive());\n\t\t\t\n\t\t\tfor (Gizmo tool : members.toArray(new Gizmo[0])) {\n\t\t\t\tif (tool instanceof Tool) {\n\t\t\t\t\t((Tool)tool).enable( lastEnabled );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (!Dungeon.hero.isAlive()) {\n\t\t\tbtnInventory.enable(true);\n\t\t}\n\t}\n\n\tpublic void alpha( float value ){\n\t\tbtnWait.alpha( value );\n\t\tbtnSearch.alpha( value );\n\t\tbtnInventory.alpha( value );\n\t\tfor (QuickslotTool tool : btnQuick){\n\t\t\ttool.alpha(value);\n\t\t}\n\t\tbtnSwap.alpha( value );\n\t}\n\n\tpublic void pickup( Item item, int cell ) {\n\t\tpickedUp.reset( item,\n\t\t\tcell,\n\t\t\tbtnInventory.centerX(),\n\t\t\tbtnInventory.centerY());\n\t}\n\t\n\tprivate static CellSelector.Listener informer = new CellSelector.Listener() {\n\t\t@Override\n\t\tpublic void onSelect( Integer cell ) {\n\t\t\tif (instance != null) {\n\t\t\t\tinstance.examining = false;\n\t\t\t\tGameScene.examineCell(cell);\n\t\t\t}\n\t\t}\n\t\t@Override\n\t\tpublic String prompt() {\n\t\t\treturn Messages.get(Toolbar.class, \"examine_prompt\");\n\t\t}\n\t};\n\t\n\tprivate static class Tool extends Button {\n\t\t\n\t\tprivate static final int BGCOLOR = 0x7B8073;\n\t\t\n\t\tprivate Image base;\n\t\tprivate Image icon;\n\t\t\n\t\tpublic Tool( int x, int y, int width, int height ) {\n\t\t\tsuper();\n\n\t\t\thotArea.blockLevel = PointerArea.ALWAYS_BLOCK;\n\t\t\tframe(x, y, width, height);\n\t\t}\n\n\t\tpublic void frame( int x, int y, int width, int height) {\n\t\t\tbase.frame( x, y, width, height );\n\n\t\t\tthis.width = width;\n\t\t\tthis.height = height;\n\t\t}\n\n\t\tpublic void icon( int x, int y, int width, int height){\n\t\t\tif (icon == null) icon = new Image( Assets.Interfaces.TOOLBAR );\n\t\t\tadd(icon);\n\n\t\t\ticon.frame( x, y, width, height);\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected void createChildren() {\n\t\t\tsuper.createChildren();\n\t\t\t\n\t\t\tbase = new Image( Assets.Interfaces.TOOLBAR );\n\t\t\tadd( base );\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected void layout() {\n\t\t\tsuper.layout();\n\t\t\t\n\t\t\tbase.x = x;\n\t\t\tbase.y = y;\n\n\t\t\tif (icon != null){\n\t\t\t\ticon.x = x + (width()- icon.width())/2f;\n\t\t\t\ticon.y = y + (height()- icon.height())/2f;\n\t\t\t}\n\t\t}\n\n\t\tpublic void alpha( float value ){\n\t\t\tbase.alpha(value);\n\t\t\tif (icon != null) icon.alpha(value);\n\t\t}\n\n\t\t@Override\n\t\tprotected void onPointerDown() {\n\t\t\tbase.brightness( 1.4f );\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected void onPointerUp() {\n\t\t\tif (active) {\n\t\t\t\tbase.resetColor();\n\t\t\t} else {\n\t\t\t\tbase.tint( BGCOLOR, 0.7f );\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic void enable( boolean value ) {\n\t\t\tif (value != active) {\n\t\t\t\tif (icon != null) icon.alpha( value ? 1f : 0.4f);\n\t\t\t\tactive = value;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate static class QuickslotTool extends Tool {\n\t\t\n\t\tprivate QuickSlotButton slot;\n\t\tprivate int borderLeft = 2;\n\t\tprivate int borderRight = 2;\n\t\t\n\t\tpublic QuickslotTool( int x, int y, int width, int height, int slotNum ) {\n\t\t\tsuper( x, y, width, height );\n\n\t\t\tslot = new QuickSlotButton( slotNum );\n\t\t\tadd( slot );\n\t\t}\n\n\t\tpublic void border( int left, int right ){\n\t\t\tborderLeft = left;\n\t\t\tborderRight = right;\n\t\t\tlayout();\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected void layout() {\n\t\t\tsuper.layout();\n\t\t\tslot.setRect( x, y, width, height );\n\t\t\tslot.slotMargins(borderLeft, 2, borderRight, 2);\n\t\t}\n\n\t\t@Override\n\t\tpublic void alpha(float value) {\n\t\t\tsuper.alpha(value);\n\t\t\tslot.alpha(value);\n\t\t}\n\n\t\t@Override\n\t\tpublic void enable( boolean value ) {\n\t\t\tsuper.enable( value && visible );\n\t\t\tslot.enable( value && visible );\n\t\t}\n\t}\n\n\tpublic static boolean swappedQuickslots = false;\n\tpublic static SlotSwapTool SWAP_INSTANCE;\n\n\tpublic static class SlotSwapTool extends Tool {\n\n\t\tprivate Image[] icons = new Image[4];\n\t\tprivate Item[] items = new Item[4];\n\n\t\tpublic SlotSwapTool(int x, int y, int width, int height) {\n\t\t\tsuper(x, y, width, height);\n\t\t\tSWAP_INSTANCE = this;\n\t\t\tupdateVisuals();\n\t\t}\n\n\t\t@Override\n\t\tpublic synchronized void destroy() {\n\t\t\tsuper.destroy();\n\t\t\tif (SWAP_INSTANCE == this) SWAP_INSTANCE = null;\n\t\t}\n\n\t\t@Override\n\t\tprotected void onClick() {\n\t\t\tsuper.onClick();\n\t\t\tswappedQuickslots = !swappedQuickslots;\n\t\t\tupdateLayout();\n\t\t\tupdateVisuals();\n\t\t}\n\n\t\tpublic void updateVisuals(){\n\t\t\tif (icons[0] == null){\n\t\t\t\ticons[0] = Icons.get(Icons.CHANGES);\n\t\t\t\ticons[0].scale.set(PixelScene.align(0.45f));\n\t\t\t\tadd(icons[0]);\n\t\t\t}\n\n\t\t\tint slot;\n\t\t\tint slotDir;\n\t\t\tif (SPDSettings.flipToolbar()){\n\t\t\t\tslot = swappedQuickslots ? 0 : 3;\n\t\t\t\tslotDir = +1;\n\t\t\t} else {\n\t\t\t\tslot = swappedQuickslots ? 2 : 5;\n\t\t\t\tslotDir = -1;\n\t\t\t}\n\n\t\t\tfor (int i = 1; i < 4; i++){\n\t\t\t\tif (items[i] == Dungeon.quickslot.getItem(slot)){\n\t\t\t\t\tslot += slotDir;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\titems[i] = Dungeon.quickslot.getItem(slot);\n\t\t\t\t}\n\t\t\t\tif (icons[i] != null){\n\t\t\t\t\ticons[i].killAndErase();\n\t\t\t\t\ticons[i] = null;\n\t\t\t\t}\n\t\t\t\tif (items[i] != null){\n\t\t\t\t\ticons[i] = new ItemSprite(items[i]);\n\t\t\t\t\ticons[i].scale.set(PixelScene.align(0.45f));\n\t\t\t\t\tif (Dungeon.quickslot.isPlaceholder(slot)) icons[i].alpha(0.29f);\n\t\t\t\t\tadd(icons[i]);\n\t\t\t\t}\n\t\t\t\tslot += slotDir;\n\t\t\t}\n\n\t\t\ticons[0].x = x + 2 + (8 - icons[0].width())/2;\n\t\t\ticons[0].y = y + 2 + (9 - icons[0].height())/2;\n\t\t\tPixelScene.align(icons[0]);\n\n\t\t\tif (icons[1] != null){\n\t\t\t\ticons[1].x = x + 11 + (8 - icons[1].width())/2;\n\t\t\t\ticons[1].y = y + 2 + (9 - icons[1].height())/2;\n\t\t\t\tPixelScene.align(icons[1]);\n\t\t\t}\n\n\t\t\tif (icons[2] != null){\n\t\t\t\ticons[2].x = x + 2 + (8 - icons[2].width())/2;\n\t\t\t\ticons[2].y = y + 12 + (9 - icons[2].height())/2;\n\t\t\t\tPixelScene.align(icons[2]);\n\t\t\t}\n\n\t\t\tif (icons[3] != null){\n\t\t\t\ticons[3].x = x + 11 + (8 - icons[3].width())/2;\n\t\t\t\ticons[3].y = y + 12 + (9 - icons[3].height())/2;\n\t\t\t\tPixelScene.align(icons[3]);\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tprotected void layout() {\n\t\t\tsuper.layout();\n\t\t\tupdateVisuals();\n\t\t}\n\n\t\t@Override\n\t\tpublic void alpha(float value) {\n\t\t\tsuper.alpha(value);\n\t\t\tfor (Image im : icons){\n\t\t\t\tif (im != null) im.alpha(value);\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void enable(boolean value) {\n\t\t\tsuper.enable(value);\n\t\t\tfor (Image ic : icons){\n\t\t\t\tif (ic != null && ic.alpha() >= 0.3f){\n\t\t\t\t\tic.alpha( value ? 1 : 0.3f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//private\n\n\t}\n\t\n\tpublic static class PickedUpItem extends ItemSprite {\n\t\t\n\t\tprivate static final float DURATION = 0.5f;\n\t\t\n\t\tprivate float startScale;\n\t\tprivate float startX, startY;\n\t\tprivate float endX, endY;\n\t\tprivate float left;\n\t\t\n\t\tpublic PickedUpItem() {\n\t\t\tsuper();\n\t\t\t\n\t\t\toriginToCenter();\n\t\t\t\n\t\t\tactive =\n\t\t\tvisible =\n\t\t\t\tfalse;\n\t\t}\n\t\t\n\t\tpublic void reset( Item item, int cell, float endX, float endY ) {\n\t\t\tview( item );\n\t\t\t\n\t\t\tactive =\n\t\t\tvisible =\n\t\t\t\ttrue;\n\t\t\t\n\t\t\tPointF tile = DungeonTerrainTilemap.raisedTileCenterToWorld(cell);\n\t\t\tPoint screen = Camera.main.cameraToScreen(tile.x, tile.y);\n\t\t\tPointF start = camera().screenToCamera(screen.x, screen.y);\n\t\t\t\n\t\t\tx = this.startX = start.x - width() / 2;\n\t\t\ty = this.startY = start.y - width() / 2;\n\t\t\t\n\t\t\tthis.endX = endX - width() / 2;\n\t\t\tthis.endY = endY - width() / 2;\n\t\t\tleft = DURATION;\n\t\t\t\n\t\t\tscale.set( startScale = Camera.main.zoom / camera().zoom );\n\t\t\t\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void update() {\n\t\t\tsuper.update();\n\t\t\t\n\t\t\tif ((left -= Game.elapsed) <= 0) {\n\t\t\t\t\n\t\t\t\tvisible =\n\t\t\t\tactive =\n\t\t\t\t\tfalse;\n\t\t\t\tif (emitter != null) emitter.on = false;\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tfloat p = left / DURATION;\n\t\t\t\tscale.set( startScale * (float)Math.sqrt( p ) );\n\t\t\t\t\n\t\t\t\tx = startX*p + endX*(1-p);\n\t\t\t\ty = startY*p + endY*(1-p);\n\t\t\t}\n\t\t}\n\t}\n}" }, { "identifier": "DungeonSeed", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/utils/DungeonSeed.java", "snippet": "public class DungeonSeed {\n\n\tpublic static long TOTAL_SEEDS = 5429503678976L; //larges possible seed has a value of 26^9\n\n\t//Seed codes take the form @@@-@@@-@@@ where @ is any letter from A to Z (only uppercase)\n\t//This is effectively a base-26 number system, therefore 26^9 unique seeds are possible.\n\n\t//Seed codes exist to make sharing and inputting seeds easier\n\t//ZZZ-ZZZ-ZZZ is much easier to enter and share than 5,429,503,678,975\n\n\t//generates a random seed, omitting seeds that contain vowels (to minimize real words appearing randomly)\n\t//This means that there are 21^9 = 794,280,046,581 unique seeds that can be randomly generated\n\tpublic static long randomSeed(){\n\t\tLong seed;\n\t\tString seedText;\n\t\tdo {\n\t\t\tseed = Random.Long(TOTAL_SEEDS);\n\t\t\tseedText = convertToCode(seed);\n\t\t} while (seedText.contains(\"A\") || seedText.contains(\"E\") || seedText.contains(\"I\") || seedText.contains(\"O\") || seedText.contains(\"U\"));\n\t\treturn seed;\n\t}\n\n\t//Takes a seed code (@@@@@@@@@) and converts it to the equivalent long value\n\tpublic static long convertFromCode( String code ){\n\t\t//if code is formatted properly, force uppercase\n\t\tif (code.length() == 11 && code.charAt(3) == '-' && code.charAt(7) == '-'){\n\t\t\tcode = code.toUpperCase(Locale.ROOT);\n\t\t}\n\n\t\t//ignore whitespace characters and dashes\n\t\tcode = code.replaceAll(\"[-\\\\s]\", \"\");\n\n\t\tif (code.length() != 9) {\n\t\t\tthrow new IllegalArgumentException(\"codes must be 9 A-Z characters.\");\n\t\t}\n\n\t\tlong result = 0;\n\t\tfor (int i = 8; i >= 0; i--) {\n\t\t\tchar c = code.charAt(i);\n\t\t\tif (c > 'Z' || c < 'A')\n\t\t\t\tthrow new IllegalArgumentException(\"codes must be 9 A-Z characters.\");\n\n\t\t\tresult += (c - 65) * Math.pow(26, (8 - i));\n\t\t}\n\t\treturn result;\n\t}\n\n\t//Takes a long value and converts it to the equivalent seed code\n\tpublic static String convertToCode( long seed ){\n\t\tif (seed < 0 || seed >= TOTAL_SEEDS) {\n\t\t\tthrow new IllegalArgumentException(\"seeds must be within the range [0, TOTAL_SEEDS)\");\n\t\t}\n\n\t\t//this almost gives us the right answer, but its 0-p instead of A-Z\n\t\tString interrim = Long.toString(seed, 26);\n\t\tStringBuilder result = new StringBuilder();\n\n\t\t//so we convert\n\t\tfor (int i = 0; i < 9; i++) {\n\n\t\t\tif (i < interrim.length()){\n\t\t\t\tchar c = interrim.charAt(i);\n\t\t\t\tif (c <= '9') c += 17; //convert 0-9 to A-J\n\t\t\t\telse c -= 22; //convert a-p to K-Z\n\n\t\t\t\tresult.append(c);\n\n\t\t\t} else {\n\t\t\t\tresult.insert(0, 'A'); //pad with A (zeroes) until we reach length of 9\n\n\t\t\t}\n\t\t}\n\n\t\t//insert dashes for readability\n\t\tresult.insert(3, '-');\n\t\tresult.insert(7, '-');\n\n\t\treturn result.toString();\n\t}\n\n\t//Creates a seed from arbitrary user text input\n\tpublic static long convertFromText( String inputText ){\n\t\tif (inputText.isEmpty()) return -1;\n\n\t\t//First see if input is a seed code, use that format if it is\n\t\ttry {\n\t\t\treturn convertFromCode(inputText);\n\t\t} catch (IllegalArgumentException e){\n\n\t\t}\n\n\t\t//Then see if input is a number (ignoring spaces), if so parse as a long seed (with overflow)\n\t\ttry {\n\t\t\treturn Long.parseLong(inputText.replaceAll(\"\\\\s\", \"\")) % TOTAL_SEEDS;\n\t\t} catch (NumberFormatException e){\n\n\t\t}\n\n\t\t//Finally, if the user has entered unformatted text, convert it to a long seed equivalent\n\t\t// This is basically the same as string.hashcode except with long, and overflow\n\t\t// this lets the user input 'fun' seeds, like names or places\n\t\tlong total = 0;\n\t\tfor (char c : inputText.toCharArray()){\n\t\t\ttotal = 31 * total + c;\n\t\t}\n\t\tif (total < 0) total += Long.MAX_VALUE;\n\t\ttotal %= TOTAL_SEEDS;\n\t\treturn total;\n\t}\n\n\n\tpublic static String formatText( String inputText ){\n\t\ttry {\n\t\t\t//if the seed matches a code, then just convert it to using the code system\n\t\t\treturn convertToCode(convertFromCode(inputText));\n\t\t} catch (IllegalArgumentException e){\n\t\t\t//otherwise just return the input text\n\t\t\treturn inputText;\n\t\t}\n\t}\n\n}" }, { "identifier": "Game", "path": "SPD-classes/src/main/java/com/watabou/noosa/Game.java", "snippet": "public class Game implements ApplicationListener {\n\n\tpublic static Game instance;\n\n\t//actual size of the display\n\tpublic static int dispWidth;\n\tpublic static int dispHeight;\n\t\n\t// Size of the EGL surface view\n\tpublic static int width;\n\tpublic static int height;\n\n\t//number of pixels from bottom of view before rendering starts\n\tpublic static int bottomInset;\n\n\t// Density: mdpi=1, hdpi=1.5, xhdpi=2...\n\tpublic static float density = 1;\n\t\n\tpublic static String version;\n\tpublic static int versionCode;\n\t\n\t// Current scene\n\tprotected Scene scene;\n\t// New scene we are going to switch to\n\tprotected Scene requestedScene;\n\t// true if scene switch is requested\n\tprotected boolean requestedReset = true;\n\t// callback to perform logic during scene change\n\tprotected SceneChangeCallback onChange;\n\t// New scene class\n\tprotected static Class<? extends Scene> sceneClass;\n\t\n\tpublic static float timeScale = 1f;\n\tpublic static float elapsed = 0f;\n\tpublic static float timeTotal = 0f;\n\tpublic static long realTime = 0;\n\n\tpublic static InputHandler inputHandler;\n\t\n\tpublic static PlatformSupport platform;\n\t\n\tpublic Game(Class<? extends Scene> c, PlatformSupport platform) {\n\t\tsceneClass = c;\n\t\t\n\t\tinstance = this;\n\t\tthis.platform = platform;\n\t}\n\t\n\t@Override\n\tpublic void create() {\n\t\tdensity = Gdx.graphics.getDensity();\n\t\tif (density == Float.POSITIVE_INFINITY){\n\t\t\tdensity = 100f / 160f; //assume 100PPI if density can't be found\n\t\t}\n\t\tdispHeight = Gdx.graphics.getDisplayMode().height;\n\t\tdispWidth = Gdx.graphics.getDisplayMode().width;\n\n\t\tinputHandler = new InputHandler( Gdx.input );\n\t\tif (ControllerHandler.controllersSupported()){\n\t\t\tControllers.addListener(new ControllerHandler());\n\t\t}\n\n\t\t//refreshes texture and vertex data stored on the gpu\n\t\tversionContextRef = Gdx.graphics.getGLVersion();\n\t\tBlending.useDefault();\n\t\tTextureCache.reload();\n\t\tVertexbuffer.reload();\n\t}\n\n\tprivate GLVersion versionContextRef;\n\t\n\t@Override\n\tpublic void resize(int width, int height) {\n\t\tif (width == 0 || height == 0){\n\t\t\treturn;\n\t\t}\n\n\t\t//If the EGL context was destroyed, we need to refresh some data stored on the GPU.\n\t\t// This checks that by seeing if GLVersion has a new object reference\n\t\tif (versionContextRef != Gdx.graphics.getGLVersion()) {\n\t\t\tversionContextRef = Gdx.graphics.getGLVersion();\n\t\t\tBlending.useDefault();\n\t\t\tTextureCache.reload();\n\t\t\tVertexbuffer.reload();\n\t\t}\n\n\t\theight -= bottomInset;\n\t\tif (height != Game.height || width != Game.width) {\n\n\t\t\tGame.width = width;\n\t\t\tGame.height = height;\n\t\t\t\n\t\t\t//TODO might be better to put this in platform support\n\t\t\tif (Gdx.app.getType() != Application.ApplicationType.Android){\n\t\t\t\tGame.dispWidth = Game.width;\n\t\t\t\tGame.dispHeight = Game.height;\n\t\t\t}\n\t\t\t\n\t\t\tresetScene();\n\t\t}\n\t}\n\n\t//FIXME this is a hack to improve start times on android (first frame is 'cheated' and skips rendering)\n\t//This is mainly to improve stats on google play, as lots of texture refreshing leads to slow warm starts\n\t//Would be nice to accomplish this goal in a less hacky way\n\tprivate boolean justResumed = true;\n\n\t@Override\n\tpublic void render() {\n\t\t//prevents weird rare cases where the app is running twice\n\t\tif (instance != this){\n\t\t\tfinish();\n\t\t\treturn;\n\t\t}\n\n\t\tif (justResumed){\n\t\t\tjustResumed = false;\n\t\t\tif (DeviceCompat.isAndroid()) return;\n\t\t}\n\n\t\tNoosaScript.get().resetCamera();\n\t\tNoosaScriptNoLighting.get().resetCamera();\n\t\tGdx.gl.glDisable(Gdx.gl.GL_SCISSOR_TEST);\n\t\tGdx.gl.glClear(Gdx.gl.GL_COLOR_BUFFER_BIT);\n\t\tdraw();\n\n\t\tGdx.gl.glDisable( Gdx.gl.GL_SCISSOR_TEST );\n\t\t\n\t\tstep();\n\t}\n\t\n\t@Override\n\tpublic void pause() {\n\t\tPointerEvent.clearPointerEvents();\n\t\t\n\t\tif (scene != null) {\n\t\t\tscene.onPause();\n\t\t}\n\t\t\n\t\tScript.reset();\n\t}\n\t\n\t@Override\n\tpublic void resume() {\n\t\tjustResumed = true;\n\t}\n\t\n\tpublic void finish(){\n\t\tGdx.app.exit();\n\t\t\n\t}\n\t\n\tpublic void destroy(){\n\t\tif (scene != null) {\n\t\t\tscene.destroy();\n\t\t\tscene = null;\n\t\t}\n\t\t\n\t\tsceneClass = null;\n\t\tMusic.INSTANCE.stop();\n\t\tSample.INSTANCE.reset();\n\t}\n\t\n\t@Override\n\tpublic void dispose() {\n\t\tdestroy();\n\t}\n\t\n\tpublic static void resetScene() {\n\t\tswitchScene( instance.sceneClass );\n\t}\n\n\tpublic static void switchScene(Class<? extends Scene> c) {\n\t\tswitchScene(c, null);\n\t}\n\t\n\tpublic static void switchScene(Class<? extends Scene> c, SceneChangeCallback callback) {\n\t\tinstance.sceneClass = c;\n\t\tinstance.requestedReset = true;\n\t\tinstance.onChange = callback;\n\t}\n\t\n\tpublic static Scene scene() {\n\t\treturn instance.scene;\n\t}\n\t\n\tprotected void step() {\n\t\t\n\t\tif (requestedReset) {\n\t\t\trequestedReset = false;\n\t\t\t\n\t\t\trequestedScene = Reflection.newInstance(sceneClass);\n\t\t\tif (requestedScene != null){\n\t\t\t\tswitchScene();\n\t\t\t}\n\n\t\t}\n\t\t\n\t\tupdate();\n\t}\n\t\n\tprotected void draw() {\n\t\tif (scene != null) scene.draw();\n\t}\n\t\n\tprotected void switchScene() {\n\n\t\tCamera.reset();\n\t\t\n\t\tif (scene != null) {\n\t\t\tscene.destroy();\n\t\t}\n\t\t//clear any leftover vertex buffers\n\t\tVertexbuffer.clear();\n\t\tscene = requestedScene;\n\t\tif (onChange != null) onChange.beforeCreate();\n\t\tscene.create();\n\t\tif (onChange != null) onChange.afterCreate();\n\t\tonChange = null;\n\t\t\n\t\tGame.elapsed = 0f;\n\t\tGame.timeScale = 1f;\n\t\tGame.timeTotal = 0f;\n\t}\n\n\tprotected void update() {\n\t\tGame.elapsed = Game.timeScale * Gdx.graphics.getDeltaTime();\n\t\tGame.timeTotal += Game.elapsed;\n\t\t\n\t\tGame.realTime = TimeUtils.millis();\n\n\t\tinputHandler.processAllEvents();\n\n\t\tMusic.INSTANCE.update();\n\t\tSample.INSTANCE.update();\n\t\tscene.update();\n\t\tCamera.updateAll();\n\t}\n\t\n\tpublic static void reportException( Throwable tr ) {\n\t\tif (instance != null && Gdx.app != null) {\n\t\t\tinstance.logException(tr);\n\t\t} else {\n\t\t\t//fallback if error happened in initialization\n\t\t\tStringWriter sw = new StringWriter();\n\t\t\tPrintWriter pw = new PrintWriter(sw);\n\t\t\ttr.printStackTrace(pw);\n\t\t\tpw.flush();\n\t\t\tSystem.err.println(sw.toString());\n\t\t}\n\t}\n\t\n\tprotected void logException( Throwable tr ){\n\t\tStringWriter sw = new StringWriter();\n\t\tPrintWriter pw = new PrintWriter(sw);\n\t\ttr.printStackTrace(pw);\n\t\tpw.flush();\n\t\tGdx.app.error(\"GAME\", sw.toString());\n\t}\n\t\n\tpublic static void runOnRenderThread(Callback c){\n\t\tGdx.app.postRunnable(new Runnable() {\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tc.call();\n\t\t\t}\n\t\t});\n\t}\n\t\n\tpublic static void vibrate( int milliseconds ) {\n\t\tplatform.vibrate( milliseconds );\n\t}\n\n\tpublic interface SceneChangeCallback{\n\t\tvoid beforeCreate();\n\t\tvoid afterCreate();\n\t}\n\t\n}" }, { "identifier": "Bundlable", "path": "SPD-classes/src/main/java/com/watabou/utils/Bundlable.java", "snippet": "public interface Bundlable {\n\n\tvoid restoreFromBundle( Bundle bundle );\n\tvoid storeInBundle( Bundle bundle );\n\t\n}" }, { "identifier": "Bundle", "path": "SPD-classes/src/main/java/com/watabou/utils/Bundle.java", "snippet": "public class Bundle {\n\n\tprivate static final String CLASS_NAME = \"__className\";\n\n\tpublic static final String DEFAULT_KEY = \"key\";\n\n\tprivate static HashMap<String,String> aliases = new HashMap<>();\n\n\t/*\n\t\tWARNING: NOT ALL METHODS IN ORG.JSON ARE PRESENT ON ANDROID/IOS!\n\t\tMany methods which work on desktop will cause the game to crash on Android and iOS\n\n\t\tThis is because the Android runtime includes its own version of org.json which does not\n\t\timplement all methods. MobiVM uses the Android runtime and so this applies to iOS as well.\n\n\t\torg.json is very fast (~2x faster than libgdx JSON), which is why the game uses it despite\n\t\tthis dependency conflict.\n\n\t\tSee https://developer.android.com/reference/org/json/package-summary for details on\n\t\twhat methods exist in all versions of org.json. This class is also commented in places\n\t\tWhere Android/iOS force the use of unusual methods.\n\t */\n\tprivate JSONObject data;\n\n\tpublic Bundle() {\n\t\tthis( new JSONObject() );\n\t}\n\n\tpublic String toString() {\n\t\treturn data.toString();\n\t}\n\n\tprivate Bundle( JSONObject data ) {\n\t\tthis.data = data;\n\t}\n\n\tpublic boolean isNull() {\n\t\treturn data == null;\n\t}\n\n\tpublic boolean contains( String key ) {\n\t\treturn !isNull() && !data.isNull( key );\n\t}\n\n\tpublic boolean remove( String key ){\n\t\treturn data.remove(key) != null;\n\t}\n\n\t//JSONObject.keyset() doesn't exist on Android/iOS\n\tpublic ArrayList<String> getKeys(){\n\t\tIterator<String> keys = data.keys();\n\t\tArrayList<String> result = new ArrayList<>();\n\t\twhile (keys.hasNext()){\n\t\t\tresult.add(keys.next());\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic boolean getBoolean( String key ) {\n\t\treturn data.optBoolean( key );\n\t}\n\n\tpublic int getInt( String key ) {\n\t\treturn data.optInt( key );\n\t}\n\n\tpublic long getLong( String key ) {\n\t\treturn data.optLong( key );\n\t}\n\n\tpublic float getFloat( String key ) {\n\t\treturn (float)data.optDouble( key, 0.0 );\n\t}\n\n\tpublic String getString( String key ) {\n\t\treturn data.optString( key );\n\t}\n\n\tpublic Class getClass( String key ) {\n\t\tString clName = getString(key).replace(\"class \", \"\");\n\t\tif (!clName.equals(\"\")){\n\t\t\tif (aliases.containsKey( clName )) {\n\t\t\t\tclName = aliases.get( clName );\n\t\t\t}\n\n\t\t\treturn Reflection.forName( clName );\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic Bundle getBundle( String key ) {\n\t\treturn new Bundle( data.optJSONObject( key ) );\n\t}\n\n\tprivate Bundlable get() {\n\t\tif (data == null) return null;\n\n\t\tString clName = getString( CLASS_NAME );\n\t\tif (aliases.containsKey( clName )) {\n\t\t\tclName = aliases.get( clName );\n\t\t}\n\n\t\tClass<?> cl = Reflection.forName( clName );\n\t\t//Skip none-static inner classes as they can't be instantiated through bundle restoring\n\t\t//Classes which make use of none-static inner classes must manage instantiation manually\n\t\tif (cl != null && (!Reflection.isMemberClass(cl) || Reflection.isStatic(cl))) {\n\t\t\tBundlable object = (Bundlable) Reflection.newInstance(cl);\n\t\t\tif (object != null) {\n\t\t\t\tobject.restoreFromBundle(this);\n\t\t\t\treturn object;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic Bundlable get( String key ) {\n\t\treturn getBundle( key ).get();\n\t}\n\n\tpublic <E extends Enum<E>> E getEnum( String key, Class<E> enumClass ) {\n\t\ttry {\n\t\t\treturn Enum.valueOf( enumClass, data.getString( key ) );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn enumClass.getEnumConstants()[0];\n\t\t} catch (IllegalArgumentException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn enumClass.getEnumConstants()[0];\n\t\t}\n\t}\n\n\tpublic int[] getIntArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tint[] result = new int[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = array.getInt( i );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic long[] getLongArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tlong[] result = new long[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = array.getLong( i );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic float[] getFloatArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tfloat[] result = new float[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = (float)array.optDouble( i, 0.0 );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic boolean[] getBooleanArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tboolean[] result = new boolean[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = array.getBoolean( i );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic String[] getStringArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tString[] result = new String[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = array.getString( i );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Class[] getClassArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tClass[] result = new Class[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tString clName = array.getString( i ).replace(\"class \", \"\");\n\t\t\t\tif (aliases.containsKey( clName )) {\n\t\t\t\t\tclName = aliases.get( clName );\n\t\t\t\t}\n\t\t\t\tClass cl = Reflection.forName( clName );\n\t\t\t\tresult[i] = cl;\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Bundle[] getBundleArray(){\n\t\treturn getBundleArray( DEFAULT_KEY );\n\t}\n\n\tpublic Bundle[] getBundleArray( String key ){\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tBundle[] result = new Bundle[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = new Bundle( array.getJSONObject( i ) );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Collection<Bundlable> getCollection( String key ) {\n\n\t\tArrayList<Bundlable> list = new ArrayList<>();\n\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tfor (int i=0; i < array.length(); i++) {\n\t\t\t\tBundlable O = new Bundle( array.getJSONObject( i ) ).get();\n\t\t\t\tif (O != null) list.add( O );\n\t\t\t}\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\n\t\treturn list;\n\t}\n\n\tpublic void put( String key, boolean value ) {\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, int value ) {\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, long value ) {\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, float value ) {\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, String value ) {\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, Class value ){\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, Bundle bundle ) {\n\t\ttry {\n\t\t\tdata.put( key, bundle.data );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, Bundlable object ) {\n\t\tif (object != null) {\n\t\t\ttry {\n\t\t\t\tBundle bundle = new Bundle();\n\t\t\t\tbundle.put( CLASS_NAME, object.getClass().getName() );\n\t\t\t\tobject.storeInBundle( bundle );\n\t\t\t\tdata.put( key, bundle.data );\n\t\t\t} catch (JSONException e) {\n\t\t\t\tGame.reportException(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void put( String key, Enum<?> value ) {\n\t\tif (value != null) {\n\t\t\ttry {\n\t\t\t\tdata.put( key, value.name() );\n\t\t\t} catch (JSONException e) {\n\t\t\t\tGame.reportException(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void put( String key, int[] array ) {\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i] );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, long[] array ) {\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i] );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, float[] array ) {\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i] );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, boolean[] array ) {\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i] );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, String[] array ) {\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i] );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, Class[] array ){\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i].getName() );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, Collection<? extends Bundlable> collection ) {\n\t\tJSONArray array = new JSONArray();\n\t\tfor (Bundlable object : collection) {\n\t\t\t//Skip none-static inner classes as they can't be instantiated through bundle restoring\n\t\t\t//Classes which make use of none-static inner classes must manage instantiation manually\n\t\t\tif (object != null) {\n\t\t\t\tClass cl = object.getClass();\n\t\t\t\tif ((!Reflection.isMemberClass(cl) || Reflection.isStatic(cl))) {\n\t\t\t\t\tBundle bundle = new Bundle();\n\t\t\t\t\tbundle.put(CLASS_NAME, cl.getName());\n\t\t\t\t\tobject.storeInBundle(bundle);\n\t\t\t\t\tarray.put(bundle.data);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tdata.put( key, array );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\t//useful to turn this off for save data debugging.\n\tprivate static final boolean compressByDefault = true;\n\n\tprivate static final int GZIP_BUFFER = 1024*4; //4 kb\n\n\tpublic static Bundle read( InputStream stream ) throws IOException {\n\n\t\ttry {\n\t\t\tif (!stream.markSupported()){\n\t\t\t\tstream = new BufferedInputStream( stream, 2 );\n\t\t\t}\n\n\t\t\t//determines if we're reading a regular, or compressed file\n\t\t\tstream.mark( 2 );\n\t\t\tbyte[] header = new byte[2];\n\t\t\tstream.read( header );\n\t\t\tstream.reset();\n\n\t\t\t//GZIP header is 0x1f8b\n\t\t\tif( header[ 0 ] == (byte) 0x1f && header[ 1 ] == (byte) 0x8b ) {\n\t\t\t\tstream = new GZIPInputStream( stream, GZIP_BUFFER );\n\t\t\t}\n\n\t\t\t//JSONTokenizer only has a string-based constructor on Android/iOS\n\t\t\tBufferedReader reader = new BufferedReader( new InputStreamReader( stream ));\n\t\t\tStringBuilder jsonBuilder = new StringBuilder();\n\n\t\t\tString line;\n\t\t\twhile ((line = reader.readLine()) != null) {\n\t\t\t\tjsonBuilder.append(line);\n\t\t\t\tjsonBuilder.append(\"\\n\");\n\t\t\t}\n\t\t\tString jsonString = jsonBuilder.toString();\n\n\t\t\tObject json;\n\t\t\ttry {\n\t\t\t\tjson = new JSONTokener(jsonString).nextValue();\n\t\t\t} catch (Exception e){\n\t\t\t\t//if the string can't be tokenized, it may be written by v1.1.X, which used libGDX JSON.\n\t\t\t\t// Some of these are written in a 'minified' format, some have duplicate keys.\n\t\t\t\t// We read them in with the libGDX JSON code, fix duplicates, write as full JSON\n\t\t\t\t// and then try to read again with org.json\n\t\t\t\tGame.reportException(e);\n\t\t\t\tJsonValue gdxJSON = new JsonReader().parse(jsonString);\n\t\t\t\tkillDuplicateKeysInLibGDXJSON(gdxJSON);\n\t\t\t\tjson = new JSONTokener(gdxJSON.prettyPrint(JsonWriter.OutputType.json, 0)).nextValue();\n\t\t\t}\n\t\t\treader.close();\n\n\t\t\t//if the data is an array, put it in a fresh object with the default key\n\t\t\tif (json instanceof JSONArray){\n\t\t\t\tjson = new JSONObject().put( DEFAULT_KEY, json );\n\t\t\t}\n\n\t\t\treturn new Bundle( (JSONObject) json );\n\t\t} catch (Exception e) {\n\t\t\tGame.reportException(e);\n\t\t\tthrow new IOException();\n\t\t}\n\t}\n\n\tprivate static void killDuplicateKeysInLibGDXJSON(JsonValue val){\n\t\tHashSet<String> keys = new HashSet<>();\n\t\twhile(val != null) {\n\t\t\tif (val.name != null && keys.contains(val.name)){\n\t\t\t\t//delete the duplicate key\n\t\t\t\tval.prev.next = val.next;\n\t\t\t\tif (val.next != null) val.next.prev = val.prev;\n\t\t\t\tval.parent.size--;\n\t\t\t} else {\n\t\t\t\tkeys.add(val.name);\n\t\t\t\tif (val.child != null){\n\t\t\t\t\tkillDuplicateKeysInLibGDXJSON(val.child);\n\t\t\t\t}\n\t\t\t}\n\t\t\tval = val.next;\n\t\t}\n\t}\n\n\tpublic static boolean write( Bundle bundle, OutputStream stream ){\n\t\treturn write(bundle, stream, compressByDefault);\n\t}\n\n\tpublic static boolean write( Bundle bundle, OutputStream stream, boolean compressed ) {\n\t\ttry {\n\t\t\tBufferedWriter writer;\n\t\t\tif (compressed) writer = new BufferedWriter( new OutputStreamWriter( new GZIPOutputStream(stream, GZIP_BUFFER ) ) );\n\t\t\telse writer = new BufferedWriter( new OutputStreamWriter( stream ) );\n\n\t\t\t//JSONObject.write does not exist on Android/iOS\n\t\t\twriter.write(bundle.data.toString());\n\t\t\twriter.close();\n\n\t\t\treturn true;\n\t\t} catch (IOException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic static void addAlias( Class<?> cl, String alias ) {\n\t\taliases.put( alias, cl.getName() );\n\t}\n\t\n}" }, { "identifier": "FileUtils", "path": "SPD-classes/src/main/java/com/watabou/utils/FileUtils.java", "snippet": "public class FileUtils {\n\t\n\t// Helper methods for setting/using a default base path and file address mode\n\t\n\tprivate static Files.FileType defaultFileType = null;\n\tprivate static String defaultPath = \"\";\n\t\n\tpublic static void setDefaultFileProperties( Files.FileType type, String path ){\n\t\tdefaultFileType = type;\n\t\tdefaultPath = path;\n\t}\n\t\n\tpublic static FileHandle getFileHandle( String name ){\n\t\treturn getFileHandle( defaultFileType, defaultPath, name );\n\t}\n\t\n\tpublic static FileHandle getFileHandle( Files.FileType type, String name ){\n\t\treturn getFileHandle( type, \"\", name );\n\t}\n\t\n\tpublic static FileHandle getFileHandle( Files.FileType type, String basePath, String name ){\n\t\tswitch (type){\n\t\t\tcase Classpath:\n\t\t\t\treturn Gdx.files.classpath( basePath + name );\n\t\t\tcase Internal:\n\t\t\t\treturn Gdx.files.internal( basePath + name );\n\t\t\tcase External:\n\t\t\t\treturn Gdx.files.external( basePath + name );\n\t\t\tcase Absolute:\n\t\t\t\treturn Gdx.files.absolute( basePath + name );\n\t\t\tcase Local:\n\t\t\t\treturn Gdx.files.local( basePath + name );\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t}\n\t}\n\t\n\t// Files\n\n\t//looks to see if there is any evidence of interrupted saving\n\tpublic static boolean cleanTempFiles(){\n\t\treturn cleanTempFiles(\"\");\n\t}\n\n\tpublic static boolean cleanTempFiles( String dirName ){\n\t\tFileHandle dir = getFileHandle(dirName);\n\t\tboolean foundTemp = false;\n\t\tfor (FileHandle file : dir.list()){\n\t\t\tif (file.isDirectory()){\n\t\t\t\tfoundTemp = cleanTempFiles(dirName + file.name()) || foundTemp;\n\t\t\t} else {\n\t\t\t\tif (file.name().endsWith(\".tmp\")){\n\t\t\t\t\tFileHandle temp = file;\n\t\t\t\t\tFileHandle original = getFileHandle( defaultFileType, \"\", temp.path().replace(\".tmp\", \"\") );\n\n\t\t\t\t\t//replace the base file with the temp one if base is invalid or temp is valid and newer\n\t\t\t\t\ttry {\n\t\t\t\t\t\tbundleFromStream(temp.read());\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tbundleFromStream(original.read());\n\n\t\t\t\t\t\t\tif (temp.lastModified() > original.lastModified()) {\n\t\t\t\t\t\t\t\ttemp.moveTo(original);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\ttemp.delete();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\ttemp.moveTo(original);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\ttemp.delete();\n\t\t\t\t\t}\n\n\t\t\t\t\tfoundTemp = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn foundTemp;\n\t}\n\t\n\tpublic static boolean fileExists( String name ){\n\t\tFileHandle file = getFileHandle( name );\n\t\treturn file.exists() && !file.isDirectory() && file.length() > 0;\n\t}\n\n\t//returns length of a file in bytes, or 0 if file does not exist\n\tpublic static long fileLength( String name ){\n\t\tFileHandle file = getFileHandle( name );\n\t\tif (!file.exists() || file.isDirectory()){\n\t\t\treturn 0;\n\t\t} else {\n\t\t\treturn file.length();\n\t\t}\n\t}\n\t\n\tpublic static boolean deleteFile( String name ){\n\t\treturn getFileHandle( name ).delete();\n\t}\n\n\t//replaces a file with junk data, for as many bytes as given\n\t//This is helpful as some cloud sync systems do not persist deleted, empty, or zeroed files\n\tpublic static void overwriteFile( String name, int bytes ){\n\t\tbyte[] data = new byte[bytes];\n\t\tArrays.fill(data, (byte)1);\n\t\tgetFileHandle( name ).writeBytes(data, false);\n\t}\n\t\n\t// Directories\n\t\n\tpublic static boolean dirExists( String name ){\n\t\tFileHandle dir = getFileHandle( name );\n\t\treturn dir.exists() && dir.isDirectory();\n\t}\n\t\n\tpublic static boolean deleteDir( String name ){\n\t\tFileHandle dir = getFileHandle( name );\n\t\t\n\t\tif (dir == null || !dir.isDirectory()){\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn dir.deleteDirectory();\n\t\t}\n\t}\n\n\tpublic static ArrayList<String> filesInDir( String name ){\n\t\tFileHandle dir = getFileHandle( name );\n\t\tArrayList result = new ArrayList();\n\t\tif (dir != null && dir.isDirectory()){\n\t\t\tfor (FileHandle file : dir.list()){\n\t\t\t\tresult.add(file.name());\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\t\n\t// bundle reading\n\t\n\t//only works for base path\n\tpublic static Bundle bundleFromFile( String fileName ) throws IOException{\n\t\ttry {\n\t\t\tFileHandle file = getFileHandle( fileName );\n\t\t\treturn bundleFromStream(file.read());\n\t\t} catch (GdxRuntimeException e){\n\t\t\t//game classes expect an IO exception, so wrap the GDX exception in that\n\t\t\tthrow new IOException(e);\n\t\t}\n\t}\n\t\n\tprivate static Bundle bundleFromStream( InputStream input ) throws IOException{\n\t\tBundle bundle = Bundle.read( input );\n\t\tinput.close();\n\t\treturn bundle;\n\t}\n\t\n\t// bundle writing\n\t\n\t//only works for base path\n\tpublic static void bundleToFile( String fileName, Bundle bundle ) throws IOException{\n\t\ttry {\n\t\t\tFileHandle file = getFileHandle(fileName);\n\n\t\t\t//write to a temp file, then move the files.\n\t\t\t// This helps prevent save corruption if writing is interrupted\n\t\t\tif (file.exists()){\n\t\t\t\tFileHandle temp = getFileHandle(fileName + \".tmp\");\n\t\t\t\tbundleToStream(temp.write(false), bundle);\n\t\t\t\tfile.delete();\n\t\t\t\ttemp.moveTo(file);\n\t\t\t} else {\n\t\t\t\tbundleToStream(file.write(false), bundle);\n\t\t\t}\n\n\t\t} catch (GdxRuntimeException e){\n\t\t\t//game classes expect an IO exception, so wrap the GDX exception in that\n\t\t\tthrow new IOException(e);\n\t\t}\n\t}\n\t\n\tprivate static void bundleToStream( OutputStream output, Bundle bundle ) throws IOException{\n\t\tBundle.write( bundle, output );\n\t\toutput.close();\n\t}\n\n}" } ]
import com.shatteredpixel.shatteredpixeldungeon.actors.Actor; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Belongings; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.HeroClass; import com.shatteredpixel.shatteredpixeldungeon.items.Generator; import com.shatteredpixel.shatteredpixeldungeon.items.Item; import com.shatteredpixel.shatteredpixeldungeon.items.bags.Bag; import com.shatteredpixel.shatteredpixeldungeon.items.potions.Potion; import com.shatteredpixel.shatteredpixeldungeon.items.quest.CorpseDust; import com.shatteredpixel.shatteredpixeldungeon.items.rings.Ring; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.Scroll; import com.shatteredpixel.shatteredpixeldungeon.journal.Notes; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.ui.QuickSlotButton; import com.shatteredpixel.shatteredpixeldungeon.ui.Toolbar; import com.shatteredpixel.shatteredpixeldungeon.utils.DungeonSeed; import com.watabou.noosa.Game; import com.watabou.utils.Bundlable; import com.watabou.utils.Bundle; import com.watabou.utils.FileUtils; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.LinkedHashMap; import java.util.Locale; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern;
91,670
Statistics.totalQuestScore = 0; for (int i : Statistics.questScores){ if (i > 0) Statistics.totalQuestScore += i; } Statistics.winMultiplier = 1f; if (Statistics.gameWon) Statistics.winMultiplier += 1f; if (Statistics.ascended) Statistics.winMultiplier += 0.5f; //pre v1.3.0 runs have different score calculations //only progress and treasure score, and they are each up to 50% bigger //win multiplier is a simple 2x if run was a win, challenge multi is the same as 1.3.0 } else { Statistics.progressScore = Dungeon.hero.lvl * Statistics.deepestFloor * 100; Statistics.treasureScore = Math.min(Statistics.goldCollected, 30_000); Statistics.exploreScore = Statistics.totalBossScore = Statistics.totalQuestScore = 0; Statistics.winMultiplier = Statistics.gameWon ? 2 : 1; } Statistics.chalMultiplier = (float)Math.pow(1.25, Challenges.activeChallenges()); Statistics.chalMultiplier = Math.round(Statistics.chalMultiplier*20f)/20f; Statistics.totalScore = Statistics.progressScore + Statistics.treasureScore + Statistics.exploreScore + Statistics.totalBossScore + Statistics.totalQuestScore; Statistics.totalScore *= Statistics.winMultiplier * Statistics.chalMultiplier; return Statistics.totalScore; } public static final String HERO = "hero"; public static final String STATS = "stats"; public static final String BADGES = "badges"; public static final String HANDLERS = "handlers"; public static final String CHALLENGES = "challenges"; public static final String GAME_VERSION = "game_version"; public static final String SEED = "seed"; public static final String CUSTOM_SEED = "custom_seed"; public static final String DAILY = "daily"; public static final String DAILY_REPLAY = "daily_replay"; public void saveGameData(Record rec){ if (Dungeon.hero == null){ rec.gameData = null; return; } rec.gameData = new Bundle(); Belongings belongings = Dungeon.hero.belongings; //save the hero and belongings ArrayList<Item> allItems = (ArrayList<Item>) belongings.backpack.items.clone(); //remove items that won't show up in the rankings screen for (Item item : belongings.backpack.items.toArray( new Item[0])) { if (item instanceof Bag){ for (Item bagItem : ((Bag) item).items.toArray( new Item[0])){ if (Dungeon.quickslot.contains(bagItem) && !Dungeon.quickslot.contains(item)){ belongings.backpack.items.add(bagItem); } } } if (!Dungeon.quickslot.contains(item)) { belongings.backpack.items.remove(item); } } //remove all buffs (ones tied to equipment will be re-applied) for(Buff b : Dungeon.hero.buffs()){ Dungeon.hero.remove(b); } rec.gameData.put( HERO, Dungeon.hero ); //save stats Bundle stats = new Bundle(); Statistics.storeInBundle(stats); rec.gameData.put( STATS, stats); //save badges Bundle badges = new Bundle(); Badges.saveLocal(badges); rec.gameData.put( BADGES, badges); //save handler information Bundle handler = new Bundle(); Scroll.saveSelectively(handler, belongings.backpack.items); Potion.saveSelectively(handler, belongings.backpack.items); //include potentially worn rings if (belongings.misc != null) belongings.backpack.items.add(belongings.misc); if (belongings.ring != null) belongings.backpack.items.add(belongings.ring); Ring.saveSelectively(handler, belongings.backpack.items); rec.gameData.put( HANDLERS, handler); //restore items now that we're done saving belongings.backpack.items = allItems; //save challenges rec.gameData.put( CHALLENGES, Dungeon.challenges ); rec.gameData.put( GAME_VERSION, Dungeon.initialVersion ); rec.gameData.put( SEED, Dungeon.seed ); rec.gameData.put( CUSTOM_SEED, Dungeon.customSeedText ); rec.gameData.put( DAILY, Dungeon.daily ); rec.gameData.put( DAILY_REPLAY, Dungeon.dailyReplay ); } public void loadGameData(Record rec){ Bundle data = rec.gameData; Actor.clear(); Dungeon.hero = null; Dungeon.level = null; Generator.fullReset();
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon; public enum Rankings { INSTANCE; public static final int TABLE_SIZE = 11; public static final String RANKINGS_FILE = "rankings.dat"; public ArrayList<Record> records; public int lastRecord; public int totalNumber; public int wonNumber; //The number of runs which are only present locally, not in the cloud public int localTotal; public int localWon; public Record latestDaily; public Record latestDailyReplay = null; //not stored, only meant to be temp public LinkedHashMap<Long, Integer> dailyScoreHistory = new LinkedHashMap<>(); public void submit( boolean win, Object cause ) { load(); Record rec = new Record(); //we trim version to just the numbers, ignoring alpha/beta, etc. Pattern p = Pattern.compile("\\d+\\.\\d+\\.\\d+"); Matcher m = p.matcher(ShatteredPixelDungeon.version); if (m.find()) { rec.version = "v" + m.group(); } else { rec.version = ""; } DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT); rec.date = format.format(new Date(Game.realTime)); rec.cause = cause instanceof Class ? (Class)cause : cause.getClass(); rec.win = win; rec.heroClass = Dungeon.hero.heroClass; rec.armorTier = Dungeon.hero.tier(); rec.herolevel = Dungeon.hero.lvl; if (Statistics.highestAscent == 0){ rec.depth = Statistics.deepestFloor; rec.ascending = false; } else { rec.depth = Statistics.highestAscent; rec.ascending = true; } rec.score = calculateScore(); rec.customSeed = Dungeon.customSeedText; rec.daily = Dungeon.daily; Badges.validateHighScore( rec.score ); INSTANCE.saveGameData(rec); rec.gameID = UUID.randomUUID().toString(); if (rec.daily){ if (Dungeon.dailyReplay){ latestDailyReplay = rec; return; } latestDaily = rec; if (Dungeon.seed <= DungeonSeed.TOTAL_SEEDS) { dailyScoreHistory.put(Dungeon.seed, rec.score); } else { dailyScoreHistory.put(Dungeon.seed - DungeonSeed.TOTAL_SEEDS, rec.score); } save(); return; } records.add( rec ); Collections.sort( records, scoreComparator ); lastRecord = records.indexOf( rec ); int size = records.size(); while (size > TABLE_SIZE) { if (lastRecord == size - 1) { records.remove( size - 2 ); lastRecord--; } else { records.remove( size - 1 ); } size = records.size(); } if (rec.customSeed.isEmpty()) { totalNumber++; if (win) { wonNumber++; } } Badges.validateGamesPlayed(); save(); } private int score( boolean win ) { return (Statistics.goldCollected + Dungeon.hero.lvl * (win ? 31 : Dungeon.depth ) * 100) * (win ? 2 : 1); } //assumes a ranking is loaded, or game is ending public int calculateScore(){ if (Dungeon.initialVersion > ShatteredPixelDungeon.v1_2_3){ Statistics.progressScore = Dungeon.hero.lvl * Statistics.deepestFloor * 65; Statistics.progressScore = Math.min(Statistics.progressScore, 50_000); if (Statistics.heldItemValue == 0) { for (Item i : Dungeon.hero.belongings) { Statistics.heldItemValue += i.value(); if (i instanceof CorpseDust && Statistics.deepestFloor >= 10){ // in case player kept the corpse dust, for a necromancer run Statistics.questScores[1] = 2000; } } } Statistics.treasureScore = Statistics.goldCollected + Statistics.heldItemValue; Statistics.treasureScore = Math.min(Statistics.treasureScore, 20_000); Statistics.exploreScore = 0; int scorePerFloor = Statistics.floorsExplored.size * 50; for (Boolean b : Statistics.floorsExplored.valueList()){ if (b) Statistics.exploreScore += scorePerFloor; } Statistics.totalBossScore = 0; for (int i : Statistics.bossScores){ if (i > 0) Statistics.totalBossScore += i; } Statistics.totalQuestScore = 0; for (int i : Statistics.questScores){ if (i > 0) Statistics.totalQuestScore += i; } Statistics.winMultiplier = 1f; if (Statistics.gameWon) Statistics.winMultiplier += 1f; if (Statistics.ascended) Statistics.winMultiplier += 0.5f; //pre v1.3.0 runs have different score calculations //only progress and treasure score, and they are each up to 50% bigger //win multiplier is a simple 2x if run was a win, challenge multi is the same as 1.3.0 } else { Statistics.progressScore = Dungeon.hero.lvl * Statistics.deepestFloor * 100; Statistics.treasureScore = Math.min(Statistics.goldCollected, 30_000); Statistics.exploreScore = Statistics.totalBossScore = Statistics.totalQuestScore = 0; Statistics.winMultiplier = Statistics.gameWon ? 2 : 1; } Statistics.chalMultiplier = (float)Math.pow(1.25, Challenges.activeChallenges()); Statistics.chalMultiplier = Math.round(Statistics.chalMultiplier*20f)/20f; Statistics.totalScore = Statistics.progressScore + Statistics.treasureScore + Statistics.exploreScore + Statistics.totalBossScore + Statistics.totalQuestScore; Statistics.totalScore *= Statistics.winMultiplier * Statistics.chalMultiplier; return Statistics.totalScore; } public static final String HERO = "hero"; public static final String STATS = "stats"; public static final String BADGES = "badges"; public static final String HANDLERS = "handlers"; public static final String CHALLENGES = "challenges"; public static final String GAME_VERSION = "game_version"; public static final String SEED = "seed"; public static final String CUSTOM_SEED = "custom_seed"; public static final String DAILY = "daily"; public static final String DAILY_REPLAY = "daily_replay"; public void saveGameData(Record rec){ if (Dungeon.hero == null){ rec.gameData = null; return; } rec.gameData = new Bundle(); Belongings belongings = Dungeon.hero.belongings; //save the hero and belongings ArrayList<Item> allItems = (ArrayList<Item>) belongings.backpack.items.clone(); //remove items that won't show up in the rankings screen for (Item item : belongings.backpack.items.toArray( new Item[0])) { if (item instanceof Bag){ for (Item bagItem : ((Bag) item).items.toArray( new Item[0])){ if (Dungeon.quickslot.contains(bagItem) && !Dungeon.quickslot.contains(item)){ belongings.backpack.items.add(bagItem); } } } if (!Dungeon.quickslot.contains(item)) { belongings.backpack.items.remove(item); } } //remove all buffs (ones tied to equipment will be re-applied) for(Buff b : Dungeon.hero.buffs()){ Dungeon.hero.remove(b); } rec.gameData.put( HERO, Dungeon.hero ); //save stats Bundle stats = new Bundle(); Statistics.storeInBundle(stats); rec.gameData.put( STATS, stats); //save badges Bundle badges = new Bundle(); Badges.saveLocal(badges); rec.gameData.put( BADGES, badges); //save handler information Bundle handler = new Bundle(); Scroll.saveSelectively(handler, belongings.backpack.items); Potion.saveSelectively(handler, belongings.backpack.items); //include potentially worn rings if (belongings.misc != null) belongings.backpack.items.add(belongings.misc); if (belongings.ring != null) belongings.backpack.items.add(belongings.ring); Ring.saveSelectively(handler, belongings.backpack.items); rec.gameData.put( HANDLERS, handler); //restore items now that we're done saving belongings.backpack.items = allItems; //save challenges rec.gameData.put( CHALLENGES, Dungeon.challenges ); rec.gameData.put( GAME_VERSION, Dungeon.initialVersion ); rec.gameData.put( SEED, Dungeon.seed ); rec.gameData.put( CUSTOM_SEED, Dungeon.customSeedText ); rec.gameData.put( DAILY, Dungeon.daily ); rec.gameData.put( DAILY_REPLAY, Dungeon.dailyReplay ); } public void loadGameData(Record rec){ Bundle data = rec.gameData; Actor.clear(); Dungeon.hero = null; Dungeon.level = null; Generator.fullReset();
Notes.reset();
12
2023-11-27 05:56:58+00:00
128k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/tests/org/jfree/chart/renderer/xy/YIntervalRendererTest.java
[ { "identifier": "JFreeChart", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/JFreeChart.java", "snippet": "public class JFreeChart implements Drawable, TitleChangeListener,\r\n PlotChangeListener, Serializable, Cloneable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -3470703747817429120L;\r\n\r\n /** Information about the project. */\r\n public static final ProjectInfo INFO = new JFreeChartInfo();\r\n\r\n /** The default font for titles. */\r\n public static final Font DEFAULT_TITLE_FONT\r\n = new Font(\"SansSerif\", Font.BOLD, 18);\r\n\r\n /** The default background color. */\r\n public static final Paint DEFAULT_BACKGROUND_PAINT\r\n = UIManager.getColor(\"Panel.background\");\r\n\r\n /** The default background image. */\r\n public static final Image DEFAULT_BACKGROUND_IMAGE = null;\r\n\r\n /** The default background image alignment. */\r\n public static final int DEFAULT_BACKGROUND_IMAGE_ALIGNMENT = Align.FIT;\r\n\r\n /** The default background image alpha. */\r\n public static final float DEFAULT_BACKGROUND_IMAGE_ALPHA = 0.5f;\r\n\r\n /**\r\n * The key for a rendering hint that can suppress the generation of a \r\n * shadow effect when drawing the chart. The hint value must be a \r\n * Boolean.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static final RenderingHints.Key KEY_SUPPRESS_SHADOW_GENERATION\r\n = new RenderingHints.Key(0) {\r\n @Override\r\n public boolean isCompatibleValue(Object val) {\r\n return val instanceof Boolean;\r\n }\r\n };\r\n \r\n /**\r\n * Rendering hints that will be used for chart drawing. This should never\r\n * be <code>null</code>.\r\n */\r\n private transient RenderingHints renderingHints;\r\n\r\n /** A flag that controls whether or not the chart border is drawn. */\r\n private boolean borderVisible;\r\n\r\n /** The stroke used to draw the chart border (if visible). */\r\n private transient Stroke borderStroke;\r\n\r\n /** The paint used to draw the chart border (if visible). */\r\n private transient Paint borderPaint;\r\n\r\n /** The padding between the chart border and the chart drawing area. */\r\n private RectangleInsets padding;\r\n\r\n /** The chart title (optional). */\r\n private TextTitle title;\r\n\r\n /**\r\n * The chart subtitles (zero, one or many). This field should never be\r\n * <code>null</code>.\r\n */\r\n private List subtitles;\r\n\r\n /** Draws the visual representation of the data. */\r\n private Plot plot;\r\n\r\n /** Paint used to draw the background of the chart. */\r\n private transient Paint backgroundPaint;\r\n\r\n /** An optional background image for the chart. */\r\n private transient Image backgroundImage; // todo: not serialized yet\r\n\r\n /** The alignment for the background image. */\r\n private int backgroundImageAlignment = Align.FIT;\r\n\r\n /** The alpha transparency for the background image. */\r\n private float backgroundImageAlpha = 0.5f;\r\n\r\n /** Storage for registered change listeners. */\r\n private transient EventListenerList changeListeners;\r\n\r\n /** Storage for registered progress listeners. */\r\n private transient EventListenerList progressListeners;\r\n\r\n /**\r\n * A flag that can be used to enable/disable notification of chart change\r\n * events.\r\n */\r\n private boolean notify;\r\n\r\n /**\r\n * Creates a new chart based on the supplied plot. The chart will have\r\n * a legend added automatically, but no title (although you can easily add\r\n * one later).\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(Plot plot) {\r\n this(null, null, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. A default font\r\n * ({@link #DEFAULT_TITLE_FONT}) is used for the title, and the chart will\r\n * have a legend added automatically.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(String title, Plot plot) {\r\n this(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. The\r\n * <code>createLegend</code> argument specifies whether or not a legend\r\n * should be added to the chart.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param titleFont the font for displaying the chart title\r\n * (<code>null</code> permitted).\r\n * @param plot controller of the visual representation of the data\r\n * (<code>null</code> not permitted).\r\n * @param createLegend a flag indicating whether or not a legend should\r\n * be created for the chart.\r\n */\r\n public JFreeChart(String title, Font titleFont, Plot plot,\r\n boolean createLegend) {\r\n\r\n ParamChecks.nullNotPermitted(plot, \"plot\");\r\n\r\n // create storage for listeners...\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.notify = true; // default is to notify listeners when the\r\n // chart changes\r\n\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n // added the following hint because of \r\n // http://stackoverflow.com/questions/7785082/\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n this.borderVisible = false;\r\n this.borderStroke = new BasicStroke(1.0f);\r\n this.borderPaint = Color.black;\r\n\r\n this.padding = RectangleInsets.ZERO_INSETS;\r\n\r\n this.plot = plot;\r\n plot.addChangeListener(this);\r\n\r\n this.subtitles = new ArrayList();\r\n\r\n // create a legend, if requested...\r\n if (createLegend) {\r\n LegendTitle legend = new LegendTitle(this.plot);\r\n legend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));\r\n legend.setFrame(new LineBorder());\r\n legend.setBackgroundPaint(Color.white);\r\n legend.setPosition(RectangleEdge.BOTTOM);\r\n this.subtitles.add(legend);\r\n legend.addChangeListener(this);\r\n }\r\n\r\n // add the chart title, if one has been specified...\r\n if (title != null) {\r\n if (titleFont == null) {\r\n titleFont = DEFAULT_TITLE_FONT;\r\n }\r\n this.title = new TextTitle(title, titleFont);\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n this.backgroundPaint = DEFAULT_BACKGROUND_PAINT;\r\n\r\n this.backgroundImage = DEFAULT_BACKGROUND_IMAGE;\r\n this.backgroundImageAlignment = DEFAULT_BACKGROUND_IMAGE_ALIGNMENT;\r\n this.backgroundImageAlpha = DEFAULT_BACKGROUND_IMAGE_ALPHA;\r\n\r\n }\r\n\r\n /**\r\n * Returns the collection of rendering hints for the chart.\r\n *\r\n * @return The rendering hints for the chart (never <code>null</code>).\r\n *\r\n * @see #setRenderingHints(RenderingHints)\r\n */\r\n public RenderingHints getRenderingHints() {\r\n return this.renderingHints;\r\n }\r\n\r\n /**\r\n * Sets the rendering hints for the chart. These will be added (using the\r\n * {@code Graphics2D.addRenderingHints()} method) near the start of the\r\n * {@code JFreeChart.draw()} method.\r\n *\r\n * @param renderingHints the rendering hints ({@code null} not permitted).\r\n *\r\n * @see #getRenderingHints()\r\n */\r\n public void setRenderingHints(RenderingHints renderingHints) {\r\n ParamChecks.nullNotPermitted(renderingHints, \"renderingHints\");\r\n this.renderingHints = renderingHints;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setBorderVisible(boolean)\r\n */\r\n public boolean isBorderVisible() {\r\n return this.borderVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isBorderVisible()\r\n */\r\n public void setBorderVisible(boolean visible) {\r\n this.borderVisible = visible;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the chart border (if visible).\r\n *\r\n * @return The border stroke.\r\n *\r\n * @see #setBorderStroke(Stroke)\r\n */\r\n public Stroke getBorderStroke() {\r\n return this.borderStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the chart border (if visible).\r\n *\r\n * @param stroke the stroke.\r\n *\r\n * @see #getBorderStroke()\r\n */\r\n public void setBorderStroke(Stroke stroke) {\r\n this.borderStroke = stroke;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the chart border (if visible).\r\n *\r\n * @return The border paint.\r\n *\r\n * @see #setBorderPaint(Paint)\r\n */\r\n public Paint getBorderPaint() {\r\n return this.borderPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the chart border (if visible).\r\n *\r\n * @param paint the paint.\r\n *\r\n * @see #getBorderPaint()\r\n */\r\n public void setBorderPaint(Paint paint) {\r\n this.borderPaint = paint;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the padding between the chart border and the chart drawing area.\r\n *\r\n * @return The padding (never <code>null</code>).\r\n *\r\n * @see #setPadding(RectangleInsets)\r\n */\r\n public RectangleInsets getPadding() {\r\n return this.padding;\r\n }\r\n\r\n /**\r\n * Sets the padding between the chart border and the chart drawing area,\r\n * and sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param padding the padding (<code>null</code> not permitted).\r\n *\r\n * @see #getPadding()\r\n */\r\n public void setPadding(RectangleInsets padding) {\r\n ParamChecks.nullNotPermitted(padding, \"padding\");\r\n this.padding = padding;\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the main chart title. Very often a chart will have just one\r\n * title, so we make this case simple by providing accessor methods for\r\n * the main title. However, multiple titles are supported - see the\r\n * {@link #addSubtitle(Title)} method.\r\n *\r\n * @return The chart title (possibly <code>null</code>).\r\n *\r\n * @see #setTitle(TextTitle)\r\n */\r\n public TextTitle getTitle() {\r\n return this.title;\r\n }\r\n\r\n /**\r\n * Sets the main title for the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners. If you do not want a title for the\r\n * chart, set it to <code>null</code>. If you want more than one title on\r\n * a chart, use the {@link #addSubtitle(Title)} method.\r\n *\r\n * @param title the title (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(TextTitle title) {\r\n if (this.title != null) {\r\n this.title.removeChangeListener(this);\r\n }\r\n this.title = title;\r\n if (title != null) {\r\n title.addChangeListener(this);\r\n }\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Sets the chart title and sends a {@link ChartChangeEvent} to all\r\n * registered listeners. This is a convenience method that ends up calling\r\n * the {@link #setTitle(TextTitle)} method. If there is an existing title,\r\n * its text is updated, otherwise a new title using the default font is\r\n * added to the chart. If <code>text</code> is <code>null</code> the chart\r\n * title is set to <code>null</code>.\r\n *\r\n * @param text the title text (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(String text) {\r\n if (text != null) {\r\n if (this.title == null) {\r\n setTitle(new TextTitle(text, JFreeChart.DEFAULT_TITLE_FONT));\r\n }\r\n else {\r\n this.title.setText(text);\r\n }\r\n }\r\n else {\r\n setTitle((TextTitle) null);\r\n }\r\n }\r\n\r\n /**\r\n * Adds a legend to the plot and sends a {@link ChartChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param legend the legend (<code>null</code> not permitted).\r\n *\r\n * @see #removeLegend()\r\n */\r\n public void addLegend(LegendTitle legend) {\r\n addSubtitle(legend);\r\n }\r\n\r\n /**\r\n * Returns the legend for the chart, if there is one. Note that a chart\r\n * can have more than one legend - this method returns the first.\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #getLegend(int)\r\n */\r\n public LegendTitle getLegend() {\r\n return getLegend(0);\r\n }\r\n\r\n /**\r\n * Returns the nth legend for a chart, or <code>null</code>.\r\n *\r\n * @param index the legend index (zero-based).\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #addLegend(LegendTitle)\r\n */\r\n public LegendTitle getLegend(int index) {\r\n int seen = 0;\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title subtitle = (Title) iterator.next();\r\n if (subtitle instanceof LegendTitle) {\r\n if (seen == index) {\r\n return (LegendTitle) subtitle;\r\n }\r\n else {\r\n seen++;\r\n }\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Removes the first legend in the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @see #getLegend()\r\n */\r\n public void removeLegend() {\r\n removeSubtitle(getLegend());\r\n }\r\n\r\n /**\r\n * Returns the list of subtitles for the chart.\r\n *\r\n * @return The subtitle list (possibly empty, but never <code>null</code>).\r\n *\r\n * @see #setSubtitles(List)\r\n */\r\n public List getSubtitles() {\r\n return new ArrayList(this.subtitles);\r\n }\r\n\r\n /**\r\n * Sets the title list for the chart (completely replaces any existing\r\n * titles) and sends a {@link ChartChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param subtitles the new list of subtitles (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public void setSubtitles(List subtitles) {\r\n if (subtitles == null) {\r\n throw new NullPointerException(\"Null 'subtitles' argument.\");\r\n }\r\n setNotify(false);\r\n clearSubtitles();\r\n Iterator iterator = subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n if (t != null) {\r\n addSubtitle(t);\r\n }\r\n }\r\n setNotify(true); // this fires a ChartChangeEvent\r\n }\r\n\r\n /**\r\n * Returns the number of titles for the chart.\r\n *\r\n * @return The number of titles for the chart.\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public int getSubtitleCount() {\r\n return this.subtitles.size();\r\n }\r\n\r\n /**\r\n * Returns a chart subtitle.\r\n *\r\n * @param index the index of the chart subtitle (zero based).\r\n *\r\n * @return A chart subtitle.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public Title getSubtitle(int index) {\r\n if ((index < 0) || (index >= getSubtitleCount())) {\r\n throw new IllegalArgumentException(\"Index out of range.\");\r\n }\r\n return (Title) this.subtitles.get(index);\r\n }\r\n\r\n /**\r\n * Adds a chart subtitle, and notifies registered listeners that the chart\r\n * has been modified.\r\n *\r\n * @param subtitle the subtitle (<code>null</code> not permitted).\r\n *\r\n * @see #getSubtitle(int)\r\n */\r\n public void addSubtitle(Title subtitle) {\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Adds a subtitle at a particular position in the subtitle list, and sends\r\n * a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param index the index (in the range 0 to {@link #getSubtitleCount()}).\r\n * @param subtitle the subtitle to add (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.6\r\n */\r\n public void addSubtitle(int index, Title subtitle) {\r\n if (index < 0 || index > getSubtitleCount()) {\r\n throw new IllegalArgumentException(\r\n \"The 'index' argument is out of range.\");\r\n }\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(index, subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Clears all subtitles from the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void clearSubtitles() {\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n t.removeChangeListener(this);\r\n }\r\n this.subtitles.clear();\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Removes the specified subtitle and sends a {@link ChartChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param title the title.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void removeSubtitle(Title title) {\r\n this.subtitles.remove(title);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the plot for the chart. The plot is a class responsible for\r\n * coordinating the visual representation of the data, including the axes\r\n * (if any).\r\n *\r\n * @return The plot.\r\n */\r\n public Plot getPlot() {\r\n return this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as a {@link CategoryPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link CategoryPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public CategoryPlot getCategoryPlot() {\r\n return (CategoryPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as an {@link XYPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link XYPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public XYPlot getXYPlot() {\r\n return (XYPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns a flag that indicates whether or not anti-aliasing is used when\r\n * the chart is drawn.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAntiAlias(boolean)\r\n */\r\n public boolean getAntiAlias() {\r\n Object val = this.renderingHints.get(RenderingHints.KEY_ANTIALIASING);\r\n return RenderingHints.VALUE_ANTIALIAS_ON.equals(val);\r\n }\r\n\r\n /**\r\n * Sets a flag that indicates whether or not anti-aliasing is used when the\r\n * chart is drawn.\r\n * <P>\r\n * Anti-aliasing usually improves the appearance of charts, but is slower.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #getAntiAlias()\r\n */\r\n public void setAntiAlias(boolean flag) {\r\n Object hint = flag ? RenderingHints.VALUE_ANTIALIAS_ON \r\n : RenderingHints.VALUE_ANTIALIAS_OFF;\r\n this.renderingHints.put(RenderingHints.KEY_ANTIALIASING, hint);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the current value stored in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING}.\r\n *\r\n * @return The hint value (possibly <code>null</code>).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public Object getTextAntiAlias() {\r\n return this.renderingHints.get(RenderingHints.KEY_TEXT_ANTIALIASING);\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} to either\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_ON} or\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_OFF}, then sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public void setTextAntiAlias(boolean flag) {\r\n if (flag) {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\r\n }\r\n else {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);\r\n }\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param val the new value (<code>null</code> permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(boolean)\r\n */\r\n public void setTextAntiAlias(Object val) {\r\n this.renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, val);\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the paint used for the chart background.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundPaint(Paint)\r\n */\r\n public Paint getBackgroundPaint() {\r\n return this.backgroundPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to fill the chart background and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundPaint()\r\n */\r\n public void setBackgroundPaint(Paint paint) {\r\n\r\n if (this.backgroundPaint != null) {\r\n if (!this.backgroundPaint.equals(paint)) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (paint != null) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image for the chart, or <code>null</code> if\r\n * there is no image.\r\n *\r\n * @return The image (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundImage(Image)\r\n */\r\n public Image getBackgroundImage() {\r\n return this.backgroundImage;\r\n }\r\n\r\n /**\r\n * Sets the background image for the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param image the image (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundImage()\r\n */\r\n public void setBackgroundImage(Image image) {\r\n\r\n if (this.backgroundImage != null) {\r\n if (!this.backgroundImage.equals(image)) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (image != null) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image alignment. Alignment constants are defined\r\n * in the <code>org.jfree.ui.Align</code> class in the JCommon class\r\n * library.\r\n *\r\n * @return The alignment.\r\n *\r\n * @see #setBackgroundImageAlignment(int)\r\n */\r\n public int getBackgroundImageAlignment() {\r\n return this.backgroundImageAlignment;\r\n }\r\n\r\n /**\r\n * Sets the background alignment. Alignment options are defined by the\r\n * {@link org.jfree.ui.Align} class.\r\n *\r\n * @param alignment the alignment.\r\n *\r\n * @see #getBackgroundImageAlignment()\r\n */\r\n public void setBackgroundImageAlignment(int alignment) {\r\n if (this.backgroundImageAlignment != alignment) {\r\n this.backgroundImageAlignment = alignment;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha-transparency for the chart's background image.\r\n *\r\n * @return The alpha-transparency.\r\n *\r\n * @see #setBackgroundImageAlpha(float)\r\n */\r\n public float getBackgroundImageAlpha() {\r\n return this.backgroundImageAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha-transparency for the chart's background image.\r\n * Registered listeners are notified that the chart has been changed.\r\n *\r\n * @param alpha the alpha value.\r\n *\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void setBackgroundImageAlpha(float alpha) {\r\n\r\n if (this.backgroundImageAlpha != alpha) {\r\n this.backgroundImageAlpha = alpha;\r\n fireChartChanged();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not change events are sent to\r\n * registered listeners.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNotify(boolean)\r\n */\r\n public boolean isNotify() {\r\n return this.notify;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not listeners receive\r\n * {@link ChartChangeEvent} notifications.\r\n *\r\n * @param notify a boolean.\r\n *\r\n * @see #isNotify()\r\n */\r\n public void setNotify(boolean notify) {\r\n this.notify = notify;\r\n // if the flag is being set to true, there may be queued up changes...\r\n if (notify) {\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area) {\r\n draw(g2, area, null, null);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer). This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D area, ChartRenderingInfo info) {\r\n draw(g2, area, null, info);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param chartArea the area within which the chart should be drawn.\r\n * @param anchor the anchor point (in Java2D space) for the chart\r\n * (<code>null</code> permitted).\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D chartArea, Point2D anchor,\r\n ChartRenderingInfo info) {\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_STARTED, 0));\r\n \r\n EntityCollection entities = null;\r\n // record the chart area, if info is requested...\r\n if (info != null) {\r\n info.clear();\r\n info.setChartArea(chartArea);\r\n entities = info.getEntityCollection();\r\n }\r\n if (entities != null) {\r\n entities.add(new JFreeChartEntity((Rectangle2D) chartArea.clone(),\r\n this));\r\n }\r\n\r\n // ensure no drawing occurs outside chart area...\r\n Shape savedClip = g2.getClip();\r\n g2.clip(chartArea);\r\n\r\n g2.addRenderingHints(this.renderingHints);\r\n\r\n // draw the chart background...\r\n if (this.backgroundPaint != null) {\r\n g2.setPaint(this.backgroundPaint);\r\n g2.fill(chartArea);\r\n }\r\n\r\n if (this.backgroundImage != null) {\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundImageAlpha));\r\n Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,\r\n this.backgroundImage.getWidth(null),\r\n this.backgroundImage.getHeight(null));\r\n Align.align(dest, chartArea, this.backgroundImageAlignment);\r\n g2.drawImage(this.backgroundImage, (int) dest.getX(),\r\n (int) dest.getY(), (int) dest.getWidth(),\r\n (int) dest.getHeight(), null);\r\n g2.setComposite(originalComposite);\r\n }\r\n\r\n if (isBorderVisible()) {\r\n Paint paint = getBorderPaint();\r\n Stroke stroke = getBorderStroke();\r\n if (paint != null && stroke != null) {\r\n Rectangle2D borderArea = new Rectangle2D.Double(\r\n chartArea.getX(), chartArea.getY(),\r\n chartArea.getWidth() - 1.0, chartArea.getHeight()\r\n - 1.0);\r\n g2.setPaint(paint);\r\n g2.setStroke(stroke);\r\n g2.draw(borderArea);\r\n }\r\n }\r\n\r\n // draw the title and subtitles...\r\n Rectangle2D nonTitleArea = new Rectangle2D.Double();\r\n nonTitleArea.setRect(chartArea);\r\n this.padding.trim(nonTitleArea);\r\n\r\n if (this.title != null && this.title.isVisible()) {\r\n EntityCollection e = drawTitle(this.title, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title currentTitle = (Title) iterator.next();\r\n if (currentTitle.isVisible()) {\r\n EntityCollection e = drawTitle(currentTitle, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n }\r\n\r\n Rectangle2D plotArea = nonTitleArea;\r\n\r\n // draw the plot (axes and data visualisation)\r\n PlotRenderingInfo plotInfo = null;\r\n if (info != null) {\r\n plotInfo = info.getPlotInfo();\r\n }\r\n this.plot.draw(g2, plotArea, anchor, null, plotInfo);\r\n\r\n g2.setClip(savedClip);\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_FINISHED, 100));\r\n }\r\n\r\n /**\r\n * Creates a rectangle that is aligned to the frame.\r\n *\r\n * @param dimensions the dimensions for the rectangle.\r\n * @param frame the frame to align to.\r\n * @param hAlign the horizontal alignment.\r\n * @param vAlign the vertical alignment.\r\n *\r\n * @return A rectangle.\r\n */\r\n private Rectangle2D createAlignedRectangle2D(Size2D dimensions,\r\n Rectangle2D frame, HorizontalAlignment hAlign,\r\n VerticalAlignment vAlign) {\r\n double x = Double.NaN;\r\n double y = Double.NaN;\r\n if (hAlign == HorizontalAlignment.LEFT) {\r\n x = frame.getX();\r\n }\r\n else if (hAlign == HorizontalAlignment.CENTER) {\r\n x = frame.getCenterX() - (dimensions.width / 2.0);\r\n }\r\n else if (hAlign == HorizontalAlignment.RIGHT) {\r\n x = frame.getMaxX() - dimensions.width;\r\n }\r\n if (vAlign == VerticalAlignment.TOP) {\r\n y = frame.getY();\r\n }\r\n else if (vAlign == VerticalAlignment.CENTER) {\r\n y = frame.getCenterY() - (dimensions.height / 2.0);\r\n }\r\n else if (vAlign == VerticalAlignment.BOTTOM) {\r\n y = frame.getMaxY() - dimensions.height;\r\n }\r\n\r\n return new Rectangle2D.Double(x, y, dimensions.width,\r\n dimensions.height);\r\n }\r\n\r\n /**\r\n * Draws a title. The title should be drawn at the top, bottom, left or\r\n * right of the specified area, and the area should be updated to reflect\r\n * the amount of space used by the title.\r\n *\r\n * @param t the title (<code>null</code> not permitted).\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param area the chart area, excluding any existing titles\r\n * (<code>null</code> not permitted).\r\n * @param entities a flag that controls whether or not an entity\r\n * collection is returned for the title.\r\n *\r\n * @return An entity collection for the title (possibly <code>null</code>).\r\n */\r\n protected EntityCollection drawTitle(Title t, Graphics2D g2,\r\n Rectangle2D area, boolean entities) {\r\n\r\n ParamChecks.nullNotPermitted(t, \"t\");\r\n ParamChecks.nullNotPermitted(area, \"area\");\r\n Rectangle2D titleArea;\r\n RectangleEdge position = t.getPosition();\r\n double ww = area.getWidth();\r\n if (ww <= 0.0) {\r\n return null;\r\n }\r\n double hh = area.getHeight();\r\n if (hh <= 0.0) {\r\n return null;\r\n }\r\n RectangleConstraint constraint = new RectangleConstraint(ww,\r\n new Range(0.0, ww), LengthConstraintType.RANGE, hh,\r\n new Range(0.0, hh), LengthConstraintType.RANGE);\r\n Object retValue = null;\r\n BlockParams p = new BlockParams();\r\n p.setGenerateEntities(entities);\r\n if (position == RectangleEdge.TOP) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.TOP);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), Math.min(area.getY() + size.height,\r\n area.getMaxY()), area.getWidth(), Math.max(area.getHeight()\r\n - size.height, 0));\r\n }\r\n else if (position == RectangleEdge.BOTTOM) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.BOTTOM);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth(),\r\n area.getHeight() - size.height);\r\n }\r\n else if (position == RectangleEdge.RIGHT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.RIGHT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n\r\n else if (position == RectangleEdge.LEFT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.LEFT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX() + size.width, area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n else {\r\n throw new RuntimeException(\"Unrecognised title position.\");\r\n }\r\n EntityCollection result = null;\r\n if (retValue instanceof EntityBlockResult) {\r\n EntityBlockResult ebr = (EntityBlockResult) retValue;\r\n result = ebr.getEntityCollection();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height) {\r\n return createBufferedImage(width, height, null);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n ChartRenderingInfo info) {\r\n return createBufferedImage(width, height, BufferedImage.TYPE_INT_ARGB,\r\n info);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param imageType the image type.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n int imageType,\r\n ChartRenderingInfo info) {\r\n BufferedImage image = new BufferedImage(width, height, imageType);\r\n Graphics2D g2 = image.createGraphics();\r\n draw(g2, new Rectangle2D.Double(0, 0, width, height), null, info);\r\n g2.dispose();\r\n return image;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param imageWidth the image width.\r\n * @param imageHeight the image height.\r\n * @param drawWidth the width for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param drawHeight the height for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param info optional object for collection chart dimension and entity\r\n * information.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int imageWidth,\r\n int imageHeight,\r\n double drawWidth,\r\n double drawHeight,\r\n ChartRenderingInfo info) {\r\n\r\n BufferedImage image = new BufferedImage(imageWidth, imageHeight,\r\n BufferedImage.TYPE_INT_ARGB);\r\n Graphics2D g2 = image.createGraphics();\r\n double scaleX = imageWidth / drawWidth;\r\n double scaleY = imageHeight / drawHeight;\r\n AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);\r\n g2.transform(st);\r\n draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,\r\n info);\r\n g2.dispose();\r\n return image;\r\n\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the chart. JFreeChart is not a UI component, so\r\n * some other object (for example, {@link ChartPanel}) needs to capture\r\n * the click event and pass it onto the JFreeChart object.\r\n * If you are not using JFreeChart in a client application, then this\r\n * method is not required.\r\n *\r\n * @param x x-coordinate of the click (in Java2D space).\r\n * @param y y-coordinate of the click (in Java2D space).\r\n * @param info contains chart dimension and entity information\r\n * (<code>null</code> not permitted).\r\n */\r\n public void handleClick(int x, int y, ChartRenderingInfo info) {\r\n\r\n // pass the click on to the plot...\r\n // rely on the plot to post a plot change event and redraw the chart...\r\n this.plot.handleClick(x, y, info.getPlotInfo());\r\n\r\n }\r\n\r\n /**\r\n * Registers an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted).\r\n *\r\n * @see #removeChangeListener(ChartChangeListener)\r\n */\r\n public void addChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.add(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted)\r\n *\r\n * @see #addChangeListener(ChartChangeListener)\r\n */\r\n public void removeChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.remove(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a default {@link ChartChangeEvent} to all registered listeners.\r\n * <P>\r\n * This method is for convenience only.\r\n */\r\n public void fireChartChanged() {\r\n ChartChangeEvent event = new ChartChangeEvent(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartChangeEvent event) {\r\n if (this.notify) {\r\n Object[] listeners = this.changeListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartChangeListener.class) {\r\n ((ChartChangeListener) listeners[i + 1]).chartChanged(\r\n event);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Registers an object for notification of progress events relating to the\r\n * chart.\r\n *\r\n * @param listener the object being registered.\r\n *\r\n * @see #removeProgressListener(ChartProgressListener)\r\n */\r\n public void addProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.add(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the object being deregistered.\r\n *\r\n * @see #addProgressListener(ChartProgressListener)\r\n */\r\n public void removeProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.remove(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartProgressEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartProgressEvent event) {\r\n\r\n Object[] listeners = this.progressListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartProgressListener.class) {\r\n ((ChartProgressListener) listeners[i + 1]).chartProgress(event);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Receives notification that a chart title has changed, and passes this\r\n * on to registered listeners.\r\n *\r\n * @param event information about the chart title change.\r\n */\r\n @Override\r\n public void titleChanged(TitleChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Receives notification that the plot has changed, and passes this on to\r\n * registered listeners.\r\n *\r\n * @param event information about the plot change.\r\n */\r\n @Override\r\n public void plotChanged(PlotChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Tests this chart for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof JFreeChart)) {\r\n return false;\r\n }\r\n JFreeChart that = (JFreeChart) obj;\r\n if (!this.renderingHints.equals(that.renderingHints)) {\r\n return false;\r\n }\r\n if (this.borderVisible != that.borderVisible) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.borderStroke, that.borderStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.borderPaint, that.borderPaint)) {\r\n return false;\r\n }\r\n if (!this.padding.equals(that.padding)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.title, that.title)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.subtitles, that.subtitles)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.plot, that.plot)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(\r\n this.backgroundPaint, that.backgroundPaint\r\n )) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundImage,\r\n that.backgroundImage)) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlignment != that.backgroundImageAlignment) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlpha != that.backgroundImageAlpha) {\r\n return false;\r\n }\r\n if (this.notify != that.notify) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.borderStroke, stream);\r\n SerialUtilities.writePaint(this.borderPaint, stream);\r\n SerialUtilities.writePaint(this.backgroundPaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.borderStroke = SerialUtilities.readStroke(stream);\r\n this.borderPaint = SerialUtilities.readPaint(stream);\r\n this.backgroundPaint = SerialUtilities.readPaint(stream);\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n // register as a listener with sub-components...\r\n if (this.title != null) {\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n getSubtitle(i).addChangeListener(this);\r\n }\r\n this.plot.addChangeListener(this);\r\n }\r\n\r\n /**\r\n * Prints information about JFreeChart to standard output.\r\n *\r\n * @param args no arguments are honored.\r\n */\r\n public static void main(String[] args) {\r\n System.out.println(JFreeChart.INFO.toString());\r\n }\r\n\r\n /**\r\n * Clones the object, and takes care of listeners.\r\n * Note: caller shall register its own listeners on cloned graph.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the chart is not cloneable.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n JFreeChart chart = (JFreeChart) super.clone();\r\n\r\n chart.renderingHints = (RenderingHints) this.renderingHints.clone();\r\n // private boolean borderVisible;\r\n // private transient Stroke borderStroke;\r\n // private transient Paint borderPaint;\r\n\r\n if (this.title != null) {\r\n chart.title = (TextTitle) this.title.clone();\r\n chart.title.addChangeListener(chart);\r\n }\r\n\r\n chart.subtitles = new ArrayList();\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n Title subtitle = (Title) getSubtitle(i).clone();\r\n chart.subtitles.add(subtitle);\r\n subtitle.addChangeListener(chart);\r\n }\r\n\r\n if (this.plot != null) {\r\n chart.plot = (Plot) this.plot.clone();\r\n chart.plot.addChangeListener(chart);\r\n }\r\n\r\n chart.progressListeners = new EventListenerList();\r\n chart.changeListeners = new EventListenerList();\r\n return chart;\r\n }\r\n\r\n}\r" }, { "identifier": "LegendItem", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/LegendItem.java", "snippet": "public class LegendItem implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -797214582948827144L;\r\n\r\n /**\r\n * The dataset.\r\n *\r\n * @since 1.0.6\r\n */\r\n private Dataset dataset;\r\n\r\n /**\r\n * The series key.\r\n *\r\n * @since 1.0.6\r\n */\r\n private Comparable seriesKey;\r\n\r\n /** The dataset index. */\r\n private int datasetIndex;\r\n\r\n /** The series index. */\r\n private int series;\r\n\r\n /** The label. */\r\n private String label;\r\n\r\n /**\r\n * The label font ({@code null} is permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n private Font labelFont;\r\n\r\n /**\r\n * The label paint ({@code null} is permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n private transient Paint labelPaint;\r\n\r\n /** The attributed label (if null, fall back to the regular label). */\r\n private transient AttributedString attributedLabel;\r\n\r\n /**\r\n * The description (not currently used - could be displayed as a tool tip).\r\n */\r\n private String description;\r\n\r\n /** The tool tip text. */\r\n private String toolTipText;\r\n\r\n /** The url text. */\r\n private String urlText;\r\n\r\n /** A flag that controls whether or not the shape is visible. */\r\n private boolean shapeVisible;\r\n\r\n /** The shape. */\r\n private transient Shape shape;\r\n\r\n /** A flag that controls whether or not the shape is filled. */\r\n private boolean shapeFilled;\r\n\r\n /** The paint. */\r\n private transient Paint fillPaint;\r\n\r\n /**\r\n * A gradient paint transformer.\r\n *\r\n * @since 1.0.4\r\n */\r\n private GradientPaintTransformer fillPaintTransformer;\r\n\r\n /** A flag that controls whether or not the shape outline is visible. */\r\n private boolean shapeOutlineVisible;\r\n\r\n /** The outline paint. */\r\n private transient Paint outlinePaint;\r\n\r\n /** The outline stroke. */\r\n private transient Stroke outlineStroke;\r\n\r\n /** A flag that controls whether or not the line is visible. */\r\n private boolean lineVisible;\r\n\r\n /** The line. */\r\n private transient Shape line;\r\n\r\n /** The stroke. */\r\n private transient Stroke lineStroke;\r\n\r\n /** The line paint. */\r\n private transient Paint linePaint;\r\n\r\n /**\r\n * The shape must be non-null for a LegendItem - if no shape is required,\r\n * use this.\r\n */\r\n private static final Shape UNUSED_SHAPE = new Line2D.Float();\r\n\r\n /**\r\n * The stroke must be non-null for a LegendItem - if no stroke is required,\r\n * use this.\r\n */\r\n private static final Stroke UNUSED_STROKE = new BasicStroke(0.0f);\r\n\r\n /**\r\n * Creates a legend item with the specified label. The remaining\r\n * attributes take default values.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n *\r\n * @since 1.0.10\r\n */\r\n public LegendItem(String label) {\r\n this(label, Color.black);\r\n }\r\n\r\n /**\r\n * Creates a legend item with the specified label and fill paint. The\r\n * remaining attributes take default values.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n * @param paint the paint ({@code null} not permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public LegendItem(String label, Paint paint) {\r\n this(label, null, null, null, new Rectangle2D.Double(-4.0, -4.0, 8.0,\r\n 8.0), paint);\r\n }\r\n\r\n /**\r\n * Creates a legend item with a filled shape. The shape is not outlined,\r\n * and no line is visible.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n * @param description the description ({@code null} permitted).\r\n * @param toolTipText the tool tip text ({@code null} permitted).\r\n * @param urlText the URL text ({@code null} permitted).\r\n * @param shape the shape ({@code null} not permitted).\r\n * @param fillPaint the paint used to fill the shape ({@code null}\r\n * not permitted).\r\n */\r\n public LegendItem(String label, String description,\r\n String toolTipText, String urlText,\r\n Shape shape, Paint fillPaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ true, shape,\r\n /* shape filled = */ true, fillPaint,\r\n /* shape outlined */ false, Color.black, UNUSED_STROKE,\r\n /* line visible */ false, UNUSED_SHAPE, UNUSED_STROKE,\r\n Color.black);\r\n\r\n }\r\n\r\n /**\r\n * Creates a legend item with a filled and outlined shape.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n * @param description the description ({@code null} permitted).\r\n * @param toolTipText the tool tip text ({@code null} permitted).\r\n * @param urlText the URL text ({@code null} permitted).\r\n * @param shape the shape ({@code null} not permitted).\r\n * @param fillPaint the paint used to fill the shape ({@code null}\r\n * not permitted).\r\n * @param outlineStroke the outline stroke ({@code null} not\r\n * permitted).\r\n * @param outlinePaint the outline paint ({@code null} not\r\n * permitted).\r\n */\r\n public LegendItem(String label, String description, String toolTipText, \r\n String urlText, Shape shape, Paint fillPaint, Stroke outlineStroke, \r\n Paint outlinePaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ true, shape,\r\n /* shape filled = */ true, fillPaint,\r\n /* shape outlined = */ true, outlinePaint, outlineStroke,\r\n /* line visible */ false, UNUSED_SHAPE, UNUSED_STROKE,\r\n Color.black);\r\n\r\n }\r\n\r\n /**\r\n * Creates a legend item using a line.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n * @param description the description ({@code null} permitted).\r\n * @param toolTipText the tool tip text ({@code null} permitted).\r\n * @param urlText the URL text ({@code null} permitted).\r\n * @param line the line ({@code null} not permitted).\r\n * @param lineStroke the line stroke ({@code null} not permitted).\r\n * @param linePaint the line paint ({@code null} not permitted).\r\n */\r\n public LegendItem(String label, String description, String toolTipText, \r\n String urlText, Shape line, Stroke lineStroke, Paint linePaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ false, UNUSED_SHAPE,\r\n /* shape filled = */ false, Color.black,\r\n /* shape outlined = */ false, Color.black, UNUSED_STROKE,\r\n /* line visible = */ true, line, lineStroke, linePaint);\r\n }\r\n\r\n /**\r\n * Creates a new legend item.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n * @param description the description (not currently used,\r\n * <code>null</code> permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text (<code>null</code> permitted).\r\n * @param shapeVisible a flag that controls whether or not the shape is\r\n * displayed.\r\n * @param shape the shape (<code>null</code> permitted).\r\n * @param shapeFilled a flag that controls whether or not the shape is\r\n * filled.\r\n * @param fillPaint the fill paint (<code>null</code> not permitted).\r\n * @param shapeOutlineVisible a flag that controls whether or not the\r\n * shape is outlined.\r\n * @param outlinePaint the outline paint (<code>null</code> not permitted).\r\n * @param outlineStroke the outline stroke (<code>null</code> not\r\n * permitted).\r\n * @param lineVisible a flag that controls whether or not the line is\r\n * visible.\r\n * @param line the line.\r\n * @param lineStroke the stroke (<code>null</code> not permitted).\r\n * @param linePaint the line paint (<code>null</code> not permitted).\r\n */\r\n public LegendItem(String label, String description,\r\n String toolTipText, String urlText,\r\n boolean shapeVisible, Shape shape,\r\n boolean shapeFilled, Paint fillPaint,\r\n boolean shapeOutlineVisible, Paint outlinePaint,\r\n Stroke outlineStroke,\r\n boolean lineVisible, Shape line,\r\n Stroke lineStroke, Paint linePaint) {\r\n\r\n ParamChecks.nullNotPermitted(label, \"label\");\r\n ParamChecks.nullNotPermitted(fillPaint, \"fillPaint\");\r\n ParamChecks.nullNotPermitted(lineStroke, \"lineStroke\");\r\n ParamChecks.nullNotPermitted(outlinePaint, \"outlinePaint\");\r\n ParamChecks.nullNotPermitted(outlineStroke, \"outlineStroke\");\r\n this.label = label;\r\n this.labelPaint = null;\r\n this.attributedLabel = null;\r\n this.description = description;\r\n this.shapeVisible = shapeVisible;\r\n this.shape = shape;\r\n this.shapeFilled = shapeFilled;\r\n this.fillPaint = fillPaint;\r\n this.fillPaintTransformer = new StandardGradientPaintTransformer();\r\n this.shapeOutlineVisible = shapeOutlineVisible;\r\n this.outlinePaint = outlinePaint;\r\n this.outlineStroke = outlineStroke;\r\n this.lineVisible = lineVisible;\r\n this.line = line;\r\n this.lineStroke = lineStroke;\r\n this.linePaint = linePaint;\r\n this.toolTipText = toolTipText;\r\n this.urlText = urlText;\r\n }\r\n\r\n /**\r\n * Creates a legend item with a filled shape. The shape is not outlined,\r\n * and no line is visible.\r\n *\r\n * @param label the label (<code>null</code> not permitted).\r\n * @param description the description (<code>null</code> permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text (<code>null</code> permitted).\r\n * @param shape the shape (<code>null</code> not permitted).\r\n * @param fillPaint the paint used to fill the shape (<code>null</code>\r\n * not permitted).\r\n */\r\n public LegendItem(AttributedString label, String description,\r\n String toolTipText, String urlText,\r\n Shape shape, Paint fillPaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ true, shape,\r\n /* shape filled = */ true, fillPaint,\r\n /* shape outlined = */ false, Color.black, UNUSED_STROKE,\r\n /* line visible = */ false, UNUSED_SHAPE, UNUSED_STROKE,\r\n Color.black);\r\n\r\n }\r\n\r\n /**\r\n * Creates a legend item with a filled and outlined shape.\r\n *\r\n * @param label the label (<code>null</code> not permitted).\r\n * @param description the description (<code>null</code> permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text (<code>null</code> permitted).\r\n * @param shape the shape (<code>null</code> not permitted).\r\n * @param fillPaint the paint used to fill the shape (<code>null</code>\r\n * not permitted).\r\n * @param outlineStroke the outline stroke (<code>null</code> not\r\n * permitted).\r\n * @param outlinePaint the outline paint (<code>null</code> not\r\n * permitted).\r\n */\r\n public LegendItem(AttributedString label, String description,\r\n String toolTipText, String urlText,\r\n Shape shape, Paint fillPaint,\r\n Stroke outlineStroke, Paint outlinePaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ true, shape,\r\n /* shape filled = */ true, fillPaint,\r\n /* shape outlined = */ true, outlinePaint, outlineStroke,\r\n /* line visible = */ false, UNUSED_SHAPE, UNUSED_STROKE,\r\n Color.black);\r\n }\r\n\r\n /**\r\n * Creates a legend item using a line.\r\n *\r\n * @param label the label (<code>null</code> not permitted).\r\n * @param description the description (<code>null</code> permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text (<code>null</code> permitted).\r\n * @param line the line (<code>null</code> not permitted).\r\n * @param lineStroke the line stroke (<code>null</code> not permitted).\r\n * @param linePaint the line paint (<code>null</code> not permitted).\r\n */\r\n public LegendItem(AttributedString label, String description,\r\n String toolTipText, String urlText,\r\n Shape line, Stroke lineStroke, Paint linePaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ false, UNUSED_SHAPE,\r\n /* shape filled = */ false, Color.black,\r\n /* shape outlined = */ false, Color.black, UNUSED_STROKE,\r\n /* line visible = */ true, line, lineStroke, linePaint);\r\n }\r\n\r\n /**\r\n * Creates a new legend item.\r\n *\r\n * @param label the label (<code>null</code> not permitted).\r\n * @param description the description (not currently used,\r\n * <code>null</code> permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text (<code>null</code> permitted).\r\n * @param shapeVisible a flag that controls whether or not the shape is\r\n * displayed.\r\n * @param shape the shape (<code>null</code> permitted).\r\n * @param shapeFilled a flag that controls whether or not the shape is\r\n * filled.\r\n * @param fillPaint the fill paint (<code>null</code> not permitted).\r\n * @param shapeOutlineVisible a flag that controls whether or not the\r\n * shape is outlined.\r\n * @param outlinePaint the outline paint (<code>null</code> not permitted).\r\n * @param outlineStroke the outline stroke (<code>null</code> not\r\n * permitted).\r\n * @param lineVisible a flag that controls whether or not the line is\r\n * visible.\r\n * @param line the line (<code>null</code> not permitted).\r\n * @param lineStroke the stroke (<code>null</code> not permitted).\r\n * @param linePaint the line paint (<code>null</code> not permitted).\r\n */\r\n public LegendItem(AttributedString label, String description,\r\n String toolTipText, String urlText,\r\n boolean shapeVisible, Shape shape,\r\n boolean shapeFilled, Paint fillPaint,\r\n boolean shapeOutlineVisible, Paint outlinePaint,\r\n Stroke outlineStroke,\r\n boolean lineVisible, Shape line, Stroke lineStroke,\r\n Paint linePaint) {\r\n\r\n ParamChecks.nullNotPermitted(label, \"label\");\r\n ParamChecks.nullNotPermitted(fillPaint, \"fillPaint\");\r\n ParamChecks.nullNotPermitted(lineStroke, \"lineStroke\");\r\n ParamChecks.nullNotPermitted(line, \"line\");\r\n ParamChecks.nullNotPermitted(linePaint, \"linePaint\");\r\n ParamChecks.nullNotPermitted(outlinePaint, \"outlinePaint\");\r\n ParamChecks.nullNotPermitted(outlineStroke, \"outlineStroke\");\r\n this.label = characterIteratorToString(label.getIterator());\r\n this.attributedLabel = label;\r\n this.description = description;\r\n this.shapeVisible = shapeVisible;\r\n this.shape = shape;\r\n this.shapeFilled = shapeFilled;\r\n this.fillPaint = fillPaint;\r\n this.fillPaintTransformer = new StandardGradientPaintTransformer();\r\n this.shapeOutlineVisible = shapeOutlineVisible;\r\n this.outlinePaint = outlinePaint;\r\n this.outlineStroke = outlineStroke;\r\n this.lineVisible = lineVisible;\r\n this.line = line;\r\n this.lineStroke = lineStroke;\r\n this.linePaint = linePaint;\r\n this.toolTipText = toolTipText;\r\n this.urlText = urlText;\r\n }\r\n\r\n /**\r\n * Returns a string containing the characters from the given iterator.\r\n *\r\n * @param iterator the iterator (<code>null</code> not permitted).\r\n *\r\n * @return A string.\r\n */\r\n private String characterIteratorToString(CharacterIterator iterator) {\r\n int endIndex = iterator.getEndIndex();\r\n int beginIndex = iterator.getBeginIndex();\r\n int count = endIndex - beginIndex;\r\n if (count <= 0) {\r\n return \"\";\r\n }\r\n char[] chars = new char[count];\r\n int i = 0;\r\n char c = iterator.first();\r\n while (c != CharacterIterator.DONE) {\r\n chars[i] = c;\r\n i++;\r\n c = iterator.next();\r\n }\r\n return new String(chars);\r\n }\r\n\r\n /**\r\n * Returns the dataset.\r\n *\r\n * @return The dataset.\r\n *\r\n * @since 1.0.6\r\n *\r\n * @see #setDatasetIndex(int)\r\n */\r\n public Dataset getDataset() {\r\n return this.dataset;\r\n }\r\n\r\n /**\r\n * Sets the dataset.\r\n *\r\n * @param dataset the dataset.\r\n *\r\n * @since 1.0.6\r\n */\r\n public void setDataset(Dataset dataset) {\r\n this.dataset = dataset;\r\n }\r\n\r\n /**\r\n * Returns the dataset index for this legend item.\r\n *\r\n * @return The dataset index.\r\n *\r\n * @since 1.0.2\r\n *\r\n * @see #setDatasetIndex(int)\r\n * @see #getDataset()\r\n */\r\n public int getDatasetIndex() {\r\n return this.datasetIndex;\r\n }\r\n\r\n /**\r\n * Sets the dataset index for this legend item.\r\n *\r\n * @param index the index.\r\n *\r\n * @since 1.0.2\r\n *\r\n * @see #getDatasetIndex()\r\n */\r\n public void setDatasetIndex(int index) {\r\n this.datasetIndex = index;\r\n }\r\n\r\n /**\r\n * Returns the series key.\r\n *\r\n * @return The series key.\r\n *\r\n * @since 1.0.6\r\n *\r\n * @see #setSeriesKey(Comparable)\r\n */\r\n public Comparable getSeriesKey() {\r\n return this.seriesKey;\r\n }\r\n\r\n /**\r\n * Sets the series key.\r\n *\r\n * @param key the series key.\r\n *\r\n * @since 1.0.6\r\n */\r\n public void setSeriesKey(Comparable key) {\r\n this.seriesKey = key;\r\n }\r\n\r\n /**\r\n * Returns the series index for this legend item.\r\n *\r\n * @return The series index.\r\n *\r\n * @since 1.0.2\r\n */\r\n public int getSeriesIndex() {\r\n return this.series;\r\n }\r\n\r\n /**\r\n * Sets the series index for this legend item.\r\n *\r\n * @param index the index.\r\n *\r\n * @since 1.0.2\r\n */\r\n public void setSeriesIndex(int index) {\r\n this.series = index;\r\n }\r\n\r\n /**\r\n * Returns the label.\r\n *\r\n * @return The label (never <code>null</code>).\r\n */\r\n public String getLabel() {\r\n return this.label;\r\n }\r\n\r\n /**\r\n * Returns the label font.\r\n *\r\n * @return The label font (possibly <code>null</code>).\r\n *\r\n * @since 1.0.11\r\n */\r\n public Font getLabelFont() {\r\n return this.labelFont;\r\n }\r\n\r\n /**\r\n * Sets the label font.\r\n *\r\n * @param font the font (<code>null</code> permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setLabelFont(Font font) {\r\n this.labelFont = font;\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the label.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @since 1.0.11\r\n */\r\n public Paint getLabelPaint() {\r\n return this.labelPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the label.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setLabelPaint(Paint paint) {\r\n this.labelPaint = paint;\r\n }\r\n\r\n /**\r\n * Returns the attributed label.\r\n *\r\n * @return The attributed label (possibly <code>null</code>).\r\n */\r\n public AttributedString getAttributedLabel() {\r\n return this.attributedLabel;\r\n }\r\n\r\n /**\r\n * Returns the description for the legend item.\r\n *\r\n * @return The description (possibly <code>null</code>).\r\n *\r\n * @see #setDescription(java.lang.String) \r\n */\r\n public String getDescription() {\r\n return this.description;\r\n }\r\n\r\n /**\r\n * Sets the description for this legend item.\r\n *\r\n * @param text the description (<code>null</code> permitted).\r\n *\r\n * @see #getDescription()\r\n * @since 1.0.14\r\n */\r\n public void setDescription(String text) {\r\n this.description = text;\r\n }\r\n\r\n /**\r\n * Returns the tool tip text.\r\n *\r\n * @return The tool tip text (possibly <code>null</code>).\r\n *\r\n * @see #setToolTipText(java.lang.String) \r\n */\r\n public String getToolTipText() {\r\n return this.toolTipText;\r\n }\r\n\r\n /**\r\n * Sets the tool tip text for this legend item.\r\n *\r\n * @param text the text (<code>null</code> permitted).\r\n *\r\n * @see #getToolTipText()\r\n * @since 1.0.14\r\n */\r\n public void setToolTipText(String text) {\r\n this.toolTipText = text;\r\n }\r\n\r\n /**\r\n * Returns the URL text.\r\n *\r\n * @return The URL text (possibly <code>null</code>).\r\n *\r\n * @see #setURLText(java.lang.String) \r\n */\r\n public String getURLText() {\r\n return this.urlText;\r\n }\r\n\r\n /**\r\n * Sets the URL text.\r\n *\r\n * @param text the text (<code>null</code> permitted).\r\n *\r\n * @see #getURLText()\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setURLText(String text) {\r\n this.urlText = text;\r\n }\r\n\r\n /**\r\n * Returns a flag that indicates whether or not the shape is visible.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setShapeVisible(boolean)\r\n */\r\n public boolean isShapeVisible() {\r\n return this.shapeVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the shape is visible.\r\n *\r\n * @param visible the new flag value.\r\n *\r\n * @see #isShapeVisible()\r\n * @see #isLineVisible()\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setShapeVisible(boolean visible) {\r\n this.shapeVisible = visible;\r\n }\r\n\r\n /**\r\n * Returns the shape used to label the series represented by this legend\r\n * item.\r\n *\r\n * @return The shape (never <code>null</code>).\r\n *\r\n * @see #setShape(java.awt.Shape) \r\n */\r\n public Shape getShape() {\r\n return this.shape;\r\n }\r\n\r\n /**\r\n * Sets the shape for the legend item.\r\n *\r\n * @param shape the shape (<code>null</code> not permitted).\r\n *\r\n * @see #getShape()\r\n * @since 1.0.14\r\n */\r\n public void setShape(Shape shape) {\r\n ParamChecks.nullNotPermitted(shape, \"shape\");\r\n this.shape = shape;\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not the shape is filled.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean isShapeFilled() {\r\n return this.shapeFilled;\r\n }\r\n\r\n /**\r\n * Returns the fill paint.\r\n *\r\n * @return The fill paint (never <code>null</code>).\r\n */\r\n public Paint getFillPaint() {\r\n return this.fillPaint;\r\n }\r\n\r\n /**\r\n * Sets the fill paint.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setFillPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.fillPaint = paint;\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the shape outline\r\n * is visible.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean isShapeOutlineVisible() {\r\n return this.shapeOutlineVisible;\r\n }\r\n\r\n /**\r\n * Returns the line stroke for the series.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n */\r\n public Stroke getLineStroke() {\r\n return this.lineStroke;\r\n }\r\n \r\n /**\r\n * Sets the line stroke.\r\n * \r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n * \r\n * @since 1.0.18\r\n */\r\n public void setLineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.lineStroke = stroke;\r\n }\r\n\r\n /**\r\n * Returns the paint used for lines.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n */\r\n public Paint getLinePaint() {\r\n return this.linePaint;\r\n }\r\n\r\n /**\r\n * Sets the line paint.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setLinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.linePaint = paint;\r\n }\r\n\r\n /**\r\n * Returns the outline paint.\r\n *\r\n * @return The outline paint (never <code>null</code>).\r\n */\r\n public Paint getOutlinePaint() {\r\n return this.outlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the outline paint.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setOutlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.outlinePaint = paint;\r\n }\r\n\r\n /**\r\n * Returns the outline stroke.\r\n *\r\n * @return The outline stroke (never <code>null</code>).\r\n *\r\n * @see #setOutlineStroke(java.awt.Stroke) \r\n */\r\n public Stroke getOutlineStroke() {\r\n return this.outlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the outline stroke.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getOutlineStroke()\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setOutlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.outlineStroke = stroke;\r\n }\r\n\r\n /**\r\n * Returns a flag that indicates whether or not the line is visible.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setLineVisible(boolean) \r\n */\r\n public boolean isLineVisible() {\r\n return this.lineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the line shape is visible for\r\n * this legend item.\r\n *\r\n * @param visible the new flag value.\r\n *\r\n * @see #isLineVisible()\r\n * @since 1.0.14\r\n */\r\n public void setLineVisible(boolean visible) {\r\n this.lineVisible = visible;\r\n }\r\n\r\n /**\r\n * Returns the line.\r\n *\r\n * @return The line (never <code>null</code>).\r\n *\r\n * @see #setLine(java.awt.Shape)\r\n * @see #isLineVisible() \r\n */\r\n public Shape getLine() {\r\n return this.line;\r\n }\r\n\r\n /**\r\n * Sets the line.\r\n *\r\n * @param line the line (<code>null</code> not permitted).\r\n *\r\n * @see #getLine()\r\n * @since 1.0.14\r\n */\r\n public void setLine(Shape line) {\r\n ParamChecks.nullNotPermitted(line, \"line\");\r\n this.line = line;\r\n }\r\n\r\n /**\r\n * Returns the transformer used when the fill paint is an instance of\r\n * <code>GradientPaint</code>.\r\n *\r\n * @return The transformer (never <code>null</code>).\r\n *\r\n * @since 1.0.4\r\n *\r\n * @see #setFillPaintTransformer(GradientPaintTransformer)\r\n */\r\n public GradientPaintTransformer getFillPaintTransformer() {\r\n return this.fillPaintTransformer;\r\n }\r\n\r\n /**\r\n * Sets the transformer used when the fill paint is an instance of\r\n * <code>GradientPaint</code>.\r\n *\r\n * @param transformer the transformer (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.4\r\n *\r\n * @see #getFillPaintTransformer()\r\n */\r\n public void setFillPaintTransformer(GradientPaintTransformer transformer) {\r\n ParamChecks.nullNotPermitted(transformer, \"transformer\");\r\n this.fillPaintTransformer = transformer;\r\n }\r\n\r\n /**\r\n * Tests this item for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof LegendItem)) {\r\n return false;\r\n }\r\n LegendItem that = (LegendItem) obj;\r\n if (this.datasetIndex != that.datasetIndex) {\r\n return false;\r\n }\r\n if (this.series != that.series) {\r\n return false;\r\n }\r\n if (!this.label.equals(that.label)) {\r\n return false;\r\n }\r\n if (!AttributedStringUtilities.equal(this.attributedLabel,\r\n that.attributedLabel)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.description, that.description)) {\r\n return false;\r\n }\r\n if (this.shapeVisible != that.shapeVisible) {\r\n return false;\r\n }\r\n if (!ShapeUtilities.equal(this.shape, that.shape)) {\r\n return false;\r\n }\r\n if (this.shapeFilled != that.shapeFilled) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.fillPaint, that.fillPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.fillPaintTransformer,\r\n that.fillPaintTransformer)) {\r\n return false;\r\n }\r\n if (this.shapeOutlineVisible != that.shapeOutlineVisible) {\r\n return false;\r\n }\r\n if (!this.outlineStroke.equals(that.outlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) {\r\n return false;\r\n }\r\n if (!this.lineVisible == that.lineVisible) {\r\n return false;\r\n }\r\n if (!ShapeUtilities.equal(this.line, that.line)) {\r\n return false;\r\n }\r\n if (!this.lineStroke.equals(that.lineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.linePaint, that.linePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.labelFont, that.labelFont)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.labelPaint, that.labelPaint)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns an independent copy of this object (except that the clone will\r\n * still reference the same dataset as the original\r\n * <code>LegendItem</code>).\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the legend item cannot be cloned.\r\n *\r\n * @since 1.0.10\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n LegendItem clone = (LegendItem) super.clone();\r\n if (this.seriesKey instanceof PublicCloneable) {\r\n PublicCloneable pc = (PublicCloneable) this.seriesKey;\r\n clone.seriesKey = (Comparable) pc.clone();\r\n }\r\n // FIXME: Clone the attributed string if it is not null\r\n clone.shape = ShapeUtilities.clone(this.shape);\r\n if (this.fillPaintTransformer instanceof PublicCloneable) {\r\n PublicCloneable pc = (PublicCloneable) this.fillPaintTransformer;\r\n clone.fillPaintTransformer = (GradientPaintTransformer) pc.clone();\r\n\r\n }\r\n clone.line = ShapeUtilities.clone(this.line);\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream (<code>null</code> not permitted).\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeAttributedString(this.attributedLabel, stream);\r\n SerialUtilities.writeShape(this.shape, stream);\r\n SerialUtilities.writePaint(this.fillPaint, stream);\r\n SerialUtilities.writeStroke(this.outlineStroke, stream);\r\n SerialUtilities.writePaint(this.outlinePaint, stream);\r\n SerialUtilities.writeShape(this.line, stream);\r\n SerialUtilities.writeStroke(this.lineStroke, stream);\r\n SerialUtilities.writePaint(this.linePaint, stream);\r\n SerialUtilities.writePaint(this.labelPaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream (<code>null</code> not permitted).\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.attributedLabel = SerialUtilities.readAttributedString(stream);\r\n this.shape = SerialUtilities.readShape(stream);\r\n this.fillPaint = SerialUtilities.readPaint(stream);\r\n this.outlineStroke = SerialUtilities.readStroke(stream);\r\n this.outlinePaint = SerialUtilities.readPaint(stream);\r\n this.line = SerialUtilities.readShape(stream);\r\n this.lineStroke = SerialUtilities.readStroke(stream);\r\n this.linePaint = SerialUtilities.readPaint(stream);\r\n this.labelPaint = SerialUtilities.readPaint(stream);\r\n }\r\n\r\n}\r" }, { "identifier": "TestUtilities", "path": "lib/jfreechart-1.0.19/tests/org/jfree/chart/TestUtilities.java", "snippet": "public class TestUtilities {\n\n /**\n * Returns <code>true</code> if the collections contains any object that\n * is an instance of the specified class, and <code>false</code> otherwise.\n *\n * @param collection the collection.\n * @param c the class.\n *\n * @return A boolean.\n */\n public static boolean containsInstanceOf(Collection collection, Class c) {\n Iterator iterator = collection.iterator();\n while (iterator.hasNext()) {\n Object obj = iterator.next();\n if (obj != null && obj.getClass().equals(c)) {\n return true;\n }\n }\n return false;\n }\n\n public static Object serialised(Object original) {\n Object result = null;\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n ObjectOutput out;\n try {\n out = new ObjectOutputStream(buffer);\n out.writeObject(original);\n out.close();\n ObjectInput in = new ObjectInputStream(\n new ByteArrayInputStream(buffer.toByteArray()));\n result = in.readObject();\n in.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n return result;\n }\n \n}" }, { "identifier": "XYTextAnnotation", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/annotations/XYTextAnnotation.java", "snippet": "public class XYTextAnnotation extends AbstractXYAnnotation\r\n implements Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -2946063342782506328L;\r\n\r\n /** The default font. */\r\n public static final Font DEFAULT_FONT = new Font(\"SansSerif\", Font.PLAIN,\r\n 10);\r\n\r\n /** The default paint. */\r\n public static final Paint DEFAULT_PAINT = Color.black;\r\n\r\n /** The default text anchor. */\r\n public static final TextAnchor DEFAULT_TEXT_ANCHOR = TextAnchor.CENTER;\r\n\r\n /** The default rotation anchor. */\r\n public static final TextAnchor DEFAULT_ROTATION_ANCHOR = TextAnchor.CENTER;\r\n\r\n /** The default rotation angle. */\r\n public static final double DEFAULT_ROTATION_ANGLE = 0.0;\r\n\r\n /** The text. */\r\n private String text;\r\n\r\n /** The font. */\r\n private Font font;\r\n\r\n /** The paint. */\r\n private transient Paint paint;\r\n\r\n /** The x-coordinate. */\r\n private double x;\r\n\r\n /** The y-coordinate. */\r\n private double y;\r\n\r\n /** The text anchor (to be aligned with (x, y)). */\r\n private TextAnchor textAnchor;\r\n\r\n /** The rotation anchor. */\r\n private TextAnchor rotationAnchor;\r\n\r\n /** The rotation angle. */\r\n private double rotationAngle;\r\n\r\n /**\r\n * The background paint (possibly null).\r\n *\r\n * @since 1.0.13\r\n */\r\n private transient Paint backgroundPaint;\r\n\r\n /**\r\n * The flag that controls the visibility of the outline.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean outlineVisible;\r\n\r\n /**\r\n * The outline paint (never null).\r\n *\r\n * @since 1.0.13\r\n */\r\n private transient Paint outlinePaint;\r\n\r\n /**\r\n * The outline stroke (never null).\r\n *\r\n * @since 1.0.13\r\n */\r\n private transient Stroke outlineStroke;\r\n\r\n /**\r\n * Creates a new annotation to be displayed at the given coordinates. The\r\n * coordinates are specified in data space (they will be converted to\r\n * Java2D space for display).\r\n *\r\n * @param text the text (<code>null</code> not permitted).\r\n * @param x the x-coordinate (in data space).\r\n * @param y the y-coordinate (in data space).\r\n */\r\n public XYTextAnnotation(String text, double x, double y) {\r\n super();\r\n ParamChecks.nullNotPermitted(text, \"text\");\r\n this.text = text;\r\n this.font = DEFAULT_FONT;\r\n this.paint = DEFAULT_PAINT;\r\n this.x = x;\r\n this.y = y;\r\n this.textAnchor = DEFAULT_TEXT_ANCHOR;\r\n this.rotationAnchor = DEFAULT_ROTATION_ANCHOR;\r\n this.rotationAngle = DEFAULT_ROTATION_ANGLE;\r\n\r\n // by default the outline and background won't be visible\r\n this.backgroundPaint = null;\r\n this.outlineVisible = false;\r\n this.outlinePaint = Color.black;\r\n this.outlineStroke = new BasicStroke(0.5f);\r\n }\r\n\r\n /**\r\n * Returns the text for the annotation.\r\n *\r\n * @return The text (never <code>null</code>).\r\n *\r\n * @see #setText(String)\r\n */\r\n public String getText() {\r\n return this.text;\r\n }\r\n\r\n /**\r\n * Sets the text for the annotation.\r\n *\r\n * @param text the text (<code>null</code> not permitted).\r\n *\r\n * @see #getText()\r\n */\r\n public void setText(String text) {\r\n ParamChecks.nullNotPermitted(text, \"text\");\r\n this.text = text;\r\n fireAnnotationChanged();\r\n }\r\n\r\n /**\r\n * Returns the font for the annotation.\r\n *\r\n * @return The font (never <code>null</code>).\r\n *\r\n * @see #setFont(Font)\r\n */\r\n public Font getFont() {\r\n return this.font;\r\n }\r\n\r\n /**\r\n * Sets the font for the annotation and sends an\r\n * {@link AnnotationChangeEvent} to all registered listeners.\r\n *\r\n * @param font the font (<code>null</code> not permitted).\r\n *\r\n * @see #getFont()\r\n */\r\n public void setFont(Font font) {\r\n ParamChecks.nullNotPermitted(font, \"font\");\r\n this.font = font;\r\n fireAnnotationChanged();\r\n }\r\n\r\n /**\r\n * Returns the paint for the annotation.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setPaint(Paint)\r\n */\r\n public Paint getPaint() {\r\n return this.paint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the annotation and sends an\r\n * {@link AnnotationChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getPaint()\r\n */\r\n public void setPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.paint = paint;\r\n fireAnnotationChanged();\r\n }\r\n\r\n /**\r\n * Returns the text anchor.\r\n *\r\n * @return The text anchor (never <code>null</code>).\r\n *\r\n * @see #setTextAnchor(TextAnchor)\r\n */\r\n public TextAnchor getTextAnchor() {\r\n return this.textAnchor;\r\n }\r\n\r\n /**\r\n * Sets the text anchor (the point on the text bounding rectangle that is\r\n * aligned to the (x, y) coordinate of the annotation) and sends an\r\n * {@link AnnotationChangeEvent} to all registered listeners.\r\n *\r\n * @param anchor the anchor point (<code>null</code> not permitted).\r\n *\r\n * @see #getTextAnchor()\r\n */\r\n public void setTextAnchor(TextAnchor anchor) {\r\n ParamChecks.nullNotPermitted(anchor, \"anchor\");\r\n this.textAnchor = anchor;\r\n fireAnnotationChanged();\r\n }\r\n\r\n /**\r\n * Returns the rotation anchor.\r\n *\r\n * @return The rotation anchor point (never <code>null</code>).\r\n *\r\n * @see #setRotationAnchor(TextAnchor)\r\n */\r\n public TextAnchor getRotationAnchor() {\r\n return this.rotationAnchor;\r\n }\r\n\r\n /**\r\n * Sets the rotation anchor point and sends an\r\n * {@link AnnotationChangeEvent} to all registered listeners.\r\n *\r\n * @param anchor the anchor (<code>null</code> not permitted).\r\n *\r\n * @see #getRotationAnchor()\r\n */\r\n public void setRotationAnchor(TextAnchor anchor) {\r\n ParamChecks.nullNotPermitted(anchor, \"anchor\");\r\n this.rotationAnchor = anchor;\r\n fireAnnotationChanged();\r\n }\r\n\r\n /**\r\n * Returns the rotation angle.\r\n *\r\n * @return The rotation angle.\r\n *\r\n * @see #setRotationAngle(double)\r\n */\r\n public double getRotationAngle() {\r\n return this.rotationAngle;\r\n }\r\n\r\n /**\r\n * Sets the rotation angle and sends an {@link AnnotationChangeEvent} to\r\n * all registered listeners. The angle is measured clockwise in radians.\r\n *\r\n * @param angle the angle (in radians).\r\n *\r\n * @see #getRotationAngle()\r\n */\r\n public void setRotationAngle(double angle) {\r\n this.rotationAngle = angle;\r\n fireAnnotationChanged();\r\n }\r\n\r\n /**\r\n * Returns the x coordinate for the text anchor point (measured against the\r\n * domain axis).\r\n *\r\n * @return The x coordinate (in data space).\r\n *\r\n * @see #setX(double)\r\n */\r\n public double getX() {\r\n return this.x;\r\n }\r\n\r\n /**\r\n * Sets the x coordinate for the text anchor point (measured against the\r\n * domain axis) and sends an {@link AnnotationChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param x the x coordinate (in data space).\r\n *\r\n * @see #getX()\r\n */\r\n public void setX(double x) {\r\n this.x = x;\r\n fireAnnotationChanged();\r\n }\r\n\r\n /**\r\n * Returns the y coordinate for the text anchor point (measured against the\r\n * range axis).\r\n *\r\n * @return The y coordinate (in data space).\r\n *\r\n * @see #setY(double)\r\n */\r\n public double getY() {\r\n return this.y;\r\n }\r\n\r\n /**\r\n * Sets the y coordinate for the text anchor point (measured against the\r\n * range axis) and sends an {@link AnnotationChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param y the y coordinate.\r\n *\r\n * @see #getY()\r\n */\r\n public void setY(double y) {\r\n this.y = y;\r\n fireAnnotationChanged();\r\n }\r\n\r\n /**\r\n * Returns the background paint for the annotation.\r\n *\r\n * @return The background paint (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundPaint(Paint)\r\n *\r\n * @since 1.0.13\r\n */\r\n public Paint getBackgroundPaint() {\r\n return this.backgroundPaint;\r\n }\r\n\r\n /**\r\n * Sets the background paint for the annotation and sends an\r\n * {@link AnnotationChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundPaint()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setBackgroundPaint(Paint paint) {\r\n this.backgroundPaint = paint;\r\n fireAnnotationChanged();\r\n }\r\n\r\n /**\r\n * Returns the outline paint for the annotation.\r\n *\r\n * @return The outline paint (never <code>null</code>).\r\n *\r\n * @see #setOutlinePaint(Paint)\r\n *\r\n * @since 1.0.13\r\n */\r\n public Paint getOutlinePaint() {\r\n return this.outlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the outline paint for the annotation and sends an\r\n * {@link AnnotationChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getOutlinePaint()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setOutlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.outlinePaint = paint;\r\n fireAnnotationChanged();\r\n }\r\n\r\n /**\r\n * Returns the outline stroke for the annotation.\r\n *\r\n * @return The outline stroke (never <code>null</code>).\r\n *\r\n * @see #setOutlineStroke(Stroke)\r\n *\r\n * @since 1.0.13\r\n */\r\n public Stroke getOutlineStroke() {\r\n return this.outlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the outline stroke for the annotation and sends an\r\n * {@link AnnotationChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getOutlineStroke()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setOutlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.outlineStroke = stroke;\r\n fireAnnotationChanged();\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the outline is drawn.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.13\r\n */\r\n public boolean isOutlineVisible() {\r\n return this.outlineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the outline is drawn and\r\n * sends an {@link AnnotationChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the new flag value.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setOutlineVisible(boolean visible) {\r\n this.outlineVisible = visible;\r\n fireAnnotationChanged();\r\n }\r\n\r\n /**\r\n * Draws the annotation.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plot the plot.\r\n * @param dataArea the data area.\r\n * @param domainAxis the domain axis.\r\n * @param rangeAxis the range axis.\r\n * @param rendererIndex the renderer index.\r\n * @param info an optional info object that will be populated with\r\n * entity information.\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea,\r\n ValueAxis domainAxis, ValueAxis rangeAxis,\r\n int rendererIndex, PlotRenderingInfo info) {\r\n\r\n PlotOrientation orientation = plot.getOrientation();\r\n RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(\r\n plot.getDomainAxisLocation(), orientation);\r\n RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation(\r\n plot.getRangeAxisLocation(), orientation);\r\n\r\n float anchorX = (float) domainAxis.valueToJava2D(\r\n this.x, dataArea, domainEdge);\r\n float anchorY = (float) rangeAxis.valueToJava2D(\r\n this.y, dataArea, rangeEdge);\r\n\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n float tempAnchor = anchorX;\r\n anchorX = anchorY;\r\n anchorY = tempAnchor;\r\n }\r\n\r\n g2.setFont(getFont());\r\n Shape hotspot = TextUtilities.calculateRotatedStringBounds(\r\n getText(), g2, anchorX, anchorY, getTextAnchor(),\r\n getRotationAngle(), getRotationAnchor());\r\n if (this.backgroundPaint != null) {\r\n g2.setPaint(this.backgroundPaint);\r\n g2.fill(hotspot);\r\n }\r\n g2.setPaint(getPaint());\r\n TextUtilities.drawRotatedString(getText(), g2, anchorX, anchorY,\r\n getTextAnchor(), getRotationAngle(), getRotationAnchor());\r\n if (this.outlineVisible) {\r\n g2.setStroke(this.outlineStroke);\r\n g2.setPaint(this.outlinePaint);\r\n g2.draw(hotspot);\r\n }\r\n\r\n String toolTip = getToolTipText();\r\n String url = getURL();\r\n if (toolTip != null || url != null) {\r\n addEntity(info, hotspot, rendererIndex, toolTip, url);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Tests this annotation for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof XYTextAnnotation)) {\r\n return false;\r\n }\r\n XYTextAnnotation that = (XYTextAnnotation) obj;\r\n if (!this.text.equals(that.text)) {\r\n return false;\r\n }\r\n if (this.x != that.x) {\r\n return false;\r\n }\r\n if (this.y != that.y) {\r\n return false;\r\n }\r\n if (!this.font.equals(that.font)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.paint, that.paint)) {\r\n return false;\r\n }\r\n if (!this.rotationAnchor.equals(that.rotationAnchor)) {\r\n return false;\r\n }\r\n if (this.rotationAngle != that.rotationAngle) {\r\n return false;\r\n }\r\n if (!this.textAnchor.equals(that.textAnchor)) {\r\n return false;\r\n }\r\n if (this.outlineVisible != that.outlineVisible) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.backgroundPaint, that.backgroundPaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) {\r\n return false;\r\n }\r\n if (!(this.outlineStroke.equals(that.outlineStroke))) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a hash code for the object.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result = 193;\r\n result = 37 * result + this.text.hashCode();\r\n result = 37 * result + this.font.hashCode();\r\n result = 37 * result + HashUtilities.hashCodeForPaint(this.paint);\r\n long temp = Double.doubleToLongBits(this.x);\r\n result = 37 * result + (int) (temp ^ (temp >>> 32));\r\n temp = Double.doubleToLongBits(this.y);\r\n result = 37 * result + (int) (temp ^ (temp >>> 32));\r\n result = 37 * result + this.textAnchor.hashCode();\r\n result = 37 * result + this.rotationAnchor.hashCode();\r\n temp = Double.doubleToLongBits(this.rotationAngle);\r\n result = 37 * result + (int) (temp ^ (temp >>> 32));\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a clone of the annotation.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the annotation can't be cloned.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n return super.clone();\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writePaint(this.paint, stream);\r\n SerialUtilities.writePaint(this.backgroundPaint, stream);\r\n SerialUtilities.writePaint(this.outlinePaint, stream);\r\n SerialUtilities.writeStroke(this.outlineStroke, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.paint = SerialUtilities.readPaint(stream);\r\n this.backgroundPaint = SerialUtilities.readPaint(stream);\r\n this.outlinePaint = SerialUtilities.readPaint(stream);\r\n this.outlineStroke = SerialUtilities.readStroke(stream);\r\n }\r\n\r\n}\r" }, { "identifier": "NumberAxis", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/axis/NumberAxis.java", "snippet": "public class NumberAxis extends ValueAxis implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 2805933088476185789L;\r\n\r\n /** The default value for the autoRangeIncludesZero flag. */\r\n public static final boolean DEFAULT_AUTO_RANGE_INCLUDES_ZERO = true;\r\n\r\n /** The default value for the autoRangeStickyZero flag. */\r\n public static final boolean DEFAULT_AUTO_RANGE_STICKY_ZERO = true;\r\n\r\n /** The default tick unit. */\r\n public static final NumberTickUnit DEFAULT_TICK_UNIT = new NumberTickUnit(\r\n 1.0, new DecimalFormat(\"0\"));\r\n\r\n /** The default setting for the vertical tick labels flag. */\r\n public static final boolean DEFAULT_VERTICAL_TICK_LABELS = false;\r\n\r\n /**\r\n * The range type (can be used to force the axis to display only positive\r\n * values or only negative values).\r\n */\r\n private RangeType rangeType;\r\n\r\n /**\r\n * A flag that affects the axis range when the range is determined\r\n * automatically. If the auto range does NOT include zero and this flag\r\n * is TRUE, then the range is changed to include zero.\r\n */\r\n private boolean autoRangeIncludesZero;\r\n\r\n /**\r\n * A flag that affects the size of the margins added to the axis range when\r\n * the range is determined automatically. If the value 0 falls within the\r\n * margin and this flag is TRUE, then the margin is truncated at zero.\r\n */\r\n private boolean autoRangeStickyZero;\r\n\r\n /** The tick unit for the axis. */\r\n private NumberTickUnit tickUnit;\r\n\r\n /** The override number format. */\r\n private NumberFormat numberFormatOverride;\r\n\r\n /** An optional band for marking regions on the axis. */\r\n private MarkerAxisBand markerBand;\r\n\r\n /**\r\n * Default constructor.\r\n */\r\n public NumberAxis() {\r\n this(null);\r\n }\r\n\r\n /**\r\n * Constructs a number axis, using default values where necessary.\r\n *\r\n * @param label the axis label (<code>null</code> permitted).\r\n */\r\n public NumberAxis(String label) {\r\n super(label, NumberAxis.createStandardTickUnits());\r\n this.rangeType = RangeType.FULL;\r\n this.autoRangeIncludesZero = DEFAULT_AUTO_RANGE_INCLUDES_ZERO;\r\n this.autoRangeStickyZero = DEFAULT_AUTO_RANGE_STICKY_ZERO;\r\n this.tickUnit = DEFAULT_TICK_UNIT;\r\n this.numberFormatOverride = null;\r\n this.markerBand = null;\r\n }\r\n\r\n /**\r\n * Returns the axis range type.\r\n *\r\n * @return The axis range type (never <code>null</code>).\r\n *\r\n * @see #setRangeType(RangeType)\r\n */\r\n public RangeType getRangeType() {\r\n return this.rangeType;\r\n }\r\n\r\n /**\r\n * Sets the axis range type.\r\n *\r\n * @param rangeType the range type (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeType()\r\n */\r\n public void setRangeType(RangeType rangeType) {\r\n ParamChecks.nullNotPermitted(rangeType, \"rangeType\");\r\n this.rangeType = rangeType;\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the flag that indicates whether or not the automatic axis range\r\n * (if indeed it is determined automatically) is forced to include zero.\r\n *\r\n * @return The flag.\r\n */\r\n public boolean getAutoRangeIncludesZero() {\r\n return this.autoRangeIncludesZero;\r\n }\r\n\r\n /**\r\n * Sets the flag that indicates whether or not the axis range, if\r\n * automatically calculated, is forced to include zero.\r\n * <p>\r\n * If the flag is changed to <code>true</code>, the axis range is\r\n * recalculated.\r\n * <p>\r\n * Any change to the flag will trigger an {@link AxisChangeEvent}.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #getAutoRangeIncludesZero()\r\n */\r\n public void setAutoRangeIncludesZero(boolean flag) {\r\n if (this.autoRangeIncludesZero != flag) {\r\n this.autoRangeIncludesZero = flag;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag that affects the auto-range when zero falls outside the\r\n * data range but inside the margins defined for the axis.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAutoRangeStickyZero(boolean)\r\n */\r\n public boolean getAutoRangeStickyZero() {\r\n return this.autoRangeStickyZero;\r\n }\r\n\r\n /**\r\n * Sets a flag that affects the auto-range when zero falls outside the data\r\n * range but inside the margins defined for the axis.\r\n *\r\n * @param flag the new flag.\r\n *\r\n * @see #getAutoRangeStickyZero()\r\n */\r\n public void setAutoRangeStickyZero(boolean flag) {\r\n if (this.autoRangeStickyZero != flag) {\r\n this.autoRangeStickyZero = flag;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the tick unit for the axis.\r\n * <p>\r\n * Note: if the <code>autoTickUnitSelection</code> flag is\r\n * <code>true</code> the tick unit may be changed while the axis is being\r\n * drawn, so in that case the return value from this method may be\r\n * irrelevant if the method is called before the axis has been drawn.\r\n *\r\n * @return The tick unit for the axis.\r\n *\r\n * @see #setTickUnit(NumberTickUnit)\r\n * @see ValueAxis#isAutoTickUnitSelection()\r\n */\r\n public NumberTickUnit getTickUnit() {\r\n return this.tickUnit;\r\n }\r\n\r\n /**\r\n * Sets the tick unit for the axis and sends an {@link AxisChangeEvent} to\r\n * all registered listeners. A side effect of calling this method is that\r\n * the \"auto-select\" feature for tick units is switched off (you can\r\n * restore it using the {@link ValueAxis#setAutoTickUnitSelection(boolean)}\r\n * method).\r\n *\r\n * @param unit the new tick unit (<code>null</code> not permitted).\r\n *\r\n * @see #getTickUnit()\r\n * @see #setTickUnit(NumberTickUnit, boolean, boolean)\r\n */\r\n public void setTickUnit(NumberTickUnit unit) {\r\n // defer argument checking...\r\n setTickUnit(unit, true, true);\r\n }\r\n\r\n /**\r\n * Sets the tick unit for the axis and, if requested, sends an\r\n * {@link AxisChangeEvent} to all registered listeners. In addition, an\r\n * option is provided to turn off the \"auto-select\" feature for tick units\r\n * (you can restore it using the\r\n * {@link ValueAxis#setAutoTickUnitSelection(boolean)} method).\r\n *\r\n * @param unit the new tick unit (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n * @param turnOffAutoSelect turn off the auto-tick selection?\r\n */\r\n public void setTickUnit(NumberTickUnit unit, boolean notify,\r\n boolean turnOffAutoSelect) {\r\n\r\n ParamChecks.nullNotPermitted(unit, \"unit\");\r\n this.tickUnit = unit;\r\n if (turnOffAutoSelect) {\r\n setAutoTickUnitSelection(false, false);\r\n }\r\n if (notify) {\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the number format override. If this is non-null, then it will\r\n * be used to format the numbers on the axis.\r\n *\r\n * @return The number formatter (possibly <code>null</code>).\r\n *\r\n * @see #setNumberFormatOverride(NumberFormat)\r\n */\r\n public NumberFormat getNumberFormatOverride() {\r\n return this.numberFormatOverride;\r\n }\r\n\r\n /**\r\n * Sets the number format override. If this is non-null, then it will be\r\n * used to format the numbers on the axis.\r\n *\r\n * @param formatter the number formatter (<code>null</code> permitted).\r\n *\r\n * @see #getNumberFormatOverride()\r\n */\r\n public void setNumberFormatOverride(NumberFormat formatter) {\r\n this.numberFormatOverride = formatter;\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the (optional) marker band for the axis.\r\n *\r\n * @return The marker band (possibly <code>null</code>).\r\n *\r\n * @see #setMarkerBand(MarkerAxisBand)\r\n */\r\n public MarkerAxisBand getMarkerBand() {\r\n return this.markerBand;\r\n }\r\n\r\n /**\r\n * Sets the marker band for the axis.\r\n * <P>\r\n * The marker band is optional, leave it set to <code>null</code> if you\r\n * don't require it.\r\n *\r\n * @param band the new band (<code>null</code> permitted).\r\n *\r\n * @see #getMarkerBand()\r\n */\r\n public void setMarkerBand(MarkerAxisBand band) {\r\n this.markerBand = band;\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Configures the axis to work with the specified plot. If the axis has\r\n * auto-scaling, then sets the maximum and minimum values.\r\n */\r\n @Override\r\n public void configure() {\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n }\r\n\r\n /**\r\n * Rescales the axis to ensure that all data is visible.\r\n */\r\n @Override\r\n protected void autoAdjustRange() {\r\n\r\n Plot plot = getPlot();\r\n if (plot == null) {\r\n return; // no plot, no data\r\n }\r\n\r\n if (plot instanceof ValueAxisPlot) {\r\n ValueAxisPlot vap = (ValueAxisPlot) plot;\r\n\r\n Range r = vap.getDataRange(this);\r\n if (r == null) {\r\n r = getDefaultAutoRange();\r\n }\r\n\r\n double upper = r.getUpperBound();\r\n double lower = r.getLowerBound();\r\n if (this.rangeType == RangeType.POSITIVE) {\r\n lower = Math.max(0.0, lower);\r\n upper = Math.max(0.0, upper);\r\n }\r\n else if (this.rangeType == RangeType.NEGATIVE) {\r\n lower = Math.min(0.0, lower);\r\n upper = Math.min(0.0, upper);\r\n }\r\n\r\n if (getAutoRangeIncludesZero()) {\r\n lower = Math.min(lower, 0.0);\r\n upper = Math.max(upper, 0.0);\r\n }\r\n double range = upper - lower;\r\n\r\n // if fixed auto range, then derive lower bound...\r\n double fixedAutoRange = getFixedAutoRange();\r\n if (fixedAutoRange > 0.0) {\r\n lower = upper - fixedAutoRange;\r\n }\r\n else {\r\n // ensure the autorange is at least <minRange> in size...\r\n double minRange = getAutoRangeMinimumSize();\r\n if (range < minRange) {\r\n double expand = (minRange - range) / 2;\r\n upper = upper + expand;\r\n lower = lower - expand;\r\n if (lower == upper) { // see bug report 1549218\r\n double adjust = Math.abs(lower) / 10.0;\r\n lower = lower - adjust;\r\n upper = upper + adjust;\r\n }\r\n if (this.rangeType == RangeType.POSITIVE) {\r\n if (lower < 0.0) {\r\n upper = upper - lower;\r\n lower = 0.0;\r\n }\r\n }\r\n else if (this.rangeType == RangeType.NEGATIVE) {\r\n if (upper > 0.0) {\r\n lower = lower - upper;\r\n upper = 0.0;\r\n }\r\n }\r\n }\r\n\r\n if (getAutoRangeStickyZero()) {\r\n if (upper <= 0.0) {\r\n upper = Math.min(0.0, upper + getUpperMargin() * range);\r\n }\r\n else {\r\n upper = upper + getUpperMargin() * range;\r\n }\r\n if (lower >= 0.0) {\r\n lower = Math.max(0.0, lower - getLowerMargin() * range);\r\n }\r\n else {\r\n lower = lower - getLowerMargin() * range;\r\n }\r\n }\r\n else {\r\n upper = upper + getUpperMargin() * range;\r\n lower = lower - getLowerMargin() * range;\r\n }\r\n }\r\n\r\n setRange(new Range(lower, upper), false, false);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Converts a data value to a coordinate in Java2D space, assuming that the\r\n * axis runs along one edge of the specified dataArea.\r\n * <p>\r\n * Note that it is possible for the coordinate to fall outside the plotArea.\r\n *\r\n * @param value the data value.\r\n * @param area the area for plotting the data.\r\n * @param edge the axis location.\r\n *\r\n * @return The Java2D coordinate.\r\n *\r\n * @see #java2DToValue(double, Rectangle2D, RectangleEdge)\r\n */\r\n @Override\r\n public double valueToJava2D(double value, Rectangle2D area,\r\n RectangleEdge edge) {\r\n\r\n Range range = getRange();\r\n double axisMin = range.getLowerBound();\r\n double axisMax = range.getUpperBound();\r\n\r\n double min = 0.0;\r\n double max = 0.0;\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n min = area.getX();\r\n max = area.getMaxX();\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n max = area.getMinY();\r\n min = area.getMaxY();\r\n }\r\n if (isInverted()) {\r\n return max\r\n - ((value - axisMin) / (axisMax - axisMin)) * (max - min);\r\n }\r\n else {\r\n return min\r\n + ((value - axisMin) / (axisMax - axisMin)) * (max - min);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Converts a coordinate in Java2D space to the corresponding data value,\r\n * assuming that the axis runs along one edge of the specified dataArea.\r\n *\r\n * @param java2DValue the coordinate in Java2D space.\r\n * @param area the area in which the data is plotted.\r\n * @param edge the location.\r\n *\r\n * @return The data value.\r\n *\r\n * @see #valueToJava2D(double, Rectangle2D, RectangleEdge)\r\n */\r\n @Override\r\n public double java2DToValue(double java2DValue, Rectangle2D area,\r\n RectangleEdge edge) {\r\n\r\n Range range = getRange();\r\n double axisMin = range.getLowerBound();\r\n double axisMax = range.getUpperBound();\r\n\r\n double min = 0.0;\r\n double max = 0.0;\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n min = area.getX();\r\n max = area.getMaxX();\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n min = area.getMaxY();\r\n max = area.getY();\r\n }\r\n if (isInverted()) {\r\n return axisMax\r\n - (java2DValue - min) / (max - min) * (axisMax - axisMin);\r\n }\r\n else {\r\n return axisMin\r\n + (java2DValue - min) / (max - min) * (axisMax - axisMin);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Calculates the value of the lowest visible tick on the axis.\r\n *\r\n * @return The value of the lowest visible tick on the axis.\r\n *\r\n * @see #calculateHighestVisibleTickValue()\r\n */\r\n protected double calculateLowestVisibleTickValue() {\r\n double unit = getTickUnit().getSize();\r\n double index = Math.ceil(getRange().getLowerBound() / unit);\r\n return index * unit;\r\n }\r\n\r\n /**\r\n * Calculates the value of the highest visible tick on the axis.\r\n *\r\n * @return The value of the highest visible tick on the axis.\r\n *\r\n * @see #calculateLowestVisibleTickValue()\r\n */\r\n protected double calculateHighestVisibleTickValue() {\r\n double unit = getTickUnit().getSize();\r\n double index = Math.floor(getRange().getUpperBound() / unit);\r\n return index * unit;\r\n }\r\n\r\n /**\r\n * Calculates the number of visible ticks.\r\n *\r\n * @return The number of visible ticks on the axis.\r\n */\r\n protected int calculateVisibleTickCount() {\r\n double unit = getTickUnit().getSize();\r\n Range range = getRange();\r\n return (int) (Math.floor(range.getUpperBound() / unit)\r\n - Math.ceil(range.getLowerBound() / unit) + 1);\r\n }\r\n\r\n /**\r\n * Draws the axis on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param cursor the cursor location.\r\n * @param plotArea the area within which the axes and data should be drawn\r\n * (<code>null</code> not permitted).\r\n * @param dataArea the area within which the data should be drawn\r\n * (<code>null</code> not permitted).\r\n * @param edge the location of the axis (<code>null</code> not permitted).\r\n * @param plotState collects information about the plot\r\n * (<code>null</code> permitted).\r\n *\r\n * @return The axis state (never <code>null</code>).\r\n */\r\n @Override\r\n public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,\r\n Rectangle2D dataArea, RectangleEdge edge,\r\n PlotRenderingInfo plotState) {\r\n\r\n AxisState state;\r\n // if the axis is not visible, don't draw it...\r\n if (!isVisible()) {\r\n state = new AxisState(cursor);\r\n // even though the axis is not visible, we need ticks for the\r\n // gridlines...\r\n List ticks = refreshTicks(g2, state, dataArea, edge);\r\n state.setTicks(ticks);\r\n return state;\r\n }\r\n\r\n // draw the tick marks and labels...\r\n state = drawTickMarksAndLabels(g2, cursor, plotArea, dataArea, edge);\r\n\r\n if (getAttributedLabel() != null) {\r\n state = drawAttributedLabel(getAttributedLabel(), g2, plotArea, \r\n dataArea, edge, state);\r\n \r\n } else {\r\n state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);\r\n }\r\n createAndAddEntity(cursor, state, dataArea, edge, plotState);\r\n return state;\r\n\r\n }\r\n\r\n /**\r\n * Creates the standard tick units.\r\n * <P>\r\n * If you don't like these defaults, create your own instance of TickUnits\r\n * and then pass it to the setStandardTickUnits() method in the\r\n * NumberAxis class.\r\n *\r\n * @return The standard tick units.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n * @see #createIntegerTickUnits()\r\n */\r\n public static TickUnitSource createStandardTickUnits() {\r\n return new NumberTickUnitSource();\r\n }\r\n\r\n /**\r\n * Returns a collection of tick units for integer values.\r\n *\r\n * @return A collection of tick units for integer values.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n * @see #createStandardTickUnits()\r\n */\r\n public static TickUnitSource createIntegerTickUnits() {\r\n return new NumberTickUnitSource(true);\r\n }\r\n\r\n /**\r\n * Creates a collection of standard tick units. The supplied locale is\r\n * used to create the number formatter (a localised instance of\r\n * <code>NumberFormat</code>).\r\n * <P>\r\n * If you don't like these defaults, create your own instance of\r\n * {@link TickUnits} and then pass it to the\r\n * <code>setStandardTickUnits()</code> method.\r\n *\r\n * @param locale the locale.\r\n *\r\n * @return A tick unit collection.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n */\r\n public static TickUnitSource createStandardTickUnits(Locale locale) {\r\n NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);\r\n return new NumberTickUnitSource(false, numberFormat);\r\n }\r\n\r\n /**\r\n * Returns a collection of tick units for integer values.\r\n * Uses a given Locale to create the DecimalFormats.\r\n *\r\n * @param locale the locale to use to represent Numbers.\r\n *\r\n * @return A collection of tick units for integer values.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n */\r\n public static TickUnitSource createIntegerTickUnits(Locale locale) {\r\n NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);\r\n return new NumberTickUnitSource(true, numberFormat);\r\n }\r\n\r\n /**\r\n * Estimates the maximum tick label height.\r\n *\r\n * @param g2 the graphics device.\r\n *\r\n * @return The maximum height.\r\n */\r\n protected double estimateMaximumTickLabelHeight(Graphics2D g2) {\r\n RectangleInsets tickLabelInsets = getTickLabelInsets();\r\n double result = tickLabelInsets.getTop() + tickLabelInsets.getBottom();\r\n\r\n Font tickLabelFont = getTickLabelFont();\r\n FontRenderContext frc = g2.getFontRenderContext();\r\n result += tickLabelFont.getLineMetrics(\"123\", frc).getHeight();\r\n return result;\r\n }\r\n\r\n /**\r\n * Estimates the maximum width of the tick labels, assuming the specified\r\n * tick unit is used.\r\n * <P>\r\n * Rather than computing the string bounds of every tick on the axis, we\r\n * just look at two values: the lower bound and the upper bound for the\r\n * axis. These two values will usually be representative.\r\n *\r\n * @param g2 the graphics device.\r\n * @param unit the tick unit to use for calculation.\r\n *\r\n * @return The estimated maximum width of the tick labels.\r\n */\r\n protected double estimateMaximumTickLabelWidth(Graphics2D g2,\r\n TickUnit unit) {\r\n\r\n RectangleInsets tickLabelInsets = getTickLabelInsets();\r\n double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();\r\n\r\n if (isVerticalTickLabels()) {\r\n // all tick labels have the same width (equal to the height of the\r\n // font)...\r\n FontRenderContext frc = g2.getFontRenderContext();\r\n LineMetrics lm = getTickLabelFont().getLineMetrics(\"0\", frc);\r\n result += lm.getHeight();\r\n }\r\n else {\r\n // look at lower and upper bounds...\r\n FontMetrics fm = g2.getFontMetrics(getTickLabelFont());\r\n Range range = getRange();\r\n double lower = range.getLowerBound();\r\n double upper = range.getUpperBound();\r\n String lowerStr, upperStr;\r\n NumberFormat formatter = getNumberFormatOverride();\r\n if (formatter != null) {\r\n lowerStr = formatter.format(lower);\r\n upperStr = formatter.format(upper);\r\n }\r\n else {\r\n lowerStr = unit.valueToString(lower);\r\n upperStr = unit.valueToString(upper);\r\n }\r\n double w1 = fm.stringWidth(lowerStr);\r\n double w2 = fm.stringWidth(upperStr);\r\n result += Math.max(w1, w2);\r\n }\r\n\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Selects an appropriate tick value for the axis. The strategy is to\r\n * display as many ticks as possible (selected from an array of 'standard'\r\n * tick units) without the labels overlapping.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area defined by the axes.\r\n * @param edge the axis location.\r\n */\r\n protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea,\r\n RectangleEdge edge) {\r\n\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n selectHorizontalAutoTickUnit(g2, dataArea, edge);\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n selectVerticalAutoTickUnit(g2, dataArea, edge);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Selects an appropriate tick value for the axis. The strategy is to\r\n * display as many ticks as possible (selected from an array of 'standard'\r\n * tick units) without the labels overlapping.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area defined by the axes.\r\n * @param edge the axis location.\r\n */\r\n protected void selectHorizontalAutoTickUnit(Graphics2D g2,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n double tickLabelWidth = estimateMaximumTickLabelWidth(g2,\r\n getTickUnit());\r\n\r\n // start with the current tick unit...\r\n TickUnitSource tickUnits = getStandardTickUnits();\r\n TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());\r\n double unit1Width = lengthToJava2D(unit1.getSize(), dataArea, edge);\r\n\r\n // then extrapolate...\r\n double guess = (tickLabelWidth / unit1Width) * unit1.getSize();\r\n\r\n NumberTickUnit unit2 = (NumberTickUnit) tickUnits.getCeilingTickUnit(\r\n guess);\r\n double unit2Width = lengthToJava2D(unit2.getSize(), dataArea, edge);\r\n\r\n tickLabelWidth = estimateMaximumTickLabelWidth(g2, unit2);\r\n if (tickLabelWidth > unit2Width) {\r\n unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);\r\n }\r\n\r\n setTickUnit(unit2, false, false);\r\n\r\n }\r\n\r\n /**\r\n * Selects an appropriate tick value for the axis. The strategy is to\r\n * display as many ticks as possible (selected from an array of 'standard'\r\n * tick units) without the labels overlapping.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area in which the plot should be drawn.\r\n * @param edge the axis location.\r\n */\r\n protected void selectVerticalAutoTickUnit(Graphics2D g2, \r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n double tickLabelHeight = estimateMaximumTickLabelHeight(g2);\r\n\r\n // start with the current tick unit...\r\n TickUnitSource tickUnits = getStandardTickUnits();\r\n TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());\r\n double unitHeight = lengthToJava2D(unit1.getSize(), dataArea, edge);\r\n double guess = unit1.getSize();\r\n if (unitHeight > 0) {\r\n // then extrapolate...\r\n guess = (tickLabelHeight / unitHeight) * unit1.getSize();\r\n }\r\n NumberTickUnit unit2 = (NumberTickUnit) tickUnits.getCeilingTickUnit(\r\n guess);\r\n double unit2Height = lengthToJava2D(unit2.getSize(), dataArea, edge);\r\n\r\n tickLabelHeight = estimateMaximumTickLabelHeight(g2);\r\n if (tickLabelHeight > unit2Height) {\r\n unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);\r\n }\r\n\r\n setTickUnit(unit2, false, false);\r\n\r\n }\r\n\r\n /**\r\n * Calculates the positions of the tick labels for the axis, storing the\r\n * results in the tick label list (ready for drawing).\r\n *\r\n * @param g2 the graphics device.\r\n * @param state the axis state.\r\n * @param dataArea the area in which the plot should be drawn.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n @Override\r\n public List refreshTicks(Graphics2D g2, AxisState state, \r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List result = new java.util.ArrayList();\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n result = refreshTicksHorizontal(g2, dataArea, edge);\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n result = refreshTicksVertical(g2, dataArea, edge);\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the positions of the tick labels for the axis, storing the\r\n * results in the tick label list (ready for drawing).\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area in which the data should be drawn.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n protected List refreshTicksHorizontal(Graphics2D g2,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List result = new java.util.ArrayList();\r\n\r\n Font tickLabelFont = getTickLabelFont();\r\n g2.setFont(tickLabelFont);\r\n\r\n if (isAutoTickUnitSelection()) {\r\n selectAutoTickUnit(g2, dataArea, edge);\r\n }\r\n\r\n TickUnit tu = getTickUnit();\r\n double size = tu.getSize();\r\n int count = calculateVisibleTickCount();\r\n double lowestTickValue = calculateLowestVisibleTickValue();\r\n\r\n if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {\r\n int minorTickSpaces = getMinorTickCount();\r\n if (minorTickSpaces <= 0) {\r\n minorTickSpaces = tu.getMinorTickCount();\r\n }\r\n for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {\r\n double minorTickValue = lowestTickValue \r\n - size * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR, minorTickValue,\r\n \"\", TextAnchor.TOP_CENTER, TextAnchor.CENTER,\r\n 0.0));\r\n }\r\n }\r\n for (int i = 0; i < count; i++) {\r\n double currentTickValue = lowestTickValue + (i * size);\r\n String tickLabel;\r\n NumberFormat formatter = getNumberFormatOverride();\r\n if (formatter != null) {\r\n tickLabel = formatter.format(currentTickValue);\r\n }\r\n else {\r\n tickLabel = getTickUnit().valueToString(currentTickValue);\r\n }\r\n TextAnchor anchor, rotationAnchor;\r\n double angle = 0.0;\r\n if (isVerticalTickLabels()) {\r\n anchor = TextAnchor.CENTER_RIGHT;\r\n rotationAnchor = TextAnchor.CENTER_RIGHT;\r\n if (edge == RectangleEdge.TOP) {\r\n angle = Math.PI / 2.0;\r\n }\r\n else {\r\n angle = -Math.PI / 2.0;\r\n }\r\n }\r\n else {\r\n if (edge == RectangleEdge.TOP) {\r\n anchor = TextAnchor.BOTTOM_CENTER;\r\n rotationAnchor = TextAnchor.BOTTOM_CENTER;\r\n }\r\n else {\r\n anchor = TextAnchor.TOP_CENTER;\r\n rotationAnchor = TextAnchor.TOP_CENTER;\r\n }\r\n }\r\n\r\n Tick tick = new NumberTick(new Double(currentTickValue),\r\n tickLabel, anchor, rotationAnchor, angle);\r\n result.add(tick);\r\n double nextTickValue = lowestTickValue + ((i + 1) * size);\r\n for (int minorTick = 1; minorTick < minorTickSpaces;\r\n minorTick++) {\r\n double minorTickValue = currentTickValue\r\n + (nextTickValue - currentTickValue)\r\n * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR,\r\n minorTickValue, \"\", TextAnchor.TOP_CENTER,\r\n TextAnchor.CENTER, 0.0));\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the positions of the tick labels for the axis, storing the\r\n * results in the tick label list (ready for drawing).\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area in which the plot should be drawn.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n protected List refreshTicksVertical(Graphics2D g2,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List result = new java.util.ArrayList();\r\n result.clear();\r\n\r\n Font tickLabelFont = getTickLabelFont();\r\n g2.setFont(tickLabelFont);\r\n if (isAutoTickUnitSelection()) {\r\n selectAutoTickUnit(g2, dataArea, edge);\r\n }\r\n\r\n TickUnit tu = getTickUnit();\r\n double size = tu.getSize();\r\n int count = calculateVisibleTickCount();\r\n double lowestTickValue = calculateLowestVisibleTickValue();\r\n\r\n if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {\r\n int minorTickSpaces = getMinorTickCount();\r\n if (minorTickSpaces <= 0) {\r\n minorTickSpaces = tu.getMinorTickCount();\r\n }\r\n for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {\r\n double minorTickValue = lowestTickValue\r\n - size * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR, minorTickValue,\r\n \"\", TextAnchor.TOP_CENTER, TextAnchor.CENTER,\r\n 0.0));\r\n }\r\n }\r\n\r\n for (int i = 0; i < count; i++) {\r\n double currentTickValue = lowestTickValue + (i * size);\r\n String tickLabel;\r\n NumberFormat formatter = getNumberFormatOverride();\r\n if (formatter != null) {\r\n tickLabel = formatter.format(currentTickValue);\r\n }\r\n else {\r\n tickLabel = getTickUnit().valueToString(currentTickValue);\r\n }\r\n\r\n TextAnchor anchor;\r\n TextAnchor rotationAnchor;\r\n double angle = 0.0;\r\n if (isVerticalTickLabels()) {\r\n if (edge == RectangleEdge.LEFT) {\r\n anchor = TextAnchor.BOTTOM_CENTER;\r\n rotationAnchor = TextAnchor.BOTTOM_CENTER;\r\n angle = -Math.PI / 2.0;\r\n }\r\n else {\r\n anchor = TextAnchor.BOTTOM_CENTER;\r\n rotationAnchor = TextAnchor.BOTTOM_CENTER;\r\n angle = Math.PI / 2.0;\r\n }\r\n }\r\n else {\r\n if (edge == RectangleEdge.LEFT) {\r\n anchor = TextAnchor.CENTER_RIGHT;\r\n rotationAnchor = TextAnchor.CENTER_RIGHT;\r\n }\r\n else {\r\n anchor = TextAnchor.CENTER_LEFT;\r\n rotationAnchor = TextAnchor.CENTER_LEFT;\r\n }\r\n }\r\n\r\n Tick tick = new NumberTick(new Double(currentTickValue),\r\n tickLabel, anchor, rotationAnchor, angle);\r\n result.add(tick);\r\n\r\n double nextTickValue = lowestTickValue + ((i + 1) * size);\r\n for (int minorTick = 1; minorTick < minorTickSpaces;\r\n minorTick++) {\r\n double minorTickValue = currentTickValue\r\n + (nextTickValue - currentTickValue)\r\n * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR,\r\n minorTickValue, \"\", TextAnchor.TOP_CENTER,\r\n TextAnchor.CENTER, 0.0));\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Returns a clone of the axis.\r\n *\r\n * @return A clone\r\n *\r\n * @throws CloneNotSupportedException if some component of the axis does\r\n * not support cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n NumberAxis clone = (NumberAxis) super.clone();\r\n if (this.numberFormatOverride != null) {\r\n clone.numberFormatOverride\r\n = (NumberFormat) this.numberFormatOverride.clone();\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * Tests the axis for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof NumberAxis)) {\r\n return false;\r\n }\r\n NumberAxis that = (NumberAxis) obj;\r\n if (this.autoRangeIncludesZero != that.autoRangeIncludesZero) {\r\n return false;\r\n }\r\n if (this.autoRangeStickyZero != that.autoRangeStickyZero) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.tickUnit, that.tickUnit)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.numberFormatOverride,\r\n that.numberFormatOverride)) {\r\n return false;\r\n }\r\n if (!this.rangeType.equals(that.rangeType)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a hash code for this object.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n return super.hashCode();\r\n }\r\n\r\n}\r" }, { "identifier": "IntervalXYItemLabelGenerator", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/labels/IntervalXYItemLabelGenerator.java", "snippet": "public class IntervalXYItemLabelGenerator extends AbstractXYItemLabelGenerator\r\n implements XYItemLabelGenerator, Cloneable, PublicCloneable,\r\n Serializable {\r\n\r\n /** The default item label format. */\r\n public static final String DEFAULT_ITEM_LABEL_FORMAT = \"{5} - {6}\";\r\n\r\n /**\r\n * Creates an item label generator using default number formatters.\r\n */\r\n public IntervalXYItemLabelGenerator() {\r\n this(DEFAULT_ITEM_LABEL_FORMAT, NumberFormat.getNumberInstance(),\r\n NumberFormat.getNumberInstance());\r\n }\r\n\r\n /**\r\n * Creates an item label generator using the specified number formatters.\r\n *\r\n * @param formatString the item label format string (<code>null</code> not\r\n * permitted).\r\n * @param xFormat the format object for the x values (<code>null</code>\r\n * not permitted).\r\n * @param yFormat the format object for the y values (<code>null</code>\r\n * not permitted).\r\n */\r\n public IntervalXYItemLabelGenerator(String formatString,\r\n NumberFormat xFormat, NumberFormat yFormat) {\r\n\r\n super(formatString, xFormat, yFormat);\r\n }\r\n\r\n /**\r\n * Creates an item label generator using the specified formatters.\r\n *\r\n * @param formatString the item label format string (<code>null</code>\r\n * not permitted).\r\n * @param xFormat the format object for the x values (<code>null</code>\r\n * not permitted).\r\n * @param yFormat the format object for the y values (<code>null</code>\r\n * not permitted).\r\n */\r\n public IntervalXYItemLabelGenerator(String formatString,\r\n DateFormat xFormat, NumberFormat yFormat) {\r\n\r\n super(formatString, xFormat, yFormat);\r\n }\r\n\r\n /**\r\n * Creates an item label generator using the specified formatters (a\r\n * number formatter for the x-values and a date formatter for the\r\n * y-values).\r\n *\r\n * @param formatString the item label format string (<code>null</code>\r\n * not permitted).\r\n * @param xFormat the format object for the x values (<code>null</code>\r\n * permitted).\r\n * @param yFormat the format object for the y values (<code>null</code>\r\n * not permitted).\r\n */\r\n public IntervalXYItemLabelGenerator(String formatString,\r\n NumberFormat xFormat, DateFormat yFormat) {\r\n\r\n super(formatString, xFormat, yFormat);\r\n }\r\n\r\n /**\r\n * Creates a label generator using the specified date formatters.\r\n *\r\n * @param formatString the label format string (<code>null</code> not\r\n * permitted).\r\n * @param xFormat the format object for the x values (<code>null</code>\r\n * not permitted).\r\n * @param yFormat the format object for the y values (<code>null</code>\r\n * not permitted).\r\n */\r\n public IntervalXYItemLabelGenerator(String formatString,\r\n DateFormat xFormat, DateFormat yFormat) {\r\n\r\n super(formatString, xFormat, yFormat);\r\n }\r\n\r\n /**\r\n * Creates the array of items that can be passed to the\r\n * {@link MessageFormat} class for creating labels.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return An array of seven items from the dataset formatted as\r\n * <code>String</code> objects (never <code>null</code>).\r\n */\r\n @Override\r\n protected Object[] createItemArray(XYDataset dataset, int series,\r\n int item) {\r\n\r\n IntervalXYDataset intervalDataset = null;\r\n if (dataset instanceof IntervalXYDataset) {\r\n intervalDataset = (IntervalXYDataset) dataset;\r\n }\r\n Object[] result = new Object[7];\r\n result[0] = dataset.getSeriesKey(series).toString();\r\n\r\n double x = dataset.getXValue(series, item);\r\n double xs = x;\r\n double xe = x;\r\n double y = dataset.getYValue(series, item);\r\n double ys = y;\r\n double ye = y;\r\n if (intervalDataset != null) {\r\n xs = intervalDataset.getStartXValue(series, item);\r\n xe = intervalDataset.getEndXValue(series, item);\r\n ys = intervalDataset.getStartYValue(series, item);\r\n ye = intervalDataset.getEndYValue(series, item);\r\n }\r\n\r\n DateFormat xdf = getXDateFormat();\r\n if (xdf != null) {\r\n result[1] = xdf.format(new Date((long) x));\r\n result[2] = xdf.format(new Date((long) xs));\r\n result[3] = xdf.format(new Date((long) xe));\r\n }\r\n else {\r\n NumberFormat xnf = getXFormat();\r\n result[1] = xnf.format(x);\r\n result[2] = xnf.format(xs);\r\n result[3] = xnf.format(xe);\r\n }\r\n\r\n NumberFormat ynf = getYFormat();\r\n DateFormat ydf = getYDateFormat();\r\n if (Double.isNaN(y) && dataset.getY(series, item) == null) {\r\n result[4] = getNullYString();\r\n }\r\n else {\r\n if (ydf != null) {\r\n result[4] = ydf.format(new Date((long) y));\r\n }\r\n else {\r\n result[4] = ynf.format(y);\r\n }\r\n }\r\n if (Double.isNaN(ys) && intervalDataset != null\r\n && intervalDataset.getStartY(series, item) == null) {\r\n result[5] = getNullYString();\r\n }\r\n else {\r\n if (ydf != null) {\r\n result[5] = ydf.format(new Date((long) ys));\r\n }\r\n else {\r\n result[5] = ynf.format(ys);\r\n }\r\n }\r\n if (Double.isNaN(ye) && intervalDataset != null\r\n && intervalDataset.getEndY(series, item) == null) {\r\n result[6] = getNullYString();\r\n }\r\n else {\r\n if (ydf != null) {\r\n result[6] = ydf.format(new Date((long) ye));\r\n }\r\n else {\r\n result[6] = ynf.format(ye);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Generates the item label text for an item in a dataset.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param series the series index (zero-based).\r\n * @param item the item index (zero-based).\r\n *\r\n * @return The label text (possibly <code>null</code>).\r\n */\r\n @Override\r\n public String generateLabel(XYDataset dataset, int series, int item) {\r\n return generateLabelString(dataset, series, item);\r\n }\r\n\r\n /**\r\n * Returns an independent copy of the generator.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if cloning is not supported.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n return super.clone();\r\n }\r\n\r\n /**\r\n * Tests this object for equality with an arbitrary object.\r\n *\r\n * @param obj the other object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof IntervalXYItemLabelGenerator)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n}\r" }, { "identifier": "StandardXYItemLabelGenerator", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/labels/StandardXYItemLabelGenerator.java", "snippet": "public class StandardXYItemLabelGenerator extends AbstractXYItemLabelGenerator\r\n implements XYItemLabelGenerator, Cloneable, PublicCloneable,\r\n Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 7807668053171837925L;\r\n\r\n /** The default item label format. */\r\n public static final String DEFAULT_ITEM_LABEL_FORMAT = \"{2}\";\r\n\r\n /**\r\n * Creates an item label generator using default number formatters.\r\n */\r\n public StandardXYItemLabelGenerator() {\r\n this(DEFAULT_ITEM_LABEL_FORMAT, NumberFormat.getNumberInstance(),\r\n NumberFormat.getNumberInstance());\r\n }\r\n\r\n /**\r\n * Creates an item label generator using the specified number formatters.\r\n *\r\n * @param formatString the item label format string (<code>null</code> not\r\n * permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n public StandardXYItemLabelGenerator(String formatString) {\r\n this(formatString, NumberFormat.getNumberInstance(),\r\n NumberFormat.getNumberInstance());\r\n }\r\n\r\n /**\r\n * Creates an item label generator using the specified number formatters.\r\n *\r\n * @param formatString the item label format string (<code>null</code> not\r\n * permitted).\r\n * @param xFormat the format object for the x values (<code>null</code>\r\n * not permitted).\r\n * @param yFormat the format object for the y values (<code>null</code>\r\n * not permitted).\r\n */\r\n public StandardXYItemLabelGenerator(String formatString,\r\n NumberFormat xFormat, NumberFormat yFormat) {\r\n\r\n super(formatString, xFormat, yFormat);\r\n }\r\n\r\n /**\r\n * Creates an item label generator using the specified formatters.\r\n *\r\n * @param formatString the item label format string (<code>null</code>\r\n * not permitted).\r\n * @param xFormat the format object for the x values (<code>null</code>\r\n * not permitted).\r\n * @param yFormat the format object for the y values (<code>null</code>\r\n * not permitted).\r\n */\r\n public StandardXYItemLabelGenerator(String formatString,\r\n DateFormat xFormat, NumberFormat yFormat) {\r\n\r\n super(formatString, xFormat, yFormat);\r\n }\r\n\r\n /**\r\n * Creates an item label generator using the specified formatters (a\r\n * number formatter for the x-values and a date formatter for the\r\n * y-values).\r\n *\r\n * @param formatString the item label format string (<code>null</code>\r\n * not permitted).\r\n * @param xFormat the format object for the x values (<code>null</code>\r\n * permitted).\r\n * @param yFormat the format object for the y values (<code>null</code>\r\n * not permitted).\r\n *\r\n * @since 1.0.4\r\n */\r\n public StandardXYItemLabelGenerator(String formatString,\r\n NumberFormat xFormat, DateFormat yFormat) {\r\n\r\n super(formatString, xFormat, yFormat);\r\n }\r\n\r\n /**\r\n * Creates a label generator using the specified date formatters.\r\n *\r\n * @param formatString the label format string (<code>null</code> not\r\n * permitted).\r\n * @param xFormat the format object for the x values (<code>null</code>\r\n * not permitted).\r\n * @param yFormat the format object for the y values (<code>null</code>\r\n * not permitted).\r\n */\r\n public StandardXYItemLabelGenerator(String formatString,\r\n DateFormat xFormat, DateFormat yFormat) {\r\n\r\n super(formatString, xFormat, yFormat);\r\n }\r\n\r\n /**\r\n * Generates the item label text for an item in a dataset.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param series the series index (zero-based).\r\n * @param item the item index (zero-based).\r\n *\r\n * @return The label text (possibly <code>null</code>).\r\n */\r\n @Override\r\n public String generateLabel(XYDataset dataset, int series, int item) {\r\n return generateLabelString(dataset, series, item);\r\n }\r\n\r\n /**\r\n * Returns an independent copy of the generator.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if cloning is not supported.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n return super.clone();\r\n }\r\n\r\n /**\r\n * Tests this object for equality with an arbitrary object.\r\n *\r\n * @param obj the other object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof StandardXYItemLabelGenerator)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n}\r" }, { "identifier": "StandardXYSeriesLabelGenerator", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/labels/StandardXYSeriesLabelGenerator.java", "snippet": "public class StandardXYSeriesLabelGenerator implements XYSeriesLabelGenerator,\r\n Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 1916017081848400024L;\r\n\r\n /** The default item label format. */\r\n public static final String DEFAULT_LABEL_FORMAT = \"{0}\";\r\n\r\n /** The format pattern. */\r\n private String formatPattern;\r\n\r\n /**\r\n * Creates a default series label generator (uses\r\n * {@link #DEFAULT_LABEL_FORMAT}).\r\n */\r\n public StandardXYSeriesLabelGenerator() {\r\n this(DEFAULT_LABEL_FORMAT);\r\n }\r\n\r\n /**\r\n * Creates a new series label generator.\r\n *\r\n * @param format the format pattern (<code>null</code> not permitted).\r\n */\r\n public StandardXYSeriesLabelGenerator(String format) {\r\n ParamChecks.nullNotPermitted(format, \"format\");\r\n this.formatPattern = format;\r\n }\r\n\r\n /**\r\n * Generates a label for the specified series. This label will be\r\n * used for the chart legend.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param series the series.\r\n *\r\n * @return A series label.\r\n */\r\n @Override\r\n public String generateLabel(XYDataset dataset, int series) {\r\n ParamChecks.nullNotPermitted(dataset, \"dataset\");\r\n String label = MessageFormat.format(\r\n this.formatPattern, createItemArray(dataset, series)\r\n );\r\n return label;\r\n }\r\n\r\n /**\r\n * Creates the array of items that can be passed to the\r\n * {@link MessageFormat} class for creating labels.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The items (never <code>null</code>).\r\n */\r\n protected Object[] createItemArray(XYDataset dataset, int series) {\r\n Object[] result = new Object[1];\r\n result[0] = dataset.getSeriesKey(series).toString();\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns an independent copy of the generator. This is unnecessary,\r\n * because instances are immutable anyway, but we retain this\r\n * behaviour for backwards compatibility.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if cloning is not supported.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n return super.clone();\r\n }\r\n\r\n /**\r\n * Tests this object for equality with an arbitrary object.\r\n *\r\n * @param obj the other object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof StandardXYSeriesLabelGenerator)) {\r\n return false;\r\n }\r\n StandardXYSeriesLabelGenerator that\r\n = (StandardXYSeriesLabelGenerator) obj;\r\n if (!this.formatPattern.equals(that.formatPattern)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code for this instance.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result = 127;\r\n result = HashUtilities.hashCode(result, this.formatPattern);\r\n return result;\r\n }\r\n\r\n}\r" }, { "identifier": "StandardXYToolTipGenerator", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/labels/StandardXYToolTipGenerator.java", "snippet": "public class StandardXYToolTipGenerator extends AbstractXYItemLabelGenerator\r\n implements XYToolTipGenerator, Cloneable, PublicCloneable,\r\n Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -3564164459039540784L;\r\n\r\n /** The default tooltip format. */\r\n public static final String DEFAULT_TOOL_TIP_FORMAT = \"{0}: ({1}, {2})\";\r\n\r\n /**\r\n * Returns a tool tip generator that formats the x-values as dates and the\r\n * y-values as numbers.\r\n *\r\n * @return A tool tip generator (never <code>null</code>).\r\n */\r\n public static StandardXYToolTipGenerator getTimeSeriesInstance() {\r\n return new StandardXYToolTipGenerator(DEFAULT_TOOL_TIP_FORMAT,\r\n DateFormat.getInstance(), NumberFormat.getInstance());\r\n }\r\n\r\n /**\r\n * Creates a tool tip generator using default number formatters.\r\n */\r\n public StandardXYToolTipGenerator() {\r\n this(DEFAULT_TOOL_TIP_FORMAT, NumberFormat.getNumberInstance(),\r\n NumberFormat.getNumberInstance());\r\n }\r\n\r\n /**\r\n * Creates a tool tip generator using the specified number formatters.\r\n *\r\n * @param formatString the item label format string (<code>null</code> not\r\n * permitted).\r\n * @param xFormat the format object for the x values (<code>null</code>\r\n * not permitted).\r\n * @param yFormat the format object for the y values (<code>null</code>\r\n * not permitted).\r\n */\r\n public StandardXYToolTipGenerator(String formatString,\r\n NumberFormat xFormat, NumberFormat yFormat) {\r\n\r\n super(formatString, xFormat, yFormat);\r\n\r\n }\r\n\r\n /**\r\n * Creates a tool tip generator using the specified number formatters.\r\n *\r\n * @param formatString the label format string (<code>null</code> not\r\n * permitted).\r\n * @param xFormat the format object for the x values (<code>null</code>\r\n * not permitted).\r\n * @param yFormat the format object for the y values (<code>null</code>\r\n * not permitted).\r\n */\r\n public StandardXYToolTipGenerator(String formatString, DateFormat xFormat,\r\n NumberFormat yFormat) {\r\n\r\n super(formatString, xFormat, yFormat);\r\n\r\n }\r\n\r\n /**\r\n * Creates a tool tip generator using the specified formatters (a\r\n * number formatter for the x-values and a date formatter for the\r\n * y-values).\r\n *\r\n * @param formatString the item label format string (<code>null</code>\r\n * not permitted).\r\n * @param xFormat the format object for the x values (<code>null</code>\r\n * permitted).\r\n * @param yFormat the format object for the y values (<code>null</code>\r\n * not permitted).\r\n *\r\n * @since 1.0.4\r\n */\r\n public StandardXYToolTipGenerator(String formatString,\r\n NumberFormat xFormat, DateFormat yFormat) {\r\n\r\n super(formatString, xFormat, yFormat);\r\n }\r\n /**\r\n * Creates a tool tip generator using the specified date formatters.\r\n *\r\n * @param formatString the label format string (<code>null</code> not\r\n * permitted).\r\n * @param xFormat the format object for the x values (<code>null</code>\r\n * not permitted).\r\n * @param yFormat the format object for the y values (<code>null</code>\r\n * not permitted).\r\n */\r\n public StandardXYToolTipGenerator(String formatString,\r\n DateFormat xFormat, DateFormat yFormat) {\r\n\r\n super(formatString, xFormat, yFormat);\r\n\r\n }\r\n\r\n /**\r\n * Generates the tool tip text for an item in a dataset.\r\n *\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param series the series index (zero-based).\r\n * @param item the item index (zero-based).\r\n *\r\n * @return The tooltip text (possibly <code>null</code>).\r\n */\r\n @Override\r\n public String generateToolTip(XYDataset dataset, int series, int item) {\r\n return generateLabelString(dataset, series, item);\r\n }\r\n\r\n /**\r\n * Tests this object for equality with an arbitrary object.\r\n *\r\n * @param obj the other object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof StandardXYToolTipGenerator)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns an independent copy of the generator.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if cloning is not supported.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n return super.clone();\r\n }\r\n\r\n}\r" }, { "identifier": "XYPlot", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/XYPlot.java", "snippet": "public class XYPlot extends Plot implements ValueAxisPlot, Pannable, Zoomable,\r\n RendererChangeListener, Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 7044148245716569264L;\r\n\r\n /** The default grid line stroke. */\r\n public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f,\r\n BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f,\r\n new float[] {2.0f, 2.0f}, 0.0f);\r\n\r\n /** The default grid line paint. */\r\n public static final Paint DEFAULT_GRIDLINE_PAINT = Color.lightGray;\r\n\r\n /** The default crosshair visibility. */\r\n public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false;\r\n\r\n /** The default crosshair stroke. */\r\n public static final Stroke DEFAULT_CROSSHAIR_STROKE\r\n = DEFAULT_GRIDLINE_STROKE;\r\n\r\n /** The default crosshair paint. */\r\n public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.blue;\r\n\r\n /** The resourceBundle for the localization. */\r\n protected static ResourceBundle localizationResources\r\n = ResourceBundleWrapper.getBundle(\r\n \"org.jfree.chart.plot.LocalizationBundle\");\r\n\r\n /** The plot orientation. */\r\n private PlotOrientation orientation;\r\n\r\n /** The offset between the data area and the axes. */\r\n private RectangleInsets axisOffset;\r\n\r\n /** The domain axis / axes (used for the x-values). */\r\n private Map<Integer, ValueAxis> domainAxes;\r\n\r\n /** The domain axis locations. */\r\n private Map<Integer, AxisLocation> domainAxisLocations;\r\n\r\n /** The range axis (used for the y-values). */\r\n private Map<Integer, ValueAxis> rangeAxes;\r\n\r\n /** The range axis location. */\r\n private Map<Integer, AxisLocation> rangeAxisLocations;\r\n\r\n /** Storage for the datasets. */\r\n private Map<Integer, XYDataset> datasets;\r\n\r\n /** Storage for the renderers. */\r\n private Map<Integer, XYItemRenderer> renderers;\r\n\r\n /**\r\n * Storage for the mapping between datasets/renderers and domain axes. The\r\n * keys in the map are Integer objects, corresponding to the dataset\r\n * index. The values in the map are List objects containing Integer\r\n * objects (corresponding to the axis indices). If the map contains no\r\n * entry for a dataset, it is assumed to map to the primary domain axis\r\n * (index = 0).\r\n */\r\n private Map<Integer, List<Integer>> datasetToDomainAxesMap;\r\n\r\n /**\r\n * Storage for the mapping between datasets/renderers and range axes. The\r\n * keys in the map are Integer objects, corresponding to the dataset\r\n * index. The values in the map are List objects containing Integer\r\n * objects (corresponding to the axis indices). If the map contains no\r\n * entry for a dataset, it is assumed to map to the primary domain axis\r\n * (index = 0).\r\n */\r\n private Map<Integer, List<Integer>> datasetToRangeAxesMap;\r\n\r\n /** The origin point for the quadrants (if drawn). */\r\n private transient Point2D quadrantOrigin = new Point2D.Double(0.0, 0.0);\r\n\r\n /** The paint used for each quadrant. */\r\n private transient Paint[] quadrantPaint\r\n = new Paint[] {null, null, null, null};\r\n\r\n /** A flag that controls whether the domain grid-lines are visible. */\r\n private boolean domainGridlinesVisible;\r\n\r\n /** The stroke used to draw the domain grid-lines. */\r\n private transient Stroke domainGridlineStroke;\r\n\r\n /** The paint used to draw the domain grid-lines. */\r\n private transient Paint domainGridlinePaint;\r\n\r\n /** A flag that controls whether the range grid-lines are visible. */\r\n private boolean rangeGridlinesVisible;\r\n\r\n /** The stroke used to draw the range grid-lines. */\r\n private transient Stroke rangeGridlineStroke;\r\n\r\n /** The paint used to draw the range grid-lines. */\r\n private transient Paint rangeGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether the domain minor grid-lines are visible.\r\n *\r\n * @since 1.0.12\r\n */\r\n private boolean domainMinorGridlinesVisible;\r\n\r\n /**\r\n * The stroke used to draw the domain minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Stroke domainMinorGridlineStroke;\r\n\r\n /**\r\n * The paint used to draw the domain minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Paint domainMinorGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether the range minor grid-lines are visible.\r\n *\r\n * @since 1.0.12\r\n */\r\n private boolean rangeMinorGridlinesVisible;\r\n\r\n /**\r\n * The stroke used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Stroke rangeMinorGridlineStroke;\r\n\r\n /**\r\n * The paint used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Paint rangeMinorGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not the zero baseline against the domain\r\n * axis is visible.\r\n *\r\n * @since 1.0.5\r\n */\r\n private boolean domainZeroBaselineVisible;\r\n\r\n /**\r\n * The stroke used for the zero baseline against the domain axis.\r\n *\r\n * @since 1.0.5\r\n */\r\n private transient Stroke domainZeroBaselineStroke;\r\n\r\n /**\r\n * The paint used for the zero baseline against the domain axis.\r\n *\r\n * @since 1.0.5\r\n */\r\n private transient Paint domainZeroBaselinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not the zero baseline against the range\r\n * axis is visible.\r\n */\r\n private boolean rangeZeroBaselineVisible;\r\n\r\n /** The stroke used for the zero baseline against the range axis. */\r\n private transient Stroke rangeZeroBaselineStroke;\r\n\r\n /** The paint used for the zero baseline against the range axis. */\r\n private transient Paint rangeZeroBaselinePaint;\r\n\r\n /** A flag that controls whether or not a domain crosshair is drawn..*/\r\n private boolean domainCrosshairVisible;\r\n\r\n /** The domain crosshair value. */\r\n private double domainCrosshairValue;\r\n\r\n /** The pen/brush used to draw the crosshair (if any). */\r\n private transient Stroke domainCrosshairStroke;\r\n\r\n /** The color used to draw the crosshair (if any). */\r\n private transient Paint domainCrosshairPaint;\r\n\r\n /**\r\n * A flag that controls whether or not the crosshair locks onto actual\r\n * data points.\r\n */\r\n private boolean domainCrosshairLockedOnData = true;\r\n\r\n /** A flag that controls whether or not a range crosshair is drawn..*/\r\n private boolean rangeCrosshairVisible;\r\n\r\n /** The range crosshair value. */\r\n private double rangeCrosshairValue;\r\n\r\n /** The pen/brush used to draw the crosshair (if any). */\r\n private transient Stroke rangeCrosshairStroke;\r\n\r\n /** The color used to draw the crosshair (if any). */\r\n private transient Paint rangeCrosshairPaint;\r\n\r\n /**\r\n * A flag that controls whether or not the crosshair locks onto actual\r\n * data points.\r\n */\r\n private boolean rangeCrosshairLockedOnData = true;\r\n\r\n /** A map of lists of foreground markers (optional) for the domain axes. */\r\n private Map foregroundDomainMarkers;\r\n\r\n /** A map of lists of background markers (optional) for the domain axes. */\r\n private Map backgroundDomainMarkers;\r\n\r\n /** A map of lists of foreground markers (optional) for the range axes. */\r\n private Map foregroundRangeMarkers;\r\n\r\n /** A map of lists of background markers (optional) for the range axes. */\r\n private Map backgroundRangeMarkers;\r\n\r\n /**\r\n * A (possibly empty) list of annotations for the plot. The list should\r\n * be initialised in the constructor and never allowed to be\r\n * <code>null</code>.\r\n */\r\n private List<XYAnnotation> annotations;\r\n\r\n /** The paint used for the domain tick bands (if any). */\r\n private transient Paint domainTickBandPaint;\r\n\r\n /** The paint used for the range tick bands (if any). */\r\n private transient Paint rangeTickBandPaint;\r\n\r\n /** The fixed domain axis space. */\r\n private AxisSpace fixedDomainAxisSpace;\r\n\r\n /** The fixed range axis space. */\r\n private AxisSpace fixedRangeAxisSpace;\r\n\r\n /**\r\n * The order of the dataset rendering (REVERSE draws the primary dataset\r\n * last so that it appears to be on top).\r\n */\r\n private DatasetRenderingOrder datasetRenderingOrder\r\n = DatasetRenderingOrder.REVERSE;\r\n\r\n /**\r\n * The order of the series rendering (REVERSE draws the primary series\r\n * last so that it appears to be on top).\r\n */\r\n private SeriesRenderingOrder seriesRenderingOrder\r\n = SeriesRenderingOrder.REVERSE;\r\n\r\n /**\r\n * The weight for this plot (only relevant if this is a subplot in a\r\n * combined plot).\r\n */\r\n private int weight;\r\n\r\n /**\r\n * An optional collection of legend items that can be returned by the\r\n * getLegendItems() method.\r\n */\r\n private LegendItemCollection fixedLegendItems;\r\n\r\n /**\r\n * A flag that controls whether or not panning is enabled for the domain\r\n * axis/axes.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean domainPannable;\r\n\r\n /**\r\n * A flag that controls whether or not panning is enabled for the range\r\n * axis/axes.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean rangePannable;\r\n\r\n /**\r\n * The shadow generator (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n private ShadowGenerator shadowGenerator;\r\n\r\n /**\r\n * Creates a new <code>XYPlot</code> instance with no dataset, no axes and\r\n * no renderer. You should specify these items before using the plot.\r\n */\r\n public XYPlot() {\r\n this(null, null, null, null);\r\n }\r\n\r\n /**\r\n * Creates a new plot with the specified dataset, axes and renderer. Any\r\n * of the arguments can be <code>null</code>, but in that case you should\r\n * take care to specify the value before using the plot (otherwise a\r\n * <code>NullPointerException</code> may be thrown).\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n * @param domainAxis the domain axis (<code>null</code> permitted).\r\n * @param rangeAxis the range axis (<code>null</code> permitted).\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n */\r\n public XYPlot(XYDataset dataset, ValueAxis domainAxis, ValueAxis rangeAxis,\r\n XYItemRenderer renderer) {\r\n super();\r\n this.orientation = PlotOrientation.VERTICAL;\r\n this.weight = 1; // only relevant when this is a subplot\r\n this.axisOffset = RectangleInsets.ZERO_INSETS;\r\n\r\n // allocate storage for datasets, axes and renderers (all optional)\r\n this.domainAxes = new HashMap<Integer, ValueAxis>();\r\n this.domainAxisLocations = new HashMap<Integer, AxisLocation>();\r\n this.foregroundDomainMarkers = new HashMap();\r\n this.backgroundDomainMarkers = new HashMap();\r\n\r\n this.rangeAxes = new HashMap<Integer, ValueAxis>();\r\n this.rangeAxisLocations = new HashMap<Integer, AxisLocation>();\r\n this.foregroundRangeMarkers = new HashMap();\r\n this.backgroundRangeMarkers = new HashMap();\r\n\r\n this.datasets = new HashMap<Integer, XYDataset>();\r\n this.renderers = new HashMap<Integer, XYItemRenderer>();\r\n\r\n this.datasetToDomainAxesMap = new TreeMap();\r\n this.datasetToRangeAxesMap = new TreeMap();\r\n\r\n this.annotations = new java.util.ArrayList();\r\n\r\n this.datasets.put(0, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n\r\n this.renderers.put(0, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n\r\n this.domainAxes.put(0, domainAxis);\r\n mapDatasetToDomainAxis(0, 0);\r\n if (domainAxis != null) {\r\n domainAxis.setPlot(this);\r\n domainAxis.addChangeListener(this);\r\n }\r\n this.domainAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT);\r\n\r\n this.rangeAxes.put(0, rangeAxis);\r\n mapDatasetToRangeAxis(0, 0);\r\n if (rangeAxis != null) {\r\n rangeAxis.setPlot(this);\r\n rangeAxis.addChangeListener(this);\r\n }\r\n this.rangeAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT);\r\n\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n\r\n this.domainGridlinesVisible = true;\r\n this.domainGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.domainGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.domainMinorGridlinesVisible = false;\r\n this.domainMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.domainMinorGridlinePaint = Color.white;\r\n\r\n this.domainZeroBaselineVisible = false;\r\n this.domainZeroBaselinePaint = Color.black;\r\n this.domainZeroBaselineStroke = new BasicStroke(0.5f);\r\n\r\n this.rangeGridlinesVisible = true;\r\n this.rangeGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.rangeMinorGridlinesVisible = false;\r\n this.rangeMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeMinorGridlinePaint = Color.white;\r\n\r\n this.rangeZeroBaselineVisible = false;\r\n this.rangeZeroBaselinePaint = Color.black;\r\n this.rangeZeroBaselineStroke = new BasicStroke(0.5f);\r\n\r\n this.domainCrosshairVisible = false;\r\n this.domainCrosshairValue = 0.0;\r\n this.domainCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.domainCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n\r\n this.rangeCrosshairVisible = false;\r\n this.rangeCrosshairValue = 0.0;\r\n this.rangeCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.rangeCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n this.shadowGenerator = null;\r\n }\r\n\r\n /**\r\n * Returns the plot type as a string.\r\n *\r\n * @return A short string describing the type of plot.\r\n */\r\n @Override\r\n public String getPlotType() {\r\n return localizationResources.getString(\"XY_Plot\");\r\n }\r\n\r\n /**\r\n * Returns the orientation of the plot.\r\n *\r\n * @return The orientation (never <code>null</code>).\r\n *\r\n * @see #setOrientation(PlotOrientation)\r\n */\r\n @Override\r\n public PlotOrientation getOrientation() {\r\n return this.orientation;\r\n }\r\n\r\n /**\r\n * Sets the orientation for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param orientation the orientation (<code>null</code> not allowed).\r\n *\r\n * @see #getOrientation()\r\n */\r\n public void setOrientation(PlotOrientation orientation) {\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n if (orientation != this.orientation) {\r\n this.orientation = orientation;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the axis offset.\r\n *\r\n * @return The axis offset (never <code>null</code>).\r\n *\r\n * @see #setAxisOffset(RectangleInsets)\r\n */\r\n public RectangleInsets getAxisOffset() {\r\n return this.axisOffset;\r\n }\r\n\r\n /**\r\n * Sets the axis offsets (gap between the data area and the axes) and sends\r\n * a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param offset the offset (<code>null</code> not permitted).\r\n *\r\n * @see #getAxisOffset()\r\n */\r\n public void setAxisOffset(RectangleInsets offset) {\r\n ParamChecks.nullNotPermitted(offset, \"offset\");\r\n this.axisOffset = offset;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the domain axis with index 0. If the domain axis for this plot\r\n * is <code>null</code>, then the method will return the parent plot's\r\n * domain axis (if there is a parent plot).\r\n *\r\n * @return The domain axis (possibly <code>null</code>).\r\n *\r\n * @see #getDomainAxis(int)\r\n * @see #setDomainAxis(ValueAxis)\r\n */\r\n public ValueAxis getDomainAxis() {\r\n return getDomainAxis(0);\r\n }\r\n\r\n /**\r\n * Returns the domain axis with the specified index, or {@code null} if \r\n * there is no axis with that index.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The axis ({@code null} possible).\r\n *\r\n * @see #setDomainAxis(int, ValueAxis)\r\n */\r\n public ValueAxis getDomainAxis(int index) {\r\n ValueAxis result = this.domainAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot xy = (XYPlot) parent;\r\n result = xy.getDomainAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the domain axis for the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axis the new axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis()\r\n * @see #setDomainAxis(int, ValueAxis)\r\n */\r\n public void setDomainAxis(ValueAxis axis) {\r\n setDomainAxis(0, axis);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis(int)\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public void setDomainAxis(int index, ValueAxis axis) {\r\n setDomainAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainAxis(int)\r\n */\r\n public void setDomainAxis(int index, ValueAxis axis, boolean notify) {\r\n ValueAxis existing = getDomainAxis(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.domainAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the domain axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setRangeAxes(ValueAxis[])\r\n */\r\n public void setDomainAxes(ValueAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setDomainAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the location of the primary domain axis.\r\n *\r\n * @return The location (never <code>null</code>).\r\n *\r\n * @see #setDomainAxisLocation(AxisLocation)\r\n */\r\n public AxisLocation getDomainAxisLocation() {\r\n return (AxisLocation) this.domainAxisLocations.get(0);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary domain axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainAxisLocation()\r\n */\r\n public void setDomainAxisLocation(AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainAxisLocation()\r\n */\r\n public void setDomainAxisLocation(AxisLocation location, boolean notify) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Returns the edge for the primary domain axis (taking into account the\r\n * plot's orientation).\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getDomainAxisLocation()\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getDomainAxisEdge() {\r\n return Plot.resolveDomainAxisLocation(getDomainAxisLocation(),\r\n this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the number of domain axes.\r\n *\r\n * @return The axis count.\r\n *\r\n * @see #getRangeAxisCount()\r\n */\r\n public int getDomainAxisCount() {\r\n return this.domainAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the domain axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #clearRangeAxes()\r\n */\r\n public void clearDomainAxes() {\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.removeChangeListener(this);\r\n }\r\n }\r\n this.domainAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the domain axes.\r\n */\r\n public void configureDomainAxes() {\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the location for a domain axis. If this hasn't been set\r\n * explicitly, the method returns the location that is opposite to the\r\n * primary domain axis location.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The location (never {@code null}).\r\n *\r\n * @see #setDomainAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getDomainAxisLocation(int index) {\r\n AxisLocation result = this.domainAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getDomainAxisLocation());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location for a domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> not permitted for index\r\n * 0).\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the axis location for a domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n * @param location the location (<code>null</code> not permitted for\r\n * index 0).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n * @see #setRangeAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.domainAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the edge for a domain axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getRangeAxisEdge(int)\r\n */\r\n public RectangleEdge getDomainAxisEdge(int index) {\r\n AxisLocation location = getDomainAxisLocation(index);\r\n return Plot.resolveDomainAxisLocation(location, this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the range axis for the plot. If the range axis for this plot is\r\n * <code>null</code>, then the method will return the parent plot's range\r\n * axis (if there is a parent plot).\r\n *\r\n * @return The range axis.\r\n *\r\n * @see #getRangeAxis(int)\r\n * @see #setRangeAxis(ValueAxis)\r\n */\r\n public ValueAxis getRangeAxis() {\r\n return getRangeAxis(0);\r\n }\r\n\r\n /**\r\n * Sets the range axis for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxis()\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public void setRangeAxis(ValueAxis axis) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n // plot is likely registered as a listener with the existing axis...\r\n ValueAxis existing = getRangeAxis();\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.rangeAxes.put(0, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the location of the primary range axis.\r\n *\r\n * @return The location (never <code>null</code>).\r\n *\r\n * @see #setRangeAxisLocation(AxisLocation)\r\n */\r\n public AxisLocation getRangeAxisLocation() {\r\n return (AxisLocation) this.rangeAxisLocations.get(0);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary range axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeAxisLocation()\r\n */\r\n public void setRangeAxisLocation(AxisLocation location) {\r\n // delegate...\r\n setRangeAxisLocation(0, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary range axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRangeAxisLocation()\r\n */\r\n public void setRangeAxisLocation(AxisLocation location, boolean notify) {\r\n // delegate...\r\n setRangeAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Returns the edge for the primary range axis.\r\n *\r\n * @return The range axis edge.\r\n *\r\n * @see #getRangeAxisLocation()\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getRangeAxisEdge() {\r\n return Plot.resolveRangeAxisLocation(getRangeAxisLocation(),\r\n this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the range axis with the specified index, or {@code null} if \r\n * there is no axis with that index.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The axis ({@code null} possible).\r\n *\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public ValueAxis getRangeAxis(int index) {\r\n ValueAxis result = this.rangeAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot xy = (XYPlot) parent;\r\n result = xy.getRangeAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets a range axis and sends a {@link PlotChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxis(int)\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis) {\r\n setRangeAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a range axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRangeAxis(int)\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis, boolean notify) {\r\n ValueAxis existing = getRangeAxis(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.rangeAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the range axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setDomainAxes(ValueAxis[])\r\n */\r\n public void setRangeAxes(ValueAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setRangeAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the number of range axes.\r\n *\r\n * @return The axis count.\r\n *\r\n * @see #getDomainAxisCount()\r\n */\r\n public int getRangeAxisCount() {\r\n return this.rangeAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the range axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #clearDomainAxes()\r\n */\r\n public void clearRangeAxes() {\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.removeChangeListener(this);\r\n }\r\n }\r\n this.rangeAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the range axes.\r\n *\r\n * @see #configureDomainAxes()\r\n */\r\n public void configureRangeAxes() {\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the location for a range axis. If this hasn't been set\r\n * explicitly, the method returns the location that is opposite to the\r\n * primary range axis location.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The location (never {@code null}).\r\n *\r\n * @see #setRangeAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getRangeAxisLocation(int index) {\r\n AxisLocation result = this.rangeAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getRangeAxisLocation());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location for a range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location) {\r\n // delegate...\r\n setRangeAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the axis location for a domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> not permitted for\r\n * index 0).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #setDomainAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.rangeAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the edge for a range axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getRangeAxisEdge(int index) {\r\n AxisLocation location = getRangeAxisLocation(index);\r\n return Plot.resolveRangeAxisLocation(location, this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the primary dataset for the plot.\r\n *\r\n * @return The primary dataset (possibly <code>null</code>).\r\n *\r\n * @see #getDataset(int)\r\n * @see #setDataset(XYDataset)\r\n */\r\n public XYDataset getDataset() {\r\n return getDataset(0);\r\n }\r\n\r\n /**\r\n * Returns the dataset with the specified index, or {@code null} if there\r\n * is no dataset with that index.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The dataset (possibly {@code null}).\r\n *\r\n * @see #setDataset(int, XYDataset)\r\n */\r\n public XYDataset getDataset(int index) {\r\n return (XYDataset) this.datasets.get(index);\r\n }\r\n\r\n /**\r\n * Sets the primary dataset for the plot, replacing the existing dataset if\r\n * there is one.\r\n *\r\n * @param dataset the dataset ({@code null} permitted).\r\n *\r\n * @see #getDataset()\r\n * @see #setDataset(int, XYDataset)\r\n */\r\n public void setDataset(XYDataset dataset) {\r\n setDataset(0, dataset);\r\n }\r\n\r\n /**\r\n * Sets a dataset for the plot and sends a change event to all registered\r\n * listeners.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n *\r\n * @see #getDataset(int)\r\n */\r\n public void setDataset(int index, XYDataset dataset) {\r\n XYDataset existing = getDataset(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.datasets.put(index, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n\r\n // send a dataset change event to self...\r\n DatasetChangeEvent event = new DatasetChangeEvent(this, dataset);\r\n datasetChanged(event);\r\n }\r\n\r\n /**\r\n * Returns the number of datasets.\r\n *\r\n * @return The number of datasets.\r\n */\r\n public int getDatasetCount() {\r\n return this.datasets.size();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified dataset, or {@code -1} if the\r\n * dataset does not belong to the plot.\r\n *\r\n * @param dataset the dataset ({@code null} not permitted).\r\n *\r\n * @return The index or -1.\r\n */\r\n public int indexOf(XYDataset dataset) {\r\n for (Map.Entry<Integer, XYDataset> entry: this.datasets.entrySet()) {\r\n if (dataset == entry.getValue()) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular domain axis. All data will be plotted\r\n * against axis zero by default, no mapping is required for this case.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index.\r\n *\r\n * @see #mapDatasetToRangeAxis(int, int)\r\n */\r\n public void mapDatasetToDomainAxis(int index, int axisIndex) {\r\n List axisIndices = new java.util.ArrayList(1);\r\n axisIndices.add(new Integer(axisIndex));\r\n mapDatasetToDomainAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToDomainAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n Integer key = new Integer(index);\r\n this.datasetToDomainAxesMap.put(key, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular range axis. All data will be plotted\r\n * against axis zero by default, no mapping is required for this case.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index.\r\n *\r\n * @see #mapDatasetToDomainAxis(int, int)\r\n */\r\n public void mapDatasetToRangeAxis(int index, int axisIndex) {\r\n List axisIndices = new java.util.ArrayList(1);\r\n axisIndices.add(new Integer(axisIndex));\r\n mapDatasetToRangeAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToRangeAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n Integer key = new Integer(index);\r\n this.datasetToRangeAxesMap.put(key, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * This method is used to perform argument checking on the list of\r\n * axis indices passed to mapDatasetToDomainAxes() and\r\n * mapDatasetToRangeAxes().\r\n *\r\n * @param indices the list of indices (<code>null</code> permitted).\r\n */\r\n private void checkAxisIndices(List<Integer> indices) {\r\n // axisIndices can be:\r\n // 1. null;\r\n // 2. non-empty, containing only Integer objects that are unique.\r\n if (indices == null) {\r\n return; // OK\r\n }\r\n int count = indices.size();\r\n if (count == 0) {\r\n throw new IllegalArgumentException(\"Empty list not permitted.\");\r\n }\r\n Set<Integer> set = new HashSet<Integer>();\r\n for (Integer item : indices) {\r\n if (set.contains(item)) {\r\n throw new IllegalArgumentException(\"Indices must be unique.\");\r\n }\r\n set.add(item);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the number of renderer slots for this plot.\r\n *\r\n * @return The number of renderer slots.\r\n *\r\n * @since 1.0.11\r\n */\r\n public int getRendererCount() {\r\n return this.renderers.size();\r\n }\r\n\r\n /**\r\n * Returns the renderer for the primary dataset.\r\n *\r\n * @return The item renderer (possibly <code>null</code>).\r\n *\r\n * @see #setRenderer(XYItemRenderer)\r\n */\r\n public XYItemRenderer getRenderer() {\r\n return getRenderer(0);\r\n }\r\n\r\n /**\r\n * Returns the renderer with the specified index, or {@code null}.\r\n *\r\n * @param index the renderer index (must be &gt;= 0).\r\n *\r\n * @return The renderer (possibly {@code null}).\r\n *\r\n * @see #setRenderer(int, XYItemRenderer)\r\n */\r\n public XYItemRenderer getRenderer(int index) {\r\n return (XYItemRenderer) this.renderers.get(index);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the primary dataset and sends a change event to \r\n * all registered listeners. If the renderer is set to <code>null</code>, \r\n * no data will be displayed.\r\n *\r\n * @param renderer the renderer ({@code null} permitted).\r\n *\r\n * @see #getRenderer()\r\n */\r\n public void setRenderer(XYItemRenderer renderer) {\r\n setRenderer(0, renderer);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the dataset with the specified index and sends a \r\n * change event to all registered listeners. Note that each dataset should \r\n * have its own renderer, you should not use one renderer for multiple \r\n * datasets.\r\n *\r\n * @param index the index (must be &gt;= 0).\r\n * @param renderer the renderer.\r\n *\r\n * @see #getRenderer(int)\r\n */\r\n public void setRenderer(int index, XYItemRenderer renderer) {\r\n setRenderer(index, renderer, true);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the dataset with the specified index and, if \r\n * requested, sends a change event to all registered listeners. Note that \r\n * each dataset should have its own renderer, you should not use one \r\n * renderer for multiple datasets.\r\n *\r\n * @param index the index (must be &gt;= 0).\r\n * @param renderer the renderer.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRenderer(int)\r\n */\r\n public void setRenderer(int index, XYItemRenderer renderer, \r\n boolean notify) {\r\n XYItemRenderer existing = getRenderer(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.renderers.put(index, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the renderers for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param renderers the renderers (<code>null</code> not permitted).\r\n */\r\n public void setRenderers(XYItemRenderer[] renderers) {\r\n for (int i = 0; i < renderers.length; i++) {\r\n setRenderer(i, renderers[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the dataset rendering order.\r\n *\r\n * @return The order (never <code>null</code>).\r\n *\r\n * @see #setDatasetRenderingOrder(DatasetRenderingOrder)\r\n */\r\n public DatasetRenderingOrder getDatasetRenderingOrder() {\r\n return this.datasetRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the rendering order and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. By default, the plot renders the primary dataset\r\n * last (so that the primary dataset overlays the secondary datasets).\r\n * You can reverse this if you want to.\r\n *\r\n * @param order the rendering order (<code>null</code> not permitted).\r\n *\r\n * @see #getDatasetRenderingOrder()\r\n */\r\n public void setDatasetRenderingOrder(DatasetRenderingOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.datasetRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the series rendering order.\r\n *\r\n * @return the order (never <code>null</code>).\r\n *\r\n * @see #setSeriesRenderingOrder(SeriesRenderingOrder)\r\n */\r\n public SeriesRenderingOrder getSeriesRenderingOrder() {\r\n return this.seriesRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the series order and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. By default, the plot renders the primary series\r\n * last (so that the primary series appears to be on top).\r\n * You can reverse this if you want to.\r\n *\r\n * @param order the rendering order (<code>null</code> not permitted).\r\n *\r\n * @see #getSeriesRenderingOrder()\r\n */\r\n public void setSeriesRenderingOrder(SeriesRenderingOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.seriesRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified renderer, or <code>-1</code> if the\r\n * renderer is not assigned to this plot.\r\n *\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n *\r\n * @return The renderer index.\r\n */\r\n public int getIndexOf(XYItemRenderer renderer) {\r\n for (Map.Entry<Integer, XYItemRenderer> entry \r\n : this.renderers.entrySet()) {\r\n if (entry.getValue() == renderer) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the renderer for the specified dataset (this is either the\r\n * renderer with the same index as the dataset or, if there isn't a \r\n * renderer with the same index, the default renderer). If the dataset\r\n * does not belong to the plot, this method will return {@code null}.\r\n *\r\n * @param dataset the dataset ({@code null} permitted).\r\n *\r\n * @return The renderer (possibly {@code null}).\r\n */\r\n public XYItemRenderer getRendererForDataset(XYDataset dataset) {\r\n int datasetIndex = indexOf(dataset);\r\n if (datasetIndex < 0) {\r\n return null;\r\n } \r\n XYItemRenderer result = this.renderers.get(datasetIndex);\r\n if (result == null) {\r\n result = getRenderer();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the weight for this plot when it is used as a subplot within a\r\n * combined plot.\r\n *\r\n * @return The weight.\r\n *\r\n * @see #setWeight(int)\r\n */\r\n public int getWeight() {\r\n return this.weight;\r\n }\r\n\r\n /**\r\n * Sets the weight for the plot and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param weight the weight.\r\n *\r\n * @see #getWeight()\r\n */\r\n public void setWeight(int weight) {\r\n this.weight = weight;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the domain gridlines are visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setDomainGridlinesVisible(boolean)\r\n */\r\n public boolean isDomainGridlinesVisible() {\r\n return this.domainGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the domain grid-lines are\r\n * visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isDomainGridlinesVisible()\r\n */\r\n public void setDomainGridlinesVisible(boolean visible) {\r\n if (this.domainGridlinesVisible != visible) {\r\n this.domainGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the domain minor gridlines are visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setDomainMinorGridlinesVisible(boolean)\r\n *\r\n * @since 1.0.12\r\n */\r\n public boolean isDomainMinorGridlinesVisible() {\r\n return this.domainMinorGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the domain minor grid-lines\r\n * are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isDomainMinorGridlinesVisible()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlinesVisible(boolean visible) {\r\n if (this.domainMinorGridlinesVisible != visible) {\r\n this.domainMinorGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the grid-lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlineStroke(Stroke)\r\n */\r\n public Stroke getDomainGridlineStroke() {\r\n return this.domainGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the grid lines plotted against the domain axis, and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>stroke</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainGridlineStroke()\r\n */\r\n public void setDomainGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke for the minor grid-lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainMinorGridlineStroke(Stroke)\r\n *\r\n * @since 1.0.12\r\n */\r\n\r\n public Stroke getDomainMinorGridlineStroke() {\r\n return this.domainMinorGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the minor grid lines plotted against the domain\r\n * axis, and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>stroke</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainMinorGridlineStroke()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainMinorGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the grid lines (if any) plotted against the domain\r\n * axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlinePaint(Paint)\r\n */\r\n public Paint getDomainGridlinePaint() {\r\n return this.domainGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the grid lines plotted against the domain axis, and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>paint</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainGridlinePaint()\r\n */\r\n public void setDomainGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the minor grid lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainMinorGridlinePaint(Paint)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Paint getDomainMinorGridlinePaint() {\r\n return this.domainMinorGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the minor grid lines plotted against the domain axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>paint</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainMinorGridlinePaint()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainMinorGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range axis grid is visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeGridlinesVisible(boolean)\r\n */\r\n public boolean isRangeGridlinesVisible() {\r\n return this.rangeGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the range axis grid lines\r\n * are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeGridlinesVisible()\r\n */\r\n public void setRangeGridlinesVisible(boolean visible) {\r\n if (this.rangeGridlinesVisible != visible) {\r\n this.rangeGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlineStroke(Stroke)\r\n */\r\n public Stroke getRangeGridlineStroke() {\r\n return this.rangeGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the grid lines plotted against the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlineStroke()\r\n */\r\n public void setRangeGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the grid lines (if any) plotted against the range\r\n * axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlinePaint(Paint)\r\n */\r\n public Paint getRangeGridlinePaint() {\r\n return this.rangeGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the grid lines plotted against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlinePaint()\r\n */\r\n public void setRangeGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range axis minor grid is visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeMinorGridlinesVisible(boolean)\r\n *\r\n * @since 1.0.12\r\n */\r\n public boolean isRangeMinorGridlinesVisible() {\r\n return this.rangeMinorGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the range axis minor grid\r\n * lines are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeMinorGridlinesVisible()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlinesVisible(boolean visible) {\r\n if (this.rangeMinorGridlinesVisible != visible) {\r\n this.rangeMinorGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlineStroke(Stroke)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Stroke getRangeMinorGridlineStroke() {\r\n return this.rangeMinorGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the minor grid lines plotted against the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlineStroke()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeMinorGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlinePaint(Paint)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Paint getRangeMinorGridlinePaint() {\r\n return this.rangeMinorGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the minor grid lines plotted against the range axis\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlinePaint()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeMinorGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a zero baseline is\r\n * displayed for the domain axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setDomainZeroBaselineVisible(boolean)\r\n */\r\n public boolean isDomainZeroBaselineVisible() {\r\n return this.domainZeroBaselineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the zero baseline is\r\n * displayed for the domain axis, and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #isDomainZeroBaselineVisible()\r\n */\r\n public void setDomainZeroBaselineVisible(boolean visible) {\r\n this.domainZeroBaselineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used for the zero baseline against the domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setDomainZeroBaselineStroke(Stroke)\r\n */\r\n public Stroke getDomainZeroBaselineStroke() {\r\n return this.domainZeroBaselineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the zero baseline for the domain axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getRangeZeroBaselineStroke()\r\n */\r\n public void setDomainZeroBaselineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainZeroBaselineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the zero baseline (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainZeroBaselinePaint(Paint)\r\n */\r\n public Paint getDomainZeroBaselinePaint() {\r\n return this.domainZeroBaselinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the zero baseline plotted against the domain axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getDomainZeroBaselinePaint()\r\n */\r\n public void setDomainZeroBaselinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainZeroBaselinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a zero baseline is\r\n * displayed for the range axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n */\r\n public boolean isRangeZeroBaselineVisible() {\r\n return this.rangeZeroBaselineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the zero baseline is\r\n * displayed for the range axis, and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isRangeZeroBaselineVisible()\r\n */\r\n public void setRangeZeroBaselineVisible(boolean visible) {\r\n this.rangeZeroBaselineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used for the zero baseline against the range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselineStroke(Stroke)\r\n */\r\n public Stroke getRangeZeroBaselineStroke() {\r\n return this.rangeZeroBaselineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the zero baseline for the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselineStroke()\r\n */\r\n public void setRangeZeroBaselineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeZeroBaselineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the zero baseline (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselinePaint(Paint)\r\n */\r\n public Paint getRangeZeroBaselinePaint() {\r\n return this.rangeZeroBaselinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the zero baseline plotted against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselinePaint()\r\n */\r\n public void setRangeZeroBaselinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeZeroBaselinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the domain tick bands. If this is\r\n * <code>null</code>, no tick bands will be drawn.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setDomainTickBandPaint(Paint)\r\n */\r\n public Paint getDomainTickBandPaint() {\r\n return this.domainTickBandPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the domain tick bands.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getDomainTickBandPaint()\r\n */\r\n public void setDomainTickBandPaint(Paint paint) {\r\n this.domainTickBandPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the range tick bands. If this is\r\n * <code>null</code>, no tick bands will be drawn.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setRangeTickBandPaint(Paint)\r\n */\r\n public Paint getRangeTickBandPaint() {\r\n return this.rangeTickBandPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the range tick bands.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getRangeTickBandPaint()\r\n */\r\n public void setRangeTickBandPaint(Paint paint) {\r\n this.rangeTickBandPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the origin for the quadrants that can be displayed on the plot.\r\n * This defaults to (0, 0).\r\n *\r\n * @return The origin point (never <code>null</code>).\r\n *\r\n * @see #setQuadrantOrigin(Point2D)\r\n */\r\n public Point2D getQuadrantOrigin() {\r\n return this.quadrantOrigin;\r\n }\r\n\r\n /**\r\n * Sets the quadrant origin and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param origin the origin (<code>null</code> not permitted).\r\n *\r\n * @see #getQuadrantOrigin()\r\n */\r\n public void setQuadrantOrigin(Point2D origin) {\r\n ParamChecks.nullNotPermitted(origin, \"origin\");\r\n this.quadrantOrigin = origin;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the specified quadrant.\r\n *\r\n * @param index the quadrant index (0-3).\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setQuadrantPaint(int, Paint)\r\n */\r\n public Paint getQuadrantPaint(int index) {\r\n if (index < 0 || index > 3) {\r\n throw new IllegalArgumentException(\"The index value (\" + index\r\n + \") should be in the range 0 to 3.\");\r\n }\r\n return this.quadrantPaint[index];\r\n }\r\n\r\n /**\r\n * Sets the paint used for the specified quadrant and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the quadrant index (0-3).\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getQuadrantPaint(int)\r\n */\r\n public void setQuadrantPaint(int index, Paint paint) {\r\n if (index < 0 || index > 3) {\r\n throw new IllegalArgumentException(\"The index value (\" + index\r\n + \") should be in the range 0 to 3.\");\r\n }\r\n this.quadrantPaint[index] = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #addDomainMarker(Marker, Layer)\r\n * @see #clearDomainMarkers()\r\n */\r\n public void addDomainMarker(Marker marker) {\r\n // defer argument checking...\r\n addDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for the domain axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void addDomainMarker(Marker marker, Layer layer) {\r\n addDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Clears all the (foreground and background) domain markers and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void clearDomainMarkers() {\r\n if (this.backgroundDomainMarkers != null) {\r\n Set<Integer> keys = this.backgroundDomainMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearDomainMarkers(key);\r\n }\r\n this.backgroundDomainMarkers.clear();\r\n }\r\n if (this.foregroundDomainMarkers != null) {\r\n Set<Integer> keys = this.foregroundDomainMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearDomainMarkers(key);\r\n }\r\n this.foregroundDomainMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Clears the (foreground and background) domain markers for a particular\r\n * renderer and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the renderer index.\r\n *\r\n * @see #clearRangeMarkers(int)\r\n */\r\n public void clearDomainMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundDomainMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis (that the renderer is mapped to), however this is\r\n * entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #clearDomainMarkers(int)\r\n * @see #addRangeMarker(int, Marker, Layer)\r\n */\r\n public void addDomainMarker(int index, Marker marker, Layer layer) {\r\n addDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis (that the renderer is mapped to), however this is\r\n * entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addDomainMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ParamChecks.nullNotPermitted(layer, \"layer\");\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker) {\r\n return removeDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker, Layer layer) {\r\n return removeDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer) {\r\n return removeDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and, if requested,\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ArrayList markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (ArrayList) this.foregroundDomainMarkers.get(\r\n new Integer(index));\r\n }\r\n else {\r\n markers = (ArrayList) this.backgroundDomainMarkers.get(\r\n new Integer(index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Adds a marker for the range axis and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #addRangeMarker(Marker, Layer)\r\n */\r\n public void addRangeMarker(Marker marker) {\r\n addRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for the range axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #addRangeMarker(int, Marker, Layer)\r\n */\r\n public void addRangeMarker(Marker marker, Layer layer) {\r\n addRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Clears all the range markers and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @see #clearRangeMarkers()\r\n */\r\n public void clearRangeMarkers() {\r\n if (this.backgroundRangeMarkers != null) {\r\n Set<Integer> keys = this.backgroundRangeMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearRangeMarkers(key);\r\n }\r\n this.backgroundRangeMarkers.clear();\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Set<Integer> keys = this.foregroundRangeMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearRangeMarkers(key);\r\n }\r\n this.foregroundRangeMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #clearRangeMarkers(int)\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer) {\r\n addRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Clears the (foreground and background) range markers for a particular\r\n * renderer.\r\n *\r\n * @param index the renderer index.\r\n */\r\n public void clearRangeMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(Marker marker) {\r\n return removeRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(Marker marker, Layer layer) {\r\n return removeRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer) {\r\n return removeRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background) (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ParamChecks.nullNotPermitted(layer, \"layer\");\r\n List markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (List) this.foregroundRangeMarkers.get(\r\n new Integer(index));\r\n }\r\n else {\r\n markers = (List) this.backgroundRangeMarkers.get(\r\n new Integer(index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @see #getAnnotations()\r\n * @see #removeAnnotation(XYAnnotation)\r\n */\r\n public void addAnnotation(XYAnnotation annotation) {\r\n addAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addAnnotation(XYAnnotation annotation, boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n this.annotations.add(annotation);\r\n annotation.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n * @see #getAnnotations()\r\n */\r\n public boolean removeAnnotation(XYAnnotation annotation) {\r\n return removeAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeAnnotation(XYAnnotation annotation, boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n boolean removed = this.annotations.remove(annotation);\r\n annotation.removeChangeListener(this);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Returns the list of annotations.\r\n *\r\n * @return The list of annotations.\r\n *\r\n * @since 1.0.1\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n */\r\n public List getAnnotations() {\r\n return new ArrayList(this.annotations);\r\n }\r\n\r\n /**\r\n * Clears all the annotations and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n */\r\n public void clearAnnotations() {\r\n for (XYAnnotation annotation : this.annotations) {\r\n annotation.removeChangeListener(this);\r\n }\r\n this.annotations.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the shadow generator for the plot, if any.\r\n *\r\n * @return The shadow generator (possibly <code>null</code>).\r\n *\r\n * @since 1.0.14\r\n */\r\n public ShadowGenerator getShadowGenerator() {\r\n return this.shadowGenerator;\r\n }\r\n\r\n /**\r\n * Sets the shadow generator for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setShadowGenerator(ShadowGenerator generator) {\r\n this.shadowGenerator = generator;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Calculates the space required for all the axes in the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateAxisSpace(Graphics2D g2,\r\n Rectangle2D plotArea) {\r\n AxisSpace space = new AxisSpace();\r\n space = calculateRangeAxisSpace(g2, plotArea, space);\r\n Rectangle2D revPlotArea = space.shrink(plotArea, null);\r\n space = calculateDomainAxisSpace(g2, revPlotArea, space);\r\n return space;\r\n }\r\n\r\n /**\r\n * Calculates the space required for the domain axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateDomainAxisSpace(Graphics2D g2, \r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the domain axis...\r\n if (this.fixedDomainAxisSpace != null) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getLeft(),\r\n RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n }\r\n else if (this.orientation == PlotOrientation.VERTICAL) {\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n }\r\n }\r\n else {\r\n // reserve space for the domain axes...\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n RectangleEdge edge = getDomainAxisEdge(\r\n findDomainAxisIndex(axis));\r\n space = axis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the space required for the range axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateRangeAxisSpace(Graphics2D g2, \r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the range axis...\r\n if (this.fixedRangeAxisSpace != null) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n }\r\n else if (this.orientation == PlotOrientation.VERTICAL) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getLeft(),\r\n RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n }\r\n }\r\n else {\r\n // reserve space for the range axes...\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n RectangleEdge edge = getRangeAxisEdge(\r\n findRangeAxisIndex(axis));\r\n space = axis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Trims a rectangle to integer coordinates.\r\n *\r\n * @param rect the incoming rectangle.\r\n *\r\n * @return A rectangle with integer coordinates.\r\n */\r\n private Rectangle integerise(Rectangle2D rect) {\r\n int x0 = (int) Math.ceil(rect.getMinX());\r\n int y0 = (int) Math.ceil(rect.getMinY());\r\n int x1 = (int) Math.floor(rect.getMaxX());\r\n int y1 = (int) Math.floor(rect.getMaxY());\r\n return new Rectangle(x0, y0, (x1 - x0), (y1 - y0));\r\n }\r\n\r\n /**\r\n * Draws the plot within the specified area on a graphics device.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the plot area (in Java2D space).\r\n * @param anchor an anchor point in Java2D space (<code>null</code>\r\n * permitted).\r\n * @param parentState the state from the parent plot, if there is one\r\n * (<code>null</code> permitted).\r\n * @param info collects chart drawing information (<code>null</code>\r\n * permitted).\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor,\r\n PlotState parentState, PlotRenderingInfo info) {\r\n\r\n // if the plot area is too small, just return...\r\n boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW);\r\n boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW);\r\n if (b1 || b2) {\r\n return;\r\n }\r\n\r\n // record the plot area...\r\n if (info != null) {\r\n info.setPlotArea(area);\r\n }\r\n\r\n // adjust the drawing area for the plot insets (if any)...\r\n RectangleInsets insets = getInsets();\r\n insets.trim(area);\r\n\r\n AxisSpace space = calculateAxisSpace(g2, area);\r\n Rectangle2D dataArea = space.shrink(area, null);\r\n this.axisOffset.trim(dataArea);\r\n\r\n dataArea = integerise(dataArea);\r\n if (dataArea.isEmpty()) {\r\n return;\r\n }\r\n createAndAddEntity((Rectangle2D) dataArea.clone(), info, null, null);\r\n if (info != null) {\r\n info.setDataArea(dataArea);\r\n }\r\n\r\n // draw the plot background and axes...\r\n drawBackground(g2, dataArea);\r\n Map axisStateMap = drawAxes(g2, area, dataArea, info);\r\n\r\n PlotOrientation orient = getOrientation();\r\n\r\n // the anchor point is typically the point where the mouse last\r\n // clicked - the crosshairs will be driven off this point...\r\n if (anchor != null && !dataArea.contains(anchor)) {\r\n anchor = null;\r\n }\r\n CrosshairState crosshairState = new CrosshairState();\r\n crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY);\r\n crosshairState.setAnchor(anchor);\r\n\r\n crosshairState.setAnchorX(Double.NaN);\r\n crosshairState.setAnchorY(Double.NaN);\r\n if (anchor != null) {\r\n ValueAxis domainAxis = getDomainAxis();\r\n if (domainAxis != null) {\r\n double x;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n x = domainAxis.java2DToValue(anchor.getX(), dataArea,\r\n getDomainAxisEdge());\r\n }\r\n else {\r\n x = domainAxis.java2DToValue(anchor.getY(), dataArea,\r\n getDomainAxisEdge());\r\n }\r\n crosshairState.setAnchorX(x);\r\n }\r\n ValueAxis rangeAxis = getRangeAxis();\r\n if (rangeAxis != null) {\r\n double y;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n y = rangeAxis.java2DToValue(anchor.getY(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n else {\r\n y = rangeAxis.java2DToValue(anchor.getX(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n crosshairState.setAnchorY(y);\r\n }\r\n }\r\n crosshairState.setCrosshairX(getDomainCrosshairValue());\r\n crosshairState.setCrosshairY(getRangeCrosshairValue());\r\n Shape originalClip = g2.getClip();\r\n Composite originalComposite = g2.getComposite();\r\n\r\n g2.clip(dataArea);\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n getForegroundAlpha()));\r\n\r\n AxisState domainAxisState = (AxisState) axisStateMap.get(\r\n getDomainAxis());\r\n if (domainAxisState == null) {\r\n if (parentState != null) {\r\n domainAxisState = (AxisState) parentState.getSharedAxisStates()\r\n .get(getDomainAxis());\r\n }\r\n }\r\n\r\n AxisState rangeAxisState = (AxisState) axisStateMap.get(getRangeAxis());\r\n if (rangeAxisState == null) {\r\n if (parentState != null) {\r\n rangeAxisState = (AxisState) parentState.getSharedAxisStates()\r\n .get(getRangeAxis());\r\n }\r\n }\r\n if (domainAxisState != null) {\r\n drawDomainTickBands(g2, dataArea, domainAxisState.getTicks());\r\n }\r\n if (rangeAxisState != null) {\r\n drawRangeTickBands(g2, dataArea, rangeAxisState.getTicks());\r\n }\r\n if (domainAxisState != null) {\r\n drawDomainGridlines(g2, dataArea, domainAxisState.getTicks());\r\n drawZeroDomainBaseline(g2, dataArea);\r\n }\r\n if (rangeAxisState != null) {\r\n drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks());\r\n drawZeroRangeBaseline(g2, dataArea);\r\n }\r\n\r\n Graphics2D savedG2 = g2;\r\n BufferedImage dataImage = null;\r\n boolean suppressShadow = Boolean.TRUE.equals(g2.getRenderingHint(\r\n JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION));\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n dataImage = new BufferedImage((int) dataArea.getWidth(),\r\n (int)dataArea.getHeight(), BufferedImage.TYPE_INT_ARGB);\r\n g2 = dataImage.createGraphics();\r\n g2.translate(-dataArea.getX(), -dataArea.getY());\r\n g2.setRenderingHints(savedG2.getRenderingHints());\r\n }\r\n\r\n // draw the markers that are associated with a specific dataset...\r\n for (XYDataset dataset: this.datasets.values()) {\r\n int datasetIndex = indexOf(dataset);\r\n drawDomainMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND);\r\n }\r\n for (XYDataset dataset: this.datasets.values()) {\r\n int datasetIndex = indexOf(dataset);\r\n drawRangeMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND);\r\n }\r\n\r\n // now draw annotations and render data items...\r\n boolean foundData = false;\r\n DatasetRenderingOrder order = getDatasetRenderingOrder();\r\n List<Integer> rendererIndices = getRendererIndices(order);\r\n List<Integer> datasetIndices = getDatasetIndices(order);\r\n // draw background annotations\r\n for (int i : rendererIndices) {\r\n XYItemRenderer renderer = getRenderer(i);\r\n if (renderer != null) {\r\n ValueAxis domainAxis = getDomainAxisForDataset(i);\r\n ValueAxis rangeAxis = getRangeAxisForDataset(i);\r\n renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, \r\n Layer.BACKGROUND, info);\r\n }\r\n }\r\n\r\n // render data items...\r\n for (int datasetIndex : datasetIndices) {\r\n XYDataset dataset = this.getDataset(datasetIndex);\r\n foundData = render(g2, dataArea, datasetIndex, info, \r\n crosshairState) || foundData;\r\n }\r\n\r\n // draw foreground annotations\r\n for (int i : rendererIndices) {\r\n XYItemRenderer renderer = getRenderer(i);\r\n if (renderer != null) {\r\n ValueAxis domainAxis = getDomainAxisForDataset(i);\r\n ValueAxis rangeAxis = getRangeAxisForDataset(i);\r\n renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, \r\n Layer.FOREGROUND, info);\r\n }\r\n }\r\n\r\n // draw domain crosshair if required...\r\n int datasetIndex = crosshairState.getDatasetIndex();\r\n ValueAxis xAxis = this.getDomainAxisForDataset(datasetIndex);\r\n RectangleEdge xAxisEdge = getDomainAxisEdge(getDomainAxisIndex(xAxis));\r\n if (!this.domainCrosshairLockedOnData && anchor != null) {\r\n double xx;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n xx = xAxis.java2DToValue(anchor.getX(), dataArea, xAxisEdge);\r\n }\r\n else {\r\n xx = xAxis.java2DToValue(anchor.getY(), dataArea, xAxisEdge);\r\n }\r\n crosshairState.setCrosshairX(xx);\r\n }\r\n setDomainCrosshairValue(crosshairState.getCrosshairX(), false);\r\n if (isDomainCrosshairVisible()) {\r\n double x = getDomainCrosshairValue();\r\n Paint paint = getDomainCrosshairPaint();\r\n Stroke stroke = getDomainCrosshairStroke();\r\n drawDomainCrosshair(g2, dataArea, orient, x, xAxis, stroke, paint);\r\n }\r\n\r\n // draw range crosshair if required...\r\n ValueAxis yAxis = getRangeAxisForDataset(datasetIndex);\r\n RectangleEdge yAxisEdge = getRangeAxisEdge(getRangeAxisIndex(yAxis));\r\n if (!this.rangeCrosshairLockedOnData && anchor != null) {\r\n double yy;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n yy = yAxis.java2DToValue(anchor.getY(), dataArea, yAxisEdge);\r\n } else {\r\n yy = yAxis.java2DToValue(anchor.getX(), dataArea, yAxisEdge);\r\n }\r\n crosshairState.setCrosshairY(yy);\r\n }\r\n setRangeCrosshairValue(crosshairState.getCrosshairY(), false);\r\n if (isRangeCrosshairVisible()) {\r\n double y = getRangeCrosshairValue();\r\n Paint paint = getRangeCrosshairPaint();\r\n Stroke stroke = getRangeCrosshairStroke();\r\n drawRangeCrosshair(g2, dataArea, orient, y, yAxis, stroke, paint);\r\n }\r\n\r\n if (!foundData) {\r\n drawNoDataMessage(g2, dataArea);\r\n }\r\n\r\n for (int i : rendererIndices) { \r\n drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n for (int i : rendererIndices) {\r\n drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n\r\n drawAnnotations(g2, dataArea, info);\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n BufferedImage shadowImage\r\n = this.shadowGenerator.createDropShadow(dataImage);\r\n g2 = savedG2;\r\n g2.drawImage(shadowImage, (int) dataArea.getX()\r\n + this.shadowGenerator.calculateOffsetX(),\r\n (int) dataArea.getY()\r\n + this.shadowGenerator.calculateOffsetY(), null);\r\n g2.drawImage(dataImage, (int) dataArea.getX(),\r\n (int) dataArea.getY(), null);\r\n }\r\n g2.setClip(originalClip);\r\n g2.setComposite(originalComposite);\r\n\r\n drawOutline(g2, dataArea);\r\n\r\n }\r\n\r\n /**\r\n * Returns the indices of the non-null datasets in the specified order.\r\n * \r\n * @param order the order (<code>null</code> not permitted).\r\n * \r\n * @return The list of indices. \r\n */\r\n private List<Integer> getDatasetIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result;\r\n }\r\n \r\n private List<Integer> getRendererIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Entry<Integer, XYItemRenderer> entry : this.renderers.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result; \r\n }\r\n \r\n /**\r\n * Draws the background for the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n */\r\n @Override\r\n public void drawBackground(Graphics2D g2, Rectangle2D area) {\r\n fillBackground(g2, area, this.orientation);\r\n drawQuadrants(g2, area);\r\n drawBackgroundImage(g2, area);\r\n }\r\n\r\n /**\r\n * Draws the quadrants.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n *\r\n * @see #setQuadrantOrigin(Point2D)\r\n * @see #setQuadrantPaint(int, Paint)\r\n */\r\n protected void drawQuadrants(Graphics2D g2, Rectangle2D area) {\r\n // 0 | 1\r\n // --+--\r\n // 2 | 3\r\n boolean somethingToDraw = false;\r\n\r\n ValueAxis xAxis = getDomainAxis();\r\n if (xAxis == null) { // we can't draw quadrants without a valid x-axis\r\n return;\r\n }\r\n double x = xAxis.getRange().constrain(this.quadrantOrigin.getX());\r\n double xx = xAxis.valueToJava2D(x, area, getDomainAxisEdge());\r\n\r\n ValueAxis yAxis = getRangeAxis();\r\n if (yAxis == null) { // we can't draw quadrants without a valid y-axis\r\n return;\r\n }\r\n double y = yAxis.getRange().constrain(this.quadrantOrigin.getY());\r\n double yy = yAxis.valueToJava2D(y, area, getRangeAxisEdge());\r\n\r\n double xmin = xAxis.getLowerBound();\r\n double xxmin = xAxis.valueToJava2D(xmin, area, getDomainAxisEdge());\r\n\r\n double xmax = xAxis.getUpperBound();\r\n double xxmax = xAxis.valueToJava2D(xmax, area, getDomainAxisEdge());\r\n\r\n double ymin = yAxis.getLowerBound();\r\n double yymin = yAxis.valueToJava2D(ymin, area, getRangeAxisEdge());\r\n\r\n double ymax = yAxis.getUpperBound();\r\n double yymax = yAxis.valueToJava2D(ymax, area, getRangeAxisEdge());\r\n\r\n Rectangle2D[] r = new Rectangle2D[] {null, null, null, null};\r\n if (this.quadrantPaint[0] != null) {\r\n if (x > xmin && y < ymax) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[0] = new Rectangle2D.Double(Math.min(yymax, yy),\r\n Math.min(xxmin, xx), Math.abs(yy - yymax),\r\n Math.abs(xx - xxmin));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[0] = new Rectangle2D.Double(Math.min(xxmin, xx),\r\n Math.min(yymax, yy), Math.abs(xx - xxmin),\r\n Math.abs(yy - yymax));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[1] != null) {\r\n if (x < xmax && y < ymax) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[1] = new Rectangle2D.Double(Math.min(yymax, yy),\r\n Math.min(xxmax, xx), Math.abs(yy - yymax),\r\n Math.abs(xx - xxmax));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[1] = new Rectangle2D.Double(Math.min(xx, xxmax),\r\n Math.min(yymax, yy), Math.abs(xx - xxmax),\r\n Math.abs(yy - yymax));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[2] != null) {\r\n if (x > xmin && y > ymin) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[2] = new Rectangle2D.Double(Math.min(yymin, yy),\r\n Math.min(xxmin, xx), Math.abs(yy - yymin),\r\n Math.abs(xx - xxmin));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[2] = new Rectangle2D.Double(Math.min(xxmin, xx),\r\n Math.min(yymin, yy), Math.abs(xx - xxmin),\r\n Math.abs(yy - yymin));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[3] != null) {\r\n if (x < xmax && y > ymin) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[3] = new Rectangle2D.Double(Math.min(yymin, yy),\r\n Math.min(xxmax, xx), Math.abs(yy - yymin),\r\n Math.abs(xx - xxmax));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[3] = new Rectangle2D.Double(Math.min(xx, xxmax),\r\n Math.min(yymin, yy), Math.abs(xx - xxmax),\r\n Math.abs(yy - yymin));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (somethingToDraw) {\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n getBackgroundAlpha()));\r\n for (int i = 0; i < 4; i++) {\r\n if (this.quadrantPaint[i] != null && r[i] != null) {\r\n g2.setPaint(this.quadrantPaint[i]);\r\n g2.fill(r[i]);\r\n }\r\n }\r\n g2.setComposite(originalComposite);\r\n }\r\n }\r\n\r\n /**\r\n * Draws the domain tick bands, if any.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #setDomainTickBandPaint(Paint)\r\n */\r\n public void drawDomainTickBands(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n Paint bandPaint = getDomainTickBandPaint();\r\n if (bandPaint != null) {\r\n boolean fillBand = false;\r\n ValueAxis xAxis = getDomainAxis();\r\n double previous = xAxis.getLowerBound();\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n double current = tick.getValue();\r\n if (fillBand) {\r\n getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea,\r\n previous, current);\r\n }\r\n previous = current;\r\n fillBand = !fillBand;\r\n }\r\n double end = xAxis.getUpperBound();\r\n if (fillBand) {\r\n getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea,\r\n previous, end);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws the range tick bands, if any.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #setRangeTickBandPaint(Paint)\r\n */\r\n public void drawRangeTickBands(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n Paint bandPaint = getRangeTickBandPaint();\r\n if (bandPaint != null) {\r\n boolean fillBand = false;\r\n ValueAxis axis = getRangeAxis();\r\n double previous = axis.getLowerBound();\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n double current = tick.getValue();\r\n if (fillBand) {\r\n getRenderer().fillRangeGridBand(g2, this, axis, dataArea,\r\n previous, current);\r\n }\r\n previous = current;\r\n fillBand = !fillBand;\r\n }\r\n double end = axis.getUpperBound();\r\n if (fillBand) {\r\n getRenderer().fillRangeGridBand(g2, this, axis, dataArea,\r\n previous, end);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * A utility method for drawing the axes.\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param plotArea the plot area (<code>null</code> not permitted).\r\n * @param dataArea the data area (<code>null</code> not permitted).\r\n * @param plotState collects information about the plot (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A map containing the state for each axis drawn.\r\n */\r\n protected Map<Axis, AxisState> drawAxes(Graphics2D g2, Rectangle2D plotArea,\r\n Rectangle2D dataArea, PlotRenderingInfo plotState) {\r\n\r\n AxisCollection axisCollection = new AxisCollection();\r\n\r\n // add domain axes to lists...\r\n for (ValueAxis axis : this.domainAxes.values()) {\r\n if (axis != null) {\r\n int axisIndex = findDomainAxisIndex(axis);\r\n axisCollection.add(axis, getDomainAxisEdge(axisIndex));\r\n }\r\n }\r\n\r\n // add range axes to lists...\r\n for (ValueAxis axis : this.rangeAxes.values()) {\r\n if (axis != null) {\r\n int axisIndex = findRangeAxisIndex(axis);\r\n axisCollection.add(axis, getRangeAxisEdge(axisIndex));\r\n }\r\n }\r\n\r\n Map axisStateMap = new HashMap();\r\n\r\n // draw the top axes\r\n double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset(\r\n dataArea.getHeight());\r\n Iterator iterator = axisCollection.getAxesAtTop().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.TOP, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the bottom axes\r\n cursor = dataArea.getMaxY()\r\n + this.axisOffset.calculateBottomOutset(dataArea.getHeight());\r\n iterator = axisCollection.getAxesAtBottom().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.BOTTOM, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the left axes\r\n cursor = dataArea.getMinX()\r\n - this.axisOffset.calculateLeftOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtLeft().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.LEFT, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the right axes\r\n cursor = dataArea.getMaxX()\r\n + this.axisOffset.calculateRightOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtRight().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.RIGHT, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n return axisStateMap;\r\n }\r\n\r\n /**\r\n * Draws a representation of the data within the dataArea region, using the\r\n * current renderer.\r\n * <P>\r\n * The <code>info</code> and <code>crosshairState</code> arguments may be\r\n * <code>null</code>.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the region in which the data is to be drawn.\r\n * @param index the dataset index.\r\n * @param info an optional object for collection dimension information.\r\n * @param crosshairState collects crosshair information\r\n * (<code>null</code> permitted).\r\n *\r\n * @return A flag that indicates whether any data was actually rendered.\r\n */\r\n public boolean render(Graphics2D g2, Rectangle2D dataArea, int index,\r\n PlotRenderingInfo info, CrosshairState crosshairState) {\r\n\r\n boolean foundData = false;\r\n XYDataset dataset = getDataset(index);\r\n if (!DatasetUtilities.isEmptyOrNull(dataset)) {\r\n foundData = true;\r\n ValueAxis xAxis = getDomainAxisForDataset(index);\r\n ValueAxis yAxis = getRangeAxisForDataset(index);\r\n if (xAxis == null || yAxis == null) {\r\n return foundData; // can't render anything without axes\r\n }\r\n XYItemRenderer renderer = getRenderer(index);\r\n if (renderer == null) {\r\n renderer = getRenderer();\r\n if (renderer == null) { // no default renderer available\r\n return foundData;\r\n }\r\n }\r\n\r\n XYItemRendererState state = renderer.initialise(g2, dataArea, this,\r\n dataset, info);\r\n int passCount = renderer.getPassCount();\r\n\r\n SeriesRenderingOrder seriesOrder = getSeriesRenderingOrder();\r\n if (seriesOrder == SeriesRenderingOrder.REVERSE) {\r\n //render series in reverse order\r\n for (int pass = 0; pass < passCount; pass++) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = seriesCount - 1; series >= 0; series--) {\r\n int firstItem = 0;\r\n int lastItem = dataset.getItemCount(series) - 1;\r\n if (lastItem == -1) {\r\n continue;\r\n }\r\n if (state.getProcessVisibleItemsOnly()) {\r\n int[] itemBounds = RendererUtilities.findLiveItems(\r\n dataset, series, xAxis.getLowerBound(),\r\n xAxis.getUpperBound());\r\n firstItem = Math.max(itemBounds[0] - 1, 0);\r\n lastItem = Math.min(itemBounds[1] + 1, lastItem);\r\n }\r\n state.startSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n for (int item = firstItem; item <= lastItem; item++) {\r\n renderer.drawItem(g2, state, dataArea, info,\r\n this, xAxis, yAxis, dataset, series, item,\r\n crosshairState, pass);\r\n }\r\n state.endSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n }\r\n }\r\n }\r\n else {\r\n //render series in forward order\r\n for (int pass = 0; pass < passCount; pass++) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n int firstItem = 0;\r\n int lastItem = dataset.getItemCount(series) - 1;\r\n if (state.getProcessVisibleItemsOnly()) {\r\n int[] itemBounds = RendererUtilities.findLiveItems(\r\n dataset, series, xAxis.getLowerBound(),\r\n xAxis.getUpperBound());\r\n firstItem = Math.max(itemBounds[0] - 1, 0);\r\n lastItem = Math.min(itemBounds[1] + 1, lastItem);\r\n }\r\n state.startSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n for (int item = firstItem; item <= lastItem; item++) {\r\n renderer.drawItem(g2, state, dataArea, info,\r\n this, xAxis, yAxis, dataset, series, item,\r\n crosshairState, pass);\r\n }\r\n state.endSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n }\r\n }\r\n }\r\n }\r\n return foundData;\r\n }\r\n\r\n /**\r\n * Returns the domain axis for a dataset.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The axis.\r\n */\r\n public ValueAxis getDomainAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n ValueAxis valueAxis;\r\n List axisIndices = (List) this.datasetToDomainAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n valueAxis = getDomainAxis(axisIndex.intValue());\r\n }\r\n else {\r\n valueAxis = getDomainAxis(0);\r\n }\r\n return valueAxis;\r\n }\r\n\r\n /**\r\n * Returns the range axis for a dataset.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The axis.\r\n */\r\n public ValueAxis getRangeAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n ValueAxis valueAxis;\r\n List axisIndices = (List) this.datasetToRangeAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n valueAxis = getRangeAxis(axisIndex.intValue());\r\n }\r\n else {\r\n valueAxis = getRangeAxis(0);\r\n }\r\n return valueAxis;\r\n }\r\n\r\n /**\r\n * Draws the gridlines for the plot, if they are visible.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #drawRangeGridlines(Graphics2D, Rectangle2D, List)\r\n */\r\n protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n\r\n // no renderer, no gridlines...\r\n if (getRenderer() == null) {\r\n return;\r\n }\r\n\r\n // draw the domain grid lines, if any...\r\n if (isDomainGridlinesVisible() || isDomainMinorGridlinesVisible()) {\r\n Stroke gridStroke = null;\r\n Paint gridPaint = null;\r\n Iterator iterator = ticks.iterator();\r\n boolean paintLine;\r\n while (iterator.hasNext()) {\r\n paintLine = false;\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if ((tick.getTickType() == TickType.MINOR)\r\n && isDomainMinorGridlinesVisible()) {\r\n gridStroke = getDomainMinorGridlineStroke();\r\n gridPaint = getDomainMinorGridlinePaint();\r\n paintLine = true;\r\n } else if ((tick.getTickType() == TickType.MAJOR)\r\n && isDomainGridlinesVisible()) {\r\n gridStroke = getDomainGridlineStroke();\r\n gridPaint = getDomainGridlinePaint();\r\n paintLine = true;\r\n }\r\n XYItemRenderer r = getRenderer();\r\n if ((r instanceof AbstractXYItemRenderer) && paintLine) {\r\n ((AbstractXYItemRenderer) r).drawDomainLine(g2, this,\r\n getDomainAxis(), dataArea, tick.getValue(),\r\n gridPaint, gridStroke);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws the gridlines for the plot's primary range axis, if they are\r\n * visible.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #drawDomainGridlines(Graphics2D, Rectangle2D, List)\r\n */\r\n protected void drawRangeGridlines(Graphics2D g2, Rectangle2D area,\r\n List ticks) {\r\n\r\n // no renderer, no gridlines...\r\n if (getRenderer() == null) {\r\n return;\r\n }\r\n\r\n // draw the range grid lines, if any...\r\n if (isRangeGridlinesVisible() || isRangeMinorGridlinesVisible()) {\r\n Stroke gridStroke = null;\r\n Paint gridPaint = null;\r\n ValueAxis axis = getRangeAxis();\r\n if (axis != null) {\r\n Iterator iterator = ticks.iterator();\r\n boolean paintLine;\r\n while (iterator.hasNext()) {\r\n paintLine = false;\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if ((tick.getTickType() == TickType.MINOR)\r\n && isRangeMinorGridlinesVisible()) {\r\n gridStroke = getRangeMinorGridlineStroke();\r\n gridPaint = getRangeMinorGridlinePaint();\r\n paintLine = true;\r\n } else if ((tick.getTickType() == TickType.MAJOR)\r\n && isRangeGridlinesVisible()) {\r\n gridStroke = getRangeGridlineStroke();\r\n gridPaint = getRangeGridlinePaint();\r\n paintLine = true;\r\n }\r\n if ((tick.getValue() != 0.0\r\n || !isRangeZeroBaselineVisible()) && paintLine) {\r\n getRenderer().drawRangeLine(g2, this, getRangeAxis(),\r\n area, tick.getValue(), gridPaint, gridStroke);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws a base line across the chart at value zero on the domain axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n *\r\n * @see #setDomainZeroBaselineVisible(boolean)\r\n *\r\n * @since 1.0.5\r\n */\r\n protected void drawZeroDomainBaseline(Graphics2D g2, Rectangle2D area) {\r\n if (isDomainZeroBaselineVisible()) {\r\n XYItemRenderer r = getRenderer();\r\n // FIXME: the renderer interface doesn't have the drawDomainLine()\r\n // method, so we have to rely on the renderer being a subclass of\r\n // AbstractXYItemRenderer (which is lame)\r\n if (r instanceof AbstractXYItemRenderer) {\r\n AbstractXYItemRenderer renderer = (AbstractXYItemRenderer) r;\r\n renderer.drawDomainLine(g2, this, getDomainAxis(), area, 0.0,\r\n this.domainZeroBaselinePaint,\r\n this.domainZeroBaselineStroke);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws a base line across the chart at value zero on the range axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n */\r\n protected void drawZeroRangeBaseline(Graphics2D g2, Rectangle2D area) {\r\n if (isRangeZeroBaselineVisible()) {\r\n getRenderer().drawRangeLine(g2, this, getRangeAxis(), area, 0.0,\r\n this.rangeZeroBaselinePaint, this.rangeZeroBaselineStroke);\r\n }\r\n }\r\n\r\n /**\r\n * Draws the annotations for the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param info the chart rendering info.\r\n */\r\n public void drawAnnotations(Graphics2D g2, Rectangle2D dataArea,\r\n PlotRenderingInfo info) {\r\n\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n ValueAxis xAxis = getDomainAxis();\r\n ValueAxis yAxis = getRangeAxis();\r\n annotation.draw(g2, this, dataArea, xAxis, yAxis, 0, info);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the domain markers (if any) for an axis and layer. This method is\r\n * typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the dataset/renderer index.\r\n * @param layer the layer (foreground or background).\r\n */\r\n protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n XYItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n // check that the renderer has a corresponding dataset (it doesn't\r\n // matter if the dataset is null)\r\n if (index >= getDatasetCount()) {\r\n return;\r\n }\r\n Collection markers = getDomainMarkers(index, layer);\r\n ValueAxis axis = getDomainAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker marker = (Marker) iterator.next();\r\n r.drawDomainMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the range markers (if any) for a renderer and layer. This method\r\n * is typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the renderer index.\r\n * @param layer the layer (foreground or background).\r\n */\r\n protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n XYItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n // check that the renderer has a corresponding dataset (it doesn't\r\n // matter if the dataset is null)\r\n if (index >= getDatasetCount()) {\r\n return;\r\n }\r\n Collection markers = getRangeMarkers(index, layer);\r\n ValueAxis axis = getRangeAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker marker = (Marker) iterator.next();\r\n r.drawRangeMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the list of domain markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of domain markers.\r\n *\r\n * @see #getRangeMarkers(Layer)\r\n */\r\n public Collection getDomainMarkers(Layer layer) {\r\n return getDomainMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns the list of range markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of range markers.\r\n *\r\n * @see #getDomainMarkers(Layer)\r\n */\r\n public Collection getRangeMarkers(Layer layer) {\r\n return getRangeMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns a collection of domain markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n *\r\n * @see #getRangeMarkers(int, Layer)\r\n */\r\n public Collection getDomainMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundDomainMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundDomainMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a collection of range markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n *\r\n * @see #getDomainMarkers(int, Layer)\r\n */\r\n public Collection getRangeMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundRangeMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundRangeMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Utility method for drawing a horizontal line across the data area of the\r\n * plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param value the coordinate, where to draw the line.\r\n * @param stroke the stroke to use.\r\n * @param paint the paint to use.\r\n */\r\n protected void drawHorizontalLine(Graphics2D g2, Rectangle2D dataArea,\r\n double value, Stroke stroke,\r\n Paint paint) {\r\n\r\n ValueAxis axis = getRangeAxis();\r\n if (getOrientation() == PlotOrientation.HORIZONTAL) {\r\n axis = getDomainAxis();\r\n }\r\n if (axis.getRange().contains(value)) {\r\n double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT);\r\n Line2D line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws a domain crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param value the crosshair value.\r\n * @param axis the axis against which the value is measured.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @since 1.0.4\r\n */\r\n protected void drawDomainCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, double value, ValueAxis axis,\r\n Stroke stroke, Paint paint) {\r\n\r\n if (!axis.getRange().contains(value)) {\r\n return;\r\n }\r\n Line2D line;\r\n if (orientation == PlotOrientation.VERTICAL) {\r\n double xx = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n } else {\r\n double yy = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n\r\n /**\r\n * Utility method for drawing a vertical line on the data area of the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param value the coordinate, where to draw the line.\r\n * @param stroke the stroke to use.\r\n * @param paint the paint to use.\r\n */\r\n protected void drawVerticalLine(Graphics2D g2, Rectangle2D dataArea,\r\n double value, Stroke stroke, Paint paint) {\r\n\r\n ValueAxis axis = getDomainAxis();\r\n if (getOrientation() == PlotOrientation.HORIZONTAL) {\r\n axis = getRangeAxis();\r\n }\r\n if (axis.getRange().contains(value)) {\r\n double xx = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.BOTTOM);\r\n Line2D line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws a range crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param value the crosshair value.\r\n * @param axis the axis against which the value is measured.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @since 1.0.4\r\n */\r\n protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, double value, ValueAxis axis,\r\n Stroke stroke, Paint paint) {\r\n\r\n if (!axis.getRange().contains(value)) {\r\n return;\r\n }\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n Line2D line;\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n double xx = axis.valueToJava2D(value, dataArea, \r\n RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n } else {\r\n double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the plot by updating the anchor values.\r\n *\r\n * @param x the x-coordinate, where the click occurred, in Java2D space.\r\n * @param y the y-coordinate, where the click occurred, in Java2D space.\r\n * @param info object containing information about the plot dimensions.\r\n */\r\n @Override\r\n public void handleClick(int x, int y, PlotRenderingInfo info) {\r\n\r\n Rectangle2D dataArea = info.getDataArea();\r\n if (dataArea.contains(x, y)) {\r\n // set the anchor value for the horizontal axis...\r\n ValueAxis xaxis = getDomainAxis();\r\n if (xaxis != null) {\r\n double hvalue = xaxis.java2DToValue(x, info.getDataArea(),\r\n getDomainAxisEdge());\r\n setDomainCrosshairValue(hvalue);\r\n }\r\n\r\n // set the anchor value for the vertical axis...\r\n ValueAxis yaxis = getRangeAxis();\r\n if (yaxis != null) {\r\n double vvalue = yaxis.java2DToValue(y, info.getDataArea(),\r\n getRangeAxisEdge());\r\n setRangeCrosshairValue(vvalue);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * A utility method that returns a list of datasets that are mapped to a\r\n * particular axis.\r\n *\r\n * @param axisIndex the axis index (<code>null</code> not permitted).\r\n *\r\n * @return A list of datasets.\r\n */\r\n private List<XYDataset> getDatasetsMappedToDomainAxis(Integer axisIndex) {\r\n ParamChecks.nullNotPermitted(axisIndex, \"axisIndex\");\r\n List<XYDataset> result = new ArrayList<XYDataset>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n int index = entry.getKey();\r\n List<Integer> mappedAxes = this.datasetToDomainAxesMap.get(index);\r\n if (mappedAxes == null) {\r\n if (axisIndex.equals(ZERO)) {\r\n result.add(entry.getValue());\r\n }\r\n } else {\r\n if (mappedAxes.contains(axisIndex)) {\r\n result.add(entry.getValue());\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * A utility method that returns a list of datasets that are mapped to a\r\n * particular axis.\r\n *\r\n * @param axisIndex the axis index (<code>null</code> not permitted).\r\n *\r\n * @return A list of datasets.\r\n */\r\n private List<XYDataset> getDatasetsMappedToRangeAxis(Integer axisIndex) {\r\n ParamChecks.nullNotPermitted(axisIndex, \"axisIndex\");\r\n List<XYDataset> result = new ArrayList<XYDataset>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n int index = entry.getKey();\r\n List<Integer> mappedAxes = this.datasetToRangeAxesMap.get(index);\r\n if (mappedAxes == null) {\r\n if (axisIndex.equals(ZERO)) {\r\n result.add(entry.getValue());\r\n }\r\n } else {\r\n if (mappedAxes.contains(axisIndex)) {\r\n result.add(entry.getValue());\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the index of the given domain axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getRangeAxisIndex(ValueAxis)\r\n */\r\n public int getDomainAxisIndex(ValueAxis axis) {\r\n int result = findDomainAxisIndex(axis);\r\n if (result < 0) {\r\n // try the parent plot\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot p = (XYPlot) parent;\r\n result = p.getDomainAxisIndex(axis);\r\n }\r\n }\r\n return result;\r\n }\r\n \r\n private int findDomainAxisIndex(ValueAxis axis) {\r\n for (Map.Entry<Integer, ValueAxis> entry : this.domainAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the index of the given range axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getDomainAxisIndex(ValueAxis)\r\n */\r\n public int getRangeAxisIndex(ValueAxis axis) {\r\n int result = findRangeAxisIndex(axis);\r\n if (result < 0) {\r\n // try the parent plot\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot p = (XYPlot) parent;\r\n result = p.getRangeAxisIndex(axis);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n private int findRangeAxisIndex(ValueAxis axis) {\r\n for (Map.Entry<Integer, ValueAxis> entry : this.rangeAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the range for the specified axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The range.\r\n */\r\n @Override\r\n public Range getDataRange(ValueAxis axis) {\r\n\r\n Range result = null;\r\n List<XYDataset> mappedDatasets = new ArrayList<XYDataset>();\r\n List<XYAnnotation> includedAnnotations = new ArrayList<XYAnnotation>();\r\n boolean isDomainAxis = true;\r\n\r\n // is it a domain axis?\r\n int domainIndex = getDomainAxisIndex(axis);\r\n if (domainIndex >= 0) {\r\n isDomainAxis = true;\r\n mappedDatasets.addAll(getDatasetsMappedToDomainAxis(domainIndex));\r\n if (domainIndex == 0) {\r\n // grab the plot's annotations\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n if (annotation instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(annotation);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // or is it a range axis?\r\n int rangeIndex = getRangeAxisIndex(axis);\r\n if (rangeIndex >= 0) {\r\n isDomainAxis = false;\r\n mappedDatasets.addAll(getDatasetsMappedToRangeAxis(rangeIndex));\r\n if (rangeIndex == 0) {\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n if (annotation instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(annotation);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // iterate through the datasets that map to the axis and get the union\r\n // of the ranges.\r\n for (XYDataset d : mappedDatasets) {\r\n if (d != null) {\r\n XYItemRenderer r = getRendererForDataset(d);\r\n if (isDomainAxis) {\r\n if (r != null) {\r\n result = Range.combine(result, r.findDomainBounds(d));\r\n }\r\n else {\r\n result = Range.combine(result,\r\n DatasetUtilities.findDomainBounds(d));\r\n }\r\n }\r\n else {\r\n if (r != null) {\r\n result = Range.combine(result, r.findRangeBounds(d));\r\n }\r\n else {\r\n result = Range.combine(result,\r\n DatasetUtilities.findRangeBounds(d));\r\n }\r\n }\r\n // FIXME: the XYItemRenderer interface doesn't specify the\r\n // getAnnotations() method but it should\r\n if (r instanceof AbstractXYItemRenderer) {\r\n AbstractXYItemRenderer rr = (AbstractXYItemRenderer) r;\r\n Collection c = rr.getAnnotations();\r\n Iterator i = c.iterator();\r\n while (i.hasNext()) {\r\n XYAnnotation a = (XYAnnotation) i.next();\r\n if (a instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(a);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n Iterator it = includedAnnotations.iterator();\r\n while (it.hasNext()) {\r\n XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next();\r\n if (xyabi.getIncludeInDataBounds()) {\r\n if (isDomainAxis) {\r\n result = Range.combine(result, xyabi.getXRange());\r\n }\r\n else {\r\n result = Range.combine(result, xyabi.getYRange());\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Receives notification of a change to an {@link Annotation} added to\r\n * this plot.\r\n *\r\n * @param event information about the event (not used here).\r\n *\r\n * @since 1.0.14\r\n */\r\n @Override\r\n public void annotationChanged(AnnotationChangeEvent event) {\r\n if (getParent() != null) {\r\n getParent().annotationChanged(event);\r\n }\r\n else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a change to the plot's dataset.\r\n * <P>\r\n * The axis ranges are updated if necessary.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void datasetChanged(DatasetChangeEvent event) {\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n if (getParent() != null) {\r\n getParent().datasetChanged(event);\r\n }\r\n else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n e.setType(ChartChangeEventType.DATASET_UPDATED);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a renderer change event.\r\n *\r\n * @param event the event.\r\n */\r\n @Override\r\n public void rendererChanged(RendererChangeEvent event) {\r\n // if the event was caused by a change to series visibility, then\r\n // the axis ranges might need updating...\r\n if (event.getSeriesVisibilityChanged()) {\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the domain crosshair is visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setDomainCrosshairVisible(boolean)\r\n */\r\n public boolean isDomainCrosshairVisible() {\r\n return this.domainCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the domain crosshair is visible\r\n * and, if the flag changes, sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isDomainCrosshairVisible()\r\n */\r\n public void setDomainCrosshairVisible(boolean flag) {\r\n if (this.domainCrosshairVisible != flag) {\r\n this.domainCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the crosshair should \"lock-on\"\r\n * to actual data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setDomainCrosshairLockedOnData(boolean)\r\n */\r\n public boolean isDomainCrosshairLockedOnData() {\r\n return this.domainCrosshairLockedOnData;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the domain crosshair should\r\n * \"lock-on\" to actual data values. If the flag value changes, this\r\n * method sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isDomainCrosshairLockedOnData()\r\n */\r\n public void setDomainCrosshairLockedOnData(boolean flag) {\r\n if (this.domainCrosshairLockedOnData != flag) {\r\n this.domainCrosshairLockedOnData = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the domain crosshair value.\r\n *\r\n * @return The value.\r\n *\r\n * @see #setDomainCrosshairValue(double)\r\n */\r\n public double getDomainCrosshairValue() {\r\n return this.domainCrosshairValue;\r\n }\r\n\r\n /**\r\n * Sets the domain crosshair value and sends a {@link PlotChangeEvent} to\r\n * all registered listeners (provided that the domain crosshair is visible).\r\n *\r\n * @param value the value.\r\n *\r\n * @see #getDomainCrosshairValue()\r\n */\r\n public void setDomainCrosshairValue(double value) {\r\n setDomainCrosshairValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the domain crosshair value and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners (provided that the\r\n * domain crosshair is visible).\r\n *\r\n * @param value the new value.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainCrosshairValue()\r\n */\r\n public void setDomainCrosshairValue(double value, boolean notify) {\r\n this.domainCrosshairValue = value;\r\n if (isDomainCrosshairVisible() && notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the {@link Stroke} used to draw the crosshair (if visible).\r\n *\r\n * @return The crosshair stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainCrosshairStroke(Stroke)\r\n * @see #isDomainCrosshairVisible()\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public Stroke getDomainCrosshairStroke() {\r\n return this.domainCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the Stroke used to draw the crosshairs (if visible) and notifies\r\n * registered listeners that the axis has been modified.\r\n *\r\n * @param stroke the new crosshair stroke (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public void setDomainCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainCrosshairStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the domain crosshair paint.\r\n *\r\n * @return The crosshair paint (never <code>null</code>).\r\n *\r\n * @see #setDomainCrosshairPaint(Paint)\r\n * @see #isDomainCrosshairVisible()\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public Paint getDomainCrosshairPaint() {\r\n return this.domainCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the new crosshair paint (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public void setDomainCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the range crosshair is visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairVisible(boolean)\r\n * @see #isDomainCrosshairVisible()\r\n */\r\n public boolean isRangeCrosshairVisible() {\r\n return this.rangeCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair is visible.\r\n * If the flag value changes, this method sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isRangeCrosshairVisible()\r\n */\r\n public void setRangeCrosshairVisible(boolean flag) {\r\n if (this.rangeCrosshairVisible != flag) {\r\n this.rangeCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the crosshair should \"lock-on\"\r\n * to actual data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairLockedOnData(boolean)\r\n */\r\n public boolean isRangeCrosshairLockedOnData() {\r\n return this.rangeCrosshairLockedOnData;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair should\r\n * \"lock-on\" to actual data values. If the flag value changes, this method\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isRangeCrosshairLockedOnData()\r\n */\r\n public void setRangeCrosshairLockedOnData(boolean flag) {\r\n if (this.rangeCrosshairLockedOnData != flag) {\r\n this.rangeCrosshairLockedOnData = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range crosshair value.\r\n *\r\n * @return The value.\r\n *\r\n * @see #setRangeCrosshairValue(double)\r\n */\r\n public double getRangeCrosshairValue() {\r\n return this.rangeCrosshairValue;\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value.\r\n * <P>\r\n * Registered listeners are notified that the plot has been modified, but\r\n * only if the crosshair is visible.\r\n *\r\n * @param value the new value.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value) {\r\n setRangeCrosshairValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value and sends a {@link PlotChangeEvent} to\r\n * all registered listeners, but only if the crosshair is visible.\r\n *\r\n * @param value the new value.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value, boolean notify) {\r\n this.rangeCrosshairValue = value;\r\n if (isRangeCrosshairVisible() && notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the crosshair (if visible).\r\n *\r\n * @return The crosshair stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairStroke(Stroke)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public Stroke getRangeCrosshairStroke() {\r\n return this.rangeCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the new crosshair stroke (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public void setRangeCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeCrosshairStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the range crosshair paint.\r\n *\r\n * @return The crosshair paint (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairPaint(Paint)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public Paint getRangeCrosshairPaint() {\r\n return this.rangeCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to color the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the new crosshair paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public void setRangeCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the fixed domain axis space.\r\n *\r\n * @return The fixed domain axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedDomainAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedDomainAxisSpace() {\r\n return this.fixedDomainAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space) {\r\n setFixedDomainAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n *\r\n * @since 1.0.9\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedDomainAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the fixed range axis space.\r\n *\r\n * @return The fixed range axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedRangeAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedRangeAxisSpace() {\r\n return this.fixedRangeAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space) {\r\n setFixedRangeAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n *\r\n * @since 1.0.9\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedRangeAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if panning is enabled for the domain axes,\r\n * and <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isDomainPannable() {\r\n return this.domainPannable;\r\n }\r\n\r\n /**\r\n * Sets the flag that enables or disables panning of the plot along the\r\n * domain axes.\r\n *\r\n * @param pannable the new flag value.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setDomainPannable(boolean pannable) {\r\n this.domainPannable = pannable;\r\n }\r\n\r\n /**\r\n * Returns {@code true} if panning is enabled for the range axis/axes,\r\n * and {@code false} otherwise. The default value is {@code false}.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isRangePannable() {\r\n return this.rangePannable;\r\n }\r\n\r\n /**\r\n * Sets the flag that enables or disables panning of the plot along\r\n * the range axis/axes.\r\n *\r\n * @param pannable the new flag value.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangePannable(boolean pannable) {\r\n this.rangePannable = pannable;\r\n }\r\n\r\n /**\r\n * Pans the domain axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panDomainAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n if (!isDomainPannable()) {\r\n return;\r\n }\r\n int domainAxisCount = getDomainAxisCount();\r\n for (int i = 0; i < domainAxisCount; i++) {\r\n ValueAxis axis = getDomainAxis(i);\r\n if (axis == null) {\r\n continue;\r\n }\r\n if (axis.isInverted()) {\r\n percent = -percent;\r\n }\r\n axis.pan(percent);\r\n }\r\n }\r\n\r\n /**\r\n * Pans the range axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panRangeAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n if (!isRangePannable()) {\r\n return;\r\n }\r\n int rangeAxisCount = getRangeAxisCount();\r\n for (int i = 0; i < rangeAxisCount; i++) {\r\n ValueAxis axis = getRangeAxis(i);\r\n if (axis == null) {\r\n continue;\r\n }\r\n if (axis.isInverted()) {\r\n percent = -percent;\r\n }\r\n axis.pan(percent);\r\n }\r\n }\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point (in Java2D space).\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo info,\r\n Point2D source) {\r\n // delegate to other method\r\n zoomDomainAxes(factor, info, source, false);\r\n }\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point (in Java2D space).\r\n * @param useAnchor use source point as zoom anchor?\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n\r\n // perform the zoom on each domain axis\r\n for (ValueAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis == null) {\r\n continue;\r\n }\r\n if (useAnchor) {\r\n // get the relevant source coordinate given the plot orientation\r\n double sourceX = source.getX();\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n sourceX = source.getY();\r\n }\r\n double anchorX = xAxis.java2DToValue(sourceX,\r\n info.getDataArea(), getDomainAxisEdge());\r\n xAxis.resizeRange2(factor, anchorX);\r\n } else {\r\n xAxis.resizeRange(factor);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the domain axis/axes. The new lower and upper bounds are\r\n * specified as percentages of the current axis range, where 0 percent is\r\n * the current lower bound and 100 percent is the current upper bound.\r\n *\r\n * @param lowerPercent a percentage that determines the new lower bound\r\n * for the axis (e.g. 0.20 is twenty percent).\r\n * @param upperPercent a percentage that determines the new upper bound\r\n * for the axis (e.g. 0.80 is eighty percent).\r\n * @param info the plot rendering info.\r\n * @param source the source point (ignored).\r\n *\r\n * @see #zoomRangeAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomDomainAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo info, Point2D source) {\r\n for (ValueAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n xAxis.zoomRange(lowerPercent, upperPercent);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo info,\r\n Point2D source) {\r\n // delegate to other method\r\n zoomRangeAxes(factor, info, source, false);\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n * @param useAnchor a flag that controls whether or not the source point\r\n * is used for the zoom anchor.\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n\r\n // perform the zoom on each range axis\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis == null) {\r\n continue;\r\n }\r\n if (useAnchor) {\r\n // get the relevant source coordinate given the plot orientation\r\n double sourceY = source.getY();\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n sourceY = source.getX();\r\n }\r\n double anchorY = yAxis.java2DToValue(sourceY,\r\n info.getDataArea(), getRangeAxisEdge());\r\n yAxis.resizeRange2(factor, anchorY);\r\n } else {\r\n yAxis.resizeRange(factor);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the range axes.\r\n *\r\n * @param lowerPercent the lower bound.\r\n * @param upperPercent the upper bound.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n *\r\n * @see #zoomDomainAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomRangeAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo info, Point2D source) {\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.zoomRange(lowerPercent, upperPercent);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code>, indicating that the domain axis/axes for this\r\n * plot are zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isRangeZoomable()\r\n */\r\n @Override\r\n public boolean isDomainZoomable() {\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code>, indicating that the range axis/axes for this\r\n * plot are zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isDomainZoomable()\r\n */\r\n @Override\r\n public boolean isRangeZoomable() {\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns the number of series in the primary dataset for this plot. If\r\n * the dataset is <code>null</code>, the method returns 0.\r\n *\r\n * @return The series count.\r\n */\r\n public int getSeriesCount() {\r\n int result = 0;\r\n XYDataset dataset = getDataset();\r\n if (dataset != null) {\r\n result = dataset.getSeriesCount();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the fixed legend items, if any.\r\n *\r\n * @return The legend items (possibly <code>null</code>).\r\n *\r\n * @see #setFixedLegendItems(LegendItemCollection)\r\n */\r\n public LegendItemCollection getFixedLegendItems() {\r\n return this.fixedLegendItems;\r\n }\r\n\r\n /**\r\n * Sets the fixed legend items for the plot. Leave this set to\r\n * <code>null</code> if you prefer the legend items to be created\r\n * automatically.\r\n *\r\n * @param items the legend items (<code>null</code> permitted).\r\n *\r\n * @see #getFixedLegendItems()\r\n */\r\n public void setFixedLegendItems(LegendItemCollection items) {\r\n this.fixedLegendItems = items;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the legend items for the plot. Each legend item is generated by\r\n * the plot's renderer, since the renderer is responsible for the visual\r\n * representation of the data.\r\n *\r\n * @return The legend items.\r\n */\r\n @Override\r\n public LegendItemCollection getLegendItems() {\r\n if (this.fixedLegendItems != null) {\r\n return this.fixedLegendItems;\r\n }\r\n LegendItemCollection result = new LegendItemCollection();\r\n for (XYDataset dataset : this.datasets.values()) {\r\n if (dataset == null) {\r\n continue;\r\n }\r\n int datasetIndex = indexOf(dataset);\r\n XYItemRenderer renderer = getRenderer(datasetIndex);\r\n if (renderer == null) {\r\n renderer = getRenderer(0);\r\n }\r\n if (renderer != null) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int i = 0; i < seriesCount; i++) {\r\n if (renderer.isSeriesVisible(i)\r\n && renderer.isSeriesVisibleInLegend(i)) {\r\n LegendItem item = renderer.getLegendItem(\r\n datasetIndex, i);\r\n if (item != null) {\r\n result.add(item);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Tests this plot for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof XYPlot)) {\r\n return false;\r\n }\r\n XYPlot that = (XYPlot) obj;\r\n if (this.weight != that.weight) {\r\n return false;\r\n }\r\n if (this.orientation != that.orientation) {\r\n return false;\r\n }\r\n if (!this.domainAxes.equals(that.domainAxes)) {\r\n return false;\r\n }\r\n if (!this.domainAxisLocations.equals(that.domainAxisLocations)) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairLockedOnData\r\n != that.rangeCrosshairLockedOnData) {\r\n return false;\r\n }\r\n if (this.domainGridlinesVisible != that.domainGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.rangeGridlinesVisible != that.rangeGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.domainMinorGridlinesVisible\r\n != that.domainMinorGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.rangeMinorGridlinesVisible\r\n != that.rangeMinorGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.domainZeroBaselineVisible != that.domainZeroBaselineVisible) {\r\n return false;\r\n }\r\n if (this.rangeZeroBaselineVisible != that.rangeZeroBaselineVisible) {\r\n return false;\r\n }\r\n if (this.domainCrosshairVisible != that.domainCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.domainCrosshairValue != that.domainCrosshairValue) {\r\n return false;\r\n }\r\n if (this.domainCrosshairLockedOnData\r\n != that.domainCrosshairLockedOnData) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairVisible != that.rangeCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairValue != that.rangeCrosshairValue) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.axisOffset, that.axisOffset)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.renderers, that.renderers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeAxes, that.rangeAxes)) {\r\n return false;\r\n }\r\n if (!this.rangeAxisLocations.equals(that.rangeAxisLocations)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToDomainAxesMap,\r\n that.datasetToDomainAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToRangeAxesMap,\r\n that.datasetToRangeAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainGridlineStroke,\r\n that.domainGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainGridlinePaint,\r\n that.domainGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeGridlineStroke,\r\n that.rangeGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeGridlinePaint,\r\n that.rangeGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainMinorGridlineStroke,\r\n that.domainMinorGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainMinorGridlinePaint,\r\n that.domainMinorGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeMinorGridlineStroke,\r\n that.rangeMinorGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeMinorGridlinePaint,\r\n that.rangeMinorGridlinePaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainZeroBaselinePaint,\r\n that.domainZeroBaselinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainZeroBaselineStroke,\r\n that.domainZeroBaselineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeZeroBaselinePaint,\r\n that.rangeZeroBaselinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeZeroBaselineStroke,\r\n that.rangeZeroBaselineStroke)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainCrosshairStroke,\r\n that.domainCrosshairStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainCrosshairPaint,\r\n that.domainCrosshairPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeCrosshairStroke,\r\n that.rangeCrosshairStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeCrosshairPaint,\r\n that.rangeCrosshairPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundDomainMarkers,\r\n that.foregroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundDomainMarkers,\r\n that.backgroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundRangeMarkers,\r\n that.foregroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundRangeMarkers,\r\n that.backgroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundDomainMarkers,\r\n that.foregroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundDomainMarkers,\r\n that.backgroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundRangeMarkers,\r\n that.foregroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundRangeMarkers,\r\n that.backgroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.annotations, that.annotations)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.fixedLegendItems,\r\n that.fixedLegendItems)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainTickBandPaint,\r\n that.domainTickBandPaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeTickBandPaint,\r\n that.rangeTickBandPaint)) {\r\n return false;\r\n }\r\n if (!this.quadrantOrigin.equals(that.quadrantOrigin)) {\r\n return false;\r\n }\r\n for (int i = 0; i < 4; i++) {\r\n if (!PaintUtilities.equal(this.quadrantPaint[i],\r\n that.quadrantPaint[i])) {\r\n return false;\r\n }\r\n }\r\n if (!ObjectUtilities.equal(this.shadowGenerator,\r\n that.shadowGenerator)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a clone of the plot.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException this can occur if some component of\r\n * the plot cannot be cloned.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n XYPlot clone = (XYPlot) super.clone();\r\n clone.domainAxes = CloneUtils.cloneMapValues(this.domainAxes);\r\n for (ValueAxis axis : clone.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n clone.rangeAxes = CloneUtils.cloneMapValues(this.rangeAxes);\r\n for (ValueAxis axis : clone.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n clone.domainAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.domainAxisLocations);\r\n clone.rangeAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.rangeAxisLocations);\r\n\r\n // the datasets are not cloned, but listeners need to be added...\r\n clone.datasets = new HashMap<Integer, XYDataset>(this.datasets);\r\n for (XYDataset dataset : clone.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(clone);\r\n }\r\n }\r\n\r\n clone.datasetToDomainAxesMap = new TreeMap();\r\n clone.datasetToDomainAxesMap.putAll(this.datasetToDomainAxesMap);\r\n clone.datasetToRangeAxesMap = new TreeMap();\r\n clone.datasetToRangeAxesMap.putAll(this.datasetToRangeAxesMap);\r\n\r\n clone.renderers = CloneUtils.cloneMapValues(this.renderers);\r\n for (XYItemRenderer renderer : clone.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.setPlot(clone);\r\n renderer.addChangeListener(clone);\r\n }\r\n }\r\n clone.foregroundDomainMarkers = (Map) ObjectUtilities.clone(\r\n this.foregroundDomainMarkers);\r\n clone.backgroundDomainMarkers = (Map) ObjectUtilities.clone(\r\n this.backgroundDomainMarkers);\r\n clone.foregroundRangeMarkers = (Map) ObjectUtilities.clone(\r\n this.foregroundRangeMarkers);\r\n clone.backgroundRangeMarkers = (Map) ObjectUtilities.clone(\r\n this.backgroundRangeMarkers);\r\n clone.annotations = (List) ObjectUtilities.deepClone(this.annotations);\r\n if (this.fixedDomainAxisSpace != null) {\r\n clone.fixedDomainAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedDomainAxisSpace);\r\n }\r\n if (this.fixedRangeAxisSpace != null) {\r\n clone.fixedRangeAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedRangeAxisSpace);\r\n }\r\n if (this.fixedLegendItems != null) {\r\n clone.fixedLegendItems\r\n = (LegendItemCollection) this.fixedLegendItems.clone();\r\n }\r\n clone.quadrantOrigin = (Point2D) ObjectUtilities.clone(\r\n this.quadrantOrigin);\r\n clone.quadrantPaint = this.quadrantPaint.clone();\r\n return clone;\r\n\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.domainGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.domainGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.domainMinorGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.domainMinorGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeMinorGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeMinorGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeZeroBaselineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeZeroBaselinePaint, stream);\r\n SerialUtilities.writeStroke(this.domainCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.domainCrosshairPaint, stream);\r\n SerialUtilities.writeStroke(this.rangeCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.rangeCrosshairPaint, stream);\r\n SerialUtilities.writePaint(this.domainTickBandPaint, stream);\r\n SerialUtilities.writePaint(this.rangeTickBandPaint, stream);\r\n SerialUtilities.writePoint2D(this.quadrantOrigin, stream);\r\n for (int i = 0; i < 4; i++) {\r\n SerialUtilities.writePaint(this.quadrantPaint[i], stream);\r\n }\r\n SerialUtilities.writeStroke(this.domainZeroBaselineStroke, stream);\r\n SerialUtilities.writePaint(this.domainZeroBaselinePaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n\r\n stream.defaultReadObject();\r\n this.domainGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.domainGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.domainMinorGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.domainMinorGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeMinorGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeMinorGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeZeroBaselineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeZeroBaselinePaint = SerialUtilities.readPaint(stream);\r\n this.domainCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.domainCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.rangeCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.rangeCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.domainTickBandPaint = SerialUtilities.readPaint(stream);\r\n this.rangeTickBandPaint = SerialUtilities.readPaint(stream);\r\n this.quadrantOrigin = SerialUtilities.readPoint2D(stream);\r\n this.quadrantPaint = new Paint[4];\r\n for (int i = 0; i < 4; i++) {\r\n this.quadrantPaint[i] = SerialUtilities.readPaint(stream);\r\n }\r\n\r\n this.domainZeroBaselineStroke = SerialUtilities.readStroke(stream);\r\n this.domainZeroBaselinePaint = SerialUtilities.readPaint(stream);\r\n\r\n // register the plot as a listener with its axes, datasets, and\r\n // renderers...\r\n for (ValueAxis axis : this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n axis.addChangeListener(this);\r\n }\r\n }\r\n for (ValueAxis axis : this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n axis.addChangeListener(this);\r\n }\r\n }\r\n for (XYDataset dataset : this.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n }\r\n for (XYItemRenderer renderer : this.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.addChangeListener(this);\r\n }\r\n }\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "StandardXYURLGenerator", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/urls/StandardXYURLGenerator.java", "snippet": "public class StandardXYURLGenerator implements XYURLGenerator, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -1771624523496595382L;\r\n\r\n /** The default prefix. */\r\n public static final String DEFAULT_PREFIX = \"index.html\";\r\n\r\n /** The default series parameter. */\r\n public static final String DEFAULT_SERIES_PARAMETER = \"series\";\r\n\r\n /** The default item parameter. */\r\n public static final String DEFAULT_ITEM_PARAMETER = \"item\";\r\n\r\n /** Prefix to the URL */\r\n private String prefix;\r\n\r\n /** Series parameter name to go in each URL */\r\n private String seriesParameterName;\r\n\r\n /** Item parameter name to go in each URL */\r\n private String itemParameterName;\r\n\r\n /**\r\n * Creates a new default generator. This constructor is equivalent to\r\n * calling <code>StandardXYURLGenerator(\"index.html\", \"series\", \"item\");\r\n * </code>.\r\n */\r\n public StandardXYURLGenerator() {\r\n this(DEFAULT_PREFIX, DEFAULT_SERIES_PARAMETER, DEFAULT_ITEM_PARAMETER);\r\n }\r\n\r\n /**\r\n * Creates a new generator with the specified prefix. This constructor\r\n * is equivalent to calling\r\n * <code>StandardXYURLGenerator(prefix, \"series\", \"item\");</code>.\r\n *\r\n * @param prefix the prefix to the URL (<code>null</code> not permitted).\r\n */\r\n public StandardXYURLGenerator(String prefix) {\r\n this(prefix, DEFAULT_SERIES_PARAMETER, DEFAULT_ITEM_PARAMETER);\r\n }\r\n\r\n /**\r\n * Constructor that overrides all the defaults\r\n *\r\n * @param prefix the prefix to the URL (<code>null</code> not permitted).\r\n * @param seriesParameterName the name of the series parameter to go in\r\n * each URL (<code>null</code> not permitted).\r\n * @param itemParameterName the name of the item parameter to go in each\r\n * URL (<code>null</code> not permitted).\r\n */\r\n public StandardXYURLGenerator(String prefix, String seriesParameterName,\r\n String itemParameterName) {\r\n ParamChecks.nullNotPermitted(prefix, \"prefix\");\r\n ParamChecks.nullNotPermitted(seriesParameterName, \"seriesParameterName\");\r\n ParamChecks.nullNotPermitted(itemParameterName, \"itemParameterName\");\r\n this.prefix = prefix;\r\n this.seriesParameterName = seriesParameterName;\r\n this.itemParameterName = itemParameterName;\r\n }\r\n\r\n /**\r\n * Generates a URL for a particular item within a series.\r\n *\r\n * @param dataset the dataset.\r\n * @param series the series number (zero-based index).\r\n * @param item the item number (zero-based index).\r\n *\r\n * @return The generated URL.\r\n */\r\n @Override\r\n public String generateURL(XYDataset dataset, int series, int item) {\r\n // TODO: URLEncode?\r\n String url = this.prefix;\r\n boolean firstParameter = url.indexOf(\"?\") == -1;\r\n url += firstParameter ? \"?\" : \"&amp;\";\r\n url += this.seriesParameterName + \"=\" + series\r\n + \"&amp;\" + this.itemParameterName + \"=\" + item;\r\n return url;\r\n }\r\n\r\n /**\r\n * Tests this generator for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof StandardXYURLGenerator)) {\r\n return false;\r\n }\r\n StandardXYURLGenerator that = (StandardXYURLGenerator) obj;\r\n if (!ObjectUtilities.equal(that.prefix, this.prefix)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(that.seriesParameterName,\r\n this.seriesParameterName)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(that.itemParameterName,\r\n this.itemParameterName)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n}\r" }, { "identifier": "YIntervalSeries", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/xy/YIntervalSeries.java", "snippet": "public class YIntervalSeries extends ComparableObjectSeries {\r\n\r\n /**\r\n * Creates a new empty series. By default, items added to the series will\r\n * be sorted into ascending order by x-value, and duplicate x-values will\r\n * be allowed (these defaults can be modified with another constructor.\r\n *\r\n * @param key the series key (<code>null</code> not permitted).\r\n */\r\n public YIntervalSeries(Comparable key) {\r\n this(key, true, true);\r\n }\r\n\r\n /**\r\n * Constructs a new xy-series that contains no data. You can specify\r\n * whether or not duplicate x-values are allowed for the series.\r\n *\r\n * @param key the series key (<code>null</code> not permitted).\r\n * @param autoSort a flag that controls whether or not the items in the\r\n * series are sorted.\r\n * @param allowDuplicateXValues a flag that controls whether duplicate\r\n * x-values are allowed.\r\n */\r\n public YIntervalSeries(Comparable key, boolean autoSort,\r\n boolean allowDuplicateXValues) {\r\n super(key, autoSort, allowDuplicateXValues);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and sends a {@link SeriesChangeEvent} to \r\n * all registered listeners.\r\n *\r\n * @param x the x-value.\r\n * @param y the y-value.\r\n * @param yLow the lower bound of the y-interval.\r\n * @param yHigh the upper bound of the y-interval.\r\n */\r\n public void add(double x, double y, double yLow, double yHigh) {\r\n add(new YIntervalDataItem(x, y, yLow, yHigh), true);\r\n }\r\n \r\n /**\r\n * Adds a data item to the series and, if requested, sends a \r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n * \r\n * @param item the data item (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n * \r\n * @since 1.0.18\r\n */\r\n public void add(YIntervalDataItem item, boolean notify) {\r\n super.add(item, notify);\r\n }\r\n\r\n /**\r\n * Returns the x-value for the specified item.\r\n *\r\n * @param index the item index.\r\n *\r\n * @return The x-value (never <code>null</code>).\r\n */\r\n public Number getX(int index) {\r\n YIntervalDataItem item = (YIntervalDataItem) getDataItem(index);\r\n return item.getX();\r\n }\r\n\r\n /**\r\n * Returns the y-value for the specified item.\r\n *\r\n * @param index the item index.\r\n *\r\n * @return The y-value.\r\n */\r\n public double getYValue(int index) {\r\n YIntervalDataItem item = (YIntervalDataItem) getDataItem(index);\r\n return item.getYValue();\r\n }\r\n\r\n /**\r\n * Returns the lower bound of the Y-interval for the specified item in the\r\n * series.\r\n *\r\n * @param index the item index.\r\n *\r\n * @return The lower bound of the Y-interval.\r\n *\r\n * @since 1.0.5\r\n */\r\n public double getYLowValue(int index) {\r\n YIntervalDataItem item = (YIntervalDataItem) getDataItem(index);\r\n return item.getYLowValue();\r\n }\r\n\r\n /**\r\n * Returns the upper bound of the y-interval for the specified item in the\r\n * series.\r\n *\r\n * @param index the item index.\r\n *\r\n * @return The upper bound of the y-interval.\r\n *\r\n * @since 1.0.5\r\n */\r\n public double getYHighValue(int index) {\r\n YIntervalDataItem item = (YIntervalDataItem) getDataItem(index);\r\n return item.getYHighValue();\r\n }\r\n\r\n /**\r\n * Returns the data item at the specified index.\r\n *\r\n * @param index the item index.\r\n *\r\n * @return The data item.\r\n */\r\n @Override\r\n public ComparableObjectItem getDataItem(int index) {\r\n return super.getDataItem(index);\r\n }\r\n\r\n}\r" }, { "identifier": "YIntervalSeriesCollection", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/xy/YIntervalSeriesCollection.java", "snippet": "public class YIntervalSeriesCollection extends AbstractIntervalXYDataset\r\n implements IntervalXYDataset, PublicCloneable, Serializable {\r\n\r\n /** Storage for the data series. */\r\n private List data;\r\n\r\n /**\r\n * Creates a new instance of <code>YIntervalSeriesCollection</code>.\r\n */\r\n public YIntervalSeriesCollection() {\r\n this.data = new java.util.ArrayList();\r\n }\r\n\r\n /**\r\n * Adds a series to the collection and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n */\r\n public void addSeries(YIntervalSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n this.data.add(series);\r\n series.addChangeListener(this);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns the number of series in the collection.\r\n *\r\n * @return The series count.\r\n */\r\n @Override\r\n public int getSeriesCount() {\r\n return this.data.size();\r\n }\r\n\r\n /**\r\n * Returns a series from the collection.\r\n *\r\n * @param series the series index (zero-based).\r\n *\r\n * @return The series.\r\n *\r\n * @throws IllegalArgumentException if <code>series</code> is not in the\r\n * range <code>0</code> to <code>getSeriesCount() - 1</code>.\r\n */\r\n public YIntervalSeries getSeries(int series) {\r\n if ((series < 0) || (series >= getSeriesCount())) {\r\n throw new IllegalArgumentException(\"Series index out of bounds\");\r\n }\r\n return (YIntervalSeries) this.data.get(series);\r\n }\r\n\r\n /**\r\n * Returns the key for a series.\r\n *\r\n * @param series the series index (in the range <code>0</code> to\r\n * <code>getSeriesCount() - 1</code>).\r\n *\r\n * @return The key for a series.\r\n *\r\n * @throws IllegalArgumentException if <code>series</code> is not in the\r\n * specified range.\r\n */\r\n @Override\r\n public Comparable getSeriesKey(int series) {\r\n // defer argument checking\r\n return getSeries(series).getKey();\r\n }\r\n\r\n /**\r\n * Returns the number of items in the specified series.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The item count.\r\n *\r\n * @throws IllegalArgumentException if <code>series</code> is not in the\r\n * range <code>0</code> to <code>getSeriesCount() - 1</code>.\r\n */\r\n @Override\r\n public int getItemCount(int series) {\r\n // defer argument checking\r\n return getSeries(series).getItemCount();\r\n }\r\n\r\n /**\r\n * Returns the x-value for an item within a series.\r\n *\r\n * @param series the series index.\r\n * @param item the item index.\r\n *\r\n * @return The x-value.\r\n */\r\n @Override\r\n public Number getX(int series, int item) {\r\n YIntervalSeries s = (YIntervalSeries) this.data.get(series);\r\n return s.getX(item);\r\n }\r\n\r\n /**\r\n * Returns the y-value (as a double primitive) for an item within a\r\n * series.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param item the item index (zero-based).\r\n *\r\n * @return The value.\r\n */\r\n @Override\r\n public double getYValue(int series, int item) {\r\n YIntervalSeries s = (YIntervalSeries) this.data.get(series);\r\n return s.getYValue(item);\r\n }\r\n\r\n /**\r\n * Returns the start y-value (as a double primitive) for an item within a\r\n * series.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param item the item index (zero-based).\r\n *\r\n * @return The value.\r\n */\r\n @Override\r\n public double getStartYValue(int series, int item) {\r\n YIntervalSeries s = (YIntervalSeries) this.data.get(series);\r\n return s.getYLowValue(item);\r\n }\r\n\r\n /**\r\n * Returns the end y-value (as a double primitive) for an item within a\r\n * series.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The value.\r\n */\r\n @Override\r\n public double getEndYValue(int series, int item) {\r\n YIntervalSeries s = (YIntervalSeries) this.data.get(series);\r\n return s.getYHighValue(item);\r\n }\r\n\r\n /**\r\n * Returns the y-value for an item within a series.\r\n *\r\n * @param series the series index.\r\n * @param item the item index.\r\n *\r\n * @return The y-value.\r\n */\r\n @Override\r\n public Number getY(int series, int item) {\r\n YIntervalSeries s = (YIntervalSeries) this.data.get(series);\r\n return new Double(s.getYValue(item));\r\n }\r\n\r\n /**\r\n * Returns the start x-value for an item within a series. This method\r\n * maps directly to {@link #getX(int, int)}.\r\n *\r\n * @param series the series index.\r\n * @param item the item index.\r\n *\r\n * @return The x-value.\r\n */\r\n @Override\r\n public Number getStartX(int series, int item) {\r\n return getX(series, item);\r\n }\r\n\r\n /**\r\n * Returns the end x-value for an item within a series. This method\r\n * maps directly to {@link #getX(int, int)}.\r\n *\r\n * @param series the series index.\r\n * @param item the item index.\r\n *\r\n * @return The x-value.\r\n */\r\n @Override\r\n public Number getEndX(int series, int item) {\r\n return getX(series, item);\r\n }\r\n\r\n /**\r\n * Returns the start y-value for an item within a series.\r\n *\r\n * @param series the series index.\r\n * @param item the item index.\r\n *\r\n * @return The start y-value.\r\n */\r\n @Override\r\n public Number getStartY(int series, int item) {\r\n YIntervalSeries s = (YIntervalSeries) this.data.get(series);\r\n return new Double(s.getYLowValue(item));\r\n }\r\n\r\n /**\r\n * Returns the end y-value for an item within a series.\r\n *\r\n * @param series the series index.\r\n * @param item the item index.\r\n *\r\n * @return The end y-value.\r\n */\r\n @Override\r\n public Number getEndY(int series, int item) {\r\n YIntervalSeries s = (YIntervalSeries) this.data.get(series);\r\n return new Double(s.getYHighValue(item));\r\n }\r\n\r\n /**\r\n * Removes a series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n *\r\n * @since 1.0.10\r\n */\r\n public void removeSeries(int series) {\r\n if ((series < 0) || (series >= getSeriesCount())) {\r\n throw new IllegalArgumentException(\"Series index out of bounds.\");\r\n }\r\n YIntervalSeries ts = (YIntervalSeries) this.data.get(series);\r\n ts.removeChangeListener(this);\r\n this.data.remove(series);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes a series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.10\r\n */\r\n public void removeSeries(YIntervalSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n if (this.data.contains(series)) {\r\n series.removeChangeListener(this);\r\n this.data.remove(series);\r\n fireDatasetChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Removes all the series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @since 1.0.10\r\n */\r\n public void removeAllSeries() {\r\n // Unregister the collection as a change listener to each series in\r\n // the collection.\r\n for (int i = 0; i < this.data.size(); i++) {\r\n YIntervalSeries series = (YIntervalSeries) this.data.get(i);\r\n series.removeChangeListener(this);\r\n }\r\n this.data.clear();\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Tests this instance for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof YIntervalSeriesCollection)) {\r\n return false;\r\n }\r\n YIntervalSeriesCollection that = (YIntervalSeriesCollection) obj;\r\n return ObjectUtilities.equal(this.data, that.data);\r\n }\r\n\r\n /**\r\n * Returns a clone of this instance.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if there is a problem.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n YIntervalSeriesCollection clone\r\n = (YIntervalSeriesCollection) super.clone();\r\n clone.data = (List) ObjectUtilities.deepClone(this.data);\r\n return clone;\r\n }\r\n\r\n}\r" } ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import org.jfree.chart.JFreeChart; import org.jfree.chart.LegendItem; import org.jfree.chart.TestUtilities; import org.jfree.chart.annotations.XYTextAnnotation; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.labels.IntervalXYItemLabelGenerator; import org.jfree.chart.labels.StandardXYItemLabelGenerator; import org.jfree.chart.labels.StandardXYSeriesLabelGenerator; import org.jfree.chart.labels.StandardXYToolTipGenerator; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.urls.StandardXYURLGenerator; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection; import org.jfree.ui.Layer; import org.jfree.util.PublicCloneable; import org.junit.Test;
92,025
"{0} {1}")); assertTrue(r1.equals(r2)); r1.setLegendItemToolTipGenerator(new StandardXYSeriesLabelGenerator()); assertFalse(r1.equals(r2)); r2.setLegendItemToolTipGenerator(new StandardXYSeriesLabelGenerator()); assertTrue(r1.equals(r2)); r1.setLegendItemURLGenerator(new StandardXYSeriesLabelGenerator()); assertFalse(r1.equals(r2)); r2.setLegendItemURLGenerator(new StandardXYSeriesLabelGenerator()); assertTrue(r1.equals(r2)); r1.setAdditionalItemLabelGenerator(new IntervalXYItemLabelGenerator()); assertFalse(r1.equals(r2)); r2.setAdditionalItemLabelGenerator(new IntervalXYItemLabelGenerator()); assertTrue(r1.equals(r2)); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashcode() { YIntervalRenderer r1 = new YIntervalRenderer(); YIntervalRenderer r2 = new YIntervalRenderer(); assertTrue(r1.equals(r2)); int h1 = r1.hashCode(); int h2 = r2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { YIntervalRenderer r1 = new YIntervalRenderer(); YIntervalRenderer r2 = (YIntervalRenderer) r1.clone(); assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); // check independence r1.setSeriesItemLabelGenerator(0, new StandardXYItemLabelGenerator()); assertFalse(r1.equals(r2)); r2.setSeriesItemLabelGenerator(0, new StandardXYItemLabelGenerator()); assertTrue(r1.equals(r2)); r1.setSeriesToolTipGenerator(0, new StandardXYToolTipGenerator()); assertFalse(r1.equals(r2)); r2.setSeriesToolTipGenerator(0, new StandardXYToolTipGenerator()); assertTrue(r1.equals(r2)); r1.addAnnotation(new XYTextAnnotation("ABC", 1.0, 2.0), Layer.FOREGROUND); assertFalse(r1.equals(r2)); r2.addAnnotation(new XYTextAnnotation("ABC", 1.0, 2.0), Layer.FOREGROUND); assertTrue(r1.equals(r2)); r1.addAnnotation(new XYTextAnnotation("ABC", 1.0, 2.0), Layer.BACKGROUND); assertFalse(r1.equals(r2)); r2.addAnnotation(new XYTextAnnotation("ABC", 1.0, 2.0), Layer.BACKGROUND); assertTrue(r1.equals(r2)); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { YIntervalRenderer r1 = new YIntervalRenderer(); assertTrue(r1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { YIntervalRenderer r1 = new YIntervalRenderer(); YIntervalRenderer r2 = (YIntervalRenderer) TestUtilities.serialised(r1); assertEquals(r1, r2); } /** * A check for the datasetIndex and seriesIndex fields in the LegendItem * returned by the getLegendItem() method. */ @Test public void testGetLegendItemSeriesIndex() { YIntervalSeriesCollection d1 = new YIntervalSeriesCollection(); YIntervalSeries s1 = new YIntervalSeries("S1"); s1.add(1.0, 1.1, 1.2, 1.3); YIntervalSeries s2 = new YIntervalSeries("S2"); s2.add(1.0, 1.1, 1.2, 1.3); d1.addSeries(s1); d1.addSeries(s2); YIntervalSeriesCollection d2 = new YIntervalSeriesCollection(); YIntervalSeries s3 = new YIntervalSeries("S3"); s3.add(1.0, 1.1, 1.2, 1.3); YIntervalSeries s4 = new YIntervalSeries("S4"); s4.add(1.0, 1.1, 1.2, 1.3); YIntervalSeries s5 = new YIntervalSeries("S5"); s5.add(1.0, 1.1, 1.2, 1.3); d2.addSeries(s3); d2.addSeries(s4); d2.addSeries(s5); YIntervalRenderer r = new YIntervalRenderer(); XYPlot plot = new XYPlot(d1, new NumberAxis("x"), new NumberAxis("y"), r); plot.setDataset(1, d2); /*JFreeChart chart =*/ new JFreeChart(plot);
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------------- * YIntervalRendererTest.java * -------------------------- * (C) Copyright 2003-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 25-Mar-2003 : Version 1 (DG); * 20-Feb-2007 : Extended the testEquals() checks (DG); * 17-May-2007 : Added testGetLegendItemSeriesIndex() (DG); * 22-Apr-2008 : Added testPublicCloneable() (DG); * 26-May-2008 : Extended testEquals() (DG); * */ package org.jfree.chart.renderer.xy; /** * Tests for the {@link YIntervalRenderer} class. */ public class YIntervalRendererTest { /** * Check that the equals() method distinguishes all fields. */ @Test public void testEquals() { YIntervalRenderer r1 = new YIntervalRenderer(); YIntervalRenderer r2 = new YIntervalRenderer(); assertEquals(r1, r2); // the following fields are inherited from the AbstractXYItemRenderer r1.setItemLabelGenerator(new StandardXYItemLabelGenerator()); assertFalse(r1.equals(r2)); r2.setItemLabelGenerator(new StandardXYItemLabelGenerator()); assertTrue(r1.equals(r2)); r1.setSeriesItemLabelGenerator(0, new StandardXYItemLabelGenerator()); assertFalse(r1.equals(r2)); r2.setSeriesItemLabelGenerator(0, new StandardXYItemLabelGenerator()); assertTrue(r1.equals(r2)); r1.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator()); assertFalse(r1.equals(r2)); r2.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator()); assertTrue(r1.equals(r2)); r1.setToolTipGenerator(new StandardXYToolTipGenerator()); assertFalse(r1.equals(r2)); r2.setToolTipGenerator(new StandardXYToolTipGenerator()); assertTrue(r1.equals(r2)); r1.setSeriesToolTipGenerator(0, new StandardXYToolTipGenerator()); assertFalse(r1.equals(r2)); r2.setSeriesToolTipGenerator(0, new StandardXYToolTipGenerator()); assertTrue(r1.equals(r2)); r1.setBaseToolTipGenerator(new StandardXYToolTipGenerator()); assertFalse(r1.equals(r2)); r2.setBaseToolTipGenerator(new StandardXYToolTipGenerator()); assertTrue(r1.equals(r2)); r1.setURLGenerator(new StandardXYURLGenerator()); assertFalse(r1.equals(r2)); r2.setURLGenerator(new StandardXYURLGenerator()); assertTrue(r1.equals(r2)); r1.addAnnotation(new XYTextAnnotation("X", 1.0, 2.0), Layer.FOREGROUND); assertFalse(r1.equals(r2)); r2.addAnnotation(new XYTextAnnotation("X", 1.0, 2.0), Layer.FOREGROUND); assertTrue(r1.equals(r2)); r1.addAnnotation(new XYTextAnnotation("X", 1.0, 2.0), Layer.BACKGROUND); assertFalse(r1.equals(r2)); r2.addAnnotation(new XYTextAnnotation("X", 1.0, 2.0), Layer.BACKGROUND); assertTrue(r1.equals(r2)); r1.setDefaultEntityRadius(99); assertFalse(r1.equals(r2)); r2.setDefaultEntityRadius(99); assertTrue(r1.equals(r2)); r1.setLegendItemLabelGenerator(new StandardXYSeriesLabelGenerator( "{0} {1}")); assertFalse(r1.equals(r2)); r2.setLegendItemLabelGenerator(new StandardXYSeriesLabelGenerator( "{0} {1}")); assertTrue(r1.equals(r2)); r1.setLegendItemToolTipGenerator(new StandardXYSeriesLabelGenerator()); assertFalse(r1.equals(r2)); r2.setLegendItemToolTipGenerator(new StandardXYSeriesLabelGenerator()); assertTrue(r1.equals(r2)); r1.setLegendItemURLGenerator(new StandardXYSeriesLabelGenerator()); assertFalse(r1.equals(r2)); r2.setLegendItemURLGenerator(new StandardXYSeriesLabelGenerator()); assertTrue(r1.equals(r2)); r1.setAdditionalItemLabelGenerator(new IntervalXYItemLabelGenerator()); assertFalse(r1.equals(r2)); r2.setAdditionalItemLabelGenerator(new IntervalXYItemLabelGenerator()); assertTrue(r1.equals(r2)); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashcode() { YIntervalRenderer r1 = new YIntervalRenderer(); YIntervalRenderer r2 = new YIntervalRenderer(); assertTrue(r1.equals(r2)); int h1 = r1.hashCode(); int h2 = r2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { YIntervalRenderer r1 = new YIntervalRenderer(); YIntervalRenderer r2 = (YIntervalRenderer) r1.clone(); assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); // check independence r1.setSeriesItemLabelGenerator(0, new StandardXYItemLabelGenerator()); assertFalse(r1.equals(r2)); r2.setSeriesItemLabelGenerator(0, new StandardXYItemLabelGenerator()); assertTrue(r1.equals(r2)); r1.setSeriesToolTipGenerator(0, new StandardXYToolTipGenerator()); assertFalse(r1.equals(r2)); r2.setSeriesToolTipGenerator(0, new StandardXYToolTipGenerator()); assertTrue(r1.equals(r2)); r1.addAnnotation(new XYTextAnnotation("ABC", 1.0, 2.0), Layer.FOREGROUND); assertFalse(r1.equals(r2)); r2.addAnnotation(new XYTextAnnotation("ABC", 1.0, 2.0), Layer.FOREGROUND); assertTrue(r1.equals(r2)); r1.addAnnotation(new XYTextAnnotation("ABC", 1.0, 2.0), Layer.BACKGROUND); assertFalse(r1.equals(r2)); r2.addAnnotation(new XYTextAnnotation("ABC", 1.0, 2.0), Layer.BACKGROUND); assertTrue(r1.equals(r2)); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { YIntervalRenderer r1 = new YIntervalRenderer(); assertTrue(r1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { YIntervalRenderer r1 = new YIntervalRenderer(); YIntervalRenderer r2 = (YIntervalRenderer) TestUtilities.serialised(r1); assertEquals(r1, r2); } /** * A check for the datasetIndex and seriesIndex fields in the LegendItem * returned by the getLegendItem() method. */ @Test public void testGetLegendItemSeriesIndex() { YIntervalSeriesCollection d1 = new YIntervalSeriesCollection(); YIntervalSeries s1 = new YIntervalSeries("S1"); s1.add(1.0, 1.1, 1.2, 1.3); YIntervalSeries s2 = new YIntervalSeries("S2"); s2.add(1.0, 1.1, 1.2, 1.3); d1.addSeries(s1); d1.addSeries(s2); YIntervalSeriesCollection d2 = new YIntervalSeriesCollection(); YIntervalSeries s3 = new YIntervalSeries("S3"); s3.add(1.0, 1.1, 1.2, 1.3); YIntervalSeries s4 = new YIntervalSeries("S4"); s4.add(1.0, 1.1, 1.2, 1.3); YIntervalSeries s5 = new YIntervalSeries("S5"); s5.add(1.0, 1.1, 1.2, 1.3); d2.addSeries(s3); d2.addSeries(s4); d2.addSeries(s5); YIntervalRenderer r = new YIntervalRenderer(); XYPlot plot = new XYPlot(d1, new NumberAxis("x"), new NumberAxis("y"), r); plot.setDataset(1, d2); /*JFreeChart chart =*/ new JFreeChart(plot);
LegendItem li = r.getLegendItem(1, 2);
1
2023-12-24 12:36:47+00:00
128k
Hoto-Mocha/Re-ARranged-Pixel-Dungeon
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/mobs/npcs/MirrorImage.java
[ { "identifier": "Dungeon", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/Dungeon.java", "snippet": "public class Dungeon {\n\n\t//enum of items which have limited spawns, records how many have spawned\n\t//could all be their own separate numbers, but this allows iterating, much nicer for bundling/initializing.\n\tpublic static enum LimitedDrops {\n\t\t//limited world drops\n\t\tSTRENGTH_POTIONS,\n\t\tUPGRADE_SCROLLS,\n\t\tARCANE_STYLI,\n\n\t\t//Health potion sources\n\t\t//enemies\n\t\tSWARM_HP,\n\t\tNECRO_HP,\n\t\tBAT_HP,\n\t\tWARLOCK_HP,\n\t\t//Demon spawners are already limited in their spawnrate, no need to limit their health drops\n\t\t//alchemy\n\t\tCOOKING_HP,\n\t\tBLANDFRUIT_SEED,\n\n\t\t//Other limited enemy drops\n\t\tSLIME_WEP,\n\t\tSKELE_WEP,\n\t\tTHEIF_MISC,\n\t\tGUARD_ARM,\n\t\tSHAMAN_WAND,\n\t\tDM200_EQUIP,\n\t\tGOLEM_EQUIP,\n\t\tSOLDIER_WEP,\n\t\tMEDIC_HP,\n\n\t\t//containers\n\t\tVELVET_POUCH,\n\t\tSCROLL_HOLDER,\n\t\tPOTION_BANDOLIER,\n\t\tMAGICAL_HOLSTER,\n\n\t\t//lore documents\n\t\tLORE_SEWERS,\n\t\tLORE_PRISON,\n\t\tLORE_CAVES,\n\t\tLORE_CITY,\n\t\tLORE_HALLS,\n\t\tLORE_LABS;\n\n\t\tpublic int count = 0;\n\n\t\t//for items which can only be dropped once, should directly access count otherwise.\n\t\tpublic boolean dropped(){\n\t\t\treturn count != 0;\n\t\t}\n\t\tpublic void drop(){\n\t\t\tcount = 1;\n\t\t}\n\n\t\tpublic static void reset(){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tlim.count = 0;\n\t\t\t}\n\t\t}\n\n\t\tpublic static void store( Bundle bundle ){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tbundle.put(lim.name(), lim.count);\n\t\t\t}\n\t\t}\n\n\t\tpublic static void restore( Bundle bundle ){\n\t\t\tfor (LimitedDrops lim : values()){\n\t\t\t\tif (bundle.contains(lim.name())){\n\t\t\t\t\tlim.count = bundle.getInt(lim.name());\n\t\t\t\t} else {\n\t\t\t\t\tlim.count = 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\n\t\t\t//pre-v2.2.0 saves\n\t\t\tif (Dungeon.version < 750\n\t\t\t\t\t&& Dungeon.isChallenged(Challenges.NO_SCROLLS)\n\t\t\t\t\t&& UPGRADE_SCROLLS.count > 0){\n\t\t\t\t//we now count SOU fully, and just don't drop every 2nd one\n\t\t\t\tUPGRADE_SCROLLS.count += UPGRADE_SCROLLS.count-1;\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic static int challenges;\n\tpublic static int mobsToChampion;\n\n\tpublic static Hero hero;\n\tpublic static Level level;\n\n\tpublic static QuickSlot quickslot = new QuickSlot();\n\t\n\tpublic static int depth;\n\t//determines path the hero is on. Current uses:\n\t// 0 is the default path\n\t// 1 is for quest sub-floors\n\tpublic static int branch;\n\n\t//keeps track of what levels the game should try to load instead of creating fresh\n\tpublic static ArrayList<Integer> generatedLevels = new ArrayList<>();\n\n\tpublic static int gold;\n\tpublic static int energy;\n\tpublic static int bullet;\n\n\tpublic static HashSet<Integer> chapters;\n\n\tpublic static SparseArray<ArrayList<Item>> droppedItems;\n\n\t//first variable is only assigned when game is started, second is updated every time game is saved\n\tpublic static int initialVersion;\n\tpublic static int version;\n\n\tpublic static boolean daily;\n\tpublic static boolean dailyReplay;\n\tpublic static String customSeedText = \"\";\n\tpublic static long seed;\n\t\n\tpublic static void init() {\n\n\t\tinitialVersion = version = Game.versionCode;\n\t\tchallenges = SPDSettings.challenges();\n\t\tmobsToChampion = -1;\n\n\t\tif (daily) {\n\t\t\t//Ensures that daily seeds are not in the range of user-enterable seeds\n\t\t\tseed = SPDSettings.lastDaily() + DungeonSeed.TOTAL_SEEDS;\n\t\t\tDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ROOT);\n\t\t\tformat.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\t\t\tcustomSeedText = format.format(new Date(SPDSettings.lastDaily()));\n\t\t} else if (!SPDSettings.customSeed().isEmpty()){\n\t\t\tcustomSeedText = SPDSettings.customSeed();\n\t\t\tseed = DungeonSeed.convertFromText(customSeedText);\n\t\t} else {\n\t\t\tcustomSeedText = \"\";\n\t\t\tseed = DungeonSeed.randomSeed();\n\t\t}\n\n\t\tActor.clear();\n\t\tActor.resetNextID();\n\n\t\t//offset seed slightly to avoid output patterns\n\t\tRandom.pushGenerator( seed+1 );\n\n\t\t\tScroll.initLabels();\n\t\t\tPotion.initColors();\n\t\t\tRing.initGems();\n\n\t\t\tSpecialRoom.initForRun();\n\t\t\tSecretRoom.initForRun();\n\n\t\t\tGenerator.fullReset();\n\n\t\tRandom.resetGenerators();\n\t\t\n\t\tStatistics.reset();\n\t\tNotes.reset();\n\n\t\tquickslot.reset();\n\t\tQuickSlotButton.reset();\n\t\tToolbar.swappedQuickslots = false;\n\t\t\n\t\tdepth = 1;\n\t\tbranch = 0;\n\t\tgeneratedLevels.clear();\n\n\t\tgold = 0;\n\t\tenergy = 0;\n\t\tbullet = 0;\n\n\t\tdroppedItems = new SparseArray<>();\n\n\t\tLimitedDrops.reset();\n\t\t\n\t\tchapters = new HashSet<>();\n\t\t\n\t\tGhost.Quest.reset();\n\t\tWandmaker.Quest.reset();\n\t\tBlacksmith.Quest.reset();\n\t\tImp.Quest.reset();\n\n\t\thero = new Hero();\n\t\thero.live();\n\t\t\n\t\tBadges.reset();\n\t\t\n\t\tGamesInProgress.selectedClass.initHero( hero );\n\t}\n\n\tpublic static boolean isChallenged( int mask ) {\n\t\treturn (challenges & mask) != 0;\n\t}\n\n\tpublic static boolean levelHasBeenGenerated(int depth, int branch){\n\t\treturn generatedLevels.contains(depth + 1000*branch);\n\t}\n\t\n\tpublic static Level newLevel() {\n\t\t\n\t\tDungeon.level = null;\n\t\tActor.clear();\n\t\t\n\t\tLevel level;\n\t\tif (branch == 0) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 1:\n\t\t\t\tcase 2:\n\t\t\t\tcase 3:\n\t\t\t\tcase 4:\n\t\t\t\t\tlevel = new SewerLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\tlevel = new SewerBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 6:\n\t\t\t\tcase 7:\n\t\t\t\tcase 8:\n\t\t\t\tcase 9:\n\t\t\t\t\tlevel = new PrisonLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 10:\n\t\t\t\t\tlevel = new PrisonBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 11:\n\t\t\t\tcase 12:\n\t\t\t\tcase 13:\n\t\t\t\tcase 14:\n\t\t\t\t\tlevel = new CavesLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 15:\n\t\t\t\t\tlevel = new CavesBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 16:\n\t\t\t\tcase 17:\n\t\t\t\tcase 18:\n\t\t\t\tcase 19:\n\t\t\t\t\tlevel = new CityLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tlevel = new CityBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 21:\n\t\t\t\tcase 22:\n\t\t\t\tcase 23:\n\t\t\t\tcase 24:\n\t\t\t\t\tlevel = new HallsLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 25:\n\t\t\t\t\tlevel = new HallsBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 26:\n\t\t\t\tcase 27:\n\t\t\t\tcase 28:\n\t\t\t\tcase 29:\n\t\t\t\t\tlevel = new LabsLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 30:\n\t\t\t\t\tlevel = new LabsBossLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 31:\n\t\t\t\t\tlevel = new NewLastLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else if (branch == 1) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 11:\n\t\t\t\tcase 12:\n\t\t\t\tcase 13:\n\t\t\t\tcase 14:\n\t\t\t\t\tlevel = new MiningLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else if (branch == 2) {\n\t\t\tswitch (depth) {\n\t\t\t\tcase 16:\n\t\t\t\tcase 17:\n\t\t\t\tcase 18:\n\t\t\t\tcase 19:\n\t\t\t\t\tlevel = new TempleLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tlevel = new TempleLastLevel();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlevel = new DeadEndLevel();\n\t\t\t}\n\t\t} else {\n\t\t\tlevel = new DeadEndLevel();\n\t\t}\n\n\t\t//dead end levels get cleared, don't count as generated\n\t\tif (!(level instanceof DeadEndLevel)){\n\t\t\t//this assumes that we will never have a depth value outside the range 0 to 999\n\t\t\t// or -500 to 499, etc.\n\t\t\tif (!generatedLevels.contains(depth + 1000*branch)) {\n\t\t\t\tgeneratedLevels.add(depth + 1000 * branch);\n\t\t\t}\n\n\t\t\tif (depth > Statistics.deepestFloor && branch == 0) {\n\t\t\t\tStatistics.deepestFloor = depth;\n\n\t\t\t\tif (Statistics.qualifiedForNoKilling) {\n\t\t\t\t\tStatistics.completedWithNoKilling = true;\n\t\t\t\t} else {\n\t\t\t\t\tStatistics.completedWithNoKilling = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tlevel.create();\n\t\t\n\t\tif (branch == 0) Statistics.qualifiedForNoKilling = !bossLevel();\n\t\tStatistics.qualifiedForBossChallengeBadge = false;\n\t\t\n\t\treturn level;\n\t}\n\t\n\tpublic static void resetLevel() {\n\t\t\n\t\tActor.clear();\n\t\t\n\t\tlevel.reset();\n\t\tswitchLevel( level, level.entrance() );\n\t}\n\n\tpublic static long seedCurDepth(){\n\t\treturn seedForDepth(depth, branch);\n\t}\n\n\tpublic static long seedForDepth(int depth, int branch){\n\t\tint lookAhead = depth;\n\t\tlookAhead += 30*branch; //Assumes depth is always 1-30, and branch is always 0 or higher\n\n\t\tRandom.pushGenerator( seed );\n\n\t\t\tfor (int i = 0; i < lookAhead; i ++) {\n\t\t\t\tRandom.Long(); //we don't care about these values, just need to go through them\n\t\t\t}\n\t\t\tlong result = Random.Long();\n\n\t\tRandom.popGenerator();\n\t\treturn result;\n\t}\n\t\n\tpublic static boolean shopOnLevel() {\n\t\treturn (depth == 6 || depth == 11 || depth == 16 || depth == 26) && branch == 0;\n\t}\n\t\n\tpublic static boolean bossLevel() {\n\t\treturn bossLevel( depth );\n\t}\n\t\n\tpublic static boolean bossLevel( int depth ) {\n\t\treturn depth == 5 || depth == 10 || depth == 15 || depth == 20 || depth == 25|| depth == 30;\n\t}\n\n\t//value used for scaling of damage values and other effects.\n\t//is usually the dungeon depth, but can be set to 26 when ascending\n\tpublic static int scalingDepth(){\n\t\tif (Dungeon.hero != null && Dungeon.hero.buff(AscensionChallenge.class) != null){\n\t\t\treturn 31;\n\t\t} else {\n\t\t\treturn depth;\n\t\t}\n\t}\n\n\tpublic static boolean interfloorTeleportAllowed(){\n\t\tif (Dungeon.level.locked\n\t\t\t\t|| (Dungeon.hero != null && Dungeon.hero.belongings.getItem(Amulet.class) != null)\n\t\t\t\t|| (Dungeon.hero != null && Dungeon.hero.buff(OldAmulet.TempleCurse.class) != null)){\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\n\tpublic static void switchLevel( final Level level, int pos ) {\n\n\t\t//Position of -2 specifically means trying to place the hero the exit\n\t\tif (pos == -2){\n\t\t\tLevelTransition t = level.getTransition(LevelTransition.Type.REGULAR_EXIT);\n\t\t\tif (t != null) pos = t.cell();\n\t\t}\n\n\t\t//Place hero at the entrance if they are out of the map (often used for pox = -1)\n\t\t// or if they are in solid terrain (except in the mining level, where that happens normally)\n\t\tif (pos < 0 || pos >= level.length()\n\t\t\t\t|| (!(level instanceof MiningLevel) && !level.passable[pos] && !level.avoid[pos])){\n\t\t\tpos = level.getTransition(null).cell();\n\t\t}\n\t\t\n\t\tPathFinder.setMapSize(level.width(), level.height());\n\t\t\n\t\tDungeon.level = level;\n\t\thero.pos = pos;\n\n\t\tif (hero.buff(AscensionChallenge.class) != null){\n\t\t\thero.buff(AscensionChallenge.class).onLevelSwitch();\n\t\t}\n\n\t\tif (hero.buff(OldAmulet.TempleCurse.class) != null){\n\t\t\thero.buff(OldAmulet.TempleCurse.class).onLevelSwitch();\n\t\t}\n\n\t\tMob.restoreAllies( level, pos );\n\n\t\tActor.init();\n\n\t\tlevel.addRespawner();\n\t\t\n\t\tfor(Mob m : level.mobs){\n\t\t\tif (m.pos == hero.pos && !Char.hasProp(m, Char.Property.IMMOVABLE)){\n\t\t\t\t//displace mob\n\t\t\t\tfor(int i : PathFinder.NEIGHBOURS8){\n\t\t\t\t\tif (Actor.findChar(m.pos+i) == null && level.passable[m.pos + i]){\n\t\t\t\t\t\tm.pos += i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tLight light = hero.buff( Light.class );\n\t\thero.viewDistance = light == null ? level.viewDistance : Math.max( Light.DISTANCE, level.viewDistance );\n\t\t\n\t\thero.curAction = hero.lastAction = null;\n\n\t\tobserve();\n\t\ttry {\n\t\t\tsaveAll();\n\t\t} catch (IOException e) {\n\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t\t/*This only catches IO errors. Yes, this means things can go wrong, and they can go wrong catastrophically.\n\t\t\tBut when they do the user will get a nice 'report this issue' dialogue, and I can fix the bug.*/\n\t\t}\n\t}\n\n\tpublic static void dropToChasm( Item item ) {\n\t\tint depth = Dungeon.depth + 1;\n\t\tArrayList<Item> dropped = Dungeon.droppedItems.get( depth );\n\t\tif (dropped == null) {\n\t\t\tDungeon.droppedItems.put( depth, dropped = new ArrayList<>() );\n\t\t}\n\t\tdropped.add( item );\n\t}\n\n\tpublic static boolean posNeeded() {\n\t\t//2 POS each floor set\n\t\tint posLeftThisSet = 2 - (LimitedDrops.STRENGTH_POTIONS.count - (depth / 5) * 2);\n\t\tif (posLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\n\t\t//pos drops every two floors, (numbers 1-2, and 3-4) with a 50% chance for the earlier one each time.\n\t\tint targetPOSLeft = 2 - floorThisSet/2;\n\t\tif (floorThisSet % 2 == 1 && Random.Int(2) == 0) targetPOSLeft --;\n\n\t\tif (targetPOSLeft < posLeftThisSet) return true;\n\t\telse return false;\n\n\t}\n\t\n\tpublic static boolean souNeeded() {\n\t\tint souLeftThisSet;\n\t\t//3 SOU each floor set\n\t\tsouLeftThisSet = 3 - (LimitedDrops.UPGRADE_SCROLLS.count - (depth / 5) * 3);\n\t\tif (souLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\t\t//chance is floors left / scrolls left\n\t\treturn Random.Int(5 - floorThisSet) < souLeftThisSet;\n\t}\n\t\n\tpublic static boolean asNeeded() {\n\t\t//1 AS each floor set\n\t\tint asLeftThisSet = 1 - (LimitedDrops.ARCANE_STYLI.count - (depth / 5));\n\t\tif (asLeftThisSet <= 0) return false;\n\n\t\tint floorThisSet = (depth % 5);\n\t\t//chance is floors left / scrolls left\n\t\treturn Random.Int(5 - floorThisSet) < asLeftThisSet;\n\t}\n\n\tprivate static final String INIT_VER\t= \"init_ver\";\n\tprivate static final String VERSION\t\t= \"version\";\n\tprivate static final String SEED\t\t= \"seed\";\n\tprivate static final String CUSTOM_SEED\t= \"custom_seed\";\n\tprivate static final String DAILY\t = \"daily\";\n\tprivate static final String DAILY_REPLAY= \"daily_replay\";\n\tprivate static final String CHALLENGES\t= \"challenges\";\n\tprivate static final String MOBS_TO_CHAMPION\t= \"mobs_to_champion\";\n\tprivate static final String HERO\t\t= \"hero\";\n\tprivate static final String DEPTH\t\t= \"depth\";\n\tprivate static final String BRANCH\t\t= \"branch\";\n\tprivate static final String GENERATED_LEVELS = \"generated_levels\";\n\tprivate static final String GOLD\t\t= \"gold\";\n\tprivate static final String ENERGY\t\t= \"energy\";\n\tprivate static final String BULLET\t\t= \"bullet\";\n\tprivate static final String DROPPED = \"dropped%d\";\n\tprivate static final String PORTED = \"ported%d\";\n\tprivate static final String LEVEL\t\t= \"level\";\n\tprivate static final String LIMDROPS = \"limited_drops\";\n\tprivate static final String CHAPTERS\t= \"chapters\";\n\tprivate static final String QUESTS\t\t= \"quests\";\n\tprivate static final String BADGES\t\t= \"badges\";\n\n\tpublic static void saveGame( int save ) {\n\t\ttry {\n\t\t\tBundle bundle = new Bundle();\n\n\t\t\tbundle.put( INIT_VER, initialVersion );\n\t\t\tbundle.put( VERSION, version = Game.versionCode );\n\t\t\tbundle.put( SEED, seed );\n\t\t\tbundle.put( CUSTOM_SEED, customSeedText );\n\t\t\tbundle.put( DAILY, daily );\n\t\t\tbundle.put( DAILY_REPLAY, dailyReplay );\n\t\t\tbundle.put( CHALLENGES, challenges );\n\t\t\tbundle.put( MOBS_TO_CHAMPION, mobsToChampion );\n\t\t\tbundle.put( HERO, hero );\n\t\t\tbundle.put( DEPTH, depth );\n\t\t\tbundle.put( BRANCH, branch );\n\n\t\t\tbundle.put( GOLD, gold );\n\t\t\tbundle.put( ENERGY, energy );\n\t\t\tbundle.put( BULLET, bullet );\n\n\t\t\tfor (int d : droppedItems.keyArray()) {\n\t\t\t\tbundle.put(Messages.format(DROPPED, d), droppedItems.get(d));\n\t\t\t}\n\n\t\t\tquickslot.storePlaceholders( bundle );\n\n\t\t\tBundle limDrops = new Bundle();\n\t\t\tLimitedDrops.store( limDrops );\n\t\t\tbundle.put ( LIMDROPS, limDrops );\n\t\t\t\n\t\t\tint count = 0;\n\t\t\tint ids[] = new int[chapters.size()];\n\t\t\tfor (Integer id : chapters) {\n\t\t\t\tids[count++] = id;\n\t\t\t}\n\t\t\tbundle.put( CHAPTERS, ids );\n\t\t\t\n\t\t\tBundle quests = new Bundle();\n\t\t\tGhost\t\t.Quest.storeInBundle( quests );\n\t\t\tWandmaker\t.Quest.storeInBundle( quests );\n\t\t\tBlacksmith\t.Quest.storeInBundle( quests );\n\t\t\tImp\t\t\t.Quest.storeInBundle( quests );\n\t\t\tbundle.put( QUESTS, quests );\n\t\t\t\n\t\t\tSpecialRoom.storeRoomsInBundle( bundle );\n\t\t\tSecretRoom.storeRoomsInBundle( bundle );\n\t\t\t\n\t\t\tStatistics.storeInBundle( bundle );\n\t\t\tNotes.storeInBundle( bundle );\n\t\t\tGenerator.storeInBundle( bundle );\n\n\t\t\tint[] bundleArr = new int[generatedLevels.size()];\n\t\t\tfor (int i = 0; i < generatedLevels.size(); i++){\n\t\t\t\tbundleArr[i] = generatedLevels.get(i);\n\t\t\t}\n\t\t\tbundle.put( GENERATED_LEVELS, bundleArr);\n\t\t\t\n\t\t\tScroll.save( bundle );\n\t\t\tPotion.save( bundle );\n\t\t\tRing.save( bundle );\n\n\t\t\tActor.storeNextID( bundle );\n\t\t\t\n\t\t\tBundle badges = new Bundle();\n\t\t\tBadges.saveLocal( badges );\n\t\t\tbundle.put( BADGES, badges );\n\t\t\t\n\t\t\tFileUtils.bundleToFile( GamesInProgress.gameFile(save), bundle);\n\t\t\t\n\t\t} catch (IOException e) {\n\t\t\tGamesInProgress.setUnknown( save );\n\t\t\tShatteredPixelDungeon.reportException(e);\n\t\t}\n\t}\n\t\n\tpublic static void saveLevel( int save ) throws IOException {\n\t\tBundle bundle = new Bundle();\n\t\tbundle.put( LEVEL, level );\n\t\t\n\t\tFileUtils.bundleToFile(GamesInProgress.depthFile( save, depth, branch ), bundle);\n\t}\n\t\n\tpublic static void saveAll() throws IOException {\n\t\tif (hero != null && (hero.isAlive() || WndResurrect.instance != null)) {\n\t\t\t\n\t\t\tActor.fixTime();\n\t\t\tupdateLevelExplored();\n\t\t\tsaveGame( GamesInProgress.curSlot );\n\t\t\tsaveLevel( GamesInProgress.curSlot );\n\n\t\t\tGamesInProgress.set( GamesInProgress.curSlot );\n\n\t\t}\n\t}\n\t\n\tpublic static void loadGame( int save ) throws IOException {\n\t\tloadGame( save, true );\n\t}\n\t\n\tpublic static void loadGame( int save, boolean fullLoad ) throws IOException {\n\t\t\n\t\tBundle bundle = FileUtils.bundleFromFile( GamesInProgress.gameFile( save ) );\n\n\t\t//pre-1.3.0 saves\n\t\tif (bundle.contains(INIT_VER)){\n\t\t\tinitialVersion = bundle.getInt( INIT_VER );\n\t\t} else {\n\t\t\tinitialVersion = bundle.getInt( VERSION );\n\t\t}\n\n\t\tversion = bundle.getInt( VERSION );\n\n\t\tseed = bundle.contains( SEED ) ? bundle.getLong( SEED ) : DungeonSeed.randomSeed();\n\t\tcustomSeedText = bundle.getString( CUSTOM_SEED );\n\t\tdaily = bundle.getBoolean( DAILY );\n\t\tdailyReplay = bundle.getBoolean( DAILY_REPLAY );\n\n\t\tActor.clear();\n\t\tActor.restoreNextID( bundle );\n\n\t\tquickslot.reset();\n\t\tQuickSlotButton.reset();\n\t\tToolbar.swappedQuickslots = false;\n\n\t\tDungeon.challenges = bundle.getInt( CHALLENGES );\n\t\tDungeon.mobsToChampion = bundle.getInt( MOBS_TO_CHAMPION );\n\t\t\n\t\tDungeon.level = null;\n\t\tDungeon.depth = -1;\n\t\t\n\t\tScroll.restore( bundle );\n\t\tPotion.restore( bundle );\n\t\tRing.restore( bundle );\n\n\t\tquickslot.restorePlaceholders( bundle );\n\t\t\n\t\tif (fullLoad) {\n\t\t\t\n\t\t\tLimitedDrops.restore( bundle.getBundle(LIMDROPS) );\n\n\t\t\tchapters = new HashSet<>();\n\t\t\tint ids[] = bundle.getIntArray( CHAPTERS );\n\t\t\tif (ids != null) {\n\t\t\t\tfor (int id : ids) {\n\t\t\t\t\tchapters.add( id );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tBundle quests = bundle.getBundle( QUESTS );\n\t\t\tif (!quests.isNull()) {\n\t\t\t\tGhost.Quest.restoreFromBundle( quests );\n\t\t\t\tWandmaker.Quest.restoreFromBundle( quests );\n\t\t\t\tBlacksmith.Quest.restoreFromBundle( quests );\n\t\t\t\tImp.Quest.restoreFromBundle( quests );\n\t\t\t} else {\n\t\t\t\tGhost.Quest.reset();\n\t\t\t\tWandmaker.Quest.reset();\n\t\t\t\tBlacksmith.Quest.reset();\n\t\t\t\tImp.Quest.reset();\n\t\t\t}\n\t\t\t\n\t\t\tSpecialRoom.restoreRoomsFromBundle(bundle);\n\t\t\tSecretRoom.restoreRoomsFromBundle(bundle);\n\t\t}\n\t\t\n\t\tBundle badges = bundle.getBundle(BADGES);\n\t\tif (!badges.isNull()) {\n\t\t\tBadges.loadLocal( badges );\n\t\t} else {\n\t\t\tBadges.reset();\n\t\t}\n\t\t\n\t\tNotes.restoreFromBundle( bundle );\n\t\t\n\t\thero = null;\n\t\thero = (Hero)bundle.get( HERO );\n\t\t\n\t\tdepth = bundle.getInt( DEPTH );\n\t\tbranch = bundle.getInt( BRANCH );\n\n\t\tgold = bundle.getInt( GOLD );\n\t\tenergy = bundle.getInt( ENERGY );\n\t\tbullet = bundle.getInt( BULLET );\n\n\t\tStatistics.restoreFromBundle( bundle );\n\t\tGenerator.restoreFromBundle( bundle );\n\n\t\tgeneratedLevels.clear();\n\t\tif (bundle.contains(GENERATED_LEVELS)){\n\t\t\tfor (int i : bundle.getIntArray(GENERATED_LEVELS)){\n\t\t\t\tgeneratedLevels.add(i);\n\t\t\t}\n\t\t//pre-v2.1.1 saves\n\t\t} else {\n\t\t\tfor (int i = 1; i <= Statistics.deepestFloor; i++){\n\t\t\t\tgeneratedLevels.add(i);\n\t\t\t}\n\t\t}\n\n\t\tdroppedItems = new SparseArray<>();\n\t\tfor (int i=1; i <= 31; i++) {\n\t\t\t\n\t\t\t//dropped items\n\t\t\tArrayList<Item> items = new ArrayList<>();\n\t\t\tif (bundle.contains(Messages.format( DROPPED, i )))\n\t\t\t\tfor (Bundlable b : bundle.getCollection( Messages.format( DROPPED, i ) ) ) {\n\t\t\t\t\titems.add( (Item)b );\n\t\t\t\t}\n\t\t\tif (!items.isEmpty()) {\n\t\t\t\tdroppedItems.put( i, items );\n\t\t\t}\n\n\t\t}\n\t}\n\t\n\tpublic static Level loadLevel( int save ) throws IOException {\n\t\t\n\t\tDungeon.level = null;\n\t\tActor.clear();\n\n\t\tBundle bundle = FileUtils.bundleFromFile( GamesInProgress.depthFile( save, depth, branch ));\n\n\t\tLevel level = (Level)bundle.get( LEVEL );\n\n\t\tif (level == null){\n\t\t\tthrow new IOException();\n\t\t} else {\n\t\t\treturn level;\n\t\t}\n\t}\n\t\n\tpublic static void deleteGame( int save, boolean deleteLevels ) {\n\n\t\tif (deleteLevels) {\n\t\t\tString folder = GamesInProgress.gameFolder(save);\n\t\t\tfor (String file : FileUtils.filesInDir(folder)){\n\t\t\t\tif (file.contains(\"depth\")){\n\t\t\t\t\tFileUtils.deleteFile(folder + \"/\" + file);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tFileUtils.overwriteFile(GamesInProgress.gameFile(save), 1);\n\t\t\n\t\tGamesInProgress.delete( save );\n\t}\n\t\n\tpublic static void preview( GamesInProgress.Info info, Bundle bundle ) {\n\t\tinfo.depth = bundle.getInt( DEPTH );\n\t\tinfo.version = bundle.getInt( VERSION );\n\t\tinfo.challenges = bundle.getInt( CHALLENGES );\n\t\tinfo.seed = bundle.getLong( SEED );\n\t\tinfo.customSeed = bundle.getString( CUSTOM_SEED );\n\t\tinfo.daily = bundle.getBoolean( DAILY );\n\t\tinfo.dailyReplay = bundle.getBoolean( DAILY_REPLAY );\n\n\t\tHero.preview( info, bundle.getBundle( HERO ) );\n\t\tStatistics.preview( info, bundle );\n\t}\n\t\n\tpublic static void fail( Object cause ) {\n\t\tif (WndResurrect.instance == null) {\n\t\t\tupdateLevelExplored();\n\t\t\tStatistics.gameWon = false;\n\t\t\tRankings.INSTANCE.submit( false, cause );\n\t\t}\n\t}\n\t\n\tpublic static void win( Object cause ) {\n\n\t\tupdateLevelExplored();\n\t\tStatistics.gameWon = true;\n\n\t\thero.belongings.identify();\n\n\t\tRankings.INSTANCE.submit( true, cause );\n\t}\n\n\tpublic static void updateLevelExplored(){\n\t\tif (branch == 0 && level instanceof RegularLevel && !Dungeon.bossLevel()){\n\t\t\tStatistics.floorsExplored.put( depth, level.isLevelExplored(depth));\n\t\t}\n\t}\n\n\t//default to recomputing based on max hero vision, in case vision just shrank/grew\n\tpublic static void observe(){\n\t\tint dist = Math.max(Dungeon.hero.viewDistance, 8);\n\t\tdist *= 1f + 0.25f*Dungeon.hero.pointsInTalent(Talent.FARSIGHT);\n\t\tdist *= 1f + 0.25f*Dungeon.hero.pointsInTalent(Talent.TELESCOPE);\n\n\t\tif (Dungeon.hero.buff(MagicalSight.class) != null){\n\t\t\tdist = Math.max( dist, MagicalSight.DISTANCE );\n\t\t}\n\n\t\tobserve( dist+1 );\n\t}\n\t\n\tpublic static void observe( int dist ) {\n\n\t\tif (level == null) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlevel.updateFieldOfView(hero, level.heroFOV);\n\n\t\tint x = hero.pos % level.width();\n\t\tint y = hero.pos / level.width();\n\t\n\t\t//left, right, top, bottom\n\t\tint l = Math.max( 0, x - dist );\n\t\tint r = Math.min( x + dist, level.width() - 1 );\n\t\tint t = Math.max( 0, y - dist );\n\t\tint b = Math.min( y + dist, level.height() - 1 );\n\t\n\t\tint width = r - l + 1;\n\t\tint height = b - t + 1;\n\t\t\n\t\tint pos = l + t * level.width();\n\t\n\t\tfor (int i = t; i <= b; i++) {\n\t\t\tBArray.or( level.visited, level.heroFOV, pos, width, level.visited );\n\t\t\tpos+=level.width();\n\t\t}\n\t\n\t\tGameScene.updateFog(l, t, width, height);\n\n\t\tif (hero.buff(MindVision.class) != null){\n\t\t\tfor (Mob m : level.mobs.toArray(new Mob[0])){\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1 - level.width(), 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1, 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, m.pos - 1 + level.width(), 3, level.visited );\n\t\t\t\t//updates adjacent cells too\n\t\t\t\tGameScene.updateFog(m.pos, 2);\n\t\t\t}\n\t\t}\n\n\t\tif (hero.buff(Awareness.class) != null){\n\t\t\tfor (Heap h : level.heaps.valueList()){\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 - level.width(), 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1, 3, level.visited );\n\t\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 + level.width(), 3, level.visited );\n\t\t\t\tGameScene.updateFog(h.pos, 2);\n\t\t\t}\n\t\t}\n\n\t\tfor (TalismanOfForesight.CharAwareness c : hero.buffs(TalismanOfForesight.CharAwareness.class)){\n\t\t\tChar ch = (Char) Actor.findById(c.charID);\n\t\t\tif (ch == null || !ch.isAlive()) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, ch.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(ch.pos, 2);\n\t\t}\n\n\t\tfor (TalismanOfForesight.HeapAwareness h : hero.buffs(TalismanOfForesight.HeapAwareness.class)){\n\t\t\tif (Dungeon.depth != h.depth || Dungeon.branch != h.branch) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, h.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(h.pos, 2);\n\t\t}\n\n\t\tfor (RevealedArea a : hero.buffs(RevealedArea.class)){\n\t\t\tif (Dungeon.depth != a.depth || Dungeon.branch != a.branch) continue;\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1 - level.width(), 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1, 3, level.visited );\n\t\t\tBArray.or( level.visited, level.heroFOV, a.pos - 1 + level.width(), 3, level.visited );\n\t\t\tGameScene.updateFog(a.pos, 2);\n\t\t}\n\n\t\tfor (Char ch : Actor.chars()){\n\t\t\tif (ch instanceof WandOfWarding.Ward\n\t\t\t\t\t|| ch instanceof WandOfRegrowth.Lotus\n\t\t\t\t\t|| ch instanceof SpiritHawk.HawkAlly){\n\t\t\t\tx = ch.pos % level.width();\n\t\t\t\ty = ch.pos / level.width();\n\n\t\t\t\t//left, right, top, bottom\n\t\t\t\tdist = ch.viewDistance+1;\n\t\t\t\tl = Math.max( 0, x - dist );\n\t\t\t\tr = Math.min( x + dist, level.width() - 1 );\n\t\t\t\tt = Math.max( 0, y - dist );\n\t\t\t\tb = Math.min( y + dist, level.height() - 1 );\n\n\t\t\t\twidth = r - l + 1;\n\t\t\t\theight = b - t + 1;\n\n\t\t\t\tpos = l + t * level.width();\n\n\t\t\t\tfor (int i = t; i <= b; i++) {\n\t\t\t\t\tBArray.or( level.visited, level.heroFOV, pos, width, level.visited );\n\t\t\t\t\tpos+=level.width();\n\t\t\t\t}\n\t\t\t\tGameScene.updateFog(ch.pos, dist);\n\t\t\t}\n\t\t}\n\n\t\tGameScene.afterObserve();\n\t}\n\n\t//we store this to avoid having to re-allocate the array with each pathfind\n\tprivate static boolean[] passable;\n\n\tprivate static void setupPassable(){\n\t\tif (passable == null || passable.length != Dungeon.level.length())\n\t\t\tpassable = new boolean[Dungeon.level.length()];\n\t\telse\n\t\t\tBArray.setFalse(passable);\n\t}\n\n\tpublic static boolean[] findPassable(Char ch, boolean[] pass, boolean[] vis, boolean chars){\n\t\treturn findPassable(ch, pass, vis, chars, chars);\n\t}\n\n\tpublic static boolean[] findPassable(Char ch, boolean[] pass, boolean[] vis, boolean chars, boolean considerLarge){\n\t\tsetupPassable();\n\t\tif (ch.flying || ch.buff( Amok.class ) != null) {\n\t\t\tBArray.or( pass, Dungeon.level.avoid, passable );\n\t\t} else {\n\t\t\tSystem.arraycopy( pass, 0, passable, 0, Dungeon.level.length() );\n\t\t}\n\n\t\tif (considerLarge && Char.hasProp(ch, Char.Property.LARGE)){\n\t\t\tBArray.and( passable, Dungeon.level.openSpace, passable );\n\t\t}\n\n\t\tch.modifyPassable(passable);\n\n\t\tif (chars) {\n\t\t\tfor (Char c : Actor.chars()) {\n\t\t\t\tif (vis[c.pos]) {\n\t\t\t\t\tpassable[c.pos] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn passable;\n\t}\n\n\tpublic static PathFinder.Path findPath(Char ch, int to, boolean[] pass, boolean[] vis, boolean chars) {\n\n\t\treturn PathFinder.find( ch.pos, to, findPassable(ch, pass, vis, chars) );\n\n\t}\n\t\n\tpublic static int findStep(Char ch, int to, boolean[] pass, boolean[] visible, boolean chars ) {\n\n\t\tif (Dungeon.level.adjacent( ch.pos, to )) {\n\t\t\treturn Actor.findChar( to ) == null && pass[to] ? to : -1;\n\t\t}\n\n\t\treturn PathFinder.getStep( ch.pos, to, findPassable(ch, pass, visible, chars) );\n\n\t}\n\t\n\tpublic static int flee( Char ch, int from, boolean[] pass, boolean[] visible, boolean chars ) {\n\t\tboolean[] passable = findPassable(ch, pass, visible, false, true);\n\t\tpassable[ch.pos] = true;\n\n\t\t//only consider other chars impassable if our retreat step may collide with them\n\t\tif (chars) {\n\t\t\tfor (Char c : Actor.chars()) {\n\t\t\t\tif (c.pos == from || Dungeon.level.adjacent(c.pos, ch.pos)) {\n\t\t\t\t\tpassable[c.pos] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//chars affected by terror have a shorter lookahead and can't approach the fear source\n\t\tboolean canApproachFromPos = ch.buff(Terror.class) == null && ch.buff(Dread.class) == null;\n\t\treturn PathFinder.getStepBack( ch.pos, from, canApproachFromPos ? 8 : 4, passable, canApproachFromPos );\n\t\t\n\t}\n\n}" }, { "identifier": "Actor", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/Actor.java", "snippet": "public abstract class Actor implements Bundlable {\n\t\n\tpublic static final float TICK\t= 1f;\n\n\tprivate float time;\n\n\tprivate int id = 0;\n\n\t//default priority values for general actor categories\n\t//note that some specific actors pick more specific values\n\t//e.g. a buff acting after all normal buffs might have priority BUFF_PRIO + 1\n\tprotected static final int VFX_PRIO = 100; //visual effects take priority\n\tprotected static final int HERO_PRIO = 0; //positive is before hero, negative after\n\tprotected static final int BLOB_PRIO = -10; //blobs act after hero, before mobs\n\tprotected static final int MOB_PRIO = -20; //mobs act between buffs and blobs\n\tprotected static final int BUFF_PRIO = -30; //buffs act last in a turn\n\tprivate static final int DEFAULT = -100; //if no priority is given, act after all else\n\n\t//used to determine what order actors act in if their time is equal. Higher values act earlier.\n\tprotected int actPriority = DEFAULT;\n\n\tprotected abstract boolean act();\n\n\t//Always spends exactly the specified amount of time, regardless of time-influencing factors\n\tprotected void spendConstant( float time ){\n\t\tthis.time += time;\n\t\t//if time is very close to a whole number, round to a whole number to fix errors\n\t\tfloat ex = Math.abs(this.time % 1f);\n\t\tif (ex < .001f){\n\t\t\tthis.time = Math.round(this.time);\n\t\t}\n\t}\n\n\t//sends time, but the amount can be influenced\n\tprotected void spend( float time ) {\n\t\tspendConstant( time );\n\t}\n\n\tpublic void spendToWhole(){\n\t\ttime = (float)Math.ceil(time);\n\t}\n\t\n\tprotected void postpone( float time ) {\n\t\tif (this.time < now + time) {\n\t\t\tthis.time = now + time;\n\t\t\t//if time is very close to a whole number, round to a whole number to fix errors\n\t\t\tfloat ex = Math.abs(this.time % 1f);\n\t\t\tif (ex < .001f){\n\t\t\t\tthis.time = Math.round(this.time);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic float cooldown() {\n\t\treturn time - now;\n\t}\n\n\tpublic void clearTime() {\n\t\ttime = 0;\n\t}\n\n\tpublic void timeToNow() {\n\t\ttime = now;\n\t}\n\t\n\tprotected void diactivate() {\n\t\ttime = Float.MAX_VALUE;\n\t}\n\t\n\tprotected void onAdd() {}\n\t\n\tprotected void onRemove() {}\n\n\tprivate static final String TIME = \"time\";\n\tprivate static final String ID = \"id\";\n\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tbundle.put( TIME, time );\n\t\tbundle.put( ID, id );\n\t}\n\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\ttime = bundle.getFloat( TIME );\n\t\tint incomingID = bundle.getInt( ID );\n\t\tif (Actor.findById(incomingID) == null){\n\t\t\tid = incomingID;\n\t\t} else {\n\t\t\tid = nextID++;\n\t\t}\n\t}\n\n\tpublic int id() {\n\t\tif (id > 0) {\n\t\t\treturn id;\n\t\t} else {\n\t\t\treturn (id = nextID++);\n\t\t}\n\t}\n\n\t// **********************\n\t// *** Static members ***\n\t// **********************\n\t\n\tprivate static HashSet<Actor> all = new HashSet<>();\n\tprivate static HashSet<Char> chars = new HashSet<>();\n\tprivate static volatile Actor current;\n\n\tprivate static SparseArray<Actor> ids = new SparseArray<>();\n\tprivate static int nextID = 1;\n\n\tprivate static float now = 0;\n\t\n\tpublic static float now(){\n\t\treturn now;\n\t}\n\t\n\tpublic static synchronized void clear() {\n\t\t\n\t\tnow = 0;\n\n\t\tall.clear();\n\t\tchars.clear();\n\n\t\tids.clear();\n\t}\n\n\tpublic static synchronized void fixTime() {\n\t\t\n\t\tif (all.isEmpty()) return;\n\t\t\n\t\tfloat min = Float.MAX_VALUE;\n\t\tfor (Actor a : all) {\n\t\t\tif (a.time < min) {\n\t\t\t\tmin = a.time;\n\t\t\t}\n\t\t}\n\n\t\t//Only pull everything back by whole numbers\n\t\t//So that turns always align with a whole number\n\t\tmin = (int)min;\n\t\tfor (Actor a : all) {\n\t\t\ta.time -= min;\n\t\t}\n\n\t\tif (Dungeon.hero != null && all.contains( Dungeon.hero )) {\n\t\t\tStatistics.duration += min;\n\t\t}\n\t\tnow -= min;\n\t}\n\t\n\tpublic static void init() {\n\t\t\n\t\tadd( Dungeon.hero );\n\t\t\n\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\tadd( mob );\n\t\t}\n\n\t\t//mobs need to remember their targets after every actor is added\n\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\tmob.restoreEnemy();\n\t\t}\n\t\t\n\t\tfor (Blob blob : Dungeon.level.blobs.values()) {\n\t\t\tadd( blob );\n\t\t}\n\t\t\n\t\tcurrent = null;\n\t}\n\n\tprivate static final String NEXTID = \"nextid\";\n\n\tpublic static void storeNextID( Bundle bundle){\n\t\tbundle.put( NEXTID, nextID );\n\t}\n\n\tpublic static void restoreNextID( Bundle bundle){\n\t\tnextID = bundle.getInt( NEXTID );\n\t}\n\n\tpublic static void resetNextID(){\n\t\tnextID = 1;\n\t}\n\n\t/*protected*/public void next() {\n\t\tif (current == this) {\n\t\t\tcurrent = null;\n\t\t}\n\t}\n\n\tpublic static boolean processing(){\n\t\treturn current != null;\n\t}\n\n\tpublic static int curActorPriority() {\n\t\treturn current != null ? current.actPriority : DEFAULT;\n\t}\n\t\n\tpublic static boolean keepActorThreadAlive = true;\n\t\n\tpublic static void process() {\n\t\t\n\t\tboolean doNext;\n\t\tboolean interrupted = false;\n\n\t\tdo {\n\t\t\t\n\t\t\tcurrent = null;\n\t\t\tif (!interrupted) {\n\t\t\t\tfloat earliest = Float.MAX_VALUE;\n\n\t\t\t\tfor (Actor actor : all) {\n\t\t\t\t\t\n\t\t\t\t\t//some actors will always go before others if time is equal.\n\t\t\t\t\tif (actor.time < earliest ||\n\t\t\t\t\t\t\tactor.time == earliest && (current == null || actor.actPriority > current.actPriority)) {\n\t\t\t\t\t\tearliest = actor.time;\n\t\t\t\t\t\tcurrent = actor;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (current != null) {\n\n\t\t\t\tnow = current.time;\n\t\t\t\tActor acting = current;\n\n\t\t\t\tif (acting instanceof Char && ((Char) acting).sprite != null) {\n\t\t\t\t\t// If it's character's turn to act, but its sprite\n\t\t\t\t\t// is moving, wait till the movement is over\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsynchronized (((Char)acting).sprite) {\n\t\t\t\t\t\t\tif (((Char)acting).sprite.isMoving) {\n\t\t\t\t\t\t\t\t((Char) acting).sprite.wait();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\tinterrupted = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tinterrupted = interrupted || Thread.interrupted();\n\t\t\t\t\n\t\t\t\tif (interrupted){\n\t\t\t\t\tdoNext = false;\n\t\t\t\t\tcurrent = null;\n\t\t\t\t} else {\n\t\t\t\t\tdoNext = acting.act();\n\t\t\t\t\tif (doNext && (Dungeon.hero == null || !Dungeon.hero.isAlive())) {\n\t\t\t\t\t\tdoNext = false;\n\t\t\t\t\t\tcurrent = null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdoNext = false;\n\t\t\t}\n\n\t\t\tif (!doNext){\n\t\t\t\tsynchronized (Thread.currentThread()) {\n\t\t\t\t\t\n\t\t\t\t\tinterrupted = interrupted || Thread.interrupted();\n\t\t\t\t\t\n\t\t\t\t\tif (interrupted){\n\t\t\t\t\t\tcurrent = null;\n\t\t\t\t\t\tinterrupted = false;\n\t\t\t\t\t}\n\n\t\t\t\t\t//signals to the gamescene that actor processing is finished for now\n\t\t\t\t\tThread.currentThread().notify();\n\t\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\tThread.currentThread().wait();\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\tinterrupted = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t} while (keepActorThreadAlive);\n\t}\n\t\n\tpublic static void add( Actor actor ) {\n\t\tadd( actor, now );\n\t}\n\t\n\tpublic static void addDelayed( Actor actor, float delay ) {\n\t\tadd( actor, now + Math.max(delay, 0) );\n\t}\n\t\n\tprivate static synchronized void add( Actor actor, float time ) {\n\t\t\n\t\tif (all.contains( actor )) {\n\t\t\treturn;\n\t\t}\n\n\t\tids.put( actor.id(), actor );\n\n\t\tall.add( actor );\n\t\tactor.time += time;\n\t\tactor.onAdd();\n\t\t\n\t\tif (actor instanceof Char) {\n\t\t\tChar ch = (Char)actor;\n\t\t\tchars.add( ch );\n\t\t\tfor (Buff buff : ch.buffs()) {\n\t\t\t\tadd(buff);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static synchronized void remove( Actor actor ) {\n\t\t\n\t\tif (actor != null) {\n\t\t\tall.remove( actor );\n\t\t\tchars.remove( actor );\n\t\t\tactor.onRemove();\n\n\t\t\tif (actor.id > 0) {\n\t\t\t\tids.remove( actor.id );\n\t\t\t}\n\t\t}\n\t}\n\n\t//'freezes' a character in time for a specified amount of time\n\t//USE CAREFULLY! Manipulating time like this is useful for some gameplay effects but is tricky\n\tpublic static void delayChar( Char ch, float time ){\n\t\tch.spendConstant(time);\n\t\tfor (Buff b : ch.buffs()){\n\t\t\tb.spendConstant(time);\n\t\t}\n\t}\n\t\n\tpublic static synchronized Char findChar( int pos ) {\n\t\tfor (Char ch : chars){\n\t\t\tif (ch.pos == pos)\n\t\t\t\treturn ch;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static synchronized Actor findById( int id ) {\n\t\treturn ids.get( id );\n\t}\n\n\tpublic static synchronized HashSet<Actor> all() {\n\t\treturn new HashSet<>(all);\n\t}\n\n\tpublic static synchronized HashSet<Char> chars() { return new HashSet<>(chars); }\n}" }, { "identifier": "Char", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/Char.java", "snippet": "public abstract class Char extends Actor {\n\t\n\tpublic int pos = 0;\n\t\n\tpublic CharSprite sprite;\n\t\n\tpublic int HT;\n\tpublic int HP;\n\t\n\tprotected float baseSpeed\t= 1;\n\tprotected PathFinder.Path path;\n\n\tpublic int paralysed\t = 0;\n\tpublic boolean rooted\t\t= false;\n\tpublic boolean flying\t\t= false;\n\tpublic int invisible\t\t= 0;\n\t\n\t//these are relative to the hero\n\tpublic enum Alignment{\n\t\tENEMY,\n\t\tNEUTRAL,\n\t\tALLY\n\t}\n\tpublic Alignment alignment;\n\t\n\tpublic int viewDistance\t= 8;\n\t\n\tpublic boolean[] fieldOfView = null;\n\t\n\tprivate LinkedHashSet<Buff> buffs = new LinkedHashSet<>();\n\t\n\t@Override\n\tprotected boolean act() {\n\t\tif (fieldOfView == null || fieldOfView.length != Dungeon.level.length()){\n\t\t\tfieldOfView = new boolean[Dungeon.level.length()];\n\t\t}\n\t\tDungeon.level.updateFieldOfView( this, fieldOfView );\n\n\t\t//throw any items that are on top of an immovable char\n\t\tif (properties().contains(Property.IMMOVABLE)){\n\t\t\tthrowItems();\n\t\t}\n\t\treturn false;\n\t}\n\n\tprotected void throwItems(){\n\t\tHeap heap = Dungeon.level.heaps.get( pos );\n\t\tif (heap != null && heap.type == Heap.Type.HEAP\n\t\t\t\t&& !(heap.peek() instanceof Tengu.BombAbility.BombItem)\n\t\t\t\t&& !(heap.peek() instanceof Tengu.ShockerAbility.ShockerItem)) {\n\t\t\tArrayList<Integer> candidates = new ArrayList<>();\n\t\t\tfor (int n : PathFinder.NEIGHBOURS8){\n\t\t\t\tif (Dungeon.level.passable[pos+n]){\n\t\t\t\t\tcandidates.add(pos+n);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!candidates.isEmpty()){\n\t\t\t\tDungeon.level.drop( heap.pickUp(), Random.element(candidates) ).sprite.drop( pos );\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic String name(){\n\t\treturn Messages.get(this, \"name\");\n\t}\n\n\tpublic boolean canInteract(Char c){\n\t\tif (Dungeon.level.adjacent( pos, c.pos )){\n\t\t\treturn true;\n\t\t} else if (c instanceof Hero\n\t\t\t\t&& alignment == Alignment.ALLY\n\t\t\t\t&& Dungeon.level.distance(pos, c.pos) <= 2*Dungeon.hero.pointsInTalent(Talent.ALLY_WARP)){\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t//swaps places by default\n\tpublic boolean interact(Char c){\n\n\t\t//don't allow char to swap onto hazard unless they're flying\n\t\t//you can swap onto a hazard though, as you're not the one instigating the swap\n\t\tif (!Dungeon.level.passable[pos] && !c.flying){\n\t\t\treturn true;\n\t\t}\n\n\t\t//can't swap into a space without room\n\t\tif (properties().contains(Property.LARGE) && !Dungeon.level.openSpace[c.pos]\n\t\t\t|| c.properties().contains(Property.LARGE) && !Dungeon.level.openSpace[pos]){\n\t\t\treturn true;\n\t\t}\n\n\t\t//we do a little raw position shuffling here so that the characters are never\n\t\t// on the same cell when logic such as occupyCell() is triggered\n\t\tint oldPos = pos;\n\t\tint newPos = c.pos;\n\n\t\t//warp instantly with allies in this case\n\t\tif (c == Dungeon.hero && Dungeon.hero.hasTalent(Talent.ALLY_WARP)){\n\t\t\tPathFinder.buildDistanceMap(c.pos, BArray.or(Dungeon.level.passable, Dungeon.level.avoid, null));\n\t\t\tif (PathFinder.distance[pos] == Integer.MAX_VALUE){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tpos = newPos;\n\t\t\tc.pos = oldPos;\n\t\t\tScrollOfTeleportation.appear(this, newPos);\n\t\t\tScrollOfTeleportation.appear(c, oldPos);\n\t\t\tDungeon.observe();\n\t\t\tGameScene.updateFog();\n\t\t\treturn true;\n\t\t}\n\n\t\t//can't swap places if one char has restricted movement\n\t\tif (rooted || c.rooted || buff(Vertigo.class) != null || c.buff(Vertigo.class) != null){\n\t\t\treturn true;\n\t\t}\n\n\t\tc.pos = oldPos;\n\t\tmoveSprite( oldPos, newPos );\n\t\tmove( newPos );\n\n\t\tc.pos = newPos;\n\t\tc.sprite.move( newPos, oldPos );\n\t\tc.move( oldPos );\n\t\t\n\t\tc.spend( 1 / c.speed() );\n\n\t\tif (c == Dungeon.hero){\n\t\t\tif (Dungeon.hero.subClass == HeroSubClass.FREERUNNER){\n\t\t\t\tBuff.affect(Dungeon.hero, Momentum.class).gainStack();\n\t\t\t}\n\n\t\t\tDungeon.hero.busy();\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t\n\tprotected boolean moveSprite( int from, int to ) {\n\t\t\n\t\tif (sprite.isVisible() && sprite.parent != null && (Dungeon.level.heroFOV[from] || Dungeon.level.heroFOV[to])) {\n\t\t\tsprite.move( from, to );\n\t\t\treturn true;\n\t\t} else {\n\t\t\tsprite.turnTo(from, to);\n\t\t\tsprite.place( to );\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic void hitSound( float pitch ){\n\t\tSample.INSTANCE.play(Assets.Sounds.HIT, 1, pitch);\n\t}\n\n\tpublic boolean blockSound( float pitch ) {\n\t\treturn false;\n\t}\n\t\n\tprotected static final String POS = \"pos\";\n\tprotected static final String TAG_HP = \"HP\";\n\tprotected static final String TAG_HT = \"HT\";\n\tprotected static final String TAG_SHLD = \"SHLD\";\n\tprotected static final String BUFFS\t = \"buffs\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.storeInBundle( bundle );\n\t\t\n\t\tbundle.put( POS, pos );\n\t\tbundle.put( TAG_HP, HP );\n\t\tbundle.put( TAG_HT, HT );\n\t\tbundle.put( BUFFS, buffs );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.restoreFromBundle( bundle );\n\t\t\n\t\tpos = bundle.getInt( POS );\n\t\tHP = bundle.getInt( TAG_HP );\n\t\tHT = bundle.getInt( TAG_HT );\n\t\t\n\t\tfor (Bundlable b : bundle.getCollection( BUFFS )) {\n\t\t\tif (b != null) {\n\t\t\t\t((Buff)b).attachTo( this );\n\t\t\t}\n\t\t}\n\t}\n\n\tfinal public boolean attack( Char enemy ){\n\t\treturn attack(enemy, 1f, 0f, 1f);\n\t}\n\t\n\tpublic boolean attack( Char enemy, float dmgMulti, float dmgBonus, float accMulti ) {\n\n\t\tif (enemy == null) return false;\n\t\t\n\t\tboolean visibleFight = Dungeon.level.heroFOV[pos] || Dungeon.level.heroFOV[enemy.pos];\n\n\t\tif (enemy.isInvulnerable(getClass())) {\n\n\t\t\tif (visibleFight) {\n\t\t\t\tenemy.sprite.showStatus( CharSprite.POSITIVE, Messages.get(this, \"invulnerable\") );\n\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1f, Random.Float(0.96f, 1.05f));\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (hit( this, enemy, accMulti, false )) {\n\t\t\t\n\t\t\tint dr = Math.round(enemy.drRoll() * AscensionChallenge.statModifier(enemy));\n\t\t\t\n\t\t\tif (this instanceof Hero){\n\t\t\t\tHero h = (Hero)this;\n\t\t\t\tif (h.belongings.attackingWeapon() instanceof MissileWeapon\n\t\t\t\t\t\t&& h.subClass == HeroSubClass.SNIPER\n\t\t\t\t\t\t&& !Dungeon.level.adjacent(h.pos, enemy.pos)){\n\t\t\t\t\tdr = 0;\n\t\t\t\t}\n\n\t\t\t\tif (h.belongings.attackingWeapon() instanceof Gun.Bullet) {\n\t\t\t\t\tdr *= ((Gun.Bullet) h.belongings.attackingWeapon()).whatBullet().armorFactor();\n\t\t\t\t}\n\n\t\t\t\tif (h.buff(MonkEnergy.MonkAbility.UnarmedAbilityTracker.class) != null){\n\t\t\t\t\tdr = 0;\n\t\t\t\t} else if (h.subClass == HeroSubClass.MONK) {\n\t\t\t\t\t//3 turns with standard attack delay\n\t\t\t\t\tBuff.prolong(h, MonkEnergy.MonkAbility.JustHitTracker.class, 4f);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//we use a float here briefly so that we don't have to constantly round while\n\t\t\t// potentially applying various multiplier effects\n\t\t\tfloat dmg;\n\t\t\tPreparation prep = buff(Preparation.class);\n\t\t\tif (prep != null){\n\t\t\t\tdmg = prep.damageRoll(this);\n\t\t\t\tif (this == Dungeon.hero && Dungeon.hero.hasTalent(Talent.BOUNTY_HUNTER)) {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.BountyHunterTracker.class, 0.0f);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdmg = damageRoll();\n\t\t\t}\n\n\t\t\tdmg = Math.round(dmg*dmgMulti);\n\n\t\t\tBerserk berserk = buff(Berserk.class);\n\t\t\tif (berserk != null) dmg = berserk.damageFactor(dmg);\n\n\t\t\tif (buff( Fury.class ) != null) {\n\t\t\t\tdmg *= 1.5f;\n\t\t\t}\n\n\t\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\t\tdmg *= buff.meleeDamageFactor();\n\t\t\t}\n\n\t\t\tdmg *= AscensionChallenge.statModifier(this);\n\n\t\t\t//flat damage bonus is applied after positive multipliers, but before negative ones\n\t\t\tdmg += dmgBonus;\n\n\t\t\t//friendly endure\n\t\t\tEndure.EndureTracker endure = buff(Endure.EndureTracker.class);\n\t\t\tif (endure != null) dmg = endure.damageFactor(dmg);\n\n\t\t\t//enemy endure\n\t\t\tendure = enemy.buff(Endure.EndureTracker.class);\n\t\t\tif (endure != null){\n\t\t\t\tdmg = endure.adjustDamageTaken(dmg);\n\t\t\t}\n\n\t\t\tif (enemy.buff(ScrollOfChallenge.ChallengeArena.class) != null){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\n\t\t\tif (enemy.buff(MonkEnergy.MonkAbility.Meditate.MeditateResistance.class) != null){\n\t\t\t\tdmg *= 0.2f;\n\t\t\t}\n\n\t\t\tif ( buff(Weakness.class) != null ){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\n\t\t\tif ( buff(SoulMark.class) != null && hero.hasTalent(Talent.MARK_OF_WEAKNESS)) {\n\t\t\t\tif (this.alignment != Alignment.ALLY) {\n\t\t\t\t\tdmg *= Math.pow(0.9f, hero.pointsInTalent(Talent.MARK_OF_WEAKNESS));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tint effectiveDamage = enemy.defenseProc( this, Math.round(dmg) );\n\t\t\t//do not trigger on-hit logic if defenseProc returned a negative value\n\t\t\tif (effectiveDamage >= 0) {\n\t\t\t\teffectiveDamage = Math.max(effectiveDamage - dr, 0);\n\n\t\t\t\tif (enemy.buff(Viscosity.ViscosityTracker.class) != null) {\n\t\t\t\t\teffectiveDamage = enemy.buff(Viscosity.ViscosityTracker.class).deferDamage(effectiveDamage);\n\t\t\t\t\tenemy.buff(Viscosity.ViscosityTracker.class).detach();\n\t\t\t\t}\n\n\t\t\t\t//vulnerable specifically applies after armor reductions\n\t\t\t\tif (enemy.buff(Vulnerable.class) != null) {\n\t\t\t\t\teffectiveDamage *= 1.33f;\n\t\t\t\t}\n\n\t\t\t\teffectiveDamage = attackProc(enemy, effectiveDamage);\n\t\t\t}\n\t\t\tif (visibleFight) {\n\t\t\t\tif (effectiveDamage > 0 || !enemy.blockSound(Random.Float(0.96f, 1.05f))) {\n\t\t\t\t\thitSound(Random.Float(0.87f, 1.15f));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If the enemy is already dead, interrupt the attack.\n\t\t\t// This matters as defence procs can sometimes inflict self-damage, such as armor glyphs.\n\t\t\tif (!enemy.isAlive()){\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tenemy.damage( effectiveDamage, this );\n\n\t\t\tif (buff(FireImbue.class) != null) buff(FireImbue.class).proc(enemy);\n\t\t\tif (buff(FrostImbue.class) != null) buff(FrostImbue.class).proc(enemy);\n\t\t\tif (buff(ThunderImbue.class) != null) buff(ThunderImbue.class).proc(enemy, (int)dmg);\n\n\t\t\tif (enemy.isAlive() && enemy.alignment != alignment && prep != null && prep.canKO(enemy)){\n\t\t\t\tenemy.HP = 0;\n\t\t\t\tif (!enemy.isAlive()) {\n\t\t\t\t\tenemy.die(this);\n\t\t\t\t} else {\n\t\t\t\t\t//helps with triggering any on-damage effects that need to activate\n\t\t\t\t\tenemy.damage(-1, this);\n\t\t\t\t\tDeathMark.processFearTheReaper(enemy);\n\t\t\t\t}\n\t\t\t\tif (enemy.sprite != null) {\n\t\t\t\t\tenemy.sprite.showStatus(CharSprite.NEGATIVE, Messages.get(Preparation.class, \"assassinated\"));\n\t\t\t\t}\n\t\t\t\tif (Random.Float() < hero.pointsInTalent(Talent.ENERGY_DRAW)/3f) {\n\t\t\t\t\tCloakOfShadows cloak = hero.belongings.getItem(CloakOfShadows.class);\n\t\t\t\t\tif (cloak != null) {\n\t\t\t\t\t\tcloak.overCharge(1);\n\t\t\t\t\t\tScrollOfRecharging.charge(Dungeon.hero);\n\t\t\t\t\t\tSpellSprite.show(hero, SpellSprite.CHARGE);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tTalent.CombinedLethalityTriggerTracker combinedLethality = buff(Talent.CombinedLethalityTriggerTracker.class);\n\t\t\tif (combinedLethality != null){\n\t\t\t\tif ( enemy.isAlive() && enemy.alignment != alignment && !Char.hasProp(enemy, Property.BOSS)\n\t\t\t\t\t\t&& !Char.hasProp(enemy, Property.MINIBOSS) && this instanceof Hero &&\n\t\t\t\t\t\t(enemy.HP/(float)enemy.HT) <= 0.4f*((Hero)this).pointsInTalent(Talent.COMBINED_LETHALITY)/3f) {\n\t\t\t\t\tenemy.HP = 0;\n\t\t\t\t\tif (!enemy.isAlive()) {\n\t\t\t\t\t\tenemy.die(this);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//helps with triggering any on-damage effects that need to activate\n\t\t\t\t\t\tenemy.damage(-1, this);\n\t\t\t\t\t\tDeathMark.processFearTheReaper(enemy);\n\t\t\t\t\t}\n\t\t\t\t\tif (enemy.sprite != null) {\n\t\t\t\t\t\tenemy.sprite.showStatus(CharSprite.NEGATIVE, Messages.get(Talent.CombinedLethalityTriggerTracker.class, \"executed\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcombinedLethality.detach();\n\t\t\t}\n\n\t\t\tif (enemy.sprite != null) {\n\t\t\t\tenemy.sprite.bloodBurstA(sprite.center(), effectiveDamage);\n\t\t\t\tenemy.sprite.flash();\n\t\t\t}\n\n\t\t\tif (!enemy.isAlive() && visibleFight) {\n\t\t\t\tif (enemy == Dungeon.hero) {\n\t\t\t\t\t\n\t\t\t\t\tif (this == Dungeon.hero) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this instanceof WandOfLivingEarth.EarthGuardian\n\t\t\t\t\t\t\t|| this instanceof MirrorImage || this instanceof PrismaticImage){\n\t\t\t\t\t\tBadges.validateDeathFromFriendlyMagic();\n\t\t\t\t\t}\n\t\t\t\t\tDungeon.fail( this );\n\t\t\t\t\tGLog.n( Messages.capitalize(Messages.get(Char.class, \"kill\", name())) );\n\t\t\t\t\t\n\t\t\t\t} else if (this == Dungeon.hero) {\n\t\t\t\t\tGLog.i( Messages.capitalize(Messages.get(Char.class, \"defeat\", enemy.name())) );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t\t\n\t\t} else {\n\n\t\t\tif (enemy instanceof Hero) {\n\t\t\t\tif (hero.pointsInTalent(Talent.SWIFT_MOVEMENT) == 3) {\n\t\t\t\t\tBuff.prolong(hero, Invisibility.class, 1.0001f);\n\t\t\t\t}\n\t\t\t\tif (Random.Int(5) < hero.pointsInTalent(Talent.COUNTER_ATTACK)) {\n\t\t\t\t\tBuff.affect(hero, Talent.CounterAttackTracker.class);\n\t\t\t\t}\n\t\t\t\tif (hero.hasTalent(Talent.QUICK_PREP)) {\n\t\t\t\t\tMomentum momentum = hero.buff(Momentum.class);\n\t\t\t\t\tif (momentum != null) {\n\t\t\t\t\t\tmomentum.quickPrep(hero.pointsInTalent(Talent.QUICK_PREP));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tenemy.sprite.showStatus( CharSprite.NEUTRAL, enemy.defenseVerb() );\n\t\t\tif (visibleFight) {\n\t\t\t\t//TODO enemy.defenseSound? currently miss plays for monks/crab even when they parry\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.MISS);\n\t\t\t}\n\t\t\t\n\t\t\treturn false;\n\t\t\t\n\t\t}\n\t}\n\n\tpublic static int INFINITE_ACCURACY = 1_000_000;\n\tpublic static int INFINITE_EVASION = 1_000_000;\n\n\tfinal public static boolean hit( Char attacker, Char defender, boolean magic ) {\n\t\treturn hit(attacker, defender, magic ? 2f : 1f, magic);\n\t}\n\n\tpublic static boolean hit( Char attacker, Char defender, float accMulti, boolean magic ) {\n\t\tfloat acuStat = attacker.attackSkill( defender );\n\t\tfloat defStat = defender.defenseSkill( attacker );\n\n\t\tif (defender instanceof Hero && ((Hero) defender).damageInterrupt){\n\t\t\t((Hero) defender).interrupt();\n\t\t}\n\n\t\t//invisible chars always hit (for the hero this is surprise attacking)\n\t\tif (attacker.invisible > 0 && attacker.canSurpriseAttack()){\n\t\t\tacuStat = INFINITE_ACCURACY;\n\t\t}\n\n\t\tif (defender.buff(MonkEnergy.MonkAbility.Focus.FocusBuff.class) != null && !magic){\n\t\t\tdefStat = INFINITE_EVASION;\n\t\t\tdefender.buff(MonkEnergy.MonkAbility.Focus.FocusBuff.class).detach();\n\t\t\tBuff.affect(defender, MonkEnergy.MonkAbility.Focus.FocusActivation.class, 0);\n\t\t}\n\n\t\t//if accuracy or evasion are large enough, treat them as infinite.\n\t\t//note that infinite evasion beats infinite accuracy\n\t\tif (defStat >= INFINITE_EVASION){\n\t\t\treturn false;\n\t\t} else if (acuStat >= INFINITE_ACCURACY){\n\t\t\treturn true;\n\t\t}\n\n\t\tfloat acuRoll = Random.Float( acuStat );\n\t\tif (attacker.buff(Bless.class) != null) acuRoll *= 1.25f;\n\t\tif (attacker.buff( Hex.class) != null) acuRoll *= 0.8f;\n\t\tif (attacker.buff( Daze.class) != null) acuRoll *= 0.5f;\n\t\tfor (ChampionEnemy buff : attacker.buffs(ChampionEnemy.class)){\n\t\t\tacuRoll *= buff.evasionAndAccuracyFactor();\n\t\t}\n\t\tacuRoll *= AscensionChallenge.statModifier(attacker);\n\t\t\n\t\tfloat defRoll = Random.Float( defStat );\n\t\tif (defender.buff(Bless.class) != null) defRoll *= 1.25f;\n\t\tif (defender.buff( Hex.class) != null) defRoll *= 0.8f;\n\t\tif (defender.buff( Daze.class) != null) defRoll *= 0.5f;\n\t\tfor (ChampionEnemy buff : defender.buffs(ChampionEnemy.class)){\n\t\t\tdefRoll *= buff.evasionAndAccuracyFactor();\n\t\t}\n\t\tdefRoll *= AscensionChallenge.statModifier(defender);\n\t\t\n\t\treturn (acuRoll * accMulti) >= defRoll;\n\t}\n\t\n\tpublic int attackSkill( Char target ) {\n\t\treturn 0;\n\t}\n\t\n\tpublic int defenseSkill( Char enemy ) {\n\t\treturn 0;\n\t}\n\t\n\tpublic String defenseVerb() {\n\t\treturn Messages.get(this, \"def_verb\");\n\t}\n\t\n\tpublic int drRoll() {\n\t\tint dr = 0;\n\n\t\tdr += Random.NormalIntRange( 0 , Barkskin.currentLevel(this) );\n\n\t\treturn dr;\n\t}\n\t\n\tpublic int damageRoll() {\n\t\treturn 1;\n\t}\n\t\n\t//TODO it would be nice to have a pre-armor and post-armor proc.\n\t// atm attack is always post-armor and defence is already pre-armor\n\t\n\tpublic int attackProc( Char enemy, int damage ) {\n\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\tbuff.onAttackProc( enemy );\n\t\t}\n\t\treturn damage;\n\t}\n\t\n\tpublic int defenseProc( Char enemy, int damage ) {\n\n\t\tEarthroot.Armor armor = buff( Earthroot.Armor.class );\n\t\tif (armor != null) {\n\t\t\tdamage = armor.absorb( damage );\n\t\t}\n\n\t\treturn damage;\n\t}\n\t\n\tpublic float speed() {\n\t\tfloat speed = baseSpeed;\n\t\tif ( buff( Cripple.class ) != null ) speed /= 2f;\n\t\tif ( buff( Stamina.class ) != null) speed *= 1.5f;\n\t\tif ( buff( Adrenaline.class ) != null) speed *= 2f;\n\t\tif ( buff( Haste.class ) != null) speed *= 3f;\n\t\tif ( buff( Dread.class ) != null) speed *= 2f;\n\t\treturn speed;\n\t}\n\n\t//currently only used by invisible chars, or by the hero\n\tpublic boolean canSurpriseAttack(){\n\t\treturn true;\n\t}\n\t\n\t//used so that buffs(Shieldbuff.class) isn't called every time unnecessarily\n\tprivate int cachedShield = 0;\n\tpublic boolean needsShieldUpdate = true;\n\t\n\tpublic int shielding(){\n\t\tif (!needsShieldUpdate){\n\t\t\treturn cachedShield;\n\t\t}\n\t\t\n\t\tcachedShield = 0;\n\t\tfor (ShieldBuff s : buffs(ShieldBuff.class)){\n\t\t\tcachedShield += s.shielding();\n\t\t}\n\t\tneedsShieldUpdate = false;\n\t\treturn cachedShield;\n\t}\n\t\n\tpublic void damage( int dmg, Object src ) {\n\t\t\n\t\tif (!isAlive() || dmg < 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tif(isInvulnerable(src.getClass())){\n\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.get(this, \"invulnerable\"));\n\t\t\treturn;\n\t\t}\n\n\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\tdmg = (int) Math.ceil(dmg * buff.damageTakenFactor());\n\t\t}\n\n\t\tif (!(src instanceof LifeLink) && buff(LifeLink.class) != null){\n\t\t\tHashSet<LifeLink> links = buffs(LifeLink.class);\n\t\t\tfor (LifeLink link : links.toArray(new LifeLink[0])){\n\t\t\t\tif (Actor.findById(link.object) == null){\n\t\t\t\t\tlinks.remove(link);\n\t\t\t\t\tlink.detach();\n\t\t\t\t}\n\t\t\t}\n\t\t\tdmg = (int)Math.ceil(dmg / (float)(links.size()+1));\n\t\t\tfor (LifeLink link : links){\n\t\t\t\tChar ch = (Char)Actor.findById(link.object);\n\t\t\t\tif (ch != null) {\n\t\t\t\t\tch.damage(dmg, link);\n\t\t\t\t\tif (!ch.isAlive()) {\n\t\t\t\t\t\tlink.detach();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tTerror t = buff(Terror.class);\n\t\tif (t != null){\n\t\t\tt.recover();\n\t\t}\n\t\tDread d = buff(Dread.class);\n\t\tif (d != null){\n\t\t\td.recover();\n\t\t}\n\t\tCharm c = buff(Charm.class);\n\t\tif (c != null){\n\t\t\tc.recover(src);\n\t\t}\n\t\tif (this.buff(Frost.class) != null){\n\t\t\tBuff.detach( this, Frost.class );\n\t\t}\n\t\tif (this.buff(MagicalSleep.class) != null){\n\t\t\tBuff.detach(this, MagicalSleep.class);\n\t\t}\n\t\tif (this.buff(Doom.class) != null && !isImmune(Doom.class)){\n\t\t\tdmg *= 1.67f;\n\t\t}\n\t\tif (alignment != Alignment.ALLY && this.buff(DeathMark.DeathMarkTracker.class) != null){\n\t\t\tdmg *= 1.25f;\n\t\t}\n\t\t\n\t\tClass<?> srcClass = src.getClass();\n\t\tif (isImmune( srcClass )) {\n\t\t\tdmg = 0;\n\t\t} else {\n\t\t\tdmg = Math.round( dmg * resist( srcClass ));\n\t\t}\n\t\t\n\t\t//TODO improve this when I have proper damage source logic\n\t\tif (AntiMagic.RESISTS.contains(src.getClass()) && buff(ArcaneArmor.class) != null){\n\t\t\tdmg -= Random.NormalIntRange(0, buff(ArcaneArmor.class).level());\n\t\t\tif (dmg < 0) dmg = 0;\n\t\t}\n\n\t\tif (buff(Sickle.HarvestBleedTracker.class) != null){\n\t\t\tif (isImmune(Bleeding.class)){\n\t\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.titleCase(Messages.get(this, \"immune\")));\n\t\t\t\tbuff(Sickle.HarvestBleedTracker.class).detach();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tBleeding b = buff(Bleeding.class);\n\t\t\tif (b == null){\n\t\t\t\tb = new Bleeding();\n\t\t\t}\n\t\t\tb.announced = false;\n\t\t\tb.set(dmg*buff(Sickle.HarvestBleedTracker.class).bleedFactor, Sickle.HarvestBleedTracker.class);\n\t\t\tb.attachTo(this);\n\t\t\tsprite.showStatus(CharSprite.WARNING, Messages.titleCase(b.name()) + \" \" + (int)b.level());\n\t\t\tbuff(Sickle.HarvestBleedTracker.class).detach();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (buff( Paralysis.class ) != null) {\n\t\t\tbuff( Paralysis.class ).processDamage(dmg);\n\t\t}\n\n\t\tint shielded = dmg;\n\t\t//FIXME: when I add proper damage properties, should add an IGNORES_SHIELDS property to use here.\n\t\tif (!(src instanceof Hunger)){\n\t\t\tfor (ShieldBuff s : buffs(ShieldBuff.class)){\n\t\t\t\tdmg = s.absorbDamage(dmg);\n\t\t\t\tif (dmg == 0) break;\n\t\t\t}\n\t\t}\n\t\tshielded -= dmg;\n\t\tHP -= dmg;\n\n\t\tif (HP > 0 && buff(Grim.GrimTracker.class) != null){\n\n\t\t\tfloat finalChance = buff(Grim.GrimTracker.class).maxChance;\n\t\t\tfinalChance *= (float)Math.pow( ((HT - HP) / (float)HT), 2);\n\n\t\t\tif (Random.Float() < finalChance) {\n\t\t\t\tint extraDmg = Math.round(HP*resist(Grim.class));\n\t\t\t\tdmg += extraDmg;\n\t\t\t\tHP -= extraDmg;\n\n\t\t\t\tsprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\tif (!isAlive() && buff(Grim.GrimTracker.class).qualifiesForBadge){\n\t\t\t\t\tBadges.validateGrimWeapon();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (HP < 0 && src instanceof Char && alignment == Alignment.ENEMY){\n\t\t\tif (((Char) src).buff(Kinetic.KineticTracker.class) != null){\n\t\t\t\tint dmgToAdd = -HP;\n\t\t\t\tdmgToAdd -= ((Char) src).buff(Kinetic.KineticTracker.class).conservedDamage;\n\t\t\t\tdmgToAdd = Math.round(dmgToAdd * Weapon.Enchantment.genericProcChanceMultiplier((Char) src));\n\t\t\t\tif (dmgToAdd > 0) {\n\t\t\t\t\tBuff.affect((Char) src, Kinetic.ConservedDamage.class).setBonus(dmgToAdd);\n\t\t\t\t}\n\t\t\t\t((Char) src).buff(Kinetic.KineticTracker.class).detach();\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (sprite != null) {\n\t\t\tsprite.showStatus(HP > HT / 2 ?\n\t\t\t\t\t\t\tCharSprite.WARNING :\n\t\t\t\t\t\t\tCharSprite.NEGATIVE,\n\t\t\t\t\tInteger.toString(dmg + shielded));\n\t\t}\n\n\t\tif (HP < 0) HP = 0;\n\n\t\tif (!isAlive()) {\n\t\t\tdie( src );\n\t\t} else if (HP == 0 && buff(DeathMark.DeathMarkTracker.class) != null){\n\t\t\tDeathMark.processFearTheReaper(this);\n\t\t}\n\t}\n\t\n\tpublic void destroy() {\n\t\tHP = 0;\n\t\tActor.remove( this );\n\n\t\tfor (Char ch : Actor.chars().toArray(new Char[0])){\n\t\t\tif (ch.buff(Charm.class) != null && ch.buff(Charm.class).object == id()){\n\t\t\t\tch.buff(Charm.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Dread.class) != null && ch.buff(Dread.class).object == id()){\n\t\t\t\tch.buff(Dread.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Terror.class) != null && ch.buff(Terror.class).object == id()){\n\t\t\t\tch.buff(Terror.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(SnipersMark.class) != null && ch.buff(SnipersMark.class).object == id()){\n\t\t\t\tch.buff(SnipersMark.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Talent.FollowupStrikeTracker.class) != null\n\t\t\t\t\t&& ch.buff(Talent.FollowupStrikeTracker.class).object == id()){\n\t\t\t\tch.buff(Talent.FollowupStrikeTracker.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Talent.DeadlyFollowupTracker.class) != null\n\t\t\t\t\t&& ch.buff(Talent.DeadlyFollowupTracker.class).object == id()){\n\t\t\t\tch.buff(Talent.DeadlyFollowupTracker.class).detach();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void die( Object src ) {\n\t\tdestroy();\n\t\tif (src != Chasm.class) sprite.die();\n\t}\n\n\t//we cache this info to prevent having to call buff(...) in isAlive.\n\t//This is relevant because we call isAlive during drawing, which has both performance\n\t//and thread coordination implications\n\tpublic boolean deathMarked = false;\n\t\n\tpublic boolean isAlive() {\n\t\treturn HP > 0 || deathMarked;\n\t}\n\n\tpublic boolean isActive() {\n\t\treturn isAlive();\n\t}\n\n\t@Override\n\tprotected void spendConstant(float time) {\n\t\tTimekeepersHourglass.timeFreeze freeze = buff(TimekeepersHourglass.timeFreeze.class);\n\t\tif (freeze != null) {\n\t\t\tfreeze.processTime(time);\n\t\t\treturn;\n\t\t}\n\n\t\tSwiftthistle.TimeBubble bubble = buff(Swiftthistle.TimeBubble.class);\n\t\tif (bubble != null){\n\t\t\tbubble.processTime(time);\n\t\t\treturn;\n\t\t}\n\n\t\tsuper.spendConstant(time);\n\t}\n\n\t@Override\n\tprotected void spend( float time ) {\n\n\t\tfloat timeScale = 1f;\n\t\tif (buff( Slow.class ) != null) {\n\t\t\ttimeScale *= 0.5f;\n\t\t\t//slowed and chilled do not stack\n\t\t} else if (buff( Chill.class ) != null) {\n\t\t\ttimeScale *= buff( Chill.class ).speedFactor();\n\t\t}\n\t\tif (buff( Speed.class ) != null) {\n\t\t\ttimeScale *= 2.0f;\n\t\t}\n\t\t\n\t\tsuper.spend( time / timeScale );\n\t}\n\t\n\tpublic synchronized LinkedHashSet<Buff> buffs() {\n\t\treturn new LinkedHashSet<>(buffs);\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\t//returns all buffs assignable from the given buff class\n\tpublic synchronized <T extends Buff> HashSet<T> buffs( Class<T> c ) {\n\t\tHashSet<T> filtered = new HashSet<>();\n\t\tfor (Buff b : buffs) {\n\t\t\tif (c.isInstance( b )) {\n\t\t\t\tfiltered.add( (T)b );\n\t\t\t}\n\t\t}\n\t\treturn filtered;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t//returns an instance of the specific buff class, if it exists. Not just assignable\n\tpublic synchronized <T extends Buff> T buff( Class<T> c ) {\n\t\tfor (Buff b : buffs) {\n\t\t\tif (b.getClass() == c) {\n\t\t\t\treturn (T)b;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic synchronized boolean isCharmedBy( Char ch ) {\n\t\tint chID = ch.id();\n\t\tfor (Buff b : buffs) {\n\t\t\tif (b instanceof Charm && ((Charm)b).object == chID) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic synchronized boolean add( Buff buff ) {\n\n\t\tif (buff(PotionOfCleansing.Cleanse.class) != null) { //cleansing buff\n\t\t\tif (buff.type == Buff.buffType.NEGATIVE\n\t\t\t\t\t&& !(buff instanceof AllyBuff)\n\t\t\t\t\t&& !(buff instanceof LostInventory)){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tif (sprite != null && buff(Challenge.SpectatorFreeze.class) != null){\n\t\t\treturn false; //can't add buffs while frozen and game is loaded\n\t\t}\n\n\t\tbuffs.add( buff );\n\t\tif (Actor.chars().contains(this)) Actor.add( buff );\n\n\t\tif (sprite != null && buff.announced) {\n\t\t\tswitch (buff.type) {\n\t\t\t\tcase POSITIVE:\n\t\t\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NEGATIVE:\n\t\t\t\t\tsprite.showStatus(CharSprite.NEGATIVE, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NEUTRAL:\n\t\t\t\tdefault:\n\t\t\t\t\tsprite.showStatus(CharSprite.NEUTRAL, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\n\t}\n\t\n\tpublic synchronized boolean remove( Buff buff ) {\n\t\t\n\t\tbuffs.remove( buff );\n\t\tActor.remove( buff );\n\n\t\treturn true;\n\t}\n\t\n\tpublic synchronized void remove( Class<? extends Buff> buffClass ) {\n\t\tfor (Buff buff : buffs( buffClass )) {\n\t\t\tremove( buff );\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected synchronized void onRemove() {\n\t\tfor (Buff buff : buffs.toArray(new Buff[buffs.size()])) {\n\t\t\tbuff.detach();\n\t\t}\n\t}\n\t\n\tpublic synchronized void updateSpriteState() {\n\t\tfor (Buff buff:buffs) {\n\t\t\tbuff.fx( true );\n\t\t}\n\t}\n\t\n\tpublic float stealth() {\n\t\treturn 0;\n\t}\n\n\tpublic final void move( int step ) {\n\t\tmove( step, true );\n\t}\n\n\t//travelling may be false when a character is moving instantaneously, such as via teleportation\n\tpublic void move( int step, boolean travelling ) {\n\n\t\tif (travelling && Dungeon.level.adjacent( step, pos ) && buff( Vertigo.class ) != null) {\n\t\t\tsprite.interruptMotion();\n\t\t\tint newPos = pos + PathFinder.NEIGHBOURS8[Random.Int( 8 )];\n\t\t\tif (!(Dungeon.level.passable[newPos] || Dungeon.level.avoid[newPos])\n\t\t\t\t\t|| (properties().contains(Property.LARGE) && !Dungeon.level.openSpace[newPos])\n\t\t\t\t\t|| Actor.findChar( newPos ) != null)\n\t\t\t\treturn;\n\t\t\telse {\n\t\t\t\tsprite.move(pos, newPos);\n\t\t\t\tstep = newPos;\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.level.map[pos] == Terrain.OPEN_DOOR) {\n\t\t\tDoor.leave( pos );\n\t\t}\n\n\t\tpos = step;\n\t\t\n\t\tif (this != Dungeon.hero) {\n\t\t\tsprite.visible = Dungeon.level.heroFOV[pos];\n\t\t}\n\t\t\n\t\tDungeon.level.occupyCell(this );\n\t}\n\t\n\tpublic int distance( Char other ) {\n\t\treturn Dungeon.level.distance( pos, other.pos );\n\t}\n\n\tpublic boolean[] modifyPassable( boolean[] passable){\n\t\t//do nothing by default, but some chars can pass over terrain that others can't\n\t\treturn passable;\n\t}\n\t\n\tpublic void onMotionComplete() {\n\t\t//Does nothing by default\n\t\t//The main actor thread already accounts for motion,\n\t\t// so calling next() here isn't necessary (see Actor.process)\n\t}\n\t\n\tpublic void onAttackComplete() {\n\t\tnext();\n\t}\n\t\n\tpublic void onOperateComplete() {\n\t\tnext();\n\t}\n\t\n\tprotected final HashSet<Class> resistances = new HashSet<>();\n\t\n\t//returns percent effectiveness after resistances\n\t//TODO currently resistances reduce effectiveness by a static 50%, and do not stack.\n\tpublic float resist( Class effect ){\n\t\tHashSet<Class> resists = new HashSet<>(resistances);\n\t\tfor (Property p : properties()){\n\t\t\tresists.addAll(p.resistances());\n\t\t}\n\t\tfor (Buff b : buffs()){\n\t\t\tresists.addAll(b.resistances());\n\t\t}\n\t\t\n\t\tfloat result = 1f;\n\t\tfor (Class c : resists){\n\t\t\tif (c.isAssignableFrom(effect)){\n\t\t\t\tresult *= 0.5f;\n\t\t\t}\n\t\t}\n\t\treturn result * RingOfElements.resist(this, effect);\n\t}\n\t\n\tprotected final HashSet<Class> immunities = new HashSet<>();\n\t\n\tpublic boolean isImmune(Class effect ){\n\t\tHashSet<Class> immunes = new HashSet<>(immunities);\n\t\tfor (Property p : properties()){\n\t\t\timmunes.addAll(p.immunities());\n\t\t}\n\t\tfor (Buff b : buffs()){\n\t\t\timmunes.addAll(b.immunities());\n\t\t}\n\t\t\n\t\tfor (Class c : immunes){\n\t\t\tif (c.isAssignableFrom(effect)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t//similar to isImmune, but only factors in damage.\n\t//Is used in AI decision-making\n\tpublic boolean isInvulnerable( Class effect ){\n\t\treturn buff(Challenge.SpectatorFreeze.class) != null;\n\t}\n\n\tprotected HashSet<Property> properties = new HashSet<>();\n\n\tpublic HashSet<Property> properties() {\n\t\tHashSet<Property> props = new HashSet<>(properties);\n\t\t//TODO any more of these and we should make it a property of the buff, like with resistances/immunities\n\t\tif (buff(ChampionEnemy.Giant.class) != null) {\n\t\t\tprops.add(Property.LARGE);\n\t\t}\n\t\treturn props;\n\t}\n\n\tpublic enum Property{\n\t\tBOSS ( new HashSet<Class>( Arrays.asList(Grim.class, GrimTrap.class, ScrollOfRetribution.class, ScrollOfPsionicBlast.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(AllyBuff.class, Dread.class) )),\n\t\tMINIBOSS ( new HashSet<Class>(),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(AllyBuff.class, Dread.class) )),\n\t\tBOSS_MINION,\n\t\tUNDEAD,\n\t\tDEMONIC,\n\t\tINORGANIC ( new HashSet<Class>(),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Bleeding.class, ToxicGas.class, Poison.class) )),\n\t\tFIERY ( new HashSet<Class>( Arrays.asList(WandOfFireblast.class, Elemental.FireElemental.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Burning.class, Blazing.class))),\n\t\tICY ( new HashSet<Class>( Arrays.asList(WandOfFrost.class, Elemental.FrostElemental.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Frost.class, Chill.class))),\n\t\tACIDIC ( new HashSet<Class>( Arrays.asList(Corrosion.class)),\n\t\t\t\tnew HashSet<Class>( Arrays.asList(Ooze.class))),\n\t\tELECTRIC ( new HashSet<Class>( Arrays.asList(WandOfLightning.class, Shocking.class, Potential.class, Electricity.class, ShockingDart.class, Elemental.ShockElemental.class )),\n\t\t\t\tnew HashSet<Class>()),\n\t\tLARGE,\n\t\tIMMOVABLE;\n\t\t\n\t\tprivate HashSet<Class> resistances;\n\t\tprivate HashSet<Class> immunities;\n\t\t\n\t\tProperty(){\n\t\t\tthis(new HashSet<Class>(), new HashSet<Class>());\n\t\t}\n\t\t\n\t\tProperty( HashSet<Class> resistances, HashSet<Class> immunities){\n\t\t\tthis.resistances = resistances;\n\t\t\tthis.immunities = immunities;\n\t\t}\n\t\t\n\t\tpublic HashSet<Class> resistances(){\n\t\t\treturn new HashSet<>(resistances);\n\t\t}\n\t\t\n\t\tpublic HashSet<Class> immunities(){\n\t\t\treturn new HashSet<>(immunities);\n\t\t}\n\n\t}\n\n\tpublic static boolean hasProp( Char ch, Property p){\n\t\treturn (ch != null && ch.properties().contains(p));\n\t}\n\n\tpublic void heal(int amount) {\n\t\tamount = Math.min( amount, this.HT - this.HP );\n\t\tif (amount > 0 && this.isAlive()) {\n\t\t\tthis.HP += amount;\n\t\t\tthis.sprite.emitter().start( Speck.factory( Speck.HEALING ), 0.4f, 1 );\n\t\t\tthis.sprite.showStatus( CharSprite.POSITIVE, Integer.toString( amount ) );\n\t\t}\n\t}\n}" }, { "identifier": "CorrosiveGas", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/blobs/CorrosiveGas.java", "snippet": "public class CorrosiveGas extends Blob {\n\n\t//FIXME should have strength per-cell\n\tprivate int strength = 0;\n\n\t//used in specific cases where the source of the corrosion is important for death logic\n\tprivate Class source;\n\n\t@Override\n\tprotected void evolve() {\n\t\tsuper.evolve();\n\n\t\tif (volume == 0){\n\t\t\tstrength = 0;\n\t\t\tsource = null;\n\t\t} else {\n\t\t\tChar ch;\n\t\t\tint cell;\n\n\t\t\tfor (int i = area.left; i < area.right; i++){\n\t\t\t\tfor (int j = area.top; j < area.bottom; j++){\n\t\t\t\t\tcell = i + j*Dungeon.level.width();\n\t\t\t\t\tif (cur[cell] > 0 && (ch = Actor.findChar( cell )) != null) {\n\t\t\t\t\t\tif (!ch.isImmune(this.getClass()))\n\t\t\t\t\t\t\tBuff.affect(ch, Corrosion.class).set(2f, strength, source);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic CorrosiveGas setStrength(int str){\n\t\treturn setStrength(str, null);\n\t}\n\n\tpublic CorrosiveGas setStrength(int str, Class source){\n\t\tif (str > strength) {\n\t\t\tstrength = str;\n\t\t\tthis.source = source;\n\t\t}\n\t\treturn this;\n\t}\n\n\tprivate static final String STRENGTH = \"strength\";\n\tprivate static final String SOURCE\t= \"source\";\n\n\t@Override\n\tpublic void restoreFromBundle(Bundle bundle) {\n\t\tsuper.restoreFromBundle(bundle);\n\t\tstrength = bundle.getInt( STRENGTH );\n\t\tsource = bundle.getClass( SOURCE );\n\t}\n\n\t@Override\n\tpublic void storeInBundle(Bundle bundle) {\n\t\tsuper.storeInBundle(bundle);\n\t\tbundle.put( STRENGTH, strength );\n\t\tbundle.put( SOURCE, source );\n\t}\n\n\t@Override\n\tpublic void use( BlobEmitter emitter ) {\n\t\tsuper.use( emitter );\n\n\t\temitter.pour( Speck.factory(Speck.CORROSION), 0.4f );\n\t}\n\n\t@Override\n\tpublic String tileDesc() {\n\t\treturn Messages.get(this, \"desc\");\n\t}\n}" }, { "identifier": "ToxicGas", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/blobs/ToxicGas.java", "snippet": "public class ToxicGas extends Blob implements Hero.Doom {\n\n\t@Override\n\tprotected void evolve() {\n\t\tsuper.evolve();\n\n\t\tint damage = 1 + Dungeon.scalingDepth()/5;\n\n\t\tChar ch;\n\t\tint cell;\n\n\t\tfor (int i = area.left; i < area.right; i++){\n\t\t\tfor (int j = area.top; j < area.bottom; j++){\n\t\t\t\tcell = i + j*Dungeon.level.width();\n\t\t\t\tif (cur[cell] > 0 && (ch = Actor.findChar( cell )) != null) {\n\t\t\t\t\tif (!ch.isImmune(this.getClass())) {\n\n\t\t\t\t\t\tch.damage(damage, this);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void use( BlobEmitter emitter ) {\n\t\tsuper.use( emitter );\n\n\t\temitter.pour( Speck.factory( Speck.TOXIC ), 0.4f );\n\t}\n\t\n\t@Override\n\tpublic String tileDesc() {\n\t\treturn Messages.get(this, \"desc\");\n\t}\n\t\n\t@Override\n\tpublic void onDeath() {\n\t\t\n\t\tBadges.validateDeathFromGas();\n\t\t\n\t\tDungeon.fail( this );\n\t\tGLog.n( Messages.get(this, \"ondeath\") );\n\t}\n}" }, { "identifier": "AllyBuff", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/AllyBuff.java", "snippet": "public abstract class AllyBuff extends Buff{\n\n\t@Override\n\tpublic boolean attachTo(Char target) {\n\t\tif (super.attachTo(target)){\n\t\t\ttarget.alignment = Char.Alignment.ALLY;\n\t\t\tif (target.buff(PinCushion.class) != null){\n\t\t\t\ttarget.buff(PinCushion.class).detach();\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t//for when applying an ally buff should also cause that enemy to give exp/loot as if they had died\n\t//consider that chars with the ally alignment do not drop items or award exp on death\n\tpublic static void affectAndLoot(Mob enemy, Hero hero, Class<?extends AllyBuff> buffCls){\n\t\tboolean wasEnemy = enemy.alignment == Char.Alignment.ENEMY;\n\t\tBuff.affect(enemy, buffCls);\n\n\t\tif (enemy.buff(buffCls) != null && wasEnemy){\n\t\t\tenemy.rollToDropLoot();\n\n\t\t\tStatistics.enemiesSlain++;\n\t\t\tBadges.validateMonstersSlain();\n\t\t\tStatistics.qualifiedForNoKilling = false;\n\n\t\t\tAscensionChallenge.processEnemyKill(enemy);\n\n\t\t\tint exp = hero.lvl <= enemy.maxLvl ? enemy.EXP : 0;\n\t\t\tif (exp > 0) {\n\t\t\t\thero.sprite.showStatus(CharSprite.POSITIVE, Messages.get(enemy, \"exp\", exp));\n\t\t\t}\n\t\t\thero.earnExp(exp, enemy.getClass());\n\n\t\t\tif (hero.subClass == HeroSubClass.MONK){\n\t\t\t\tBuff.affect(hero, MonkEnergy.class).gainEnergy(enemy);\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "Buff", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Buff.java", "snippet": "public class Buff extends Actor {\n\t\n\tpublic Char target;\n\n\t{\n\t\tactPriority = BUFF_PRIO; //low priority, towards the end of a turn\n\t}\n\n\t//determines how the buff is announced when it is shown.\n\tpublic enum buffType {POSITIVE, NEGATIVE, NEUTRAL}\n\tpublic buffType type = buffType.NEUTRAL;\n\t\n\t//whether or not the buff announces its name\n\tpublic boolean announced = false;\n\n\t//whether a buff should persist through revive effects for the hero\n\tpublic boolean revivePersists = false;\n\t\n\tprotected HashSet<Class> resistances = new HashSet<>();\n\t\n\tpublic HashSet<Class> resistances() {\n\t\treturn new HashSet<>(resistances);\n\t}\n\t\n\tprotected HashSet<Class> immunities = new HashSet<>();\n\t\n\tpublic HashSet<Class> immunities() {\n\t\treturn new HashSet<>(immunities);\n\t}\n\t\n\tpublic boolean attachTo( Char target ) {\n\n\t\tif (target.isImmune( getClass() )) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tthis.target = target;\n\n\t\tif (target.add( this )){\n\t\t\tif (target.sprite != null) fx( true );\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.target = null;\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic void detach() {\n\t\tif (target.remove( this ) && target.sprite != null) fx( false );\n\t}\n\t\n\t@Override\n\tpublic boolean act() {\n\t\tdiactivate();\n\t\treturn true;\n\t}\n\t\n\tpublic int icon() {\n\t\treturn BuffIndicator.NONE;\n\t}\n\n\t//some buffs may want to tint the base texture color of their icon\n\tpublic void tintIcon( Image icon ){\n\t\t//do nothing by default\n\t}\n\n\t//percent (0-1) to fade out out the buff icon, usually if buff is expiring\n\tpublic float iconFadePercent(){\n\t\treturn 0;\n\t}\n\n\t//text to display on large buff icons in the desktop UI\n\tpublic String iconTextDisplay(){\n\t\treturn \"\";\n\t}\n\n\t//visual effect usually attached to the sprite of the character the buff is attacked to\n\tpublic void fx(boolean on) {\n\t\t//do nothing by default\n\t}\n\n\tpublic String heroMessage(){\n\t\tString msg = Messages.get(this, \"heromsg\");\n\t\tif (msg.isEmpty()) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn msg;\n\t\t}\n\t}\n\n\tpublic String name() {\n\t\treturn Messages.get(this, \"name\");\n\t}\n\n\tpublic String desc(){\n\t\treturn Messages.get(this, \"desc\");\n\t}\n\n\t//to handle the common case of showing how many turns are remaining in a buff description.\n\tprotected String dispTurns(float input){\n\t\treturn Messages.decimalFormat(\"#.##\", input);\n\t}\n\n\t//buffs act after the hero, so it is often useful to use cooldown+1 when display buff time remaining\n\tpublic float visualcooldown(){\n\t\treturn cooldown()+1f;\n\t}\n\n\t//creates a fresh instance of the buff and attaches that, this allows duplication.\n\tpublic static<T extends Buff> T append( Char target, Class<T> buffClass ) {\n\t\tT buff = Reflection.newInstance(buffClass);\n\t\tbuff.attachTo( target );\n\t\treturn buff;\n\t}\n\n\tpublic static<T extends FlavourBuff> T append( Char target, Class<T> buffClass, float duration ) {\n\t\tT buff = append( target, buffClass );\n\t\tbuff.spend( duration * target.resist(buffClass) );\n\t\treturn buff;\n\t}\n\n\t//same as append, but prevents duplication.\n\tpublic static<T extends Buff> T affect( Char target, Class<T> buffClass ) {\n\t\tT buff = target.buff( buffClass );\n\t\tif (buff != null) {\n\t\t\treturn buff;\n\t\t} else {\n\t\t\treturn append( target, buffClass );\n\t\t}\n\t}\n\t\n\tpublic static<T extends FlavourBuff> T affect( Char target, Class<T> buffClass, float duration ) {\n\t\tT buff = affect( target, buffClass );\n\t\tbuff.spend( duration * target.resist(buffClass) );\n\t\treturn buff;\n\t}\n\n\t//postpones an already active buff, or creates & attaches a new buff and delays that.\n\tpublic static<T extends FlavourBuff> T prolong( Char target, Class<T> buffClass, float duration ) {\n\t\tT buff = affect( target, buffClass );\n\t\tbuff.postpone( duration * target.resist(buffClass) );\n\t\treturn buff;\n\t}\n\n\tpublic static<T extends CounterBuff> T count( Char target, Class<T> buffclass, float count ) {\n\t\tT buff = affect( target, buffclass );\n\t\tbuff.countUp( count );\n\t\treturn buff;\n\t}\n\t\n\tpublic static void detach( Char target, Class<? extends Buff> cl ) {\n\t\tfor ( Buff b : target.buffs( cl )){\n\t\t\tb.detach();\n\t\t}\n\t}\n}" }, { "identifier": "Burning", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Burning.java", "snippet": "public class Burning extends Buff implements Hero.Doom {\n\t\n\tprivate static final float DURATION = 8f;\n\t\n\tprivate float left;\n\t\n\t//for tracking burning of hero items\n\tprivate int burnIncrement = 0;\n\t\n\tprivate static final String LEFT\t= \"left\";\n\tprivate static final String BURN\t= \"burnIncrement\";\n\n\t{\n\t\ttype = buffType.NEGATIVE;\n\t\tannounced = true;\n\t}\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tsuper.storeInBundle( bundle );\n\t\tbundle.put( LEFT, left );\n\t\tbundle.put( BURN, burnIncrement );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tsuper.restoreFromBundle(bundle);\n\t\tleft = bundle.getFloat( LEFT );\n\t\tburnIncrement = bundle.getInt( BURN );\n\t}\n\n\t@Override\n\tpublic boolean attachTo(Char target) {\n\t\tBuff.detach( target, Chill.class);\n\n\t\treturn super.attachTo(target);\n\t}\n\n\t@Override\n\tpublic boolean act() {\n\t\t\n\t\tif (target.isAlive() && !target.isImmune(getClass())) {\n\t\t\t\n\t\t\tint damage = Random.NormalIntRange( 1, 3 + Dungeon.scalingDepth()/4 );\n\t\t\tBuff.detach( target, Chill.class);\n\n\t\t\tif (target instanceof Hero && target.buff(TimekeepersHourglass.timeStasis.class) == null) {\n\t\t\t\t\n\t\t\t\tHero hero = (Hero)target;\n\n\t\t\t\thero.damage( damage, this );\n\t\t\t\tburnIncrement++;\n\n\t\t\t\t//at 4+ turns, there is a (turns-3)/3 chance an item burns\n\t\t\t\tif (Random.Int(3) < (burnIncrement - 3)){\n\t\t\t\t\tburnIncrement = 0;\n\n\t\t\t\t\tArrayList<Item> burnable = new ArrayList<>();\n\t\t\t\t\t//does not reach inside of containers\n\t\t\t\t\tif (hero.buff(LostInventory.class) == null) {\n\t\t\t\t\t\tfor (Item i : hero.belongings.backpack.items) {\n\t\t\t\t\t\t\tif (!i.unique && (i instanceof Scroll || i instanceof MysteryMeat || i instanceof FrozenCarpaccio)) {\n\t\t\t\t\t\t\t\tburnable.add(i);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!burnable.isEmpty()){\n\t\t\t\t\t\tItem toBurn = Random.element(burnable).detach(hero.belongings.backpack);\n\t\t\t\t\t\tGLog.w( Messages.capitalize(Messages.get(this, \"burnsup\", toBurn.title())) );\n\t\t\t\t\t\tif (toBurn instanceof MysteryMeat || toBurn instanceof FrozenCarpaccio){\n\t\t\t\t\t\t\tChargrilledMeat steak = new ChargrilledMeat();\n\t\t\t\t\t\t\tif (!steak.collect( hero.belongings.backpack )) {\n\t\t\t\t\t\t\t\tDungeon.level.drop( steak, hero.pos ).sprite.drop();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tHeap.burnFX( hero.pos );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\ttarget.damage( damage, this );\n\t\t\t}\n\n\t\t\tif (target instanceof Thief && ((Thief) target).item != null) {\n\n\t\t\t\tItem item = ((Thief) target).item;\n\n\t\t\t\tif (!item.unique && item instanceof Scroll) {\n\t\t\t\t\ttarget.sprite.emitter().burst( ElmoParticle.FACTORY, 6 );\n\t\t\t\t\t((Thief)target).item = null;\n\t\t\t\t} else if (item instanceof MysteryMeat) {\n\t\t\t\t\ttarget.sprite.emitter().burst( ElmoParticle.FACTORY, 6 );\n\t\t\t\t\t((Thief)target).item = new ChargrilledMeat();\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tdetach();\n\t\t}\n\t\t\n\t\tif (Dungeon.level.flamable[target.pos] && Blob.volumeAt(target.pos, Fire.class) == 0) {\n\t\t\tGameScene.add( Blob.seed( target.pos, 4, Fire.class ) );\n\t\t}\n\t\t\n\t\tspend( TICK );\n\t\tleft -= TICK;\n\t\t\n\t\tif (left <= 0 ||\n\t\t\t(Dungeon.level.water[target.pos] && !target.flying)) {\n\t\t\t\n\t\t\tdetach();\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t\n\tpublic void reignite( Char ch ) {\n\t\treignite( ch, DURATION );\n\t}\n\t\n\tpublic void reignite( Char ch, float duration ) {\n\t\tif (ch.isImmune(Burning.class)){\n\t\t\t//TODO this only works for the hero, not others who can have brimstone+arcana effect\n\t\t\t// e.g. prismatic image, shadow clone\n\t\t\tif (ch instanceof Hero\n\t\t\t\t\t&& ((Hero) ch).belongings.armor() != null\n\t\t\t\t\t&& ((Hero) ch).belongings.armor().hasGlyph(Brimstone.class, ch)){\n\t\t\t\t//has a 2*boost/50% chance to generate 1 shield per turn, to a max of 4x boost\n\t\t\t\tfloat shieldChance = 2*(Armor.Glyph.genericProcChanceMultiplier(ch) - 1f);\n\t\t\t\tint shieldCap = Math.round(shieldChance*4f);\n\t\t\t\tif (shieldCap > 0 && Random.Float() < shieldChance){\n\t\t\t\t\tBarrier barrier = Buff.affect(ch, Barrier.class);\n\t\t\t\t\tif (barrier.shielding() < shieldCap){\n\t\t\t\t\t\tbarrier.incShield(1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tleft = duration;\n\t}\n\t\n\t@Override\n\tpublic int icon() {\n\t\treturn BuffIndicator.FIRE;\n\t}\n\n\t@Override\n\tpublic float iconFadePercent() {\n\t\treturn Math.max(0, (DURATION - left) / DURATION);\n\t}\n\n\t@Override\n\tpublic String iconTextDisplay() {\n\t\treturn Integer.toString((int)left);\n\t}\n\n\t@Override\n\tpublic void fx(boolean on) {\n\t\tif (on) target.sprite.add(CharSprite.State.BURNING);\n\t\telse target.sprite.remove(CharSprite.State.BURNING);\n\t}\n\n\t@Override\n\tpublic String desc() {\n\t\treturn Messages.get(this, \"desc\", dispTurns(left));\n\t}\n\n\t@Override\n\tpublic void onDeath() {\n\t\t\n\t\tBadges.validateDeathFromFire();\n\t\t\n\t\tDungeon.fail( this );\n\t\tGLog.n( Messages.get(this, \"ondeath\") );\n\t}\n}" }, { "identifier": "Invisibility", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/Invisibility.java", "snippet": "public class Invisibility extends FlavourBuff {\n\n\tpublic static final float DURATION\t= 20f;\n\n\t{\n\t\ttype = buffType.POSITIVE;\n\t\tannounced = true;\n\t}\n\t\n\t@Override\n\tpublic boolean attachTo( Char target ) {\n\t\tif (super.attachTo( target )) {\n\t\t\ttarget.invisible++;\n\t\t\tif (target instanceof Hero && ((Hero) target).subClass == HeroSubClass.ASSASSIN){\n\t\t\t\tBuff.affect(target, Preparation.class);\n\t\t\t}\n\t\t\tif (target instanceof Hero && ((Hero) target).hasTalent(Talent.PROTECTIVE_SHADOWS)){\n\t\t\t\tBuff.affect(target, Talent.ProtectiveShadowsTracker.class);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void detach() {\n\t\tif (target.invisible > 0)\n\t\t\ttarget.invisible--;\n\t\tsuper.detach();\n\t}\n\t\n\t@Override\n\tpublic int icon() {\n\t\treturn BuffIndicator.INVISIBLE;\n\t}\n\n\t@Override\n\tpublic float iconFadePercent() {\n\t\treturn Math.max(0, (DURATION - visualcooldown()) / DURATION);\n\t}\n\n\t@Override\n\tpublic void fx(boolean on) {\n\t\tif (on) target.sprite.add( CharSprite.State.INVISIBLE );\n\t\telse if (target.invisible == 0) target.sprite.remove( CharSprite.State.INVISIBLE );\n\t}\n\n\tpublic static void dispel() {\n\t\tif (Dungeon.hero == null) return;\n\n\t\tdispel(Dungeon.hero);\n\t}\n\n\tpublic static void dispel(Char ch){\n\n\t\tfor ( Buff invis : ch.buffs( Invisibility.class )){\n\t\t\tinvis.detach();\n\t\t}\n\t\tCloakOfShadows.cloakStealth cloakBuff = ch.buff( CloakOfShadows.cloakStealth.class );\n\t\tif (cloakBuff != null) {\n\t\t\tcloakBuff.dispel();\n\t\t}\n\n\t\t//these aren't forms of invisibility, but do dispel at the same time as it.\n\t\tTimekeepersHourglass.timeFreeze timeFreeze = ch.buff( TimekeepersHourglass.timeFreeze.class );\n\t\tif (timeFreeze != null) {\n\t\t\ttimeFreeze.detach();\n\t\t}\n\n\t\tPreparation prep = ch.buff( Preparation.class );\n\t\tif (prep != null){\n\t\t\tprep.detach();\n\t\t}\n\n\t\tSwiftthistle.TimeBubble bubble = ch.buff( Swiftthistle.TimeBubble.class );\n\t\tif (bubble != null){\n\t\t\tbubble.detach();\n\t\t}\n\t}\n}" }, { "identifier": "Hero", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/hero/Hero.java", "snippet": "public class Hero extends Char {\n\n\t{\n\t\tactPriority = HERO_PRIO;\n\t\t\n\t\talignment = Alignment.ALLY;\n\t}\n\t\n\tpublic static final int MAX_LEVEL = 30;\n\n\tpublic static final int STARTING_STR = 10;\n\t\n\tprivate static final float TIME_TO_REST\t\t = 1f;\n\tprivate static final float TIME_TO_SEARCH\t = 2f;\n\tprivate static final float HUNGER_FOR_SEARCH\t= 6f;\n\t\n\tpublic HeroClass heroClass = HeroClass.ROGUE;\n\tpublic HeroSubClass subClass = HeroSubClass.NONE;\n\tpublic ArmorAbility armorAbility = null;\n\tpublic ArrayList<LinkedHashMap<Talent, Integer>> talents = new ArrayList<>();\n\tpublic LinkedHashMap<Talent, Talent> metamorphedTalents = new LinkedHashMap<>();\n\t\n\tprivate int attackSkill = 10;\n\tprivate int defenseSkill = 5;\n\n\tpublic boolean ready = false;\n\tpublic boolean damageInterrupt = true;\n\tpublic HeroAction curAction = null;\n\tpublic HeroAction lastAction = null;\n\n\tprivate Char enemy;\n\t\n\tpublic boolean resting = false;\n\t\n\tpublic Belongings belongings;\n\t\n\tpublic int STR;\n\t\n\tpublic float awareness;\n\t\n\tpublic int lvl = 1;\n\tpublic int exp = 0;\n\t\n\tpublic int HTBoost = 0;\n\t\n\tprivate ArrayList<Mob> visibleEnemies;\n\n\t//This list is maintained so that some logic checks can be skipped\n\t// for enemies we know we aren't seeing normally, resulting in better performance\n\tpublic ArrayList<Mob> mindVisionEnemies = new ArrayList<>();\n\n\tpublic Hero() {\n\t\tsuper();\n\n\t\tHP = HT = (Dungeon.isChallenged(Challenges.SUPERMAN)) ? 10 : 20;\n\t\tSTR = STARTING_STR;\n\t\t\n\t\tbelongings = new Belongings( this );\n\t\t\n\t\tvisibleEnemies = new ArrayList<>();\n\t}\n\t\n\tpublic void updateHT( boolean boostHP ){\n\t\tint curHT = HT;\n\n\t\tHT = (Dungeon.isChallenged(Challenges.SUPERMAN)) ? 10 : 20 + 5 * (lvl-1) + HTBoost;\n\t\tif (this.hasTalent(Talent.MAX_HEALTH)) {\n\t\t\tHT += 5*this.pointsInTalent(Talent.MAX_HEALTH);\n\t\t}\n\t\tfloat multiplier = RingOfMight.HTMultiplier(this);\n\t\tHT = Math.round(multiplier * HT);\n\t\t\n\t\tif (buff(ElixirOfMight.HTBoost.class) != null){\n\t\t\tHT += buff(ElixirOfMight.HTBoost.class).boost();\n\t\t}\n\n\t\tif (buff(ElixirOfTalent.ElixirOfTalentHTBoost.class) != null){\n\t\t\tHT += buff(ElixirOfTalent.ElixirOfTalentHTBoost.class).boost();\n\t\t}\n\t\t\n\t\tif (boostHP){\n\t\t\tHP += Math.max(HT - curHT, 0);\n\t\t}\n\t\tHP = Math.min(HP, HT);\n\t}\n\n\tpublic int STR() {\n\t\tint strBonus = 0;\n\n\t\tstrBonus += RingOfMight.strengthBonus( this );\n\t\t\n\t\tAdrenalineSurge buff = buff(AdrenalineSurge.class);\n\t\tif (buff != null){\n\t\t\tstrBonus += buff.boost();\n\t\t}\n\n\t\tif (hasTalent(Talent.STRONGMAN)){\n\t\t\tstrBonus += (int)Math.floor(STR * (0.03f + 0.05f*pointsInTalent(Talent.STRONGMAN)));\n\t\t}\n\n\t\treturn STR + strBonus;\n\t}\n\n\tpublic void onSTRGained() {\n\n\t}\n\n\tpublic void onSTRLost() {\n\n\t}\n\n\tprivate static final String CLASS = \"class\";\n\tprivate static final String SUBCLASS = \"subClass\";\n\tprivate static final String ABILITY = \"armorAbility\";\n\n\tprivate static final String ATTACK\t\t= \"attackSkill\";\n\tprivate static final String DEFENSE\t\t= \"defenseSkill\";\n\tprivate static final String STRENGTH\t= \"STR\";\n\tprivate static final String LEVEL\t\t= \"lvl\";\n\tprivate static final String EXPERIENCE\t= \"exp\";\n\tprivate static final String HTBOOST = \"htboost\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\n\t\tsuper.storeInBundle( bundle );\n\n\t\tbundle.put( CLASS, heroClass );\n\t\tbundle.put( SUBCLASS, subClass );\n\t\tbundle.put( ABILITY, armorAbility );\n\t\tTalent.storeTalentsInBundle( bundle, this );\n\t\t\n\t\tbundle.put( ATTACK, attackSkill );\n\t\tbundle.put( DEFENSE, defenseSkill );\n\t\t\n\t\tbundle.put( STRENGTH, STR );\n\t\t\n\t\tbundle.put( LEVEL, lvl );\n\t\tbundle.put( EXPERIENCE, exp );\n\t\t\n\t\tbundle.put( HTBOOST, HTBoost );\n\n\t\tbelongings.storeInBundle( bundle );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\n\t\tlvl = bundle.getInt( LEVEL );\n\t\texp = bundle.getInt( EXPERIENCE );\n\n\t\tHTBoost = bundle.getInt(HTBOOST);\n\n\t\tsuper.restoreFromBundle( bundle );\n\n\t\theroClass = bundle.getEnum( CLASS, HeroClass.class );\n\t\tsubClass = bundle.getEnum( SUBCLASS, HeroSubClass.class );\n\t\tarmorAbility = (ArmorAbility)bundle.get( ABILITY );\n\t\tTalent.restoreTalentsFromBundle( bundle, this );\n\t\t\n\t\tattackSkill = bundle.getInt( ATTACK );\n\t\tdefenseSkill = bundle.getInt( DEFENSE );\n\t\t\n\t\tSTR = bundle.getInt( STRENGTH );\n\n\t\tbelongings.restoreFromBundle( bundle );\n\t}\n\t\n\tpublic static void preview( GamesInProgress.Info info, Bundle bundle ) {\n\t\tinfo.level = bundle.getInt( LEVEL );\n\t\tinfo.str = bundle.getInt( STRENGTH );\n\t\tinfo.exp = bundle.getInt( EXPERIENCE );\n\t\tinfo.hp = bundle.getInt( Char.TAG_HP );\n\t\tinfo.ht = bundle.getInt( Char.TAG_HT );\n\t\tinfo.shld = bundle.getInt( Char.TAG_SHLD );\n\t\tinfo.heroClass = bundle.getEnum( CLASS, HeroClass.class );\n\t\tinfo.subClass = bundle.getEnum( SUBCLASS, HeroSubClass.class );\n\t\tBelongings.preview( info, bundle );\n\t}\n\n\tpublic boolean hasTalent( Talent talent ){\n\t\treturn pointsInTalent(talent) > 0;\n\t}\n\n\tpublic int pointsInTalent( Talent talent ){\n\t\tfor (LinkedHashMap<Talent, Integer> tier : talents){\n\t\t\tfor (Talent f : tier.keySet()){\n\t\t\t\tif (f == talent) return tier.get(f);\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\n\tpublic void upgradeTalent( Talent talent ){\n\t\tfor (LinkedHashMap<Talent, Integer> tier : talents){\n\t\t\tfor (Talent f : tier.keySet()){\n\t\t\t\tif (f == talent) tier.put(talent, tier.get(talent)+1);\n\t\t\t}\n\t\t}\n\t\tTalent.onTalentUpgraded(this, talent);\n\t}\n\n\tpublic int talentPointsSpent(int tier){\n\t\tint total = 0;\n\t\tfor (int i : talents.get(tier-1).values()){\n\t\t\ttotal += i;\n\t\t}\n\t\treturn total;\n\t}\n\n\tpublic int talentPointsAvailable(int tier){\n\t\tif (lvl < (Talent.tierLevelThresholds[tier] - 1)\n\t\t\t|| (tier == 3 && subClass == HeroSubClass.NONE)\n\t\t\t|| (tier == 4 && armorAbility == null)) {\n\t\t\treturn 0;\n\t\t} else if (lvl >= Talent.tierLevelThresholds[tier+1]){\n\t\t\treturn Talent.tierLevelThresholds[tier+1] - Talent.tierLevelThresholds[tier] - talentPointsSpent(tier) + bonusTalentPoints(tier);\n\t\t} else {\n\t\t\treturn 1 + lvl - Talent.tierLevelThresholds[tier] - talentPointsSpent(tier) + bonusTalentPoints(tier);\n\t\t}\n\t}\n\n\tpublic int bonusTalentPoints(int tier){\n\t\tint bonusPoints = 0;\n\t\tif (lvl < (Talent.tierLevelThresholds[tier]-1)\n\t\t\t\t|| (tier == 3 && subClass == HeroSubClass.NONE)\n\t\t\t\t|| (tier == 4 && armorAbility == null)) {\n\t\t\treturn 0;\n\t\t} else if (buff(PotionOfDivineInspiration.DivineInspirationTracker.class) != null\n\t\t\t\t\t&& buff(PotionOfDivineInspiration.DivineInspirationTracker.class).isBoosted(tier)) {\n\t\t\tbonusPoints += 2;\n\t\t}\n\t\tif (tier == 3 && buff(ElixirOfTalent.BonusTalentTracker.class) != null) {\n\t\t\tbonusPoints += 4;\n\t\t}\n\t\treturn bonusPoints;\n\t}\n\t\n\tpublic String className() {\n\t\treturn subClass == null || subClass == HeroSubClass.NONE ? heroClass.title() : subClass.title();\n\t}\n\n\t@Override\n\tpublic String name(){\n\t\treturn className();\n\t}\n\n\t@Override\n\tpublic void hitSound(float pitch) {\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\tbelongings.attackingWeapon().hitSound(pitch);\n\t\t} else if (RingOfForce.getBuffedBonus(this, RingOfForce.Force.class) > 0) {\n\t\t\t//pitch deepens by 2.5% (additive) per point of strength, down to 75%\n\t\t\tsuper.hitSound( pitch * GameMath.gate( 0.75f, 1.25f - 0.025f*STR(), 1f) );\n\t\t} else {\n\t\t\tsuper.hitSound(pitch * 1.1f);\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean blockSound(float pitch) {\n\t\tif ( belongings.weapon() != null && belongings.weapon().defenseFactor(this) >= 4 ){\n\t\t\tSample.INSTANCE.play( Assets.Sounds.HIT_PARRY, 1, pitch);\n\t\t\treturn true;\n\t\t}\n\t\treturn super.blockSound(pitch);\n\t}\n\n\tpublic void live() {\n\t\tfor (Buff b : buffs()){\n\t\t\tif (!b.revivePersists) b.detach();\n\t\t}\n\t\tBuff.affect( this, Regeneration.class );\n\t\tBuff.affect( this, Hunger.class );\n\t}\n\t\n\tpublic int tier() {\n\t\tArmor armor = belongings.armor();\n\t\tif (armor instanceof ClassArmor){\n\t\t\treturn 6;\n\t\t} else if (armor != null){\n\t\t\treturn armor.tier;\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tpublic boolean shoot( Char enemy, MissileWeapon wep ) {\n\n\t\tthis.enemy = enemy;\n\t\tboolean wasEnemy = enemy.alignment == Alignment.ENEMY\n\t\t\t\t|| (enemy instanceof Mimic && enemy.alignment == Alignment.NEUTRAL);\n\n\t\t//temporarily set the hero's weapon to the missile weapon being used\n\t\t//TODO improve this!\n\t\tbelongings.thrownWeapon = wep;\n\t\tboolean hit = attack( enemy );\n\t\tInvisibility.dispel();\n\t\tbelongings.thrownWeapon = null;\n\n\t\tif (hit && subClass == HeroSubClass.GLADIATOR && wasEnemy){\n\t\t\tBuff.affect( this, Combo.class ).hit( enemy );\n\t\t}\n\n\t\tif (hit && heroClass == HeroClass.DUELIST && wasEnemy){\n\t\t\tBuff.affect( this, Sai.ComboStrikeTracker.class).addHit();\n\t\t}\n\n\t\treturn hit;\n\t}\n\t\n\t@Override\n\tpublic int attackSkill( Char target ) {\n\t\tKindOfWeapon wep = belongings.attackingWeapon();\n\t\t\n\t\tfloat accuracy = 1;\n\t\taccuracy *= RingOfAccuracy.accuracyMultiplier( this );\n\n\t\tif (Dungeon.isChallenged(Challenges.SUPERMAN)) {\n\t\t\taccuracy *= 2;\n\t\t}\n\t\t\n\t\tif (wep instanceof MissileWeapon && !(wep instanceof Gun.Bullet)){ //총탄을 제외한 투척 무기의 정확성\n\t\t\tif (Dungeon.level.adjacent( pos, target.pos )) {\n\t\t\t\taccuracy *= (0.5f + 0.2f*pointsInTalent(Talent.POINT_BLANK));\n\t\t\t} else {\n\t\t\t\taccuracy *= 1.5f;\n\t\t\t}\n\t\t}\n\n\t\tif (wep instanceof Gun.Bullet) {\t//총탄의 정확성\n\t\t\tif (Dungeon.level.adjacent( pos, target.pos )) {\n\t\t\t\tif (wep instanceof SG.SGBullet) {\n\t\t\t\t\taccuracy *= 10f; //산탄총은 기본적으로 0.2배의 명중률 보정이 있으며, 이를 10배함으로써 2배의 명중률을 가짐\n\t\t\t\t} else {\n\t\t\t\t\taccuracy *= (0.5f + 0.2f*pointsInTalent(Talent.POINT_BLANK));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hero.hasTalent(Talent.INEVITABLE_DEATH) && hero.buff(RouletteOfDeath.class) != null && hero.buff(RouletteOfDeath.class).timeToDeath()) {\n\t\t\t\taccuracy *= 1 + hero.pointsInTalent(Talent.INEVITABLE_DEATH);\n\t\t\t}\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.GUNSLINGER && hero.justMoved && wep instanceof MissileWeapon) {\n\t\t\taccuracy *= 0.25f*(1+0.5f*hero.pointsInTalent(Talent.MOVING_SHOT));\n\t\t}\n\n\t\tif (buff(Scimitar.SwordDance.class) != null){\n\t\t\taccuracy *= 1.25f;\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.ACC_ENHANCE)) {\n\t\t\taccuracy *= 1 + 0.05f * hero.pointsInTalent(Talent.ACC_ENHANCE);\n\t\t}\n\n\t\tif (hero.buff(LargeSword.LargeSwordBuff.class) != null) {\n\t\t\taccuracy *= hero.buff(LargeSword.LargeSwordBuff.class).getAccuracyFactor();\n\t\t}\n\n\t\tif (hero.buff(UnholyBible.Demon.class) != null) {\n\t\t\taccuracy = INFINITE_ACCURACY;\n\t\t}\n\n\t\tif (hero.buff(MeleeWeapon.DashAttack.class) != null) {\n\t\t\taccuracy = INFINITE_ACCURACY;\n\t\t}\n\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\treturn (int)(attackSkill * accuracy * wep.accuracyFactor( this, target ));\n\t\t} else {\n\t\t\treturn (int)(attackSkill * accuracy);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic int defenseSkill( Char enemy ) {\n\n\t\tif (buff(Combo.ParryTracker.class) != null){\n\t\t\tif (canAttack(enemy) && !isCharmedBy(enemy)){\n\t\t\t\tBuff.affect(this, Combo.RiposteTracker.class).enemy = enemy;\n\t\t\t}\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\n\t\tif (buff(RoundShield.GuardTracker.class) != null){\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\n\t\tif (buff(Talent.ParryTracker.class) != null){\n\t\t\tif (canAttack(enemy) && !isCharmedBy(enemy)){\n\t\t\t\tBuff.affect(this, Talent.RiposteTracker.class).enemy = enemy;\n\t\t\t}\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\n\t\tif (buff(Nunchaku.ParryTracker.class) != null){\n\t\t\tif (canAttack(enemy) && !isCharmedBy(enemy)){\n\t\t\t\tBuff.affect(this, Nunchaku.RiposteTracker.class).enemy = enemy;\n\t\t\t}\n\t\t\treturn INFINITE_EVASION;\n\t\t}\n\t\t\n\t\tfloat evasion = defenseSkill;\n\t\t\n\t\tevasion *= RingOfEvasion.evasionMultiplier( this );\n\n\t\tif (hero.hasTalent(Talent.SWIFT_MOVEMENT)) {\n\t\t\tevasion += hero.STR()-10;\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.SUPERMAN)) {\n\t\t\tevasion *= 3;\n\t\t}\n\n\t\tif (buff(Talent.RestoredAgilityTracker.class) != null){\n\t\t\tif (pointsInTalent(Talent.LIQUID_AGILITY) == 1){\n\t\t\t\tevasion *= 4f;\n\t\t\t} else if (pointsInTalent(Talent.LIQUID_AGILITY) == 2){\n\t\t\t\treturn INFINITE_EVASION;\n\t\t\t}\n\t\t}\n\n\t\tif (buff(Quarterstaff.DefensiveStance.class) != null){\n\t\t\tevasion *= 3;\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.EVA_ENHANCE)) {\n\t\t\tevasion *= 1 + 0.05f * hero.pointsInTalent(Talent.EVA_ENHANCE);\n\t\t}\n\n\t\tif (hero.buff(UnholyBible.Demon.class) != null) {\n\t\t\tevasion /= 2;\n\t\t}\n\t\t\n\t\tif (paralysed > 0) {\n\t\t\tevasion /= 2;\n\t\t}\n\n\t\tif (belongings.armor() != null) {\n\t\t\tevasion = belongings.armor().evasionFactor(this, evasion);\n\t\t}\n\n\t\treturn Math.round(evasion);\n\t}\n\n\t@Override\n\tpublic String defenseVerb() {\n\t\tCombo.ParryTracker parry = buff(Combo.ParryTracker.class);\n\t\tif (parry != null){\n\t\t\tparry.parried = true;\n\t\t\tif (buff(Combo.class).getComboCount() < 9 || pointsInTalent(Talent.ENHANCED_COMBO) < 2){\n\t\t\t\tparry.detach();\n\t\t\t}\n\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t}\n\n\t\tif (buff(RoundShield.GuardTracker.class) != null){\n\t\t\tbuff(RoundShield.GuardTracker.class).detach();\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1, Random.Float(0.96f, 1.05f));\n\t\t\treturn Messages.get(RoundShield.GuardTracker.class, \"guarded\");\n\t\t}\n\n\t\tif (buff(MonkEnergy.MonkAbility.Focus.FocusActivation.class) != null){\n\t\t\tbuff(MonkEnergy.MonkAbility.Focus.FocusActivation.class).detach();\n\t\t\tif (sprite != null && sprite.visible) {\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1, Random.Float(0.96f, 1.05f));\n\t\t\t}\n\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t}\n\n\t\tTalent.ParryTracker parryTracker = buff(Talent.ParryTracker.class);\n\t\tif (hasTalent(Talent.PARRY)) {\n\t\t\tif (parryTracker != null) {\n\t\t\t\tparryTracker.detach();\n\t\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t\t}\n\t\t}\n\n\t\tNunchaku.ParryTracker nunchakuParry = buff(Nunchaku.ParryTracker.class);\n\t\tif (nunchakuParry != null){\n\t\t\tnunchakuParry.parried = true;\n\t\t\tif (sprite != null && sprite.visible) {\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1, Random.Float(0.96f, 1.05f));\n\t\t\t}\n\t\t\treturn Messages.get(Monk.class, \"parried\");\n\t\t}\n\n\t\tRouletteOfDeath roulette = buff(RouletteOfDeath.class);\n\t\tif (hasTalent(Talent.HONORABLE_SHOT) && roulette != null && roulette.overHalf()) {\n\t\t\tBuff.prolong(hero, Talent.HonorableShotTracker.class, 1f);\n\t\t}\n\n\t\treturn super.defenseVerb();\n\t}\n\n\t@Override\n\tpublic int drRoll() {\n\t\tint dr = super.drRoll();\n\n\t\tif (belongings.armor() != null) {\n\t\t\tint armDr = Random.NormalIntRange( belongings.armor().DRMin(), belongings.armor().DRMax());\n\t\t\tif (STR() < belongings.armor().STRReq()){\n\t\t\t\tarmDr -= 2*(belongings.armor().STRReq() - STR());\n\t\t\t}\n\t\t\tif (armDr > 0) dr += armDr;\n\t\t}\n\t\tif (belongings.weapon() != null && !RingOfForce.fightingUnarmed(this)) {\n\t\t\tint wepDr = Random.NormalIntRange( 0 , belongings.weapon().defenseFactor( this ) );\n\t\t\tif (STR() < ((Weapon)belongings.weapon()).STRReq()){\n\t\t\t\twepDr -= 2*(((Weapon)belongings.weapon()).STRReq() - STR());\n\t\t\t}\n\t\t\tif (wepDr > 0) dr += wepDr;\n\t\t}\n\n\t\tif (buff(HoldFast.class) != null){\n\t\t\tdr += buff(HoldFast.class).armorBonus();\n\t\t}\n\n\t\tReinforcedArmor.ReinforcedArmorTracker rearmor = hero.buff(ReinforcedArmor.ReinforcedArmorTracker.class);\n\t\tif (rearmor != null) dr += rearmor.blockingRoll();\n\t\t\n\t\treturn dr;\n\t}\n\t\n\t@Override\n\tpublic int damageRoll() {\n\t\tKindOfWeapon wep = belongings.attackingWeapon();\n\t\tint dmg;\n\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\tdmg = wep.damageRoll( this );\n\n\t\t\tif (!(wep instanceof MissileWeapon)) dmg += RingOfForce.armedDamageBonus(this);\n\t\t} else {\n\t\t\tdmg = RingOfForce.damageRoll(this);\n\t\t\tif (RingOfForce.unarmedGetsWeaponAugment(this)){\n\t\t\t\tdmg = ((Weapon)belongings.attackingWeapon()).augment.damageFactor(dmg);\n\t\t\t}\n\t\t}\n\n\t\tPhysicalEmpower emp = buff(PhysicalEmpower.class);\n\t\tif (emp != null){\n\t\t\tdmg += emp.dmgBoost;\n\t\t\temp.left--;\n\t\t\tif (emp.left <= 0) {\n\t\t\t\temp.detach();\n\t\t\t}\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG, 0.75f, 1.2f);\n\t\t}\n\n\t\tif (heroClass != HeroClass.DUELIST\n\t\t\t\t&& hasTalent(Talent.WEAPON_RECHARGING)\n\t\t\t\t&& (buff(Recharging.class) != null || buff(ArtifactRecharge.class) != null)){\n\t\t\tdmg = Math.round(dmg * 1.025f + (.025f*pointsInTalent(Talent.WEAPON_RECHARGING)));\n\t\t}\n\n\t\tif (dmg < 0) dmg = 0;\n\t\treturn dmg;\n\t}\n\t\n\t@Override\n\tpublic float speed() {\n\n\t\tfloat speed = super.speed();\n\n\t\tspeed *= RingOfHaste.speedMultiplier(this);\n\t\t\n\t\tif (belongings.armor() != null) {\n\t\t\tspeed = belongings.armor().speedFactor(this, speed);\n\t\t}\n\t\t\n\t\tMomentum momentum = buff(Momentum.class);\n\t\tif (momentum != null){\n\t\t\t((HeroSprite)sprite).sprint( momentum.freerunning() ? 1.5f : 1f );\n\t\t\tspeed *= momentum.speedMultiplier();\n\t\t} else {\n\t\t\t((HeroSprite)sprite).sprint( 1f );\n\t\t}\n\n\t\tNaturesPower.naturesPowerTracker natStrength = buff(NaturesPower.naturesPowerTracker.class);\n\t\tif (natStrength != null){\n\t\t\tspeed *= (2f + 0.25f*pointsInTalent(Talent.GROWING_POWER));\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.MOVESPEED_ENHANCE)) {\n\t\t\tspeed *= 1 + 0.1*hero.pointsInTalent(Talent.MOVESPEED_ENHANCE);\n\t\t}\n\n\t\tif (subClass == HeroSubClass.MONK && buff(MonkEnergy.class) != null && buff(MonkEnergy.class).harmonized(this)) {\n\t\t\tspeed *= 1.5f;\n\t\t}\n\n\t\tif (hero.buff(ReinforcedArmor.ReinforcedArmorTracker.class) != null && hero.hasTalent(Talent.PLATE_ADD)) {\n\t\t\tspeed *= (1 - hero.pointsInTalent(Talent.PLATE_ADD)/8f);\n\t\t}\n\n\t\tif (hero.buff(Riot.RiotTracker.class) != null && hero.hasTalent(Talent.HASTE_MOVE)) {\n\t\t\tspeed *= 1f + 0.25f * hero.pointsInTalent(Talent.HASTE_MOVE);\n\t\t}\n\n\t\tspeed = AscensionChallenge.modifyHeroSpeed(speed);\n\t\t\n\t\treturn speed;\n\t\t\n\t}\n\n\t@Override\n\tpublic boolean canSurpriseAttack(){\n\t\tKindOfWeapon w = belongings.attackingWeapon();\n\t\tif (!(w instanceof Weapon)) return true;\n\t\tif (RingOfForce.fightingUnarmed(this)) return true;\n\t\tif (STR() < ((Weapon)w).STRReq()) return false;\n\t\tif (w instanceof Flail) return false;\n\t\tif (w instanceof ChainFlail) return false;\n\t\tif (w instanceof SG.SGBullet) return false;\n\n\t\treturn super.canSurpriseAttack();\n\t}\n\n\tpublic boolean canAttack(Char enemy){\n\t\tif (enemy == null || pos == enemy.pos || !Actor.chars().contains(enemy)) {\n\t\t\treturn false;\n\t\t}\n\n\t\t//can always attack adjacent enemies\n\t\tif (Dungeon.level.adjacent(pos, enemy.pos)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tKindOfWeapon wep = Dungeon.hero.belongings.attackingWeapon();\n\n\t\tif (wep != null){\n\t\t\treturn wep.canReach(this, enemy.pos);\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic float attackDelay() {\n\t\tif (buff(Talent.LethalMomentumTracker.class) != null){\n\t\t\tbuff(Talent.LethalMomentumTracker.class).detach();\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (buff(Talent.CounterAttackTracker.class) != null && hero.belongings.weapon == null) {\n\t\t\tbuff(Talent.CounterAttackTracker.class).detach();\n\t\t\treturn 0;\n\t\t}\n\n\t\tfloat delay = 1f;\n\n\t\tif ( buff(Adrenaline.class) != null) delay /= 1.5f;\n\n\t\tif (!RingOfForce.fightingUnarmed(this)) {\n\t\t\t\n\t\t\treturn delay * belongings.attackingWeapon().delayFactor( this );\n\t\t\t\n\t\t} else {\n\t\t\t//Normally putting furor speed on unarmed attacks would be unnecessary\n\t\t\t//But there's going to be that one guy who gets a furor+force ring combo\n\t\t\t//This is for that one guy, you shall get your fists of fury!\n\t\t\tfloat speed = RingOfFuror.attackSpeedMultiplier(this);\n\n\t\t\tif (hero.hasTalent(Talent.LESS_RESIST)) {\n\t\t\t\tint aEnc = hero.belongings.armor.STRReq() - hero.STR();\n\t\t\t\tif (aEnc < 0) {\n\t\t\t\t\tspeed *= 1 + 0.05f * hero.pointsInTalent(Talent.LESS_RESIST) * (-aEnc);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.QUICK_FOLLOWUP) && hero.buff(Talent.QuickFollowupTracker.class) != null) {\n\t\t\t\tspeed *= 1+hero.pointsInTalent(Talent.QUICK_FOLLOWUP)/3f;\n\t\t\t}\n\n\t\t\tif (hero.subClass == HeroSubClass.MONK && hero.buff(MonkEnergy.class) != null && hero.buff(MonkEnergy.class).harmonized(hero)) {\n\t\t\t\tspeed *= 1.5f;\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.ATK_SPEED_ENHANCE)) {\n\t\t\t\tspeed *= 1 + 0.05f * hero.pointsInTalent(Talent.ATK_SPEED_ENHANCE);\n\t\t\t}\n\n\t\t\t//ditto for furor + sword dance!\n\t\t\tif (buff(Scimitar.SwordDance.class) != null){\n\t\t\t\tspeed += 0.6f;\n\t\t\t}\n\n\t\t\t//and augments + brawler's stance! My goodness, so many options now compared to 2014!\n\t\t\tif (RingOfForce.unarmedGetsWeaponAugment(this)){\n\t\t\t\tdelay = ((Weapon)belongings.weapon).augment.delayFactor(delay);\n\t\t\t}\n\n\t\t\treturn delay/speed;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void spend( float time ) {\n\t\tsuper.spend(time);\n\t}\n\n\t@Override\n\tpublic void spendConstant(float time) {\n\t\tjustMoved = false;\n\t\tsuper.spendConstant(time);\n\t}\n\n\tpublic void spendAndNextConstant(float time ) {\n\t\tbusy();\n\t\tspendConstant( time );\n\t\tnext();\n\t}\n\n\tpublic void spendAndNext( float time ) {\n\t\tbusy();\n\t\tspend( time );\n\t\tnext();\n\t}\n\t\n\t@Override\n\tpublic boolean act() {\n\t\t\n\t\t//calls to dungeon.observe will also update hero's local FOV.\n\t\tfieldOfView = Dungeon.level.heroFOV;\n\n\t\tif (buff(Endure.EndureTracker.class) != null){\n\t\t\tbuff(Endure.EndureTracker.class).endEnduring();\n\t\t}\n\t\t\n\t\tif (!ready) {\n\t\t\t//do a full observe (including fog update) if not resting.\n\t\t\tif (!resting || buff(MindVision.class) != null || buff(Awareness.class) != null) {\n\t\t\t\tDungeon.observe();\n\t\t\t} else {\n\t\t\t\t//otherwise just directly re-calculate FOV\n\t\t\t\tDungeon.level.updateFieldOfView(this, fieldOfView);\n\t\t\t}\n\t\t}\n\t\t\n\t\tcheckVisibleMobs();\n\t\tBuffIndicator.refreshHero();\n\t\tBuffIndicator.refreshBoss();\n\t\t\n\t\tif (paralysed > 0) {\n\t\t\t\n\t\t\tcurAction = null;\n\t\t\t\n\t\t\tspendAndNext( TICK );\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tboolean actResult;\n\t\tif (curAction == null) {\n\t\t\t\n\t\t\tif (resting) {\n\t\t\t\tspendConstant( TIME_TO_REST );\n\t\t\t\tnext();\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\t\t\t\n\t\t\tactResult = false;\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tresting = false;\n\t\t\t\n\t\t\tready = false;\n\t\t\t\n\t\t\tif (curAction instanceof HeroAction.Move) {\n\t\t\t\tactResult = actMove( (HeroAction.Move)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Interact) {\n\t\t\t\tactResult = actInteract( (HeroAction.Interact)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Buy) {\n\t\t\t\tactResult = actBuy( (HeroAction.Buy)curAction );\n\t\t\t\t\n\t\t\t}else if (curAction instanceof HeroAction.PickUp) {\n\t\t\t\tactResult = actPickUp( (HeroAction.PickUp)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.OpenChest) {\n\t\t\t\tactResult = actOpenChest( (HeroAction.OpenChest)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Unlock) {\n\t\t\t\tactResult = actUnlock((HeroAction.Unlock) curAction);\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Mine) {\n\t\t\t\tactResult = actMine( (HeroAction.Mine)curAction );\n\n\t\t\t}else if (curAction instanceof HeroAction.LvlTransition) {\n\t\t\t\tactResult = actTransition( (HeroAction.LvlTransition)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Attack) {\n\t\t\t\tactResult = actAttack( (HeroAction.Attack)curAction );\n\t\t\t\t\n\t\t\t} else if (curAction instanceof HeroAction.Alchemy) {\n\t\t\t\tactResult = actAlchemy( (HeroAction.Alchemy)curAction );\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tactResult = false;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(hasTalent(Talent.BARKSKIN) && Dungeon.level.map[pos] == Terrain.FURROWED_GRASS){\n\t\t\tBarkskin.conditionallyAppend(this, (lvl*pointsInTalent(Talent.BARKSKIN))/2, 1 );\n\t\t}\n\n\t\tif (hasTalent(Talent.PARRY) && buff(Talent.ParryCooldown.class) == null){\n\t\t\tBuff.affect(this, Talent.ParryTracker.class);\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.CURSED_DUNGEON) && hero.buff(GhostSpawner.class) == null) {\n\t\t\tBuff.affect(hero, GhostSpawner.class);\n\t\t}\n\t\t\n\t\treturn actResult;\n\t}\n\t\n\tpublic void busy() {\n\t\tready = false;\n\t}\n\t\n\tprivate void ready() {\n\t\tif (sprite.looping()) sprite.idle();\n\t\tcurAction = null;\n\t\tdamageInterrupt = true;\n\t\twaitOrPickup = false;\n\t\tready = true;\n\t\tcanSelfTrample = true;\n\n\t\tAttackIndicator.updateState();\n\t\t\n\t\tGameScene.ready();\n\t}\n\t\n\tpublic void interrupt() {\n\t\tif (isAlive() && curAction != null &&\n\t\t\t((curAction instanceof HeroAction.Move && curAction.dst != pos) ||\n\t\t\t(curAction instanceof HeroAction.LvlTransition))) {\n\t\t\tlastAction = curAction;\n\t\t}\n\t\tcurAction = null;\n\t\tGameScene.resetKeyHold();\n\t}\n\t\n\tpublic void resume() {\n\t\tcurAction = lastAction;\n\t\tlastAction = null;\n\t\tdamageInterrupt = false;\n\t\tnext();\n\t}\n\n\tprivate boolean canSelfTrample = false;\n\tpublic boolean canSelfTrample(){\n\t\treturn canSelfTrample && !rooted && !flying &&\n\t\t\t\t//standing in high grass\n\t\t\t\t(Dungeon.level.map[pos] == Terrain.HIGH_GRASS ||\n\t\t\t\t//standing in furrowed grass and not huntress\n\t\t\t\t((heroClass != HeroClass.HUNTRESS && hero.subClass != HeroSubClass.SPECIALIST) && Dungeon.level.map[pos] == Terrain.FURROWED_GRASS) ||\n\t\t\t\t//standing on a plant\n\t\t\t\tDungeon.level.plants.get(pos) != null);\n\t}\n\t\n\tprivate boolean actMove( HeroAction.Move action ) {\n\n\t\tif (getCloser( action.dst )) {\n\t\t\tcanSelfTrample = false;\n\t\t\treturn true;\n\n\t\t//Hero moves in place if there is grass to trample\n\t\t} else if (pos == action.dst && canSelfTrample()){\n\t\t\tcanSelfTrample = false;\n\t\t\tDungeon.level.pressCell(pos);\n\t\t\tspendAndNext( 1 / speed() );\n\t\t\treturn false;\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actInteract( HeroAction.Interact action ) {\n\t\t\n\t\tChar ch = action.ch;\n\n\t\tif (ch.isAlive() && ch.canInteract(this)) {\n\t\t\t\n\t\t\tready();\n\t\t\tsprite.turnTo( pos, ch.pos );\n\t\t\treturn ch.interact(this);\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tif (fieldOfView[ch.pos] && getCloser( ch.pos )) {\n\n\t\t\t\treturn true;\n\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\t\n\tprivate boolean actBuy( HeroAction.Buy action ) {\n\t\tint dst = action.dst;\n\t\tif (pos == dst) {\n\n\t\t\tready();\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( dst );\n\t\t\tif (heap != null && heap.type == Type.FOR_SALE && heap.size() == 1) {\n\t\t\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\tGameScene.show( new WndTradeItem( heap ) );\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate boolean actAlchemy( HeroAction.Alchemy action ) {\n\t\tint dst = action.dst;\n\t\tif (Dungeon.level.distance(dst, pos) <= 1) {\n\n\t\t\tready();\n\t\t\t\n\t\t\tAlchemistsToolkit.kitEnergy kit = buff(AlchemistsToolkit.kitEnergy.class);\n\t\t\tif (kit != null && kit.isCursed()){\n\t\t\t\tGLog.w( Messages.get(AlchemistsToolkit.class, \"cursed\"));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tAlchemyScene.clearToolkit();\n\t\t\tShatteredPixelDungeon.switchScene(AlchemyScene.class);\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t//used to keep track if the wait/pickup action was used\n\t// so that the hero spends a turn even if the fail to pick up an item\n\tpublic boolean waitOrPickup = false;\n\n\tprivate boolean actPickUp( HeroAction.PickUp action ) {\n\t\tint dst = action.dst;\n\t\tif (pos == dst) {\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( pos );\n\t\t\tif (heap != null) {\n\t\t\t\tItem item = heap.peek();\n\t\t\t\tif (item.doPickUp( this )) {\n\t\t\t\t\theap.pickUp();\n\n\t\t\t\t\tif (item instanceof Dewdrop\n\t\t\t\t\t\t\t|| item instanceof TimekeepersHourglass.sandBag\n\t\t\t\t\t\t\t|| item instanceof DriedRose.Petal\n\t\t\t\t\t\t\t|| item instanceof Key\n\t\t\t\t\t\t\t|| item instanceof Guidebook) {\n\t\t\t\t\t\t//Do Nothing\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t//TODO make all unique items important? or just POS / SOU?\n\t\t\t\t\t\tboolean important = item.unique && item.isIdentified() &&\n\t\t\t\t\t\t\t\t(item instanceof Scroll || item instanceof Potion);\n\t\t\t\t\t\tif (important) {\n\t\t\t\t\t\t\tGLog.p( Messages.capitalize(Messages.get(this, \"you_now_have\", item.name())) );\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tGLog.i( Messages.capitalize(Messages.get(this, \"you_now_have\", item.name())) );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tcurAction = null;\n\t\t\t\t} else {\n\n\t\t\t\t\tif (waitOrPickup) {\n\t\t\t\t\t\tspendAndNextConstant(TIME_TO_REST);\n\t\t\t\t\t}\n\n\t\t\t\t\t//allow the hero to move between levels even if they can't collect the item\n\t\t\t\t\tif (Dungeon.level.getTransition(pos) != null){\n\t\t\t\t\t\tthrowItems();\n\t\t\t\t\t} else {\n\t\t\t\t\t\theap.sprite.drop();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (item instanceof Dewdrop\n\t\t\t\t\t\t\t|| item instanceof TimekeepersHourglass.sandBag\n\t\t\t\t\t\t\t|| item instanceof DriedRose.Petal\n\t\t\t\t\t\t\t|| item instanceof Key) {\n\t\t\t\t\t\t//Do Nothing\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGLog.newLine();\n\t\t\t\t\t\tGLog.n(Messages.capitalize(Messages.get(this, \"you_cant_have\", item.name())));\n\t\t\t\t\t}\n\n\t\t\t\t\tready();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actOpenChest( HeroAction.OpenChest action ) {\n\t\tint dst = action.dst;\n\t\tif (Dungeon.level.adjacent( pos, dst ) || pos == dst) {\n\t\t\tpath = null;\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( dst );\n\t\t\tif (heap != null && (heap.type != Type.HEAP && heap.type != Type.FOR_SALE)) {\n\t\t\t\t\n\t\t\t\tif ((heap.type == Type.LOCKED_CHEST && Notes.keyCount(new GoldenKey(Dungeon.depth)) < 1)\n\t\t\t\t\t|| (heap.type == Type.CRYSTAL_CHEST && Notes.keyCount(new CrystalKey(Dungeon.depth)) < 1)){\n\n\t\t\t\t\t\tGLog.w( Messages.get(this, \"locked_chest\") );\n\t\t\t\t\t\tready();\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tswitch (heap.type) {\n\t\t\t\tcase TOMB:\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.TOMB );\n\t\t\t\t\tPixelScene.shake( 1, 0.5f );\n\t\t\t\t\tbreak;\n\t\t\t\tcase SKELETON:\n\t\t\t\tcase REMAINS:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.UNLOCK );\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tsprite.operate( dst );\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actUnlock( HeroAction.Unlock action ) {\n\t\tint doorCell = action.dst;\n\t\tif (Dungeon.level.adjacent( pos, doorCell )) {\n\t\t\tpath = null;\n\t\t\t\n\t\t\tboolean hasKey = false;\n\t\t\tint door = Dungeon.level.map[doorCell];\n\t\t\t\n\t\t\tif (door == Terrain.LOCKED_DOOR\n\t\t\t\t\t&& Notes.keyCount(new IronKey(Dungeon.depth)) > 0) {\n\t\t\t\t\n\t\t\t\thasKey = true;\n\t\t\t\t\n\t\t\t} else if (door == Terrain.CRYSTAL_DOOR\n\t\t\t\t\t&& Notes.keyCount(new CrystalKey(Dungeon.depth, Dungeon.branch)) > 0) {\n\n\t\t\t\thasKey = true;\n\n\t\t\t} else if (door == Terrain.LOCKED_EXIT\n\t\t\t\t\t&& Notes.keyCount(new SkeletonKey(Dungeon.depth)) > 0) {\n\n\t\t\t\thasKey = true;\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tif (hasKey) {\n\t\t\t\t\n\t\t\t\tsprite.operate( doorCell );\n\t\t\t\t\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.UNLOCK );\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tGLog.w( Messages.get(this, \"locked_door\") );\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( doorCell )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic boolean actMine(HeroAction.Mine action){\n\t\tif (Dungeon.level.adjacent(pos, action.dst)){\n\t\t\tpath = null;\n\t\t\tif ((Dungeon.level.map[action.dst] == Terrain.WALL\n\t\t\t\t\t|| Dungeon.level.map[action.dst] == Terrain.WALL_DECO\n\t\t\t\t\t|| Dungeon.level.map[action.dst] == Terrain.MINE_CRYSTAL\n\t\t\t\t\t|| Dungeon.level.map[action.dst] == Terrain.MINE_BOULDER)\n\t\t\t\t&& Dungeon.level.insideMap(action.dst)){\n\t\t\t\tsprite.attack(action.dst, new Callback() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void call() {\n\n\t\t\t\t\t\tboolean crystalAdjacent = false;\n\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS8) {\n\t\t\t\t\t\t\tif (Dungeon.level.map[action.dst + i] == Terrain.MINE_CRYSTAL){\n\t\t\t\t\t\t\t\tcrystalAdjacent = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//1 hunger spent total\n\t\t\t\t\t\tif (Dungeon.level.map[action.dst] == Terrain.WALL_DECO){\n\t\t\t\t\t\t\tDarkGold gold = new DarkGold();\n\t\t\t\t\t\t\tif (gold.doPickUp( Dungeon.hero )) {\n\t\t\t\t\t\t\t\tDarkGold existing = Dungeon.hero.belongings.getItem(DarkGold.class);\n\t\t\t\t\t\t\t\tif (existing != null && existing.quantity()%5 == 0){\n\t\t\t\t\t\t\t\t\tif (existing.quantity() >= 40) {\n\t\t\t\t\t\t\t\t\t\tGLog.p(Messages.get(DarkGold.class, \"you_now_have\", existing.quantity()));\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tGLog.i(Messages.get(DarkGold.class, \"you_now_have\", existing.quantity()));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tspend(-Actor.TICK); //picking up the gold doesn't spend a turn here\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tDungeon.level.drop( gold, pos ).sprite.drop();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tPixelScene.shake(0.5f, 0.5f);\n\t\t\t\t\t\t\tCellEmitter.center( action.dst ).burst( Speck.factory( Speck.STAR ), 7 );\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.EVOKE );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY_DECO );\n\n\t\t\t\t\t\t\t//mining gold doesn't break crystals\n\t\t\t\t\t\t\tcrystalAdjacent = false;\n\n\t\t\t\t\t\t//4 hunger spent total\n\t\t\t\t\t\t} else if (Dungeon.level.map[action.dst] == Terrain.WALL){\n\t\t\t\t\t\t\tbuff(Hunger.class).affectHunger(-3);\n\t\t\t\t\t\t\tPixelScene.shake(0.5f, 0.5f);\n\t\t\t\t\t\t\tCellEmitter.get( action.dst ).burst( Speck.factory( Speck.ROCK ), 2 );\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.MINE );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY_DECO );\n\n\t\t\t\t\t\t//1 hunger spent total\n\t\t\t\t\t\t} else if (Dungeon.level.map[action.dst] == Terrain.MINE_CRYSTAL){\n\t\t\t\t\t\t\tSplash.at(action.dst, 0xFFFFFF, 5);\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.SHATTER );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY );\n\n\t\t\t\t\t\t//1 hunger spent total\n\t\t\t\t\t\t} else if (Dungeon.level.map[action.dst] == Terrain.MINE_BOULDER){\n\t\t\t\t\t\t\tSplash.at(action.dst, ColorMath.random( 0x444444, 0x777766 ), 5);\n\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.MINE, 0.6f );\n\t\t\t\t\t\t\tLevel.set( action.dst, Terrain.EMPTY );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\t\tDungeon.level.discoverable[action.dst + i] = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\t\tGameScene.updateMap( action.dst+i );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (crystalAdjacent){\n\t\t\t\t\t\t\tsprite.parent.add(new Delayer(0.2f){\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tprotected void onComplete() {\n\t\t\t\t\t\t\t\t\tboolean broke = false;\n\t\t\t\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS8) {\n\t\t\t\t\t\t\t\t\t\tif (Dungeon.level.map[action.dst+i] == Terrain.MINE_CRYSTAL){\n\t\t\t\t\t\t\t\t\t\t\tSplash.at(action.dst+i, 0xFFFFFF, 5);\n\t\t\t\t\t\t\t\t\t\t\tLevel.set( action.dst+i, Terrain.EMPTY );\n\t\t\t\t\t\t\t\t\t\t\tbroke = true;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (broke){\n\t\t\t\t\t\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.SHATTER );\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS9) {\n\t\t\t\t\t\t\t\t\t\tGameScene.updateMap( action.dst+i );\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tspendAndNext(TICK);\n\t\t\t\t\t\t\t\t\tready();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tspendAndNext(TICK);\n\t\t\t\t\t\t\tready();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tDungeon.observe();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\t\t\treturn false;\n\t\t} else if (getCloser( action.dst )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actTransition(HeroAction.LvlTransition action ) {\n\t\tint stairs = action.dst;\n\t\tLevelTransition transition = Dungeon.level.getTransition(stairs);\n\n\t\tif (rooted) {\n\t\t\tPixelScene.shake(1, 1f);\n\t\t\tready();\n\t\t\treturn false;\n\n\t\t} else if (!Dungeon.level.locked && transition != null && transition.inside(pos)) {\n\n\t\t\tif (Dungeon.level.activateTransition(this, transition)){\n\t\t\t\tcurAction = null;\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (getCloser( stairs )) {\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\tready();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate boolean actAttack( HeroAction.Attack action ) {\n\n\t\tenemy = action.target;\n\n\t\tif (enemy.isAlive() && canAttack( enemy ) && !isCharmedBy( enemy ) && enemy.invisible == 0) {\n\n\t\t\tif (heroClass != HeroClass.DUELIST\n\t\t\t\t\t&& hasTalent(Talent.AGGRESSIVE_BARRIER)\n\t\t\t\t\t&& buff(Talent.AggressiveBarrierCooldown.class) == null\n\t\t\t\t\t&& (HP / (float)HT) < 0.20f*(1+pointsInTalent(Talent.AGGRESSIVE_BARRIER))){\n\t\t\t\tBuff.affect(this, Barrier.class).setShield(3);\n\t\t\t\tBuff.affect(this, Talent.AggressiveBarrierCooldown.class, 50f);\n\t\t\t}\n\t\t\tsprite.attack( enemy.pos );\n\n\t\t\treturn false;\n\n\t\t} else {\n\n\t\t\tif (fieldOfView[enemy.pos] && getCloser( enemy.pos )) {\n\n\t\t\t\treturn true;\n\n\t\t\t} else {\n\t\t\t\tready();\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t}\n\t}\n\n\tpublic Char enemy(){\n\t\treturn enemy;\n\t}\n\t\n\tpublic void rest( boolean fullRest ) {\n\t\tspendAndNextConstant( TIME_TO_REST );\n\t\tif (hasTalent(Talent.HOLD_FAST)){\n\t\t\tBuff.affect(this, HoldFast.class).pos = pos;\n\t\t}\n\t\tif (hasTalent(Talent.PATIENT_STRIKE)){\n\t\t\tBuff.affect(Dungeon.hero, Talent.PatientStrikeTracker.class).pos = Dungeon.hero.pos;\n\t\t}\n\t\tif (!fullRest) {\n\t\t\tif (sprite != null) {\n\t\t\t\tsprite.showStatus(CharSprite.DEFAULT, Messages.get(this, \"wait\"));\n\t\t\t}\n\n\t\t\tif (belongings.weapon instanceof LargeSword || belongings.secondWep instanceof LargeSword){\n\t\t\t\tBuff.affect(this, LargeSword.LargeSwordBuff.class).setDamageFactor(belongings.weapon.buffedLvl(), (belongings.secondWep instanceof LargeSword));\n\t\t\t\tif (hero.sprite != null) {\n\t\t\t\t\tEmitter e = hero.sprite.centerEmitter();\n\t\t\t\t\tif (e != null) e.burst(EnergyParticle.FACTORY, 15);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Dungeon.hero.subClass == HeroSubClass.CHASER\n\t\t\t\t\t&& hero.buff(Talent.ChaseCooldown.class) == null\n\t\t\t\t\t&& hero.buff(Invisibility.class) == null\n\t\t\t\t\t&& hero.buff(CloakOfShadows.cloakStealth.class) == null ) {\n\t\t\t\tif (hero.hasTalent(Talent.MASTER_OF_CLOAKING)) {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Invisibility.class, 6f);\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Invisibility.class, 5f);\n\t\t\t\t}\n\t\t\t\tif (hero.pointsInTalent(Talent.MASTER_OF_CLOAKING) > 1) {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.ChaseCooldown.class, 10f);\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.ChaseCooldown.class, 15f);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Dungeon.level.map[pos] == Terrain.FURROWED_GRASS && hero.subClass == HeroSubClass.SPECIALIST) {\n\t\t\t\tboolean adjacentMob = false;\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] )) {\n\t\t\t\t\tif (level.adjacent(hero.pos, mob.pos)) {\n\t\t\t\t\t\tadjacentMob = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (hero.pointsInTalent(Talent.STEALTH_MASTER) > 1) {\n\t\t\t\t\tadjacentMob = false;\n\t\t\t\t}\n\t\t\t\tif (!adjacentMob && hero.hasTalent(Talent.INTO_THE_SHADOW) && hero.buff(Talent.IntoTheShadowCooldown.class) == null) {\n\t\t\t\t\tBuff.affect(this, Invisibility.class, 3f*hero.pointsInTalent(Talent.INTO_THE_SHADOW));\n\t\t\t\t\tBuff.affect(this, Talent.IntoTheShadowCooldown.class, 15);\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(this, Cloaking.class);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresting = fullRest;\n\t}\n\t\n\t@Override\n\tpublic int attackProc( final Char enemy, int damage ) {\n\t\tdamage = super.attackProc( enemy, damage );\n\n\t\tKindOfWeapon wep;\n\t\tif (RingOfForce.fightingUnarmed(this) && !RingOfForce.unarmedGetsWeaponEnchantment(this)){\n\t\t\twep = null;\n\t\t} else {\n\t\t\twep = belongings.attackingWeapon();\n\t\t}\n\n\t\tif (hero.buff(MeleeWeapon.DashAttack.class) != null) {\n\t\t\tdamage *= hero.buff(MeleeWeapon.DashAttack.class).getDmgMulti();\n\t\t\thero.buff(MeleeWeapon.DashAttack.class).detach();\n\t\t}\n\n\t\tif (wep != null) damage = wep.proc( this, enemy, damage );\n\n\t\tdamage = Talent.onAttackProc( this, enemy, damage );\n\t\t\n\t\tswitch (subClass) {\n\t\t\tcase SNIPER:\n\t\t\t\tif (wep instanceof MissileWeapon && !(wep instanceof SpiritBow.SpiritArrow) && enemy != this) {\n\t\t\t\t\tActor.add(new Actor() {\n\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tactPriority = VFX_PRIO;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tprotected boolean act() {\n\t\t\t\t\t\t\tif (enemy.isAlive()) {\n\t\t\t\t\t\t\t\tint bonusTurns = hasTalent(Talent.SHARED_UPGRADES) ? wep.buffedLvl() : 0;\n\t\t\t\t\t\t\t\tBuff.prolong(Hero.this, SnipersMark.class, SnipersMark.DURATION + bonusTurns).set(enemy.id(), bonusTurns);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tActor.remove(this);\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (hero.hasTalent(Talent.KICK)\n\t\t\t\t\t\t&& enemy.buff(PinCushion.class) != null\n\t\t\t\t\t\t&& level.adjacent(hero.pos, enemy.pos)\n\t\t\t\t\t\t&& hero.buff(Talent.KickCooldown.class) == null) {\n\t\t\t\t\tItem item = enemy.buff(PinCushion.class).grabOne();\n\t\t\t\t\tif (item.doPickUp(hero, enemy.pos)){\n\t\t\t\t\t\thero.spend(-1); //attacking enemy already takes a turn\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGLog.w(Messages.get(this, \"cant_grab\"));\n\t\t\t\t\t\tDungeon.level.drop(item, enemy.pos).sprite.drop();\n\t\t\t\t\t}\n\t\t\t\t\tBallistica trajectory = new Ballistica(hero.pos, enemy.pos, Ballistica.STOP_TARGET);\n\t\t\t\t\ttrajectory = new Ballistica(trajectory.collisionPos, trajectory.path.get(trajectory.path.size() - 1), Ballistica.PROJECTILE);\n\t\t\t\t\tint dist = hero.pointsInTalent(Talent.KICK);\n\t\t\t\t\tWandOfBlastWave.throwChar(enemy, trajectory, dist, true, false ,hero.getClass());\n\t\t\t\t\tBuff.affect(hero, Talent.KickCooldown.class, 10f);\n\t\t\t\t}\n\t\t\t\tif (wep instanceof MissileWeapon\n\t\t\t\t\t\t&& hero.hasTalent(Talent.SHOOTING_EYES)\n\t\t\t\t\t\t&& enemy.buff(Talent.ShootingEyesTracker.class) == null) {\n\t\t\t\t\tif (Random.Float() < hero.pointsInTalent(Talent.SHOOTING_EYES)/3f) {\n\t\t\t\t\t\tBuff.affect(enemy, Blindness.class, 2f);\n\t\t\t\t\t}\n\t\t\t\t\tBuff.affect(enemy, Talent.ShootingEyesTracker.class);\n\t\t\t\t}\n\t\t\t\tif (wep instanceof MissileWeapon\n\t\t\t\t\t\t&& hero.hasTalent(Talent.TARGET_SPOTTING)\n\t\t\t\t\t\t&& hero.buff(SnipersMark.class) != null\n\t\t\t\t\t\t&& hero.buff(SnipersMark.class).object == enemy.id()) {\n\t\t\t\t\tdamage *= 1+0.1f*hero.pointsInTalent(Talent.TARGET_SPOTTING);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase FIGHTER:\n\t\t\t\tif (wep == null && Random.Int(3) < hero.pointsInTalent(Talent.QUICK_STEP)) {\n\t\t\t\t\tBuff.prolong(hero, Talent.QuickStep.class, 1.0001f);\n\t\t\t\t}\n\t\t\t\tif (wep == null && hero.hasTalent(Talent.RING_KNUCKLE) && hero.buff(RingOfForce.Force.class) == null) {\n\t\t\t\t\tBuff.prolong(hero, EnhancedRingsCombo.class, (Dungeon.hero.pointsInTalent(Talent.RING_KNUCKLE) >= 2) ? 2f : 1f).hit();\n\t\t\t\t\thero.updateHT(false);\n\t\t\t\t\tupdateQuickslot();\n\t\t\t\t}\n\t\t\t\tif (wep == null && Random.Float() < hero.pointsInTalent(Talent.MYSTICAL_PUNCH)/3f) {\n\t\t\t\t\tif (hero.belongings.ring != null) {\n\t\t\t\t\t\tdamage *= Ring.onHit(hero, enemy, damage, Ring.ringTypes.get(hero.belongings.ring.getClass()));\n\t\t\t\t\t}\n\t\t\t\t\tif (hero.belongings.misc instanceof Ring) {\n\t\t\t\t\t\tdamage *= Ring.onHit(hero, enemy, damage, Ring.ringTypes.get(hero.belongings.misc.getClass()));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CHAMPION:\n\t\t\t\tif (hero.belongings.weapon != null && hero.belongings.secondWep != null\n\t\t\t\t\t\t&& hero.pointsInTalent(Talent.TWIN_SWORD) > 1\n\t\t\t\t\t\t&& hero.belongings.weapon.getClass() == hero.belongings.secondWep.getClass()) {\n\t\t\t\t\tKindOfWeapon other = hero.belongings.secondWep;\n\t\t\t\t\tif (hero.belongings.secondWep == wep) {\n\t\t\t\t\t\tother = hero.belongings.weapon;\n\t\t\t\t\t}\n\t\t\t\t\tdamage = other.proc( this, enemy, damage );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase VETERAN:\n\t\t\t\tif (level.adjacent(enemy.pos, pos) && hero.buff(Tackle.TackleTracker.class) == null) {\n\t\t\t\t\tActor.add(new Actor() {\n\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tactPriority = VFX_PRIO;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tprotected boolean act() {\n\t\t\t\t\t\t\tif (enemy.isAlive()) {\n\t\t\t\t\t\t\t\tBuff.prolong(Hero.this, Tackle.class, 1).set(enemy.id());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tActor.remove(this);\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OUTLAW:\n\t\t\t\tif (wep instanceof Gun.Bullet) {\n\t\t\t\t\tif (hero.hasTalent(Talent.HEADSHOT) && Random.Float() < 0.01f*hero.pointsInTalent(Talent.HEADSHOT)) {\n\t\t\t\t\t\tif (!Char.hasProp(enemy, Property.BOSS) && !Char.hasProp(enemy, Property.MINIBOSS)) {\n\t\t\t\t\t\t\tdamage = enemy.HP;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdamage *= 1.2f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemy.sprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\t\t}\n\n\t\t\t\t\tif (hero.buff(Talent.HonorableShotTracker.class) != null\n\t\t\t\t\t\t\t&& (enemy.HP/(float)enemy.HT) <= 0.4f*hero.pointsInTalent(Talent.HONORABLE_SHOT)/3f) {\n\t\t\t\t\t\tif (!Char.hasProp(enemy, Property.BOSS) && !Char.hasProp(enemy, Property.MINIBOSS)) {\n\t\t\t\t\t\t\tdamage = enemy.HP;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdamage *= 1.2f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemy.sprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\t\t\thero.buff(Talent.HonorableShotTracker.class).detach();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (hero.buff(RouletteOfDeath.class) == null || !hero.buff(RouletteOfDeath.class).timeToDeath()) {\n\t\t\t\t\t\tBuff.affect(this, RouletteOfDeath.class).hit();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (!Char.hasProp(enemy, Property.BOSS) && !Char.hasProp(enemy, Property.MINIBOSS)) {\n\t\t\t\t\t\t\tdamage = enemy.HP;\n\t\t\t\t\t\t\tif (hero.belongings.weapon instanceof Gun) {\n\t\t\t\t\t\t\t\t((Gun)hero.belongings.weapon).quickReload();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (hero.hasTalent(Talent.BULLET_TIME)) {\n\t\t\t\t\t\t\t\tfor (Char ch : Actor.chars()) {\n\t\t\t\t\t\t\t\t\tif (level.heroFOV[ch.pos]) {\n\t\t\t\t\t\t\t\t\t\tBuff.affect(ch, Slow.class, 4*hero.pointsInTalent(Talent.BULLET_TIME));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdamage *= 1.2f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemy.sprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\t\t\thero.buff(RouletteOfDeath.class).detach();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.WATER_FRIENDLY) && Dungeon.level.map[hero.pos] == Terrain.WATER) {\n\t\t\tdamage += Random.NormalIntRange(1, hero.pointsInTalent(Talent.WATER_FRIENDLY));\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t}\n\n\t\tif (hero.buff(Talent.SkilledHandTracker.class) != null) {\n\t\t\tdamage += 1+hero.pointsInTalent(Talent.SKILLED_HAND);\n\t\t\thero.buff(Talent.SkilledHandTracker.class).detach();\n\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t}\n\n\t\tif (Random.Float() < hero.pointsInTalent(Talent.MADNESS)/10f) {\n\t\t\tBuff.prolong(enemy, Amok.class, 3f);\n\t\t}\n\n\t\tSpellBook.SpellBookCoolDown spellBookCoolDown = buff(SpellBook.SpellBookCoolDown.class);\n\t\tif (hero.hasTalent(Talent.BRIG_BOOST) && spellBookCoolDown != null) {\n\t\t\tspellBookCoolDown.hit(hero.pointsInTalent(Talent.BRIG_BOOST));\n\t\t}\n\n\t\tif (hero.buff(Bible.Angel.class) != null) {\n\t\t\thero.heal(Math.max(Math.round(0.2f*damage), 1));\n\t\t}\n\n\t\tif (hero.buff(UnholyBible.Demon.class) != null) {\n\t\t\tdamage *= 1.33f;\n\t\t}\n\n\t\tif (hero.buff(DualDagger.ReverseBlade.class) != null) {\n\t\t\tdamage *= 0.5f;\n\t\t\tBuff.affect(enemy, Bleeding.class).add(Random.NormalIntRange(1, 3));\n\t\t\tif (enemy.sprite.visible) {\n\t\t\t\tSplash.at( enemy.sprite.center(), -PointF.PI / 2, PointF.PI / 6,\n\t\t\t\t\t\tenemy.sprite.blood(), Math.min( 10 * Random.NormalIntRange(1, 3) / enemy.HT, 10 ) );\n\t\t\t}\n\t\t}\n\n\t\tif (enemy instanceof Mob && ((Mob) enemy).surprisedBy(hero)) {\n\t\t\tif (hero.hasTalent(Talent.POISONOUS_BLADE)) {\n\t\t\t\tBuff.affect(enemy, Poison.class).set(2+hero.pointsInTalent(Talent.POISONOUS_BLADE));\n\t\t\t}\n\t\t\tif (hero.hasTalent(Talent.SOUL_COLLECT) && damage >= enemy.HP) {\n\t\t\t\tint healAmt = 3*hero.pointsInTalent(Talent.SOUL_COLLECT);\n\t\t\t\thealAmt = Math.min( healAmt, hero.HT - hero.HP );\n\t\t\t\tif (healAmt > 0 && hero.isAlive()) {\n\t\t\t\t\thero.HP += healAmt;\n\t\t\t\t\thero.sprite.emitter().start( Speck.factory( Speck.HEALING ), 0.4f, 2 );\n\t\t\t\t\thero.sprite.showStatus( CharSprite.POSITIVE, Integer.toString( healAmt ) );\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hero.hasTalent(Talent.TRAIL_TRACKING) && damage >= enemy.HP) {\n\t\t\t\tBuff.affect(hero, MindVision.class, hero.pointsInTalent(Talent.TRAIL_TRACKING));\n\t\t\t}\n\n\t\t\tif (hero.pointsInTalent(Talent.MASTER_OF_CLOAKING) == 3) {\n\t\t\t\tif (hero.buff(Talent.ChaseCooldown.class) != null) {\n\t\t\t\t\thero.buff(Talent.ChaseCooldown.class).spendTime();\n\t\t\t\t}\n\t\t\t\tif (hero.buff(Talent.ChainCooldown.class) != null) {\n\t\t\t\t\thero.buff(Talent.ChainCooldown.class).spendTime();\n\t\t\t\t}\n\t\t\t\tif (hero.buff(Talent.LethalCooldown.class) != null) {\n\t\t\t\t\thero.buff(Talent.LethalCooldown.class).spendTime();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.BAYONET) && hero.buff(ReinforcedArmor.ReinforcedArmorTracker.class) != null){\n\t\t\tif (wep instanceof Gun) {\n\t\t\t\tBuff.affect( enemy, Bleeding.class ).set( 4 + hero.pointsInTalent(Talent.BAYONET));\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.SUPERMAN)) {\n\t\t\tdamage *= 3f;\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.PYRO)) {\n\t\t\tBuff.affect(enemy, Burning.class).reignite(enemy, 8f);\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.FATIGUE)) {\n\t\t\tBuff.affect(this, Fatigue.class).hit(true);\n\t\t}\n\t\t\n\t\treturn damage;\n\t}\n\t\n\t@Override\n\tpublic int defenseProc( Char enemy, int damage ) {\n\t\t\n\t\tif (damage > 0 && subClass == HeroSubClass.BERSERKER){\n\t\t\tBerserk berserk = Buff.affect(this, Berserk.class);\n\t\t\tberserk.damage(damage);\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.GLADIATOR && Random.Float() < hero.pointsInTalent(Talent.OFFENSIVE_DEFENSE)/3f) {\n\t\t\tCombo combo = Buff.affect(this, Combo.class);\n\t\t\tcombo.hit(enemy);\n\t\t}\n\t\t\n\t\tif (belongings.armor() != null) {\n\t\t\tdamage = belongings.armor().proc( enemy, this, damage );\n\t\t}\n\n\t\tWandOfLivingEarth.RockArmor rockArmor = buff(WandOfLivingEarth.RockArmor.class);\n\t\tif (rockArmor != null) {\n\t\t\tdamage = rockArmor.absorb(damage);\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.EMERGENCY_ESCAPE) && Random.Float() < hero.pointsInTalent(Talent.EMERGENCY_ESCAPE)/50f) {\n\t\t\tBuff.prolong(this, Invisibility.class, 3f);\n\t\t}\n\n\t\tif (hero.hasTalent(Talent.OVERCOMING)) {\n\t\t\tMomentum momentum = buff(Momentum.class);\n\t\t\tif (momentum != null && momentum.freerunning()) {\n\t\t\t\tBuff.affect(this, Haste.class, 2f);\n\t\t\t\tif (hero.pointsInTalent(Talent.OVERCOMING) > 1) Buff.affect(this, Adrenaline.class, 2f);\n\t\t\t\tif (hero.pointsInTalent(Talent.OVERCOMING) > 2) Buff.affect(this, EvasiveMove.class, 2f);\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.isChallenged(Challenges.FATIGUE)) {\n\t\t\tBuff.affect(this, Fatigue.class).hit(false);\n\t\t}\n\t\t\n\t\treturn super.defenseProc( enemy, damage );\n\t}\n\t\n\t@Override\n\tpublic void damage( int dmg, Object src ) {\n\t\tif (buff(TimekeepersHourglass.timeStasis.class) != null)\n\t\t\treturn;\n\n\t\t//regular damage interrupt, triggers on any damage except specific mild DOT effects\n\t\t// unless the player recently hit 'continue moving', in which case this is ignored\n\t\tif (!(src instanceof Hunger || src instanceof Viscosity.DeferedDamage) && damageInterrupt) {\n\t\t\tinterrupt();\n\t\t\tresting = false;\n\t\t}\n\n\t\tif (this.buff(Drowsy.class) != null){\n\t\t\tBuff.detach(this, Drowsy.class);\n\t\t\tGLog.w( Messages.get(this, \"pain_resist\") );\n\t\t}\n\n\t\tEndure.EndureTracker endure = buff(Endure.EndureTracker.class);\n\t\tif (!(src instanceof Char)){\n\t\t\t//reduce damage here if it isn't coming from a character (if it is we already reduced it)\n\t\t\tif (endure != null){\n\t\t\t\tdmg = Math.round(endure.adjustDamageTaken(dmg));\n\t\t\t}\n\t\t\t//the same also applies to challenge scroll damage reduction\n\t\t\tif (buff(ScrollOfChallenge.ChallengeArena.class) != null){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\t\t\t//and to monk meditate damage reduction\n\t\t\tif (buff(MonkEnergy.MonkAbility.Meditate.MeditateResistance.class) != null){\n\t\t\t\tdmg *= 0.2f;\n\t\t\t}\n\t\t}\n\n\t\tCapeOfThorns.Thorns thorns = buff( CapeOfThorns.Thorns.class );\n\t\tif (thorns != null) {\n\t\t\tdmg = thorns.proc(dmg, (src instanceof Char ? (Char)src : null), this);\n\t\t}\n\n\t\tdmg = (int)Math.ceil(dmg * RingOfTenacity.damageMultiplier( this ));\n\n\t\tLargeSword.LargeSwordBuff largeSwordBuff = hero.buff(LargeSword.LargeSwordBuff.class);\n\t\tif (largeSwordBuff != null) {\n\t\t\tdmg = (int)Math.ceil(dmg * largeSwordBuff.getDefenseFactor());\n\t\t}\n\n\t\t//TODO improve this when I have proper damage source logic\n\t\tif (belongings.armor() != null && belongings.armor().hasGlyph(AntiMagic.class, this)\n\t\t\t\t&& AntiMagic.RESISTS.contains(src.getClass())){\n\t\t\tdmg -= AntiMagic.drRoll(this, belongings.armor().buffedLvl());\n\t\t}\n\n\t\tif (buff(Talent.WarriorFoodImmunity.class) != null){\n\t\t\tif (pointsInTalent(Talent.IRON_STOMACH) == 1) dmg = Math.round(dmg*0.25f);\n\t\t\telse if (pointsInTalent(Talent.IRON_STOMACH) == 2) dmg = Math.round(dmg*0.00f);\n\t\t}\n\n\t\tif (buff(Tackle.SuperArmorTracker.class) != null) {\n\t\t\tswitch (pointsInTalent(Talent.SUPER_ARMOR)) {\n\t\t\t\tcase 1:\n\t\t\t\t\tdmg = Math.round(dmg*0.67f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tdmg = Math.round(dmg*0.33f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tdmg = Math.round(dmg*0.00f);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0: default:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tint preHP = HP + shielding();\n\t\tif (src instanceof Hunger) preHP -= shielding();\n\t\tsuper.damage( dmg, src );\n\t\tint postHP = HP + shielding();\n\t\tif (src instanceof Hunger) postHP -= shielding();\n\t\tint effectiveDamage = preHP - postHP;\n\n\t\tif (effectiveDamage <= 0) return;\n\n\t\tif (buff(Challenge.DuelParticipant.class) != null){\n\t\t\tbuff(Challenge.DuelParticipant.class).addDamage(effectiveDamage);\n\t\t}\n\n\t\t//flash red when hit for serious damage.\n\t\tfloat percentDMG = effectiveDamage / (float)preHP; //percent of current HP that was taken\n\t\tfloat percentHP = 1 - ((HT - postHP) / (float)HT); //percent health after damage was taken\n\t\t// The flash intensity increases primarily based on damage taken and secondarily on missing HP.\n\t\tfloat flashIntensity = 0.25f * (percentDMG * percentDMG) / percentHP;\n\t\t//if the intensity is very low don't flash at all\n\t\tif (flashIntensity >= 0.05f){\n\t\t\tflashIntensity = Math.min(1/3f, flashIntensity); //cap intensity at 1/3\n\t\t\tGameScene.flash( (int)(0xFF*flashIntensity) << 16 );\n\t\t\tif (isAlive()) {\n\t\t\t\tif (flashIntensity >= 1/6f) {\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HEALTH_CRITICAL, 1/3f + flashIntensity * 2f);\n\t\t\t\t} else {\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HEALTH_WARN, 1/3f + flashIntensity * 4f);\n\t\t\t\t}\n\t\t\t\t//hero gets interrupted on taking serious damage, regardless of any other factor\n\t\t\t\tinterrupt();\n\t\t\t\tresting = false;\n\t\t\t\tdamageInterrupt = true;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void checkVisibleMobs() {\n\t\tArrayList<Mob> visible = new ArrayList<>();\n\n\t\tboolean newMob = false;\n\n\t\tMob target = null;\n\t\tfor (Mob m : Dungeon.level.mobs.toArray(new Mob[0])) {\n\t\t\tif (fieldOfView[ m.pos ] && m.alignment == Alignment.ENEMY) {\n\t\t\t\tvisible.add(m);\n\t\t\t\tif (!visibleEnemies.contains( m )) {\n\t\t\t\t\tnewMob = true;\n\t\t\t\t}\n\n\t\t\t\tif (!mindVisionEnemies.contains(m) && QuickSlotButton.autoAim(m) != -1){\n\t\t\t\t\tif (target == null){\n\t\t\t\t\t\ttarget = m;\n\t\t\t\t\t} else if (distance(target) > distance(m)) {\n\t\t\t\t\t\ttarget = m;\n\t\t\t\t\t}\n\t\t\t\t\tif (m instanceof Snake && Dungeon.level.distance(m.pos, pos) <= 4\n\t\t\t\t\t\t\t&& !Document.ADVENTURERS_GUIDE.isPageRead(Document.GUIDE_EXAMINING)){\n\t\t\t\t\t\tGLog.p(Messages.get(Guidebook.class, \"hint\"));\n\t\t\t\t\t\tGameScene.flashForDocument(Document.ADVENTURERS_GUIDE, Document.GUIDE_EXAMINING);\n\t\t\t\t\t\t//we set to read here to prevent this message popping up a bunch\n\t\t\t\t\t\tDocument.ADVENTURERS_GUIDE.readPage(Document.GUIDE_EXAMINING);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tChar lastTarget = QuickSlotButton.lastTarget;\n\t\tif (target != null && (lastTarget == null ||\n\t\t\t\t\t\t\t!lastTarget.isAlive() || !lastTarget.isActive() ||\n\t\t\t\t\t\t\tlastTarget.alignment == Alignment.ALLY ||\n\t\t\t\t\t\t\t!fieldOfView[lastTarget.pos])){\n\t\t\tQuickSlotButton.target(target);\n\t\t}\n\t\t\n\t\tif (newMob) {\n\t\t\tinterrupt();\n\t\t\tif (resting){\n\t\t\t\tDungeon.observe();\n\t\t\t\tresting = false;\n\t\t\t}\n\t\t}\n\n\t\tvisibleEnemies = visible;\n\t}\n\t\n\tpublic int visibleEnemies() {\n\t\treturn visibleEnemies.size();\n\t}\n\t\n\tpublic Mob visibleEnemy( int index ) {\n\t\treturn visibleEnemies.get(index % visibleEnemies.size());\n\t}\n\n\tpublic ArrayList<Mob> getVisibleEnemies(){\n\t\treturn new ArrayList<>(visibleEnemies);\n\t}\n\t\n\tprivate boolean walkingToVisibleTrapInFog = false;\n\t\n\t//FIXME this is a fairly crude way to track this, really it would be nice to have a short\n\t//history of hero actions\n\tpublic boolean justMoved = false;\n\t\n\tprivate boolean getCloser( final int target ) {\n\n\t\tif (target == pos)\n\t\t\treturn false;\n\n\t\tif (rooted) {\n\t\t\tPixelScene.shake( 1, 1f );\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tint step = -1;\n\t\t\n\t\tif (Dungeon.level.adjacent( pos, target )) {\n\n\t\t\tpath = null;\n\n\t\t\tif (Actor.findChar( target ) == null) {\n\t\t\t\tif (Dungeon.level.passable[target] || Dungeon.level.avoid[target]) {\n\t\t\t\t\tstep = target;\n\t\t\t\t}\n\t\t\t\tif (walkingToVisibleTrapInFog\n\t\t\t\t\t\t&& Dungeon.level.traps.get(target) != null\n\t\t\t\t\t\t&& Dungeon.level.traps.get(target).visible){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t} else {\n\n\t\t\tboolean newPath = false;\n\t\t\tif (path == null || path.isEmpty() || !Dungeon.level.adjacent(pos, path.getFirst()))\n\t\t\t\tnewPath = true;\n\t\t\telse if (path.getLast() != target)\n\t\t\t\tnewPath = true;\n\t\t\telse {\n\t\t\t\tif (!Dungeon.level.passable[path.get(0)] || Actor.findChar(path.get(0)) != null) {\n\t\t\t\t\tnewPath = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (newPath) {\n\n\t\t\t\tint len = Dungeon.level.length();\n\t\t\t\tboolean[] p = Dungeon.level.passable;\n\t\t\t\tboolean[] v = Dungeon.level.visited;\n\t\t\t\tboolean[] m = Dungeon.level.mapped;\n\t\t\t\tboolean[] passable = new boolean[len];\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\tpassable[i] = p[i] && (v[i] || m[i]);\n\t\t\t\t}\n\n\t\t\t\tPathFinder.Path newpath = Dungeon.findPath(this, target, passable, fieldOfView, true);\n\t\t\t\tif (newpath != null && path != null && newpath.size() > 2*path.size()){\n\t\t\t\t\tpath = null;\n\t\t\t\t} else {\n\t\t\t\t\tpath = newpath;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (path == null) return false;\n\t\t\tstep = path.removeFirst();\n\n\t\t}\n\n\t\tif (step != -1) {\n\n\t\t\tfloat delay = 1 / speed();\n\n\t\t\tif (Dungeon.level.pit[step] && !Dungeon.level.solid[step]\n\t\t\t\t\t&& (!flying || buff(Levitation.class) != null && buff(Levitation.class).detachesWithinDelay(delay))){\n\t\t\t\tif (!Chasm.jumpConfirmed){\n\t\t\t\t\tChasm.heroJump(this);\n\t\t\t\t\tinterrupt();\n\t\t\t\t} else {\n\t\t\t\t\tflying = false;\n\t\t\t\t\tremove(buff(Levitation.class)); //directly remove to prevent cell pressing\n\t\t\t\t\tChasm.heroFall(target);\n\t\t\t\t}\n\t\t\t\tcanSelfTrample = false;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif ((hero.belongings.weapon instanceof Lance ||\n\t\t\t\t\thero.belongings.secondWep instanceof Lance ||\n\t\t\t\t\t(hero.belongings.weapon instanceof LanceNShield && ((LanceNShield)hero.belongings.weapon).stance) ||\n\t\t\t\t\t(hero.belongings.secondWep instanceof LanceNShield && ((LanceNShield)hero.belongings.secondWep).stance))) {\n\t\t\t\tBuff.affect(this, Lance.LanceBuff.class).setDamageFactor(1 + (hero.speed()), hero.belongings.secondWep instanceof Lance || (hero.belongings.secondWep instanceof LanceNShield && ((LanceNShield) hero.belongings.secondWep).stance));\n\t\t\t}\n\n\t\t\tif (subClass == HeroSubClass.FREERUNNER){\n\t\t\t\tBuff.affect(this, Momentum.class).gainStack();\n\t\t\t}\n\n\t\t\tif (hero.buff(Talent.RollingTracker.class) != null && hero.belongings.weapon instanceof Gun && Dungeon.bullet > 1) {\n\t\t\t\tDungeon.bullet --;\n\t\t\t\t((Gun)hero.belongings.weapon).manualReload();\n\t\t\t\thero.buff(Talent.RollingTracker.class).detach();\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.QUICK_RELOAD) && hero.belongings.weapon instanceof Gun && Random.Float() < 0.03f * hero.pointsInTalent(Talent.QUICK_RELOAD) && Dungeon.bullet > 1) {\n\t\t\t\tDungeon.bullet --;\n\t\t\t\t((Gun)hero.belongings.weapon).manualReload();\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.MIND_VISION) && Random.Float() < 0.01f*hero.pointsInTalent(Talent.MIND_VISION)) {\n\t\t\t\tBuff.affect(this, MindVision.class, 1f);\n\t\t\t}\n\t\t\t\n\t\t\tsprite.move(pos, step);\n\t\t\tmove(step);\n\n\t\t\tif (buff(Talent.QuickStep.class) != null) {\n\t\t\t\tspend(-delay);\n\t\t\t\tbuff(Talent.QuickStep.class).detach();\n\t\t\t}\n\n\t\t\tspend( delay );\n\t\t\tjustMoved = true;\n\t\t\t\n\t\t\tsearch(false);\n\n\t\t\treturn true;\n\n\t\t} else {\n\n\t\t\treturn false;\n\t\t\t\n\t\t}\n\n\t}\n\t\n\tpublic boolean handle( int cell ) {\n\t\t\n\t\tif (cell == -1) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (fieldOfView == null || fieldOfView.length != Dungeon.level.length()){\n\t\t\tfieldOfView = new boolean[Dungeon.level.length()];\n\t\t\tDungeon.level.updateFieldOfView( this, fieldOfView );\n\t\t}\n\t\t\n\t\tChar ch = Actor.findChar( cell );\n\t\tHeap heap = Dungeon.level.heaps.get( cell );\n\n\t\tif (Dungeon.level.map[cell] == Terrain.ALCHEMY && cell != pos) {\n\t\t\t\n\t\t\tcurAction = new HeroAction.Alchemy( cell );\n\t\t\t\n\t\t} else if (fieldOfView[cell] && ch instanceof Mob) {\n\n\t\t\tif (ch.alignment != Alignment.ENEMY && ch.buff(Amok.class) == null) {\n\t\t\t\tcurAction = new HeroAction.Interact( ch );\n\t\t\t} else {\n\t\t\t\tcurAction = new HeroAction.Attack( ch );\n\t\t\t}\n\n\t\t//TODO perhaps only trigger this if hero is already adjacent? reducing mistaps\n\t\t} else if (Dungeon.level instanceof MiningLevel &&\n\t\t\t\t\tbelongings.getItem(Pickaxe.class) != null &&\n\t\t\t\t(Dungeon.level.map[cell] == Terrain.WALL\n\t\t\t\t\t\t|| Dungeon.level.map[cell] == Terrain.WALL_DECO\n\t\t\t\t\t\t|| Dungeon.level.map[cell] == Terrain.MINE_CRYSTAL\n\t\t\t\t\t\t|| Dungeon.level.map[cell] == Terrain.MINE_BOULDER)){\n\n\t\t\tcurAction = new HeroAction.Mine( cell );\n\n\t\t} else if (heap != null\n\t\t\t\t//moving to an item doesn't auto-pickup when enemies are near...\n\t\t\t\t&& (visibleEnemies.size() == 0 || cell == pos ||\n\t\t\t\t//...but only for standard heaps. Chests and similar open as normal.\n\t\t\t\t(heap.type != Type.HEAP && heap.type != Type.FOR_SALE))) {\n\n\t\t\tswitch (heap.type) {\n\t\t\tcase HEAP:\n\t\t\t\tcurAction = new HeroAction.PickUp( cell );\n\t\t\t\tbreak;\n\t\t\tcase FOR_SALE:\n\t\t\t\tcurAction = heap.size() == 1 && heap.peek().value() > 0 ?\n\t\t\t\t\tnew HeroAction.Buy( cell ) :\n\t\t\t\t\tnew HeroAction.PickUp( cell );\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tcurAction = new HeroAction.OpenChest( cell );\n\t\t\t}\n\t\t\t\n\t\t} else if (Dungeon.level.map[cell] == Terrain.LOCKED_DOOR || Dungeon.level.map[cell] == Terrain.CRYSTAL_DOOR || Dungeon.level.map[cell] == Terrain.LOCKED_EXIT) {\n\t\t\t\n\t\t\tcurAction = new HeroAction.Unlock( cell );\n\t\t\t\n\t\t} else if (Dungeon.level.getTransition(cell) != null\n\t\t\t\t//moving to a transition doesn't automatically trigger it when enemies are near\n\t\t\t\t&& (visibleEnemies.size() == 0 || cell == pos)\n\t\t\t\t&& !Dungeon.level.locked\n\t\t\t\t&& (Dungeon.depth < 31 || Dungeon.level.getTransition(cell).type == LevelTransition.Type.REGULAR_ENTRANCE) ) {\n\n\t\t\tcurAction = new HeroAction.LvlTransition( cell );\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tif (!Dungeon.level.visited[cell] && !Dungeon.level.mapped[cell]\n\t\t\t\t\t&& Dungeon.level.traps.get(cell) != null && Dungeon.level.traps.get(cell).visible) {\n\t\t\t\twalkingToVisibleTrapInFog = true;\n\t\t\t} else {\n\t\t\t\twalkingToVisibleTrapInFog = false;\n\t\t\t}\n\t\t\t\n\t\t\tcurAction = new HeroAction.Move( cell );\n\t\t\tlastAction = null;\n\t\t\t\n\t\t}\n\n\t\treturn true;\n\t}\n\t\n\tpublic void earnExp( int exp, Class source ) {\n\n\t\t//xp granted by ascension challenge is only for on-exp gain effects\n\t\tif (source != AscensionChallenge.class) {\n\t\t\tthis.exp += exp;\n\t\t}\n\t\tfloat percent = exp/(float)maxExp();\n\n\t\tEtherealChains.chainsRecharge chains = buff(EtherealChains.chainsRecharge.class);\n\t\tif (chains != null) chains.gainExp(percent);\n\n\t\tHornOfPlenty.hornRecharge horn = buff(HornOfPlenty.hornRecharge.class);\n\t\tif (horn != null) horn.gainCharge(percent);\n\t\t\n\t\tAlchemistsToolkit.kitEnergy kit = buff(AlchemistsToolkit.kitEnergy.class);\n\t\tif (kit != null) kit.gainCharge(percent);\n\n\t\tMasterThievesArmband.Thievery armband = buff(MasterThievesArmband.Thievery.class);\n\t\tif (armband != null) armband.gainCharge(percent);\n\t\t\n\t\tBerserk berserk = buff(Berserk.class);\n\t\tif (berserk != null) berserk.recover(percent);\n\t\t\n\t\tif (source != PotionOfExperience.class) {\n\t\t\tfor (Item i : belongings) {\n\t\t\t\ti.onHeroGainExp(percent, this);\n\t\t\t}\n\t\t\tif (buff(Talent.RejuvenatingStepsFurrow.class) != null){\n\t\t\t\tbuff(Talent.RejuvenatingStepsFurrow.class).countDown(percent*200f);\n\t\t\t\tif (buff(Talent.RejuvenatingStepsFurrow.class).count() <= 0){\n\t\t\t\t\tbuff(Talent.RejuvenatingStepsFurrow.class).detach();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (buff(ElementalStrike.ElementalStrikeFurrowCounter.class) != null){\n\t\t\t\tbuff(ElementalStrike.ElementalStrikeFurrowCounter.class).countDown(percent*20f);\n\t\t\t\tif (buff(ElementalStrike.ElementalStrikeFurrowCounter.class).count() <= 0){\n\t\t\t\t\tbuff(ElementalStrike.ElementalStrikeFurrowCounter.class).detach();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tboolean levelUp = false;\n\t\twhile (this.exp >= maxExp()) {\n\t\t\tthis.exp -= maxExp();\n\t\t\tif (lvl < MAX_LEVEL) {\n\t\t\t\tlvl++;\n\t\t\t\tlevelUp = true;\n\t\t\t\t\n\t\t\t\tif (buff(ElixirOfMight.HTBoost.class) != null){\n\t\t\t\t\tbuff(ElixirOfMight.HTBoost.class).onLevelUp();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tupdateHT( true );\n\t\t\t\tattackSkill++;\n\t\t\t\tdefenseSkill++;\n\n\t\t\t} else {\n\t\t\t\tBuff.prolong(this, Bless.class, Bless.DURATION);\n\t\t\t\tthis.exp = 0;\n\n\t\t\t\tGLog.newLine();\n\t\t\t\tGLog.p( Messages.get(this, \"level_cap\"));\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.LEVELUP );\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tif (levelUp) {\n\t\t\t\n\t\t\tif (sprite != null) {\n\t\t\t\tGLog.newLine();\n\t\t\t\tGLog.p( Messages.get(this, \"new_level\") );\n\t\t\t\tsprite.showStatus( CharSprite.POSITIVE, Messages.get(Hero.class, \"level_up\") );\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.LEVELUP );\n\t\t\t\tif (lvl < Talent.tierLevelThresholds[Talent.MAX_TALENT_TIERS+1]){\n\t\t\t\t\tGLog.newLine();\n\t\t\t\t\tGLog.p( Messages.get(this, \"new_talent\") );\n\t\t\t\t\tStatusPane.talentBlink = 10f;\n\t\t\t\t\tWndHero.lastIdx = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tItem.updateQuickslot();\n\t\t\t\n\t\t\tBadges.validateLevelReached();\n\t\t}\n\t}\n\t\n\tpublic int maxExp() {\n\t\treturn maxExp( lvl );\n\t}\n\t\n\tpublic static int maxExp( int lvl ){\n\t\treturn 5 + lvl * 5;\n\t}\n\t\n\tpublic boolean isStarving() {\n\t\treturn Buff.affect(this, Hunger.class).isStarving();\n\t}\n\t\n\t@Override\n\tpublic boolean add( Buff buff ) {\n\n\t\tif (buff(TimekeepersHourglass.timeStasis.class) != null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tboolean added = super.add( buff );\n\n\t\tif (sprite != null && added) {\n\t\t\tString msg = buff.heroMessage();\n\t\t\tif (msg != null){\n\t\t\t\tGLog.w(msg);\n\t\t\t}\n\n\t\t\tif (buff instanceof Paralysis || buff instanceof Vertigo) {\n\t\t\t\tinterrupt();\n\t\t\t}\n\n\t\t}\n\t\t\n\t\tBuffIndicator.refreshHero();\n\n\t\treturn added;\n\t}\n\t\n\t@Override\n\tpublic boolean remove( Buff buff ) {\n\t\tif (super.remove( buff )) {\n\t\t\tBuffIndicator.refreshHero();\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic float stealth() {\n\t\tfloat stealth = super.stealth();\n\t\t\n\t\tif (belongings.armor() != null){\n\t\t\tstealth = belongings.armor().stealthFactor(this, stealth);\n\t\t}\n\t\t\n\t\treturn stealth;\n\t}\n\t\n\t@Override\n\tpublic void die( Object cause ) {\n\n\t\tif (buff(Enduring.class) != null) {\n\t\t\tthis.HP = 1;\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tcurAction = null;\n\n\t\tAnkh ankh = null;\n\n\t\t//look for ankhs in player inventory, prioritize ones which are blessed.\n\t\tfor (Ankh i : belongings.getAllItems(Ankh.class)){\n\t\t\tif (ankh == null || i.isBlessed()) {\n\t\t\t\tankh = i;\n\t\t\t}\n\t\t}\n\n\t\tif (ankh != null) {\n\t\t\tinterrupt();\n\t\t\tresting = false;\n\n\t\t\tif (ankh.isBlessed()) {\n\t\t\t\tthis.HP = HT / 4;\n\n\t\t\t\tPotionOfHealing.cure(this);\n\t\t\t\tBuff.prolong(this, AnkhInvulnerability.class, AnkhInvulnerability.DURATION);\n\n\t\t\t\tSpellSprite.show(this, SpellSprite.ANKH);\n\t\t\t\tGameScene.flash(0x80FFFF40);\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TELEPORT);\n\t\t\t\tGLog.w(Messages.get(this, \"revive\"));\n\t\t\t\tStatistics.ankhsUsed++;\n\n\t\t\t\tankh.detach(belongings.backpack);\n\n\t\t\t\tfor (Char ch : Actor.chars()) {\n\t\t\t\t\tif (ch instanceof DriedRose.GhostHero) {\n\t\t\t\t\t\t((DriedRose.GhostHero) ch).sayAnhk();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\n\t\t\t\t//this is hacky, basically we want to declare that a wndResurrect exists before\n\t\t\t\t//it actually gets created. This is important so that the game knows to not\n\t\t\t\t//delete the run or submit it to rankings, because a WndResurrect is about to exist\n\t\t\t\t//this is needed because the actual creation of the window is delayed here\n\t\t\t\tWndResurrect.instance = new Object();\n\t\t\t\tAnkh finalAnkh = ankh;\n\t\t\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void call() {\n\t\t\t\t\t\tGameScene.show( new WndResurrect(finalAnkh) );\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (cause instanceof Hero.Doom) {\n\t\t\t\t\t((Hero.Doom)cause).onDeath();\n\t\t\t\t}\n\n\t\t\t\tSacrificialFire.Marked sacMark = buff(SacrificialFire.Marked.class);\n\t\t\t\tif (sacMark != null){\n\t\t\t\t\tsacMark.detach();\n\t\t\t\t}\n\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tActor.fixTime();\n\t\tsuper.die( cause );\n\t\treallyDie( cause );\n\t}\n\t\n\tpublic static void reallyDie( Object cause ) {\n\t\t\n\t\tint length = Dungeon.level.length();\n\t\tint[] map = Dungeon.level.map;\n\t\tboolean[] visited = Dungeon.level.visited;\n\t\tboolean[] discoverable = Dungeon.level.discoverable;\n\t\t\n\t\tfor (int i=0; i < length; i++) {\n\t\t\t\n\t\t\tint terr = map[i];\n\t\t\t\n\t\t\tif (discoverable[i]) {\n\t\t\t\t\n\t\t\t\tvisited[i] = true;\n\t\t\t\tif ((Terrain.flags[terr] & Terrain.SECRET) != 0) {\n\t\t\t\t\tDungeon.level.discover( i );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tBones.leave();\n\t\t\n\t\tDungeon.observe();\n\t\tGameScene.updateFog();\n\t\t\t\t\n\t\tDungeon.hero.belongings.identify();\n\n\t\tint pos = Dungeon.hero.pos;\n\n\t\tArrayList<Integer> passable = new ArrayList<>();\n\t\tfor (Integer ofs : PathFinder.NEIGHBOURS8) {\n\t\t\tint cell = pos + ofs;\n\t\t\tif ((Dungeon.level.passable[cell] || Dungeon.level.avoid[cell]) && Dungeon.level.heaps.get( cell ) == null) {\n\t\t\t\tpassable.add( cell );\n\t\t\t}\n\t\t}\n\t\tCollections.shuffle( passable );\n\n\t\tArrayList<Item> items = new ArrayList<>(Dungeon.hero.belongings.backpack.items);\n\t\tfor (Integer cell : passable) {\n\t\t\tif (items.isEmpty()) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tItem item = Random.element( items );\n\t\t\tDungeon.level.drop( item, cell ).sprite.drop( pos );\n\t\t\titems.remove( item );\n\t\t}\n\n\t\tfor (Char c : Actor.chars()){\n\t\t\tif (c instanceof DriedRose.GhostHero){\n\t\t\t\t((DriedRose.GhostHero) c).sayHeroKilled();\n\t\t\t}\n\t\t}\n\n\t\tGame.runOnRenderThread(new Callback() {\n\t\t\t@Override\n\t\t\tpublic void call() {\n\t\t\t\tGameScene.gameOver();\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.DEATH );\n\t\t\t}\n\t\t});\n\n\t\tif (cause instanceof Hero.Doom) {\n\t\t\t((Hero.Doom)cause).onDeath();\n\t\t}\n\n\t\tDungeon.deleteGame( GamesInProgress.curSlot, true );\n\t}\n\n\t//effectively cache this buff to prevent having to call buff(...) a bunch.\n\t//This is relevant because we call isAlive during drawing, which has both performance\n\t//and thread coordination implications if that method calls buff(...) frequently\n\tprivate Berserk berserk;\n\n\t@Override\n\tpublic boolean isAlive() {\n\t\t\n\t\tif (HP <= 0){\n\t\t\tif (berserk == null) berserk = buff(Berserk.class);\n\t\t\treturn berserk != null && berserk.berserking();\n\t\t} else {\n\t\t\tberserk = null;\n\t\t\treturn super.isAlive();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void move(int step, boolean travelling) {\n\t\tboolean wasHighGrass = Dungeon.level.map[step] == Terrain.HIGH_GRASS;\n\n\t\tsuper.move( step, travelling);\n\t\t\n\t\tif (!flying && travelling) {\n\t\t\tif (Dungeon.level.water[pos]) {\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.WATER, 1, Random.Float( 0.8f, 1.25f ) );\n\t\t\t} else if (Dungeon.level.map[pos] == Terrain.EMPTY_SP) {\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.STURDY, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t} else if (Dungeon.level.map[pos] == Terrain.GRASS\n\t\t\t\t\t|| Dungeon.level.map[pos] == Terrain.EMBERS\n\t\t\t\t\t|| Dungeon.level.map[pos] == Terrain.FURROWED_GRASS){\n\t\t\t\tif (step == pos && wasHighGrass) {\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TRAMPLE, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t\t} else {\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.GRASS, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSample.INSTANCE.play( Assets.Sounds.STEP, 1, Random.Float( 0.96f, 1.05f ) );\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void onAttackComplete() {\n\n\t\tif (enemy == null){\n\t\t\tcurAction = null;\n\t\t\tsuper.onAttackComplete();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tAttackIndicator.target(enemy);\n\t\tboolean wasEnemy = enemy.alignment == Alignment.ENEMY\n\t\t\t\t|| (enemy instanceof Mimic && enemy.alignment == Alignment.NEUTRAL);\n\n\t\tboolean hit = attack( enemy );\n\t\t\n\t\tInvisibility.dispel();\n\t\tspend( attackDelay() );\n\n\t\tif (hit && subClass == HeroSubClass.GLADIATOR && wasEnemy){\n\t\t\tBuff.affect( this, Combo.class ).hit( enemy );\n\t\t}\n\n\t\tif (hit && subClass == HeroSubClass.BATTLEMAGE && hero.belongings.attackingWeapon() instanceof MagesStaff && hero.hasTalent(Talent.BATTLE_MAGIC) && wasEnemy) {\n\t\t\tBuff.affect( this, MagicalCombo.class).hit( enemy );\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.CHASER\n\t\t\t\t&& hero.hasTalent(Talent.CHAIN_CLOCK)\n\t\t\t\t&& ((Mob) enemy).surprisedBy(hero)\n\t\t\t\t&& hero.buff(Talent.ChainCooldown.class) == null){\n\t\t\tBuff.affect( this, Invisibility.class, 1f * hero.pointsInTalent(Talent.CHAIN_CLOCK));\n\t\t\tBuff.affect( this, Haste.class, 1f * hero.pointsInTalent(Talent.CHAIN_CLOCK));\n\t\t\tBuff.affect( this, Talent.ChainCooldown.class, 10f);\n\t\t\tSample.INSTANCE.play( Assets.Sounds.MELD );\n\t\t}\n\n\t\tif (hero.subClass == HeroSubClass.CHASER\n\t\t\t\t&& hero.hasTalent(Talent.LETHAL_SURPRISE)\n\t\t\t\t&& ((Mob) enemy).surprisedBy(hero)\n\t\t\t\t&& !enemy.isAlive()\n\t\t\t\t&& hero.buff(Talent.LethalCooldown.class) == null) {\n\t\t\tif (hero.pointsInTalent(Talent.LETHAL_SURPRISE) >= 1) {\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] )) {\n\t\t\t\t\tif (mob.alignment != Char.Alignment.ALLY && Dungeon.level.heroFOV[mob.pos]) {\n\t\t\t\t\t\tBuff.affect( mob, Vulnerable.class, 1f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tBuff.affect(hero, Talent.LethalCooldown.class, 5f);\n\t\t\t}\n\t\t\tif (hero.pointsInTalent(Talent.LETHAL_SURPRISE) >= 2) {\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] )) {\n\t\t\t\t\tif (mob.alignment != Char.Alignment.ALLY && Dungeon.level.heroFOV[mob.pos]) {\n\t\t\t\t\t\tBuff.affect( mob, Paralysis.class, 1f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hero.pointsInTalent(Talent.LETHAL_SURPRISE) == 3) {\n\t\t\t\tBuff.affect(hero, Swiftthistle.TimeBubble.class).twoTurns();\n\t\t\t}\n\t\t}\n\n\t\tif (hit && heroClass == HeroClass.DUELIST && wasEnemy){\n\t\t\tBuff.affect( this, Sai.ComboStrikeTracker.class).addHit();\n\t\t}\n\n\t\tRingOfForce.BrawlersStance brawlStance = buff(RingOfForce.BrawlersStance.class);\n\t\tif (brawlStance != null && brawlStance.hitsLeft() > 0){\n\t\t\tMeleeWeapon.Charger charger = Buff.affect(this, MeleeWeapon.Charger.class);\n\t\t\tcharger.partialCharge -= RingOfForce.BrawlersStance.HIT_CHARGE_USE;\n\t\t\twhile (charger.partialCharge < 0) {\n\t\t\t\tcharger.charges--;\n\t\t\t\tcharger.partialCharge++;\n\t\t\t}\n\t\t\tBuffIndicator.refreshHero();\n\t\t\tItem.updateQuickslot();\n\t\t}\n\n\t\tif (!hit && hero.belongings.weapon == null && hero.subClass == HeroSubClass.FIGHTER && Random.Int(5) == 0 && hero.pointsInTalent(Talent.SWIFT_MOVEMENT) > 1) {\n\t\t\tBuff.prolong(hero, EvasiveMove.class, 0.9999f);\n\t\t}\n\n\t\tcurAction = null;\n\n\t\tsuper.onAttackComplete();\n\t}\n\t\n\t@Override\n\tpublic void onMotionComplete() {\n\t\tGameScene.checkKeyHold();\n\t}\n\t\n\t@Override\n\tpublic void onOperateComplete() {\n\t\t\n\t\tif (curAction instanceof HeroAction.Unlock) {\n\n\t\t\tint doorCell = ((HeroAction.Unlock)curAction).dst;\n\t\t\tint door = Dungeon.level.map[doorCell];\n\t\t\t\n\t\t\tif (Dungeon.level.distance(pos, doorCell) <= 1) {\n\t\t\t\tboolean hasKey = true;\n\t\t\t\tif (door == Terrain.LOCKED_DOOR) {\n\t\t\t\t\thasKey = Notes.remove(new IronKey(Dungeon.depth));\n\t\t\t\t\tif (hasKey) Level.set(doorCell, Terrain.DOOR);\n\t\t\t\t} else if (door == Terrain.CRYSTAL_DOOR) {\n\t\t\t\t\thasKey = Notes.remove(new CrystalKey(Dungeon.depth, Dungeon.branch));\n\t\t\t\t\tif (hasKey) {\n\t\t\t\t\t\tLevel.set(doorCell, Terrain.EMPTY);\n\t\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.TELEPORT);\n\t\t\t\t\t\tCellEmitter.get( doorCell ).start( Speck.factory( Speck.DISCOVER ), 0.025f, 20 );\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\thasKey = Notes.remove(new SkeletonKey(Dungeon.depth));\n\t\t\t\t\tif (hasKey) Level.set(doorCell, Terrain.UNLOCKED_EXIT);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (hasKey) {\n\t\t\t\t\tGameScene.updateKeyDisplay();\n\t\t\t\t\tGameScene.updateMap(doorCell);\n\t\t\t\t\tspend(Key.TIME_TO_UNLOCK);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t} else if (curAction instanceof HeroAction.OpenChest) {\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( ((HeroAction.OpenChest)curAction).dst );\n\t\t\t\n\t\t\tif (Dungeon.level.distance(pos, heap.pos) <= 1){\n\t\t\t\tboolean hasKey = true;\n\t\t\t\tif (heap.type == Type.SKELETON || heap.type == Type.REMAINS) {\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.BONES );\n\t\t\t\t} else if (heap.type == Type.LOCKED_CHEST){\n\t\t\t\t\thasKey = Notes.remove(new GoldenKey(Dungeon.depth));\n\t\t\t\t} else if (heap.type == Type.CRYSTAL_CHEST){\n\t\t\t\t\thasKey = Notes.remove(new CrystalKey(Dungeon.depth));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (hasKey) {\n\t\t\t\t\tGameScene.updateKeyDisplay();\n\t\t\t\t\theap.open(this);\n\t\t\t\t\tspend(Key.TIME_TO_UNLOCK);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t\tcurAction = null;\n\n\t\tif (!ready) {\n\t\t\tsuper.onOperateComplete();\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean isImmune(Class effect) {\n\t\tif (effect == Burning.class\n\t\t\t\t&& belongings.armor() != null\n\t\t\t\t&& belongings.armor().hasGlyph(Brimstone.class, this)){\n\t\t\treturn true;\n\t\t}\n\t\treturn super.isImmune(effect);\n\t}\n\n\t@Override\n\tpublic boolean isInvulnerable(Class effect) {\n\t\treturn super.isInvulnerable(effect) || buff(AnkhInvulnerability.class) != null;\n\t}\n\n\tpublic boolean search( boolean intentional ) {\n\t\t\n\t\tif (!isAlive()) return false;\n\t\t\n\t\tboolean smthFound = false;\n\n\t\tboolean circular = pointsInTalent(Talent.WIDE_SEARCH) == 1;\n\t\tint distance = heroClass == HeroClass.ROGUE ? 2 : 1;\n\t\tif (hasTalent(Talent.WIDE_SEARCH)) distance++;\n\t\t\n\t\tboolean foresight = buff(Foresight.class) != null;\n\t\tboolean foresightScan = foresight && !Dungeon.level.mapped[pos];\n\n\t\tif (foresightScan){\n\t\t\tDungeon.level.mapped[pos] = true;\n\t\t}\n\n\t\tif (foresight) {\n\t\t\tdistance = Foresight.DISTANCE;\n\t\t\tcircular = true;\n\t\t}\n\n\t\tPoint c = Dungeon.level.cellToPoint(pos);\n\n\t\tTalismanOfForesight.Foresight talisman = buff( TalismanOfForesight.Foresight.class );\n\t\tboolean cursed = talisman != null && talisman.isCursed();\n\n\t\tint[] rounding = ShadowCaster.rounding[distance];\n\n\t\tint left, right;\n\t\tint curr;\n\t\tfor (int y = Math.max(0, c.y - distance); y <= Math.min(Dungeon.level.height()-1, c.y + distance); y++) {\n\t\t\tif (!circular){\n\t\t\t\tleft = c.x - distance;\n\t\t\t} else if (rounding[Math.abs(c.y - y)] < Math.abs(c.y - y)) {\n\t\t\t\tleft = c.x - rounding[Math.abs(c.y - y)];\n\t\t\t} else {\n\t\t\t\tleft = distance;\n\t\t\t\twhile (rounding[left] < rounding[Math.abs(c.y - y)]){\n\t\t\t\t\tleft--;\n\t\t\t\t}\n\t\t\t\tleft = c.x - left;\n\t\t\t}\n\t\t\tright = Math.min(Dungeon.level.width()-1, c.x + c.x - left);\n\t\t\tleft = Math.max(0, left);\n\t\t\tfor (curr = left + y * Dungeon.level.width(); curr <= right + y * Dungeon.level.width(); curr++){\n\n\t\t\t\tif ((foresight || fieldOfView[curr]) && curr != pos) {\n\n\t\t\t\t\tif ((foresight && (!Dungeon.level.mapped[curr] || foresightScan))){\n\t\t\t\t\t\tGameScene.effectOverFog(new CheckedCell(curr, foresightScan ? pos : curr));\n\t\t\t\t\t} else if (intentional) {\n\t\t\t\t\t\tGameScene.effectOverFog(new CheckedCell(curr, pos));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (foresight){\n\t\t\t\t\t\tDungeon.level.mapped[curr] = true;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (Dungeon.level.secret[curr]){\n\t\t\t\t\t\t\n\t\t\t\t\t\tTrap trap = Dungeon.level.traps.get( curr );\n\t\t\t\t\t\tfloat chance;\n\n\t\t\t\t\t\t//searches aided by foresight always succeed, even if trap isn't searchable\n\t\t\t\t\t\tif (foresight){\n\t\t\t\t\t\t\tchance = 1f;\n\n\t\t\t\t\t\t//otherwise if the trap isn't searchable, searching always fails\n\t\t\t\t\t\t} else if (trap != null && !trap.canBeSearched){\n\t\t\t\t\t\t\tchance = 0f;\n\n\t\t\t\t\t\t//intentional searches always succeed against regular traps and doors\n\t\t\t\t\t\t} else if (intentional){\n\t\t\t\t\t\t\tchance = 1f;\n\t\t\t\t\t\t\n\t\t\t\t\t\t//unintentional searches always fail with a cursed talisman\n\t\t\t\t\t\t} else if (cursed) {\n\t\t\t\t\t\t\tchance = 0f;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t//unintentional trap detection scales from 40% at floor 0 to 30% at floor 25\n\t\t\t\t\t\t} else if (Dungeon.level.map[curr] == Terrain.SECRET_TRAP) {\n\t\t\t\t\t\t\tchance = 0.4f - (Dungeon.depth / 250f);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t//unintentional door detection scales from 20% at floor 0 to 0% at floor 20\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tchance = 0.2f - (Dungeon.depth / 100f);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//don't want to let the player search though hidden doors in tutorial\n\t\t\t\t\t\tif (SPDSettings.intro()){\n\t\t\t\t\t\t\tchance = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (Random.Float() < chance) {\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tint oldValue = Dungeon.level.map[curr];\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tGameScene.discoverTile( curr, oldValue );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tDungeon.level.discover( curr );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tScrollOfMagicMapping.discover( curr );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (fieldOfView[curr]) smthFound = true;\n\t\n\t\t\t\t\t\t\tif (talisman != null){\n\t\t\t\t\t\t\t\tif (oldValue == Terrain.SECRET_TRAP){\n\t\t\t\t\t\t\t\t\ttalisman.charge(2);\n\t\t\t\t\t\t\t\t} else if (oldValue == Terrain.SECRET_DOOR){\n\t\t\t\t\t\t\t\t\ttalisman.charge(10);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (intentional) {\n\t\t\tsprite.showStatus( CharSprite.DEFAULT, Messages.get(this, \"search\") );\n\t\t\tsprite.operate( pos );\n\t\t\tif (!Dungeon.level.locked) {\n\t\t\t\tif (cursed) {\n\t\t\t\t\tGLog.n(Messages.get(this, \"search_distracted\"));\n\t\t\t\t\tBuff.affect(this, Hunger.class).affectHunger(TIME_TO_SEARCH - (2 * HUNGER_FOR_SEARCH));\n\t\t\t\t} else {\n\t\t\t\t\tBuff.affect(this, Hunger.class).affectHunger(TIME_TO_SEARCH - HUNGER_FOR_SEARCH);\n\t\t\t\t}\n\t\t\t}\n\t\t\tspendAndNext(TIME_TO_SEARCH);\n\t\t\t\n\t\t}\n\t\t\n\t\tif (smthFound) {\n\t\t\tGLog.w( Messages.get(this, \"noticed_smth\") );\n\t\t\tSample.INSTANCE.play( Assets.Sounds.SECRET );\n\t\t\tinterrupt();\n\t\t}\n\n\t\tif (foresight){\n\t\t\tGameScene.updateFog(pos, Foresight.DISTANCE+1);\n\t\t}\n\t\t\n\t\treturn smthFound;\n\t}\n\t\n\tpublic void resurrect() {\n\t\tHP = HT;\n\t\tlive();\n\n\t\tMagicalHolster holster = belongings.getItem(MagicalHolster.class);\n\n\t\tBuff.affect(this, LostInventory.class);\n\t\tBuff.affect(this, Invisibility.class, 3f);\n\t\t//lost inventory is dropped in interlevelscene\n\n\t\t//activate items that persist after lost inventory\n\t\t//FIXME this is very messy, maybe it would be better to just have one buff that\n\t\t// handled all items that recharge over time?\n\t\tfor (Item i : belongings){\n\t\t\tif (i instanceof EquipableItem && i.isEquipped(this)){\n\t\t\t\t((EquipableItem) i).activate(this);\n\t\t\t} else if (i instanceof CloakOfShadows && i.keptThroughLostInventory() && hasTalent(Talent.LIGHT_CLOAK)){\n\t\t\t\t((CloakOfShadows) i).activate(this);\n\t\t\t} else if (i instanceof Wand && i.keptThroughLostInventory()){\n\t\t\t\tif (holster != null && holster.contains(i)){\n\t\t\t\t\t((Wand) i).charge(this, MagicalHolster.HOLSTER_SCALE_FACTOR);\n\t\t\t\t} else {\n\t\t\t\t\t((Wand) i).charge(this);\n\t\t\t\t}\n\t\t\t} else if (i instanceof MagesStaff && i.keptThroughLostInventory()){\n\t\t\t\t((MagesStaff) i).applyWandChargeBuff(this);\n\t\t\t}\n\t\t}\n\n\t\tupdateHT(false);\n\t}\n\n\t@Override\n\tpublic void next() {\n\t\tif (isAlive())\n\t\t\tsuper.next();\n\t}\n\n\tpublic static interface Doom {\n\t\tpublic void onDeath();\n\t}\n}" }, { "identifier": "Mob", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/mobs/Mob.java", "snippet": "public abstract class Mob extends Char {\n\n\t{\n\t\tactPriority = MOB_PRIO;\n\t\t\n\t\talignment = Alignment.ENEMY;\n\t}\n\t\n\tprivate static final String\tTXT_DIED\t= \"You hear something died in the distance\";\n\t\n\tprotected static final String TXT_NOTICE1\t= \"?!\";\n\tprotected static final String TXT_RAGE\t\t= \"#$%^\";\n\tprotected static final String TXT_EXP\t\t= \"%+dEXP\";\n\n\tpublic AiState SLEEPING = new Sleeping();\n\tpublic AiState HUNTING\t\t= new Hunting();\n\tpublic AiState WANDERING\t= new Wandering();\n\tpublic AiState FLEEING\t\t= new Fleeing();\n\tpublic AiState PASSIVE\t\t= new Passive();\n\tpublic AiState state = SLEEPING;\n\t\n\tpublic Class<? extends CharSprite> spriteClass;\n\t\n\tprotected int target = -1;\n\t\n\tpublic int defenseSkill = 0;\n\t\n\tpublic int EXP = 1;\n\tpublic int maxLvl = Hero.MAX_LEVEL-1;\n\t\n\tprotected Char enemy;\n\tprotected int enemyID = -1; //used for save/restore\n\tprotected boolean enemySeen;\n\tprotected boolean alerted = false;\n\n\tprotected static final float TIME_TO_WAKE_UP = 1f;\n\n\tprotected boolean firstAdded = true;\n\tprotected void onAdd(){\n\t\tif (firstAdded) {\n\t\t\t//modify health for ascension challenge if applicable, only on first add\n\t\t\tfloat percent = HP / (float) HT;\n\t\t\tHT = Math.round(HT * AscensionChallenge.statModifier(this));\n\t\t\tHP = Math.round(HT * percent);\n\t\t\tfirstAdded = false;\n\t\t}\n\t}\n\n\tprivate static final String STATE\t= \"state\";\n\tprivate static final String SEEN\t= \"seen\";\n\tprivate static final String TARGET\t= \"target\";\n\tprivate static final String MAX_LVL\t= \"max_lvl\";\n\n\tprivate static final String ENEMY_ID\t= \"enemy_id\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.storeInBundle( bundle );\n\n\t\tif (state == SLEEPING) {\n\t\t\tbundle.put( STATE, Sleeping.TAG );\n\t\t} else if (state == WANDERING) {\n\t\t\tbundle.put( STATE, Wandering.TAG );\n\t\t} else if (state == HUNTING) {\n\t\t\tbundle.put( STATE, Hunting.TAG );\n\t\t} else if (state == FLEEING) {\n\t\t\tbundle.put( STATE, Fleeing.TAG );\n\t\t} else if (state == PASSIVE) {\n\t\t\tbundle.put( STATE, Passive.TAG );\n\t\t}\n\t\tbundle.put( SEEN, enemySeen );\n\t\tbundle.put( TARGET, target );\n\t\tbundle.put( MAX_LVL, maxLvl );\n\n\t\tif (enemy != null) {\n\t\t\tbundle.put(ENEMY_ID, enemy.id() );\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.restoreFromBundle( bundle );\n\n\t\tString state = bundle.getString( STATE );\n\t\tif (state.equals( Sleeping.TAG )) {\n\t\t\tthis.state = SLEEPING;\n\t\t} else if (state.equals( Wandering.TAG )) {\n\t\t\tthis.state = WANDERING;\n\t\t} else if (state.equals( Hunting.TAG )) {\n\t\t\tthis.state = HUNTING;\n\t\t} else if (state.equals( Fleeing.TAG )) {\n\t\t\tthis.state = FLEEING;\n\t\t} else if (state.equals( Passive.TAG )) {\n\t\t\tthis.state = PASSIVE;\n\t\t}\n\n\t\tenemySeen = bundle.getBoolean( SEEN );\n\n\t\ttarget = bundle.getInt( TARGET );\n\n\t\tif (bundle.contains(MAX_LVL)) maxLvl = bundle.getInt(MAX_LVL);\n\n\t\tif (bundle.contains(ENEMY_ID)) {\n\t\t\tenemyID = bundle.getInt(ENEMY_ID);\n\t\t}\n\n\t\t//no need to actually save this, must be false\n\t\tfirstAdded = false;\n\t}\n\n\t//mobs need to remember their targets after every actor is added\n\tpublic void restoreEnemy(){\n\t\tif (enemyID != -1 && enemy == null) enemy = (Char)Actor.findById(enemyID);\n\t}\n\t\n\tpublic CharSprite sprite() {\n\t\treturn Reflection.newInstance(spriteClass);\n\t}\n\t\n\t@Override\n\tprotected boolean act() {\n\t\t\n\t\tsuper.act();\n\t\t\n\t\tboolean justAlerted = alerted;\n\t\talerted = false;\n\t\t\n\t\tif (justAlerted){\n\t\t\tsprite.showAlert();\n\t\t} else {\n\t\t\tsprite.hideAlert();\n\t\t\tsprite.hideLost();\n\t\t}\n\t\t\n\t\tif (paralysed > 0) {\n\t\t\tenemySeen = false;\n\t\t\tspend( TICK );\n\t\t\treturn true;\n\t\t}\n\n\t\tif (buff(Terror.class) != null || buff(Dread.class) != null ){\n\t\t\tstate = FLEEING;\n\t\t}\n\t\t\n\t\tenemy = chooseEnemy();\n\t\t\n\t\tboolean enemyInFOV = enemy != null && enemy.isAlive() && fieldOfView[enemy.pos] && enemy.invisible <= 0;\n\n\t\t//prevents action, but still updates enemy seen status\n\t\tif (buff(Feint.AfterImage.FeintConfusion.class) != null){\n\t\t\tenemySeen = enemyInFOV;\n\t\t\tspend( TICK );\n\t\t\treturn true;\n\t\t}\n\n\t\treturn state.act( enemyInFOV, justAlerted );\n\t}\n\t\n\t//FIXME this is sort of a band-aid correction for allies needing more intelligent behaviour\n\tprotected boolean intelligentAlly = false;\n\t\n\tprotected Char chooseEnemy() {\n\n\t\tDread dread = buff( Dread.class );\n\t\tif (dread != null) {\n\t\t\tChar source = (Char)Actor.findById( dread.object );\n\t\t\tif (source != null) {\n\t\t\t\treturn source;\n\t\t\t}\n\t\t}\n\n\t\tTerror terror = buff( Terror.class );\n\t\tif (terror != null) {\n\t\t\tChar source = (Char)Actor.findById( terror.object );\n\t\t\tif (source != null) {\n\t\t\t\treturn source;\n\t\t\t}\n\t\t}\n\t\t\n\t\t//if we are an alert enemy, auto-hunt a target that is affected by aggression, even another enemy\n\t\tif (alignment == Alignment.ENEMY && state != PASSIVE && state != SLEEPING) {\n\t\t\tif (enemy != null && enemy.buff(StoneOfAggression.Aggression.class) != null){\n\t\t\t\tstate = HUNTING;\n\t\t\t\treturn enemy;\n\t\t\t}\n\t\t\tfor (Char ch : Actor.chars()) {\n\t\t\t\tif (ch != this && fieldOfView[ch.pos] &&\n\t\t\t\t\t\tch.buff(StoneOfAggression.Aggression.class) != null) {\n\t\t\t\t\tstate = HUNTING;\n\t\t\t\t\treturn ch;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//find a new enemy if..\n\t\tboolean newEnemy = false;\n\t\t//we have no enemy, or the current one is dead/missing\n\t\tif ( enemy == null || !enemy.isAlive() || !Actor.chars().contains(enemy) || state == WANDERING) {\n\t\t\tnewEnemy = true;\n\t\t//We are amoked and current enemy is the hero\n\t\t} else if (buff( Amok.class ) != null && enemy == Dungeon.hero) {\n\t\t\tnewEnemy = true;\n\t\t//We are charmed and current enemy is what charmed us\n\t\t} else if (buff(Charm.class) != null && buff(Charm.class).object == enemy.id()) {\n\t\t\tnewEnemy = true;\n\t\t}\n\n\t\t//additionally, if we are an ally, find a new enemy if...\n\t\tif (!newEnemy && alignment == Alignment.ALLY){\n\t\t\t//current enemy is also an ally\n\t\t\tif (enemy.alignment == Alignment.ALLY){\n\t\t\t\tnewEnemy = true;\n\t\t\t//current enemy is invulnerable\n\t\t\t} else if (enemy.isInvulnerable(getClass())){\n\t\t\t\tnewEnemy = true;\n\t\t\t}\n\t\t}\n\n\t\tif ( newEnemy ) {\n\n\t\t\tHashSet<Char> enemies = new HashSet<>();\n\n\t\t\t//if we are amoked...\n\t\t\tif ( buff(Amok.class) != null) {\n\t\t\t\t//try to find an enemy mob to attack first.\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs)\n\t\t\t\t\tif (mob.alignment == Alignment.ENEMY && mob != this\n\t\t\t\t\t\t\t&& fieldOfView[mob.pos] && mob.invisible <= 0) {\n\t\t\t\t\t\tenemies.add(mob);\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (enemies.isEmpty()) {\n\t\t\t\t\t//try to find ally mobs to attack second.\n\t\t\t\t\tfor (Mob mob : Dungeon.level.mobs)\n\t\t\t\t\t\tif (mob.alignment == Alignment.ALLY && mob != this\n\t\t\t\t\t\t\t\t&& fieldOfView[mob.pos] && mob.invisible <= 0) {\n\t\t\t\t\t\t\tenemies.add(mob);\n\t\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (enemies.isEmpty()) {\n\t\t\t\t\t\t//try to find the hero third\n\t\t\t\t\t\tif (fieldOfView[Dungeon.hero.pos] && Dungeon.hero.invisible <= 0) {\n\t\t\t\t\t\t\tenemies.add(Dungeon.hero);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t//if we are an ally...\n\t\t\t} else if ( alignment == Alignment.ALLY ) {\n\t\t\t\t//look for hostile mobs to attack\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs)\n\t\t\t\t\tif (mob.alignment == Alignment.ENEMY && fieldOfView[mob.pos]\n\t\t\t\t\t\t\t&& mob.invisible <= 0 && !mob.isInvulnerable(getClass()))\n\t\t\t\t\t\t//intelligent allies do not target mobs which are passive, wandering, or asleep\n\t\t\t\t\t\tif (!intelligentAlly ||\n\t\t\t\t\t\t\t\t(mob.state != mob.SLEEPING && mob.state != mob.PASSIVE && mob.state != mob.WANDERING)) {\n\t\t\t\t\t\t\tenemies.add(mob);\n\t\t\t\t\t\t}\n\t\t\t\t\n\t\t\t//if we are an enemy...\n\t\t\t} else if (alignment == Alignment.ENEMY) {\n\t\t\t\t//look for ally mobs to attack\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs)\n\t\t\t\t\tif (mob.alignment == Alignment.ALLY && fieldOfView[mob.pos] && mob.invisible <= 0)\n\t\t\t\t\t\tenemies.add(mob);\n\n\t\t\t\t//and look for the hero\n\t\t\t\tif (fieldOfView[Dungeon.hero.pos] && Dungeon.hero.invisible <= 0) {\n\t\t\t\t\tenemies.add(Dungeon.hero);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\n\t\t\t//do not target anything that's charming us\n\t\t\tCharm charm = buff( Charm.class );\n\t\t\tif (charm != null){\n\t\t\t\tChar source = (Char)Actor.findById( charm.object );\n\t\t\t\tif (source != null && enemies.contains(source) && enemies.size() > 1){\n\t\t\t\t\tenemies.remove(source);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//neutral characters in particular do not choose enemies.\n\t\t\tif (enemies.isEmpty()){\n\t\t\t\treturn null;\n\t\t\t} else {\n\t\t\t\t//go after the closest potential enemy, preferring enemies that can be reached/attacked, and the hero if two are equidistant\n\t\t\t\tPathFinder.buildDistanceMap(pos, Dungeon.findPassable(this, Dungeon.level.passable, fieldOfView, true));\n\t\t\t\tChar closest = null;\n\n\t\t\t\tfor (Char curr : enemies){\n\t\t\t\t\tif (closest == null){\n\t\t\t\t\t\tclosest = curr;\n\t\t\t\t\t} else if (canAttack(closest) && !canAttack(curr)){\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t} else if ((canAttack(curr) && !canAttack(closest))\n\t\t\t\t\t\t\t|| (PathFinder.distance[curr.pos] < PathFinder.distance[closest.pos])){\n\t\t\t\t\t\tclosest = curr;\n\t\t\t\t\t} else if ( curr == Dungeon.hero &&\n\t\t\t\t\t\t\t(PathFinder.distance[curr.pos] == PathFinder.distance[closest.pos]) || (canAttack(curr) && canAttack(closest))){\n\t\t\t\t\t\tclosest = curr;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//if we were going to target the hero, but an afterimage exists, target that instead\n\t\t\t\tif (closest == Dungeon.hero){\n\t\t\t\t\tfor (Char ch : enemies){\n\t\t\t\t\t\tif (ch instanceof Feint.AfterImage){\n\t\t\t\t\t\t\tclosest = ch;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn closest;\n\t\t\t}\n\n\t\t} else\n\t\t\treturn enemy;\n\t}\n\t\n\t@Override\n\tpublic boolean add( Buff buff ) {\n\t\tif (super.add( buff )) {\n\t\t\tif (buff instanceof Amok || buff instanceof AllyBuff) {\n\t\t\t\tstate = HUNTING;\n\t\t\t} else if (buff instanceof Terror || buff instanceof Dread) {\n\t\t\t\tstate = FLEEING;\n\t\t\t} else if (buff instanceof Sleep) {\n\t\t\t\tstate = SLEEPING;\n\t\t\t\tpostpone(Sleep.SWS);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic boolean remove( Buff buff ) {\n\t\tif (super.remove( buff )) {\n\t\t\tif ((buff instanceof Terror && buff(Dread.class) == null)\n\t\t\t\t\t|| (buff instanceof Dread && buff(Terror.class) == null)) {\n\t\t\t\tif (enemySeen) {\n\t\t\t\t\tsprite.showStatus(CharSprite.NEGATIVE, Messages.get(this, \"rage\"));\n\t\t\t\t\tstate = HUNTING;\n\t\t\t\t} else {\n\t\t\t\t\tstate = WANDERING;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected boolean canAttack( Char enemy ) {\n\t\tif (Dungeon.level.adjacent( pos, enemy.pos )){\n\t\t\treturn true;\n\t\t}\n\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\tif (buff.canAttackWithExtraReach( enemy )){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate boolean cellIsPathable( int cell ){\n\t\tif (!Dungeon.level.passable[cell]){\n\t\t\tif (flying || buff(Amok.class) != null){\n\t\t\t\tif (!Dungeon.level.avoid[cell]){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (Char.hasProp(this, Char.Property.LARGE) && !Dungeon.level.openSpace[cell]){\n\t\t\treturn false;\n\t\t}\n\t\tif (Actor.findChar(cell) != null){\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tprotected boolean getCloser( int target ) {\n\t\t\n\t\tif (rooted || target == pos) {\n\t\t\treturn false;\n\t\t}\n\n\t\tint step = -1;\n\n\t\tif (Dungeon.level.adjacent( pos, target )) {\n\n\t\t\tpath = null;\n\n\t\t\tif (cellIsPathable(target)) {\n\t\t\t\tstep = target;\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tboolean newPath = false;\n\t\t\t//scrap the current path if it's empty, no longer connects to the current location\n\t\t\t//or if it's extremely inefficient and checking again may result in a much better path\n\t\t\tif (path == null || path.isEmpty()\n\t\t\t\t\t|| !Dungeon.level.adjacent(pos, path.getFirst())\n\t\t\t\t\t|| path.size() > 2*Dungeon.level.distance(pos, target))\n\t\t\t\tnewPath = true;\n\t\t\telse if (path.getLast() != target) {\n\t\t\t\t//if the new target is adjacent to the end of the path, adjust for that\n\t\t\t\t//rather than scrapping the whole path.\n\t\t\t\tif (Dungeon.level.adjacent(target, path.getLast())) {\n\t\t\t\t\tint last = path.removeLast();\n\n\t\t\t\t\tif (path.isEmpty()) {\n\n\t\t\t\t\t\t//shorten for a closer one\n\t\t\t\t\t\tif (Dungeon.level.adjacent(target, pos)) {\n\t\t\t\t\t\t\tpath.add(target);\n\t\t\t\t\t\t//extend the path for a further target\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpath.add(last);\n\t\t\t\t\t\t\tpath.add(target);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//if the new target is simply 1 earlier in the path shorten the path\n\t\t\t\t\t\tif (path.getLast() == target) {\n\n\t\t\t\t\t\t//if the new target is closer/same, need to modify end of path\n\t\t\t\t\t\t} else if (Dungeon.level.adjacent(target, path.getLast())) {\n\t\t\t\t\t\t\tpath.add(target);\n\n\t\t\t\t\t\t//if the new target is further away, need to extend the path\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpath.add(last);\n\t\t\t\t\t\t\tpath.add(target);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tnewPath = true;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t//checks if the next cell along the current path can be stepped into\n\t\t\tif (!newPath) {\n\t\t\t\tint nextCell = path.removeFirst();\n\t\t\t\tif (!cellIsPathable(nextCell)) {\n\n\t\t\t\t\tnewPath = true;\n\t\t\t\t\t//If the next cell on the path can't be moved into, see if there is another cell that could replace it\n\t\t\t\t\tif (!path.isEmpty()) {\n\t\t\t\t\t\tfor (int i : PathFinder.NEIGHBOURS8) {\n\t\t\t\t\t\t\tif (Dungeon.level.adjacent(pos, nextCell + i) && Dungeon.level.adjacent(nextCell + i, path.getFirst())) {\n\t\t\t\t\t\t\t\tif (cellIsPathable(nextCell+i)){\n\t\t\t\t\t\t\t\t\tpath.addFirst(nextCell+i);\n\t\t\t\t\t\t\t\t\tnewPath = false;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tpath.addFirst(nextCell);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//generate a new path\n\t\t\tif (newPath) {\n\t\t\t\t//If we aren't hunting, always take a full path\n\t\t\t\tPathFinder.Path full = Dungeon.findPath(this, target, Dungeon.level.passable, fieldOfView, true);\n\t\t\t\tif (state != HUNTING){\n\t\t\t\t\tpath = full;\n\t\t\t\t} else {\n\t\t\t\t\t//otherwise, check if other characters are forcing us to take a very slow route\n\t\t\t\t\t// and don't try to go around them yet in response, basically assume their blockage is temporary\n\t\t\t\t\tPathFinder.Path ignoreChars = Dungeon.findPath(this, target, Dungeon.level.passable, fieldOfView, false);\n\t\t\t\t\tif (ignoreChars != null && (full == null || full.size() > 2*ignoreChars.size())){\n\t\t\t\t\t\t//check if first cell of shorter path is valid. If it is, use new shorter path. Otherwise do nothing and wait.\n\t\t\t\t\t\tpath = ignoreChars;\n\t\t\t\t\t\tif (!cellIsPathable(ignoreChars.getFirst())) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpath = full;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (path != null) {\n\t\t\t\tstep = path.removeFirst();\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (step != -1) {\n\t\t\tmove( step );\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprotected boolean getFurther( int target ) {\n\t\tif (rooted || target == pos) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tint step = Dungeon.flee( this, target, Dungeon.level.passable, fieldOfView, true );\n\t\tif (step != -1) {\n\t\t\tmove( step );\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void updateSpriteState() {\n\t\tsuper.updateSpriteState();\n\t\tif (Dungeon.hero.buff(TimekeepersHourglass.timeFreeze.class) != null\n\t\t\t\t|| Dungeon.hero.buff(Swiftthistle.TimeBubble.class) != null)\n\t\t\tsprite.add( CharSprite.State.PARALYSED );\n\t}\n\t\n\tpublic float attackDelay() {\n\t\tfloat delay = 1f;\n\t\tif ( buff(Adrenaline.class) != null) delay /= 1.5f;\n\t\treturn delay;\n\t}\n\t\n\tprotected boolean doAttack( Char enemy ) {\n\t\t\n\t\tif (sprite != null && (sprite.visible || enemy.sprite.visible)) {\n\t\t\tsprite.attack( enemy.pos );\n\t\t\treturn false;\n\t\t\t\n\t\t} else {\n\t\t\tattack( enemy );\n\t\t\tInvisibility.dispel(this);\n\t\t\tspend( attackDelay() );\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void onAttackComplete() {\n\t\tattack( enemy );\n\t\tInvisibility.dispel(this);\n\t\tspend( attackDelay() );\n\t\tsuper.onAttackComplete();\n\t}\n\t\n\t@Override\n\tpublic int defenseSkill( Char enemy ) {\n\t\tif ( !surprisedBy(enemy)\n\t\t\t\t&& paralysed == 0\n\t\t\t\t&& !(alignment == Alignment.ALLY && enemy == Dungeon.hero)) {\n\t\t\treturn this.defenseSkill;\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic int defenseProc( Char enemy, int damage ) {\n\t\t\n\t\tif (enemy instanceof Hero\n\t\t\t\t&& ((Hero) enemy).belongings.attackingWeapon() instanceof MissileWeapon){\n\t\t\tStatistics.thrownAttacks++;\n\t\t\tBadges.validateHuntressUnlock();\n\t\t}\n\t\t\n\t\tif (surprisedBy(enemy)) {\n\t\t\tStatistics.sneakAttacks++;\n\t\t\tBadges.validateRogueUnlock();\n\t\t\t//TODO this is somewhat messy, it would be nicer to not have to manually handle delays here\n\t\t\t// playing the strong hit sound might work best as another property of weapon?\n\t\t\tif (Dungeon.hero.belongings.attackingWeapon() instanceof SpiritBow.SpiritArrow\n\t\t\t\t|| Dungeon.hero.belongings.attackingWeapon() instanceof Dart){\n\t\t\t\tSample.INSTANCE.playDelayed(Assets.Sounds.HIT_STRONG, 0.125f);\n\t\t\t} else {\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_STRONG);\n\t\t\t}\n\t\t\tif (enemy.buff(Preparation.class) != null) {\n\t\t\t\tWound.hit(this);\n\t\t\t} else {\n\t\t\t\tSurprise.hit(this);\n\t\t\t}\n\t\t}\n\n\t\t//if attacked by something else than current target, and that thing is closer, switch targets\n\t\tif (this.enemy == null\n\t\t\t\t|| (enemy != this.enemy && (Dungeon.level.distance(pos, enemy.pos) < Dungeon.level.distance(pos, this.enemy.pos)))) {\n\t\t\taggro(enemy);\n\t\t\ttarget = enemy.pos;\n\t\t}\n\n\t\tif (buff(SoulMark.class) != null) {\n\t\t\tint restoration = Math.min(damage, HP+shielding());\n\t\t\t\n\t\t\t//physical damage that doesn't come from the hero is less effective\n\t\t\tif (enemy != Dungeon.hero){\n\t\t\t\trestoration = Math.round(restoration * 0.4f*Dungeon.hero.pointsInTalent(Talent.SOUL_SIPHON)/3f);\n\t\t\t}\n\t\t\tif (restoration > 0) {\n\t\t\t\tBuff.affect(Dungeon.hero, Hunger.class).affectHunger(restoration*Dungeon.hero.pointsInTalent(Talent.SOUL_EATER)/3f);\n\t\t\t\tDungeon.hero.HP = (int) Math.ceil(Math.min(Dungeon.hero.HT, Dungeon.hero.HP + (restoration * 0.4f)));\n\t\t\t\tDungeon.hero.sprite.emitter().burst(Speck.factory(Speck.HEALING), 1);\n\t\t\t}\n\t\t}\n\n\t\tif (buff(BookOfTransfusion.VampiricMark.class) != null) {\n\t\t\tBookOfTransfusion.VampiricMark.proc(enemy, Math.min(damage, HP+shielding()));\n\t\t}\n\n\t\treturn super.defenseProc(enemy, damage);\n\t}\n\n\t@Override\n\tpublic float speed() {\n\t\treturn super.speed() * AscensionChallenge.enemySpeedModifier(this);\n\t}\n\n\tpublic final boolean surprisedBy( Char enemy ){\n\t\treturn surprisedBy( enemy, true);\n\t}\n\n\tpublic boolean surprisedBy( Char enemy, boolean attacking ){\n\t\treturn enemy == Dungeon.hero\n\t\t\t\t&& (enemy.invisible > 0 || !enemySeen || (fieldOfView != null && fieldOfView.length == Dungeon.level.length() && !fieldOfView[enemy.pos]))\n\t\t\t\t&& (!attacking || enemy.canSurpriseAttack());\n\t}\n\n\tpublic void aggro( Char ch ) {\n\t\tenemy = ch;\n\t\tif (state != PASSIVE){\n\t\t\tstate = HUNTING;\n\t\t}\n\t}\n\n\tpublic void clearEnemy(){\n\t\tenemy = null;\n\t\tenemySeen = false;\n\t\tif (state == HUNTING) state = WANDERING;\n\t}\n\t\n\tpublic boolean isTargeting( Char ch){\n\t\treturn enemy == ch;\n\t}\n\n\t@Override\n\tpublic void damage( int dmg, Object src ) {\n\n\t\tif (state == SLEEPING) {\n\t\t\tstate = WANDERING;\n\t\t}\n\t\tif (state != HUNTING && !(src instanceof Corruption)) {\n\t\t\talerted = true;\n\t\t}\n\t\t\n\t\tsuper.damage( dmg, src );\n\t}\n\t\n\t\n\t@Override\n\tpublic void destroy() {\n\t\t\n\t\tsuper.destroy();\n\t\t\n\t\tDungeon.level.mobs.remove( this );\n\n\t\tif (Dungeon.hero.buff(MindVision.class) != null){\n\t\t\tDungeon.observe();\n\t\t\tGameScene.updateFog(pos, 2);\n\t\t}\n\n\t\tif (Dungeon.hero.isAlive()) {\n\t\t\t\n\t\t\tif (alignment == Alignment.ENEMY) {\n\t\t\t\tStatistics.enemiesSlain++;\n\t\t\t\tBadges.validateMonstersSlain();\n\t\t\t\tStatistics.qualifiedForNoKilling = false;\n\n\t\t\t\tAscensionChallenge.processEnemyKill(this);\n\t\t\t\t\n\t\t\t\tint exp = Dungeon.hero.lvl <= maxLvl ? EXP : 0;\n\n\t\t\t\t//during ascent, under-levelled enemies grant 10 xp each until level 30\n\t\t\t\t// after this enemy kills which reduce the amulet curse still grant 10 effective xp\n\t\t\t\t// for the purposes of on-exp effects, see AscensionChallenge.processEnemyKill\n\t\t\t\tif (Dungeon.hero.buff(AscensionChallenge.class) != null &&\n\t\t\t\t\t\texp == 0 && maxLvl > 0 && EXP > 0 && Dungeon.hero.lvl < Hero.MAX_LEVEL){\n\t\t\t\t\texp = Math.round(10 * spawningWeight());\n\t\t\t\t}\n\n\t\t\t\tif (exp > 0) {\n\t\t\t\t\tDungeon.hero.sprite.showStatus(CharSprite.POSITIVE, Messages.get(this, \"exp\", exp));\n\t\t\t\t}\n\t\t\t\tDungeon.hero.earnExp(exp, getClass());\n\n\t\t\t\tif (Dungeon.hero.subClass == HeroSubClass.MONK){\n\t\t\t\t\tBuff.affect(Dungeon.hero, MonkEnergy.class).gainEnergy(this);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void die( Object cause ) {\n\n\t\tif (cause == Chasm.class){\n\t\t\t//50% chance to round up, 50% to round down\n\t\t\tif (EXP % 2 == 1) EXP += Random.Int(2);\n\t\t\tEXP /= 2;\n\t\t}\n\n\t\tif (alignment == Alignment.ENEMY){\n\t\t\trollToDropLoot();\n\n\t\t\tif (cause == Dungeon.hero || cause instanceof Weapon || cause instanceof Weapon.Enchantment){\n\t\t\t\tif (Dungeon.hero.hasTalent(Talent.LETHAL_MOMENTUM)\n\t\t\t\t\t\t&& Random.Float() < 0.34f + 0.33f* Dungeon.hero.pointsInTalent(Talent.LETHAL_MOMENTUM)){\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.LethalMomentumTracker.class, 0f);\n\t\t\t\t}\n\t\t\t\tif (Dungeon.hero.heroClass != HeroClass.DUELIST\n\t\t\t\t\t\t&& Dungeon.hero.hasTalent(Talent.LETHAL_HASTE)\n\t\t\t\t\t\t&& Dungeon.hero.buff(Talent.LethalHasteCooldown.class) == null){\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.LethalHasteCooldown.class, 100f);\n\t\t\t\t\tBuff.affect(Dungeon.hero, Haste.class, 1.67f + Dungeon.hero.pointsInTalent(Talent.LETHAL_HASTE));\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tif (Dungeon.level.map[pos] != Terrain.PIT && hero.hasTalent(Talent.ENERGY_REMAINS)) {\n\t\t\tint chance = Random.Int(6);\n\t\t\tint point = Dungeon.hero.pointsInTalent(Talent.ENERGY_REMAINS);\n\t\t\tswitch (chance) {\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0:\n\t\t\t\t\tif (point >= 1) {\n\t\t\t\t\t\tBuff.affect(hero, WandRechargeArea.class).setup(pos);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tif (point >= 2) {\n\t\t\t\t\t\tBuff.affect(hero, ArtifactRechargeArea.class).setup(pos);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tif (point >= 3) {\n\t\t\t\t\t\tBuff.affect(hero, BarrierRechargeArea.class).setup(pos);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (cause == hero) {\n\t\t\tif (Dungeon.hero.hasTalent(Talent.LETHAL_RAGE)){\n\t\t\t\tBerserk berserk = Buff.affect(hero, Berserk.class);\n\t\t\t\tberserk.add(0.067f*Dungeon.hero.pointsInTalent(Talent.LETHAL_RAGE));\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.BULLET_COLLECT)) {\n\t\t\t\tBulletItem bullet = new BulletItem();\n\t\t\t\tbullet.quantity(hero.pointsInTalent(Talent.BULLET_COLLECT));\n\t\t\t\tDungeon.level.drop(bullet, pos).sprite.drop();\n\t\t\t}\n\n\t\t\tif (hero.hasTalent(Talent.SOUL_BULLET)) {\n\t\t\t\tBuff.affect(hero, InfiniteBullet.class, hero.pointsInTalent(Talent.SOUL_BULLET));\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.hero.isAlive() && !Dungeon.level.heroFOV[pos]) {\n\t\t\tGLog.i( Messages.get(this, \"died\") );\n\t\t}\n\n\t\tboolean soulMarked = buff(SoulMark.class) != null;\n\n\t\tsuper.die( cause );\n\n\t\tif (!(this instanceof Wraith)\n\t\t\t\t&& soulMarked\n\t\t\t\t&& Random.Float() < (0.4f*Dungeon.hero.pointsInTalent(Talent.NECROMANCERS_MINIONS)/3f)){\n\t\t\tWraith w = Wraith.spawnAt(pos, false);\n\t\t\tif (w != null) {\n\t\t\t\tBuff.affect(w, Corruption.class);\n\t\t\t\tif (Dungeon.level.heroFOV[pos]) {\n\t\t\t\t\tCellEmitter.get(pos).burst(ShadowParticle.CURSE, 6);\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.CURSED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (this instanceof Wraith && Dungeon.isChallenged(Challenges.CURSED_DUNGEON) && Random.Int(5) < 1) {\n\t\t\tWraith w = Wraith.spawnAt(pos, false);\n\t\t\tif (w != null) {\n\t\t\t\tBuff.affect(w, Corruption.class);\n\t\t\t\tif (Dungeon.level.heroFOV[pos]) {\n\t\t\t\t\tCellEmitter.get(pos).burst(ShadowParticle.CURSE, 6);\n\t\t\t\t\tSample.INSTANCE.play(Assets.Sounds.CURSED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic float lootChance(){\n\t\tfloat lootChance = this.lootChance;\n\n\t\tfloat dropBonus = RingOfWealth.dropChanceMultiplier( Dungeon.hero );\n\n\t\tTalent.BountyHunterTracker bhTracker = Dungeon.hero.buff(Talent.BountyHunterTracker.class);\n\t\tif (bhTracker != null){\n\t\t\tPreparation prep = Dungeon.hero.buff(Preparation.class);\n\t\t\tif (prep != null){\n\t\t\t\t// 2/4/8/16% per prep level, multiplied by talent points\n\t\t\t\tfloat bhBonus = 0.02f * (float)Math.pow(2, prep.attackLevel()-1);\n\t\t\t\tbhBonus *= Dungeon.hero.pointsInTalent(Talent.BOUNTY_HUNTER);\n\t\t\t\tdropBonus += bhBonus;\n\t\t\t}\n\t\t}\n\n\t\treturn lootChance * dropBonus;\n\t}\n\t\n\tpublic void rollToDropLoot(){\n\t\tif (Dungeon.hero.lvl > maxLvl + 2) return;\n\n\t\tMasterThievesArmband.StolenTracker stolen = buff(MasterThievesArmband.StolenTracker.class);\n\t\tif (stolen == null || !stolen.itemWasStolen()) {\n\t\t\tif (Random.Float() < lootChance()) {\n\t\t\t\tItem loot = createLoot();\n\t\t\t\tif (loot != null) {\n\t\t\t\t\tDungeon.level.drop(loot, pos).sprite.drop();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t//ring of wealth logic\n\t\tif (Ring.getBuffedBonus(Dungeon.hero, RingOfWealth.Wealth.class) > 0) {\n\t\t\tint rolls = 1;\n\t\t\tif (properties.contains(Property.BOSS)) rolls = 15;\n\t\t\telse if (properties.contains(Property.MINIBOSS)) rolls = 5;\n\t\t\tArrayList<Item> bonus = RingOfWealth.tryForBonusDrop(Dungeon.hero, rolls);\n\t\t\tif (bonus != null && !bonus.isEmpty()) {\n\t\t\t\tfor (Item b : bonus) Dungeon.level.drop(b, pos).sprite.drop();\n\t\t\t\tRingOfWealth.showFlareForBonusDrop(sprite);\n\t\t\t}\n\t\t}\n\t\t\n\t\t//lucky enchant logic\n\t\tif (buff(Lucky.LuckProc.class) != null){\n\t\t\tDungeon.level.drop(buff(Lucky.LuckProc.class).genLoot(), pos).sprite.drop();\n\t\t\tLucky.showFlare(sprite);\n\t\t}\n\n\t\t//soul eater talent\n\t\tif (buff(SoulMark.class) != null &&\n\t\t\t\tRandom.Int(10) < Dungeon.hero.pointsInTalent(Talent.SOUL_EATER)){\n\t\t\tTalent.onFoodEaten(Dungeon.hero, 0, null);\n\t\t}\n\n\t}\n\t\n\tprotected Object loot = null;\n\tprotected float lootChance = 0;\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic Item createLoot() {\n\t\tItem item;\n\t\tif (loot instanceof Generator.Category) {\n\n\t\t\titem = Generator.randomUsingDefaults( (Generator.Category)loot );\n\n\t\t} else if (loot instanceof Class<?>) {\n\n\t\t\titem = Generator.random( (Class<? extends Item>)loot );\n\n\t\t} else {\n\n\t\t\titem = (Item)loot;\n\n\t\t}\n\t\treturn item;\n\t}\n\n\t//how many mobs this one should count as when determining spawning totals\n\tpublic float spawningWeight(){\n\t\treturn 1;\n\t}\n\t\n\tpublic boolean reset() {\n\t\treturn false;\n\t}\n\t\n\tpublic void beckon( int cell ) {\n\t\t\n\t\tnotice();\n\t\t\n\t\tif (state != HUNTING && state != FLEEING) {\n\t\t\tstate = WANDERING;\n\t\t}\n\t\ttarget = cell;\n\t}\n\t\n\tpublic String description() {\n\t\treturn Messages.get(this, \"desc\");\n\t}\n\n\tpublic String info(){\n\t\tString desc = description();\n\n\t\tfor (Buff b : buffs(ChampionEnemy.class)){\n\t\t\tdesc += \"\\n\\n_\" + Messages.titleCase(b.name()) + \"_\\n\" + b.desc();\n\t\t}\n\n\t\treturn desc;\n\t}\n\t\n\tpublic void notice() {\n\t\tsprite.showAlert();\n\t}\n\t\n\tpublic void yell( String str ) {\n\t\tGLog.newLine();\n\t\tGLog.n( \"%s: \\\"%s\\\" \", Messages.titleCase(name()), str );\n\t}\n\n\tpublic interface AiState {\n\t\tboolean act( boolean enemyInFOV, boolean justAlerted );\n\t}\n\n\tprotected class Sleeping implements AiState {\n\n\t\tpublic static final String TAG\t= \"SLEEPING\";\n\n\t\t@Override\n\t\tpublic boolean act( boolean enemyInFOV, boolean justAlerted ) {\n\n\t\t\t//debuffs cause mobs to wake as well\n\t\t\tfor (Buff b : buffs()){\n\t\t\t\tif (b.type == Buff.buffType.NEGATIVE){\n\t\t\t\t\tawaken(enemyInFOV);\n\t\t\t\t\tif (state == SLEEPING){\n\t\t\t\t\t\tspend(TICK); //wait if we can't wake up for some reason\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (enemyInFOV) {\n\n\t\t\t\tfloat enemyStealth = enemy.stealth();\n\n\t\t\t\tif (enemy instanceof Hero && ((Hero) enemy).hasTalent(Talent.SILENT_STEPS)){\n\t\t\t\t\tif (Dungeon.level.distance(pos, enemy.pos) >= 4 - ((Hero) enemy).pointsInTalent(Talent.SILENT_STEPS)) {\n\t\t\t\t\t\tenemyStealth = Float.POSITIVE_INFINITY;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (Random.Float( distance( enemy ) + enemyStealth ) < 1) {\n\t\t\t\t\tawaken(enemyInFOV);\n\t\t\t\t\tif (state == SLEEPING){\n\t\t\t\t\t\tspend(TICK); //wait if we can't wake up for some reason\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tenemySeen = false;\n\t\t\tspend( TICK );\n\n\t\t\treturn true;\n\t\t}\n\n\t\tprotected void awaken( boolean enemyInFOV ){\n\t\t\tif (enemyInFOV) {\n\t\t\t\tenemySeen = true;\n\t\t\t\tnotice();\n\t\t\t\tstate = HUNTING;\n\t\t\t\ttarget = enemy.pos;\n\t\t\t} else {\n\t\t\t\tnotice();\n\t\t\t\tstate = WANDERING;\n\t\t\t\ttarget = Dungeon.level.randomDestination( Mob.this );\n\t\t\t}\n\n\t\t\tif (alignment == Alignment.ENEMY && Dungeon.isChallenged(Challenges.SWARM_INTELLIGENCE)) {\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\t\t\tif (mob.paralysed <= 0\n\t\t\t\t\t\t\t&& Dungeon.level.distance(pos, mob.pos) <= 8\n\t\t\t\t\t\t\t&& mob.state != mob.HUNTING) {\n\t\t\t\t\t\tmob.beckon(target);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tspend(TIME_TO_WAKE_UP);\n\t\t}\n\t}\n\n\tprotected class Wandering implements AiState {\n\n\t\tpublic static final String TAG\t= \"WANDERING\";\n\n\t\t@Override\n\t\tpublic boolean act( boolean enemyInFOV, boolean justAlerted ) {\n\t\t\tif (enemyInFOV && (justAlerted || Random.Float( distance( enemy ) / 2f + enemy.stealth() ) < 1)) {\n\n\t\t\t\treturn noticeEnemy();\n\n\t\t\t} else {\n\n\t\t\t\treturn continueWandering();\n\n\t\t\t}\n\t\t}\n\t\t\n\t\tprotected boolean noticeEnemy(){\n\t\t\tenemySeen = true;\n\t\t\t\n\t\t\tnotice();\n\t\t\talerted = true;\n\t\t\tstate = HUNTING;\n\t\t\ttarget = enemy.pos;\n\t\t\t\n\t\t\tif (alignment == Alignment.ENEMY && Dungeon.isChallenged( Challenges.SWARM_INTELLIGENCE )) {\n\t\t\t\tfor (Mob mob : Dungeon.level.mobs) {\n\t\t\t\t\tif (mob.paralysed <= 0\n\t\t\t\t\t\t\t&& Dungeon.level.distance(pos, mob.pos) <= 8\n\t\t\t\t\t\t\t&& mob.state != mob.HUNTING) {\n\t\t\t\t\t\tmob.beckon( target );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\tprotected boolean continueWandering(){\n\t\t\tenemySeen = false;\n\t\t\t\n\t\t\tint oldPos = pos;\n\t\t\tif (target != -1 && getCloser( target )) {\n\t\t\t\tspend( 1 / speed() );\n\t\t\t\treturn moveSprite( oldPos, pos );\n\t\t\t} else {\n\t\t\t\ttarget = randomDestination();\n\t\t\t\tspend( TICK );\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t}\n\n\t\tprotected int randomDestination(){\n\t\t\treturn Dungeon.level.randomDestination( Mob.this );\n\t\t}\n\t\t\n\t}\n\n\tprotected class Hunting implements AiState {\n\n\t\tpublic static final String TAG\t= \"HUNTING\";\n\n\t\t//prevents rare infinite loop cases\n\t\tprivate boolean recursing = false;\n\n\t\t@Override\n\t\tpublic boolean act( boolean enemyInFOV, boolean justAlerted ) {\n\t\t\tenemySeen = enemyInFOV;\n\t\t\tif (enemyInFOV && !isCharmedBy( enemy ) && canAttack( enemy )) {\n\n\t\t\t\ttarget = enemy.pos;\n\t\t\t\treturn doAttack( enemy );\n\n\t\t\t} else {\n\n\t\t\t\tif (enemyInFOV) {\n\t\t\t\t\ttarget = enemy.pos;\n\t\t\t\t} else if (enemy == null) {\n\t\t\t\t\tsprite.showLost();\n\t\t\t\t\tstate = WANDERING;\n\t\t\t\t\ttarget = Dungeon.level.randomDestination( Mob.this );\n\t\t\t\t\tspend( TICK );\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tint oldPos = pos;\n\t\t\t\tif (target != -1 && getCloser( target )) {\n\t\t\t\t\t\n\t\t\t\t\tspend( 1 / speed() );\n\t\t\t\t\treturn moveSprite( oldPos, pos );\n\n\t\t\t\t} else {\n\n\t\t\t\t\t//if moving towards an enemy isn't possible, try to switch targets to another enemy that is closer\n\t\t\t\t\t//unless we have already done that and still can't move toward them, then move on.\n\t\t\t\t\tif (!recursing) {\n\t\t\t\t\t\tChar oldEnemy = enemy;\n\t\t\t\t\t\tenemy = null;\n\t\t\t\t\t\tenemy = chooseEnemy();\n\t\t\t\t\t\tif (enemy != null && enemy != oldEnemy) {\n\t\t\t\t\t\t\trecursing = true;\n\t\t\t\t\t\t\tboolean result = act(enemyInFOV, justAlerted);\n\t\t\t\t\t\t\trecursing = false;\n\t\t\t\t\t\t\treturn result;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tspend( TICK );\n\t\t\t\t\tif (!enemyInFOV) {\n\t\t\t\t\t\tsprite.showLost();\n\t\t\t\t\t\tstate = WANDERING;\n\t\t\t\t\t\ttarget = Dungeon.level.randomDestination( Mob.this );\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected class Fleeing implements AiState {\n\n\t\tpublic static final String TAG\t= \"FLEEING\";\n\n\t\t@Override\n\t\tpublic boolean act( boolean enemyInFOV, boolean justAlerted ) {\n\t\t\tenemySeen = enemyInFOV;\n\t\t\t//triggers escape logic when 0-dist rolls a 6 or greater.\n\t\t\tif (enemy == null || !enemyInFOV && 1 + Random.Int(Dungeon.level.distance(pos, target)) >= 6){\n\t\t\t\tescaped();\n\t\t\t\tif (state != FLEEING){\n\t\t\t\t\tspend( TICK );\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\n\t\t\t//if enemy isn't in FOV, keep running from their previous position.\n\t\t\t} else if (enemyInFOV) {\n\t\t\t\ttarget = enemy.pos;\n\t\t\t}\n\n\t\t\tint oldPos = pos;\n\t\t\tif (target != -1 && getFurther( target )) {\n\n\t\t\t\tspend( 1 / speed() );\n\t\t\t\treturn moveSprite( oldPos, pos );\n\n\t\t\t} else {\n\n\t\t\t\tspend( TICK );\n\t\t\t\tnowhereToRun();\n\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tprotected void escaped(){\n\t\t\t//does nothing by default, some enemies have special logic for this\n\t\t}\n\n\t\t//enemies will turn and fight if they have nowhere to run and aren't affect by terror\n\t\tprotected void nowhereToRun() {\n\t\t\tif (buff( Terror.class ) == null\n\t\t\t\t\t&& buffs( AllyBuff.class ).isEmpty()\n\t\t\t\t\t&& buff( Dread.class ) == null) {\n\t\t\t\tif (enemySeen) {\n\t\t\t\t\tsprite.showStatus(CharSprite.NEGATIVE, Messages.get(Mob.class, \"rage\"));\n\t\t\t\t\tstate = HUNTING;\n\t\t\t\t} else {\n\t\t\t\t\tstate = WANDERING;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected class Passive implements AiState {\n\n\t\tpublic static final String TAG\t= \"PASSIVE\";\n\n\t\t@Override\n\t\tpublic boolean act( boolean enemyInFOV, boolean justAlerted ) {\n\t\t\tenemySeen = enemyInFOV;\n\t\t\tspend( TICK );\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\t\n\tprivate static ArrayList<Mob> heldAllies = new ArrayList<>();\n\n\tpublic static void holdAllies( Level level ){\n\t\tholdAllies(level, Dungeon.hero.pos);\n\t}\n\n\tpublic static void holdAllies( Level level, int holdFromPos ){\n\t\theldAllies.clear();\n\t\tfor (Mob mob : level.mobs.toArray( new Mob[0] )) {\n\t\t\t//preserve directable allies no matter where they are\n\t\t\tif (mob instanceof DirectableAlly) {\n\t\t\t\t((DirectableAlly) mob).clearDefensingPos();\n\t\t\t\tlevel.mobs.remove( mob );\n\t\t\t\theldAllies.add(mob);\n\t\t\t\t\n\t\t\t//preserve intelligent allies if they are near the hero\n\t\t\t} else if (mob.alignment == Alignment.ALLY\n\t\t\t\t\t&& mob.intelligentAlly\n\t\t\t\t\t&& Dungeon.level.distance(holdFromPos, mob.pos) <= 5){\n\t\t\t\tlevel.mobs.remove( mob );\n\t\t\t\theldAllies.add(mob);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void restoreAllies( Level level, int pos ){\n\t\trestoreAllies(level, pos, -1);\n\t}\n\n\tpublic static void restoreAllies( Level level, int pos, int gravitatePos ){\n\t\tif (!heldAllies.isEmpty()){\n\t\t\t\n\t\t\tArrayList<Integer> candidatePositions = new ArrayList<>();\n\t\t\tfor (int i : PathFinder.NEIGHBOURS8) {\n\t\t\t\tif (!Dungeon.level.solid[i+pos] && level.findMob(i+pos) == null){\n\t\t\t\t\tcandidatePositions.add(i+pos);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//gravitate pos sets a preferred location for allies to be closer to\n\t\t\tif (gravitatePos == -1) {\n\t\t\t\tCollections.shuffle(candidatePositions);\n\t\t\t} else {\n\t\t\t\tCollections.sort(candidatePositions, new Comparator<Integer>() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic int compare(Integer t1, Integer t2) {\n\t\t\t\t\t\treturn Dungeon.level.distance(gravitatePos, t1) -\n\t\t\t\t\t\t\t\tDungeon.level.distance(gravitatePos, t2);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\t\n\t\t\tfor (Mob ally : heldAllies) {\n\t\t\t\tlevel.mobs.add(ally);\n\t\t\t\tally.state = ally.WANDERING;\n\t\t\t\t\n\t\t\t\tif (!candidatePositions.isEmpty()){\n\t\t\t\t\tally.pos = candidatePositions.remove(0);\n\t\t\t\t} else {\n\t\t\t\t\tally.pos = pos;\n\t\t\t\t}\n\t\t\t\tif (ally.sprite != null) ally.sprite.place(ally.pos);\n\n\t\t\t\tif (ally.fieldOfView == null || ally.fieldOfView.length != level.length()){\n\t\t\t\t\tally.fieldOfView = new boolean[level.length()];\n\t\t\t\t}\n\t\t\t\tDungeon.level.updateFieldOfView( ally, ally.fieldOfView );\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\theldAllies.clear();\n\t}\n\t\n\tpublic static void clearHeldAllies(){\n\t\theldAllies.clear();\n\t}\n}" }, { "identifier": "RingOfAccuracy", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/rings/RingOfAccuracy.java", "snippet": "public class RingOfAccuracy extends Ring {\n\n\t{\n\t\ticon = ItemSpriteSheet.Icons.RING_ACCURACY;\n\t}\n\t\n\tpublic String statsInfo() {\n\t\tif (isIdentified()){\n\t\t\tString info = Messages.get(this, \"stats\",\n\t\t\t\t\tMessages.decimalFormat(\"#.##\", 100f * (Math.pow(1.3f, soloBuffedBonus()) - 1f)));\n\t\t\tif (isEquipped(Dungeon.hero) && soloBuffedBonus() != combinedBuffedBonus(Dungeon.hero, Accuracy.class)){\n\t\t\t\tinfo += \"\\n\\n\" + Messages.get(this, \"combined_stats\",\n\t\t\t\t\t\tMessages.decimalFormat(\"#.##\", 100f * (Math.pow(1.3f, combinedBuffedBonus(Dungeon.hero, Accuracy.class)) - 1f)));\n\t\t\t}\n\t\t\treturn info;\n\t\t} else {\n\t\t\treturn Messages.get(this, \"typical_stats\", Messages.decimalFormat(\"#.##\", 30f));\n\t\t}\n\t}\n\n\t@Override\n\tpublic String info(){\n\t\tString desc = super.info();\n\n\t\tif (hero != null && hero.hasTalent(Talent.MYSTICAL_PUNCH)) {\n\t\t\tdesc += \"\\n\\n\" + Messages.get(this, \"special_effect\");\n\t\t}\n\n\t\treturn desc;\n\t}\n\t\n\t@Override\n\tprotected RingBuff buff( ) {\n\t\treturn new Accuracy();\n\t}\n\t\n\tpublic static float accuracyMultiplier( Char target ){\n\t\treturn (float)Math.pow(1.3f, getBuffedBonus(target, Accuracy.class));\n\t}\n\t\n\tpublic class Accuracy extends RingBuff {\n\t}\n}" }, { "identifier": "RingOfEvasion", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/rings/RingOfEvasion.java", "snippet": "public class RingOfEvasion extends Ring {\n\n\t{\n\t\ticon = ItemSpriteSheet.Icons.RING_EVASION;\n\t}\n\n\tpublic String statsInfo() {\n\t\tif (isIdentified()){\n\t\t\tString info = Messages.get(this, \"stats\",\n\t\t\t\t\tMessages.decimalFormat(\"#.##\", 100f * (Math.pow(1.125f, soloBuffedBonus()) - 1f)));\n\t\t\tif (isEquipped(Dungeon.hero) && soloBuffedBonus() != combinedBuffedBonus(Dungeon.hero, Evasion.class)){\n\t\t\t\tinfo += \"\\n\\n\" + Messages.get(this, \"combined_stats\",\n\t\t\t\t\t\tMessages.decimalFormat(\"#.##\", 100f * (Math.pow(1.125f, combinedBuffedBonus(Dungeon.hero, Evasion.class)) - 1f)));\n\t\t\t}\n\t\t\treturn info;\n\t\t} else {\n\t\t\treturn Messages.get(this, \"typical_stats\", Messages.decimalFormat(\"#.##\", 12.5f));\n\t\t}\n\t}\n\n\t@Override\n\tpublic String info(){\n\t\tString desc = super.info();\n\n\t\tif (hero != null && hero.hasTalent(Talent.MYSTICAL_PUNCH)) {\n\t\t\tdesc += \"\\n\\n\" + Messages.get(this, \"special_effect\");\n\t\t}\n\n\t\treturn desc;\n\t}\n\t\n\t@Override\n\tprotected RingBuff buff( ) {\n\t\treturn new Evasion();\n\t}\n\t\n\tpublic static float evasionMultiplier( Char target ){\n\t\treturn (float) Math.pow( 1.125, getBuffedBonus(target, Evasion.class));\n\t}\n\n\tpublic class Evasion extends RingBuff {\n\t}\n}" }, { "identifier": "Messages", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/messages/Messages.java", "snippet": "public class Messages {\n\n\tprivate static ArrayList<I18NBundle> bundles;\n\tprivate static Languages lang;\n\tprivate static Locale locale;\n\n\tpublic static final String NO_TEXT_FOUND = \"!!!NO TEXT FOUND!!!\";\n\n\tpublic static Languages lang(){\n\t\treturn lang;\n\t}\n\n\tpublic static Locale locale(){\n\t\treturn locale;\n\t}\n\n\t/**\n\t * Setup Methods\n\t */\n\n\tprivate static String[] prop_files = new String[]{\n\t\t\tAssets.Messages.ACTORS,\n\t\t\tAssets.Messages.ITEMS,\n\t\t\tAssets.Messages.JOURNAL,\n\t\t\tAssets.Messages.LEVELS,\n\t\t\tAssets.Messages.MISC,\n\t\t\tAssets.Messages.PLANTS,\n\t\t\tAssets.Messages.SCENES,\n\t\t\tAssets.Messages.UI,\n\t\t\tAssets.Messages.WINDOWS\n\t};\n\n\tstatic{\n\t\tsetup(SPDSettings.language());\n\t}\n\n\tpublic static void setup( Languages lang ){\n\t\t//seeing as missing keys are part of our process, this is faster than throwing an exception\n\t\tI18NBundle.setExceptionOnMissingKey(false);\n\n\t\t//store language and locale info for various string logic\n\t\tMessages.lang = lang;\n\t\tif (lang == Languages.ENGLISH){\n\t\t\tlocale = Locale.ENGLISH;\n\t\t} else {\n\t\t\tlocale = new Locale(lang.code());\n\t\t}\n\n\t\t//strictly match the language code when fetching bundles however\n\t\tbundles = new ArrayList<>();\n\t\tLocale bundleLocal = new Locale(lang.code());\n\t\tfor (String file : prop_files) {\n\t\t\tbundles.add(I18NBundle.createBundle(Gdx.files.internal(file), bundleLocal));\n\t\t}\n\t}\n\n\n\n\t/**\n\t * Resource grabbing methods\n\t */\n\n\tpublic static String get(String key, Object...args){\n\t\treturn get(null, key, args);\n\t}\n\n\tpublic static String get(Object o, String k, Object...args){\n\t\treturn get(o.getClass(), k, args);\n\t}\n\n\tpublic static String get(Class c, String k, Object...args){\n\t\tString key;\n\t\tif (c != null){\n\t\t\tkey = c.getName().replace(\"com.shatteredpixel.shatteredpixeldungeon.\", \"\");\n\t\t\tkey += \".\" + k;\n\t\t} else\n\t\t\tkey = k;\n\n\t\tString value = getFromBundle(key.toLowerCase(Locale.ENGLISH));\n\t\tif (value != null){\n\t\t\tif (args.length > 0) return format(value, args);\n\t\t\telse return value;\n\t\t} else {\n\t\t\t//this is so child classes can inherit properties from their parents.\n\t\t\t//in cases where text is commonly grabbed as a utility from classes that aren't mean to be instantiated\n\t\t\t//(e.g. flavourbuff.dispTurns()) using .class directly is probably smarter to prevent unnecessary recursive calls.\n\t\t\tif (c != null && c.getSuperclass() != null){\n\t\t\t\treturn get(c.getSuperclass(), k, args);\n\t\t\t} else {\n\t\t\t\treturn NO_TEXT_FOUND;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static String getFromBundle(String key){\n\t\tString result;\n\t\tfor (I18NBundle b : bundles){\n\t\t\tresult = b.get(key);\n\t\t\t//if it isn't the return string for no key found, return it\n\t\t\tif (result.length() != key.length()+6 || !result.contains(key)){\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\n\n\t/**\n\t * String Utility Methods\n\t */\n\n\tpublic static String format( String format, Object...args ) {\n\t\ttry {\n\t\t\treturn String.format(Locale.ENGLISH, format, args);\n\t\t} catch (IllegalFormatException e) {\n\t\t\tShatteredPixelDungeon.reportException( new Exception(\"formatting error for the string: \" + format, e) );\n\t\t\treturn format;\n\t\t}\n\t}\n\n\tprivate static HashMap<String, DecimalFormat> formatters = new HashMap<>();\n\n\tpublic static String decimalFormat( String format, double number ){\n\t\tif (!formatters.containsKey(format)){\n\t\t\tformatters.put(format, new DecimalFormat(format, DecimalFormatSymbols.getInstance(Locale.ENGLISH)));\n\t\t}\n\t\treturn formatters.get(format).format(number);\n\t}\n\n\tpublic static String capitalize( String str ){\n\t\tif (str.length() == 0) return str;\n\t\telse return str.substring( 0, 1 ).toUpperCase(locale) + str.substring( 1 );\n\t}\n\n\t//Words which should not be capitalized in title case, mostly prepositions which appear ingame\n\t//This list is not comprehensive!\n\tprivate static final HashSet<String> noCaps = new HashSet<>(\n\t\t\tArrays.asList(\"a\", \"an\", \"and\", \"of\", \"by\", \"to\", \"the\", \"x\", \"for\")\n\t);\n\n\tpublic static String titleCase( String str ){\n\t\t//English capitalizes every word except for a few exceptions\n\t\tif (lang == Languages.ENGLISH){\n\t\t\tString result = \"\";\n\t\t\t//split by any unicode space character\n\t\t\tfor (String word : str.split(\"(?<=\\\\p{Zs})\")){\n\t\t\t\tif (noCaps.contains(word.trim().toLowerCase(Locale.ENGLISH).replaceAll(\":|[0-9]\", \"\"))){\n\t\t\t\t\tresult += word;\n\t\t\t\t} else {\n\t\t\t\t\tresult += capitalize(word);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//first character is always capitalized.\n\t\t\treturn capitalize(result);\n\t\t}\n\n\t\t//Otherwise, use sentence case\n\t\treturn capitalize(str);\n\t}\n\n\tpublic static String upperCase( String str ){\n\t\treturn str.toUpperCase(locale);\n\t}\n\n\tpublic static String lowerCase( String str ){\n\t\treturn str.toLowerCase(locale);\n\t}\n}" }, { "identifier": "CharSprite", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/sprites/CharSprite.java", "snippet": "public class CharSprite extends MovieClip implements Tweener.Listener, MovieClip.Listener {\n\t\n\t// Color constants for floating text\n\tpublic static final int DEFAULT\t\t= 0xFFFFFF;\n\tpublic static final int POSITIVE\t= 0x00FF00;\n\tpublic static final int NEGATIVE\t= 0xFF0000;\n\tpublic static final int WARNING\t\t= 0xFF8800;\n\tpublic static final int NEUTRAL\t\t= 0xFFFF00;\n\t\n\tpublic static final float DEFAULT_MOVE_INTERVAL = 0.1f;\n\tprivate static float moveInterval = DEFAULT_MOVE_INTERVAL;\n\tprivate static final float FLASH_INTERVAL\t= 0.05f;\n\n\t//the amount the sprite is raised from flat when viewed in a raised perspective\n\tprotected float perspectiveRaise = 6 / 16f; //6 pixels\n\n\t//the width and height of the shadow are a percentage of sprite size\n\t//offset is the number of pixels the shadow is moved down or up (handy for some animations)\n\tprotected boolean renderShadow = false;\n\tprotected float shadowWidth = 1.2f;\n\tprotected float shadowHeight = 0.25f;\n\tprotected float shadowOffset = 0.25f;\n\n\tpublic enum State {\n\t\tBURNING, LEVITATING, INVISIBLE, PARALYSED, FROZEN, ILLUMINATED, CHILLED, DARKENED, MARKED, HEALING, SHIELDED, HEARTS\n\t}\n\tprivate int stunStates = 0;\n\t\n\tprotected Animation idle;\n\tprotected Animation run;\n\tprotected Animation attack;\n\tprotected Animation operate;\n\tprotected Animation zap;\n\tprotected Animation die;\n\t\n\tprotected Callback animCallback;\n\t\n\tprotected PosTweener motion;\n\t\n\tprotected Emitter burning;\n\tprotected Emitter chilled;\n\tprotected Emitter marked;\n\tprotected Emitter levitation;\n\tprotected Emitter healing;\n\tprotected Emitter hearts;\n\t\n\tprotected IceBlock iceBlock;\n\tprotected DarkBlock darkBlock;\n\tprotected TorchHalo light;\n\tprotected ShieldHalo shield;\n\tprotected AlphaTweener invisible;\n\tprotected Flare aura;\n\t\n\tprotected EmoIcon emo;\n\tprotected CharHealthIndicator health;\n\n\tprivate Tweener jumpTweener;\n\tprivate Callback jumpCallback;\n\n\tprotected float flashTime = 0;\n\t\n\tprotected boolean sleeping = false;\n\n\tpublic Char ch;\n\n\t//used to prevent the actor associated with this sprite from acting until movement completes\n\tpublic volatile boolean isMoving = false;\n\t\n\tpublic CharSprite() {\n\t\tsuper();\n\t\tlistener = this;\n\t}\n\t\n\t@Override\n\tpublic void play(Animation anim) {\n\t\t//Shouldn't interrupt the dieing animation\n\t\tif (curAnim == null || curAnim != die) {\n\t\t\tsuper.play(anim);\n\t\t}\n\t}\n\t\n\t//intended to be used for placing a character in the game world\n\tpublic void link( Char ch ) {\n\t\tlinkVisuals( ch );\n\t\t\n\t\tthis.ch = ch;\n\t\tch.sprite = this;\n\t\t\n\t\tplace( ch.pos );\n\t\tturnTo( ch.pos, Random.Int( Dungeon.level.length() ) );\n\t\trenderShadow = true;\n\t\t\n\t\tif (ch != Dungeon.hero) {\n\t\t\tif (health == null) {\n\t\t\t\thealth = new CharHealthIndicator(ch);\n\t\t\t} else {\n\t\t\t\thealth.target(ch);\n\t\t\t}\n\t\t}\n\n\t\tch.updateSpriteState();\n\t}\n\n\t@Override\n\tpublic void destroy() {\n\t\tsuper.destroy();\n\t\tif (ch != null && ch.sprite == this){\n\t\t\tch.sprite = null;\n\t\t}\n\t}\n\n\t//used for just updating a sprite based on a given character, not linking them or placing in the game\n\tpublic void linkVisuals( Char ch ){\n\t\t//do nothin by default\n\t}\n\t\n\tpublic PointF worldToCamera( int cell ) {\n\t\t\n\t\tfinal int csize = DungeonTilemap.SIZE;\n\t\t\n\t\treturn new PointF(\n\t\t\tPixelScene.align(Camera.main, ((cell % Dungeon.level.width()) + 0.5f) * csize - width() * 0.5f),\n\t\t\tPixelScene.align(Camera.main, ((cell / Dungeon.level.width()) + 1.0f) * csize - height() - csize * perspectiveRaise)\n\t\t);\n\t}\n\t\n\tpublic void place( int cell ) {\n\t\tpoint( worldToCamera( cell ) );\n\t}\n\t\n\tpublic void showStatus( int color, String text, Object... args ) {\n\t\tif (visible) {\n\t\t\tif (args.length > 0) {\n\t\t\t\ttext = Messages.format( text, args );\n\t\t\t}\n\t\t\tfloat x = destinationCenter().x;\n\t\t\tfloat y = destinationCenter().y - height()/2f;\n\t\t\tif (ch != null) {\n\t\t\t\tFloatingText.show( x, y, ch.pos, text, color );\n\t\t\t} else {\n\t\t\t\tFloatingText.show( x, y, text, color );\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void idle() {\n\t\tplay(idle);\n\t}\n\t\n\tpublic void move( int from, int to ) {\n\t\tturnTo( from , to );\n\n\t\tplay( run );\n\t\t\n\t\tmotion = new PosTweener( this, worldToCamera( to ), moveInterval );\n\t\tmotion.listener = this;\n\t\tparent.add( motion );\n\n\t\tisMoving = true;\n\t\t\n\t\tif (visible && Dungeon.level.water[from] && !ch.flying) {\n\t\t\tGameScene.ripple( from );\n\t\t}\n\n\t}\n\t\n\tpublic static void setMoveInterval( float interval){\n\t\tmoveInterval = interval;\n\t}\n\t\n\t//returns where the center of this sprite will be after it completes any motion in progress\n\tpublic PointF destinationCenter(){\n\t\tPosTweener motion = this.motion;\n\t\tif (motion != null && motion.elapsed >= 0){\n\t\t\treturn new PointF(motion.end.x + width()/2f, motion.end.y + height()/2f);\n\t\t} else {\n\t\t\treturn center();\n\t\t}\n\t}\n\t\n\tpublic void interruptMotion() {\n\t\tif (motion != null) {\n\t\t\tmotion.stop(false);\n\t\t}\n\t}\n\t\n\tpublic void attack( int cell ) {\n\t\tattack( cell, null );\n\t}\n\t\n\tpublic synchronized void attack( int cell, Callback callback ) {\n\t\tanimCallback = callback;\n\t\tturnTo( ch.pos, cell );\n\t\tplay( attack );\n\t}\n\t\n\tpublic void operate( int cell ) {\n\t\toperate( cell, null );\n\t}\n\t\n\tpublic synchronized void operate( int cell, Callback callback ) {\n\t\tanimCallback = callback;\n\t\tturnTo( ch.pos, cell );\n\t\tplay( operate );\n\t}\n\t\n\tpublic void zap( int cell ) {\n\t\tzap( cell, null );\n\t}\n\t\n\tpublic synchronized void zap( int cell, Callback callback ) {\n\t\tanimCallback = callback;\n\t\tturnTo( ch.pos, cell );\n\t\tplay( zap );\n\t}\n\t\n\tpublic void turnTo( int from, int to ) {\n\t\tint fx = from % Dungeon.level.width();\n\t\tint tx = to % Dungeon.level.width();\n\t\tif (tx > fx) {\n\t\t\tflipHorizontal = false;\n\t\t} else if (tx < fx) {\n\t\t\tflipHorizontal = true;\n\t\t}\n\t}\n\n\tpublic void jump( int from, int to, Callback callback ) {\n\t\tfloat distance = Math.max( 1f, Dungeon.level.trueDistance( from, to ));\n\t\tjump( from, to, distance * 2, distance * 0.1f, callback );\n\t}\n\n\tpublic void jump( int from, int to, float height, float duration, Callback callback ) {\n\t\tjumpCallback = callback;\n\n\t\tjumpTweener = new JumpTweener( this, worldToCamera( to ), height, duration );\n\t\tjumpTweener.listener = this;\n\t\tparent.add( jumpTweener );\n\n\t\tturnTo( from, to );\n\t}\n\n\tpublic void die() {\n\t\tsleeping = false;\n\t\tplay( die );\n\n\t\thideEmo();\n\t\t\n\t\tif (health != null){\n\t\t\thealth.killAndErase();\n\t\t}\n\t}\n\t\n\tpublic Emitter emitter() {\n\t\tEmitter emitter = GameScene.emitter();\n\t\tif (emitter != null) emitter.pos( this );\n\t\treturn emitter;\n\t}\n\t\n\tpublic Emitter centerEmitter() {\n\t\tEmitter emitter = GameScene.emitter();\n\t\tif (emitter != null) emitter.pos( center() );\n\t\treturn emitter;\n\t}\n\t\n\tpublic Emitter bottomEmitter() {\n\t\tEmitter emitter = GameScene.emitter();\n\t\tif (emitter != null) emitter.pos( x, y + height, width, 0 );\n\t\treturn emitter;\n\t}\n\t\n\tpublic void burst( final int color, int n ) {\n\t\tif (visible) {\n\t\t\tSplash.at( center(), color, n );\n\t\t}\n\t}\n\t\n\tpublic void bloodBurstA( PointF from, int damage ) {\n\t\tif (visible) {\n\t\t\tPointF c = center();\n\t\t\tint n = (int)Math.min( 9 * Math.sqrt( (double)damage / ch.HT ), 9 );\n\t\t\tSplash.at( c, PointF.angle( from, c ), 3.1415926f / 2, blood(), n );\n\t\t}\n\t}\n\n\tpublic int blood() {\n\t\treturn 0xFFBB0000;\n\t}\n\t\n\tpublic void flash() {\n\t\tra = ba = ga = 1f;\n\t\tflashTime = FLASH_INTERVAL;\n\t}\n\t\n\tpublic void add( State state ) {\n\t\tswitch (state) {\n\t\t\tcase BURNING:\n\t\t\t\tburning = emitter();\n\t\t\t\tburning.pour( FlameParticle.FACTORY, 0.06f );\n\t\t\t\tif (visible) {\n\t\t\t\t\tSample.INSTANCE.play( Assets.Sounds.BURNING );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase LEVITATING:\n\t\t\t\tlevitation = emitter();\n\t\t\t\tlevitation.pour( Speck.factory( Speck.JET ), 0.02f );\n\t\t\t\tbreak;\n\t\t\tcase INVISIBLE:\n\t\t\t\tif (invisible != null) {\n\t\t\t\t\tinvisible.killAndErase();\n\t\t\t\t}\n\t\t\t\tinvisible = new AlphaTweener( this, 0.4f, 0.4f );\n\t\t\t\tif (parent != null){\n\t\t\t\t\tparent.add(invisible);\n\t\t\t\t} else\n\t\t\t\t\talpha( 0.4f );\n\t\t\t\tbreak;\n\t\t\tcase PARALYSED:\n\t\t\t\tpaused = true;\n\t\t\t\tbreak;\n\t\t\tcase FROZEN:\n\t\t\t\ticeBlock = IceBlock.freeze( this );\n\t\t\t\tbreak;\n\t\t\tcase ILLUMINATED:\n\t\t\t\tGameScene.effect( light = new TorchHalo( this ) );\n\t\t\t\tbreak;\n\t\t\tcase CHILLED:\n\t\t\t\tchilled = emitter();\n\t\t\t\tchilled.pour(SnowParticle.FACTORY, 0.1f);\n\t\t\t\tbreak;\n\t\t\tcase DARKENED:\n\t\t\t\tdarkBlock = DarkBlock.darken( this );\n\t\t\t\tbreak;\n\t\t\tcase MARKED:\n\t\t\t\tmarked = emitter();\n\t\t\t\tmarked.pour(ShadowParticle.UP, 0.1f);\n\t\t\t\tbreak;\n\t\t\tcase HEALING:\n\t\t\t\thealing = emitter();\n\t\t\t\thealing.pour(Speck.factory(Speck.HEALING), 0.5f);\n\t\t\t\tbreak;\n\t\t\tcase SHIELDED:\n\t\t\t\tif (shield != null) {\n\t\t\t\t\tshield.killAndErase();\n\t\t\t\t}\n\t\t\t\tGameScene.effect(shield = new ShieldHalo(this));\n\t\t\t\tbreak;\n\t\t\tcase HEARTS:\n\t\t\t\thearts = emitter();\n\t\t\t\thearts.pour(Speck.factory(Speck.HEART), 0.5f);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tpublic void remove( State state ) {\n\t\tswitch (state) {\n\t\t\tcase BURNING:\n\t\t\t\tif (burning != null) {\n\t\t\t\t\tburning.on = false;\n\t\t\t\t\tburning = null;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase LEVITATING:\n\t\t\t\tif (levitation != null) {\n\t\t\t\t\tlevitation.on = false;\n\t\t\t\t\tlevitation = null;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase INVISIBLE:\n\t\t\t\tif (invisible != null) {\n\t\t\t\t\tinvisible.killAndErase();\n\t\t\t\t\tinvisible = null;\n\t\t\t\t}\n\t\t\t\talpha( 1f );\n\t\t\t\tbreak;\n\t\t\tcase PARALYSED:\n\t\t\t\tpaused = false;\n\t\t\t\tbreak;\n\t\t\tcase FROZEN:\n\t\t\t\tif (iceBlock != null) {\n\t\t\t\t\ticeBlock.melt();\n\t\t\t\t\ticeBlock = null;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase ILLUMINATED:\n\t\t\t\tif (light != null) {\n\t\t\t\t\tlight.putOut();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CHILLED:\n\t\t\t\tif (chilled != null){\n\t\t\t\t\tchilled.on = false;\n\t\t\t\t\tchilled = null;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase DARKENED:\n\t\t\t\tif (darkBlock != null) {\n\t\t\t\t\tdarkBlock.lighten();\n\t\t\t\t\tdarkBlock = null;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase MARKED:\n\t\t\t\tif (marked != null){\n\t\t\t\t\tmarked.on = false;\n\t\t\t\t\tmarked = null;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase HEALING:\n\t\t\t\tif (healing != null){\n\t\t\t\t\thealing.on = false;\n\t\t\t\t\thealing = null;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SHIELDED:\n\t\t\t\tif (shield != null){\n\t\t\t\t\tshield.putOut();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase HEARTS:\n\t\t\t\tif (hearts != null){\n\t\t\t\t\thearts.on = false;\n\t\t\t\t\thearts = null;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tpublic void aura( int color ){\n\t\tif (aura != null){\n\t\t\taura.killAndErase();\n\t\t}\n\t\tfloat size = Math.max(width(), height());\n\t\tsize = Math.max(size+4, 16);\n\t\taura = new Flare(5, size);\n\t\taura.angularSpeed = 90;\n\t\taura.color(color, true);\n\t\taura.visible = visible;\n\n\t\tif (parent != null) {\n\t\t\taura.show(this, 0);\n\t\t}\n\t}\n\n\tpublic void clearAura(){\n\t\tif (aura != null){\n\t\t\taura.killAndErase();\n\t\t\taura = null;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void update() {\n\t\tif (paused && ch != null && curAnim != null && !curAnim.looped && !finished){\n\t\t\tlistener.onComplete(curAnim);\n\t\t\tfinished = true;\n\t\t}\n\t\t\n\t\tsuper.update();\n\t\t\n\t\tif (flashTime > 0 && (flashTime -= Game.elapsed) <= 0) {\n\t\t\tresetColor();\n\t\t}\n\t\t\n\t\tif (burning != null) {\n\t\t\tburning.visible = visible;\n\t\t}\n\t\tif (levitation != null) {\n\t\t\tlevitation.visible = visible;\n\t\t}\n\t\tif (iceBlock != null) {\n\t\t\ticeBlock.visible = visible;\n\t\t}\n\t\tif (chilled != null) {\n\t\t\tchilled.visible = visible;\n\t\t}\n\t\tif (marked != null) {\n\t\t\tmarked.visible = visible;\n\t\t}\n\t\tif (healing != null){\n\t\t\thealing.visible = visible;\n\t\t}\n\t\tif (hearts != null){\n\t\t\thearts.visible = visible;\n\t\t}\n\t\tif (aura != null){\n\t\t\tif (aura.parent == null){\n\t\t\t\taura.show(this, 0);\n\t\t\t}\n\t\t\taura.visible = visible;\n\t\t\taura.point(center());\n\t\t}\n\t\tif (sleeping) {\n\t\t\tshowSleep();\n\t\t} else {\n\t\t\thideSleep();\n\t\t}\n\t\tsynchronized (EmoIcon.class) {\n\t\t\tif (emo != null && emo.alive) {\n\t\t\t\temo.visible = visible;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void resetColor() {\n\t\tsuper.resetColor();\n\t\tif (invisible != null){\n\t\t\talpha(0.4f);\n\t\t}\n\t}\n\t\n\tpublic void showSleep() {\n\t\tsynchronized (EmoIcon.class) {\n\t\t\tif (!(emo instanceof EmoIcon.Sleep)) {\n\t\t\t\tif (emo != null) {\n\t\t\t\t\temo.killAndErase();\n\t\t\t\t}\n\t\t\t\temo = new EmoIcon.Sleep(this);\n\t\t\t\temo.visible = visible;\n\t\t\t}\n\t\t}\n\t\tidle();\n\t}\n\t\n\tpublic void hideSleep() {\n\t\tsynchronized (EmoIcon.class) {\n\t\t\tif (emo instanceof EmoIcon.Sleep) {\n\t\t\t\temo.killAndErase();\n\t\t\t\temo = null;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void showAlert() {\n\t\tsynchronized (EmoIcon.class) {\n\t\t\tif (!(emo instanceof EmoIcon.Alert)) {\n\t\t\t\tif (emo != null) {\n\t\t\t\t\temo.killAndErase();\n\t\t\t\t}\n\t\t\t\temo = new EmoIcon.Alert(this);\n\t\t\t\temo.visible = visible;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void hideAlert() {\n\t\tsynchronized (EmoIcon.class) {\n\t\t\tif (emo instanceof EmoIcon.Alert) {\n\t\t\t\temo.killAndErase();\n\t\t\t\temo = null;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void showLost() {\n\t\tsynchronized (EmoIcon.class) {\n\t\t\tif (!(emo instanceof EmoIcon.Lost)) {\n\t\t\t\tif (emo != null) {\n\t\t\t\t\temo.killAndErase();\n\t\t\t\t}\n\t\t\t\temo = new EmoIcon.Lost(this);\n\t\t\t\temo.visible = visible;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void hideLost() {\n\t\tsynchronized (EmoIcon.class) {\n\t\t\tif (emo instanceof EmoIcon.Lost) {\n\t\t\t\temo.killAndErase();\n\t\t\t\temo = null;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void hideEmo(){\n\t\tsynchronized (EmoIcon.class) {\n\t\t\tif (emo != null) {\n\t\t\t\temo.killAndErase();\n\t\t\t\temo = null;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void kill() {\n\t\tsuper.kill();\n\t\t\n\t\thideEmo();\n\t\t\n\t\tfor( State s : State.values()){\n\t\t\tremove(s);\n\t\t}\n\t\t\n\t\tif (health != null){\n\t\t\thealth.killAndErase();\n\t\t}\n\t}\n\n\tprivate float[] shadowMatrix = new float[16];\n\n\t@Override\n\tprotected void updateMatrix() {\n\t\tsuper.updateMatrix();\n\t\tMatrix.copy(matrix, shadowMatrix);\n\t\tMatrix.translate(shadowMatrix,\n\t\t\t\t(width * (1f - shadowWidth)) / 2f,\n\t\t\t\t(height * (1f - shadowHeight)) + shadowOffset);\n\t\tMatrix.scale(shadowMatrix, shadowWidth, shadowHeight);\n\t}\n\n\t@Override\n\tpublic void draw() {\n\t\tif (texture == null || (!dirty && buffer == null))\n\t\t\treturn;\n\n\t\tif (renderShadow) {\n\t\t\tif (dirty) {\n\t\t\t\t((Buffer)verticesBuffer).position(0);\n\t\t\t\tverticesBuffer.put(vertices);\n\t\t\t\tif (buffer == null)\n\t\t\t\t\tbuffer = new Vertexbuffer(verticesBuffer);\n\t\t\t\telse\n\t\t\t\t\tbuffer.updateVertices(verticesBuffer);\n\t\t\t\tdirty = false;\n\t\t\t}\n\n\t\t\tNoosaScript script = script();\n\n\t\t\ttexture.bind();\n\n\t\t\tscript.camera(camera());\n\n\t\t\tupdateMatrix();\n\n\t\t\tscript.uModel.valueM4(shadowMatrix);\n\t\t\tscript.lighting(\n\t\t\t\t\t0, 0, 0, am * .6f,\n\t\t\t\t\t0, 0, 0, aa * .6f);\n\n\t\t\tscript.drawQuad(buffer);\n\t\t}\n\n\t\tsuper.draw();\n\n\t}\n\n\t@Override\n\tpublic void onComplete( Tweener tweener ) {\n\t\tif (tweener == jumpTweener) {\n\n\t\t\tif (visible && Dungeon.level.water[ch.pos] && !ch.flying) {\n\t\t\t\tGameScene.ripple( ch.pos );\n\t\t\t}\n\t\t\tif (jumpCallback != null) {\n\t\t\t\tjumpCallback.call();\n\t\t\t}\n\n\t\t} else if (tweener == motion) {\n\n\t\t\tsynchronized (this) {\n\t\t\t\tisMoving = false;\n\n\t\t\t\tmotion.killAndErase();\n\t\t\t\tmotion = null;\n\t\t\t\tch.onMotionComplete();\n\n\t\t\t\tGameScene.sortMobSprites();\n\t\t\t\tnotifyAll();\n\t\t\t}\n\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void onComplete( Animation anim ) {\n\t\t\n\t\tif (animCallback != null) {\n\t\t\tCallback executing = animCallback;\n\t\t\tanimCallback = null;\n\t\t\texecuting.call();\n\t\t} else {\n\t\t\t\n\t\t\tif (anim == attack) {\n\t\t\t\t\n\t\t\t\tidle();\n\t\t\t\tch.onAttackComplete();\n\t\t\t\t\n\t\t\t} else if (anim == operate) {\n\t\t\t\t\n\t\t\t\tidle();\n\t\t\t\tch.onOperateComplete();\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\n\tprivate static class JumpTweener extends Tweener {\n\n\t\tpublic CharSprite visual;\n\n\t\tpublic PointF start;\n\t\tpublic PointF end;\n\n\t\tpublic float height;\n\n\t\tpublic JumpTweener( CharSprite visual, PointF pos, float height, float time ) {\n\t\t\tsuper( visual, time );\n\n\t\t\tthis.visual = visual;\n\t\t\tstart = visual.point();\n\t\t\tend = pos;\n\n\t\t\tthis.height = height;\n\t\t}\n\n\t\t@Override\n\t\tprotected void updateValues( float progress ) {\n\t\t\tfloat hVal = -height * 4 * progress * (1 - progress);\n\t\t\tvisual.point( PointF.inter( start, end, progress ).offset( 0, hVal ) );\n\t\t\tvisual.shadowOffset = 0.25f - hVal*0.8f;\n\t\t}\n\t}\n}" }, { "identifier": "MirrorSprite", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/sprites/MirrorSprite.java", "snippet": "public class MirrorSprite extends MobSprite {\n\t\n\tprivate static final int FRAME_WIDTH\t= 12;\n\tprivate static final int FRAME_HEIGHT\t= 15;\n\t\n\tpublic MirrorSprite() {\n\t\tsuper();\n\t\t\n\t\ttexture( Dungeon.hero.heroClass.spritesheet() );\n\t\tupdateArmor( 0 );\n\t\tidle();\n\t}\n\t\n\t@Override\n\tpublic void link( Char ch ) {\n\t\tsuper.link( ch );\n\t\tupdateArmor();\n\t}\n\n\t@Override\n\tpublic void bloodBurstA(PointF from, int damage) {\n\t\t//do nothing\n\t}\n\n\tpublic void updateArmor(){\n\t\tupdateArmor( ((MirrorImage)ch).armTier );\n\t}\n\t\n\tpublic void updateArmor( int tier ) {\n\t\tTextureFilm film = new TextureFilm( HeroSprite.tiers(), tier, FRAME_WIDTH, FRAME_HEIGHT );\n\t\t\n\t\tidle = new Animation( 1, true );\n\t\tidle.frames( film, 0, 0, 0, 1, 0, 0, 1, 1 );\n\t\t\n\t\trun = new Animation( 20, true );\n\t\trun.frames( film, 2, 3, 4, 5, 6, 7 );\n\t\t\n\t\tdie = new Animation( 20, false );\n\t\tdie.frames( film, 0 );\n\t\t\n\t\tattack = new Animation( 15, false );\n\t\tattack.frames( film, 13, 14, 15, 0 );\n\t\t\n\t\tidle();\n\t}\n}" }, { "identifier": "BuffIndicator", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/ui/BuffIndicator.java", "snippet": "public class BuffIndicator extends Component {\n\t\n\t//transparent icon\n\tpublic static final int NONE = 127;\n\n\t//FIXME this is becoming a mess, should do a big cleaning pass on all of these\n\t//and think about tinting options\n\tpublic static final int MIND_VISION = 0;\n\tpublic static final int LEVITATION = 1;\n\tpublic static final int FIRE = 2;\n\tpublic static final int POISON = 3;\n\tpublic static final int PARALYSIS = 4;\n\tpublic static final int HUNGER = 5;\n\tpublic static final int STARVATION = 6;\n\tpublic static final int TIME = 7;\n\tpublic static final int OOZE = 8;\n\tpublic static final int AMOK = 9;\n\tpublic static final int TERROR = 10;\n\tpublic static final int ROOTS = 11;\n\tpublic static final int INVISIBLE = 12;\n\tpublic static final int SHADOWS = 13;\n\tpublic static final int WEAKNESS = 14;\n\tpublic static final int FROST = 15;\n\tpublic static final int BLINDNESS = 16;\n\tpublic static final int COMBO = 17;\n\tpublic static final int FURY = 18;\n\tpublic static final int HERB_HEALING= 19;\n\tpublic static final int ARMOR = 20;\n\tpublic static final int HEART = 21;\n\tpublic static final int LIGHT = 22;\n\tpublic static final int CRIPPLE = 23;\n\tpublic static final int BARKSKIN = 24;\n\tpublic static final int IMMUNITY = 25;\n\tpublic static final int BLEEDING = 26;\n\tpublic static final int MARK = 27;\n\tpublic static final int DEFERRED = 28;\n\tpublic static final int DROWSY = 29;\n\tpublic static final int MAGIC_SLEEP = 30;\n\tpublic static final int THORNS = 31;\n\tpublic static final int FORESIGHT = 32;\n\tpublic static final int VERTIGO = 33;\n\tpublic static final int RECHARGING = 34;\n\tpublic static final int LOCKED_FLOOR= 35;\n\tpublic static final int CORRUPT = 36;\n\tpublic static final int BLESS = 37;\n\tpublic static final int RAGE = 38;\n\tpublic static final int SACRIFICE = 39;\n\tpublic static final int BERSERK = 40;\n\tpublic static final int HASTE = 41;\n\tpublic static final int PREPARATION = 42;\n\tpublic static final int WELL_FED = 43;\n\tpublic static final int HEALING = 44;\n\tpublic static final int WEAPON = 45;\n\tpublic static final int VULNERABLE = 46;\n\tpublic static final int HEX = 47;\n\tpublic static final int DEGRADE = 48;\n\tpublic static final int PINCUSHION = 49;\n\tpublic static final int UPGRADE = 50;\n\tpublic static final int MOMENTUM = 51;\n\tpublic static final int ANKH = 52;\n\tpublic static final int NOINV = 53;\n\tpublic static final int TARGETED = 54;\n\tpublic static final int IMBUE = 55;\n\tpublic static final int ENDURE = 56;\n\tpublic static final int INVERT_MARK = 57;\n\tpublic static final int NATURE_POWER= 58;\n\tpublic static final int AMULET = 59;\n\tpublic static final int DUEL_CLEAVE = 60;\n\tpublic static final int DUEL_GUARD = 61;\n\tpublic static final int DUEL_SPIN = 62;\n\tpublic static final int DUEL_EVASIVE= 63;\n\tpublic static final int DUEL_DANCE = 64;\n\tpublic static final int DUEL_BRAWL = 65;\n\tpublic static final int DUEL_XBOW = 66;\n\tpublic static final int CHALLENGE = 67;\n\tpublic static final int MONK_ENERGY = 68;\n\tpublic static final int DUEL_COMBO = 69;\n\tpublic static final int DAZE = 70;\n\n\t//arranged buffs\n\tpublic static final int PARRY\t\t= 136;\n\tpublic static final int DUEL_ANGEL\t= 137;\n\tpublic static final int DUEL_EVIL\t= 138;\n\tpublic static final int DUEL_DAGGER\t= 139;\n\tpublic static final int BULLET\t\t= 140;\n\tpublic static final int PLATE \t\t= 141;\n\tpublic static final int ROULETTE_1 \t= 142;\n\tpublic static final int ROULETTE_2 \t= 143;\n\tpublic static final int ROULETTE_3 \t= 144;\n\tpublic static final int ROULETTE_4 \t= 145;\n\tpublic static final int ROULETTE_5 \t= 146;\n\tpublic static final int ROULETTE_6 \t= 147;\n\tpublic static final int CLOAKING \t= 148;\n\n\tpublic static final int SIZE_SMALL = 7;\n\tpublic static final int SIZE_LARGE = 16;\n\t\n\tprivate static BuffIndicator heroInstance;\n\tprivate static BuffIndicator bossInstance;\n\t\n\tprivate LinkedHashMap<Buff, BuffButton> buffButtons = new LinkedHashMap<>();\n\tprivate boolean needsRefresh;\n\tprivate Char ch;\n\n\tprivate boolean large = false;\n\t\n\tpublic BuffIndicator( Char ch, boolean large ) {\n\t\tsuper();\n\t\t\n\t\tthis.ch = ch;\n\t\tthis.large = large;\n\t\tif (ch == Dungeon.hero) {\n\t\t\theroInstance = this;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void destroy() {\n\t\tsuper.destroy();\n\t\t\n\t\tif (this == heroInstance) {\n\t\t\theroInstance = null;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void update() {\n\t\tsuper.update();\n\t\tif (needsRefresh){\n\t\t\tneedsRefresh = false;\n\t\t\tlayout();\n\t\t}\n\t}\n\n\tprivate boolean buffsHidden = false;\n\n\t@Override\n\tprotected void layout() {\n\n\t\tArrayList<Buff> newBuffs = new ArrayList<>();\n\t\tfor (Buff buff : ch.buffs()) {\n\t\t\tif (buff.icon() != NONE) {\n\t\t\t\tnewBuffs.add(buff);\n\t\t\t}\n\t\t}\n\n\t\tint size = large ? SIZE_LARGE : SIZE_SMALL;\n\n\t\t//remove any icons no longer present\n\t\tfor (Buff buff : buffButtons.keySet().toArray(new Buff[0])){\n\t\t\tif (!newBuffs.contains(buff)){\n\t\t\t\tImage icon = buffButtons.get( buff ).icon;\n\t\t\t\ticon.originToCenter();\n\t\t\t\ticon.alpha(0.6f);\n\t\t\t\tadd( icon );\n\t\t\t\tadd( new AlphaTweener( icon, 0, 0.6f ) {\n\t\t\t\t\t@Override\n\t\t\t\t\tprotected void updateValues( float progress ) {\n\t\t\t\t\t\tsuper.updateValues( progress );\n\t\t\t\t\t\timage.scale.set( 1 + 5 * progress );\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t@Override\n\t\t\t\t\tprotected void onComplete() {\n\t\t\t\t\t\timage.killAndErase();\n\t\t\t\t\t}\n\t\t\t\t} );\n\t\t\t\t\n\t\t\t\tbuffButtons.get( buff ).destroy();\n\t\t\t\tremove(buffButtons.get( buff ));\n\t\t\t\tbuffButtons.remove( buff );\n\t\t\t}\n\t\t}\n\t\t\n\t\t//add new icons\n\t\tfor (Buff buff : newBuffs) {\n\t\t\tif (!buffButtons.containsKey(buff)) {\n\t\t\t\tBuffButton icon = new BuffButton(buff, large);\n\t\t\t\tadd(icon);\n\t\t\t\tbuffButtons.put( buff, icon );\n\t\t\t}\n\t\t}\n\t\t\n\t\t//layout\n\t\tint pos = 0;\n\t\tfloat lastIconLeft = 0;\n\t\tfor (BuffButton icon : buffButtons.values()){\n\t\t\ticon.updateIcon();\n\t\t\t//button areas are slightly oversized, especially on small buttons\n\t\t\ticon.setRect(x + pos * (size + 1), y, size + 1, size + (large ? 0 : 5));\n\t\t\tPixelScene.align(icon);\n\t\t\tpos++;\n\n\t\t\ticon.visible = icon.left() <= right();\n\t\t\tlastIconLeft = icon.left();\n\t\t}\n\n\t\tbuffsHidden = false;\n\t\t//squish buff icons together if there isn't enough room\n\t\tfloat excessWidth = lastIconLeft - right();\n\t\tif (excessWidth > 0) {\n\t\t\tfloat leftAdjust = excessWidth/(buffButtons.size()-1);\n\t\t\t//can't squish by more than 50% on large and 62% on small\n\t\t\tif (large && leftAdjust >= size*0.48f) leftAdjust = size*0.5f;\n\t\t\tif (!large && leftAdjust >= size*0.62f) leftAdjust = size*0.65f;\n\t\t\tfloat cumulativeAdjust = leftAdjust * (buffButtons.size()-1);\n\n\t\t\tArrayList<BuffButton> buttons = new ArrayList<>(buffButtons.values());\n\t\t\tCollections.reverse(buttons);\n\t\t\tfor (BuffButton icon : buttons) {\n\t\t\t\ticon.setPos(icon.left() - cumulativeAdjust, icon.top());\n\t\t\t\ticon.visible = icon.left() <= right();\n\t\t\t\tif (!icon.visible) buffsHidden = true;\n\t\t\t\tPixelScene.align(icon);\n\t\t\t\tbringToFront(icon);\n\t\t\t\ticon.givePointerPriority();\n\t\t\t\tcumulativeAdjust -= leftAdjust;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic boolean allBuffsVisible(){\n\t\treturn !buffsHidden;\n\t}\n\n\tprivate static class BuffButton extends IconButton {\n\n\t\tprivate Buff buff;\n\n\t\tprivate boolean large;\n\n\t\tpublic Image grey; //only for small\n\t\tpublic BitmapText text; //only for large\n\n\t\tpublic BuffButton( Buff buff, boolean large ){\n\t\t\tsuper( new BuffIcon(buff, large));\n\t\t\tthis.buff = buff;\n\t\t\tthis.large = large;\n\n\t\t\tbringToFront(grey);\n\t\t\tbringToFront(text);\n\t\t}\n\n\t\t@Override\n\t\tprotected void createChildren() {\n\t\t\tsuper.createChildren();\n\t\t\tgrey = new Image( TextureCache.createSolid(0xCC666666));\n\t\t\tadd( grey );\n\n\t\t\ttext = new BitmapText(PixelScene.pixelFont);\n\t\t\tadd( text );\n\t\t}\n\n\t\tpublic void updateIcon(){\n\t\t\t((BuffIcon)icon).refresh(buff);\n\t\t\t//round up to the nearest pixel if <50% faded, otherwise round down\n\t\t\tif (!large || buff.iconTextDisplay().isEmpty()) {\n\t\t\t\ttext.visible = false;\n\t\t\t\tgrey.visible = true;\n\t\t\t\tfloat fadeHeight = buff.iconFadePercent() * icon.height();\n\t\t\t\tfloat zoom = (camera() != null) ? camera().zoom : 1;\n\t\t\t\tif (fadeHeight < icon.height() / 2f) {\n\t\t\t\t\tgrey.scale.set(icon.width(), (float) Math.ceil(zoom * fadeHeight) / zoom);\n\t\t\t\t} else {\n\t\t\t\t\tgrey.scale.set(icon.width(), (float) Math.floor(zoom * fadeHeight) / zoom);\n\t\t\t\t}\n\t\t\t} else if (!buff.iconTextDisplay().isEmpty()) {\n\t\t\t\ttext.visible = true;\n\t\t\t\tgrey.visible = false;\n\t\t\t\tif (buff.type == Buff.buffType.POSITIVE) text.hardlight(CharSprite.POSITIVE);\n\t\t\t\telse if (buff.type == Buff.buffType.NEGATIVE) text.hardlight(CharSprite.NEGATIVE);\n\t\t\t\ttext.alpha(0.7f);\n\n\t\t\t\ttext.text(buff.iconTextDisplay());\n\t\t\t\ttext.measure();\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tprotected void layout() {\n\t\t\tsuper.layout();\n\t\t\tgrey.x = icon.x = this.x + (large ? 0 : 1);\n\t\t\tgrey.y = icon.y = this.y + (large ? 0 : 2);\n\n\t\t\tif (text.width > width()){\n\t\t\t\ttext.scale.set(PixelScene.align(0.5f));\n\t\t\t} else {\n\t\t\t\ttext.scale.set(1f);\n\t\t\t}\n\t\t\ttext.x = this.x + width() - text.width() - 1;\n\t\t\ttext.y = this.y + width() - text.baseLine() - 2;\n\t\t}\n\n\t\t@Override\n\t\tprotected void onClick() {\n\t\t\tif (buff.icon() != NONE) GameScene.show(new WndInfoBuff(buff));\n\t\t}\n\n\t\t@Override\n\t\tprotected void onPointerDown() {\n\t\t\t//don't affect buff color\n\t\t\tSample.INSTANCE.play( Assets.Sounds.CLICK );\n\t\t}\n\n\t\t@Override\n\t\tprotected void onPointerUp() {\n\t\t\t//don't affect buff color\n\t\t}\n\n\t\t@Override\n\t\tprotected String hoverText() {\n\t\t\treturn Messages.titleCase(buff.name());\n\t\t}\n\t}\n\t\n\tpublic static void refreshHero() {\n\t\tif (heroInstance != null) {\n\t\t\theroInstance.needsRefresh = true;\n\t\t}\n\t}\n\n\tpublic static void refreshBoss(){\n\t\tif (bossInstance != null) {\n\t\t\tbossInstance.needsRefresh = true;\n\t\t}\n\t}\n\n\tpublic static void setBossInstance(BuffIndicator boss){\n\t\tbossInstance = boss;\n\t}\n}" }, { "identifier": "GLog", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/utils/GLog.java", "snippet": "public class GLog {\n\n\tpublic static final String TAG = \"GAME\";\n\t\n\tpublic static final String POSITIVE\t\t= \"++ \";\n\tpublic static final String NEGATIVE\t\t= \"-- \";\n\tpublic static final String WARNING\t\t= \"** \";\n\tpublic static final String HIGHLIGHT\t= \"@@ \";\n\n\tpublic static final String NEW_LINE\t = \"\\n\";\n\t\n\tpublic static Signal<String> update = new Signal<>();\n\n\tpublic static void newLine(){\n\t\tupdate.dispatch( NEW_LINE );\n\t}\n\t\n\tpublic static void i( String text, Object... args ) {\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttext = Messages.format( text, args );\n\t\t}\n\t\t\n\t\tDeviceCompat.log( TAG, text );\n\t\tupdate.dispatch( text );\n\t}\n\t\n\tpublic static void p( String text, Object... args ) {\n\t\ti( POSITIVE + text, args );\n\t}\n\t\n\tpublic static void n( String text, Object... args ) {\n\t\ti( NEGATIVE + text, args );\n\t}\n\t\n\tpublic static void w( String text, Object... args ) {\n\t\ti( WARNING + text, args );\n\t}\n\t\n\tpublic static void h( String text, Object... args ) {\n\t\ti( HIGHLIGHT + text, args );\n\t}\n}" }, { "identifier": "Bundle", "path": "SPD-classes/src/main/java/com/watabou/utils/Bundle.java", "snippet": "public class Bundle {\n\n\tprivate static final String CLASS_NAME = \"__className\";\n\n\tpublic static final String DEFAULT_KEY = \"key\";\n\n\tprivate static HashMap<String,String> aliases = new HashMap<>();\n\n\t/*\n\t\tWARNING: NOT ALL METHODS IN ORG.JSON ARE PRESENT ON ANDROID/IOS!\n\t\tMany methods which work on desktop will cause the game to crash on Android and iOS\n\n\t\tThis is because the Android runtime includes its own version of org.json which does not\n\t\timplement all methods. MobiVM uses the Android runtime and so this applies to iOS as well.\n\n\t\torg.json is very fast (~2x faster than libgdx JSON), which is why the game uses it despite\n\t\tthis dependency conflict.\n\n\t\tSee https://developer.android.com/reference/org/json/package-summary for details on\n\t\twhat methods exist in all versions of org.json. This class is also commented in places\n\t\tWhere Android/iOS force the use of unusual methods.\n\t */\n\tprivate JSONObject data;\n\n\tpublic Bundle() {\n\t\tthis( new JSONObject() );\n\t}\n\n\tpublic String toString() {\n\t\treturn data.toString();\n\t}\n\n\tprivate Bundle( JSONObject data ) {\n\t\tthis.data = data;\n\t}\n\n\tpublic boolean isNull() {\n\t\treturn data == null;\n\t}\n\n\tpublic boolean contains( String key ) {\n\t\treturn !isNull() && !data.isNull( key );\n\t}\n\n\tpublic boolean remove( String key ){\n\t\treturn data.remove(key) != null;\n\t}\n\n\t//JSONObject.keyset() doesn't exist on Android/iOS\n\tpublic ArrayList<String> getKeys(){\n\t\tIterator<String> keys = data.keys();\n\t\tArrayList<String> result = new ArrayList<>();\n\t\twhile (keys.hasNext()){\n\t\t\tresult.add(keys.next());\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic boolean getBoolean( String key ) {\n\t\treturn data.optBoolean( key );\n\t}\n\n\tpublic int getInt( String key ) {\n\t\treturn data.optInt( key );\n\t}\n\n\tpublic long getLong( String key ) {\n\t\treturn data.optLong( key );\n\t}\n\n\tpublic float getFloat( String key ) {\n\t\treturn (float)data.optDouble( key, 0.0 );\n\t}\n\n\tpublic String getString( String key ) {\n\t\treturn data.optString( key );\n\t}\n\n\tpublic Class getClass( String key ) {\n\t\tString clName = getString(key).replace(\"class \", \"\");\n\t\tif (!clName.equals(\"\")){\n\t\t\tif (aliases.containsKey( clName )) {\n\t\t\t\tclName = aliases.get( clName );\n\t\t\t}\n\n\t\t\treturn Reflection.forName( clName );\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic Bundle getBundle( String key ) {\n\t\treturn new Bundle( data.optJSONObject( key ) );\n\t}\n\n\tprivate Bundlable get() {\n\t\tif (data == null) return null;\n\n\t\tString clName = getString( CLASS_NAME );\n\t\tif (aliases.containsKey( clName )) {\n\t\t\tclName = aliases.get( clName );\n\t\t}\n\n\t\tClass<?> cl = Reflection.forName( clName );\n\t\t//Skip none-static inner classes as they can't be instantiated through bundle restoring\n\t\t//Classes which make use of none-static inner classes must manage instantiation manually\n\t\tif (cl != null && (!Reflection.isMemberClass(cl) || Reflection.isStatic(cl))) {\n\t\t\tBundlable object = (Bundlable) Reflection.newInstance(cl);\n\t\t\tif (object != null) {\n\t\t\t\tobject.restoreFromBundle(this);\n\t\t\t\treturn object;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic Bundlable get( String key ) {\n\t\treturn getBundle( key ).get();\n\t}\n\n\tpublic <E extends Enum<E>> E getEnum( String key, Class<E> enumClass ) {\n\t\ttry {\n\t\t\treturn Enum.valueOf( enumClass, data.getString( key ) );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn enumClass.getEnumConstants()[0];\n\t\t} catch (IllegalArgumentException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn enumClass.getEnumConstants()[0];\n\t\t}\n\t}\n\n\tpublic int[] getIntArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tint[] result = new int[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = array.getInt( i );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic long[] getLongArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tlong[] result = new long[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = array.getLong( i );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic float[] getFloatArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tfloat[] result = new float[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = (float)array.optDouble( i, 0.0 );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic boolean[] getBooleanArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tboolean[] result = new boolean[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = array.getBoolean( i );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic String[] getStringArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tString[] result = new String[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = array.getString( i );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Class[] getClassArray( String key ) {\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tClass[] result = new Class[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tString clName = array.getString( i ).replace(\"class \", \"\");\n\t\t\t\tif (aliases.containsKey( clName )) {\n\t\t\t\t\tclName = aliases.get( clName );\n\t\t\t\t}\n\t\t\t\tClass cl = Reflection.forName( clName );\n\t\t\t\tresult[i] = cl;\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Bundle[] getBundleArray(){\n\t\treturn getBundleArray( DEFAULT_KEY );\n\t}\n\n\tpublic Bundle[] getBundleArray( String key ){\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tint length = array.length();\n\t\t\tBundle[] result = new Bundle[length];\n\t\t\tfor (int i=0; i < length; i++) {\n\t\t\t\tresult[i] = new Bundle( array.getJSONObject( i ) );\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Collection<Bundlable> getCollection( String key ) {\n\n\t\tArrayList<Bundlable> list = new ArrayList<>();\n\n\t\ttry {\n\t\t\tJSONArray array = data.getJSONArray( key );\n\t\t\tfor (int i=0; i < array.length(); i++) {\n\t\t\t\tBundlable O = new Bundle( array.getJSONObject( i ) ).get();\n\t\t\t\tif (O != null) list.add( O );\n\t\t\t}\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\n\t\treturn list;\n\t}\n\n\tpublic void put( String key, boolean value ) {\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, int value ) {\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, long value ) {\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, float value ) {\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, String value ) {\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, Class value ){\n\t\ttry {\n\t\t\tdata.put( key, value );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, Bundle bundle ) {\n\t\ttry {\n\t\t\tdata.put( key, bundle.data );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, Bundlable object ) {\n\t\tif (object != null) {\n\t\t\ttry {\n\t\t\t\tBundle bundle = new Bundle();\n\t\t\t\tbundle.put( CLASS_NAME, object.getClass().getName() );\n\t\t\t\tobject.storeInBundle( bundle );\n\t\t\t\tdata.put( key, bundle.data );\n\t\t\t} catch (JSONException e) {\n\t\t\t\tGame.reportException(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void put( String key, Enum<?> value ) {\n\t\tif (value != null) {\n\t\t\ttry {\n\t\t\t\tdata.put( key, value.name() );\n\t\t\t} catch (JSONException e) {\n\t\t\t\tGame.reportException(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void put( String key, int[] array ) {\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i] );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, long[] array ) {\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i] );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, float[] array ) {\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i] );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, boolean[] array ) {\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i] );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, String[] array ) {\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i] );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, Class[] array ){\n\t\ttry {\n\t\t\tJSONArray jsonArray = new JSONArray();\n\t\t\tfor (int i=0; i < array.length; i++) {\n\t\t\t\tjsonArray.put( i, array[i].getName() );\n\t\t\t}\n\t\t\tdata.put( key, jsonArray );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\tpublic void put( String key, Collection<? extends Bundlable> collection ) {\n\t\tJSONArray array = new JSONArray();\n\t\tfor (Bundlable object : collection) {\n\t\t\t//Skip none-static inner classes as they can't be instantiated through bundle restoring\n\t\t\t//Classes which make use of none-static inner classes must manage instantiation manually\n\t\t\tif (object != null) {\n\t\t\t\tClass cl = object.getClass();\n\t\t\t\tif ((!Reflection.isMemberClass(cl) || Reflection.isStatic(cl))) {\n\t\t\t\t\tBundle bundle = new Bundle();\n\t\t\t\t\tbundle.put(CLASS_NAME, cl.getName());\n\t\t\t\t\tobject.storeInBundle(bundle);\n\t\t\t\t\tarray.put(bundle.data);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tdata.put( key, array );\n\t\t} catch (JSONException e) {\n\t\t\tGame.reportException(e);\n\t\t}\n\t}\n\n\t//useful to turn this off for save data debugging.\n\tprivate static final boolean compressByDefault = true;\n\n\tprivate static final int GZIP_BUFFER = 1024*4; //4 kb\n\n\tpublic static Bundle read( InputStream stream ) throws IOException {\n\n\t\ttry {\n\t\t\tif (!stream.markSupported()){\n\t\t\t\tstream = new BufferedInputStream( stream, 2 );\n\t\t\t}\n\n\t\t\t//determines if we're reading a regular, or compressed file\n\t\t\tstream.mark( 2 );\n\t\t\tbyte[] header = new byte[2];\n\t\t\tstream.read( header );\n\t\t\tstream.reset();\n\n\t\t\t//GZIP header is 0x1f8b\n\t\t\tif( header[ 0 ] == (byte) 0x1f && header[ 1 ] == (byte) 0x8b ) {\n\t\t\t\tstream = new GZIPInputStream( stream, GZIP_BUFFER );\n\t\t\t}\n\n\t\t\t//JSONTokenizer only has a string-based constructor on Android/iOS\n\t\t\tBufferedReader reader = new BufferedReader( new InputStreamReader( stream ));\n\t\t\tStringBuilder jsonBuilder = new StringBuilder();\n\n\t\t\tString line;\n\t\t\twhile ((line = reader.readLine()) != null) {\n\t\t\t\tjsonBuilder.append(line);\n\t\t\t\tjsonBuilder.append(\"\\n\");\n\t\t\t}\n\t\t\tString jsonString = jsonBuilder.toString();\n\n\t\t\tObject json;\n\t\t\ttry {\n\t\t\t\tjson = new JSONTokener(jsonString).nextValue();\n\t\t\t} catch (Exception e){\n\t\t\t\t//if the string can't be tokenized, it may be written by v1.1.X, which used libGDX JSON.\n\t\t\t\t// Some of these are written in a 'minified' format, some have duplicate keys.\n\t\t\t\t// We read them in with the libGDX JSON code, fix duplicates, write as full JSON\n\t\t\t\t// and then try to read again with org.json\n\t\t\t\tGame.reportException(e);\n\t\t\t\tJsonValue gdxJSON = new JsonReader().parse(jsonString);\n\t\t\t\tkillDuplicateKeysInLibGDXJSON(gdxJSON);\n\t\t\t\tjson = new JSONTokener(gdxJSON.prettyPrint(JsonWriter.OutputType.json, 0)).nextValue();\n\t\t\t}\n\t\t\treader.close();\n\n\t\t\t//if the data is an array, put it in a fresh object with the default key\n\t\t\tif (json instanceof JSONArray){\n\t\t\t\tjson = new JSONObject().put( DEFAULT_KEY, json );\n\t\t\t}\n\n\t\t\treturn new Bundle( (JSONObject) json );\n\t\t} catch (Exception e) {\n\t\t\tGame.reportException(e);\n\t\t\tthrow new IOException();\n\t\t}\n\t}\n\n\tprivate static void killDuplicateKeysInLibGDXJSON(JsonValue val){\n\t\tHashSet<String> keys = new HashSet<>();\n\t\twhile(val != null) {\n\t\t\tif (val.name != null && keys.contains(val.name)){\n\t\t\t\t//delete the duplicate key\n\t\t\t\tval.prev.next = val.next;\n\t\t\t\tif (val.next != null) val.next.prev = val.prev;\n\t\t\t\tval.parent.size--;\n\t\t\t} else {\n\t\t\t\tkeys.add(val.name);\n\t\t\t\tif (val.child != null){\n\t\t\t\t\tkillDuplicateKeysInLibGDXJSON(val.child);\n\t\t\t\t}\n\t\t\t}\n\t\t\tval = val.next;\n\t\t}\n\t}\n\n\tpublic static boolean write( Bundle bundle, OutputStream stream ){\n\t\treturn write(bundle, stream, compressByDefault);\n\t}\n\n\tpublic static boolean write( Bundle bundle, OutputStream stream, boolean compressed ) {\n\t\ttry {\n\t\t\tBufferedWriter writer;\n\t\t\tif (compressed) writer = new BufferedWriter( new OutputStreamWriter( new GZIPOutputStream(stream, GZIP_BUFFER ) ) );\n\t\t\telse writer = new BufferedWriter( new OutputStreamWriter( stream ) );\n\n\t\t\t//JSONObject.write does not exist on Android/iOS\n\t\t\twriter.write(bundle.data.toString());\n\t\t\twriter.close();\n\n\t\t\treturn true;\n\t\t} catch (IOException e) {\n\t\t\tGame.reportException(e);\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic static void addAlias( Class<?> cl, String alias ) {\n\t\taliases.put( alias, cl.getName() );\n\t}\n\t\n}" }, { "identifier": "Random", "path": "SPD-classes/src/main/java/com/watabou/utils/Random.java", "snippet": "public class Random {\n\n\t//we store a stack of random number generators, which may be seeded deliberately or randomly.\n\t//top of the stack is what is currently being used to generate new numbers.\n\t//the base generator is always created with no seed, and cannot be popped.\n\tprivate static ArrayDeque<java.util.Random> generators;\n\tstatic {\n\t\tresetGenerators();\n\t}\n\n\tpublic static synchronized void resetGenerators(){\n\t\tgenerators = new ArrayDeque<>();\n\t\tgenerators.push(new java.util.Random());\n\t}\n\n\tpublic static synchronized void pushGenerator(){\n\t\tgenerators.push( new java.util.Random() );\n\t}\n\n\tpublic static synchronized void pushGenerator( long seed ){\n\t\tgenerators.push( new java.util.Random( scrambleSeed(seed) ) );\n\t}\n\n\t//scrambles a given seed, this helps eliminate patterns between the outputs of similar seeds\n\t//Algorithm used is MX3 by Jon Maiga (jonkagstrom.com), CC0 license.\n\tprivate static synchronized long scrambleSeed( long seed ){\n\t\tseed ^= seed >>> 32;\n\t\tseed *= 0xbea225f9eb34556dL;\n\t\tseed ^= seed >>> 29;\n\t\tseed *= 0xbea225f9eb34556dL;\n\t\tseed ^= seed >>> 32;\n\t\tseed *= 0xbea225f9eb34556dL;\n\t\tseed ^= seed >>> 29;\n\t\treturn seed;\n\t}\n\n\tpublic static synchronized void popGenerator(){\n\t\tif (generators.size() == 1){\n\t\t\tGame.reportException( new RuntimeException(\"tried to pop the last random number generator!\"));\n\t\t} else {\n\t\t\tgenerators.pop();\n\t\t}\n\t}\n\n\t//returns a uniformly distributed float in the range [0, 1)\n\tpublic static synchronized float Float() {\n\t\treturn generators.peek().nextFloat();\n\t}\n\n\t//returns a uniformly distributed float in the range [0, max)\n\tpublic static float Float( float max ) {\n\t\treturn Float() * max;\n\t}\n\n\t//returns a uniformly distributed float in the range [min, max)\n\tpublic static float Float( float min, float max ) {\n\t\treturn min + Float(max - min);\n\t}\n\t\n\t//returns a triangularly distributed float in the range [min, max)\n\tpublic static float NormalFloat( float min, float max ) {\n\t\treturn min + ((Float(max - min) + Float(max - min))/2f);\n\t}\n\n\t//returns a uniformly distributed int in the range [0, max)\n\tpublic static synchronized int Int( int max ) {\n\t\treturn max > 0 ? generators.peek().nextInt(max) : 0;\n\t}\n\n\t//returns a uniformly distributed int in the range [min, max)\n\tpublic static int Int( int min, int max ) {\n\t\treturn min + Int(max - min);\n\t}\n\n\t//returns a uniformly distributed int in the range [min, max]\n\tpublic static int IntRange( int min, int max ) {\n\t\treturn min + Int(max - min + 1);\n\t}\n\n\t//returns a triangularly distributed int in the range [min, max]\n\tpublic static int NormalIntRange( int min, int max ) {\n\t\treturn min + (int)((Float() + Float()) * (max - min + 1) / 2f);\n\t}\n\n\t//returns a uniformly distributed long in the range [-2^63, 2^63)\n\tpublic static synchronized long Long() {\n\t\treturn generators.peek().nextLong();\n\t}\n\n\t//returns a uniformly distributed long in the range [0, max)\n\tpublic static long Long( long max ) {\n\t\tlong result = Long();\n\t\tif (result < 0) result += Long.MAX_VALUE;\n\t\treturn result % max;\n\t}\n\n\t//returns an index from chances, the probability of each index is the weight values in changes\n\tpublic static int chances( float[] chances ) {\n\t\t\n\t\tint length = chances.length;\n\t\t\n\t\tfloat sum = 0;\n\t\tfor (int i=0; i < length; i++) {\n\t\t\tsum += chances[i];\n\t\t}\n\t\t\n\t\tfloat value = Float( sum );\n\t\tsum = 0;\n\t\tfor (int i=0; i < length; i++) {\n\t\t\tsum += chances[i];\n\t\t\tif (value < sum) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn -1;\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\t//returns a key element from chances, the probability of each key is the weight value it maps to\n\tpublic static <K> K chances( HashMap<K,Float> chances ) {\n\t\t\n\t\tint size = chances.size();\n\n\t\tObject[] values = chances.keySet().toArray();\n\t\tfloat[] probs = new float[size];\n\t\tfloat sum = 0;\n\t\tfor (int i=0; i < size; i++) {\n\t\t\tprobs[i] = chances.get( values[i] );\n\t\t\tsum += probs[i];\n\t\t}\n\t\t\n\t\tif (sum <= 0) {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tfloat value = Float( sum );\n\t\t\n\t\tsum = probs[0];\n\t\tfor (int i=0; i < size; i++) {\n\t\t\tif (value < sum) {\n\t\t\t\treturn (K)values[i];\n\t\t\t}\n\t\t\tsum += probs[i + 1];\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic static int index( Collection<?> collection ) {\n\t\treturn Int(collection.size());\n\t}\n\n\t@SafeVarargs\n\tpublic static<T> T oneOf(T... array ) {\n\t\treturn array[Int(array.length)];\n\t}\n\t\n\tpublic static<T> T element( T[] array ) {\n\t\treturn element( array, array.length );\n\t}\n\t\n\tpublic static<T> T element( T[] array, int max ) {\n\t\treturn array[Int(max)];\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static<T> T element( Collection<? extends T> collection ) {\n\t\tint size = collection.size();\n\t\treturn size > 0 ?\n\t\t\t(T)collection.toArray()[Int( size )] :\n\t\t\tnull;\n\t}\n\n\tpublic synchronized static<T> void shuffle( List<?extends T> list){\n\t\tCollections.shuffle(list, generators.peek());\n\t}\n\t\n\tpublic static<T> void shuffle( T[] array ) {\n\t\tfor (int i=0; i < array.length - 1; i++) {\n\t\t\tint j = Int( i, array.length );\n\t\t\tif (j != i) {\n\t\t\t\tT t = array[i];\n\t\t\t\tarray[i] = array[j];\n\t\t\t\tarray[j] = t;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static<U,V> void shuffle( U[] u, V[]v ) {\n\t\tfor (int i=0; i < u.length - 1; i++) {\n\t\t\tint j = Int( i, u.length );\n\t\t\tif (j != i) {\n\t\t\t\tU ut = u[i];\n\t\t\t\tu[i] = u[j];\n\t\t\t\tu[j] = ut;\n\t\t\t\t\n\t\t\t\tV vt = v[i];\n\t\t\t\tv[i] = v[j];\n\t\t\t\tv[j] = vt;\n\t\t\t}\n\t\t}\n\t}\n}" } ]
import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.actors.Actor; import com.shatteredpixel.shatteredpixeldungeon.actors.Char; import com.shatteredpixel.shatteredpixeldungeon.actors.blobs.CorrosiveGas; import com.shatteredpixel.shatteredpixeldungeon.actors.blobs.ToxicGas; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.AllyBuff; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Burning; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Invisibility; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero; import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.Mob; import com.shatteredpixel.shatteredpixeldungeon.items.rings.RingOfAccuracy; import com.shatteredpixel.shatteredpixeldungeon.items.rings.RingOfEvasion; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.sprites.CharSprite; import com.shatteredpixel.shatteredpixeldungeon.sprites.MirrorSprite; import com.shatteredpixel.shatteredpixeldungeon.ui.BuffIndicator; import com.shatteredpixel.shatteredpixeldungeon.utils.GLog; import com.watabou.utils.Bundle; import com.watabou.utils.Random;
83,319
armTier = hero.tier(); ((MirrorSprite)sprite).updateArmor( armTier ); } return super.act(); } private static final String HEROID = "hero_id"; @Override public void storeInBundle( Bundle bundle ) { super.storeInBundle( bundle ); bundle.put( HEROID, heroID ); } @Override public void restoreFromBundle( Bundle bundle ) { super.restoreFromBundle( bundle ); heroID = bundle.getInt( HEROID ); } public void duplicate( Hero hero ) { this.hero = hero; heroID = this.hero.id(); Buff.affect(this, MirrorInvis.class, Short.MAX_VALUE); } @Override public int damageRoll() { int damage; if (hero.belongings.weapon() != null){ damage = hero.belongings.weapon().damageRoll(this); } else { damage = hero.damageRoll(); //handles ring of force } return (damage+1)/2; //half hero damage, rounded up } @Override public int attackSkill( Char target ) { //same base attack skill as hero, benefits from accuracy ring and weapon int attackSkill = 9 + hero.lvl; attackSkill *= RingOfAccuracy.accuracyMultiplier(hero); if (hero.belongings.attackingWeapon() != null){ attackSkill *= hero.belongings.attackingWeapon().accuracyFactor(this, target); } return attackSkill; } @Override public int defenseSkill(Char enemy) { if (hero != null) { int baseEvasion = 4 + hero.lvl; int heroEvasion = (int)((4 + hero.lvl) * RingOfEvasion.evasionMultiplier( hero )); //if the hero has more/less evasion, 50% of it is applied //includes ring of evasion boost return super.defenseSkill(enemy) * (baseEvasion + heroEvasion) / 2; } else { return 0; } } @Override public float attackDelay() { return hero.attackDelay(); //handles ring of furor } @Override protected boolean canAttack(Char enemy) { return super.canAttack(enemy) || (hero.belongings.weapon() != null && hero.belongings.weapon().canReach(this, enemy.pos)); } @Override public int drRoll() { int dr = super.drRoll(); if (hero != null && hero.belongings.weapon() != null){ return dr + Random.NormalIntRange(0, hero.belongings.weapon().defenseFactor(this)/2); } else { return dr; } } @Override public int attackProc( Char enemy, int damage ) { damage = super.attackProc( enemy, damage ); MirrorInvis buff = buff(MirrorInvis.class); if (buff != null){ buff.detach(); } if (enemy instanceof Mob) { ((Mob)enemy).aggro( this ); } if (hero.belongings.weapon() != null){ damage = hero.belongings.weapon().proc( this, enemy, damage ); if (!enemy.isAlive() && enemy == Dungeon.hero){ Dungeon.fail(this); GLog.n( Messages.capitalize(Messages.get(Char.class, "kill", name())) ); } return damage; } else { return damage; } } @Override public CharSprite sprite() { CharSprite s = super.sprite(); hero = (Hero)Actor.findById(heroID); if (hero != null) { armTier = hero.tier(); } ((MirrorSprite)s).updateArmor( armTier ); return s; } {
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs; public class MirrorImage extends NPC { { spriteClass = MirrorSprite.class; HP = HT = 1; defenseSkill = 1; alignment = Alignment.ALLY; state = HUNTING; //before other mobs actPriority = MOB_PRIO + 1; } private Hero hero; private int heroID; public int armTier; @Override protected boolean act() { if ( hero == null ){ hero = (Hero)Actor.findById(heroID); if ( hero == null ){ die(null); sprite.killAndErase(); return true; } } if (hero.tier() != armTier){ armTier = hero.tier(); ((MirrorSprite)sprite).updateArmor( armTier ); } return super.act(); } private static final String HEROID = "hero_id"; @Override public void storeInBundle( Bundle bundle ) { super.storeInBundle( bundle ); bundle.put( HEROID, heroID ); } @Override public void restoreFromBundle( Bundle bundle ) { super.restoreFromBundle( bundle ); heroID = bundle.getInt( HEROID ); } public void duplicate( Hero hero ) { this.hero = hero; heroID = this.hero.id(); Buff.affect(this, MirrorInvis.class, Short.MAX_VALUE); } @Override public int damageRoll() { int damage; if (hero.belongings.weapon() != null){ damage = hero.belongings.weapon().damageRoll(this); } else { damage = hero.damageRoll(); //handles ring of force } return (damage+1)/2; //half hero damage, rounded up } @Override public int attackSkill( Char target ) { //same base attack skill as hero, benefits from accuracy ring and weapon int attackSkill = 9 + hero.lvl; attackSkill *= RingOfAccuracy.accuracyMultiplier(hero); if (hero.belongings.attackingWeapon() != null){ attackSkill *= hero.belongings.attackingWeapon().accuracyFactor(this, target); } return attackSkill; } @Override public int defenseSkill(Char enemy) { if (hero != null) { int baseEvasion = 4 + hero.lvl; int heroEvasion = (int)((4 + hero.lvl) * RingOfEvasion.evasionMultiplier( hero )); //if the hero has more/less evasion, 50% of it is applied //includes ring of evasion boost return super.defenseSkill(enemy) * (baseEvasion + heroEvasion) / 2; } else { return 0; } } @Override public float attackDelay() { return hero.attackDelay(); //handles ring of furor } @Override protected boolean canAttack(Char enemy) { return super.canAttack(enemy) || (hero.belongings.weapon() != null && hero.belongings.weapon().canReach(this, enemy.pos)); } @Override public int drRoll() { int dr = super.drRoll(); if (hero != null && hero.belongings.weapon() != null){ return dr + Random.NormalIntRange(0, hero.belongings.weapon().defenseFactor(this)/2); } else { return dr; } } @Override public int attackProc( Char enemy, int damage ) { damage = super.attackProc( enemy, damage ); MirrorInvis buff = buff(MirrorInvis.class); if (buff != null){ buff.detach(); } if (enemy instanceof Mob) { ((Mob)enemy).aggro( this ); } if (hero.belongings.weapon() != null){ damage = hero.belongings.weapon().proc( this, enemy, damage ); if (!enemy.isAlive() && enemy == Dungeon.hero){ Dungeon.fail(this); GLog.n( Messages.capitalize(Messages.get(Char.class, "kill", name())) ); } return damage; } else { return damage; } } @Override public CharSprite sprite() { CharSprite s = super.sprite(); hero = (Hero)Actor.findById(heroID); if (hero != null) { armTier = hero.tier(); } ((MirrorSprite)s).updateArmor( armTier ); return s; } {
immunities.add( ToxicGas.class );
4
2023-11-27 05:56:58+00:00
128k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/tests/org/jfree/chart/renderer/xy/XYAreaRenderer2Test.java
[ { "identifier": "JFreeChart", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/JFreeChart.java", "snippet": "public class JFreeChart implements Drawable, TitleChangeListener,\r\n PlotChangeListener, Serializable, Cloneable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -3470703747817429120L;\r\n\r\n /** Information about the project. */\r\n public static final ProjectInfo INFO = new JFreeChartInfo();\r\n\r\n /** The default font for titles. */\r\n public static final Font DEFAULT_TITLE_FONT\r\n = new Font(\"SansSerif\", Font.BOLD, 18);\r\n\r\n /** The default background color. */\r\n public static final Paint DEFAULT_BACKGROUND_PAINT\r\n = UIManager.getColor(\"Panel.background\");\r\n\r\n /** The default background image. */\r\n public static final Image DEFAULT_BACKGROUND_IMAGE = null;\r\n\r\n /** The default background image alignment. */\r\n public static final int DEFAULT_BACKGROUND_IMAGE_ALIGNMENT = Align.FIT;\r\n\r\n /** The default background image alpha. */\r\n public static final float DEFAULT_BACKGROUND_IMAGE_ALPHA = 0.5f;\r\n\r\n /**\r\n * The key for a rendering hint that can suppress the generation of a \r\n * shadow effect when drawing the chart. The hint value must be a \r\n * Boolean.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static final RenderingHints.Key KEY_SUPPRESS_SHADOW_GENERATION\r\n = new RenderingHints.Key(0) {\r\n @Override\r\n public boolean isCompatibleValue(Object val) {\r\n return val instanceof Boolean;\r\n }\r\n };\r\n \r\n /**\r\n * Rendering hints that will be used for chart drawing. This should never\r\n * be <code>null</code>.\r\n */\r\n private transient RenderingHints renderingHints;\r\n\r\n /** A flag that controls whether or not the chart border is drawn. */\r\n private boolean borderVisible;\r\n\r\n /** The stroke used to draw the chart border (if visible). */\r\n private transient Stroke borderStroke;\r\n\r\n /** The paint used to draw the chart border (if visible). */\r\n private transient Paint borderPaint;\r\n\r\n /** The padding between the chart border and the chart drawing area. */\r\n private RectangleInsets padding;\r\n\r\n /** The chart title (optional). */\r\n private TextTitle title;\r\n\r\n /**\r\n * The chart subtitles (zero, one or many). This field should never be\r\n * <code>null</code>.\r\n */\r\n private List subtitles;\r\n\r\n /** Draws the visual representation of the data. */\r\n private Plot plot;\r\n\r\n /** Paint used to draw the background of the chart. */\r\n private transient Paint backgroundPaint;\r\n\r\n /** An optional background image for the chart. */\r\n private transient Image backgroundImage; // todo: not serialized yet\r\n\r\n /** The alignment for the background image. */\r\n private int backgroundImageAlignment = Align.FIT;\r\n\r\n /** The alpha transparency for the background image. */\r\n private float backgroundImageAlpha = 0.5f;\r\n\r\n /** Storage for registered change listeners. */\r\n private transient EventListenerList changeListeners;\r\n\r\n /** Storage for registered progress listeners. */\r\n private transient EventListenerList progressListeners;\r\n\r\n /**\r\n * A flag that can be used to enable/disable notification of chart change\r\n * events.\r\n */\r\n private boolean notify;\r\n\r\n /**\r\n * Creates a new chart based on the supplied plot. The chart will have\r\n * a legend added automatically, but no title (although you can easily add\r\n * one later).\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(Plot plot) {\r\n this(null, null, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. A default font\r\n * ({@link #DEFAULT_TITLE_FONT}) is used for the title, and the chart will\r\n * have a legend added automatically.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(String title, Plot plot) {\r\n this(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. The\r\n * <code>createLegend</code> argument specifies whether or not a legend\r\n * should be added to the chart.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param titleFont the font for displaying the chart title\r\n * (<code>null</code> permitted).\r\n * @param plot controller of the visual representation of the data\r\n * (<code>null</code> not permitted).\r\n * @param createLegend a flag indicating whether or not a legend should\r\n * be created for the chart.\r\n */\r\n public JFreeChart(String title, Font titleFont, Plot plot,\r\n boolean createLegend) {\r\n\r\n ParamChecks.nullNotPermitted(plot, \"plot\");\r\n\r\n // create storage for listeners...\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.notify = true; // default is to notify listeners when the\r\n // chart changes\r\n\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n // added the following hint because of \r\n // http://stackoverflow.com/questions/7785082/\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n this.borderVisible = false;\r\n this.borderStroke = new BasicStroke(1.0f);\r\n this.borderPaint = Color.black;\r\n\r\n this.padding = RectangleInsets.ZERO_INSETS;\r\n\r\n this.plot = plot;\r\n plot.addChangeListener(this);\r\n\r\n this.subtitles = new ArrayList();\r\n\r\n // create a legend, if requested...\r\n if (createLegend) {\r\n LegendTitle legend = new LegendTitle(this.plot);\r\n legend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));\r\n legend.setFrame(new LineBorder());\r\n legend.setBackgroundPaint(Color.white);\r\n legend.setPosition(RectangleEdge.BOTTOM);\r\n this.subtitles.add(legend);\r\n legend.addChangeListener(this);\r\n }\r\n\r\n // add the chart title, if one has been specified...\r\n if (title != null) {\r\n if (titleFont == null) {\r\n titleFont = DEFAULT_TITLE_FONT;\r\n }\r\n this.title = new TextTitle(title, titleFont);\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n this.backgroundPaint = DEFAULT_BACKGROUND_PAINT;\r\n\r\n this.backgroundImage = DEFAULT_BACKGROUND_IMAGE;\r\n this.backgroundImageAlignment = DEFAULT_BACKGROUND_IMAGE_ALIGNMENT;\r\n this.backgroundImageAlpha = DEFAULT_BACKGROUND_IMAGE_ALPHA;\r\n\r\n }\r\n\r\n /**\r\n * Returns the collection of rendering hints for the chart.\r\n *\r\n * @return The rendering hints for the chart (never <code>null</code>).\r\n *\r\n * @see #setRenderingHints(RenderingHints)\r\n */\r\n public RenderingHints getRenderingHints() {\r\n return this.renderingHints;\r\n }\r\n\r\n /**\r\n * Sets the rendering hints for the chart. These will be added (using the\r\n * {@code Graphics2D.addRenderingHints()} method) near the start of the\r\n * {@code JFreeChart.draw()} method.\r\n *\r\n * @param renderingHints the rendering hints ({@code null} not permitted).\r\n *\r\n * @see #getRenderingHints()\r\n */\r\n public void setRenderingHints(RenderingHints renderingHints) {\r\n ParamChecks.nullNotPermitted(renderingHints, \"renderingHints\");\r\n this.renderingHints = renderingHints;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setBorderVisible(boolean)\r\n */\r\n public boolean isBorderVisible() {\r\n return this.borderVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isBorderVisible()\r\n */\r\n public void setBorderVisible(boolean visible) {\r\n this.borderVisible = visible;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the chart border (if visible).\r\n *\r\n * @return The border stroke.\r\n *\r\n * @see #setBorderStroke(Stroke)\r\n */\r\n public Stroke getBorderStroke() {\r\n return this.borderStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the chart border (if visible).\r\n *\r\n * @param stroke the stroke.\r\n *\r\n * @see #getBorderStroke()\r\n */\r\n public void setBorderStroke(Stroke stroke) {\r\n this.borderStroke = stroke;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the chart border (if visible).\r\n *\r\n * @return The border paint.\r\n *\r\n * @see #setBorderPaint(Paint)\r\n */\r\n public Paint getBorderPaint() {\r\n return this.borderPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the chart border (if visible).\r\n *\r\n * @param paint the paint.\r\n *\r\n * @see #getBorderPaint()\r\n */\r\n public void setBorderPaint(Paint paint) {\r\n this.borderPaint = paint;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the padding between the chart border and the chart drawing area.\r\n *\r\n * @return The padding (never <code>null</code>).\r\n *\r\n * @see #setPadding(RectangleInsets)\r\n */\r\n public RectangleInsets getPadding() {\r\n return this.padding;\r\n }\r\n\r\n /**\r\n * Sets the padding between the chart border and the chart drawing area,\r\n * and sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param padding the padding (<code>null</code> not permitted).\r\n *\r\n * @see #getPadding()\r\n */\r\n public void setPadding(RectangleInsets padding) {\r\n ParamChecks.nullNotPermitted(padding, \"padding\");\r\n this.padding = padding;\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the main chart title. Very often a chart will have just one\r\n * title, so we make this case simple by providing accessor methods for\r\n * the main title. However, multiple titles are supported - see the\r\n * {@link #addSubtitle(Title)} method.\r\n *\r\n * @return The chart title (possibly <code>null</code>).\r\n *\r\n * @see #setTitle(TextTitle)\r\n */\r\n public TextTitle getTitle() {\r\n return this.title;\r\n }\r\n\r\n /**\r\n * Sets the main title for the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners. If you do not want a title for the\r\n * chart, set it to <code>null</code>. If you want more than one title on\r\n * a chart, use the {@link #addSubtitle(Title)} method.\r\n *\r\n * @param title the title (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(TextTitle title) {\r\n if (this.title != null) {\r\n this.title.removeChangeListener(this);\r\n }\r\n this.title = title;\r\n if (title != null) {\r\n title.addChangeListener(this);\r\n }\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Sets the chart title and sends a {@link ChartChangeEvent} to all\r\n * registered listeners. This is a convenience method that ends up calling\r\n * the {@link #setTitle(TextTitle)} method. If there is an existing title,\r\n * its text is updated, otherwise a new title using the default font is\r\n * added to the chart. If <code>text</code> is <code>null</code> the chart\r\n * title is set to <code>null</code>.\r\n *\r\n * @param text the title text (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(String text) {\r\n if (text != null) {\r\n if (this.title == null) {\r\n setTitle(new TextTitle(text, JFreeChart.DEFAULT_TITLE_FONT));\r\n }\r\n else {\r\n this.title.setText(text);\r\n }\r\n }\r\n else {\r\n setTitle((TextTitle) null);\r\n }\r\n }\r\n\r\n /**\r\n * Adds a legend to the plot and sends a {@link ChartChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param legend the legend (<code>null</code> not permitted).\r\n *\r\n * @see #removeLegend()\r\n */\r\n public void addLegend(LegendTitle legend) {\r\n addSubtitle(legend);\r\n }\r\n\r\n /**\r\n * Returns the legend for the chart, if there is one. Note that a chart\r\n * can have more than one legend - this method returns the first.\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #getLegend(int)\r\n */\r\n public LegendTitle getLegend() {\r\n return getLegend(0);\r\n }\r\n\r\n /**\r\n * Returns the nth legend for a chart, or <code>null</code>.\r\n *\r\n * @param index the legend index (zero-based).\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #addLegend(LegendTitle)\r\n */\r\n public LegendTitle getLegend(int index) {\r\n int seen = 0;\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title subtitle = (Title) iterator.next();\r\n if (subtitle instanceof LegendTitle) {\r\n if (seen == index) {\r\n return (LegendTitle) subtitle;\r\n }\r\n else {\r\n seen++;\r\n }\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Removes the first legend in the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @see #getLegend()\r\n */\r\n public void removeLegend() {\r\n removeSubtitle(getLegend());\r\n }\r\n\r\n /**\r\n * Returns the list of subtitles for the chart.\r\n *\r\n * @return The subtitle list (possibly empty, but never <code>null</code>).\r\n *\r\n * @see #setSubtitles(List)\r\n */\r\n public List getSubtitles() {\r\n return new ArrayList(this.subtitles);\r\n }\r\n\r\n /**\r\n * Sets the title list for the chart (completely replaces any existing\r\n * titles) and sends a {@link ChartChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param subtitles the new list of subtitles (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public void setSubtitles(List subtitles) {\r\n if (subtitles == null) {\r\n throw new NullPointerException(\"Null 'subtitles' argument.\");\r\n }\r\n setNotify(false);\r\n clearSubtitles();\r\n Iterator iterator = subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n if (t != null) {\r\n addSubtitle(t);\r\n }\r\n }\r\n setNotify(true); // this fires a ChartChangeEvent\r\n }\r\n\r\n /**\r\n * Returns the number of titles for the chart.\r\n *\r\n * @return The number of titles for the chart.\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public int getSubtitleCount() {\r\n return this.subtitles.size();\r\n }\r\n\r\n /**\r\n * Returns a chart subtitle.\r\n *\r\n * @param index the index of the chart subtitle (zero based).\r\n *\r\n * @return A chart subtitle.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public Title getSubtitle(int index) {\r\n if ((index < 0) || (index >= getSubtitleCount())) {\r\n throw new IllegalArgumentException(\"Index out of range.\");\r\n }\r\n return (Title) this.subtitles.get(index);\r\n }\r\n\r\n /**\r\n * Adds a chart subtitle, and notifies registered listeners that the chart\r\n * has been modified.\r\n *\r\n * @param subtitle the subtitle (<code>null</code> not permitted).\r\n *\r\n * @see #getSubtitle(int)\r\n */\r\n public void addSubtitle(Title subtitle) {\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Adds a subtitle at a particular position in the subtitle list, and sends\r\n * a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param index the index (in the range 0 to {@link #getSubtitleCount()}).\r\n * @param subtitle the subtitle to add (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.6\r\n */\r\n public void addSubtitle(int index, Title subtitle) {\r\n if (index < 0 || index > getSubtitleCount()) {\r\n throw new IllegalArgumentException(\r\n \"The 'index' argument is out of range.\");\r\n }\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(index, subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Clears all subtitles from the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void clearSubtitles() {\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n t.removeChangeListener(this);\r\n }\r\n this.subtitles.clear();\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Removes the specified subtitle and sends a {@link ChartChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param title the title.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void removeSubtitle(Title title) {\r\n this.subtitles.remove(title);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the plot for the chart. The plot is a class responsible for\r\n * coordinating the visual representation of the data, including the axes\r\n * (if any).\r\n *\r\n * @return The plot.\r\n */\r\n public Plot getPlot() {\r\n return this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as a {@link CategoryPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link CategoryPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public CategoryPlot getCategoryPlot() {\r\n return (CategoryPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as an {@link XYPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link XYPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public XYPlot getXYPlot() {\r\n return (XYPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns a flag that indicates whether or not anti-aliasing is used when\r\n * the chart is drawn.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAntiAlias(boolean)\r\n */\r\n public boolean getAntiAlias() {\r\n Object val = this.renderingHints.get(RenderingHints.KEY_ANTIALIASING);\r\n return RenderingHints.VALUE_ANTIALIAS_ON.equals(val);\r\n }\r\n\r\n /**\r\n * Sets a flag that indicates whether or not anti-aliasing is used when the\r\n * chart is drawn.\r\n * <P>\r\n * Anti-aliasing usually improves the appearance of charts, but is slower.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #getAntiAlias()\r\n */\r\n public void setAntiAlias(boolean flag) {\r\n Object hint = flag ? RenderingHints.VALUE_ANTIALIAS_ON \r\n : RenderingHints.VALUE_ANTIALIAS_OFF;\r\n this.renderingHints.put(RenderingHints.KEY_ANTIALIASING, hint);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the current value stored in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING}.\r\n *\r\n * @return The hint value (possibly <code>null</code>).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public Object getTextAntiAlias() {\r\n return this.renderingHints.get(RenderingHints.KEY_TEXT_ANTIALIASING);\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} to either\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_ON} or\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_OFF}, then sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public void setTextAntiAlias(boolean flag) {\r\n if (flag) {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\r\n }\r\n else {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);\r\n }\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param val the new value (<code>null</code> permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(boolean)\r\n */\r\n public void setTextAntiAlias(Object val) {\r\n this.renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, val);\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the paint used for the chart background.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundPaint(Paint)\r\n */\r\n public Paint getBackgroundPaint() {\r\n return this.backgroundPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to fill the chart background and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundPaint()\r\n */\r\n public void setBackgroundPaint(Paint paint) {\r\n\r\n if (this.backgroundPaint != null) {\r\n if (!this.backgroundPaint.equals(paint)) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (paint != null) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image for the chart, or <code>null</code> if\r\n * there is no image.\r\n *\r\n * @return The image (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundImage(Image)\r\n */\r\n public Image getBackgroundImage() {\r\n return this.backgroundImage;\r\n }\r\n\r\n /**\r\n * Sets the background image for the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param image the image (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundImage()\r\n */\r\n public void setBackgroundImage(Image image) {\r\n\r\n if (this.backgroundImage != null) {\r\n if (!this.backgroundImage.equals(image)) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (image != null) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image alignment. Alignment constants are defined\r\n * in the <code>org.jfree.ui.Align</code> class in the JCommon class\r\n * library.\r\n *\r\n * @return The alignment.\r\n *\r\n * @see #setBackgroundImageAlignment(int)\r\n */\r\n public int getBackgroundImageAlignment() {\r\n return this.backgroundImageAlignment;\r\n }\r\n\r\n /**\r\n * Sets the background alignment. Alignment options are defined by the\r\n * {@link org.jfree.ui.Align} class.\r\n *\r\n * @param alignment the alignment.\r\n *\r\n * @see #getBackgroundImageAlignment()\r\n */\r\n public void setBackgroundImageAlignment(int alignment) {\r\n if (this.backgroundImageAlignment != alignment) {\r\n this.backgroundImageAlignment = alignment;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha-transparency for the chart's background image.\r\n *\r\n * @return The alpha-transparency.\r\n *\r\n * @see #setBackgroundImageAlpha(float)\r\n */\r\n public float getBackgroundImageAlpha() {\r\n return this.backgroundImageAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha-transparency for the chart's background image.\r\n * Registered listeners are notified that the chart has been changed.\r\n *\r\n * @param alpha the alpha value.\r\n *\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void setBackgroundImageAlpha(float alpha) {\r\n\r\n if (this.backgroundImageAlpha != alpha) {\r\n this.backgroundImageAlpha = alpha;\r\n fireChartChanged();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not change events are sent to\r\n * registered listeners.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNotify(boolean)\r\n */\r\n public boolean isNotify() {\r\n return this.notify;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not listeners receive\r\n * {@link ChartChangeEvent} notifications.\r\n *\r\n * @param notify a boolean.\r\n *\r\n * @see #isNotify()\r\n */\r\n public void setNotify(boolean notify) {\r\n this.notify = notify;\r\n // if the flag is being set to true, there may be queued up changes...\r\n if (notify) {\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area) {\r\n draw(g2, area, null, null);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer). This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D area, ChartRenderingInfo info) {\r\n draw(g2, area, null, info);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param chartArea the area within which the chart should be drawn.\r\n * @param anchor the anchor point (in Java2D space) for the chart\r\n * (<code>null</code> permitted).\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D chartArea, Point2D anchor,\r\n ChartRenderingInfo info) {\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_STARTED, 0));\r\n \r\n EntityCollection entities = null;\r\n // record the chart area, if info is requested...\r\n if (info != null) {\r\n info.clear();\r\n info.setChartArea(chartArea);\r\n entities = info.getEntityCollection();\r\n }\r\n if (entities != null) {\r\n entities.add(new JFreeChartEntity((Rectangle2D) chartArea.clone(),\r\n this));\r\n }\r\n\r\n // ensure no drawing occurs outside chart area...\r\n Shape savedClip = g2.getClip();\r\n g2.clip(chartArea);\r\n\r\n g2.addRenderingHints(this.renderingHints);\r\n\r\n // draw the chart background...\r\n if (this.backgroundPaint != null) {\r\n g2.setPaint(this.backgroundPaint);\r\n g2.fill(chartArea);\r\n }\r\n\r\n if (this.backgroundImage != null) {\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundImageAlpha));\r\n Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,\r\n this.backgroundImage.getWidth(null),\r\n this.backgroundImage.getHeight(null));\r\n Align.align(dest, chartArea, this.backgroundImageAlignment);\r\n g2.drawImage(this.backgroundImage, (int) dest.getX(),\r\n (int) dest.getY(), (int) dest.getWidth(),\r\n (int) dest.getHeight(), null);\r\n g2.setComposite(originalComposite);\r\n }\r\n\r\n if (isBorderVisible()) {\r\n Paint paint = getBorderPaint();\r\n Stroke stroke = getBorderStroke();\r\n if (paint != null && stroke != null) {\r\n Rectangle2D borderArea = new Rectangle2D.Double(\r\n chartArea.getX(), chartArea.getY(),\r\n chartArea.getWidth() - 1.0, chartArea.getHeight()\r\n - 1.0);\r\n g2.setPaint(paint);\r\n g2.setStroke(stroke);\r\n g2.draw(borderArea);\r\n }\r\n }\r\n\r\n // draw the title and subtitles...\r\n Rectangle2D nonTitleArea = new Rectangle2D.Double();\r\n nonTitleArea.setRect(chartArea);\r\n this.padding.trim(nonTitleArea);\r\n\r\n if (this.title != null && this.title.isVisible()) {\r\n EntityCollection e = drawTitle(this.title, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title currentTitle = (Title) iterator.next();\r\n if (currentTitle.isVisible()) {\r\n EntityCollection e = drawTitle(currentTitle, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n }\r\n\r\n Rectangle2D plotArea = nonTitleArea;\r\n\r\n // draw the plot (axes and data visualisation)\r\n PlotRenderingInfo plotInfo = null;\r\n if (info != null) {\r\n plotInfo = info.getPlotInfo();\r\n }\r\n this.plot.draw(g2, plotArea, anchor, null, plotInfo);\r\n\r\n g2.setClip(savedClip);\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_FINISHED, 100));\r\n }\r\n\r\n /**\r\n * Creates a rectangle that is aligned to the frame.\r\n *\r\n * @param dimensions the dimensions for the rectangle.\r\n * @param frame the frame to align to.\r\n * @param hAlign the horizontal alignment.\r\n * @param vAlign the vertical alignment.\r\n *\r\n * @return A rectangle.\r\n */\r\n private Rectangle2D createAlignedRectangle2D(Size2D dimensions,\r\n Rectangle2D frame, HorizontalAlignment hAlign,\r\n VerticalAlignment vAlign) {\r\n double x = Double.NaN;\r\n double y = Double.NaN;\r\n if (hAlign == HorizontalAlignment.LEFT) {\r\n x = frame.getX();\r\n }\r\n else if (hAlign == HorizontalAlignment.CENTER) {\r\n x = frame.getCenterX() - (dimensions.width / 2.0);\r\n }\r\n else if (hAlign == HorizontalAlignment.RIGHT) {\r\n x = frame.getMaxX() - dimensions.width;\r\n }\r\n if (vAlign == VerticalAlignment.TOP) {\r\n y = frame.getY();\r\n }\r\n else if (vAlign == VerticalAlignment.CENTER) {\r\n y = frame.getCenterY() - (dimensions.height / 2.0);\r\n }\r\n else if (vAlign == VerticalAlignment.BOTTOM) {\r\n y = frame.getMaxY() - dimensions.height;\r\n }\r\n\r\n return new Rectangle2D.Double(x, y, dimensions.width,\r\n dimensions.height);\r\n }\r\n\r\n /**\r\n * Draws a title. The title should be drawn at the top, bottom, left or\r\n * right of the specified area, and the area should be updated to reflect\r\n * the amount of space used by the title.\r\n *\r\n * @param t the title (<code>null</code> not permitted).\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param area the chart area, excluding any existing titles\r\n * (<code>null</code> not permitted).\r\n * @param entities a flag that controls whether or not an entity\r\n * collection is returned for the title.\r\n *\r\n * @return An entity collection for the title (possibly <code>null</code>).\r\n */\r\n protected EntityCollection drawTitle(Title t, Graphics2D g2,\r\n Rectangle2D area, boolean entities) {\r\n\r\n ParamChecks.nullNotPermitted(t, \"t\");\r\n ParamChecks.nullNotPermitted(area, \"area\");\r\n Rectangle2D titleArea;\r\n RectangleEdge position = t.getPosition();\r\n double ww = area.getWidth();\r\n if (ww <= 0.0) {\r\n return null;\r\n }\r\n double hh = area.getHeight();\r\n if (hh <= 0.0) {\r\n return null;\r\n }\r\n RectangleConstraint constraint = new RectangleConstraint(ww,\r\n new Range(0.0, ww), LengthConstraintType.RANGE, hh,\r\n new Range(0.0, hh), LengthConstraintType.RANGE);\r\n Object retValue = null;\r\n BlockParams p = new BlockParams();\r\n p.setGenerateEntities(entities);\r\n if (position == RectangleEdge.TOP) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.TOP);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), Math.min(area.getY() + size.height,\r\n area.getMaxY()), area.getWidth(), Math.max(area.getHeight()\r\n - size.height, 0));\r\n }\r\n else if (position == RectangleEdge.BOTTOM) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.BOTTOM);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth(),\r\n area.getHeight() - size.height);\r\n }\r\n else if (position == RectangleEdge.RIGHT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.RIGHT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n\r\n else if (position == RectangleEdge.LEFT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.LEFT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX() + size.width, area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n else {\r\n throw new RuntimeException(\"Unrecognised title position.\");\r\n }\r\n EntityCollection result = null;\r\n if (retValue instanceof EntityBlockResult) {\r\n EntityBlockResult ebr = (EntityBlockResult) retValue;\r\n result = ebr.getEntityCollection();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height) {\r\n return createBufferedImage(width, height, null);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n ChartRenderingInfo info) {\r\n return createBufferedImage(width, height, BufferedImage.TYPE_INT_ARGB,\r\n info);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param imageType the image type.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n int imageType,\r\n ChartRenderingInfo info) {\r\n BufferedImage image = new BufferedImage(width, height, imageType);\r\n Graphics2D g2 = image.createGraphics();\r\n draw(g2, new Rectangle2D.Double(0, 0, width, height), null, info);\r\n g2.dispose();\r\n return image;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param imageWidth the image width.\r\n * @param imageHeight the image height.\r\n * @param drawWidth the width for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param drawHeight the height for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param info optional object for collection chart dimension and entity\r\n * information.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int imageWidth,\r\n int imageHeight,\r\n double drawWidth,\r\n double drawHeight,\r\n ChartRenderingInfo info) {\r\n\r\n BufferedImage image = new BufferedImage(imageWidth, imageHeight,\r\n BufferedImage.TYPE_INT_ARGB);\r\n Graphics2D g2 = image.createGraphics();\r\n double scaleX = imageWidth / drawWidth;\r\n double scaleY = imageHeight / drawHeight;\r\n AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);\r\n g2.transform(st);\r\n draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,\r\n info);\r\n g2.dispose();\r\n return image;\r\n\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the chart. JFreeChart is not a UI component, so\r\n * some other object (for example, {@link ChartPanel}) needs to capture\r\n * the click event and pass it onto the JFreeChart object.\r\n * If you are not using JFreeChart in a client application, then this\r\n * method is not required.\r\n *\r\n * @param x x-coordinate of the click (in Java2D space).\r\n * @param y y-coordinate of the click (in Java2D space).\r\n * @param info contains chart dimension and entity information\r\n * (<code>null</code> not permitted).\r\n */\r\n public void handleClick(int x, int y, ChartRenderingInfo info) {\r\n\r\n // pass the click on to the plot...\r\n // rely on the plot to post a plot change event and redraw the chart...\r\n this.plot.handleClick(x, y, info.getPlotInfo());\r\n\r\n }\r\n\r\n /**\r\n * Registers an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted).\r\n *\r\n * @see #removeChangeListener(ChartChangeListener)\r\n */\r\n public void addChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.add(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted)\r\n *\r\n * @see #addChangeListener(ChartChangeListener)\r\n */\r\n public void removeChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.remove(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a default {@link ChartChangeEvent} to all registered listeners.\r\n * <P>\r\n * This method is for convenience only.\r\n */\r\n public void fireChartChanged() {\r\n ChartChangeEvent event = new ChartChangeEvent(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartChangeEvent event) {\r\n if (this.notify) {\r\n Object[] listeners = this.changeListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartChangeListener.class) {\r\n ((ChartChangeListener) listeners[i + 1]).chartChanged(\r\n event);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Registers an object for notification of progress events relating to the\r\n * chart.\r\n *\r\n * @param listener the object being registered.\r\n *\r\n * @see #removeProgressListener(ChartProgressListener)\r\n */\r\n public void addProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.add(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the object being deregistered.\r\n *\r\n * @see #addProgressListener(ChartProgressListener)\r\n */\r\n public void removeProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.remove(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartProgressEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartProgressEvent event) {\r\n\r\n Object[] listeners = this.progressListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartProgressListener.class) {\r\n ((ChartProgressListener) listeners[i + 1]).chartProgress(event);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Receives notification that a chart title has changed, and passes this\r\n * on to registered listeners.\r\n *\r\n * @param event information about the chart title change.\r\n */\r\n @Override\r\n public void titleChanged(TitleChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Receives notification that the plot has changed, and passes this on to\r\n * registered listeners.\r\n *\r\n * @param event information about the plot change.\r\n */\r\n @Override\r\n public void plotChanged(PlotChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Tests this chart for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof JFreeChart)) {\r\n return false;\r\n }\r\n JFreeChart that = (JFreeChart) obj;\r\n if (!this.renderingHints.equals(that.renderingHints)) {\r\n return false;\r\n }\r\n if (this.borderVisible != that.borderVisible) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.borderStroke, that.borderStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.borderPaint, that.borderPaint)) {\r\n return false;\r\n }\r\n if (!this.padding.equals(that.padding)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.title, that.title)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.subtitles, that.subtitles)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.plot, that.plot)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(\r\n this.backgroundPaint, that.backgroundPaint\r\n )) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundImage,\r\n that.backgroundImage)) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlignment != that.backgroundImageAlignment) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlpha != that.backgroundImageAlpha) {\r\n return false;\r\n }\r\n if (this.notify != that.notify) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.borderStroke, stream);\r\n SerialUtilities.writePaint(this.borderPaint, stream);\r\n SerialUtilities.writePaint(this.backgroundPaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.borderStroke = SerialUtilities.readStroke(stream);\r\n this.borderPaint = SerialUtilities.readPaint(stream);\r\n this.backgroundPaint = SerialUtilities.readPaint(stream);\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n // register as a listener with sub-components...\r\n if (this.title != null) {\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n getSubtitle(i).addChangeListener(this);\r\n }\r\n this.plot.addChangeListener(this);\r\n }\r\n\r\n /**\r\n * Prints information about JFreeChart to standard output.\r\n *\r\n * @param args no arguments are honored.\r\n */\r\n public static void main(String[] args) {\r\n System.out.println(JFreeChart.INFO.toString());\r\n }\r\n\r\n /**\r\n * Clones the object, and takes care of listeners.\r\n * Note: caller shall register its own listeners on cloned graph.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the chart is not cloneable.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n JFreeChart chart = (JFreeChart) super.clone();\r\n\r\n chart.renderingHints = (RenderingHints) this.renderingHints.clone();\r\n // private boolean borderVisible;\r\n // private transient Stroke borderStroke;\r\n // private transient Paint borderPaint;\r\n\r\n if (this.title != null) {\r\n chart.title = (TextTitle) this.title.clone();\r\n chart.title.addChangeListener(chart);\r\n }\r\n\r\n chart.subtitles = new ArrayList();\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n Title subtitle = (Title) getSubtitle(i).clone();\r\n chart.subtitles.add(subtitle);\r\n subtitle.addChangeListener(chart);\r\n }\r\n\r\n if (this.plot != null) {\r\n chart.plot = (Plot) this.plot.clone();\r\n chart.plot.addChangeListener(chart);\r\n }\r\n\r\n chart.progressListeners = new EventListenerList();\r\n chart.changeListeners = new EventListenerList();\r\n return chart;\r\n }\r\n\r\n}\r" }, { "identifier": "LegendItem", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/LegendItem.java", "snippet": "public class LegendItem implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -797214582948827144L;\r\n\r\n /**\r\n * The dataset.\r\n *\r\n * @since 1.0.6\r\n */\r\n private Dataset dataset;\r\n\r\n /**\r\n * The series key.\r\n *\r\n * @since 1.0.6\r\n */\r\n private Comparable seriesKey;\r\n\r\n /** The dataset index. */\r\n private int datasetIndex;\r\n\r\n /** The series index. */\r\n private int series;\r\n\r\n /** The label. */\r\n private String label;\r\n\r\n /**\r\n * The label font ({@code null} is permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n private Font labelFont;\r\n\r\n /**\r\n * The label paint ({@code null} is permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n private transient Paint labelPaint;\r\n\r\n /** The attributed label (if null, fall back to the regular label). */\r\n private transient AttributedString attributedLabel;\r\n\r\n /**\r\n * The description (not currently used - could be displayed as a tool tip).\r\n */\r\n private String description;\r\n\r\n /** The tool tip text. */\r\n private String toolTipText;\r\n\r\n /** The url text. */\r\n private String urlText;\r\n\r\n /** A flag that controls whether or not the shape is visible. */\r\n private boolean shapeVisible;\r\n\r\n /** The shape. */\r\n private transient Shape shape;\r\n\r\n /** A flag that controls whether or not the shape is filled. */\r\n private boolean shapeFilled;\r\n\r\n /** The paint. */\r\n private transient Paint fillPaint;\r\n\r\n /**\r\n * A gradient paint transformer.\r\n *\r\n * @since 1.0.4\r\n */\r\n private GradientPaintTransformer fillPaintTransformer;\r\n\r\n /** A flag that controls whether or not the shape outline is visible. */\r\n private boolean shapeOutlineVisible;\r\n\r\n /** The outline paint. */\r\n private transient Paint outlinePaint;\r\n\r\n /** The outline stroke. */\r\n private transient Stroke outlineStroke;\r\n\r\n /** A flag that controls whether or not the line is visible. */\r\n private boolean lineVisible;\r\n\r\n /** The line. */\r\n private transient Shape line;\r\n\r\n /** The stroke. */\r\n private transient Stroke lineStroke;\r\n\r\n /** The line paint. */\r\n private transient Paint linePaint;\r\n\r\n /**\r\n * The shape must be non-null for a LegendItem - if no shape is required,\r\n * use this.\r\n */\r\n private static final Shape UNUSED_SHAPE = new Line2D.Float();\r\n\r\n /**\r\n * The stroke must be non-null for a LegendItem - if no stroke is required,\r\n * use this.\r\n */\r\n private static final Stroke UNUSED_STROKE = new BasicStroke(0.0f);\r\n\r\n /**\r\n * Creates a legend item with the specified label. The remaining\r\n * attributes take default values.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n *\r\n * @since 1.0.10\r\n */\r\n public LegendItem(String label) {\r\n this(label, Color.black);\r\n }\r\n\r\n /**\r\n * Creates a legend item with the specified label and fill paint. The\r\n * remaining attributes take default values.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n * @param paint the paint ({@code null} not permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public LegendItem(String label, Paint paint) {\r\n this(label, null, null, null, new Rectangle2D.Double(-4.0, -4.0, 8.0,\r\n 8.0), paint);\r\n }\r\n\r\n /**\r\n * Creates a legend item with a filled shape. The shape is not outlined,\r\n * and no line is visible.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n * @param description the description ({@code null} permitted).\r\n * @param toolTipText the tool tip text ({@code null} permitted).\r\n * @param urlText the URL text ({@code null} permitted).\r\n * @param shape the shape ({@code null} not permitted).\r\n * @param fillPaint the paint used to fill the shape ({@code null}\r\n * not permitted).\r\n */\r\n public LegendItem(String label, String description,\r\n String toolTipText, String urlText,\r\n Shape shape, Paint fillPaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ true, shape,\r\n /* shape filled = */ true, fillPaint,\r\n /* shape outlined */ false, Color.black, UNUSED_STROKE,\r\n /* line visible */ false, UNUSED_SHAPE, UNUSED_STROKE,\r\n Color.black);\r\n\r\n }\r\n\r\n /**\r\n * Creates a legend item with a filled and outlined shape.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n * @param description the description ({@code null} permitted).\r\n * @param toolTipText the tool tip text ({@code null} permitted).\r\n * @param urlText the URL text ({@code null} permitted).\r\n * @param shape the shape ({@code null} not permitted).\r\n * @param fillPaint the paint used to fill the shape ({@code null}\r\n * not permitted).\r\n * @param outlineStroke the outline stroke ({@code null} not\r\n * permitted).\r\n * @param outlinePaint the outline paint ({@code null} not\r\n * permitted).\r\n */\r\n public LegendItem(String label, String description, String toolTipText, \r\n String urlText, Shape shape, Paint fillPaint, Stroke outlineStroke, \r\n Paint outlinePaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ true, shape,\r\n /* shape filled = */ true, fillPaint,\r\n /* shape outlined = */ true, outlinePaint, outlineStroke,\r\n /* line visible */ false, UNUSED_SHAPE, UNUSED_STROKE,\r\n Color.black);\r\n\r\n }\r\n\r\n /**\r\n * Creates a legend item using a line.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n * @param description the description ({@code null} permitted).\r\n * @param toolTipText the tool tip text ({@code null} permitted).\r\n * @param urlText the URL text ({@code null} permitted).\r\n * @param line the line ({@code null} not permitted).\r\n * @param lineStroke the line stroke ({@code null} not permitted).\r\n * @param linePaint the line paint ({@code null} not permitted).\r\n */\r\n public LegendItem(String label, String description, String toolTipText, \r\n String urlText, Shape line, Stroke lineStroke, Paint linePaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ false, UNUSED_SHAPE,\r\n /* shape filled = */ false, Color.black,\r\n /* shape outlined = */ false, Color.black, UNUSED_STROKE,\r\n /* line visible = */ true, line, lineStroke, linePaint);\r\n }\r\n\r\n /**\r\n * Creates a new legend item.\r\n *\r\n * @param label the label ({@code null} not permitted).\r\n * @param description the description (not currently used,\r\n * <code>null</code> permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text (<code>null</code> permitted).\r\n * @param shapeVisible a flag that controls whether or not the shape is\r\n * displayed.\r\n * @param shape the shape (<code>null</code> permitted).\r\n * @param shapeFilled a flag that controls whether or not the shape is\r\n * filled.\r\n * @param fillPaint the fill paint (<code>null</code> not permitted).\r\n * @param shapeOutlineVisible a flag that controls whether or not the\r\n * shape is outlined.\r\n * @param outlinePaint the outline paint (<code>null</code> not permitted).\r\n * @param outlineStroke the outline stroke (<code>null</code> not\r\n * permitted).\r\n * @param lineVisible a flag that controls whether or not the line is\r\n * visible.\r\n * @param line the line.\r\n * @param lineStroke the stroke (<code>null</code> not permitted).\r\n * @param linePaint the line paint (<code>null</code> not permitted).\r\n */\r\n public LegendItem(String label, String description,\r\n String toolTipText, String urlText,\r\n boolean shapeVisible, Shape shape,\r\n boolean shapeFilled, Paint fillPaint,\r\n boolean shapeOutlineVisible, Paint outlinePaint,\r\n Stroke outlineStroke,\r\n boolean lineVisible, Shape line,\r\n Stroke lineStroke, Paint linePaint) {\r\n\r\n ParamChecks.nullNotPermitted(label, \"label\");\r\n ParamChecks.nullNotPermitted(fillPaint, \"fillPaint\");\r\n ParamChecks.nullNotPermitted(lineStroke, \"lineStroke\");\r\n ParamChecks.nullNotPermitted(outlinePaint, \"outlinePaint\");\r\n ParamChecks.nullNotPermitted(outlineStroke, \"outlineStroke\");\r\n this.label = label;\r\n this.labelPaint = null;\r\n this.attributedLabel = null;\r\n this.description = description;\r\n this.shapeVisible = shapeVisible;\r\n this.shape = shape;\r\n this.shapeFilled = shapeFilled;\r\n this.fillPaint = fillPaint;\r\n this.fillPaintTransformer = new StandardGradientPaintTransformer();\r\n this.shapeOutlineVisible = shapeOutlineVisible;\r\n this.outlinePaint = outlinePaint;\r\n this.outlineStroke = outlineStroke;\r\n this.lineVisible = lineVisible;\r\n this.line = line;\r\n this.lineStroke = lineStroke;\r\n this.linePaint = linePaint;\r\n this.toolTipText = toolTipText;\r\n this.urlText = urlText;\r\n }\r\n\r\n /**\r\n * Creates a legend item with a filled shape. The shape is not outlined,\r\n * and no line is visible.\r\n *\r\n * @param label the label (<code>null</code> not permitted).\r\n * @param description the description (<code>null</code> permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text (<code>null</code> permitted).\r\n * @param shape the shape (<code>null</code> not permitted).\r\n * @param fillPaint the paint used to fill the shape (<code>null</code>\r\n * not permitted).\r\n */\r\n public LegendItem(AttributedString label, String description,\r\n String toolTipText, String urlText,\r\n Shape shape, Paint fillPaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ true, shape,\r\n /* shape filled = */ true, fillPaint,\r\n /* shape outlined = */ false, Color.black, UNUSED_STROKE,\r\n /* line visible = */ false, UNUSED_SHAPE, UNUSED_STROKE,\r\n Color.black);\r\n\r\n }\r\n\r\n /**\r\n * Creates a legend item with a filled and outlined shape.\r\n *\r\n * @param label the label (<code>null</code> not permitted).\r\n * @param description the description (<code>null</code> permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text (<code>null</code> permitted).\r\n * @param shape the shape (<code>null</code> not permitted).\r\n * @param fillPaint the paint used to fill the shape (<code>null</code>\r\n * not permitted).\r\n * @param outlineStroke the outline stroke (<code>null</code> not\r\n * permitted).\r\n * @param outlinePaint the outline paint (<code>null</code> not\r\n * permitted).\r\n */\r\n public LegendItem(AttributedString label, String description,\r\n String toolTipText, String urlText,\r\n Shape shape, Paint fillPaint,\r\n Stroke outlineStroke, Paint outlinePaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ true, shape,\r\n /* shape filled = */ true, fillPaint,\r\n /* shape outlined = */ true, outlinePaint, outlineStroke,\r\n /* line visible = */ false, UNUSED_SHAPE, UNUSED_STROKE,\r\n Color.black);\r\n }\r\n\r\n /**\r\n * Creates a legend item using a line.\r\n *\r\n * @param label the label (<code>null</code> not permitted).\r\n * @param description the description (<code>null</code> permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text (<code>null</code> permitted).\r\n * @param line the line (<code>null</code> not permitted).\r\n * @param lineStroke the line stroke (<code>null</code> not permitted).\r\n * @param linePaint the line paint (<code>null</code> not permitted).\r\n */\r\n public LegendItem(AttributedString label, String description,\r\n String toolTipText, String urlText,\r\n Shape line, Stroke lineStroke, Paint linePaint) {\r\n\r\n this(label, description, toolTipText, urlText,\r\n /* shape visible = */ false, UNUSED_SHAPE,\r\n /* shape filled = */ false, Color.black,\r\n /* shape outlined = */ false, Color.black, UNUSED_STROKE,\r\n /* line visible = */ true, line, lineStroke, linePaint);\r\n }\r\n\r\n /**\r\n * Creates a new legend item.\r\n *\r\n * @param label the label (<code>null</code> not permitted).\r\n * @param description the description (not currently used,\r\n * <code>null</code> permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text (<code>null</code> permitted).\r\n * @param shapeVisible a flag that controls whether or not the shape is\r\n * displayed.\r\n * @param shape the shape (<code>null</code> permitted).\r\n * @param shapeFilled a flag that controls whether or not the shape is\r\n * filled.\r\n * @param fillPaint the fill paint (<code>null</code> not permitted).\r\n * @param shapeOutlineVisible a flag that controls whether or not the\r\n * shape is outlined.\r\n * @param outlinePaint the outline paint (<code>null</code> not permitted).\r\n * @param outlineStroke the outline stroke (<code>null</code> not\r\n * permitted).\r\n * @param lineVisible a flag that controls whether or not the line is\r\n * visible.\r\n * @param line the line (<code>null</code> not permitted).\r\n * @param lineStroke the stroke (<code>null</code> not permitted).\r\n * @param linePaint the line paint (<code>null</code> not permitted).\r\n */\r\n public LegendItem(AttributedString label, String description,\r\n String toolTipText, String urlText,\r\n boolean shapeVisible, Shape shape,\r\n boolean shapeFilled, Paint fillPaint,\r\n boolean shapeOutlineVisible, Paint outlinePaint,\r\n Stroke outlineStroke,\r\n boolean lineVisible, Shape line, Stroke lineStroke,\r\n Paint linePaint) {\r\n\r\n ParamChecks.nullNotPermitted(label, \"label\");\r\n ParamChecks.nullNotPermitted(fillPaint, \"fillPaint\");\r\n ParamChecks.nullNotPermitted(lineStroke, \"lineStroke\");\r\n ParamChecks.nullNotPermitted(line, \"line\");\r\n ParamChecks.nullNotPermitted(linePaint, \"linePaint\");\r\n ParamChecks.nullNotPermitted(outlinePaint, \"outlinePaint\");\r\n ParamChecks.nullNotPermitted(outlineStroke, \"outlineStroke\");\r\n this.label = characterIteratorToString(label.getIterator());\r\n this.attributedLabel = label;\r\n this.description = description;\r\n this.shapeVisible = shapeVisible;\r\n this.shape = shape;\r\n this.shapeFilled = shapeFilled;\r\n this.fillPaint = fillPaint;\r\n this.fillPaintTransformer = new StandardGradientPaintTransformer();\r\n this.shapeOutlineVisible = shapeOutlineVisible;\r\n this.outlinePaint = outlinePaint;\r\n this.outlineStroke = outlineStroke;\r\n this.lineVisible = lineVisible;\r\n this.line = line;\r\n this.lineStroke = lineStroke;\r\n this.linePaint = linePaint;\r\n this.toolTipText = toolTipText;\r\n this.urlText = urlText;\r\n }\r\n\r\n /**\r\n * Returns a string containing the characters from the given iterator.\r\n *\r\n * @param iterator the iterator (<code>null</code> not permitted).\r\n *\r\n * @return A string.\r\n */\r\n private String characterIteratorToString(CharacterIterator iterator) {\r\n int endIndex = iterator.getEndIndex();\r\n int beginIndex = iterator.getBeginIndex();\r\n int count = endIndex - beginIndex;\r\n if (count <= 0) {\r\n return \"\";\r\n }\r\n char[] chars = new char[count];\r\n int i = 0;\r\n char c = iterator.first();\r\n while (c != CharacterIterator.DONE) {\r\n chars[i] = c;\r\n i++;\r\n c = iterator.next();\r\n }\r\n return new String(chars);\r\n }\r\n\r\n /**\r\n * Returns the dataset.\r\n *\r\n * @return The dataset.\r\n *\r\n * @since 1.0.6\r\n *\r\n * @see #setDatasetIndex(int)\r\n */\r\n public Dataset getDataset() {\r\n return this.dataset;\r\n }\r\n\r\n /**\r\n * Sets the dataset.\r\n *\r\n * @param dataset the dataset.\r\n *\r\n * @since 1.0.6\r\n */\r\n public void setDataset(Dataset dataset) {\r\n this.dataset = dataset;\r\n }\r\n\r\n /**\r\n * Returns the dataset index for this legend item.\r\n *\r\n * @return The dataset index.\r\n *\r\n * @since 1.0.2\r\n *\r\n * @see #setDatasetIndex(int)\r\n * @see #getDataset()\r\n */\r\n public int getDatasetIndex() {\r\n return this.datasetIndex;\r\n }\r\n\r\n /**\r\n * Sets the dataset index for this legend item.\r\n *\r\n * @param index the index.\r\n *\r\n * @since 1.0.2\r\n *\r\n * @see #getDatasetIndex()\r\n */\r\n public void setDatasetIndex(int index) {\r\n this.datasetIndex = index;\r\n }\r\n\r\n /**\r\n * Returns the series key.\r\n *\r\n * @return The series key.\r\n *\r\n * @since 1.0.6\r\n *\r\n * @see #setSeriesKey(Comparable)\r\n */\r\n public Comparable getSeriesKey() {\r\n return this.seriesKey;\r\n }\r\n\r\n /**\r\n * Sets the series key.\r\n *\r\n * @param key the series key.\r\n *\r\n * @since 1.0.6\r\n */\r\n public void setSeriesKey(Comparable key) {\r\n this.seriesKey = key;\r\n }\r\n\r\n /**\r\n * Returns the series index for this legend item.\r\n *\r\n * @return The series index.\r\n *\r\n * @since 1.0.2\r\n */\r\n public int getSeriesIndex() {\r\n return this.series;\r\n }\r\n\r\n /**\r\n * Sets the series index for this legend item.\r\n *\r\n * @param index the index.\r\n *\r\n * @since 1.0.2\r\n */\r\n public void setSeriesIndex(int index) {\r\n this.series = index;\r\n }\r\n\r\n /**\r\n * Returns the label.\r\n *\r\n * @return The label (never <code>null</code>).\r\n */\r\n public String getLabel() {\r\n return this.label;\r\n }\r\n\r\n /**\r\n * Returns the label font.\r\n *\r\n * @return The label font (possibly <code>null</code>).\r\n *\r\n * @since 1.0.11\r\n */\r\n public Font getLabelFont() {\r\n return this.labelFont;\r\n }\r\n\r\n /**\r\n * Sets the label font.\r\n *\r\n * @param font the font (<code>null</code> permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setLabelFont(Font font) {\r\n this.labelFont = font;\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the label.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @since 1.0.11\r\n */\r\n public Paint getLabelPaint() {\r\n return this.labelPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the label.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setLabelPaint(Paint paint) {\r\n this.labelPaint = paint;\r\n }\r\n\r\n /**\r\n * Returns the attributed label.\r\n *\r\n * @return The attributed label (possibly <code>null</code>).\r\n */\r\n public AttributedString getAttributedLabel() {\r\n return this.attributedLabel;\r\n }\r\n\r\n /**\r\n * Returns the description for the legend item.\r\n *\r\n * @return The description (possibly <code>null</code>).\r\n *\r\n * @see #setDescription(java.lang.String) \r\n */\r\n public String getDescription() {\r\n return this.description;\r\n }\r\n\r\n /**\r\n * Sets the description for this legend item.\r\n *\r\n * @param text the description (<code>null</code> permitted).\r\n *\r\n * @see #getDescription()\r\n * @since 1.0.14\r\n */\r\n public void setDescription(String text) {\r\n this.description = text;\r\n }\r\n\r\n /**\r\n * Returns the tool tip text.\r\n *\r\n * @return The tool tip text (possibly <code>null</code>).\r\n *\r\n * @see #setToolTipText(java.lang.String) \r\n */\r\n public String getToolTipText() {\r\n return this.toolTipText;\r\n }\r\n\r\n /**\r\n * Sets the tool tip text for this legend item.\r\n *\r\n * @param text the text (<code>null</code> permitted).\r\n *\r\n * @see #getToolTipText()\r\n * @since 1.0.14\r\n */\r\n public void setToolTipText(String text) {\r\n this.toolTipText = text;\r\n }\r\n\r\n /**\r\n * Returns the URL text.\r\n *\r\n * @return The URL text (possibly <code>null</code>).\r\n *\r\n * @see #setURLText(java.lang.String) \r\n */\r\n public String getURLText() {\r\n return this.urlText;\r\n }\r\n\r\n /**\r\n * Sets the URL text.\r\n *\r\n * @param text the text (<code>null</code> permitted).\r\n *\r\n * @see #getURLText()\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setURLText(String text) {\r\n this.urlText = text;\r\n }\r\n\r\n /**\r\n * Returns a flag that indicates whether or not the shape is visible.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setShapeVisible(boolean)\r\n */\r\n public boolean isShapeVisible() {\r\n return this.shapeVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the shape is visible.\r\n *\r\n * @param visible the new flag value.\r\n *\r\n * @see #isShapeVisible()\r\n * @see #isLineVisible()\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setShapeVisible(boolean visible) {\r\n this.shapeVisible = visible;\r\n }\r\n\r\n /**\r\n * Returns the shape used to label the series represented by this legend\r\n * item.\r\n *\r\n * @return The shape (never <code>null</code>).\r\n *\r\n * @see #setShape(java.awt.Shape) \r\n */\r\n public Shape getShape() {\r\n return this.shape;\r\n }\r\n\r\n /**\r\n * Sets the shape for the legend item.\r\n *\r\n * @param shape the shape (<code>null</code> not permitted).\r\n *\r\n * @see #getShape()\r\n * @since 1.0.14\r\n */\r\n public void setShape(Shape shape) {\r\n ParamChecks.nullNotPermitted(shape, \"shape\");\r\n this.shape = shape;\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not the shape is filled.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean isShapeFilled() {\r\n return this.shapeFilled;\r\n }\r\n\r\n /**\r\n * Returns the fill paint.\r\n *\r\n * @return The fill paint (never <code>null</code>).\r\n */\r\n public Paint getFillPaint() {\r\n return this.fillPaint;\r\n }\r\n\r\n /**\r\n * Sets the fill paint.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setFillPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.fillPaint = paint;\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the shape outline\r\n * is visible.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean isShapeOutlineVisible() {\r\n return this.shapeOutlineVisible;\r\n }\r\n\r\n /**\r\n * Returns the line stroke for the series.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n */\r\n public Stroke getLineStroke() {\r\n return this.lineStroke;\r\n }\r\n \r\n /**\r\n * Sets the line stroke.\r\n * \r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n * \r\n * @since 1.0.18\r\n */\r\n public void setLineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.lineStroke = stroke;\r\n }\r\n\r\n /**\r\n * Returns the paint used for lines.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n */\r\n public Paint getLinePaint() {\r\n return this.linePaint;\r\n }\r\n\r\n /**\r\n * Sets the line paint.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setLinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.linePaint = paint;\r\n }\r\n\r\n /**\r\n * Returns the outline paint.\r\n *\r\n * @return The outline paint (never <code>null</code>).\r\n */\r\n public Paint getOutlinePaint() {\r\n return this.outlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the outline paint.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setOutlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.outlinePaint = paint;\r\n }\r\n\r\n /**\r\n * Returns the outline stroke.\r\n *\r\n * @return The outline stroke (never <code>null</code>).\r\n *\r\n * @see #setOutlineStroke(java.awt.Stroke) \r\n */\r\n public Stroke getOutlineStroke() {\r\n return this.outlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the outline stroke.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getOutlineStroke()\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setOutlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.outlineStroke = stroke;\r\n }\r\n\r\n /**\r\n * Returns a flag that indicates whether or not the line is visible.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setLineVisible(boolean) \r\n */\r\n public boolean isLineVisible() {\r\n return this.lineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the line shape is visible for\r\n * this legend item.\r\n *\r\n * @param visible the new flag value.\r\n *\r\n * @see #isLineVisible()\r\n * @since 1.0.14\r\n */\r\n public void setLineVisible(boolean visible) {\r\n this.lineVisible = visible;\r\n }\r\n\r\n /**\r\n * Returns the line.\r\n *\r\n * @return The line (never <code>null</code>).\r\n *\r\n * @see #setLine(java.awt.Shape)\r\n * @see #isLineVisible() \r\n */\r\n public Shape getLine() {\r\n return this.line;\r\n }\r\n\r\n /**\r\n * Sets the line.\r\n *\r\n * @param line the line (<code>null</code> not permitted).\r\n *\r\n * @see #getLine()\r\n * @since 1.0.14\r\n */\r\n public void setLine(Shape line) {\r\n ParamChecks.nullNotPermitted(line, \"line\");\r\n this.line = line;\r\n }\r\n\r\n /**\r\n * Returns the transformer used when the fill paint is an instance of\r\n * <code>GradientPaint</code>.\r\n *\r\n * @return The transformer (never <code>null</code>).\r\n *\r\n * @since 1.0.4\r\n *\r\n * @see #setFillPaintTransformer(GradientPaintTransformer)\r\n */\r\n public GradientPaintTransformer getFillPaintTransformer() {\r\n return this.fillPaintTransformer;\r\n }\r\n\r\n /**\r\n * Sets the transformer used when the fill paint is an instance of\r\n * <code>GradientPaint</code>.\r\n *\r\n * @param transformer the transformer (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.4\r\n *\r\n * @see #getFillPaintTransformer()\r\n */\r\n public void setFillPaintTransformer(GradientPaintTransformer transformer) {\r\n ParamChecks.nullNotPermitted(transformer, \"transformer\");\r\n this.fillPaintTransformer = transformer;\r\n }\r\n\r\n /**\r\n * Tests this item for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof LegendItem)) {\r\n return false;\r\n }\r\n LegendItem that = (LegendItem) obj;\r\n if (this.datasetIndex != that.datasetIndex) {\r\n return false;\r\n }\r\n if (this.series != that.series) {\r\n return false;\r\n }\r\n if (!this.label.equals(that.label)) {\r\n return false;\r\n }\r\n if (!AttributedStringUtilities.equal(this.attributedLabel,\r\n that.attributedLabel)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.description, that.description)) {\r\n return false;\r\n }\r\n if (this.shapeVisible != that.shapeVisible) {\r\n return false;\r\n }\r\n if (!ShapeUtilities.equal(this.shape, that.shape)) {\r\n return false;\r\n }\r\n if (this.shapeFilled != that.shapeFilled) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.fillPaint, that.fillPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.fillPaintTransformer,\r\n that.fillPaintTransformer)) {\r\n return false;\r\n }\r\n if (this.shapeOutlineVisible != that.shapeOutlineVisible) {\r\n return false;\r\n }\r\n if (!this.outlineStroke.equals(that.outlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) {\r\n return false;\r\n }\r\n if (!this.lineVisible == that.lineVisible) {\r\n return false;\r\n }\r\n if (!ShapeUtilities.equal(this.line, that.line)) {\r\n return false;\r\n }\r\n if (!this.lineStroke.equals(that.lineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.linePaint, that.linePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.labelFont, that.labelFont)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.labelPaint, that.labelPaint)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns an independent copy of this object (except that the clone will\r\n * still reference the same dataset as the original\r\n * <code>LegendItem</code>).\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the legend item cannot be cloned.\r\n *\r\n * @since 1.0.10\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n LegendItem clone = (LegendItem) super.clone();\r\n if (this.seriesKey instanceof PublicCloneable) {\r\n PublicCloneable pc = (PublicCloneable) this.seriesKey;\r\n clone.seriesKey = (Comparable) pc.clone();\r\n }\r\n // FIXME: Clone the attributed string if it is not null\r\n clone.shape = ShapeUtilities.clone(this.shape);\r\n if (this.fillPaintTransformer instanceof PublicCloneable) {\r\n PublicCloneable pc = (PublicCloneable) this.fillPaintTransformer;\r\n clone.fillPaintTransformer = (GradientPaintTransformer) pc.clone();\r\n\r\n }\r\n clone.line = ShapeUtilities.clone(this.line);\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream (<code>null</code> not permitted).\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeAttributedString(this.attributedLabel, stream);\r\n SerialUtilities.writeShape(this.shape, stream);\r\n SerialUtilities.writePaint(this.fillPaint, stream);\r\n SerialUtilities.writeStroke(this.outlineStroke, stream);\r\n SerialUtilities.writePaint(this.outlinePaint, stream);\r\n SerialUtilities.writeShape(this.line, stream);\r\n SerialUtilities.writeStroke(this.lineStroke, stream);\r\n SerialUtilities.writePaint(this.linePaint, stream);\r\n SerialUtilities.writePaint(this.labelPaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream (<code>null</code> not permitted).\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.attributedLabel = SerialUtilities.readAttributedString(stream);\r\n this.shape = SerialUtilities.readShape(stream);\r\n this.fillPaint = SerialUtilities.readPaint(stream);\r\n this.outlineStroke = SerialUtilities.readStroke(stream);\r\n this.outlinePaint = SerialUtilities.readPaint(stream);\r\n this.line = SerialUtilities.readShape(stream);\r\n this.lineStroke = SerialUtilities.readStroke(stream);\r\n this.linePaint = SerialUtilities.readPaint(stream);\r\n this.labelPaint = SerialUtilities.readPaint(stream);\r\n }\r\n\r\n}\r" }, { "identifier": "TestUtilities", "path": "lib/jfreechart-1.0.19/tests/org/jfree/chart/TestUtilities.java", "snippet": "public class TestUtilities {\n\n /**\n * Returns <code>true</code> if the collections contains any object that\n * is an instance of the specified class, and <code>false</code> otherwise.\n *\n * @param collection the collection.\n * @param c the class.\n *\n * @return A boolean.\n */\n public static boolean containsInstanceOf(Collection collection, Class c) {\n Iterator iterator = collection.iterator();\n while (iterator.hasNext()) {\n Object obj = iterator.next();\n if (obj != null && obj.getClass().equals(c)) {\n return true;\n }\n }\n return false;\n }\n\n public static Object serialised(Object original) {\n Object result = null;\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n ObjectOutput out;\n try {\n out = new ObjectOutputStream(buffer);\n out.writeObject(original);\n out.close();\n ObjectInput in = new ObjectInputStream(\n new ByteArrayInputStream(buffer.toByteArray()));\n result = in.readObject();\n in.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n return result;\n }\n \n}" }, { "identifier": "NumberAxis", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/axis/NumberAxis.java", "snippet": "public class NumberAxis extends ValueAxis implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 2805933088476185789L;\r\n\r\n /** The default value for the autoRangeIncludesZero flag. */\r\n public static final boolean DEFAULT_AUTO_RANGE_INCLUDES_ZERO = true;\r\n\r\n /** The default value for the autoRangeStickyZero flag. */\r\n public static final boolean DEFAULT_AUTO_RANGE_STICKY_ZERO = true;\r\n\r\n /** The default tick unit. */\r\n public static final NumberTickUnit DEFAULT_TICK_UNIT = new NumberTickUnit(\r\n 1.0, new DecimalFormat(\"0\"));\r\n\r\n /** The default setting for the vertical tick labels flag. */\r\n public static final boolean DEFAULT_VERTICAL_TICK_LABELS = false;\r\n\r\n /**\r\n * The range type (can be used to force the axis to display only positive\r\n * values or only negative values).\r\n */\r\n private RangeType rangeType;\r\n\r\n /**\r\n * A flag that affects the axis range when the range is determined\r\n * automatically. If the auto range does NOT include zero and this flag\r\n * is TRUE, then the range is changed to include zero.\r\n */\r\n private boolean autoRangeIncludesZero;\r\n\r\n /**\r\n * A flag that affects the size of the margins added to the axis range when\r\n * the range is determined automatically. If the value 0 falls within the\r\n * margin and this flag is TRUE, then the margin is truncated at zero.\r\n */\r\n private boolean autoRangeStickyZero;\r\n\r\n /** The tick unit for the axis. */\r\n private NumberTickUnit tickUnit;\r\n\r\n /** The override number format. */\r\n private NumberFormat numberFormatOverride;\r\n\r\n /** An optional band for marking regions on the axis. */\r\n private MarkerAxisBand markerBand;\r\n\r\n /**\r\n * Default constructor.\r\n */\r\n public NumberAxis() {\r\n this(null);\r\n }\r\n\r\n /**\r\n * Constructs a number axis, using default values where necessary.\r\n *\r\n * @param label the axis label (<code>null</code> permitted).\r\n */\r\n public NumberAxis(String label) {\r\n super(label, NumberAxis.createStandardTickUnits());\r\n this.rangeType = RangeType.FULL;\r\n this.autoRangeIncludesZero = DEFAULT_AUTO_RANGE_INCLUDES_ZERO;\r\n this.autoRangeStickyZero = DEFAULT_AUTO_RANGE_STICKY_ZERO;\r\n this.tickUnit = DEFAULT_TICK_UNIT;\r\n this.numberFormatOverride = null;\r\n this.markerBand = null;\r\n }\r\n\r\n /**\r\n * Returns the axis range type.\r\n *\r\n * @return The axis range type (never <code>null</code>).\r\n *\r\n * @see #setRangeType(RangeType)\r\n */\r\n public RangeType getRangeType() {\r\n return this.rangeType;\r\n }\r\n\r\n /**\r\n * Sets the axis range type.\r\n *\r\n * @param rangeType the range type (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeType()\r\n */\r\n public void setRangeType(RangeType rangeType) {\r\n ParamChecks.nullNotPermitted(rangeType, \"rangeType\");\r\n this.rangeType = rangeType;\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the flag that indicates whether or not the automatic axis range\r\n * (if indeed it is determined automatically) is forced to include zero.\r\n *\r\n * @return The flag.\r\n */\r\n public boolean getAutoRangeIncludesZero() {\r\n return this.autoRangeIncludesZero;\r\n }\r\n\r\n /**\r\n * Sets the flag that indicates whether or not the axis range, if\r\n * automatically calculated, is forced to include zero.\r\n * <p>\r\n * If the flag is changed to <code>true</code>, the axis range is\r\n * recalculated.\r\n * <p>\r\n * Any change to the flag will trigger an {@link AxisChangeEvent}.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #getAutoRangeIncludesZero()\r\n */\r\n public void setAutoRangeIncludesZero(boolean flag) {\r\n if (this.autoRangeIncludesZero != flag) {\r\n this.autoRangeIncludesZero = flag;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag that affects the auto-range when zero falls outside the\r\n * data range but inside the margins defined for the axis.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAutoRangeStickyZero(boolean)\r\n */\r\n public boolean getAutoRangeStickyZero() {\r\n return this.autoRangeStickyZero;\r\n }\r\n\r\n /**\r\n * Sets a flag that affects the auto-range when zero falls outside the data\r\n * range but inside the margins defined for the axis.\r\n *\r\n * @param flag the new flag.\r\n *\r\n * @see #getAutoRangeStickyZero()\r\n */\r\n public void setAutoRangeStickyZero(boolean flag) {\r\n if (this.autoRangeStickyZero != flag) {\r\n this.autoRangeStickyZero = flag;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the tick unit for the axis.\r\n * <p>\r\n * Note: if the <code>autoTickUnitSelection</code> flag is\r\n * <code>true</code> the tick unit may be changed while the axis is being\r\n * drawn, so in that case the return value from this method may be\r\n * irrelevant if the method is called before the axis has been drawn.\r\n *\r\n * @return The tick unit for the axis.\r\n *\r\n * @see #setTickUnit(NumberTickUnit)\r\n * @see ValueAxis#isAutoTickUnitSelection()\r\n */\r\n public NumberTickUnit getTickUnit() {\r\n return this.tickUnit;\r\n }\r\n\r\n /**\r\n * Sets the tick unit for the axis and sends an {@link AxisChangeEvent} to\r\n * all registered listeners. A side effect of calling this method is that\r\n * the \"auto-select\" feature for tick units is switched off (you can\r\n * restore it using the {@link ValueAxis#setAutoTickUnitSelection(boolean)}\r\n * method).\r\n *\r\n * @param unit the new tick unit (<code>null</code> not permitted).\r\n *\r\n * @see #getTickUnit()\r\n * @see #setTickUnit(NumberTickUnit, boolean, boolean)\r\n */\r\n public void setTickUnit(NumberTickUnit unit) {\r\n // defer argument checking...\r\n setTickUnit(unit, true, true);\r\n }\r\n\r\n /**\r\n * Sets the tick unit for the axis and, if requested, sends an\r\n * {@link AxisChangeEvent} to all registered listeners. In addition, an\r\n * option is provided to turn off the \"auto-select\" feature for tick units\r\n * (you can restore it using the\r\n * {@link ValueAxis#setAutoTickUnitSelection(boolean)} method).\r\n *\r\n * @param unit the new tick unit (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n * @param turnOffAutoSelect turn off the auto-tick selection?\r\n */\r\n public void setTickUnit(NumberTickUnit unit, boolean notify,\r\n boolean turnOffAutoSelect) {\r\n\r\n ParamChecks.nullNotPermitted(unit, \"unit\");\r\n this.tickUnit = unit;\r\n if (turnOffAutoSelect) {\r\n setAutoTickUnitSelection(false, false);\r\n }\r\n if (notify) {\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the number format override. If this is non-null, then it will\r\n * be used to format the numbers on the axis.\r\n *\r\n * @return The number formatter (possibly <code>null</code>).\r\n *\r\n * @see #setNumberFormatOverride(NumberFormat)\r\n */\r\n public NumberFormat getNumberFormatOverride() {\r\n return this.numberFormatOverride;\r\n }\r\n\r\n /**\r\n * Sets the number format override. If this is non-null, then it will be\r\n * used to format the numbers on the axis.\r\n *\r\n * @param formatter the number formatter (<code>null</code> permitted).\r\n *\r\n * @see #getNumberFormatOverride()\r\n */\r\n public void setNumberFormatOverride(NumberFormat formatter) {\r\n this.numberFormatOverride = formatter;\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the (optional) marker band for the axis.\r\n *\r\n * @return The marker band (possibly <code>null</code>).\r\n *\r\n * @see #setMarkerBand(MarkerAxisBand)\r\n */\r\n public MarkerAxisBand getMarkerBand() {\r\n return this.markerBand;\r\n }\r\n\r\n /**\r\n * Sets the marker band for the axis.\r\n * <P>\r\n * The marker band is optional, leave it set to <code>null</code> if you\r\n * don't require it.\r\n *\r\n * @param band the new band (<code>null</code> permitted).\r\n *\r\n * @see #getMarkerBand()\r\n */\r\n public void setMarkerBand(MarkerAxisBand band) {\r\n this.markerBand = band;\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Configures the axis to work with the specified plot. If the axis has\r\n * auto-scaling, then sets the maximum and minimum values.\r\n */\r\n @Override\r\n public void configure() {\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n }\r\n\r\n /**\r\n * Rescales the axis to ensure that all data is visible.\r\n */\r\n @Override\r\n protected void autoAdjustRange() {\r\n\r\n Plot plot = getPlot();\r\n if (plot == null) {\r\n return; // no plot, no data\r\n }\r\n\r\n if (plot instanceof ValueAxisPlot) {\r\n ValueAxisPlot vap = (ValueAxisPlot) plot;\r\n\r\n Range r = vap.getDataRange(this);\r\n if (r == null) {\r\n r = getDefaultAutoRange();\r\n }\r\n\r\n double upper = r.getUpperBound();\r\n double lower = r.getLowerBound();\r\n if (this.rangeType == RangeType.POSITIVE) {\r\n lower = Math.max(0.0, lower);\r\n upper = Math.max(0.0, upper);\r\n }\r\n else if (this.rangeType == RangeType.NEGATIVE) {\r\n lower = Math.min(0.0, lower);\r\n upper = Math.min(0.0, upper);\r\n }\r\n\r\n if (getAutoRangeIncludesZero()) {\r\n lower = Math.min(lower, 0.0);\r\n upper = Math.max(upper, 0.0);\r\n }\r\n double range = upper - lower;\r\n\r\n // if fixed auto range, then derive lower bound...\r\n double fixedAutoRange = getFixedAutoRange();\r\n if (fixedAutoRange > 0.0) {\r\n lower = upper - fixedAutoRange;\r\n }\r\n else {\r\n // ensure the autorange is at least <minRange> in size...\r\n double minRange = getAutoRangeMinimumSize();\r\n if (range < minRange) {\r\n double expand = (minRange - range) / 2;\r\n upper = upper + expand;\r\n lower = lower - expand;\r\n if (lower == upper) { // see bug report 1549218\r\n double adjust = Math.abs(lower) / 10.0;\r\n lower = lower - adjust;\r\n upper = upper + adjust;\r\n }\r\n if (this.rangeType == RangeType.POSITIVE) {\r\n if (lower < 0.0) {\r\n upper = upper - lower;\r\n lower = 0.0;\r\n }\r\n }\r\n else if (this.rangeType == RangeType.NEGATIVE) {\r\n if (upper > 0.0) {\r\n lower = lower - upper;\r\n upper = 0.0;\r\n }\r\n }\r\n }\r\n\r\n if (getAutoRangeStickyZero()) {\r\n if (upper <= 0.0) {\r\n upper = Math.min(0.0, upper + getUpperMargin() * range);\r\n }\r\n else {\r\n upper = upper + getUpperMargin() * range;\r\n }\r\n if (lower >= 0.0) {\r\n lower = Math.max(0.0, lower - getLowerMargin() * range);\r\n }\r\n else {\r\n lower = lower - getLowerMargin() * range;\r\n }\r\n }\r\n else {\r\n upper = upper + getUpperMargin() * range;\r\n lower = lower - getLowerMargin() * range;\r\n }\r\n }\r\n\r\n setRange(new Range(lower, upper), false, false);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Converts a data value to a coordinate in Java2D space, assuming that the\r\n * axis runs along one edge of the specified dataArea.\r\n * <p>\r\n * Note that it is possible for the coordinate to fall outside the plotArea.\r\n *\r\n * @param value the data value.\r\n * @param area the area for plotting the data.\r\n * @param edge the axis location.\r\n *\r\n * @return The Java2D coordinate.\r\n *\r\n * @see #java2DToValue(double, Rectangle2D, RectangleEdge)\r\n */\r\n @Override\r\n public double valueToJava2D(double value, Rectangle2D area,\r\n RectangleEdge edge) {\r\n\r\n Range range = getRange();\r\n double axisMin = range.getLowerBound();\r\n double axisMax = range.getUpperBound();\r\n\r\n double min = 0.0;\r\n double max = 0.0;\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n min = area.getX();\r\n max = area.getMaxX();\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n max = area.getMinY();\r\n min = area.getMaxY();\r\n }\r\n if (isInverted()) {\r\n return max\r\n - ((value - axisMin) / (axisMax - axisMin)) * (max - min);\r\n }\r\n else {\r\n return min\r\n + ((value - axisMin) / (axisMax - axisMin)) * (max - min);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Converts a coordinate in Java2D space to the corresponding data value,\r\n * assuming that the axis runs along one edge of the specified dataArea.\r\n *\r\n * @param java2DValue the coordinate in Java2D space.\r\n * @param area the area in which the data is plotted.\r\n * @param edge the location.\r\n *\r\n * @return The data value.\r\n *\r\n * @see #valueToJava2D(double, Rectangle2D, RectangleEdge)\r\n */\r\n @Override\r\n public double java2DToValue(double java2DValue, Rectangle2D area,\r\n RectangleEdge edge) {\r\n\r\n Range range = getRange();\r\n double axisMin = range.getLowerBound();\r\n double axisMax = range.getUpperBound();\r\n\r\n double min = 0.0;\r\n double max = 0.0;\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n min = area.getX();\r\n max = area.getMaxX();\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n min = area.getMaxY();\r\n max = area.getY();\r\n }\r\n if (isInverted()) {\r\n return axisMax\r\n - (java2DValue - min) / (max - min) * (axisMax - axisMin);\r\n }\r\n else {\r\n return axisMin\r\n + (java2DValue - min) / (max - min) * (axisMax - axisMin);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Calculates the value of the lowest visible tick on the axis.\r\n *\r\n * @return The value of the lowest visible tick on the axis.\r\n *\r\n * @see #calculateHighestVisibleTickValue()\r\n */\r\n protected double calculateLowestVisibleTickValue() {\r\n double unit = getTickUnit().getSize();\r\n double index = Math.ceil(getRange().getLowerBound() / unit);\r\n return index * unit;\r\n }\r\n\r\n /**\r\n * Calculates the value of the highest visible tick on the axis.\r\n *\r\n * @return The value of the highest visible tick on the axis.\r\n *\r\n * @see #calculateLowestVisibleTickValue()\r\n */\r\n protected double calculateHighestVisibleTickValue() {\r\n double unit = getTickUnit().getSize();\r\n double index = Math.floor(getRange().getUpperBound() / unit);\r\n return index * unit;\r\n }\r\n\r\n /**\r\n * Calculates the number of visible ticks.\r\n *\r\n * @return The number of visible ticks on the axis.\r\n */\r\n protected int calculateVisibleTickCount() {\r\n double unit = getTickUnit().getSize();\r\n Range range = getRange();\r\n return (int) (Math.floor(range.getUpperBound() / unit)\r\n - Math.ceil(range.getLowerBound() / unit) + 1);\r\n }\r\n\r\n /**\r\n * Draws the axis on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param cursor the cursor location.\r\n * @param plotArea the area within which the axes and data should be drawn\r\n * (<code>null</code> not permitted).\r\n * @param dataArea the area within which the data should be drawn\r\n * (<code>null</code> not permitted).\r\n * @param edge the location of the axis (<code>null</code> not permitted).\r\n * @param plotState collects information about the plot\r\n * (<code>null</code> permitted).\r\n *\r\n * @return The axis state (never <code>null</code>).\r\n */\r\n @Override\r\n public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,\r\n Rectangle2D dataArea, RectangleEdge edge,\r\n PlotRenderingInfo plotState) {\r\n\r\n AxisState state;\r\n // if the axis is not visible, don't draw it...\r\n if (!isVisible()) {\r\n state = new AxisState(cursor);\r\n // even though the axis is not visible, we need ticks for the\r\n // gridlines...\r\n List ticks = refreshTicks(g2, state, dataArea, edge);\r\n state.setTicks(ticks);\r\n return state;\r\n }\r\n\r\n // draw the tick marks and labels...\r\n state = drawTickMarksAndLabels(g2, cursor, plotArea, dataArea, edge);\r\n\r\n if (getAttributedLabel() != null) {\r\n state = drawAttributedLabel(getAttributedLabel(), g2, plotArea, \r\n dataArea, edge, state);\r\n \r\n } else {\r\n state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);\r\n }\r\n createAndAddEntity(cursor, state, dataArea, edge, plotState);\r\n return state;\r\n\r\n }\r\n\r\n /**\r\n * Creates the standard tick units.\r\n * <P>\r\n * If you don't like these defaults, create your own instance of TickUnits\r\n * and then pass it to the setStandardTickUnits() method in the\r\n * NumberAxis class.\r\n *\r\n * @return The standard tick units.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n * @see #createIntegerTickUnits()\r\n */\r\n public static TickUnitSource createStandardTickUnits() {\r\n return new NumberTickUnitSource();\r\n }\r\n\r\n /**\r\n * Returns a collection of tick units for integer values.\r\n *\r\n * @return A collection of tick units for integer values.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n * @see #createStandardTickUnits()\r\n */\r\n public static TickUnitSource createIntegerTickUnits() {\r\n return new NumberTickUnitSource(true);\r\n }\r\n\r\n /**\r\n * Creates a collection of standard tick units. The supplied locale is\r\n * used to create the number formatter (a localised instance of\r\n * <code>NumberFormat</code>).\r\n * <P>\r\n * If you don't like these defaults, create your own instance of\r\n * {@link TickUnits} and then pass it to the\r\n * <code>setStandardTickUnits()</code> method.\r\n *\r\n * @param locale the locale.\r\n *\r\n * @return A tick unit collection.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n */\r\n public static TickUnitSource createStandardTickUnits(Locale locale) {\r\n NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);\r\n return new NumberTickUnitSource(false, numberFormat);\r\n }\r\n\r\n /**\r\n * Returns a collection of tick units for integer values.\r\n * Uses a given Locale to create the DecimalFormats.\r\n *\r\n * @param locale the locale to use to represent Numbers.\r\n *\r\n * @return A collection of tick units for integer values.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n */\r\n public static TickUnitSource createIntegerTickUnits(Locale locale) {\r\n NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);\r\n return new NumberTickUnitSource(true, numberFormat);\r\n }\r\n\r\n /**\r\n * Estimates the maximum tick label height.\r\n *\r\n * @param g2 the graphics device.\r\n *\r\n * @return The maximum height.\r\n */\r\n protected double estimateMaximumTickLabelHeight(Graphics2D g2) {\r\n RectangleInsets tickLabelInsets = getTickLabelInsets();\r\n double result = tickLabelInsets.getTop() + tickLabelInsets.getBottom();\r\n\r\n Font tickLabelFont = getTickLabelFont();\r\n FontRenderContext frc = g2.getFontRenderContext();\r\n result += tickLabelFont.getLineMetrics(\"123\", frc).getHeight();\r\n return result;\r\n }\r\n\r\n /**\r\n * Estimates the maximum width of the tick labels, assuming the specified\r\n * tick unit is used.\r\n * <P>\r\n * Rather than computing the string bounds of every tick on the axis, we\r\n * just look at two values: the lower bound and the upper bound for the\r\n * axis. These two values will usually be representative.\r\n *\r\n * @param g2 the graphics device.\r\n * @param unit the tick unit to use for calculation.\r\n *\r\n * @return The estimated maximum width of the tick labels.\r\n */\r\n protected double estimateMaximumTickLabelWidth(Graphics2D g2,\r\n TickUnit unit) {\r\n\r\n RectangleInsets tickLabelInsets = getTickLabelInsets();\r\n double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();\r\n\r\n if (isVerticalTickLabels()) {\r\n // all tick labels have the same width (equal to the height of the\r\n // font)...\r\n FontRenderContext frc = g2.getFontRenderContext();\r\n LineMetrics lm = getTickLabelFont().getLineMetrics(\"0\", frc);\r\n result += lm.getHeight();\r\n }\r\n else {\r\n // look at lower and upper bounds...\r\n FontMetrics fm = g2.getFontMetrics(getTickLabelFont());\r\n Range range = getRange();\r\n double lower = range.getLowerBound();\r\n double upper = range.getUpperBound();\r\n String lowerStr, upperStr;\r\n NumberFormat formatter = getNumberFormatOverride();\r\n if (formatter != null) {\r\n lowerStr = formatter.format(lower);\r\n upperStr = formatter.format(upper);\r\n }\r\n else {\r\n lowerStr = unit.valueToString(lower);\r\n upperStr = unit.valueToString(upper);\r\n }\r\n double w1 = fm.stringWidth(lowerStr);\r\n double w2 = fm.stringWidth(upperStr);\r\n result += Math.max(w1, w2);\r\n }\r\n\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Selects an appropriate tick value for the axis. The strategy is to\r\n * display as many ticks as possible (selected from an array of 'standard'\r\n * tick units) without the labels overlapping.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area defined by the axes.\r\n * @param edge the axis location.\r\n */\r\n protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea,\r\n RectangleEdge edge) {\r\n\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n selectHorizontalAutoTickUnit(g2, dataArea, edge);\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n selectVerticalAutoTickUnit(g2, dataArea, edge);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Selects an appropriate tick value for the axis. The strategy is to\r\n * display as many ticks as possible (selected from an array of 'standard'\r\n * tick units) without the labels overlapping.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area defined by the axes.\r\n * @param edge the axis location.\r\n */\r\n protected void selectHorizontalAutoTickUnit(Graphics2D g2,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n double tickLabelWidth = estimateMaximumTickLabelWidth(g2,\r\n getTickUnit());\r\n\r\n // start with the current tick unit...\r\n TickUnitSource tickUnits = getStandardTickUnits();\r\n TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());\r\n double unit1Width = lengthToJava2D(unit1.getSize(), dataArea, edge);\r\n\r\n // then extrapolate...\r\n double guess = (tickLabelWidth / unit1Width) * unit1.getSize();\r\n\r\n NumberTickUnit unit2 = (NumberTickUnit) tickUnits.getCeilingTickUnit(\r\n guess);\r\n double unit2Width = lengthToJava2D(unit2.getSize(), dataArea, edge);\r\n\r\n tickLabelWidth = estimateMaximumTickLabelWidth(g2, unit2);\r\n if (tickLabelWidth > unit2Width) {\r\n unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);\r\n }\r\n\r\n setTickUnit(unit2, false, false);\r\n\r\n }\r\n\r\n /**\r\n * Selects an appropriate tick value for the axis. The strategy is to\r\n * display as many ticks as possible (selected from an array of 'standard'\r\n * tick units) without the labels overlapping.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area in which the plot should be drawn.\r\n * @param edge the axis location.\r\n */\r\n protected void selectVerticalAutoTickUnit(Graphics2D g2, \r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n double tickLabelHeight = estimateMaximumTickLabelHeight(g2);\r\n\r\n // start with the current tick unit...\r\n TickUnitSource tickUnits = getStandardTickUnits();\r\n TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());\r\n double unitHeight = lengthToJava2D(unit1.getSize(), dataArea, edge);\r\n double guess = unit1.getSize();\r\n if (unitHeight > 0) {\r\n // then extrapolate...\r\n guess = (tickLabelHeight / unitHeight) * unit1.getSize();\r\n }\r\n NumberTickUnit unit2 = (NumberTickUnit) tickUnits.getCeilingTickUnit(\r\n guess);\r\n double unit2Height = lengthToJava2D(unit2.getSize(), dataArea, edge);\r\n\r\n tickLabelHeight = estimateMaximumTickLabelHeight(g2);\r\n if (tickLabelHeight > unit2Height) {\r\n unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);\r\n }\r\n\r\n setTickUnit(unit2, false, false);\r\n\r\n }\r\n\r\n /**\r\n * Calculates the positions of the tick labels for the axis, storing the\r\n * results in the tick label list (ready for drawing).\r\n *\r\n * @param g2 the graphics device.\r\n * @param state the axis state.\r\n * @param dataArea the area in which the plot should be drawn.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n @Override\r\n public List refreshTicks(Graphics2D g2, AxisState state, \r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List result = new java.util.ArrayList();\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n result = refreshTicksHorizontal(g2, dataArea, edge);\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n result = refreshTicksVertical(g2, dataArea, edge);\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the positions of the tick labels for the axis, storing the\r\n * results in the tick label list (ready for drawing).\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area in which the data should be drawn.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n protected List refreshTicksHorizontal(Graphics2D g2,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List result = new java.util.ArrayList();\r\n\r\n Font tickLabelFont = getTickLabelFont();\r\n g2.setFont(tickLabelFont);\r\n\r\n if (isAutoTickUnitSelection()) {\r\n selectAutoTickUnit(g2, dataArea, edge);\r\n }\r\n\r\n TickUnit tu = getTickUnit();\r\n double size = tu.getSize();\r\n int count = calculateVisibleTickCount();\r\n double lowestTickValue = calculateLowestVisibleTickValue();\r\n\r\n if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {\r\n int minorTickSpaces = getMinorTickCount();\r\n if (minorTickSpaces <= 0) {\r\n minorTickSpaces = tu.getMinorTickCount();\r\n }\r\n for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {\r\n double minorTickValue = lowestTickValue \r\n - size * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR, minorTickValue,\r\n \"\", TextAnchor.TOP_CENTER, TextAnchor.CENTER,\r\n 0.0));\r\n }\r\n }\r\n for (int i = 0; i < count; i++) {\r\n double currentTickValue = lowestTickValue + (i * size);\r\n String tickLabel;\r\n NumberFormat formatter = getNumberFormatOverride();\r\n if (formatter != null) {\r\n tickLabel = formatter.format(currentTickValue);\r\n }\r\n else {\r\n tickLabel = getTickUnit().valueToString(currentTickValue);\r\n }\r\n TextAnchor anchor, rotationAnchor;\r\n double angle = 0.0;\r\n if (isVerticalTickLabels()) {\r\n anchor = TextAnchor.CENTER_RIGHT;\r\n rotationAnchor = TextAnchor.CENTER_RIGHT;\r\n if (edge == RectangleEdge.TOP) {\r\n angle = Math.PI / 2.0;\r\n }\r\n else {\r\n angle = -Math.PI / 2.0;\r\n }\r\n }\r\n else {\r\n if (edge == RectangleEdge.TOP) {\r\n anchor = TextAnchor.BOTTOM_CENTER;\r\n rotationAnchor = TextAnchor.BOTTOM_CENTER;\r\n }\r\n else {\r\n anchor = TextAnchor.TOP_CENTER;\r\n rotationAnchor = TextAnchor.TOP_CENTER;\r\n }\r\n }\r\n\r\n Tick tick = new NumberTick(new Double(currentTickValue),\r\n tickLabel, anchor, rotationAnchor, angle);\r\n result.add(tick);\r\n double nextTickValue = lowestTickValue + ((i + 1) * size);\r\n for (int minorTick = 1; minorTick < minorTickSpaces;\r\n minorTick++) {\r\n double minorTickValue = currentTickValue\r\n + (nextTickValue - currentTickValue)\r\n * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR,\r\n minorTickValue, \"\", TextAnchor.TOP_CENTER,\r\n TextAnchor.CENTER, 0.0));\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the positions of the tick labels for the axis, storing the\r\n * results in the tick label list (ready for drawing).\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area in which the plot should be drawn.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n protected List refreshTicksVertical(Graphics2D g2,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List result = new java.util.ArrayList();\r\n result.clear();\r\n\r\n Font tickLabelFont = getTickLabelFont();\r\n g2.setFont(tickLabelFont);\r\n if (isAutoTickUnitSelection()) {\r\n selectAutoTickUnit(g2, dataArea, edge);\r\n }\r\n\r\n TickUnit tu = getTickUnit();\r\n double size = tu.getSize();\r\n int count = calculateVisibleTickCount();\r\n double lowestTickValue = calculateLowestVisibleTickValue();\r\n\r\n if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {\r\n int minorTickSpaces = getMinorTickCount();\r\n if (minorTickSpaces <= 0) {\r\n minorTickSpaces = tu.getMinorTickCount();\r\n }\r\n for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {\r\n double minorTickValue = lowestTickValue\r\n - size * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR, minorTickValue,\r\n \"\", TextAnchor.TOP_CENTER, TextAnchor.CENTER,\r\n 0.0));\r\n }\r\n }\r\n\r\n for (int i = 0; i < count; i++) {\r\n double currentTickValue = lowestTickValue + (i * size);\r\n String tickLabel;\r\n NumberFormat formatter = getNumberFormatOverride();\r\n if (formatter != null) {\r\n tickLabel = formatter.format(currentTickValue);\r\n }\r\n else {\r\n tickLabel = getTickUnit().valueToString(currentTickValue);\r\n }\r\n\r\n TextAnchor anchor;\r\n TextAnchor rotationAnchor;\r\n double angle = 0.0;\r\n if (isVerticalTickLabels()) {\r\n if (edge == RectangleEdge.LEFT) {\r\n anchor = TextAnchor.BOTTOM_CENTER;\r\n rotationAnchor = TextAnchor.BOTTOM_CENTER;\r\n angle = -Math.PI / 2.0;\r\n }\r\n else {\r\n anchor = TextAnchor.BOTTOM_CENTER;\r\n rotationAnchor = TextAnchor.BOTTOM_CENTER;\r\n angle = Math.PI / 2.0;\r\n }\r\n }\r\n else {\r\n if (edge == RectangleEdge.LEFT) {\r\n anchor = TextAnchor.CENTER_RIGHT;\r\n rotationAnchor = TextAnchor.CENTER_RIGHT;\r\n }\r\n else {\r\n anchor = TextAnchor.CENTER_LEFT;\r\n rotationAnchor = TextAnchor.CENTER_LEFT;\r\n }\r\n }\r\n\r\n Tick tick = new NumberTick(new Double(currentTickValue),\r\n tickLabel, anchor, rotationAnchor, angle);\r\n result.add(tick);\r\n\r\n double nextTickValue = lowestTickValue + ((i + 1) * size);\r\n for (int minorTick = 1; minorTick < minorTickSpaces;\r\n minorTick++) {\r\n double minorTickValue = currentTickValue\r\n + (nextTickValue - currentTickValue)\r\n * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR,\r\n minorTickValue, \"\", TextAnchor.TOP_CENTER,\r\n TextAnchor.CENTER, 0.0));\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Returns a clone of the axis.\r\n *\r\n * @return A clone\r\n *\r\n * @throws CloneNotSupportedException if some component of the axis does\r\n * not support cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n NumberAxis clone = (NumberAxis) super.clone();\r\n if (this.numberFormatOverride != null) {\r\n clone.numberFormatOverride\r\n = (NumberFormat) this.numberFormatOverride.clone();\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * Tests the axis for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof NumberAxis)) {\r\n return false;\r\n }\r\n NumberAxis that = (NumberAxis) obj;\r\n if (this.autoRangeIncludesZero != that.autoRangeIncludesZero) {\r\n return false;\r\n }\r\n if (this.autoRangeStickyZero != that.autoRangeStickyZero) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.tickUnit, that.tickUnit)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.numberFormatOverride,\r\n that.numberFormatOverride)) {\r\n return false;\r\n }\r\n if (!this.rangeType.equals(that.rangeType)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a hash code for this object.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n return super.hashCode();\r\n }\r\n\r\n}\r" }, { "identifier": "XYPlot", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/XYPlot.java", "snippet": "public class XYPlot extends Plot implements ValueAxisPlot, Pannable, Zoomable,\r\n RendererChangeListener, Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 7044148245716569264L;\r\n\r\n /** The default grid line stroke. */\r\n public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f,\r\n BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f,\r\n new float[] {2.0f, 2.0f}, 0.0f);\r\n\r\n /** The default grid line paint. */\r\n public static final Paint DEFAULT_GRIDLINE_PAINT = Color.lightGray;\r\n\r\n /** The default crosshair visibility. */\r\n public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false;\r\n\r\n /** The default crosshair stroke. */\r\n public static final Stroke DEFAULT_CROSSHAIR_STROKE\r\n = DEFAULT_GRIDLINE_STROKE;\r\n\r\n /** The default crosshair paint. */\r\n public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.blue;\r\n\r\n /** The resourceBundle for the localization. */\r\n protected static ResourceBundle localizationResources\r\n = ResourceBundleWrapper.getBundle(\r\n \"org.jfree.chart.plot.LocalizationBundle\");\r\n\r\n /** The plot orientation. */\r\n private PlotOrientation orientation;\r\n\r\n /** The offset between the data area and the axes. */\r\n private RectangleInsets axisOffset;\r\n\r\n /** The domain axis / axes (used for the x-values). */\r\n private Map<Integer, ValueAxis> domainAxes;\r\n\r\n /** The domain axis locations. */\r\n private Map<Integer, AxisLocation> domainAxisLocations;\r\n\r\n /** The range axis (used for the y-values). */\r\n private Map<Integer, ValueAxis> rangeAxes;\r\n\r\n /** The range axis location. */\r\n private Map<Integer, AxisLocation> rangeAxisLocations;\r\n\r\n /** Storage for the datasets. */\r\n private Map<Integer, XYDataset> datasets;\r\n\r\n /** Storage for the renderers. */\r\n private Map<Integer, XYItemRenderer> renderers;\r\n\r\n /**\r\n * Storage for the mapping between datasets/renderers and domain axes. The\r\n * keys in the map are Integer objects, corresponding to the dataset\r\n * index. The values in the map are List objects containing Integer\r\n * objects (corresponding to the axis indices). If the map contains no\r\n * entry for a dataset, it is assumed to map to the primary domain axis\r\n * (index = 0).\r\n */\r\n private Map<Integer, List<Integer>> datasetToDomainAxesMap;\r\n\r\n /**\r\n * Storage for the mapping between datasets/renderers and range axes. The\r\n * keys in the map are Integer objects, corresponding to the dataset\r\n * index. The values in the map are List objects containing Integer\r\n * objects (corresponding to the axis indices). If the map contains no\r\n * entry for a dataset, it is assumed to map to the primary domain axis\r\n * (index = 0).\r\n */\r\n private Map<Integer, List<Integer>> datasetToRangeAxesMap;\r\n\r\n /** The origin point for the quadrants (if drawn). */\r\n private transient Point2D quadrantOrigin = new Point2D.Double(0.0, 0.0);\r\n\r\n /** The paint used for each quadrant. */\r\n private transient Paint[] quadrantPaint\r\n = new Paint[] {null, null, null, null};\r\n\r\n /** A flag that controls whether the domain grid-lines are visible. */\r\n private boolean domainGridlinesVisible;\r\n\r\n /** The stroke used to draw the domain grid-lines. */\r\n private transient Stroke domainGridlineStroke;\r\n\r\n /** The paint used to draw the domain grid-lines. */\r\n private transient Paint domainGridlinePaint;\r\n\r\n /** A flag that controls whether the range grid-lines are visible. */\r\n private boolean rangeGridlinesVisible;\r\n\r\n /** The stroke used to draw the range grid-lines. */\r\n private transient Stroke rangeGridlineStroke;\r\n\r\n /** The paint used to draw the range grid-lines. */\r\n private transient Paint rangeGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether the domain minor grid-lines are visible.\r\n *\r\n * @since 1.0.12\r\n */\r\n private boolean domainMinorGridlinesVisible;\r\n\r\n /**\r\n * The stroke used to draw the domain minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Stroke domainMinorGridlineStroke;\r\n\r\n /**\r\n * The paint used to draw the domain minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Paint domainMinorGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether the range minor grid-lines are visible.\r\n *\r\n * @since 1.0.12\r\n */\r\n private boolean rangeMinorGridlinesVisible;\r\n\r\n /**\r\n * The stroke used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Stroke rangeMinorGridlineStroke;\r\n\r\n /**\r\n * The paint used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Paint rangeMinorGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not the zero baseline against the domain\r\n * axis is visible.\r\n *\r\n * @since 1.0.5\r\n */\r\n private boolean domainZeroBaselineVisible;\r\n\r\n /**\r\n * The stroke used for the zero baseline against the domain axis.\r\n *\r\n * @since 1.0.5\r\n */\r\n private transient Stroke domainZeroBaselineStroke;\r\n\r\n /**\r\n * The paint used for the zero baseline against the domain axis.\r\n *\r\n * @since 1.0.5\r\n */\r\n private transient Paint domainZeroBaselinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not the zero baseline against the range\r\n * axis is visible.\r\n */\r\n private boolean rangeZeroBaselineVisible;\r\n\r\n /** The stroke used for the zero baseline against the range axis. */\r\n private transient Stroke rangeZeroBaselineStroke;\r\n\r\n /** The paint used for the zero baseline against the range axis. */\r\n private transient Paint rangeZeroBaselinePaint;\r\n\r\n /** A flag that controls whether or not a domain crosshair is drawn..*/\r\n private boolean domainCrosshairVisible;\r\n\r\n /** The domain crosshair value. */\r\n private double domainCrosshairValue;\r\n\r\n /** The pen/brush used to draw the crosshair (if any). */\r\n private transient Stroke domainCrosshairStroke;\r\n\r\n /** The color used to draw the crosshair (if any). */\r\n private transient Paint domainCrosshairPaint;\r\n\r\n /**\r\n * A flag that controls whether or not the crosshair locks onto actual\r\n * data points.\r\n */\r\n private boolean domainCrosshairLockedOnData = true;\r\n\r\n /** A flag that controls whether or not a range crosshair is drawn..*/\r\n private boolean rangeCrosshairVisible;\r\n\r\n /** The range crosshair value. */\r\n private double rangeCrosshairValue;\r\n\r\n /** The pen/brush used to draw the crosshair (if any). */\r\n private transient Stroke rangeCrosshairStroke;\r\n\r\n /** The color used to draw the crosshair (if any). */\r\n private transient Paint rangeCrosshairPaint;\r\n\r\n /**\r\n * A flag that controls whether or not the crosshair locks onto actual\r\n * data points.\r\n */\r\n private boolean rangeCrosshairLockedOnData = true;\r\n\r\n /** A map of lists of foreground markers (optional) for the domain axes. */\r\n private Map foregroundDomainMarkers;\r\n\r\n /** A map of lists of background markers (optional) for the domain axes. */\r\n private Map backgroundDomainMarkers;\r\n\r\n /** A map of lists of foreground markers (optional) for the range axes. */\r\n private Map foregroundRangeMarkers;\r\n\r\n /** A map of lists of background markers (optional) for the range axes. */\r\n private Map backgroundRangeMarkers;\r\n\r\n /**\r\n * A (possibly empty) list of annotations for the plot. The list should\r\n * be initialised in the constructor and never allowed to be\r\n * <code>null</code>.\r\n */\r\n private List<XYAnnotation> annotations;\r\n\r\n /** The paint used for the domain tick bands (if any). */\r\n private transient Paint domainTickBandPaint;\r\n\r\n /** The paint used for the range tick bands (if any). */\r\n private transient Paint rangeTickBandPaint;\r\n\r\n /** The fixed domain axis space. */\r\n private AxisSpace fixedDomainAxisSpace;\r\n\r\n /** The fixed range axis space. */\r\n private AxisSpace fixedRangeAxisSpace;\r\n\r\n /**\r\n * The order of the dataset rendering (REVERSE draws the primary dataset\r\n * last so that it appears to be on top).\r\n */\r\n private DatasetRenderingOrder datasetRenderingOrder\r\n = DatasetRenderingOrder.REVERSE;\r\n\r\n /**\r\n * The order of the series rendering (REVERSE draws the primary series\r\n * last so that it appears to be on top).\r\n */\r\n private SeriesRenderingOrder seriesRenderingOrder\r\n = SeriesRenderingOrder.REVERSE;\r\n\r\n /**\r\n * The weight for this plot (only relevant if this is a subplot in a\r\n * combined plot).\r\n */\r\n private int weight;\r\n\r\n /**\r\n * An optional collection of legend items that can be returned by the\r\n * getLegendItems() method.\r\n */\r\n private LegendItemCollection fixedLegendItems;\r\n\r\n /**\r\n * A flag that controls whether or not panning is enabled for the domain\r\n * axis/axes.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean domainPannable;\r\n\r\n /**\r\n * A flag that controls whether or not panning is enabled for the range\r\n * axis/axes.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean rangePannable;\r\n\r\n /**\r\n * The shadow generator (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n private ShadowGenerator shadowGenerator;\r\n\r\n /**\r\n * Creates a new <code>XYPlot</code> instance with no dataset, no axes and\r\n * no renderer. You should specify these items before using the plot.\r\n */\r\n public XYPlot() {\r\n this(null, null, null, null);\r\n }\r\n\r\n /**\r\n * Creates a new plot with the specified dataset, axes and renderer. Any\r\n * of the arguments can be <code>null</code>, but in that case you should\r\n * take care to specify the value before using the plot (otherwise a\r\n * <code>NullPointerException</code> may be thrown).\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n * @param domainAxis the domain axis (<code>null</code> permitted).\r\n * @param rangeAxis the range axis (<code>null</code> permitted).\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n */\r\n public XYPlot(XYDataset dataset, ValueAxis domainAxis, ValueAxis rangeAxis,\r\n XYItemRenderer renderer) {\r\n super();\r\n this.orientation = PlotOrientation.VERTICAL;\r\n this.weight = 1; // only relevant when this is a subplot\r\n this.axisOffset = RectangleInsets.ZERO_INSETS;\r\n\r\n // allocate storage for datasets, axes and renderers (all optional)\r\n this.domainAxes = new HashMap<Integer, ValueAxis>();\r\n this.domainAxisLocations = new HashMap<Integer, AxisLocation>();\r\n this.foregroundDomainMarkers = new HashMap();\r\n this.backgroundDomainMarkers = new HashMap();\r\n\r\n this.rangeAxes = new HashMap<Integer, ValueAxis>();\r\n this.rangeAxisLocations = new HashMap<Integer, AxisLocation>();\r\n this.foregroundRangeMarkers = new HashMap();\r\n this.backgroundRangeMarkers = new HashMap();\r\n\r\n this.datasets = new HashMap<Integer, XYDataset>();\r\n this.renderers = new HashMap<Integer, XYItemRenderer>();\r\n\r\n this.datasetToDomainAxesMap = new TreeMap();\r\n this.datasetToRangeAxesMap = new TreeMap();\r\n\r\n this.annotations = new java.util.ArrayList();\r\n\r\n this.datasets.put(0, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n\r\n this.renderers.put(0, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n\r\n this.domainAxes.put(0, domainAxis);\r\n mapDatasetToDomainAxis(0, 0);\r\n if (domainAxis != null) {\r\n domainAxis.setPlot(this);\r\n domainAxis.addChangeListener(this);\r\n }\r\n this.domainAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT);\r\n\r\n this.rangeAxes.put(0, rangeAxis);\r\n mapDatasetToRangeAxis(0, 0);\r\n if (rangeAxis != null) {\r\n rangeAxis.setPlot(this);\r\n rangeAxis.addChangeListener(this);\r\n }\r\n this.rangeAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT);\r\n\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n\r\n this.domainGridlinesVisible = true;\r\n this.domainGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.domainGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.domainMinorGridlinesVisible = false;\r\n this.domainMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.domainMinorGridlinePaint = Color.white;\r\n\r\n this.domainZeroBaselineVisible = false;\r\n this.domainZeroBaselinePaint = Color.black;\r\n this.domainZeroBaselineStroke = new BasicStroke(0.5f);\r\n\r\n this.rangeGridlinesVisible = true;\r\n this.rangeGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.rangeMinorGridlinesVisible = false;\r\n this.rangeMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeMinorGridlinePaint = Color.white;\r\n\r\n this.rangeZeroBaselineVisible = false;\r\n this.rangeZeroBaselinePaint = Color.black;\r\n this.rangeZeroBaselineStroke = new BasicStroke(0.5f);\r\n\r\n this.domainCrosshairVisible = false;\r\n this.domainCrosshairValue = 0.0;\r\n this.domainCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.domainCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n\r\n this.rangeCrosshairVisible = false;\r\n this.rangeCrosshairValue = 0.0;\r\n this.rangeCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.rangeCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n this.shadowGenerator = null;\r\n }\r\n\r\n /**\r\n * Returns the plot type as a string.\r\n *\r\n * @return A short string describing the type of plot.\r\n */\r\n @Override\r\n public String getPlotType() {\r\n return localizationResources.getString(\"XY_Plot\");\r\n }\r\n\r\n /**\r\n * Returns the orientation of the plot.\r\n *\r\n * @return The orientation (never <code>null</code>).\r\n *\r\n * @see #setOrientation(PlotOrientation)\r\n */\r\n @Override\r\n public PlotOrientation getOrientation() {\r\n return this.orientation;\r\n }\r\n\r\n /**\r\n * Sets the orientation for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param orientation the orientation (<code>null</code> not allowed).\r\n *\r\n * @see #getOrientation()\r\n */\r\n public void setOrientation(PlotOrientation orientation) {\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n if (orientation != this.orientation) {\r\n this.orientation = orientation;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the axis offset.\r\n *\r\n * @return The axis offset (never <code>null</code>).\r\n *\r\n * @see #setAxisOffset(RectangleInsets)\r\n */\r\n public RectangleInsets getAxisOffset() {\r\n return this.axisOffset;\r\n }\r\n\r\n /**\r\n * Sets the axis offsets (gap between the data area and the axes) and sends\r\n * a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param offset the offset (<code>null</code> not permitted).\r\n *\r\n * @see #getAxisOffset()\r\n */\r\n public void setAxisOffset(RectangleInsets offset) {\r\n ParamChecks.nullNotPermitted(offset, \"offset\");\r\n this.axisOffset = offset;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the domain axis with index 0. If the domain axis for this plot\r\n * is <code>null</code>, then the method will return the parent plot's\r\n * domain axis (if there is a parent plot).\r\n *\r\n * @return The domain axis (possibly <code>null</code>).\r\n *\r\n * @see #getDomainAxis(int)\r\n * @see #setDomainAxis(ValueAxis)\r\n */\r\n public ValueAxis getDomainAxis() {\r\n return getDomainAxis(0);\r\n }\r\n\r\n /**\r\n * Returns the domain axis with the specified index, or {@code null} if \r\n * there is no axis with that index.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The axis ({@code null} possible).\r\n *\r\n * @see #setDomainAxis(int, ValueAxis)\r\n */\r\n public ValueAxis getDomainAxis(int index) {\r\n ValueAxis result = this.domainAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot xy = (XYPlot) parent;\r\n result = xy.getDomainAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the domain axis for the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axis the new axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis()\r\n * @see #setDomainAxis(int, ValueAxis)\r\n */\r\n public void setDomainAxis(ValueAxis axis) {\r\n setDomainAxis(0, axis);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis(int)\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public void setDomainAxis(int index, ValueAxis axis) {\r\n setDomainAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainAxis(int)\r\n */\r\n public void setDomainAxis(int index, ValueAxis axis, boolean notify) {\r\n ValueAxis existing = getDomainAxis(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.domainAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the domain axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setRangeAxes(ValueAxis[])\r\n */\r\n public void setDomainAxes(ValueAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setDomainAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the location of the primary domain axis.\r\n *\r\n * @return The location (never <code>null</code>).\r\n *\r\n * @see #setDomainAxisLocation(AxisLocation)\r\n */\r\n public AxisLocation getDomainAxisLocation() {\r\n return (AxisLocation) this.domainAxisLocations.get(0);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary domain axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainAxisLocation()\r\n */\r\n public void setDomainAxisLocation(AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainAxisLocation()\r\n */\r\n public void setDomainAxisLocation(AxisLocation location, boolean notify) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Returns the edge for the primary domain axis (taking into account the\r\n * plot's orientation).\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getDomainAxisLocation()\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getDomainAxisEdge() {\r\n return Plot.resolveDomainAxisLocation(getDomainAxisLocation(),\r\n this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the number of domain axes.\r\n *\r\n * @return The axis count.\r\n *\r\n * @see #getRangeAxisCount()\r\n */\r\n public int getDomainAxisCount() {\r\n return this.domainAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the domain axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #clearRangeAxes()\r\n */\r\n public void clearDomainAxes() {\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.removeChangeListener(this);\r\n }\r\n }\r\n this.domainAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the domain axes.\r\n */\r\n public void configureDomainAxes() {\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the location for a domain axis. If this hasn't been set\r\n * explicitly, the method returns the location that is opposite to the\r\n * primary domain axis location.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The location (never {@code null}).\r\n *\r\n * @see #setDomainAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getDomainAxisLocation(int index) {\r\n AxisLocation result = this.domainAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getDomainAxisLocation());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location for a domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> not permitted for index\r\n * 0).\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the axis location for a domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n * @param location the location (<code>null</code> not permitted for\r\n * index 0).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n * @see #setRangeAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.domainAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the edge for a domain axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getRangeAxisEdge(int)\r\n */\r\n public RectangleEdge getDomainAxisEdge(int index) {\r\n AxisLocation location = getDomainAxisLocation(index);\r\n return Plot.resolveDomainAxisLocation(location, this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the range axis for the plot. If the range axis for this plot is\r\n * <code>null</code>, then the method will return the parent plot's range\r\n * axis (if there is a parent plot).\r\n *\r\n * @return The range axis.\r\n *\r\n * @see #getRangeAxis(int)\r\n * @see #setRangeAxis(ValueAxis)\r\n */\r\n public ValueAxis getRangeAxis() {\r\n return getRangeAxis(0);\r\n }\r\n\r\n /**\r\n * Sets the range axis for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxis()\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public void setRangeAxis(ValueAxis axis) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n // plot is likely registered as a listener with the existing axis...\r\n ValueAxis existing = getRangeAxis();\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.rangeAxes.put(0, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the location of the primary range axis.\r\n *\r\n * @return The location (never <code>null</code>).\r\n *\r\n * @see #setRangeAxisLocation(AxisLocation)\r\n */\r\n public AxisLocation getRangeAxisLocation() {\r\n return (AxisLocation) this.rangeAxisLocations.get(0);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary range axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeAxisLocation()\r\n */\r\n public void setRangeAxisLocation(AxisLocation location) {\r\n // delegate...\r\n setRangeAxisLocation(0, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary range axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRangeAxisLocation()\r\n */\r\n public void setRangeAxisLocation(AxisLocation location, boolean notify) {\r\n // delegate...\r\n setRangeAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Returns the edge for the primary range axis.\r\n *\r\n * @return The range axis edge.\r\n *\r\n * @see #getRangeAxisLocation()\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getRangeAxisEdge() {\r\n return Plot.resolveRangeAxisLocation(getRangeAxisLocation(),\r\n this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the range axis with the specified index, or {@code null} if \r\n * there is no axis with that index.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The axis ({@code null} possible).\r\n *\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public ValueAxis getRangeAxis(int index) {\r\n ValueAxis result = this.rangeAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot xy = (XYPlot) parent;\r\n result = xy.getRangeAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets a range axis and sends a {@link PlotChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxis(int)\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis) {\r\n setRangeAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a range axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRangeAxis(int)\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis, boolean notify) {\r\n ValueAxis existing = getRangeAxis(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.rangeAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the range axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setDomainAxes(ValueAxis[])\r\n */\r\n public void setRangeAxes(ValueAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setRangeAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the number of range axes.\r\n *\r\n * @return The axis count.\r\n *\r\n * @see #getDomainAxisCount()\r\n */\r\n public int getRangeAxisCount() {\r\n return this.rangeAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the range axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #clearDomainAxes()\r\n */\r\n public void clearRangeAxes() {\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.removeChangeListener(this);\r\n }\r\n }\r\n this.rangeAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the range axes.\r\n *\r\n * @see #configureDomainAxes()\r\n */\r\n public void configureRangeAxes() {\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the location for a range axis. If this hasn't been set\r\n * explicitly, the method returns the location that is opposite to the\r\n * primary range axis location.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The location (never {@code null}).\r\n *\r\n * @see #setRangeAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getRangeAxisLocation(int index) {\r\n AxisLocation result = this.rangeAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getRangeAxisLocation());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location for a range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location) {\r\n // delegate...\r\n setRangeAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the axis location for a domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> not permitted for\r\n * index 0).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #setDomainAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.rangeAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the edge for a range axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getRangeAxisEdge(int index) {\r\n AxisLocation location = getRangeAxisLocation(index);\r\n return Plot.resolveRangeAxisLocation(location, this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the primary dataset for the plot.\r\n *\r\n * @return The primary dataset (possibly <code>null</code>).\r\n *\r\n * @see #getDataset(int)\r\n * @see #setDataset(XYDataset)\r\n */\r\n public XYDataset getDataset() {\r\n return getDataset(0);\r\n }\r\n\r\n /**\r\n * Returns the dataset with the specified index, or {@code null} if there\r\n * is no dataset with that index.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The dataset (possibly {@code null}).\r\n *\r\n * @see #setDataset(int, XYDataset)\r\n */\r\n public XYDataset getDataset(int index) {\r\n return (XYDataset) this.datasets.get(index);\r\n }\r\n\r\n /**\r\n * Sets the primary dataset for the plot, replacing the existing dataset if\r\n * there is one.\r\n *\r\n * @param dataset the dataset ({@code null} permitted).\r\n *\r\n * @see #getDataset()\r\n * @see #setDataset(int, XYDataset)\r\n */\r\n public void setDataset(XYDataset dataset) {\r\n setDataset(0, dataset);\r\n }\r\n\r\n /**\r\n * Sets a dataset for the plot and sends a change event to all registered\r\n * listeners.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n *\r\n * @see #getDataset(int)\r\n */\r\n public void setDataset(int index, XYDataset dataset) {\r\n XYDataset existing = getDataset(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.datasets.put(index, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n\r\n // send a dataset change event to self...\r\n DatasetChangeEvent event = new DatasetChangeEvent(this, dataset);\r\n datasetChanged(event);\r\n }\r\n\r\n /**\r\n * Returns the number of datasets.\r\n *\r\n * @return The number of datasets.\r\n */\r\n public int getDatasetCount() {\r\n return this.datasets.size();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified dataset, or {@code -1} if the\r\n * dataset does not belong to the plot.\r\n *\r\n * @param dataset the dataset ({@code null} not permitted).\r\n *\r\n * @return The index or -1.\r\n */\r\n public int indexOf(XYDataset dataset) {\r\n for (Map.Entry<Integer, XYDataset> entry: this.datasets.entrySet()) {\r\n if (dataset == entry.getValue()) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular domain axis. All data will be plotted\r\n * against axis zero by default, no mapping is required for this case.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index.\r\n *\r\n * @see #mapDatasetToRangeAxis(int, int)\r\n */\r\n public void mapDatasetToDomainAxis(int index, int axisIndex) {\r\n List axisIndices = new java.util.ArrayList(1);\r\n axisIndices.add(new Integer(axisIndex));\r\n mapDatasetToDomainAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToDomainAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n Integer key = new Integer(index);\r\n this.datasetToDomainAxesMap.put(key, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular range axis. All data will be plotted\r\n * against axis zero by default, no mapping is required for this case.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index.\r\n *\r\n * @see #mapDatasetToDomainAxis(int, int)\r\n */\r\n public void mapDatasetToRangeAxis(int index, int axisIndex) {\r\n List axisIndices = new java.util.ArrayList(1);\r\n axisIndices.add(new Integer(axisIndex));\r\n mapDatasetToRangeAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToRangeAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n Integer key = new Integer(index);\r\n this.datasetToRangeAxesMap.put(key, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * This method is used to perform argument checking on the list of\r\n * axis indices passed to mapDatasetToDomainAxes() and\r\n * mapDatasetToRangeAxes().\r\n *\r\n * @param indices the list of indices (<code>null</code> permitted).\r\n */\r\n private void checkAxisIndices(List<Integer> indices) {\r\n // axisIndices can be:\r\n // 1. null;\r\n // 2. non-empty, containing only Integer objects that are unique.\r\n if (indices == null) {\r\n return; // OK\r\n }\r\n int count = indices.size();\r\n if (count == 0) {\r\n throw new IllegalArgumentException(\"Empty list not permitted.\");\r\n }\r\n Set<Integer> set = new HashSet<Integer>();\r\n for (Integer item : indices) {\r\n if (set.contains(item)) {\r\n throw new IllegalArgumentException(\"Indices must be unique.\");\r\n }\r\n set.add(item);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the number of renderer slots for this plot.\r\n *\r\n * @return The number of renderer slots.\r\n *\r\n * @since 1.0.11\r\n */\r\n public int getRendererCount() {\r\n return this.renderers.size();\r\n }\r\n\r\n /**\r\n * Returns the renderer for the primary dataset.\r\n *\r\n * @return The item renderer (possibly <code>null</code>).\r\n *\r\n * @see #setRenderer(XYItemRenderer)\r\n */\r\n public XYItemRenderer getRenderer() {\r\n return getRenderer(0);\r\n }\r\n\r\n /**\r\n * Returns the renderer with the specified index, or {@code null}.\r\n *\r\n * @param index the renderer index (must be &gt;= 0).\r\n *\r\n * @return The renderer (possibly {@code null}).\r\n *\r\n * @see #setRenderer(int, XYItemRenderer)\r\n */\r\n public XYItemRenderer getRenderer(int index) {\r\n return (XYItemRenderer) this.renderers.get(index);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the primary dataset and sends a change event to \r\n * all registered listeners. If the renderer is set to <code>null</code>, \r\n * no data will be displayed.\r\n *\r\n * @param renderer the renderer ({@code null} permitted).\r\n *\r\n * @see #getRenderer()\r\n */\r\n public void setRenderer(XYItemRenderer renderer) {\r\n setRenderer(0, renderer);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the dataset with the specified index and sends a \r\n * change event to all registered listeners. Note that each dataset should \r\n * have its own renderer, you should not use one renderer for multiple \r\n * datasets.\r\n *\r\n * @param index the index (must be &gt;= 0).\r\n * @param renderer the renderer.\r\n *\r\n * @see #getRenderer(int)\r\n */\r\n public void setRenderer(int index, XYItemRenderer renderer) {\r\n setRenderer(index, renderer, true);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the dataset with the specified index and, if \r\n * requested, sends a change event to all registered listeners. Note that \r\n * each dataset should have its own renderer, you should not use one \r\n * renderer for multiple datasets.\r\n *\r\n * @param index the index (must be &gt;= 0).\r\n * @param renderer the renderer.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRenderer(int)\r\n */\r\n public void setRenderer(int index, XYItemRenderer renderer, \r\n boolean notify) {\r\n XYItemRenderer existing = getRenderer(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.renderers.put(index, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the renderers for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param renderers the renderers (<code>null</code> not permitted).\r\n */\r\n public void setRenderers(XYItemRenderer[] renderers) {\r\n for (int i = 0; i < renderers.length; i++) {\r\n setRenderer(i, renderers[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the dataset rendering order.\r\n *\r\n * @return The order (never <code>null</code>).\r\n *\r\n * @see #setDatasetRenderingOrder(DatasetRenderingOrder)\r\n */\r\n public DatasetRenderingOrder getDatasetRenderingOrder() {\r\n return this.datasetRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the rendering order and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. By default, the plot renders the primary dataset\r\n * last (so that the primary dataset overlays the secondary datasets).\r\n * You can reverse this if you want to.\r\n *\r\n * @param order the rendering order (<code>null</code> not permitted).\r\n *\r\n * @see #getDatasetRenderingOrder()\r\n */\r\n public void setDatasetRenderingOrder(DatasetRenderingOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.datasetRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the series rendering order.\r\n *\r\n * @return the order (never <code>null</code>).\r\n *\r\n * @see #setSeriesRenderingOrder(SeriesRenderingOrder)\r\n */\r\n public SeriesRenderingOrder getSeriesRenderingOrder() {\r\n return this.seriesRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the series order and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. By default, the plot renders the primary series\r\n * last (so that the primary series appears to be on top).\r\n * You can reverse this if you want to.\r\n *\r\n * @param order the rendering order (<code>null</code> not permitted).\r\n *\r\n * @see #getSeriesRenderingOrder()\r\n */\r\n public void setSeriesRenderingOrder(SeriesRenderingOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.seriesRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified renderer, or <code>-1</code> if the\r\n * renderer is not assigned to this plot.\r\n *\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n *\r\n * @return The renderer index.\r\n */\r\n public int getIndexOf(XYItemRenderer renderer) {\r\n for (Map.Entry<Integer, XYItemRenderer> entry \r\n : this.renderers.entrySet()) {\r\n if (entry.getValue() == renderer) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the renderer for the specified dataset (this is either the\r\n * renderer with the same index as the dataset or, if there isn't a \r\n * renderer with the same index, the default renderer). If the dataset\r\n * does not belong to the plot, this method will return {@code null}.\r\n *\r\n * @param dataset the dataset ({@code null} permitted).\r\n *\r\n * @return The renderer (possibly {@code null}).\r\n */\r\n public XYItemRenderer getRendererForDataset(XYDataset dataset) {\r\n int datasetIndex = indexOf(dataset);\r\n if (datasetIndex < 0) {\r\n return null;\r\n } \r\n XYItemRenderer result = this.renderers.get(datasetIndex);\r\n if (result == null) {\r\n result = getRenderer();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the weight for this plot when it is used as a subplot within a\r\n * combined plot.\r\n *\r\n * @return The weight.\r\n *\r\n * @see #setWeight(int)\r\n */\r\n public int getWeight() {\r\n return this.weight;\r\n }\r\n\r\n /**\r\n * Sets the weight for the plot and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param weight the weight.\r\n *\r\n * @see #getWeight()\r\n */\r\n public void setWeight(int weight) {\r\n this.weight = weight;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the domain gridlines are visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setDomainGridlinesVisible(boolean)\r\n */\r\n public boolean isDomainGridlinesVisible() {\r\n return this.domainGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the domain grid-lines are\r\n * visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isDomainGridlinesVisible()\r\n */\r\n public void setDomainGridlinesVisible(boolean visible) {\r\n if (this.domainGridlinesVisible != visible) {\r\n this.domainGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the domain minor gridlines are visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setDomainMinorGridlinesVisible(boolean)\r\n *\r\n * @since 1.0.12\r\n */\r\n public boolean isDomainMinorGridlinesVisible() {\r\n return this.domainMinorGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the domain minor grid-lines\r\n * are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isDomainMinorGridlinesVisible()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlinesVisible(boolean visible) {\r\n if (this.domainMinorGridlinesVisible != visible) {\r\n this.domainMinorGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the grid-lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlineStroke(Stroke)\r\n */\r\n public Stroke getDomainGridlineStroke() {\r\n return this.domainGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the grid lines plotted against the domain axis, and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>stroke</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainGridlineStroke()\r\n */\r\n public void setDomainGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke for the minor grid-lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainMinorGridlineStroke(Stroke)\r\n *\r\n * @since 1.0.12\r\n */\r\n\r\n public Stroke getDomainMinorGridlineStroke() {\r\n return this.domainMinorGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the minor grid lines plotted against the domain\r\n * axis, and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>stroke</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainMinorGridlineStroke()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainMinorGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the grid lines (if any) plotted against the domain\r\n * axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlinePaint(Paint)\r\n */\r\n public Paint getDomainGridlinePaint() {\r\n return this.domainGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the grid lines plotted against the domain axis, and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>paint</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainGridlinePaint()\r\n */\r\n public void setDomainGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the minor grid lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainMinorGridlinePaint(Paint)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Paint getDomainMinorGridlinePaint() {\r\n return this.domainMinorGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the minor grid lines plotted against the domain axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>paint</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainMinorGridlinePaint()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainMinorGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range axis grid is visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeGridlinesVisible(boolean)\r\n */\r\n public boolean isRangeGridlinesVisible() {\r\n return this.rangeGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the range axis grid lines\r\n * are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeGridlinesVisible()\r\n */\r\n public void setRangeGridlinesVisible(boolean visible) {\r\n if (this.rangeGridlinesVisible != visible) {\r\n this.rangeGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlineStroke(Stroke)\r\n */\r\n public Stroke getRangeGridlineStroke() {\r\n return this.rangeGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the grid lines plotted against the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlineStroke()\r\n */\r\n public void setRangeGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the grid lines (if any) plotted against the range\r\n * axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlinePaint(Paint)\r\n */\r\n public Paint getRangeGridlinePaint() {\r\n return this.rangeGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the grid lines plotted against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlinePaint()\r\n */\r\n public void setRangeGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range axis minor grid is visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeMinorGridlinesVisible(boolean)\r\n *\r\n * @since 1.0.12\r\n */\r\n public boolean isRangeMinorGridlinesVisible() {\r\n return this.rangeMinorGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the range axis minor grid\r\n * lines are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeMinorGridlinesVisible()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlinesVisible(boolean visible) {\r\n if (this.rangeMinorGridlinesVisible != visible) {\r\n this.rangeMinorGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlineStroke(Stroke)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Stroke getRangeMinorGridlineStroke() {\r\n return this.rangeMinorGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the minor grid lines plotted against the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlineStroke()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeMinorGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlinePaint(Paint)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Paint getRangeMinorGridlinePaint() {\r\n return this.rangeMinorGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the minor grid lines plotted against the range axis\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlinePaint()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeMinorGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a zero baseline is\r\n * displayed for the domain axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setDomainZeroBaselineVisible(boolean)\r\n */\r\n public boolean isDomainZeroBaselineVisible() {\r\n return this.domainZeroBaselineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the zero baseline is\r\n * displayed for the domain axis, and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #isDomainZeroBaselineVisible()\r\n */\r\n public void setDomainZeroBaselineVisible(boolean visible) {\r\n this.domainZeroBaselineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used for the zero baseline against the domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setDomainZeroBaselineStroke(Stroke)\r\n */\r\n public Stroke getDomainZeroBaselineStroke() {\r\n return this.domainZeroBaselineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the zero baseline for the domain axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getRangeZeroBaselineStroke()\r\n */\r\n public void setDomainZeroBaselineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainZeroBaselineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the zero baseline (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainZeroBaselinePaint(Paint)\r\n */\r\n public Paint getDomainZeroBaselinePaint() {\r\n return this.domainZeroBaselinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the zero baseline plotted against the domain axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getDomainZeroBaselinePaint()\r\n */\r\n public void setDomainZeroBaselinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainZeroBaselinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a zero baseline is\r\n * displayed for the range axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n */\r\n public boolean isRangeZeroBaselineVisible() {\r\n return this.rangeZeroBaselineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the zero baseline is\r\n * displayed for the range axis, and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isRangeZeroBaselineVisible()\r\n */\r\n public void setRangeZeroBaselineVisible(boolean visible) {\r\n this.rangeZeroBaselineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used for the zero baseline against the range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselineStroke(Stroke)\r\n */\r\n public Stroke getRangeZeroBaselineStroke() {\r\n return this.rangeZeroBaselineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the zero baseline for the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselineStroke()\r\n */\r\n public void setRangeZeroBaselineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeZeroBaselineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the zero baseline (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselinePaint(Paint)\r\n */\r\n public Paint getRangeZeroBaselinePaint() {\r\n return this.rangeZeroBaselinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the zero baseline plotted against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselinePaint()\r\n */\r\n public void setRangeZeroBaselinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeZeroBaselinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the domain tick bands. If this is\r\n * <code>null</code>, no tick bands will be drawn.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setDomainTickBandPaint(Paint)\r\n */\r\n public Paint getDomainTickBandPaint() {\r\n return this.domainTickBandPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the domain tick bands.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getDomainTickBandPaint()\r\n */\r\n public void setDomainTickBandPaint(Paint paint) {\r\n this.domainTickBandPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the range tick bands. If this is\r\n * <code>null</code>, no tick bands will be drawn.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setRangeTickBandPaint(Paint)\r\n */\r\n public Paint getRangeTickBandPaint() {\r\n return this.rangeTickBandPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the range tick bands.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getRangeTickBandPaint()\r\n */\r\n public void setRangeTickBandPaint(Paint paint) {\r\n this.rangeTickBandPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the origin for the quadrants that can be displayed on the plot.\r\n * This defaults to (0, 0).\r\n *\r\n * @return The origin point (never <code>null</code>).\r\n *\r\n * @see #setQuadrantOrigin(Point2D)\r\n */\r\n public Point2D getQuadrantOrigin() {\r\n return this.quadrantOrigin;\r\n }\r\n\r\n /**\r\n * Sets the quadrant origin and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param origin the origin (<code>null</code> not permitted).\r\n *\r\n * @see #getQuadrantOrigin()\r\n */\r\n public void setQuadrantOrigin(Point2D origin) {\r\n ParamChecks.nullNotPermitted(origin, \"origin\");\r\n this.quadrantOrigin = origin;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the specified quadrant.\r\n *\r\n * @param index the quadrant index (0-3).\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setQuadrantPaint(int, Paint)\r\n */\r\n public Paint getQuadrantPaint(int index) {\r\n if (index < 0 || index > 3) {\r\n throw new IllegalArgumentException(\"The index value (\" + index\r\n + \") should be in the range 0 to 3.\");\r\n }\r\n return this.quadrantPaint[index];\r\n }\r\n\r\n /**\r\n * Sets the paint used for the specified quadrant and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the quadrant index (0-3).\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getQuadrantPaint(int)\r\n */\r\n public void setQuadrantPaint(int index, Paint paint) {\r\n if (index < 0 || index > 3) {\r\n throw new IllegalArgumentException(\"The index value (\" + index\r\n + \") should be in the range 0 to 3.\");\r\n }\r\n this.quadrantPaint[index] = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #addDomainMarker(Marker, Layer)\r\n * @see #clearDomainMarkers()\r\n */\r\n public void addDomainMarker(Marker marker) {\r\n // defer argument checking...\r\n addDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for the domain axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void addDomainMarker(Marker marker, Layer layer) {\r\n addDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Clears all the (foreground and background) domain markers and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void clearDomainMarkers() {\r\n if (this.backgroundDomainMarkers != null) {\r\n Set<Integer> keys = this.backgroundDomainMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearDomainMarkers(key);\r\n }\r\n this.backgroundDomainMarkers.clear();\r\n }\r\n if (this.foregroundDomainMarkers != null) {\r\n Set<Integer> keys = this.foregroundDomainMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearDomainMarkers(key);\r\n }\r\n this.foregroundDomainMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Clears the (foreground and background) domain markers for a particular\r\n * renderer and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the renderer index.\r\n *\r\n * @see #clearRangeMarkers(int)\r\n */\r\n public void clearDomainMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundDomainMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis (that the renderer is mapped to), however this is\r\n * entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #clearDomainMarkers(int)\r\n * @see #addRangeMarker(int, Marker, Layer)\r\n */\r\n public void addDomainMarker(int index, Marker marker, Layer layer) {\r\n addDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis (that the renderer is mapped to), however this is\r\n * entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addDomainMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ParamChecks.nullNotPermitted(layer, \"layer\");\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker) {\r\n return removeDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker, Layer layer) {\r\n return removeDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer) {\r\n return removeDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and, if requested,\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ArrayList markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (ArrayList) this.foregroundDomainMarkers.get(\r\n new Integer(index));\r\n }\r\n else {\r\n markers = (ArrayList) this.backgroundDomainMarkers.get(\r\n new Integer(index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Adds a marker for the range axis and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #addRangeMarker(Marker, Layer)\r\n */\r\n public void addRangeMarker(Marker marker) {\r\n addRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for the range axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #addRangeMarker(int, Marker, Layer)\r\n */\r\n public void addRangeMarker(Marker marker, Layer layer) {\r\n addRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Clears all the range markers and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @see #clearRangeMarkers()\r\n */\r\n public void clearRangeMarkers() {\r\n if (this.backgroundRangeMarkers != null) {\r\n Set<Integer> keys = this.backgroundRangeMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearRangeMarkers(key);\r\n }\r\n this.backgroundRangeMarkers.clear();\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Set<Integer> keys = this.foregroundRangeMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearRangeMarkers(key);\r\n }\r\n this.foregroundRangeMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #clearRangeMarkers(int)\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer) {\r\n addRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Clears the (foreground and background) range markers for a particular\r\n * renderer.\r\n *\r\n * @param index the renderer index.\r\n */\r\n public void clearRangeMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(Marker marker) {\r\n return removeRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(Marker marker, Layer layer) {\r\n return removeRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer) {\r\n return removeRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background) (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ParamChecks.nullNotPermitted(layer, \"layer\");\r\n List markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (List) this.foregroundRangeMarkers.get(\r\n new Integer(index));\r\n }\r\n else {\r\n markers = (List) this.backgroundRangeMarkers.get(\r\n new Integer(index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @see #getAnnotations()\r\n * @see #removeAnnotation(XYAnnotation)\r\n */\r\n public void addAnnotation(XYAnnotation annotation) {\r\n addAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addAnnotation(XYAnnotation annotation, boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n this.annotations.add(annotation);\r\n annotation.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n * @see #getAnnotations()\r\n */\r\n public boolean removeAnnotation(XYAnnotation annotation) {\r\n return removeAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeAnnotation(XYAnnotation annotation, boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n boolean removed = this.annotations.remove(annotation);\r\n annotation.removeChangeListener(this);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Returns the list of annotations.\r\n *\r\n * @return The list of annotations.\r\n *\r\n * @since 1.0.1\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n */\r\n public List getAnnotations() {\r\n return new ArrayList(this.annotations);\r\n }\r\n\r\n /**\r\n * Clears all the annotations and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n */\r\n public void clearAnnotations() {\r\n for (XYAnnotation annotation : this.annotations) {\r\n annotation.removeChangeListener(this);\r\n }\r\n this.annotations.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the shadow generator for the plot, if any.\r\n *\r\n * @return The shadow generator (possibly <code>null</code>).\r\n *\r\n * @since 1.0.14\r\n */\r\n public ShadowGenerator getShadowGenerator() {\r\n return this.shadowGenerator;\r\n }\r\n\r\n /**\r\n * Sets the shadow generator for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setShadowGenerator(ShadowGenerator generator) {\r\n this.shadowGenerator = generator;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Calculates the space required for all the axes in the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateAxisSpace(Graphics2D g2,\r\n Rectangle2D plotArea) {\r\n AxisSpace space = new AxisSpace();\r\n space = calculateRangeAxisSpace(g2, plotArea, space);\r\n Rectangle2D revPlotArea = space.shrink(plotArea, null);\r\n space = calculateDomainAxisSpace(g2, revPlotArea, space);\r\n return space;\r\n }\r\n\r\n /**\r\n * Calculates the space required for the domain axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateDomainAxisSpace(Graphics2D g2, \r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the domain axis...\r\n if (this.fixedDomainAxisSpace != null) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getLeft(),\r\n RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n }\r\n else if (this.orientation == PlotOrientation.VERTICAL) {\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n }\r\n }\r\n else {\r\n // reserve space for the domain axes...\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n RectangleEdge edge = getDomainAxisEdge(\r\n findDomainAxisIndex(axis));\r\n space = axis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the space required for the range axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateRangeAxisSpace(Graphics2D g2, \r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the range axis...\r\n if (this.fixedRangeAxisSpace != null) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n }\r\n else if (this.orientation == PlotOrientation.VERTICAL) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getLeft(),\r\n RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n }\r\n }\r\n else {\r\n // reserve space for the range axes...\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n RectangleEdge edge = getRangeAxisEdge(\r\n findRangeAxisIndex(axis));\r\n space = axis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Trims a rectangle to integer coordinates.\r\n *\r\n * @param rect the incoming rectangle.\r\n *\r\n * @return A rectangle with integer coordinates.\r\n */\r\n private Rectangle integerise(Rectangle2D rect) {\r\n int x0 = (int) Math.ceil(rect.getMinX());\r\n int y0 = (int) Math.ceil(rect.getMinY());\r\n int x1 = (int) Math.floor(rect.getMaxX());\r\n int y1 = (int) Math.floor(rect.getMaxY());\r\n return new Rectangle(x0, y0, (x1 - x0), (y1 - y0));\r\n }\r\n\r\n /**\r\n * Draws the plot within the specified area on a graphics device.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the plot area (in Java2D space).\r\n * @param anchor an anchor point in Java2D space (<code>null</code>\r\n * permitted).\r\n * @param parentState the state from the parent plot, if there is one\r\n * (<code>null</code> permitted).\r\n * @param info collects chart drawing information (<code>null</code>\r\n * permitted).\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor,\r\n PlotState parentState, PlotRenderingInfo info) {\r\n\r\n // if the plot area is too small, just return...\r\n boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW);\r\n boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW);\r\n if (b1 || b2) {\r\n return;\r\n }\r\n\r\n // record the plot area...\r\n if (info != null) {\r\n info.setPlotArea(area);\r\n }\r\n\r\n // adjust the drawing area for the plot insets (if any)...\r\n RectangleInsets insets = getInsets();\r\n insets.trim(area);\r\n\r\n AxisSpace space = calculateAxisSpace(g2, area);\r\n Rectangle2D dataArea = space.shrink(area, null);\r\n this.axisOffset.trim(dataArea);\r\n\r\n dataArea = integerise(dataArea);\r\n if (dataArea.isEmpty()) {\r\n return;\r\n }\r\n createAndAddEntity((Rectangle2D) dataArea.clone(), info, null, null);\r\n if (info != null) {\r\n info.setDataArea(dataArea);\r\n }\r\n\r\n // draw the plot background and axes...\r\n drawBackground(g2, dataArea);\r\n Map axisStateMap = drawAxes(g2, area, dataArea, info);\r\n\r\n PlotOrientation orient = getOrientation();\r\n\r\n // the anchor point is typically the point where the mouse last\r\n // clicked - the crosshairs will be driven off this point...\r\n if (anchor != null && !dataArea.contains(anchor)) {\r\n anchor = null;\r\n }\r\n CrosshairState crosshairState = new CrosshairState();\r\n crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY);\r\n crosshairState.setAnchor(anchor);\r\n\r\n crosshairState.setAnchorX(Double.NaN);\r\n crosshairState.setAnchorY(Double.NaN);\r\n if (anchor != null) {\r\n ValueAxis domainAxis = getDomainAxis();\r\n if (domainAxis != null) {\r\n double x;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n x = domainAxis.java2DToValue(anchor.getX(), dataArea,\r\n getDomainAxisEdge());\r\n }\r\n else {\r\n x = domainAxis.java2DToValue(anchor.getY(), dataArea,\r\n getDomainAxisEdge());\r\n }\r\n crosshairState.setAnchorX(x);\r\n }\r\n ValueAxis rangeAxis = getRangeAxis();\r\n if (rangeAxis != null) {\r\n double y;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n y = rangeAxis.java2DToValue(anchor.getY(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n else {\r\n y = rangeAxis.java2DToValue(anchor.getX(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n crosshairState.setAnchorY(y);\r\n }\r\n }\r\n crosshairState.setCrosshairX(getDomainCrosshairValue());\r\n crosshairState.setCrosshairY(getRangeCrosshairValue());\r\n Shape originalClip = g2.getClip();\r\n Composite originalComposite = g2.getComposite();\r\n\r\n g2.clip(dataArea);\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n getForegroundAlpha()));\r\n\r\n AxisState domainAxisState = (AxisState) axisStateMap.get(\r\n getDomainAxis());\r\n if (domainAxisState == null) {\r\n if (parentState != null) {\r\n domainAxisState = (AxisState) parentState.getSharedAxisStates()\r\n .get(getDomainAxis());\r\n }\r\n }\r\n\r\n AxisState rangeAxisState = (AxisState) axisStateMap.get(getRangeAxis());\r\n if (rangeAxisState == null) {\r\n if (parentState != null) {\r\n rangeAxisState = (AxisState) parentState.getSharedAxisStates()\r\n .get(getRangeAxis());\r\n }\r\n }\r\n if (domainAxisState != null) {\r\n drawDomainTickBands(g2, dataArea, domainAxisState.getTicks());\r\n }\r\n if (rangeAxisState != null) {\r\n drawRangeTickBands(g2, dataArea, rangeAxisState.getTicks());\r\n }\r\n if (domainAxisState != null) {\r\n drawDomainGridlines(g2, dataArea, domainAxisState.getTicks());\r\n drawZeroDomainBaseline(g2, dataArea);\r\n }\r\n if (rangeAxisState != null) {\r\n drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks());\r\n drawZeroRangeBaseline(g2, dataArea);\r\n }\r\n\r\n Graphics2D savedG2 = g2;\r\n BufferedImage dataImage = null;\r\n boolean suppressShadow = Boolean.TRUE.equals(g2.getRenderingHint(\r\n JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION));\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n dataImage = new BufferedImage((int) dataArea.getWidth(),\r\n (int)dataArea.getHeight(), BufferedImage.TYPE_INT_ARGB);\r\n g2 = dataImage.createGraphics();\r\n g2.translate(-dataArea.getX(), -dataArea.getY());\r\n g2.setRenderingHints(savedG2.getRenderingHints());\r\n }\r\n\r\n // draw the markers that are associated with a specific dataset...\r\n for (XYDataset dataset: this.datasets.values()) {\r\n int datasetIndex = indexOf(dataset);\r\n drawDomainMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND);\r\n }\r\n for (XYDataset dataset: this.datasets.values()) {\r\n int datasetIndex = indexOf(dataset);\r\n drawRangeMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND);\r\n }\r\n\r\n // now draw annotations and render data items...\r\n boolean foundData = false;\r\n DatasetRenderingOrder order = getDatasetRenderingOrder();\r\n List<Integer> rendererIndices = getRendererIndices(order);\r\n List<Integer> datasetIndices = getDatasetIndices(order);\r\n // draw background annotations\r\n for (int i : rendererIndices) {\r\n XYItemRenderer renderer = getRenderer(i);\r\n if (renderer != null) {\r\n ValueAxis domainAxis = getDomainAxisForDataset(i);\r\n ValueAxis rangeAxis = getRangeAxisForDataset(i);\r\n renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, \r\n Layer.BACKGROUND, info);\r\n }\r\n }\r\n\r\n // render data items...\r\n for (int datasetIndex : datasetIndices) {\r\n XYDataset dataset = this.getDataset(datasetIndex);\r\n foundData = render(g2, dataArea, datasetIndex, info, \r\n crosshairState) || foundData;\r\n }\r\n\r\n // draw foreground annotations\r\n for (int i : rendererIndices) {\r\n XYItemRenderer renderer = getRenderer(i);\r\n if (renderer != null) {\r\n ValueAxis domainAxis = getDomainAxisForDataset(i);\r\n ValueAxis rangeAxis = getRangeAxisForDataset(i);\r\n renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, \r\n Layer.FOREGROUND, info);\r\n }\r\n }\r\n\r\n // draw domain crosshair if required...\r\n int datasetIndex = crosshairState.getDatasetIndex();\r\n ValueAxis xAxis = this.getDomainAxisForDataset(datasetIndex);\r\n RectangleEdge xAxisEdge = getDomainAxisEdge(getDomainAxisIndex(xAxis));\r\n if (!this.domainCrosshairLockedOnData && anchor != null) {\r\n double xx;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n xx = xAxis.java2DToValue(anchor.getX(), dataArea, xAxisEdge);\r\n }\r\n else {\r\n xx = xAxis.java2DToValue(anchor.getY(), dataArea, xAxisEdge);\r\n }\r\n crosshairState.setCrosshairX(xx);\r\n }\r\n setDomainCrosshairValue(crosshairState.getCrosshairX(), false);\r\n if (isDomainCrosshairVisible()) {\r\n double x = getDomainCrosshairValue();\r\n Paint paint = getDomainCrosshairPaint();\r\n Stroke stroke = getDomainCrosshairStroke();\r\n drawDomainCrosshair(g2, dataArea, orient, x, xAxis, stroke, paint);\r\n }\r\n\r\n // draw range crosshair if required...\r\n ValueAxis yAxis = getRangeAxisForDataset(datasetIndex);\r\n RectangleEdge yAxisEdge = getRangeAxisEdge(getRangeAxisIndex(yAxis));\r\n if (!this.rangeCrosshairLockedOnData && anchor != null) {\r\n double yy;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n yy = yAxis.java2DToValue(anchor.getY(), dataArea, yAxisEdge);\r\n } else {\r\n yy = yAxis.java2DToValue(anchor.getX(), dataArea, yAxisEdge);\r\n }\r\n crosshairState.setCrosshairY(yy);\r\n }\r\n setRangeCrosshairValue(crosshairState.getCrosshairY(), false);\r\n if (isRangeCrosshairVisible()) {\r\n double y = getRangeCrosshairValue();\r\n Paint paint = getRangeCrosshairPaint();\r\n Stroke stroke = getRangeCrosshairStroke();\r\n drawRangeCrosshair(g2, dataArea, orient, y, yAxis, stroke, paint);\r\n }\r\n\r\n if (!foundData) {\r\n drawNoDataMessage(g2, dataArea);\r\n }\r\n\r\n for (int i : rendererIndices) { \r\n drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n for (int i : rendererIndices) {\r\n drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n\r\n drawAnnotations(g2, dataArea, info);\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n BufferedImage shadowImage\r\n = this.shadowGenerator.createDropShadow(dataImage);\r\n g2 = savedG2;\r\n g2.drawImage(shadowImage, (int) dataArea.getX()\r\n + this.shadowGenerator.calculateOffsetX(),\r\n (int) dataArea.getY()\r\n + this.shadowGenerator.calculateOffsetY(), null);\r\n g2.drawImage(dataImage, (int) dataArea.getX(),\r\n (int) dataArea.getY(), null);\r\n }\r\n g2.setClip(originalClip);\r\n g2.setComposite(originalComposite);\r\n\r\n drawOutline(g2, dataArea);\r\n\r\n }\r\n\r\n /**\r\n * Returns the indices of the non-null datasets in the specified order.\r\n * \r\n * @param order the order (<code>null</code> not permitted).\r\n * \r\n * @return The list of indices. \r\n */\r\n private List<Integer> getDatasetIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result;\r\n }\r\n \r\n private List<Integer> getRendererIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Entry<Integer, XYItemRenderer> entry : this.renderers.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result; \r\n }\r\n \r\n /**\r\n * Draws the background for the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n */\r\n @Override\r\n public void drawBackground(Graphics2D g2, Rectangle2D area) {\r\n fillBackground(g2, area, this.orientation);\r\n drawQuadrants(g2, area);\r\n drawBackgroundImage(g2, area);\r\n }\r\n\r\n /**\r\n * Draws the quadrants.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n *\r\n * @see #setQuadrantOrigin(Point2D)\r\n * @see #setQuadrantPaint(int, Paint)\r\n */\r\n protected void drawQuadrants(Graphics2D g2, Rectangle2D area) {\r\n // 0 | 1\r\n // --+--\r\n // 2 | 3\r\n boolean somethingToDraw = false;\r\n\r\n ValueAxis xAxis = getDomainAxis();\r\n if (xAxis == null) { // we can't draw quadrants without a valid x-axis\r\n return;\r\n }\r\n double x = xAxis.getRange().constrain(this.quadrantOrigin.getX());\r\n double xx = xAxis.valueToJava2D(x, area, getDomainAxisEdge());\r\n\r\n ValueAxis yAxis = getRangeAxis();\r\n if (yAxis == null) { // we can't draw quadrants without a valid y-axis\r\n return;\r\n }\r\n double y = yAxis.getRange().constrain(this.quadrantOrigin.getY());\r\n double yy = yAxis.valueToJava2D(y, area, getRangeAxisEdge());\r\n\r\n double xmin = xAxis.getLowerBound();\r\n double xxmin = xAxis.valueToJava2D(xmin, area, getDomainAxisEdge());\r\n\r\n double xmax = xAxis.getUpperBound();\r\n double xxmax = xAxis.valueToJava2D(xmax, area, getDomainAxisEdge());\r\n\r\n double ymin = yAxis.getLowerBound();\r\n double yymin = yAxis.valueToJava2D(ymin, area, getRangeAxisEdge());\r\n\r\n double ymax = yAxis.getUpperBound();\r\n double yymax = yAxis.valueToJava2D(ymax, area, getRangeAxisEdge());\r\n\r\n Rectangle2D[] r = new Rectangle2D[] {null, null, null, null};\r\n if (this.quadrantPaint[0] != null) {\r\n if (x > xmin && y < ymax) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[0] = new Rectangle2D.Double(Math.min(yymax, yy),\r\n Math.min(xxmin, xx), Math.abs(yy - yymax),\r\n Math.abs(xx - xxmin));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[0] = new Rectangle2D.Double(Math.min(xxmin, xx),\r\n Math.min(yymax, yy), Math.abs(xx - xxmin),\r\n Math.abs(yy - yymax));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[1] != null) {\r\n if (x < xmax && y < ymax) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[1] = new Rectangle2D.Double(Math.min(yymax, yy),\r\n Math.min(xxmax, xx), Math.abs(yy - yymax),\r\n Math.abs(xx - xxmax));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[1] = new Rectangle2D.Double(Math.min(xx, xxmax),\r\n Math.min(yymax, yy), Math.abs(xx - xxmax),\r\n Math.abs(yy - yymax));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[2] != null) {\r\n if (x > xmin && y > ymin) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[2] = new Rectangle2D.Double(Math.min(yymin, yy),\r\n Math.min(xxmin, xx), Math.abs(yy - yymin),\r\n Math.abs(xx - xxmin));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[2] = new Rectangle2D.Double(Math.min(xxmin, xx),\r\n Math.min(yymin, yy), Math.abs(xx - xxmin),\r\n Math.abs(yy - yymin));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[3] != null) {\r\n if (x < xmax && y > ymin) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[3] = new Rectangle2D.Double(Math.min(yymin, yy),\r\n Math.min(xxmax, xx), Math.abs(yy - yymin),\r\n Math.abs(xx - xxmax));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[3] = new Rectangle2D.Double(Math.min(xx, xxmax),\r\n Math.min(yymin, yy), Math.abs(xx - xxmax),\r\n Math.abs(yy - yymin));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (somethingToDraw) {\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n getBackgroundAlpha()));\r\n for (int i = 0; i < 4; i++) {\r\n if (this.quadrantPaint[i] != null && r[i] != null) {\r\n g2.setPaint(this.quadrantPaint[i]);\r\n g2.fill(r[i]);\r\n }\r\n }\r\n g2.setComposite(originalComposite);\r\n }\r\n }\r\n\r\n /**\r\n * Draws the domain tick bands, if any.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #setDomainTickBandPaint(Paint)\r\n */\r\n public void drawDomainTickBands(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n Paint bandPaint = getDomainTickBandPaint();\r\n if (bandPaint != null) {\r\n boolean fillBand = false;\r\n ValueAxis xAxis = getDomainAxis();\r\n double previous = xAxis.getLowerBound();\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n double current = tick.getValue();\r\n if (fillBand) {\r\n getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea,\r\n previous, current);\r\n }\r\n previous = current;\r\n fillBand = !fillBand;\r\n }\r\n double end = xAxis.getUpperBound();\r\n if (fillBand) {\r\n getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea,\r\n previous, end);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws the range tick bands, if any.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #setRangeTickBandPaint(Paint)\r\n */\r\n public void drawRangeTickBands(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n Paint bandPaint = getRangeTickBandPaint();\r\n if (bandPaint != null) {\r\n boolean fillBand = false;\r\n ValueAxis axis = getRangeAxis();\r\n double previous = axis.getLowerBound();\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n double current = tick.getValue();\r\n if (fillBand) {\r\n getRenderer().fillRangeGridBand(g2, this, axis, dataArea,\r\n previous, current);\r\n }\r\n previous = current;\r\n fillBand = !fillBand;\r\n }\r\n double end = axis.getUpperBound();\r\n if (fillBand) {\r\n getRenderer().fillRangeGridBand(g2, this, axis, dataArea,\r\n previous, end);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * A utility method for drawing the axes.\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param plotArea the plot area (<code>null</code> not permitted).\r\n * @param dataArea the data area (<code>null</code> not permitted).\r\n * @param plotState collects information about the plot (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A map containing the state for each axis drawn.\r\n */\r\n protected Map<Axis, AxisState> drawAxes(Graphics2D g2, Rectangle2D plotArea,\r\n Rectangle2D dataArea, PlotRenderingInfo plotState) {\r\n\r\n AxisCollection axisCollection = new AxisCollection();\r\n\r\n // add domain axes to lists...\r\n for (ValueAxis axis : this.domainAxes.values()) {\r\n if (axis != null) {\r\n int axisIndex = findDomainAxisIndex(axis);\r\n axisCollection.add(axis, getDomainAxisEdge(axisIndex));\r\n }\r\n }\r\n\r\n // add range axes to lists...\r\n for (ValueAxis axis : this.rangeAxes.values()) {\r\n if (axis != null) {\r\n int axisIndex = findRangeAxisIndex(axis);\r\n axisCollection.add(axis, getRangeAxisEdge(axisIndex));\r\n }\r\n }\r\n\r\n Map axisStateMap = new HashMap();\r\n\r\n // draw the top axes\r\n double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset(\r\n dataArea.getHeight());\r\n Iterator iterator = axisCollection.getAxesAtTop().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.TOP, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the bottom axes\r\n cursor = dataArea.getMaxY()\r\n + this.axisOffset.calculateBottomOutset(dataArea.getHeight());\r\n iterator = axisCollection.getAxesAtBottom().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.BOTTOM, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the left axes\r\n cursor = dataArea.getMinX()\r\n - this.axisOffset.calculateLeftOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtLeft().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.LEFT, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the right axes\r\n cursor = dataArea.getMaxX()\r\n + this.axisOffset.calculateRightOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtRight().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.RIGHT, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n return axisStateMap;\r\n }\r\n\r\n /**\r\n * Draws a representation of the data within the dataArea region, using the\r\n * current renderer.\r\n * <P>\r\n * The <code>info</code> and <code>crosshairState</code> arguments may be\r\n * <code>null</code>.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the region in which the data is to be drawn.\r\n * @param index the dataset index.\r\n * @param info an optional object for collection dimension information.\r\n * @param crosshairState collects crosshair information\r\n * (<code>null</code> permitted).\r\n *\r\n * @return A flag that indicates whether any data was actually rendered.\r\n */\r\n public boolean render(Graphics2D g2, Rectangle2D dataArea, int index,\r\n PlotRenderingInfo info, CrosshairState crosshairState) {\r\n\r\n boolean foundData = false;\r\n XYDataset dataset = getDataset(index);\r\n if (!DatasetUtilities.isEmptyOrNull(dataset)) {\r\n foundData = true;\r\n ValueAxis xAxis = getDomainAxisForDataset(index);\r\n ValueAxis yAxis = getRangeAxisForDataset(index);\r\n if (xAxis == null || yAxis == null) {\r\n return foundData; // can't render anything without axes\r\n }\r\n XYItemRenderer renderer = getRenderer(index);\r\n if (renderer == null) {\r\n renderer = getRenderer();\r\n if (renderer == null) { // no default renderer available\r\n return foundData;\r\n }\r\n }\r\n\r\n XYItemRendererState state = renderer.initialise(g2, dataArea, this,\r\n dataset, info);\r\n int passCount = renderer.getPassCount();\r\n\r\n SeriesRenderingOrder seriesOrder = getSeriesRenderingOrder();\r\n if (seriesOrder == SeriesRenderingOrder.REVERSE) {\r\n //render series in reverse order\r\n for (int pass = 0; pass < passCount; pass++) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = seriesCount - 1; series >= 0; series--) {\r\n int firstItem = 0;\r\n int lastItem = dataset.getItemCount(series) - 1;\r\n if (lastItem == -1) {\r\n continue;\r\n }\r\n if (state.getProcessVisibleItemsOnly()) {\r\n int[] itemBounds = RendererUtilities.findLiveItems(\r\n dataset, series, xAxis.getLowerBound(),\r\n xAxis.getUpperBound());\r\n firstItem = Math.max(itemBounds[0] - 1, 0);\r\n lastItem = Math.min(itemBounds[1] + 1, lastItem);\r\n }\r\n state.startSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n for (int item = firstItem; item <= lastItem; item++) {\r\n renderer.drawItem(g2, state, dataArea, info,\r\n this, xAxis, yAxis, dataset, series, item,\r\n crosshairState, pass);\r\n }\r\n state.endSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n }\r\n }\r\n }\r\n else {\r\n //render series in forward order\r\n for (int pass = 0; pass < passCount; pass++) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n int firstItem = 0;\r\n int lastItem = dataset.getItemCount(series) - 1;\r\n if (state.getProcessVisibleItemsOnly()) {\r\n int[] itemBounds = RendererUtilities.findLiveItems(\r\n dataset, series, xAxis.getLowerBound(),\r\n xAxis.getUpperBound());\r\n firstItem = Math.max(itemBounds[0] - 1, 0);\r\n lastItem = Math.min(itemBounds[1] + 1, lastItem);\r\n }\r\n state.startSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n for (int item = firstItem; item <= lastItem; item++) {\r\n renderer.drawItem(g2, state, dataArea, info,\r\n this, xAxis, yAxis, dataset, series, item,\r\n crosshairState, pass);\r\n }\r\n state.endSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n }\r\n }\r\n }\r\n }\r\n return foundData;\r\n }\r\n\r\n /**\r\n * Returns the domain axis for a dataset.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The axis.\r\n */\r\n public ValueAxis getDomainAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n ValueAxis valueAxis;\r\n List axisIndices = (List) this.datasetToDomainAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n valueAxis = getDomainAxis(axisIndex.intValue());\r\n }\r\n else {\r\n valueAxis = getDomainAxis(0);\r\n }\r\n return valueAxis;\r\n }\r\n\r\n /**\r\n * Returns the range axis for a dataset.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The axis.\r\n */\r\n public ValueAxis getRangeAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n ValueAxis valueAxis;\r\n List axisIndices = (List) this.datasetToRangeAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n valueAxis = getRangeAxis(axisIndex.intValue());\r\n }\r\n else {\r\n valueAxis = getRangeAxis(0);\r\n }\r\n return valueAxis;\r\n }\r\n\r\n /**\r\n * Draws the gridlines for the plot, if they are visible.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #drawRangeGridlines(Graphics2D, Rectangle2D, List)\r\n */\r\n protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n\r\n // no renderer, no gridlines...\r\n if (getRenderer() == null) {\r\n return;\r\n }\r\n\r\n // draw the domain grid lines, if any...\r\n if (isDomainGridlinesVisible() || isDomainMinorGridlinesVisible()) {\r\n Stroke gridStroke = null;\r\n Paint gridPaint = null;\r\n Iterator iterator = ticks.iterator();\r\n boolean paintLine;\r\n while (iterator.hasNext()) {\r\n paintLine = false;\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if ((tick.getTickType() == TickType.MINOR)\r\n && isDomainMinorGridlinesVisible()) {\r\n gridStroke = getDomainMinorGridlineStroke();\r\n gridPaint = getDomainMinorGridlinePaint();\r\n paintLine = true;\r\n } else if ((tick.getTickType() == TickType.MAJOR)\r\n && isDomainGridlinesVisible()) {\r\n gridStroke = getDomainGridlineStroke();\r\n gridPaint = getDomainGridlinePaint();\r\n paintLine = true;\r\n }\r\n XYItemRenderer r = getRenderer();\r\n if ((r instanceof AbstractXYItemRenderer) && paintLine) {\r\n ((AbstractXYItemRenderer) r).drawDomainLine(g2, this,\r\n getDomainAxis(), dataArea, tick.getValue(),\r\n gridPaint, gridStroke);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws the gridlines for the plot's primary range axis, if they are\r\n * visible.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #drawDomainGridlines(Graphics2D, Rectangle2D, List)\r\n */\r\n protected void drawRangeGridlines(Graphics2D g2, Rectangle2D area,\r\n List ticks) {\r\n\r\n // no renderer, no gridlines...\r\n if (getRenderer() == null) {\r\n return;\r\n }\r\n\r\n // draw the range grid lines, if any...\r\n if (isRangeGridlinesVisible() || isRangeMinorGridlinesVisible()) {\r\n Stroke gridStroke = null;\r\n Paint gridPaint = null;\r\n ValueAxis axis = getRangeAxis();\r\n if (axis != null) {\r\n Iterator iterator = ticks.iterator();\r\n boolean paintLine;\r\n while (iterator.hasNext()) {\r\n paintLine = false;\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if ((tick.getTickType() == TickType.MINOR)\r\n && isRangeMinorGridlinesVisible()) {\r\n gridStroke = getRangeMinorGridlineStroke();\r\n gridPaint = getRangeMinorGridlinePaint();\r\n paintLine = true;\r\n } else if ((tick.getTickType() == TickType.MAJOR)\r\n && isRangeGridlinesVisible()) {\r\n gridStroke = getRangeGridlineStroke();\r\n gridPaint = getRangeGridlinePaint();\r\n paintLine = true;\r\n }\r\n if ((tick.getValue() != 0.0\r\n || !isRangeZeroBaselineVisible()) && paintLine) {\r\n getRenderer().drawRangeLine(g2, this, getRangeAxis(),\r\n area, tick.getValue(), gridPaint, gridStroke);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws a base line across the chart at value zero on the domain axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n *\r\n * @see #setDomainZeroBaselineVisible(boolean)\r\n *\r\n * @since 1.0.5\r\n */\r\n protected void drawZeroDomainBaseline(Graphics2D g2, Rectangle2D area) {\r\n if (isDomainZeroBaselineVisible()) {\r\n XYItemRenderer r = getRenderer();\r\n // FIXME: the renderer interface doesn't have the drawDomainLine()\r\n // method, so we have to rely on the renderer being a subclass of\r\n // AbstractXYItemRenderer (which is lame)\r\n if (r instanceof AbstractXYItemRenderer) {\r\n AbstractXYItemRenderer renderer = (AbstractXYItemRenderer) r;\r\n renderer.drawDomainLine(g2, this, getDomainAxis(), area, 0.0,\r\n this.domainZeroBaselinePaint,\r\n this.domainZeroBaselineStroke);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws a base line across the chart at value zero on the range axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n */\r\n protected void drawZeroRangeBaseline(Graphics2D g2, Rectangle2D area) {\r\n if (isRangeZeroBaselineVisible()) {\r\n getRenderer().drawRangeLine(g2, this, getRangeAxis(), area, 0.0,\r\n this.rangeZeroBaselinePaint, this.rangeZeroBaselineStroke);\r\n }\r\n }\r\n\r\n /**\r\n * Draws the annotations for the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param info the chart rendering info.\r\n */\r\n public void drawAnnotations(Graphics2D g2, Rectangle2D dataArea,\r\n PlotRenderingInfo info) {\r\n\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n ValueAxis xAxis = getDomainAxis();\r\n ValueAxis yAxis = getRangeAxis();\r\n annotation.draw(g2, this, dataArea, xAxis, yAxis, 0, info);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the domain markers (if any) for an axis and layer. This method is\r\n * typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the dataset/renderer index.\r\n * @param layer the layer (foreground or background).\r\n */\r\n protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n XYItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n // check that the renderer has a corresponding dataset (it doesn't\r\n // matter if the dataset is null)\r\n if (index >= getDatasetCount()) {\r\n return;\r\n }\r\n Collection markers = getDomainMarkers(index, layer);\r\n ValueAxis axis = getDomainAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker marker = (Marker) iterator.next();\r\n r.drawDomainMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the range markers (if any) for a renderer and layer. This method\r\n * is typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the renderer index.\r\n * @param layer the layer (foreground or background).\r\n */\r\n protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n XYItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n // check that the renderer has a corresponding dataset (it doesn't\r\n // matter if the dataset is null)\r\n if (index >= getDatasetCount()) {\r\n return;\r\n }\r\n Collection markers = getRangeMarkers(index, layer);\r\n ValueAxis axis = getRangeAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker marker = (Marker) iterator.next();\r\n r.drawRangeMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the list of domain markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of domain markers.\r\n *\r\n * @see #getRangeMarkers(Layer)\r\n */\r\n public Collection getDomainMarkers(Layer layer) {\r\n return getDomainMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns the list of range markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of range markers.\r\n *\r\n * @see #getDomainMarkers(Layer)\r\n */\r\n public Collection getRangeMarkers(Layer layer) {\r\n return getRangeMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns a collection of domain markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n *\r\n * @see #getRangeMarkers(int, Layer)\r\n */\r\n public Collection getDomainMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundDomainMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundDomainMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a collection of range markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n *\r\n * @see #getDomainMarkers(int, Layer)\r\n */\r\n public Collection getRangeMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundRangeMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundRangeMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Utility method for drawing a horizontal line across the data area of the\r\n * plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param value the coordinate, where to draw the line.\r\n * @param stroke the stroke to use.\r\n * @param paint the paint to use.\r\n */\r\n protected void drawHorizontalLine(Graphics2D g2, Rectangle2D dataArea,\r\n double value, Stroke stroke,\r\n Paint paint) {\r\n\r\n ValueAxis axis = getRangeAxis();\r\n if (getOrientation() == PlotOrientation.HORIZONTAL) {\r\n axis = getDomainAxis();\r\n }\r\n if (axis.getRange().contains(value)) {\r\n double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT);\r\n Line2D line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws a domain crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param value the crosshair value.\r\n * @param axis the axis against which the value is measured.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @since 1.0.4\r\n */\r\n protected void drawDomainCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, double value, ValueAxis axis,\r\n Stroke stroke, Paint paint) {\r\n\r\n if (!axis.getRange().contains(value)) {\r\n return;\r\n }\r\n Line2D line;\r\n if (orientation == PlotOrientation.VERTICAL) {\r\n double xx = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n } else {\r\n double yy = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n\r\n /**\r\n * Utility method for drawing a vertical line on the data area of the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param value the coordinate, where to draw the line.\r\n * @param stroke the stroke to use.\r\n * @param paint the paint to use.\r\n */\r\n protected void drawVerticalLine(Graphics2D g2, Rectangle2D dataArea,\r\n double value, Stroke stroke, Paint paint) {\r\n\r\n ValueAxis axis = getDomainAxis();\r\n if (getOrientation() == PlotOrientation.HORIZONTAL) {\r\n axis = getRangeAxis();\r\n }\r\n if (axis.getRange().contains(value)) {\r\n double xx = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.BOTTOM);\r\n Line2D line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws a range crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param value the crosshair value.\r\n * @param axis the axis against which the value is measured.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @since 1.0.4\r\n */\r\n protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, double value, ValueAxis axis,\r\n Stroke stroke, Paint paint) {\r\n\r\n if (!axis.getRange().contains(value)) {\r\n return;\r\n }\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n Line2D line;\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n double xx = axis.valueToJava2D(value, dataArea, \r\n RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n } else {\r\n double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the plot by updating the anchor values.\r\n *\r\n * @param x the x-coordinate, where the click occurred, in Java2D space.\r\n * @param y the y-coordinate, where the click occurred, in Java2D space.\r\n * @param info object containing information about the plot dimensions.\r\n */\r\n @Override\r\n public void handleClick(int x, int y, PlotRenderingInfo info) {\r\n\r\n Rectangle2D dataArea = info.getDataArea();\r\n if (dataArea.contains(x, y)) {\r\n // set the anchor value for the horizontal axis...\r\n ValueAxis xaxis = getDomainAxis();\r\n if (xaxis != null) {\r\n double hvalue = xaxis.java2DToValue(x, info.getDataArea(),\r\n getDomainAxisEdge());\r\n setDomainCrosshairValue(hvalue);\r\n }\r\n\r\n // set the anchor value for the vertical axis...\r\n ValueAxis yaxis = getRangeAxis();\r\n if (yaxis != null) {\r\n double vvalue = yaxis.java2DToValue(y, info.getDataArea(),\r\n getRangeAxisEdge());\r\n setRangeCrosshairValue(vvalue);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * A utility method that returns a list of datasets that are mapped to a\r\n * particular axis.\r\n *\r\n * @param axisIndex the axis index (<code>null</code> not permitted).\r\n *\r\n * @return A list of datasets.\r\n */\r\n private List<XYDataset> getDatasetsMappedToDomainAxis(Integer axisIndex) {\r\n ParamChecks.nullNotPermitted(axisIndex, \"axisIndex\");\r\n List<XYDataset> result = new ArrayList<XYDataset>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n int index = entry.getKey();\r\n List<Integer> mappedAxes = this.datasetToDomainAxesMap.get(index);\r\n if (mappedAxes == null) {\r\n if (axisIndex.equals(ZERO)) {\r\n result.add(entry.getValue());\r\n }\r\n } else {\r\n if (mappedAxes.contains(axisIndex)) {\r\n result.add(entry.getValue());\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * A utility method that returns a list of datasets that are mapped to a\r\n * particular axis.\r\n *\r\n * @param axisIndex the axis index (<code>null</code> not permitted).\r\n *\r\n * @return A list of datasets.\r\n */\r\n private List<XYDataset> getDatasetsMappedToRangeAxis(Integer axisIndex) {\r\n ParamChecks.nullNotPermitted(axisIndex, \"axisIndex\");\r\n List<XYDataset> result = new ArrayList<XYDataset>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n int index = entry.getKey();\r\n List<Integer> mappedAxes = this.datasetToRangeAxesMap.get(index);\r\n if (mappedAxes == null) {\r\n if (axisIndex.equals(ZERO)) {\r\n result.add(entry.getValue());\r\n }\r\n } else {\r\n if (mappedAxes.contains(axisIndex)) {\r\n result.add(entry.getValue());\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the index of the given domain axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getRangeAxisIndex(ValueAxis)\r\n */\r\n public int getDomainAxisIndex(ValueAxis axis) {\r\n int result = findDomainAxisIndex(axis);\r\n if (result < 0) {\r\n // try the parent plot\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot p = (XYPlot) parent;\r\n result = p.getDomainAxisIndex(axis);\r\n }\r\n }\r\n return result;\r\n }\r\n \r\n private int findDomainAxisIndex(ValueAxis axis) {\r\n for (Map.Entry<Integer, ValueAxis> entry : this.domainAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the index of the given range axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getDomainAxisIndex(ValueAxis)\r\n */\r\n public int getRangeAxisIndex(ValueAxis axis) {\r\n int result = findRangeAxisIndex(axis);\r\n if (result < 0) {\r\n // try the parent plot\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot p = (XYPlot) parent;\r\n result = p.getRangeAxisIndex(axis);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n private int findRangeAxisIndex(ValueAxis axis) {\r\n for (Map.Entry<Integer, ValueAxis> entry : this.rangeAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the range for the specified axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The range.\r\n */\r\n @Override\r\n public Range getDataRange(ValueAxis axis) {\r\n\r\n Range result = null;\r\n List<XYDataset> mappedDatasets = new ArrayList<XYDataset>();\r\n List<XYAnnotation> includedAnnotations = new ArrayList<XYAnnotation>();\r\n boolean isDomainAxis = true;\r\n\r\n // is it a domain axis?\r\n int domainIndex = getDomainAxisIndex(axis);\r\n if (domainIndex >= 0) {\r\n isDomainAxis = true;\r\n mappedDatasets.addAll(getDatasetsMappedToDomainAxis(domainIndex));\r\n if (domainIndex == 0) {\r\n // grab the plot's annotations\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n if (annotation instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(annotation);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // or is it a range axis?\r\n int rangeIndex = getRangeAxisIndex(axis);\r\n if (rangeIndex >= 0) {\r\n isDomainAxis = false;\r\n mappedDatasets.addAll(getDatasetsMappedToRangeAxis(rangeIndex));\r\n if (rangeIndex == 0) {\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n if (annotation instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(annotation);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // iterate through the datasets that map to the axis and get the union\r\n // of the ranges.\r\n for (XYDataset d : mappedDatasets) {\r\n if (d != null) {\r\n XYItemRenderer r = getRendererForDataset(d);\r\n if (isDomainAxis) {\r\n if (r != null) {\r\n result = Range.combine(result, r.findDomainBounds(d));\r\n }\r\n else {\r\n result = Range.combine(result,\r\n DatasetUtilities.findDomainBounds(d));\r\n }\r\n }\r\n else {\r\n if (r != null) {\r\n result = Range.combine(result, r.findRangeBounds(d));\r\n }\r\n else {\r\n result = Range.combine(result,\r\n DatasetUtilities.findRangeBounds(d));\r\n }\r\n }\r\n // FIXME: the XYItemRenderer interface doesn't specify the\r\n // getAnnotations() method but it should\r\n if (r instanceof AbstractXYItemRenderer) {\r\n AbstractXYItemRenderer rr = (AbstractXYItemRenderer) r;\r\n Collection c = rr.getAnnotations();\r\n Iterator i = c.iterator();\r\n while (i.hasNext()) {\r\n XYAnnotation a = (XYAnnotation) i.next();\r\n if (a instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(a);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n Iterator it = includedAnnotations.iterator();\r\n while (it.hasNext()) {\r\n XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next();\r\n if (xyabi.getIncludeInDataBounds()) {\r\n if (isDomainAxis) {\r\n result = Range.combine(result, xyabi.getXRange());\r\n }\r\n else {\r\n result = Range.combine(result, xyabi.getYRange());\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Receives notification of a change to an {@link Annotation} added to\r\n * this plot.\r\n *\r\n * @param event information about the event (not used here).\r\n *\r\n * @since 1.0.14\r\n */\r\n @Override\r\n public void annotationChanged(AnnotationChangeEvent event) {\r\n if (getParent() != null) {\r\n getParent().annotationChanged(event);\r\n }\r\n else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a change to the plot's dataset.\r\n * <P>\r\n * The axis ranges are updated if necessary.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void datasetChanged(DatasetChangeEvent event) {\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n if (getParent() != null) {\r\n getParent().datasetChanged(event);\r\n }\r\n else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n e.setType(ChartChangeEventType.DATASET_UPDATED);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a renderer change event.\r\n *\r\n * @param event the event.\r\n */\r\n @Override\r\n public void rendererChanged(RendererChangeEvent event) {\r\n // if the event was caused by a change to series visibility, then\r\n // the axis ranges might need updating...\r\n if (event.getSeriesVisibilityChanged()) {\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the domain crosshair is visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setDomainCrosshairVisible(boolean)\r\n */\r\n public boolean isDomainCrosshairVisible() {\r\n return this.domainCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the domain crosshair is visible\r\n * and, if the flag changes, sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isDomainCrosshairVisible()\r\n */\r\n public void setDomainCrosshairVisible(boolean flag) {\r\n if (this.domainCrosshairVisible != flag) {\r\n this.domainCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the crosshair should \"lock-on\"\r\n * to actual data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setDomainCrosshairLockedOnData(boolean)\r\n */\r\n public boolean isDomainCrosshairLockedOnData() {\r\n return this.domainCrosshairLockedOnData;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the domain crosshair should\r\n * \"lock-on\" to actual data values. If the flag value changes, this\r\n * method sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isDomainCrosshairLockedOnData()\r\n */\r\n public void setDomainCrosshairLockedOnData(boolean flag) {\r\n if (this.domainCrosshairLockedOnData != flag) {\r\n this.domainCrosshairLockedOnData = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the domain crosshair value.\r\n *\r\n * @return The value.\r\n *\r\n * @see #setDomainCrosshairValue(double)\r\n */\r\n public double getDomainCrosshairValue() {\r\n return this.domainCrosshairValue;\r\n }\r\n\r\n /**\r\n * Sets the domain crosshair value and sends a {@link PlotChangeEvent} to\r\n * all registered listeners (provided that the domain crosshair is visible).\r\n *\r\n * @param value the value.\r\n *\r\n * @see #getDomainCrosshairValue()\r\n */\r\n public void setDomainCrosshairValue(double value) {\r\n setDomainCrosshairValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the domain crosshair value and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners (provided that the\r\n * domain crosshair is visible).\r\n *\r\n * @param value the new value.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainCrosshairValue()\r\n */\r\n public void setDomainCrosshairValue(double value, boolean notify) {\r\n this.domainCrosshairValue = value;\r\n if (isDomainCrosshairVisible() && notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the {@link Stroke} used to draw the crosshair (if visible).\r\n *\r\n * @return The crosshair stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainCrosshairStroke(Stroke)\r\n * @see #isDomainCrosshairVisible()\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public Stroke getDomainCrosshairStroke() {\r\n return this.domainCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the Stroke used to draw the crosshairs (if visible) and notifies\r\n * registered listeners that the axis has been modified.\r\n *\r\n * @param stroke the new crosshair stroke (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public void setDomainCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainCrosshairStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the domain crosshair paint.\r\n *\r\n * @return The crosshair paint (never <code>null</code>).\r\n *\r\n * @see #setDomainCrosshairPaint(Paint)\r\n * @see #isDomainCrosshairVisible()\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public Paint getDomainCrosshairPaint() {\r\n return this.domainCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the new crosshair paint (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public void setDomainCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the range crosshair is visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairVisible(boolean)\r\n * @see #isDomainCrosshairVisible()\r\n */\r\n public boolean isRangeCrosshairVisible() {\r\n return this.rangeCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair is visible.\r\n * If the flag value changes, this method sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isRangeCrosshairVisible()\r\n */\r\n public void setRangeCrosshairVisible(boolean flag) {\r\n if (this.rangeCrosshairVisible != flag) {\r\n this.rangeCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the crosshair should \"lock-on\"\r\n * to actual data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairLockedOnData(boolean)\r\n */\r\n public boolean isRangeCrosshairLockedOnData() {\r\n return this.rangeCrosshairLockedOnData;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair should\r\n * \"lock-on\" to actual data values. If the flag value changes, this method\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isRangeCrosshairLockedOnData()\r\n */\r\n public void setRangeCrosshairLockedOnData(boolean flag) {\r\n if (this.rangeCrosshairLockedOnData != flag) {\r\n this.rangeCrosshairLockedOnData = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range crosshair value.\r\n *\r\n * @return The value.\r\n *\r\n * @see #setRangeCrosshairValue(double)\r\n */\r\n public double getRangeCrosshairValue() {\r\n return this.rangeCrosshairValue;\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value.\r\n * <P>\r\n * Registered listeners are notified that the plot has been modified, but\r\n * only if the crosshair is visible.\r\n *\r\n * @param value the new value.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value) {\r\n setRangeCrosshairValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value and sends a {@link PlotChangeEvent} to\r\n * all registered listeners, but only if the crosshair is visible.\r\n *\r\n * @param value the new value.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value, boolean notify) {\r\n this.rangeCrosshairValue = value;\r\n if (isRangeCrosshairVisible() && notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the crosshair (if visible).\r\n *\r\n * @return The crosshair stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairStroke(Stroke)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public Stroke getRangeCrosshairStroke() {\r\n return this.rangeCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the new crosshair stroke (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public void setRangeCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeCrosshairStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the range crosshair paint.\r\n *\r\n * @return The crosshair paint (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairPaint(Paint)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public Paint getRangeCrosshairPaint() {\r\n return this.rangeCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to color the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the new crosshair paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public void setRangeCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the fixed domain axis space.\r\n *\r\n * @return The fixed domain axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedDomainAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedDomainAxisSpace() {\r\n return this.fixedDomainAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space) {\r\n setFixedDomainAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n *\r\n * @since 1.0.9\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedDomainAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the fixed range axis space.\r\n *\r\n * @return The fixed range axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedRangeAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedRangeAxisSpace() {\r\n return this.fixedRangeAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space) {\r\n setFixedRangeAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n *\r\n * @since 1.0.9\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedRangeAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if panning is enabled for the domain axes,\r\n * and <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isDomainPannable() {\r\n return this.domainPannable;\r\n }\r\n\r\n /**\r\n * Sets the flag that enables or disables panning of the plot along the\r\n * domain axes.\r\n *\r\n * @param pannable the new flag value.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setDomainPannable(boolean pannable) {\r\n this.domainPannable = pannable;\r\n }\r\n\r\n /**\r\n * Returns {@code true} if panning is enabled for the range axis/axes,\r\n * and {@code false} otherwise. The default value is {@code false}.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isRangePannable() {\r\n return this.rangePannable;\r\n }\r\n\r\n /**\r\n * Sets the flag that enables or disables panning of the plot along\r\n * the range axis/axes.\r\n *\r\n * @param pannable the new flag value.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangePannable(boolean pannable) {\r\n this.rangePannable = pannable;\r\n }\r\n\r\n /**\r\n * Pans the domain axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panDomainAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n if (!isDomainPannable()) {\r\n return;\r\n }\r\n int domainAxisCount = getDomainAxisCount();\r\n for (int i = 0; i < domainAxisCount; i++) {\r\n ValueAxis axis = getDomainAxis(i);\r\n if (axis == null) {\r\n continue;\r\n }\r\n if (axis.isInverted()) {\r\n percent = -percent;\r\n }\r\n axis.pan(percent);\r\n }\r\n }\r\n\r\n /**\r\n * Pans the range axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panRangeAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n if (!isRangePannable()) {\r\n return;\r\n }\r\n int rangeAxisCount = getRangeAxisCount();\r\n for (int i = 0; i < rangeAxisCount; i++) {\r\n ValueAxis axis = getRangeAxis(i);\r\n if (axis == null) {\r\n continue;\r\n }\r\n if (axis.isInverted()) {\r\n percent = -percent;\r\n }\r\n axis.pan(percent);\r\n }\r\n }\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point (in Java2D space).\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo info,\r\n Point2D source) {\r\n // delegate to other method\r\n zoomDomainAxes(factor, info, source, false);\r\n }\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point (in Java2D space).\r\n * @param useAnchor use source point as zoom anchor?\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n\r\n // perform the zoom on each domain axis\r\n for (ValueAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis == null) {\r\n continue;\r\n }\r\n if (useAnchor) {\r\n // get the relevant source coordinate given the plot orientation\r\n double sourceX = source.getX();\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n sourceX = source.getY();\r\n }\r\n double anchorX = xAxis.java2DToValue(sourceX,\r\n info.getDataArea(), getDomainAxisEdge());\r\n xAxis.resizeRange2(factor, anchorX);\r\n } else {\r\n xAxis.resizeRange(factor);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the domain axis/axes. The new lower and upper bounds are\r\n * specified as percentages of the current axis range, where 0 percent is\r\n * the current lower bound and 100 percent is the current upper bound.\r\n *\r\n * @param lowerPercent a percentage that determines the new lower bound\r\n * for the axis (e.g. 0.20 is twenty percent).\r\n * @param upperPercent a percentage that determines the new upper bound\r\n * for the axis (e.g. 0.80 is eighty percent).\r\n * @param info the plot rendering info.\r\n * @param source the source point (ignored).\r\n *\r\n * @see #zoomRangeAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomDomainAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo info, Point2D source) {\r\n for (ValueAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n xAxis.zoomRange(lowerPercent, upperPercent);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo info,\r\n Point2D source) {\r\n // delegate to other method\r\n zoomRangeAxes(factor, info, source, false);\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n * @param useAnchor a flag that controls whether or not the source point\r\n * is used for the zoom anchor.\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n\r\n // perform the zoom on each range axis\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis == null) {\r\n continue;\r\n }\r\n if (useAnchor) {\r\n // get the relevant source coordinate given the plot orientation\r\n double sourceY = source.getY();\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n sourceY = source.getX();\r\n }\r\n double anchorY = yAxis.java2DToValue(sourceY,\r\n info.getDataArea(), getRangeAxisEdge());\r\n yAxis.resizeRange2(factor, anchorY);\r\n } else {\r\n yAxis.resizeRange(factor);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the range axes.\r\n *\r\n * @param lowerPercent the lower bound.\r\n * @param upperPercent the upper bound.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n *\r\n * @see #zoomDomainAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomRangeAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo info, Point2D source) {\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.zoomRange(lowerPercent, upperPercent);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code>, indicating that the domain axis/axes for this\r\n * plot are zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isRangeZoomable()\r\n */\r\n @Override\r\n public boolean isDomainZoomable() {\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code>, indicating that the range axis/axes for this\r\n * plot are zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isDomainZoomable()\r\n */\r\n @Override\r\n public boolean isRangeZoomable() {\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns the number of series in the primary dataset for this plot. If\r\n * the dataset is <code>null</code>, the method returns 0.\r\n *\r\n * @return The series count.\r\n */\r\n public int getSeriesCount() {\r\n int result = 0;\r\n XYDataset dataset = getDataset();\r\n if (dataset != null) {\r\n result = dataset.getSeriesCount();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the fixed legend items, if any.\r\n *\r\n * @return The legend items (possibly <code>null</code>).\r\n *\r\n * @see #setFixedLegendItems(LegendItemCollection)\r\n */\r\n public LegendItemCollection getFixedLegendItems() {\r\n return this.fixedLegendItems;\r\n }\r\n\r\n /**\r\n * Sets the fixed legend items for the plot. Leave this set to\r\n * <code>null</code> if you prefer the legend items to be created\r\n * automatically.\r\n *\r\n * @param items the legend items (<code>null</code> permitted).\r\n *\r\n * @see #getFixedLegendItems()\r\n */\r\n public void setFixedLegendItems(LegendItemCollection items) {\r\n this.fixedLegendItems = items;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the legend items for the plot. Each legend item is generated by\r\n * the plot's renderer, since the renderer is responsible for the visual\r\n * representation of the data.\r\n *\r\n * @return The legend items.\r\n */\r\n @Override\r\n public LegendItemCollection getLegendItems() {\r\n if (this.fixedLegendItems != null) {\r\n return this.fixedLegendItems;\r\n }\r\n LegendItemCollection result = new LegendItemCollection();\r\n for (XYDataset dataset : this.datasets.values()) {\r\n if (dataset == null) {\r\n continue;\r\n }\r\n int datasetIndex = indexOf(dataset);\r\n XYItemRenderer renderer = getRenderer(datasetIndex);\r\n if (renderer == null) {\r\n renderer = getRenderer(0);\r\n }\r\n if (renderer != null) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int i = 0; i < seriesCount; i++) {\r\n if (renderer.isSeriesVisible(i)\r\n && renderer.isSeriesVisibleInLegend(i)) {\r\n LegendItem item = renderer.getLegendItem(\r\n datasetIndex, i);\r\n if (item != null) {\r\n result.add(item);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Tests this plot for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof XYPlot)) {\r\n return false;\r\n }\r\n XYPlot that = (XYPlot) obj;\r\n if (this.weight != that.weight) {\r\n return false;\r\n }\r\n if (this.orientation != that.orientation) {\r\n return false;\r\n }\r\n if (!this.domainAxes.equals(that.domainAxes)) {\r\n return false;\r\n }\r\n if (!this.domainAxisLocations.equals(that.domainAxisLocations)) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairLockedOnData\r\n != that.rangeCrosshairLockedOnData) {\r\n return false;\r\n }\r\n if (this.domainGridlinesVisible != that.domainGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.rangeGridlinesVisible != that.rangeGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.domainMinorGridlinesVisible\r\n != that.domainMinorGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.rangeMinorGridlinesVisible\r\n != that.rangeMinorGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.domainZeroBaselineVisible != that.domainZeroBaselineVisible) {\r\n return false;\r\n }\r\n if (this.rangeZeroBaselineVisible != that.rangeZeroBaselineVisible) {\r\n return false;\r\n }\r\n if (this.domainCrosshairVisible != that.domainCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.domainCrosshairValue != that.domainCrosshairValue) {\r\n return false;\r\n }\r\n if (this.domainCrosshairLockedOnData\r\n != that.domainCrosshairLockedOnData) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairVisible != that.rangeCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairValue != that.rangeCrosshairValue) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.axisOffset, that.axisOffset)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.renderers, that.renderers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeAxes, that.rangeAxes)) {\r\n return false;\r\n }\r\n if (!this.rangeAxisLocations.equals(that.rangeAxisLocations)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToDomainAxesMap,\r\n that.datasetToDomainAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToRangeAxesMap,\r\n that.datasetToRangeAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainGridlineStroke,\r\n that.domainGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainGridlinePaint,\r\n that.domainGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeGridlineStroke,\r\n that.rangeGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeGridlinePaint,\r\n that.rangeGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainMinorGridlineStroke,\r\n that.domainMinorGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainMinorGridlinePaint,\r\n that.domainMinorGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeMinorGridlineStroke,\r\n that.rangeMinorGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeMinorGridlinePaint,\r\n that.rangeMinorGridlinePaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainZeroBaselinePaint,\r\n that.domainZeroBaselinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainZeroBaselineStroke,\r\n that.domainZeroBaselineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeZeroBaselinePaint,\r\n that.rangeZeroBaselinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeZeroBaselineStroke,\r\n that.rangeZeroBaselineStroke)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainCrosshairStroke,\r\n that.domainCrosshairStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainCrosshairPaint,\r\n that.domainCrosshairPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeCrosshairStroke,\r\n that.rangeCrosshairStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeCrosshairPaint,\r\n that.rangeCrosshairPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundDomainMarkers,\r\n that.foregroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundDomainMarkers,\r\n that.backgroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundRangeMarkers,\r\n that.foregroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundRangeMarkers,\r\n that.backgroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundDomainMarkers,\r\n that.foregroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundDomainMarkers,\r\n that.backgroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundRangeMarkers,\r\n that.foregroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundRangeMarkers,\r\n that.backgroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.annotations, that.annotations)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.fixedLegendItems,\r\n that.fixedLegendItems)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainTickBandPaint,\r\n that.domainTickBandPaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeTickBandPaint,\r\n that.rangeTickBandPaint)) {\r\n return false;\r\n }\r\n if (!this.quadrantOrigin.equals(that.quadrantOrigin)) {\r\n return false;\r\n }\r\n for (int i = 0; i < 4; i++) {\r\n if (!PaintUtilities.equal(this.quadrantPaint[i],\r\n that.quadrantPaint[i])) {\r\n return false;\r\n }\r\n }\r\n if (!ObjectUtilities.equal(this.shadowGenerator,\r\n that.shadowGenerator)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a clone of the plot.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException this can occur if some component of\r\n * the plot cannot be cloned.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n XYPlot clone = (XYPlot) super.clone();\r\n clone.domainAxes = CloneUtils.cloneMapValues(this.domainAxes);\r\n for (ValueAxis axis : clone.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n clone.rangeAxes = CloneUtils.cloneMapValues(this.rangeAxes);\r\n for (ValueAxis axis : clone.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n clone.domainAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.domainAxisLocations);\r\n clone.rangeAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.rangeAxisLocations);\r\n\r\n // the datasets are not cloned, but listeners need to be added...\r\n clone.datasets = new HashMap<Integer, XYDataset>(this.datasets);\r\n for (XYDataset dataset : clone.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(clone);\r\n }\r\n }\r\n\r\n clone.datasetToDomainAxesMap = new TreeMap();\r\n clone.datasetToDomainAxesMap.putAll(this.datasetToDomainAxesMap);\r\n clone.datasetToRangeAxesMap = new TreeMap();\r\n clone.datasetToRangeAxesMap.putAll(this.datasetToRangeAxesMap);\r\n\r\n clone.renderers = CloneUtils.cloneMapValues(this.renderers);\r\n for (XYItemRenderer renderer : clone.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.setPlot(clone);\r\n renderer.addChangeListener(clone);\r\n }\r\n }\r\n clone.foregroundDomainMarkers = (Map) ObjectUtilities.clone(\r\n this.foregroundDomainMarkers);\r\n clone.backgroundDomainMarkers = (Map) ObjectUtilities.clone(\r\n this.backgroundDomainMarkers);\r\n clone.foregroundRangeMarkers = (Map) ObjectUtilities.clone(\r\n this.foregroundRangeMarkers);\r\n clone.backgroundRangeMarkers = (Map) ObjectUtilities.clone(\r\n this.backgroundRangeMarkers);\r\n clone.annotations = (List) ObjectUtilities.deepClone(this.annotations);\r\n if (this.fixedDomainAxisSpace != null) {\r\n clone.fixedDomainAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedDomainAxisSpace);\r\n }\r\n if (this.fixedRangeAxisSpace != null) {\r\n clone.fixedRangeAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedRangeAxisSpace);\r\n }\r\n if (this.fixedLegendItems != null) {\r\n clone.fixedLegendItems\r\n = (LegendItemCollection) this.fixedLegendItems.clone();\r\n }\r\n clone.quadrantOrigin = (Point2D) ObjectUtilities.clone(\r\n this.quadrantOrigin);\r\n clone.quadrantPaint = this.quadrantPaint.clone();\r\n return clone;\r\n\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.domainGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.domainGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.domainMinorGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.domainMinorGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeMinorGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeMinorGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeZeroBaselineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeZeroBaselinePaint, stream);\r\n SerialUtilities.writeStroke(this.domainCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.domainCrosshairPaint, stream);\r\n SerialUtilities.writeStroke(this.rangeCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.rangeCrosshairPaint, stream);\r\n SerialUtilities.writePaint(this.domainTickBandPaint, stream);\r\n SerialUtilities.writePaint(this.rangeTickBandPaint, stream);\r\n SerialUtilities.writePoint2D(this.quadrantOrigin, stream);\r\n for (int i = 0; i < 4; i++) {\r\n SerialUtilities.writePaint(this.quadrantPaint[i], stream);\r\n }\r\n SerialUtilities.writeStroke(this.domainZeroBaselineStroke, stream);\r\n SerialUtilities.writePaint(this.domainZeroBaselinePaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n\r\n stream.defaultReadObject();\r\n this.domainGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.domainGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.domainMinorGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.domainMinorGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeMinorGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeMinorGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeZeroBaselineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeZeroBaselinePaint = SerialUtilities.readPaint(stream);\r\n this.domainCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.domainCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.rangeCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.rangeCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.domainTickBandPaint = SerialUtilities.readPaint(stream);\r\n this.rangeTickBandPaint = SerialUtilities.readPaint(stream);\r\n this.quadrantOrigin = SerialUtilities.readPoint2D(stream);\r\n this.quadrantPaint = new Paint[4];\r\n for (int i = 0; i < 4; i++) {\r\n this.quadrantPaint[i] = SerialUtilities.readPaint(stream);\r\n }\r\n\r\n this.domainZeroBaselineStroke = SerialUtilities.readStroke(stream);\r\n this.domainZeroBaselinePaint = SerialUtilities.readPaint(stream);\r\n\r\n // register the plot as a listener with its axes, datasets, and\r\n // renderers...\r\n for (ValueAxis axis : this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n axis.addChangeListener(this);\r\n }\r\n }\r\n for (ValueAxis axis : this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n axis.addChangeListener(this);\r\n }\r\n }\r\n for (XYDataset dataset : this.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n }\r\n for (XYItemRenderer renderer : this.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.addChangeListener(this);\r\n }\r\n }\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "DefaultTableXYDataset", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/xy/DefaultTableXYDataset.java", "snippet": "public class DefaultTableXYDataset extends AbstractIntervalXYDataset\r\n implements TableXYDataset, IntervalXYDataset, DomainInfo,\r\n PublicCloneable {\r\n\r\n /**\r\n * Storage for the data - this list will contain zero, one or many\r\n * XYSeries objects.\r\n */\r\n private List data = null;\r\n\r\n /** Storage for the x values. */\r\n private HashSet xPoints = null;\r\n\r\n /** A flag that controls whether or not events are propogated. */\r\n private boolean propagateEvents = true;\r\n\r\n /** A flag that controls auto pruning. */\r\n private boolean autoPrune = false;\r\n\r\n /** The delegate used to control the interval width. */\r\n private IntervalXYDelegate intervalDelegate;\r\n\r\n /**\r\n * Creates a new empty dataset.\r\n */\r\n public DefaultTableXYDataset() {\r\n this(false);\r\n }\r\n\r\n /**\r\n * Creates a new empty dataset.\r\n *\r\n * @param autoPrune a flag that controls whether or not x-values are\r\n * removed whenever the corresponding y-values are all\r\n * <code>null</code>.\r\n */\r\n public DefaultTableXYDataset(boolean autoPrune) {\r\n this.autoPrune = autoPrune;\r\n this.data = new ArrayList();\r\n this.xPoints = new HashSet();\r\n this.intervalDelegate = new IntervalXYDelegate(this, false);\r\n addChangeListener(this.intervalDelegate);\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not x-values are removed from\r\n * the dataset when the corresponding y-values are all <code>null</code>.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean isAutoPrune() {\r\n return this.autoPrune;\r\n }\r\n\r\n /**\r\n * Adds a series to the collection and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners. The series should be configured to NOT\r\n * allow duplicate x-values.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n */\r\n public void addSeries(XYSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n if (series.getAllowDuplicateXValues()) {\r\n throw new IllegalArgumentException(\r\n \"Cannot accept XYSeries that allow duplicate values. \"\r\n + \"Use XYSeries(seriesName, <sort>, false) constructor.\"\r\n );\r\n }\r\n updateXPoints(series);\r\n this.data.add(series);\r\n series.addChangeListener(this);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Adds any unique x-values from 'series' to the dataset, and also adds any\r\n * x-values that are in the dataset but not in 'series' to the series.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n */\r\n private void updateXPoints(XYSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n HashSet seriesXPoints = new HashSet();\r\n boolean savedState = this.propagateEvents;\r\n this.propagateEvents = false;\r\n for (int itemNo = 0; itemNo < series.getItemCount(); itemNo++) {\r\n Number xValue = series.getX(itemNo);\r\n seriesXPoints.add(xValue);\r\n if (!this.xPoints.contains(xValue)) {\r\n this.xPoints.add(xValue);\r\n int seriesCount = this.data.size();\r\n for (int seriesNo = 0; seriesNo < seriesCount; seriesNo++) {\r\n XYSeries dataSeries = (XYSeries) this.data.get(seriesNo);\r\n if (!dataSeries.equals(series)) {\r\n dataSeries.add(xValue, null);\r\n }\r\n }\r\n }\r\n }\r\n Iterator iterator = this.xPoints.iterator();\r\n while (iterator.hasNext()) {\r\n Number xPoint = (Number) iterator.next();\r\n if (!seriesXPoints.contains(xPoint)) {\r\n series.add(xPoint, null);\r\n }\r\n }\r\n this.propagateEvents = savedState;\r\n }\r\n\r\n /**\r\n * Updates the x-values for all the series in the dataset.\r\n */\r\n public void updateXPoints() {\r\n this.propagateEvents = false;\r\n for (int s = 0; s < this.data.size(); s++) {\r\n updateXPoints((XYSeries) this.data.get(s));\r\n }\r\n if (this.autoPrune) {\r\n prune();\r\n }\r\n this.propagateEvents = true;\r\n }\r\n\r\n /**\r\n * Returns the number of series in the collection.\r\n *\r\n * @return The series count.\r\n */\r\n @Override\r\n public int getSeriesCount() {\r\n return this.data.size();\r\n }\r\n\r\n /**\r\n * Returns the number of x values in the dataset.\r\n *\r\n * @return The number of x values in the dataset.\r\n */\r\n @Override\r\n public int getItemCount() {\r\n if (this.xPoints == null) {\r\n return 0;\r\n }\r\n else {\r\n return this.xPoints.size();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a series.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The series (never <code>null</code>).\r\n */\r\n public XYSeries getSeries(int series) {\r\n if ((series < 0) || (series >= getSeriesCount())) {\r\n throw new IllegalArgumentException(\"Index outside valid range.\");\r\n }\r\n return (XYSeries) this.data.get(series);\r\n }\r\n\r\n /**\r\n * Returns the key for a series.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The key for a series.\r\n */\r\n @Override\r\n public Comparable getSeriesKey(int series) {\r\n // check arguments...delegated\r\n return getSeries(series).getKey();\r\n }\r\n\r\n /**\r\n * Returns the number of items in the specified series.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The number of items in the specified series.\r\n */\r\n @Override\r\n public int getItemCount(int series) {\r\n // check arguments...delegated\r\n return getSeries(series).getItemCount();\r\n }\r\n\r\n /**\r\n * Returns the x-value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The x-value for the specified series and item.\r\n */\r\n @Override\r\n public Number getX(int series, int item) {\r\n XYSeries s = (XYSeries) this.data.get(series);\r\n return s.getX(item);\r\n\r\n }\r\n\r\n /**\r\n * Returns the starting X value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The starting X value.\r\n */\r\n @Override\r\n public Number getStartX(int series, int item) {\r\n return this.intervalDelegate.getStartX(series, item);\r\n }\r\n\r\n /**\r\n * Returns the ending X value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The ending X value.\r\n */\r\n @Override\r\n public Number getEndX(int series, int item) {\r\n return this.intervalDelegate.getEndX(series, item);\r\n }\r\n\r\n /**\r\n * Returns the y-value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param index the index of the item of interest (zero-based).\r\n *\r\n * @return The y-value for the specified series and item (possibly\r\n * <code>null</code>).\r\n */\r\n @Override\r\n public Number getY(int series, int index) {\r\n XYSeries s = (XYSeries) this.data.get(series);\r\n return s.getY(index);\r\n }\r\n\r\n /**\r\n * Returns the starting Y value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The starting Y value.\r\n */\r\n @Override\r\n public Number getStartY(int series, int item) {\r\n return getY(series, item);\r\n }\r\n\r\n /**\r\n * Returns the ending Y value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The ending Y value.\r\n */\r\n @Override\r\n public Number getEndY(int series, int item) {\r\n return getY(series, item);\r\n }\r\n\r\n /**\r\n * Removes all the series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n */\r\n public void removeAllSeries() {\r\n\r\n // Unregister the collection as a change listener to each series in\r\n // the collection.\r\n for (int i = 0; i < this.data.size(); i++) {\r\n XYSeries series = (XYSeries) this.data.get(i);\r\n series.removeChangeListener(this);\r\n }\r\n\r\n // Remove all the series from the collection and notify listeners.\r\n this.data.clear();\r\n this.xPoints.clear();\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes a series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n */\r\n public void removeSeries(XYSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n if (this.data.contains(series)) {\r\n series.removeChangeListener(this);\r\n this.data.remove(series);\r\n if (this.data.isEmpty()) {\r\n this.xPoints.clear();\r\n }\r\n fireDatasetChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Removes a series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series (zero based index).\r\n */\r\n public void removeSeries(int series) {\r\n\r\n // check arguments...\r\n if ((series < 0) || (series > getSeriesCount())) {\r\n throw new IllegalArgumentException(\"Index outside valid range.\");\r\n }\r\n\r\n // fetch the series, remove the change listener, then remove the series.\r\n XYSeries s = (XYSeries) this.data.get(series);\r\n s.removeChangeListener(this);\r\n this.data.remove(series);\r\n if (this.data.isEmpty()) {\r\n this.xPoints.clear();\r\n }\r\n else if (this.autoPrune) {\r\n prune();\r\n }\r\n fireDatasetChanged();\r\n\r\n }\r\n\r\n /**\r\n * Removes the items from all series for a given x value.\r\n *\r\n * @param x the x-value.\r\n */\r\n public void removeAllValuesForX(Number x) {\r\n ParamChecks.nullNotPermitted(x, \"x\");\r\n boolean savedState = this.propagateEvents;\r\n this.propagateEvents = false;\r\n for (int s = 0; s < this.data.size(); s++) {\r\n XYSeries series = (XYSeries) this.data.get(s);\r\n series.remove(x);\r\n }\r\n this.propagateEvents = savedState;\r\n this.xPoints.remove(x);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if all the y-values for the specified x-value\r\n * are <code>null</code> and <code>false</code> otherwise.\r\n *\r\n * @param x the x-value.\r\n *\r\n * @return A boolean.\r\n */\r\n protected boolean canPrune(Number x) {\r\n for (int s = 0; s < this.data.size(); s++) {\r\n XYSeries series = (XYSeries) this.data.get(s);\r\n if (series.getY(series.indexOf(x)) != null) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Removes all x-values for which all the y-values are <code>null</code>.\r\n */\r\n public void prune() {\r\n HashSet hs = (HashSet) this.xPoints.clone();\r\n Iterator iterator = hs.iterator();\r\n while (iterator.hasNext()) {\r\n Number x = (Number) iterator.next();\r\n if (canPrune(x)) {\r\n removeAllValuesForX(x);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * This method receives notification when a series belonging to the dataset\r\n * changes. It responds by updating the x-points for the entire dataset\r\n * and sending a {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param event information about the change.\r\n */\r\n @Override\r\n public void seriesChanged(SeriesChangeEvent event) {\r\n if (this.propagateEvents) {\r\n updateXPoints();\r\n fireDatasetChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Tests this collection for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof DefaultTableXYDataset)) {\r\n return false;\r\n }\r\n DefaultTableXYDataset that = (DefaultTableXYDataset) obj;\r\n if (this.autoPrune != that.autoPrune) {\r\n return false;\r\n }\r\n if (this.propagateEvents != that.propagateEvents) {\r\n return false;\r\n }\r\n if (!this.intervalDelegate.equals(that.intervalDelegate)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.data, that.data)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result;\r\n result = (this.data != null ? this.data.hashCode() : 0);\r\n result = 29 * result\r\n + (this.xPoints != null ? this.xPoints.hashCode() : 0);\r\n result = 29 * result + (this.propagateEvents ? 1 : 0);\r\n result = 29 * result + (this.autoPrune ? 1 : 0);\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns an independent copy of this dataset.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if there is some reason that cloning\r\n * cannot be performed.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n DefaultTableXYDataset clone = (DefaultTableXYDataset) super.clone();\r\n int seriesCount = this.data.size();\r\n clone.data = new java.util.ArrayList(seriesCount);\r\n for (int i = 0; i < seriesCount; i++) {\r\n XYSeries series = (XYSeries) this.data.get(i);\r\n clone.data.add(series.clone());\r\n }\r\n\r\n clone.intervalDelegate = new IntervalXYDelegate(clone);\r\n // need to configure the intervalDelegate to match the original\r\n clone.intervalDelegate.setFixedIntervalWidth(getIntervalWidth());\r\n clone.intervalDelegate.setAutoWidth(isAutoWidth());\r\n clone.intervalDelegate.setIntervalPositionFactor(\r\n getIntervalPositionFactor());\r\n clone.updateXPoints();\r\n return clone;\r\n }\r\n\r\n /**\r\n * Returns the minimum x-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The minimum value.\r\n */\r\n @Override\r\n public double getDomainLowerBound(boolean includeInterval) {\r\n return this.intervalDelegate.getDomainLowerBound(includeInterval);\r\n }\r\n\r\n /**\r\n * Returns the maximum x-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The maximum value.\r\n */\r\n @Override\r\n public double getDomainUpperBound(boolean includeInterval) {\r\n return this.intervalDelegate.getDomainUpperBound(includeInterval);\r\n }\r\n\r\n /**\r\n * Returns the range of the values in this dataset's domain.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The range.\r\n */\r\n @Override\r\n public Range getDomainBounds(boolean includeInterval) {\r\n if (includeInterval) {\r\n return this.intervalDelegate.getDomainBounds(includeInterval);\r\n }\r\n else {\r\n return DatasetUtilities.iterateDomainBounds(this, includeInterval);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the interval position factor.\r\n *\r\n * @return The interval position factor.\r\n */\r\n public double getIntervalPositionFactor() {\r\n return this.intervalDelegate.getIntervalPositionFactor();\r\n }\r\n\r\n /**\r\n * Sets the interval position factor. Must be between 0.0 and 1.0 inclusive.\r\n * If the factor is 0.5, the gap is in the middle of the x values. If it\r\n * is lesser than 0.5, the gap is farther to the left and if greater than\r\n * 0.5 it gets farther to the right.\r\n *\r\n * @param d the new interval position factor.\r\n */\r\n public void setIntervalPositionFactor(double d) {\r\n this.intervalDelegate.setIntervalPositionFactor(d);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * returns the full interval width.\r\n *\r\n * @return The interval width to use.\r\n */\r\n public double getIntervalWidth() {\r\n return this.intervalDelegate.getIntervalWidth();\r\n }\r\n\r\n /**\r\n * Sets the interval width to a fixed value, and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param d the new interval width (must be &gt; 0).\r\n */\r\n public void setIntervalWidth(double d) {\r\n this.intervalDelegate.setFixedIntervalWidth(d);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns whether the interval width is automatically calculated or not.\r\n *\r\n * @return A flag that determines whether or not the interval width is\r\n * automatically calculated.\r\n */\r\n public boolean isAutoWidth() {\r\n return this.intervalDelegate.isAutoWidth();\r\n }\r\n\r\n /**\r\n * Sets the flag that indicates whether the interval width is automatically\r\n * calculated or not.\r\n *\r\n * @param b a boolean.\r\n */\r\n public void setAutoWidth(boolean b) {\r\n this.intervalDelegate.setAutoWidth(b);\r\n fireDatasetChanged();\r\n }\r\n\r\n}\r" }, { "identifier": "XYSeries", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/xy/XYSeries.java", "snippet": "public class XYSeries extends Series implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n static final long serialVersionUID = -5908509288197150436L;\r\n\r\n // In version 0.9.12, in response to several developer requests, I changed\r\n // the 'data' attribute from 'private' to 'protected', so that others can\r\n // make subclasses that work directly with the underlying data structure.\r\n\r\n /** Storage for the data items in the series. */\r\n protected List data;\r\n\r\n /** The maximum number of items for the series. */\r\n private int maximumItemCount = Integer.MAX_VALUE;\r\n\r\n /**\r\n * A flag that controls whether the items are automatically sorted\r\n * (by x-value ascending).\r\n */\r\n private boolean autoSort;\r\n\r\n /** A flag that controls whether or not duplicate x-values are allowed. */\r\n private boolean allowDuplicateXValues;\r\n\r\n /** The lowest x-value in the series, excluding Double.NaN values. */\r\n private double minX;\r\n\r\n /** The highest x-value in the series, excluding Double.NaN values. */\r\n private double maxX;\r\n\r\n /** The lowest y-value in the series, excluding Double.NaN values. */\r\n private double minY;\r\n\r\n /** The highest y-value in the series, excluding Double.NaN values. */\r\n private double maxY;\r\n\r\n /**\r\n * Creates a new empty series. By default, items added to the series will\r\n * be sorted into ascending order by x-value, and duplicate x-values will\r\n * be allowed (these defaults can be modified with another constructor).\r\n *\r\n * @param key the series key (<code>null</code> not permitted).\r\n */\r\n public XYSeries(Comparable key) {\r\n this(key, true, true);\r\n }\r\n\r\n /**\r\n * Constructs a new empty series, with the auto-sort flag set as requested,\r\n * and duplicate values allowed.\r\n *\r\n * @param key the series key (<code>null</code> not permitted).\r\n * @param autoSort a flag that controls whether or not the items in the\r\n * series are sorted.\r\n */\r\n public XYSeries(Comparable key, boolean autoSort) {\r\n this(key, autoSort, true);\r\n }\r\n\r\n /**\r\n * Constructs a new xy-series that contains no data. You can specify\r\n * whether or not duplicate x-values are allowed for the series.\r\n *\r\n * @param key the series key (<code>null</code> not permitted).\r\n * @param autoSort a flag that controls whether or not the items in the\r\n * series are sorted.\r\n * @param allowDuplicateXValues a flag that controls whether duplicate\r\n * x-values are allowed.\r\n */\r\n public XYSeries(Comparable key, boolean autoSort,\r\n boolean allowDuplicateXValues) {\r\n super(key);\r\n this.data = new java.util.ArrayList();\r\n this.autoSort = autoSort;\r\n this.allowDuplicateXValues = allowDuplicateXValues;\r\n this.minX = Double.NaN;\r\n this.maxX = Double.NaN;\r\n this.minY = Double.NaN;\r\n this.maxY = Double.NaN;\r\n }\r\n\r\n /**\r\n * Returns the smallest x-value in the series, ignoring any Double.NaN\r\n * values. This method returns Double.NaN if there is no smallest x-value\r\n * (for example, when the series is empty).\r\n *\r\n * @return The smallest x-value.\r\n *\r\n * @see #getMaxX()\r\n *\r\n * @since 1.0.13\r\n */\r\n public double getMinX() {\r\n return this.minX;\r\n }\r\n\r\n /**\r\n * Returns the largest x-value in the series, ignoring any Double.NaN\r\n * values. This method returns Double.NaN if there is no largest x-value\r\n * (for example, when the series is empty).\r\n *\r\n * @return The largest x-value.\r\n *\r\n * @see #getMinX()\r\n *\r\n * @since 1.0.13\r\n */\r\n public double getMaxX() {\r\n return this.maxX;\r\n }\r\n\r\n /**\r\n * Returns the smallest y-value in the series, ignoring any null and\r\n * Double.NaN values. This method returns Double.NaN if there is no\r\n * smallest y-value (for example, when the series is empty).\r\n *\r\n * @return The smallest y-value.\r\n *\r\n * @see #getMaxY()\r\n *\r\n * @since 1.0.13\r\n */\r\n public double getMinY() {\r\n return this.minY;\r\n }\r\n\r\n /**\r\n * Returns the largest y-value in the series, ignoring any Double.NaN\r\n * values. This method returns Double.NaN if there is no largest y-value\r\n * (for example, when the series is empty).\r\n *\r\n * @return The largest y-value.\r\n *\r\n * @see #getMinY()\r\n *\r\n * @since 1.0.13\r\n */\r\n public double getMaxY() {\r\n return this.maxY;\r\n }\r\n\r\n /**\r\n * Updates the cached values for the minimum and maximum data values.\r\n *\r\n * @param item the item added (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.13\r\n */\r\n private void updateBoundsForAddedItem(XYDataItem item) {\r\n double x = item.getXValue();\r\n this.minX = minIgnoreNaN(this.minX, x);\r\n this.maxX = maxIgnoreNaN(this.maxX, x);\r\n if (item.getY() != null) {\r\n double y = item.getYValue();\r\n this.minY = minIgnoreNaN(this.minY, y);\r\n this.maxY = maxIgnoreNaN(this.maxY, y);\r\n }\r\n }\r\n\r\n /**\r\n * Updates the cached values for the minimum and maximum data values on\r\n * the basis that the specified item has just been removed.\r\n *\r\n * @param item the item added (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.13\r\n */\r\n private void updateBoundsForRemovedItem(XYDataItem item) {\r\n boolean itemContributesToXBounds = false;\r\n boolean itemContributesToYBounds = false;\r\n double x = item.getXValue();\r\n if (!Double.isNaN(x)) {\r\n if (x <= this.minX || x >= this.maxX) {\r\n itemContributesToXBounds = true;\r\n }\r\n }\r\n if (item.getY() != null) {\r\n double y = item.getYValue();\r\n if (!Double.isNaN(y)) {\r\n if (y <= this.minY || y >= this.maxY) {\r\n itemContributesToYBounds = true;\r\n }\r\n }\r\n }\r\n if (itemContributesToYBounds) {\r\n findBoundsByIteration();\r\n }\r\n else if (itemContributesToXBounds) {\r\n if (getAutoSort()) {\r\n this.minX = getX(0).doubleValue();\r\n this.maxX = getX(getItemCount() - 1).doubleValue();\r\n }\r\n else {\r\n findBoundsByIteration();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Finds the bounds of the x and y values for the series, by iterating\r\n * through all the data items.\r\n *\r\n * @since 1.0.13\r\n */\r\n private void findBoundsByIteration() {\r\n this.minX = Double.NaN;\r\n this.maxX = Double.NaN;\r\n this.minY = Double.NaN;\r\n this.maxY = Double.NaN;\r\n Iterator iterator = this.data.iterator();\r\n while (iterator.hasNext()) {\r\n XYDataItem item = (XYDataItem) iterator.next();\r\n updateBoundsForAddedItem(item);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether the items in the series are\r\n * automatically sorted. There is no setter for this flag, it must be\r\n * defined in the series constructor.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean getAutoSort() {\r\n return this.autoSort;\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether duplicate x-values are allowed.\r\n * This flag can only be set in the constructor.\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean getAllowDuplicateXValues() {\r\n return this.allowDuplicateXValues;\r\n }\r\n\r\n /**\r\n * Returns the number of items in the series.\r\n *\r\n * @return The item count.\r\n *\r\n * @see #getItems()\r\n */\r\n @Override\r\n public int getItemCount() {\r\n return this.data.size();\r\n }\r\n\r\n /**\r\n * Returns the list of data items for the series (the list contains\r\n * {@link XYDataItem} objects and is unmodifiable).\r\n *\r\n * @return The list of data items.\r\n */\r\n public List getItems() {\r\n return Collections.unmodifiableList(this.data);\r\n }\r\n\r\n /**\r\n * Returns the maximum number of items that will be retained in the series.\r\n * The default value is <code>Integer.MAX_VALUE</code>.\r\n *\r\n * @return The maximum item count.\r\n *\r\n * @see #setMaximumItemCount(int)\r\n */\r\n public int getMaximumItemCount() {\r\n return this.maximumItemCount;\r\n }\r\n\r\n /**\r\n * Sets the maximum number of items that will be retained in the series.\r\n * If you add a new item to the series such that the number of items will\r\n * exceed the maximum item count, then the first element in the series is\r\n * automatically removed, ensuring that the maximum item count is not\r\n * exceeded.\r\n * <p>\r\n * Typically this value is set before the series is populated with data,\r\n * but if it is applied later, it may cause some items to be removed from\r\n * the series (in which case a {@link SeriesChangeEvent} will be sent to\r\n * all registered listeners).\r\n *\r\n * @param maximum the maximum number of items for the series.\r\n */\r\n public void setMaximumItemCount(int maximum) {\r\n this.maximumItemCount = maximum;\r\n int remove = this.data.size() - maximum;\r\n if (remove > 0) {\r\n this.data.subList(0, remove).clear();\r\n findBoundsByIteration();\r\n fireSeriesChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and sends a {@link SeriesChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param item the (x, y) item (<code>null</code> not permitted).\r\n */\r\n public void add(XYDataItem item) {\r\n // argument checking delegated...\r\n add(item, true);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and sends a {@link SeriesChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param x the x value.\r\n * @param y the y value.\r\n */\r\n public void add(double x, double y) {\r\n add(new Double(x), new Double(y), true);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and, if requested, sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param x the x value.\r\n * @param y the y value.\r\n * @param notify a flag that controls whether or not a\r\n * {@link SeriesChangeEvent} is sent to all registered\r\n * listeners.\r\n */\r\n public void add(double x, double y, boolean notify) {\r\n add(new Double(x), new Double(y), notify);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and sends a {@link SeriesChangeEvent} to\r\n * all registered listeners. The unusual pairing of parameter types is to\r\n * make it easier to add <code>null</code> y-values.\r\n *\r\n * @param x the x value.\r\n * @param y the y value (<code>null</code> permitted).\r\n */\r\n public void add(double x, Number y) {\r\n add(new Double(x), y);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and, if requested, sends a\r\n * {@link SeriesChangeEvent} to all registered listeners. The unusual\r\n * pairing of parameter types is to make it easier to add null y-values.\r\n *\r\n * @param x the x value.\r\n * @param y the y value (<code>null</code> permitted).\r\n * @param notify a flag that controls whether or not a\r\n * {@link SeriesChangeEvent} is sent to all registered\r\n * listeners.\r\n */\r\n public void add(double x, Number y, boolean notify) {\r\n add(new Double(x), y, notify);\r\n }\r\n\r\n /**\r\n * Adds a new data item to the series (in the correct position if the\r\n * <code>autoSort</code> flag is set for the series) and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n * <P>\r\n * Throws an exception if the x-value is a duplicate AND the\r\n * allowDuplicateXValues flag is false.\r\n *\r\n * @param x the x-value (<code>null</code> not permitted).\r\n * @param y the y-value (<code>null</code> permitted).\r\n *\r\n * @throws SeriesException if the x-value is a duplicate and the\r\n * <code>allowDuplicateXValues</code> flag is not set for this series.\r\n */\r\n public void add(Number x, Number y) {\r\n // argument checking delegated...\r\n add(x, y, true);\r\n }\r\n\r\n /**\r\n * Adds new data to the series and, if requested, sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n * <P>\r\n * Throws an exception if the x-value is a duplicate AND the\r\n * allowDuplicateXValues flag is false.\r\n *\r\n * @param x the x-value (<code>null</code> not permitted).\r\n * @param y the y-value (<code>null</code> permitted).\r\n * @param notify a flag the controls whether or not a\r\n * {@link SeriesChangeEvent} is sent to all registered\r\n * listeners.\r\n */\r\n public void add(Number x, Number y, boolean notify) {\r\n // delegate argument checking to XYDataItem...\r\n XYDataItem item = new XYDataItem(x, y);\r\n add(item, notify);\r\n }\r\n\r\n /**\r\n * Adds a data item to the series and, if requested, sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param item the (x, y) item (<code>null</code> not permitted).\r\n * @param notify a flag that controls whether or not a\r\n * {@link SeriesChangeEvent} is sent to all registered\r\n * listeners.\r\n */\r\n public void add(XYDataItem item, boolean notify) {\r\n ParamChecks.nullNotPermitted(item, \"item\");\r\n item = (XYDataItem) item.clone();\r\n if (this.autoSort) {\r\n int index = Collections.binarySearch(this.data, item);\r\n if (index < 0) {\r\n this.data.add(-index - 1, item);\r\n }\r\n else {\r\n if (this.allowDuplicateXValues) {\r\n // need to make sure we are adding *after* any duplicates\r\n int size = this.data.size();\r\n while (index < size && item.compareTo(\r\n this.data.get(index)) == 0) {\r\n index++;\r\n }\r\n if (index < this.data.size()) {\r\n this.data.add(index, item);\r\n }\r\n else {\r\n this.data.add(item);\r\n }\r\n }\r\n else {\r\n throw new SeriesException(\"X-value already exists.\");\r\n }\r\n }\r\n }\r\n else {\r\n if (!this.allowDuplicateXValues) {\r\n // can't allow duplicate values, so we need to check whether\r\n // there is an item with the given x-value already\r\n int index = indexOf(item.getX());\r\n if (index >= 0) {\r\n throw new SeriesException(\"X-value already exists.\");\r\n }\r\n }\r\n this.data.add(item);\r\n }\r\n updateBoundsForAddedItem(item);\r\n if (getItemCount() > this.maximumItemCount) {\r\n XYDataItem removed = (XYDataItem) this.data.remove(0);\r\n updateBoundsForRemovedItem(removed);\r\n }\r\n if (notify) {\r\n fireSeriesChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Deletes a range of items from the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param start the start index (zero-based).\r\n * @param end the end index (zero-based).\r\n */\r\n public void delete(int start, int end) {\r\n this.data.subList(start, end + 1).clear();\r\n findBoundsByIteration();\r\n fireSeriesChanged();\r\n }\r\n\r\n /**\r\n * Removes the item at the specified index and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param index the index.\r\n *\r\n * @return The item removed.\r\n */\r\n public XYDataItem remove(int index) {\r\n XYDataItem removed = (XYDataItem) this.data.remove(index);\r\n updateBoundsForRemovedItem(removed);\r\n fireSeriesChanged();\r\n return removed;\r\n }\r\n\r\n /**\r\n * Removes an item with the specified x-value and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners. Note that when\r\n * a series permits multiple items with the same x-value, this method\r\n * could remove any one of the items with that x-value.\r\n *\r\n * @param x the x-value.\r\n\r\n * @return The item removed.\r\n */\r\n public XYDataItem remove(Number x) {\r\n return remove(indexOf(x));\r\n }\r\n\r\n /**\r\n * Removes all data items from the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n */\r\n public void clear() {\r\n if (this.data.size() > 0) {\r\n this.data.clear();\r\n this.minX = Double.NaN;\r\n this.maxX = Double.NaN;\r\n this.minY = Double.NaN;\r\n this.maxY = Double.NaN;\r\n fireSeriesChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Return the data item with the specified index.\r\n *\r\n * @param index the index.\r\n *\r\n * @return The data item with the specified index.\r\n */\r\n public XYDataItem getDataItem(int index) {\r\n XYDataItem item = (XYDataItem) this.data.get(index);\r\n return (XYDataItem) item.clone();\r\n }\r\n\r\n /**\r\n * Return the data item with the specified index.\r\n *\r\n * @param index the index.\r\n *\r\n * @return The data item with the specified index.\r\n *\r\n * @since 1.0.14\r\n */\r\n XYDataItem getRawDataItem(int index) {\r\n return (XYDataItem) this.data.get(index);\r\n }\r\n\r\n /**\r\n * Returns the x-value at the specified index.\r\n *\r\n * @param index the index (zero-based).\r\n *\r\n * @return The x-value (never <code>null</code>).\r\n */\r\n public Number getX(int index) {\r\n return getRawDataItem(index).getX();\r\n }\r\n\r\n /**\r\n * Returns the y-value at the specified index.\r\n *\r\n * @param index the index (zero-based).\r\n *\r\n * @return The y-value (possibly <code>null</code>).\r\n */\r\n public Number getY(int index) {\r\n return getRawDataItem(index).getY();\r\n }\r\n\r\n /**\r\n * Updates the value of an item in the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param index the item (zero based index).\r\n * @param y the new value (<code>null</code> permitted).\r\n *\r\n * @deprecated Renamed {@link #updateByIndex(int, Number)} to avoid\r\n * confusion with the {@link #update(Number, Number)} method.\r\n */\r\n public void update(int index, Number y) {\r\n XYDataItem item = getRawDataItem(index);\r\n\r\n // figure out if we need to iterate through all the y-values\r\n boolean iterate = false;\r\n double oldY = item.getYValue();\r\n if (!Double.isNaN(oldY)) {\r\n iterate = oldY <= this.minY || oldY >= this.maxY;\r\n }\r\n item.setY(y);\r\n\r\n if (iterate) {\r\n findBoundsByIteration();\r\n }\r\n else if (y != null) {\r\n double yy = y.doubleValue();\r\n this.minY = minIgnoreNaN(this.minY, yy);\r\n this.maxY = maxIgnoreNaN(this.maxY, yy);\r\n }\r\n fireSeriesChanged();\r\n }\r\n\r\n /**\r\n * A function to find the minimum of two values, but ignoring any\r\n * Double.NaN values.\r\n *\r\n * @param a the first value.\r\n * @param b the second value.\r\n *\r\n * @return The minimum of the two values.\r\n */\r\n private double minIgnoreNaN(double a, double b) {\r\n if (Double.isNaN(a)) {\r\n return b;\r\n }\r\n if (Double.isNaN(b)) {\r\n return a;\r\n }\r\n return Math.min(a, b);\r\n }\r\n\r\n /**\r\n * A function to find the maximum of two values, but ignoring any\r\n * Double.NaN values.\r\n *\r\n * @param a the first value.\r\n * @param b the second value.\r\n *\r\n * @return The maximum of the two values.\r\n */\r\n private double maxIgnoreNaN(double a, double b) {\r\n if (Double.isNaN(a)) {\r\n return b;\r\n }\r\n if (Double.isNaN(b)) {\r\n return a;\r\n }\r\n return Math.max(a, b);\r\n }\r\n\r\n /**\r\n * Updates the value of an item in the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param index the item (zero based index).\r\n * @param y the new value (<code>null</code> permitted).\r\n *\r\n * @since 1.0.1\r\n */\r\n public void updateByIndex(int index, Number y) {\r\n update(index, y);\r\n }\r\n\r\n /**\r\n * Updates an item in the series.\r\n *\r\n * @param x the x-value (<code>null</code> not permitted).\r\n * @param y the y-value (<code>null</code> permitted).\r\n *\r\n * @throws SeriesException if there is no existing item with the specified\r\n * x-value.\r\n */\r\n public void update(Number x, Number y) {\r\n int index = indexOf(x);\r\n if (index < 0) {\r\n throw new SeriesException(\"No observation for x = \" + x);\r\n }\r\n updateByIndex(index, y);\r\n }\r\n\r\n /**\r\n * Adds or updates an item in the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param x the x-value.\r\n * @param y the y-value.\r\n *\r\n * @return The item that was overwritten, if any.\r\n *\r\n * @since 1.0.10\r\n */\r\n public XYDataItem addOrUpdate(double x, double y) {\r\n return addOrUpdate(new Double(x), new Double(y));\r\n }\r\n\r\n /**\r\n * Adds or updates an item in the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param x the x-value (<code>null</code> not permitted).\r\n * @param y the y-value (<code>null</code> permitted).\r\n *\r\n * @return A copy of the overwritten data item, or <code>null</code> if no\r\n * item was overwritten.\r\n */\r\n public XYDataItem addOrUpdate(Number x, Number y) {\r\n // defer argument checking\r\n return addOrUpdate(new XYDataItem(x, y));\r\n }\r\n\r\n /**\r\n * Adds or updates an item in the series and sends a\r\n * {@link SeriesChangeEvent} to all registered listeners.\r\n *\r\n * @param item the data item (<code>null</code> not permitted).\r\n *\r\n * @return A copy of the overwritten data item, or <code>null</code> if no\r\n * item was overwritten.\r\n *\r\n * @since 1.0.14\r\n */\r\n public XYDataItem addOrUpdate(XYDataItem item) {\r\n ParamChecks.nullNotPermitted(item, \"item\");\r\n if (this.allowDuplicateXValues) {\r\n add(item);\r\n return null;\r\n }\r\n\r\n // if we get to here, we know that duplicate X values are not permitted\r\n XYDataItem overwritten = null;\r\n int index = indexOf(item.getX());\r\n if (index >= 0) {\r\n XYDataItem existing = (XYDataItem) this.data.get(index);\r\n overwritten = (XYDataItem) existing.clone();\r\n // figure out if we need to iterate through all the y-values\r\n boolean iterate = false;\r\n double oldY = existing.getYValue();\r\n if (!Double.isNaN(oldY)) {\r\n iterate = oldY <= this.minY || oldY >= this.maxY;\r\n }\r\n existing.setY(item.getY());\r\n\r\n if (iterate) {\r\n findBoundsByIteration();\r\n }\r\n else if (item.getY() != null) {\r\n double yy = item.getY().doubleValue();\r\n this.minY = minIgnoreNaN(this.minY, yy);\r\n this.maxY = maxIgnoreNaN(this.maxY, yy);\r\n }\r\n }\r\n else {\r\n // if the series is sorted, the negative index is a result from\r\n // Collections.binarySearch() and tells us where to insert the\r\n // new item...otherwise it will be just -1 and we should just\r\n // append the value to the list...\r\n item = (XYDataItem) item.clone();\r\n if (this.autoSort) {\r\n this.data.add(-index - 1, item);\r\n }\r\n else {\r\n this.data.add(item);\r\n }\r\n updateBoundsForAddedItem(item);\r\n\r\n // check if this addition will exceed the maximum item count...\r\n if (getItemCount() > this.maximumItemCount) {\r\n XYDataItem removed = (XYDataItem) this.data.remove(0);\r\n updateBoundsForRemovedItem(removed);\r\n }\r\n }\r\n fireSeriesChanged();\r\n return overwritten;\r\n }\r\n\r\n /**\r\n * Returns the index of the item with the specified x-value, or a negative\r\n * index if the series does not contain an item with that x-value. Be\r\n * aware that for an unsorted series, the index is found by iterating\r\n * through all items in the series.\r\n *\r\n * @param x the x-value (<code>null</code> not permitted).\r\n *\r\n * @return The index.\r\n */\r\n public int indexOf(Number x) {\r\n if (this.autoSort) {\r\n return Collections.binarySearch(this.data, new XYDataItem(x, null));\r\n }\r\n else {\r\n for (int i = 0; i < this.data.size(); i++) {\r\n XYDataItem item = (XYDataItem) this.data.get(i);\r\n if (item.getX().equals(x)) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n }\r\n }\r\n\r\n /**\r\n * Returns a new array containing the x and y values from this series.\r\n *\r\n * @return A new array containing the x and y values from this series.\r\n *\r\n * @since 1.0.4\r\n */\r\n public double[][] toArray() {\r\n int itemCount = getItemCount();\r\n double[][] result = new double[2][itemCount];\r\n for (int i = 0; i < itemCount; i++) {\r\n result[0][i] = this.getX(i).doubleValue();\r\n Number y = getY(i);\r\n if (y != null) {\r\n result[1][i] = y.doubleValue();\r\n }\r\n else {\r\n result[1][i] = Double.NaN;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a clone of the series.\r\n *\r\n * @return A clone of the series.\r\n *\r\n * @throws CloneNotSupportedException if there is a cloning problem.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n XYSeries clone = (XYSeries) super.clone();\r\n clone.data = (List) ObjectUtilities.deepClone(this.data);\r\n return clone;\r\n }\r\n\r\n /**\r\n * Creates a new series by copying a subset of the data in this time series.\r\n *\r\n * @param start the index of the first item to copy.\r\n * @param end the index of the last item to copy.\r\n *\r\n * @return A series containing a copy of this series from start until end.\r\n *\r\n * @throws CloneNotSupportedException if there is a cloning problem.\r\n */\r\n public XYSeries createCopy(int start, int end)\r\n throws CloneNotSupportedException {\r\n\r\n XYSeries copy = (XYSeries) super.clone();\r\n copy.data = new java.util.ArrayList();\r\n if (this.data.size() > 0) {\r\n for (int index = start; index <= end; index++) {\r\n XYDataItem item = (XYDataItem) this.data.get(index);\r\n XYDataItem clone = (XYDataItem) item.clone();\r\n try {\r\n copy.add(clone);\r\n }\r\n catch (SeriesException e) {\r\n throw new RuntimeException(\r\n \"Unable to add cloned data item.\", e);\r\n }\r\n }\r\n }\r\n return copy;\r\n\r\n }\r\n\r\n /**\r\n * Tests this series for equality with an arbitrary object.\r\n *\r\n * @param obj the object to test against for equality\r\n * (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof XYSeries)) {\r\n return false;\r\n }\r\n if (!super.equals(obj)) {\r\n return false;\r\n }\r\n XYSeries that = (XYSeries) obj;\r\n if (this.maximumItemCount != that.maximumItemCount) {\r\n return false;\r\n }\r\n if (this.autoSort != that.autoSort) {\r\n return false;\r\n }\r\n if (this.allowDuplicateXValues != that.allowDuplicateXValues) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.data, that.data)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result = super.hashCode();\r\n // it is too slow to look at every data item, so let's just look at\r\n // the first, middle and last items...\r\n int count = getItemCount();\r\n if (count > 0) {\r\n XYDataItem item = getRawDataItem(0);\r\n result = 29 * result + item.hashCode();\r\n }\r\n if (count > 1) {\r\n XYDataItem item = getRawDataItem(count - 1);\r\n result = 29 * result + item.hashCode();\r\n }\r\n if (count > 2) {\r\n XYDataItem item = getRawDataItem(count / 2);\r\n result = 29 * result + item.hashCode();\r\n }\r\n result = 29 * result + this.maximumItemCount;\r\n result = 29 * result + (this.autoSort ? 1 : 0);\r\n result = 29 * result + (this.allowDuplicateXValues ? 1 : 0);\r\n return result;\r\n }\r\n\r\n}\r" }, { "identifier": "XYSeriesCollection", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/xy/XYSeriesCollection.java", "snippet": "public class XYSeriesCollection extends AbstractIntervalXYDataset\r\n implements IntervalXYDataset, DomainInfo, RangeInfo, \r\n VetoableChangeListener, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -7590013825931496766L;\r\n\r\n /** The series that are included in the collection. */\r\n private List data;\r\n\r\n /** The interval delegate (used to calculate the start and end x-values). */\r\n private IntervalXYDelegate intervalDelegate;\r\n\r\n /**\r\n * Constructs an empty dataset.\r\n */\r\n public XYSeriesCollection() {\r\n this(null);\r\n }\r\n\r\n /**\r\n * Constructs a dataset and populates it with a single series.\r\n *\r\n * @param series the series (<code>null</code> ignored).\r\n */\r\n public XYSeriesCollection(XYSeries series) {\r\n this.data = new java.util.ArrayList();\r\n this.intervalDelegate = new IntervalXYDelegate(this, false);\r\n addChangeListener(this.intervalDelegate);\r\n if (series != null) {\r\n this.data.add(series);\r\n series.addChangeListener(this);\r\n series.addVetoableChangeListener(this);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the order of the domain (X) values, if this is known.\r\n *\r\n * @return The domain order.\r\n */\r\n @Override\r\n public DomainOrder getDomainOrder() {\r\n int seriesCount = getSeriesCount();\r\n for (int i = 0; i < seriesCount; i++) {\r\n XYSeries s = getSeries(i);\r\n if (!s.getAutoSort()) {\r\n return DomainOrder.NONE; // we can't be sure of the order\r\n }\r\n }\r\n return DomainOrder.ASCENDING;\r\n }\r\n\r\n /**\r\n * Adds a series to the collection and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n * \r\n * @throws IllegalArgumentException if the key for the series is null or\r\n * not unique within the dataset.\r\n */\r\n public void addSeries(XYSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n if (getSeriesIndex(series.getKey()) >= 0) {\r\n throw new IllegalArgumentException(\r\n \"This dataset already contains a series with the key \" \r\n + series.getKey());\r\n }\r\n this.data.add(series);\r\n series.addChangeListener(this);\r\n series.addVetoableChangeListener(this);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes a series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series index (zero-based).\r\n */\r\n public void removeSeries(int series) {\r\n if ((series < 0) || (series >= getSeriesCount())) {\r\n throw new IllegalArgumentException(\"Series index out of bounds.\");\r\n }\r\n XYSeries s = (XYSeries) this.data.get(series);\r\n if (s != null) {\r\n removeSeries(s);\r\n }\r\n }\r\n\r\n /**\r\n * Removes a series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n */\r\n public void removeSeries(XYSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n if (this.data.contains(series)) {\r\n series.removeChangeListener(this);\r\n series.removeVetoableChangeListener(this);\r\n this.data.remove(series);\r\n fireDatasetChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Removes all the series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n */\r\n public void removeAllSeries() {\r\n // Unregister the collection as a change listener to each series in\r\n // the collection.\r\n for (int i = 0; i < this.data.size(); i++) {\r\n XYSeries series = (XYSeries) this.data.get(i);\r\n series.removeChangeListener(this);\r\n series.removeVetoableChangeListener(this);\r\n }\r\n\r\n // Remove all the series from the collection and notify listeners.\r\n this.data.clear();\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns the number of series in the collection.\r\n *\r\n * @return The series count.\r\n */\r\n @Override\r\n public int getSeriesCount() {\r\n return this.data.size();\r\n }\r\n\r\n /**\r\n * Returns a list of all the series in the collection.\r\n *\r\n * @return The list (which is unmodifiable).\r\n */\r\n public List getSeries() {\r\n return Collections.unmodifiableList(this.data);\r\n }\r\n\r\n /**\r\n * Returns the index of the specified series, or -1 if that series is not\r\n * present in the dataset.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n *\r\n * @return The series index.\r\n *\r\n * @since 1.0.6\r\n */\r\n public int indexOf(XYSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n return this.data.indexOf(series);\r\n }\r\n\r\n /**\r\n * Returns a series from the collection.\r\n *\r\n * @param series the series index (zero-based).\r\n *\r\n * @return The series.\r\n *\r\n * @throws IllegalArgumentException if <code>series</code> is not in the\r\n * range <code>0</code> to <code>getSeriesCount() - 1</code>.\r\n */\r\n public XYSeries getSeries(int series) {\r\n if ((series < 0) || (series >= getSeriesCount())) {\r\n throw new IllegalArgumentException(\"Series index out of bounds\");\r\n }\r\n return (XYSeries) this.data.get(series);\r\n }\r\n\r\n /**\r\n * Returns a series from the collection.\r\n *\r\n * @param key the key (<code>null</code> not permitted).\r\n *\r\n * @return The series with the specified key.\r\n *\r\n * @throws UnknownKeyException if <code>key</code> is not found in the\r\n * collection.\r\n *\r\n * @since 1.0.9\r\n */\r\n public XYSeries getSeries(Comparable key) {\r\n ParamChecks.nullNotPermitted(key, \"key\");\r\n Iterator iterator = this.data.iterator();\r\n while (iterator.hasNext()) {\r\n XYSeries series = (XYSeries) iterator.next();\r\n if (key.equals(series.getKey())) {\r\n return series;\r\n }\r\n }\r\n throw new UnknownKeyException(\"Key not found: \" + key);\r\n }\r\n\r\n /**\r\n * Returns the key for a series.\r\n *\r\n * @param series the series index (in the range <code>0</code> to\r\n * <code>getSeriesCount() - 1</code>).\r\n *\r\n * @return The key for a series.\r\n *\r\n * @throws IllegalArgumentException if <code>series</code> is not in the\r\n * specified range.\r\n */\r\n @Override\r\n public Comparable getSeriesKey(int series) {\r\n // defer argument checking\r\n return getSeries(series).getKey();\r\n }\r\n\r\n /**\r\n * Returns the index of the series with the specified key, or -1 if no\r\n * series has that key.\r\n * \r\n * @param key the key (<code>null</code> not permitted).\r\n * \r\n * @return The index.\r\n * \r\n * @since 1.0.14\r\n */\r\n public int getSeriesIndex(Comparable key) {\r\n ParamChecks.nullNotPermitted(key, \"key\");\r\n int seriesCount = getSeriesCount();\r\n for (int i = 0; i < seriesCount; i++) {\r\n XYSeries series = (XYSeries) this.data.get(i);\r\n if (key.equals(series.getKey())) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the number of items in the specified series.\r\n *\r\n * @param series the series (zero-based index).\r\n *\r\n * @return The item count.\r\n *\r\n * @throws IllegalArgumentException if <code>series</code> is not in the\r\n * range <code>0</code> to <code>getSeriesCount() - 1</code>.\r\n */\r\n @Override\r\n public int getItemCount(int series) {\r\n // defer argument checking\r\n return getSeries(series).getItemCount();\r\n }\r\n\r\n /**\r\n * Returns the x-value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The value.\r\n */\r\n @Override\r\n public Number getX(int series, int item) {\r\n XYSeries s = (XYSeries) this.data.get(series);\r\n return s.getX(item);\r\n }\r\n\r\n /**\r\n * Returns the starting X value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The starting X value.\r\n */\r\n @Override\r\n public Number getStartX(int series, int item) {\r\n return this.intervalDelegate.getStartX(series, item);\r\n }\r\n\r\n /**\r\n * Returns the ending X value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The ending X value.\r\n */\r\n @Override\r\n public Number getEndX(int series, int item) {\r\n return this.intervalDelegate.getEndX(series, item);\r\n }\r\n\r\n /**\r\n * Returns the y-value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param index the index of the item of interest (zero-based).\r\n *\r\n * @return The value (possibly <code>null</code>).\r\n */\r\n @Override\r\n public Number getY(int series, int index) {\r\n XYSeries s = (XYSeries) this.data.get(series);\r\n return s.getY(index);\r\n }\r\n\r\n /**\r\n * Returns the starting Y value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The starting Y value.\r\n */\r\n @Override\r\n public Number getStartY(int series, int item) {\r\n return getY(series, item);\r\n }\r\n\r\n /**\r\n * Returns the ending Y value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The ending Y value.\r\n */\r\n @Override\r\n public Number getEndY(int series, int item) {\r\n return getY(series, item);\r\n }\r\n\r\n /**\r\n * Tests this collection for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof XYSeriesCollection)) {\r\n return false;\r\n }\r\n XYSeriesCollection that = (XYSeriesCollection) obj;\r\n if (!this.intervalDelegate.equals(that.intervalDelegate)) {\r\n return false;\r\n }\r\n return ObjectUtilities.equal(this.data, that.data);\r\n }\r\n\r\n /**\r\n * Returns a clone of this instance.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if there is a problem.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n XYSeriesCollection clone = (XYSeriesCollection) super.clone();\r\n clone.data = (List) ObjectUtilities.deepClone(this.data);\r\n clone.intervalDelegate\r\n = (IntervalXYDelegate) this.intervalDelegate.clone();\r\n return clone;\r\n }\r\n\r\n /**\r\n * Returns a hash code.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int hash = 5;\r\n hash = HashUtilities.hashCode(hash, this.intervalDelegate);\r\n hash = HashUtilities.hashCode(hash, this.data);\r\n return hash;\r\n }\r\n\r\n /**\r\n * Returns the minimum x-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The minimum value.\r\n */\r\n @Override\r\n public double getDomainLowerBound(boolean includeInterval) {\r\n if (includeInterval) {\r\n return this.intervalDelegate.getDomainLowerBound(includeInterval);\r\n }\r\n double result = Double.NaN;\r\n int seriesCount = getSeriesCount();\r\n for (int s = 0; s < seriesCount; s++) {\r\n XYSeries series = getSeries(s);\r\n double lowX = series.getMinX();\r\n if (Double.isNaN(result)) {\r\n result = lowX;\r\n }\r\n else {\r\n if (!Double.isNaN(lowX)) {\r\n result = Math.min(result, lowX);\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the maximum x-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The maximum value.\r\n */\r\n @Override\r\n public double getDomainUpperBound(boolean includeInterval) {\r\n if (includeInterval) {\r\n return this.intervalDelegate.getDomainUpperBound(includeInterval);\r\n }\r\n else {\r\n double result = Double.NaN;\r\n int seriesCount = getSeriesCount();\r\n for (int s = 0; s < seriesCount; s++) {\r\n XYSeries series = getSeries(s);\r\n double hiX = series.getMaxX();\r\n if (Double.isNaN(result)) {\r\n result = hiX;\r\n }\r\n else {\r\n if (!Double.isNaN(hiX)) {\r\n result = Math.max(result, hiX);\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range of the values in this dataset's domain.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The range (or <code>null</code> if the dataset contains no\r\n * values).\r\n */\r\n @Override\r\n public Range getDomainBounds(boolean includeInterval) {\r\n if (includeInterval) {\r\n return this.intervalDelegate.getDomainBounds(includeInterval);\r\n }\r\n else {\r\n double lower = Double.POSITIVE_INFINITY;\r\n double upper = Double.NEGATIVE_INFINITY;\r\n int seriesCount = getSeriesCount();\r\n for (int s = 0; s < seriesCount; s++) {\r\n XYSeries series = getSeries(s);\r\n double minX = series.getMinX();\r\n if (!Double.isNaN(minX)) {\r\n lower = Math.min(lower, minX);\r\n }\r\n double maxX = series.getMaxX();\r\n if (!Double.isNaN(maxX)) {\r\n upper = Math.max(upper, maxX);\r\n }\r\n }\r\n if (lower > upper) {\r\n return null;\r\n }\r\n else {\r\n return new Range(lower, upper);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the interval width. This is used to calculate the start and end\r\n * x-values, if/when the dataset is used as an {@link IntervalXYDataset}.\r\n *\r\n * @return The interval width.\r\n */\r\n public double getIntervalWidth() {\r\n return this.intervalDelegate.getIntervalWidth();\r\n }\r\n\r\n /**\r\n * Sets the interval width and sends a {@link DatasetChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param width the width (negative values not permitted).\r\n */\r\n public void setIntervalWidth(double width) {\r\n if (width < 0.0) {\r\n throw new IllegalArgumentException(\"Negative 'width' argument.\");\r\n }\r\n this.intervalDelegate.setFixedIntervalWidth(width);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns the interval position factor.\r\n *\r\n * @return The interval position factor.\r\n */\r\n public double getIntervalPositionFactor() {\r\n return this.intervalDelegate.getIntervalPositionFactor();\r\n }\r\n\r\n /**\r\n * Sets the interval position factor. This controls where the x-value is in\r\n * relation to the interval surrounding the x-value (0.0 means the x-value\r\n * will be positioned at the start, 0.5 in the middle, and 1.0 at the end).\r\n *\r\n * @param factor the factor.\r\n */\r\n public void setIntervalPositionFactor(double factor) {\r\n this.intervalDelegate.setIntervalPositionFactor(factor);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns whether the interval width is automatically calculated or not.\r\n *\r\n * @return Whether the width is automatically calculated or not.\r\n */\r\n public boolean isAutoWidth() {\r\n return this.intervalDelegate.isAutoWidth();\r\n }\r\n\r\n /**\r\n * Sets the flag that indicates whether the interval width is automatically\r\n * calculated or not.\r\n *\r\n * @param b a boolean.\r\n */\r\n public void setAutoWidth(boolean b) {\r\n this.intervalDelegate.setAutoWidth(b);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns the range of the values in this dataset's range.\r\n *\r\n * @param includeInterval ignored.\r\n *\r\n * @return The range (or <code>null</code> if the dataset contains no\r\n * values).\r\n */\r\n @Override\r\n public Range getRangeBounds(boolean includeInterval) {\r\n double lower = Double.POSITIVE_INFINITY;\r\n double upper = Double.NEGATIVE_INFINITY;\r\n int seriesCount = getSeriesCount();\r\n for (int s = 0; s < seriesCount; s++) {\r\n XYSeries series = getSeries(s);\r\n double minY = series.getMinY();\r\n if (!Double.isNaN(minY)) {\r\n lower = Math.min(lower, minY);\r\n }\r\n double maxY = series.getMaxY();\r\n if (!Double.isNaN(maxY)) {\r\n upper = Math.max(upper, maxY);\r\n }\r\n }\r\n if (lower > upper) {\r\n return null;\r\n }\r\n else {\r\n return new Range(lower, upper);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the minimum y-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * y-interval is taken into account.\r\n *\r\n * @return The minimum value.\r\n */\r\n @Override\r\n public double getRangeLowerBound(boolean includeInterval) {\r\n double result = Double.NaN;\r\n int seriesCount = getSeriesCount();\r\n for (int s = 0; s < seriesCount; s++) {\r\n XYSeries series = getSeries(s);\r\n double lowY = series.getMinY();\r\n if (Double.isNaN(result)) {\r\n result = lowY;\r\n }\r\n else {\r\n if (!Double.isNaN(lowY)) {\r\n result = Math.min(result, lowY);\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the maximum y-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * y-interval is taken into account.\r\n *\r\n * @return The maximum value.\r\n */\r\n @Override\r\n public double getRangeUpperBound(boolean includeInterval) {\r\n double result = Double.NaN;\r\n int seriesCount = getSeriesCount();\r\n for (int s = 0; s < seriesCount; s++) {\r\n XYSeries series = getSeries(s);\r\n double hiY = series.getMaxY();\r\n if (Double.isNaN(result)) {\r\n result = hiY;\r\n }\r\n else {\r\n if (!Double.isNaN(hiY)) {\r\n result = Math.max(result, hiY);\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Receives notification that the key for one of the series in the \r\n * collection has changed, and vetos it if the key is already present in \r\n * the collection.\r\n * \r\n * @param e the event.\r\n * \r\n * @since 1.0.14\r\n */\r\n @Override\r\n public void vetoableChange(PropertyChangeEvent e)\r\n throws PropertyVetoException {\r\n // if it is not the series name, then we have no interest\r\n if (!\"Key\".equals(e.getPropertyName())) {\r\n return;\r\n }\r\n \r\n // to be defensive, let's check that the source series does in fact\r\n // belong to this collection\r\n Series s = (Series) e.getSource();\r\n if (getSeriesIndex(s.getKey()) == -1) {\r\n throw new IllegalStateException(\"Receiving events from a series \" +\r\n \"that does not belong to this collection.\");\r\n }\r\n // check if the new series name already exists for another series\r\n Comparable key = (Comparable) e.getNewValue();\r\n if (getSeriesIndex(key) >= 0) {\r\n throw new PropertyVetoException(\"Duplicate key2\", e);\r\n }\r\n }\r\n\r\n}\r" } ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import java.awt.Rectangle; import org.jfree.chart.JFreeChart; import org.jfree.chart.LegendItem; import org.jfree.chart.TestUtilities; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.util.PublicCloneable; import org.junit.Test;
94,545
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------ * XYAreaRenderer2Test.java * ------------------------ * (C) Copyright 2005-2013, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 24-May-2005 : Version 1 (DG); * 30-Nov-2006 : Extended testEquals() and testCloning() (DG); * 17-May-2007 : Added testGetLegendItemSeriesIndex() (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.chart.renderer.xy; /** * Tests for the {@link XYAreaRenderer2} class. */ public class XYAreaRenderer2Test { /** * Check that the equals() method distinguishes all fields. */ @Test public void testEquals() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); XYAreaRenderer2 r2 = new XYAreaRenderer2(); assertEquals(r1, r2); r1.setOutline(!r1.isOutline()); assertFalse(r1.equals(r2)); r2.setOutline(r1.isOutline()); assertTrue(r1.equals(r2)); r1.setLegendArea(new Rectangle(1, 2, 3, 4)); assertFalse(r1.equals(r2)); r2.setLegendArea(new Rectangle(1, 2, 3, 4)); assertTrue(r1.equals(r2)); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashcode() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); XYAreaRenderer2 r2 = new XYAreaRenderer2(); assertTrue(r1.equals(r2)); int h1 = r1.hashCode(); int h2 = r2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { XYAreaRenderer2 r1 = new XYAreaRenderer2(); Rectangle rect = new Rectangle(1, 2, 3, 4); r1.setLegendArea(rect); XYAreaRenderer2 r2 = (XYAreaRenderer2) r1.clone(); assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); // check independence rect.setBounds(99, 99, 99, 99); assertFalse(r1.equals(r2)); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); assertTrue(r1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); XYAreaRenderer2 r2 = (XYAreaRenderer2) TestUtilities.serialised(r1); assertEquals(r1, r2); } /** * Draws the chart with a <code>null</code> info object to make sure that * no exceptions are thrown (particularly by code in the renderer). */ @Test public void testDrawWithNullInfo() { try { DefaultTableXYDataset dataset = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(5.0, 5.0); s1.add(10.0, 15.5); s1.add(15.0, 9.5); s1.add(20.0, 7.5); dataset.addSeries(s1); XYSeries s2 = new XYSeries("Series 2", true, false); s2.add(5.0, 5.0); s2.add(10.0, 15.5); s2.add(15.0, 9.5); s2.add(20.0, 3.5); dataset.addSeries(s2); XYPlot plot = new XYPlot(dataset,
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------ * XYAreaRenderer2Test.java * ------------------------ * (C) Copyright 2005-2013, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 24-May-2005 : Version 1 (DG); * 30-Nov-2006 : Extended testEquals() and testCloning() (DG); * 17-May-2007 : Added testGetLegendItemSeriesIndex() (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.chart.renderer.xy; /** * Tests for the {@link XYAreaRenderer2} class. */ public class XYAreaRenderer2Test { /** * Check that the equals() method distinguishes all fields. */ @Test public void testEquals() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); XYAreaRenderer2 r2 = new XYAreaRenderer2(); assertEquals(r1, r2); r1.setOutline(!r1.isOutline()); assertFalse(r1.equals(r2)); r2.setOutline(r1.isOutline()); assertTrue(r1.equals(r2)); r1.setLegendArea(new Rectangle(1, 2, 3, 4)); assertFalse(r1.equals(r2)); r2.setLegendArea(new Rectangle(1, 2, 3, 4)); assertTrue(r1.equals(r2)); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashcode() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); XYAreaRenderer2 r2 = new XYAreaRenderer2(); assertTrue(r1.equals(r2)); int h1 = r1.hashCode(); int h2 = r2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { XYAreaRenderer2 r1 = new XYAreaRenderer2(); Rectangle rect = new Rectangle(1, 2, 3, 4); r1.setLegendArea(rect); XYAreaRenderer2 r2 = (XYAreaRenderer2) r1.clone(); assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); // check independence rect.setBounds(99, 99, 99, 99); assertFalse(r1.equals(r2)); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); assertTrue(r1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { XYAreaRenderer2 r1 = new XYAreaRenderer2(); XYAreaRenderer2 r2 = (XYAreaRenderer2) TestUtilities.serialised(r1); assertEquals(r1, r2); } /** * Draws the chart with a <code>null</code> info object to make sure that * no exceptions are thrown (particularly by code in the renderer). */ @Test public void testDrawWithNullInfo() { try { DefaultTableXYDataset dataset = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(5.0, 5.0); s1.add(10.0, 15.5); s1.add(15.0, 9.5); s1.add(20.0, 7.5); dataset.addSeries(s1); XYSeries s2 = new XYSeries("Series 2", true, false); s2.add(5.0, 5.0); s2.add(10.0, 15.5); s2.add(15.0, 9.5); s2.add(20.0, 3.5); dataset.addSeries(s2); XYPlot plot = new XYPlot(dataset,
new NumberAxis("X"), new NumberAxis("Y"),
3
2023-12-24 12:36:47+00:00
128k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/swt/org/jfree/experimental/chart/swt/ChartComposite.java
[ { "identifier": "ChartMouseEvent", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/ChartMouseEvent.java", "snippet": "public class ChartMouseEvent extends EventObject implements Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -682393837314562149L;\r\n\r\n /** The chart that the mouse event relates to. */\r\n private JFreeChart chart;\r\n\r\n /** The Java mouse event that triggered this event. */\r\n private MouseEvent trigger;\r\n\r\n /** The chart entity (if any). */\r\n private ChartEntity entity;\r\n\r\n /**\r\n * Constructs a new event.\r\n *\r\n * @param chart the source chart (<code>null</code> not permitted).\r\n * @param trigger the mouse event that triggered this event\r\n * (<code>null</code> not permitted).\r\n * @param entity the chart entity (if any) under the mouse point\r\n * (<code>null</code> permitted).\r\n */\r\n public ChartMouseEvent(JFreeChart chart, MouseEvent trigger,\r\n ChartEntity entity) {\r\n super(chart);\r\n this.chart = chart;\r\n this.trigger = trigger;\r\n this.entity = entity;\r\n }\r\n\r\n /**\r\n * Returns the chart that the mouse event relates to.\r\n *\r\n * @return The chart (never <code>null</code>).\r\n */\r\n public JFreeChart getChart() {\r\n return this.chart;\r\n }\r\n\r\n /**\r\n * Returns the mouse event that triggered this event.\r\n *\r\n * @return The event (never <code>null</code>).\r\n */\r\n public MouseEvent getTrigger() {\r\n return this.trigger;\r\n }\r\n\r\n /**\r\n * Returns the chart entity (if any) under the mouse point.\r\n *\r\n * @return The chart entity (possibly <code>null</code>).\r\n */\r\n public ChartEntity getEntity() {\r\n return this.entity;\r\n }\r\n\r\n}\r" }, { "identifier": "ChartMouseListener", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/ChartMouseListener.java", "snippet": "public interface ChartMouseListener extends EventListener {\r\n\r\n /**\r\n * Callback method for receiving notification of a mouse click on a chart.\r\n *\r\n * @param event information about the event.\r\n */\r\n void chartMouseClicked(ChartMouseEvent event);\r\n\r\n /**\r\n * Callback method for receiving notification of a mouse movement on a\r\n * chart.\r\n *\r\n * @param event information about the event.\r\n */\r\n void chartMouseMoved(ChartMouseEvent event);\r\n\r\n}\r" }, { "identifier": "ChartRenderingInfo", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/ChartRenderingInfo.java", "snippet": "public class ChartRenderingInfo implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 2751952018173406822L;\r\n\r\n /** The area in which the chart is drawn. */\r\n private transient Rectangle2D chartArea;\r\n\r\n /** Rendering info for the chart's plot (and subplots, if any). */\r\n private PlotRenderingInfo plotInfo;\r\n\r\n /**\r\n * Storage for the chart entities. Since retaining entity information for\r\n * charts with a large number of data points consumes a lot of memory, it\r\n * is intended that you can set this to <code>null</code> to prevent the\r\n * information being collected.\r\n */\r\n private EntityCollection entities;\r\n\r\n /**\r\n * Constructs a new ChartRenderingInfo structure that can be used to\r\n * collect information about the dimensions of a rendered chart.\r\n */\r\n public ChartRenderingInfo() {\r\n this(new StandardEntityCollection());\r\n }\r\n\r\n /**\r\n * Constructs a new instance. If an entity collection is supplied, it will\r\n * be populated with information about the entities in a chart. If it is\r\n * <code>null</code>, no entity information (including tool tips) will\r\n * be collected.\r\n *\r\n * @param entities an entity collection (<code>null</code> permitted).\r\n */\r\n public ChartRenderingInfo(EntityCollection entities) {\r\n this.chartArea = new Rectangle2D.Double();\r\n this.plotInfo = new PlotRenderingInfo(this);\r\n this.entities = entities;\r\n }\r\n\r\n /**\r\n * Returns the area in which the chart was drawn.\r\n *\r\n * @return The area in which the chart was drawn.\r\n *\r\n * @see #setChartArea(Rectangle2D)\r\n */\r\n public Rectangle2D getChartArea() {\r\n return this.chartArea;\r\n }\r\n\r\n /**\r\n * Sets the area in which the chart was drawn.\r\n *\r\n * @param area the chart area.\r\n *\r\n * @see #getChartArea()\r\n */\r\n public void setChartArea(Rectangle2D area) {\r\n this.chartArea.setRect(area);\r\n }\r\n\r\n /**\r\n * Returns the collection of entities maintained by this instance.\r\n *\r\n * @return The entity collection (possibly <code>null</code>).\r\n *\r\n * @see #setEntityCollection(EntityCollection)\r\n */\r\n public EntityCollection getEntityCollection() {\r\n return this.entities;\r\n }\r\n\r\n /**\r\n * Sets the entity collection.\r\n *\r\n * @param entities the entity collection (<code>null</code> permitted).\r\n *\r\n * @see #getEntityCollection()\r\n */\r\n public void setEntityCollection(EntityCollection entities) {\r\n this.entities = entities;\r\n }\r\n\r\n /**\r\n * Clears the information recorded by this object.\r\n */\r\n public void clear() {\r\n this.chartArea.setRect(0.0, 0.0, 0.0, 0.0);\r\n this.plotInfo = new PlotRenderingInfo(this);\r\n if (this.entities != null) {\r\n this.entities.clear();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the rendering info for the chart's plot.\r\n *\r\n * @return The rendering info for the plot.\r\n */\r\n public PlotRenderingInfo getPlotInfo() {\r\n return this.plotInfo;\r\n }\r\n\r\n /**\r\n * Tests this object for equality with an arbitrary object.\r\n *\r\n * @param obj the object to test against (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof ChartRenderingInfo)) {\r\n return false;\r\n }\r\n ChartRenderingInfo that = (ChartRenderingInfo) obj;\r\n if (!ObjectUtilities.equal(this.chartArea, that.chartArea)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.plotInfo, that.plotInfo)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.entities, that.entities)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a clone of this object.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the object cannot be cloned.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n ChartRenderingInfo clone = (ChartRenderingInfo) super.clone();\r\n if (this.chartArea != null) {\r\n clone.chartArea = (Rectangle2D) this.chartArea.clone();\r\n }\r\n if (this.entities instanceof PublicCloneable) {\r\n PublicCloneable pc = (PublicCloneable) this.entities;\r\n clone.entities = (EntityCollection) pc.clone();\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeShape(this.chartArea, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.chartArea = (Rectangle2D) SerialUtilities.readShape(stream);\r\n }\r\n\r\n}\r" }, { "identifier": "ChartUtilities", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/ChartUtilities.java", "snippet": "public abstract class ChartUtilities {\r\n\r\n /**\r\n * Applies the current theme to the specified chart. This method is\r\n * provided for convenience, the theme itself is stored in the\r\n * {@link ChartFactory} class.\r\n *\r\n * @param chart the chart (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.11\r\n */\r\n public static void applyCurrentTheme(JFreeChart chart) {\r\n ChartFactory.getChartTheme().apply(chart);\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in PNG format.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsPNG(OutputStream out, JFreeChart chart,\r\n int width, int height) throws IOException {\r\n\r\n // defer argument checking...\r\n writeChartAsPNG(out, chart, width, height, null);\r\n\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in PNG format.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param encodeAlpha encode alpha?\r\n * @param compression the compression level (0-9).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsPNG(OutputStream out, JFreeChart chart,\r\n int width, int height, boolean encodeAlpha, int compression)\r\n throws IOException {\r\n\r\n // defer argument checking...\r\n ChartUtilities.writeChartAsPNG(out, chart, width, height, null,\r\n encodeAlpha, compression);\r\n\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in PNG format. This method allows\r\n * you to pass in a {@link ChartRenderingInfo} object, to collect\r\n * information about the chart dimensions/entities. You will need this\r\n * info if you want to create an HTML image map.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info the chart rendering info (<code>null</code> permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsPNG(OutputStream out, JFreeChart chart,\r\n int width, int height, ChartRenderingInfo info)\r\n throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n BufferedImage bufferedImage\r\n = chart.createBufferedImage(width, height, info);\r\n EncoderUtil.writeBufferedImage(bufferedImage, ImageFormat.PNG, out);\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in PNG format. This method allows\r\n * you to pass in a {@link ChartRenderingInfo} object, to collect\r\n * information about the chart dimensions/entities. You will need this\r\n * info if you want to create an HTML image map.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info carries back chart rendering info (<code>null</code>\r\n * permitted).\r\n * @param encodeAlpha encode alpha?\r\n * @param compression the PNG compression level (0-9).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsPNG(OutputStream out, JFreeChart chart,\r\n int width, int height, ChartRenderingInfo info,\r\n boolean encodeAlpha, int compression) throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(out, \"out\");\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n BufferedImage chartImage = chart.createBufferedImage(width, height,\r\n BufferedImage.TYPE_INT_ARGB, info);\r\n ChartUtilities.writeBufferedImageAsPNG(out, chartImage, encodeAlpha,\r\n compression);\r\n\r\n }\r\n\r\n /**\r\n * Writes a scaled version of a chart to an output stream in PNG format.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the unscaled chart width.\r\n * @param height the unscaled chart height.\r\n * @param widthScaleFactor the horizontal scale factor.\r\n * @param heightScaleFactor the vertical scale factor.\r\n *\r\n * @throws IOException if there are any I/O problems.\r\n */\r\n public static void writeScaledChartAsPNG(OutputStream out,\r\n JFreeChart chart, int width, int height, int widthScaleFactor,\r\n int heightScaleFactor) throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(out, \"out\");\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n\r\n double desiredWidth = width * widthScaleFactor;\r\n double desiredHeight = height * heightScaleFactor;\r\n double defaultWidth = width;\r\n double defaultHeight = height;\r\n boolean scale = false;\r\n\r\n // get desired width and height from somewhere then...\r\n if ((widthScaleFactor != 1) || (heightScaleFactor != 1)) {\r\n scale = true;\r\n }\r\n\r\n double scaleX = desiredWidth / defaultWidth;\r\n double scaleY = desiredHeight / defaultHeight;\r\n\r\n BufferedImage image = new BufferedImage((int) desiredWidth,\r\n (int) desiredHeight, BufferedImage.TYPE_INT_ARGB);\r\n Graphics2D g2 = image.createGraphics();\r\n\r\n if (scale) {\r\n AffineTransform saved = g2.getTransform();\r\n g2.transform(AffineTransform.getScaleInstance(scaleX, scaleY));\r\n chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth,\r\n defaultHeight), null, null);\r\n g2.setTransform(saved);\r\n g2.dispose();\r\n }\r\n else {\r\n chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth,\r\n defaultHeight), null, null);\r\n }\r\n out.write(encodeAsPNG(image));\r\n\r\n }\r\n\r\n /**\r\n * Saves a chart to the specified file in PNG format.\r\n *\r\n * @param file the file name (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void saveChartAsPNG(File file, JFreeChart chart,\r\n int width, int height) throws IOException {\r\n\r\n // defer argument checking...\r\n saveChartAsPNG(file, chart, width, height, null);\r\n\r\n }\r\n\r\n /**\r\n * Saves a chart to a file in PNG format. This method allows you to pass\r\n * in a {@link ChartRenderingInfo} object, to collect information about the\r\n * chart dimensions/entities. You will need this info if you want to\r\n * create an HTML image map.\r\n *\r\n * @param file the file (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info the chart rendering info (<code>null</code> permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void saveChartAsPNG(File file, JFreeChart chart,\r\n int width, int height, ChartRenderingInfo info)\r\n throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(file, \"file\");\r\n OutputStream out = new BufferedOutputStream(new FileOutputStream(file));\r\n try {\r\n ChartUtilities.writeChartAsPNG(out, chart, width, height, info);\r\n }\r\n finally {\r\n out.close();\r\n }\r\n }\r\n\r\n /**\r\n * Saves a chart to a file in PNG format. This method allows you to pass\r\n * in a {@link ChartRenderingInfo} object, to collect information about the\r\n * chart dimensions/entities. You will need this info if you want to\r\n * create an HTML image map.\r\n *\r\n * @param file the file (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info the chart rendering info (<code>null</code> permitted).\r\n * @param encodeAlpha encode alpha?\r\n * @param compression the PNG compression level (0-9).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void saveChartAsPNG(File file, JFreeChart chart,\r\n int width, int height, ChartRenderingInfo info, boolean encodeAlpha,\r\n int compression) throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(file, \"file\");\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n OutputStream out = new BufferedOutputStream(new FileOutputStream(file));\r\n try {\r\n writeChartAsPNG(out, chart, width, height, info, encodeAlpha,\r\n compression);\r\n }\r\n finally {\r\n out.close();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in JPEG format. Please note that\r\n * JPEG is a poor format for chart images, use PNG if possible.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsJPEG(OutputStream out,\r\n JFreeChart chart, int width, int height) throws IOException {\r\n\r\n // defer argument checking...\r\n writeChartAsJPEG(out, chart, width, height, null);\r\n\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in JPEG format. Please note that\r\n * JPEG is a poor format for chart images, use PNG if possible.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param quality the quality setting.\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsJPEG(OutputStream out, float quality,\r\n JFreeChart chart, int width, int height) throws IOException {\r\n\r\n // defer argument checking...\r\n ChartUtilities.writeChartAsJPEG(out, quality, chart, width, height,\r\n null);\r\n\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in JPEG format. This method allows\r\n * you to pass in a {@link ChartRenderingInfo} object, to collect\r\n * information about the chart dimensions/entities. You will need this\r\n * info if you want to create an HTML image map.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info the chart rendering info (<code>null</code> permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsJPEG(OutputStream out, JFreeChart chart,\r\n int width, int height, ChartRenderingInfo info)\r\n throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(out, \"out\");\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n BufferedImage image = chart.createBufferedImage(width, height,\r\n BufferedImage.TYPE_INT_RGB, info);\r\n EncoderUtil.writeBufferedImage(image, ImageFormat.JPEG, out);\r\n\r\n }\r\n\r\n /**\r\n * Writes a chart to an output stream in JPEG format. This method allows\r\n * you to pass in a {@link ChartRenderingInfo} object, to collect\r\n * information about the chart dimensions/entities. You will need this\r\n * info if you want to create an HTML image map.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param quality the output quality (0.0f to 1.0f).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info the chart rendering info (<code>null</code> permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeChartAsJPEG(OutputStream out, float quality,\r\n JFreeChart chart, int width, int height, ChartRenderingInfo info)\r\n throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(out, \"out\");\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n BufferedImage image = chart.createBufferedImage(width, height,\r\n BufferedImage.TYPE_INT_RGB, info);\r\n EncoderUtil.writeBufferedImage(image, ImageFormat.JPEG, out, quality);\r\n\r\n }\r\n\r\n /**\r\n * Saves a chart to a file in JPEG format.\r\n *\r\n * @param file the file (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void saveChartAsJPEG(File file, JFreeChart chart,\r\n int width, int height) throws IOException {\r\n\r\n // defer argument checking...\r\n saveChartAsJPEG(file, chart, width, height, null);\r\n\r\n }\r\n\r\n /**\r\n * Saves a chart to a file in JPEG format.\r\n *\r\n * @param file the file (<code>null</code> not permitted).\r\n * @param quality the JPEG quality setting.\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void saveChartAsJPEG(File file, float quality,\r\n JFreeChart chart, int width, int height) throws IOException {\r\n\r\n // defer argument checking...\r\n saveChartAsJPEG(file, quality, chart, width, height, null);\r\n\r\n }\r\n\r\n /**\r\n * Saves a chart to a file in JPEG format. This method allows you to pass\r\n * in a {@link ChartRenderingInfo} object, to collect information about the\r\n * chart dimensions/entities. You will need this info if you want to\r\n * create an HTML image map.\r\n *\r\n * @param file the file name (<code>null</code> not permitted).\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info the chart rendering info (<code>null</code> permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void saveChartAsJPEG(File file, JFreeChart chart,\r\n int width, int height, ChartRenderingInfo info) throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(file, \"file\");\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n OutputStream out = new BufferedOutputStream(new FileOutputStream(file));\r\n try {\r\n writeChartAsJPEG(out, chart, width, height, info);\r\n }\r\n finally {\r\n out.close();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Saves a chart to a file in JPEG format. This method allows you to pass\r\n * in a {@link ChartRenderingInfo} object, to collect information about the\r\n * chart dimensions/entities. You will need this info if you want to\r\n * create an HTML image map.\r\n *\r\n * @param file the file name (<code>null</code> not permitted).\r\n * @param quality the quality setting.\r\n * @param chart the chart (<code>null</code> not permitted).\r\n * @param width the image width.\r\n * @param height the image height.\r\n * @param info the chart rendering info (<code>null</code> permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void saveChartAsJPEG(File file, float quality,\r\n JFreeChart chart, int width, int height,\r\n ChartRenderingInfo info) throws IOException {\r\n\r\n ParamChecks.nullNotPermitted(file, \"file\");\r\n ParamChecks.nullNotPermitted(chart, \"chart\");\r\n OutputStream out = new BufferedOutputStream(new FileOutputStream(\r\n file));\r\n try {\r\n writeChartAsJPEG(out, quality, chart, width, height, info);\r\n }\r\n finally {\r\n out.close();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Writes a {@link BufferedImage} to an output stream in JPEG format.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param image the image (<code>null</code> not permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeBufferedImageAsJPEG(OutputStream out,\r\n BufferedImage image) throws IOException {\r\n\r\n // defer argument checking...\r\n writeBufferedImageAsJPEG(out, 0.75f, image);\r\n\r\n }\r\n\r\n /**\r\n * Writes a {@link BufferedImage} to an output stream in JPEG format.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param quality the image quality (0.0f to 1.0f).\r\n * @param image the image (<code>null</code> not permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeBufferedImageAsJPEG(OutputStream out, float quality,\r\n BufferedImage image) throws IOException {\r\n\r\n EncoderUtil.writeBufferedImage(image, ImageFormat.JPEG, out, quality);\r\n\r\n }\r\n\r\n /**\r\n * Writes a {@link BufferedImage} to an output stream in PNG format.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param image the image (<code>null</code> not permitted).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeBufferedImageAsPNG(OutputStream out,\r\n BufferedImage image) throws IOException {\r\n\r\n EncoderUtil.writeBufferedImage(image, ImageFormat.PNG, out);\r\n\r\n }\r\n\r\n /**\r\n * Writes a {@link BufferedImage} to an output stream in PNG format.\r\n *\r\n * @param out the output stream (<code>null</code> not permitted).\r\n * @param image the image (<code>null</code> not permitted).\r\n * @param encodeAlpha encode alpha?\r\n * @param compression the compression level (0-9).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeBufferedImageAsPNG(OutputStream out,\r\n BufferedImage image, boolean encodeAlpha, int compression)\r\n throws IOException {\r\n\r\n EncoderUtil.writeBufferedImage(image, ImageFormat.PNG, out,\r\n compression, encodeAlpha);\r\n }\r\n\r\n /**\r\n * Encodes a {@link BufferedImage} to PNG format.\r\n *\r\n * @param image the image (<code>null</code> not permitted).\r\n *\r\n * @return A byte array in PNG format.\r\n *\r\n * @throws IOException if there is an I/O problem.\r\n */\r\n public static byte[] encodeAsPNG(BufferedImage image) throws IOException {\r\n return EncoderUtil.encode(image, ImageFormat.PNG);\r\n }\r\n\r\n /**\r\n * Encodes a {@link BufferedImage} to PNG format.\r\n *\r\n * @param image the image (<code>null</code> not permitted).\r\n * @param encodeAlpha encode alpha?\r\n * @param compression the PNG compression level (0-9).\r\n *\r\n * @return The byte array in PNG format.\r\n *\r\n * @throws IOException if there is an I/O problem.\r\n */\r\n public static byte[] encodeAsPNG(BufferedImage image, boolean encodeAlpha,\r\n int compression) throws IOException {\r\n return EncoderUtil.encode(image, ImageFormat.PNG, compression,\r\n encodeAlpha);\r\n }\r\n\r\n /**\r\n * Writes an image map to an output stream.\r\n *\r\n * @param writer the writer (<code>null</code> not permitted).\r\n * @param name the map name (<code>null</code> not permitted).\r\n * @param info the chart rendering info (<code>null</code> not permitted).\r\n * @param useOverLibForToolTips whether to use OverLIB for tooltips\r\n * (http://www.bosrup.com/web/overlib/).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeImageMap(PrintWriter writer, String name,\r\n ChartRenderingInfo info, boolean useOverLibForToolTips)\r\n throws IOException {\r\n\r\n ToolTipTagFragmentGenerator toolTipTagFragmentGenerator;\r\n if (useOverLibForToolTips) {\r\n toolTipTagFragmentGenerator\r\n = new OverLIBToolTipTagFragmentGenerator();\r\n }\r\n else {\r\n toolTipTagFragmentGenerator\r\n = new StandardToolTipTagFragmentGenerator();\r\n }\r\n ImageMapUtilities.writeImageMap(writer, name, info,\r\n toolTipTagFragmentGenerator,\r\n new StandardURLTagFragmentGenerator());\r\n\r\n }\r\n\r\n /**\r\n * Writes an image map to the specified writer.\r\n *\r\n * @param writer the writer (<code>null</code> not permitted).\r\n * @param name the map name (<code>null</code> not permitted).\r\n * @param info the chart rendering info (<code>null</code> not permitted).\r\n * @param toolTipTagFragmentGenerator a generator for the HTML fragment\r\n * that will contain the tooltip text (<code>null</code> not permitted\r\n * if <code>info</code> contains tooltip information).\r\n * @param urlTagFragmentGenerator a generator for the HTML fragment that\r\n * will contain the URL reference (<code>null</code> not permitted if\r\n * <code>info</code> contains URLs).\r\n *\r\n * @throws IOException if there are any I/O errors.\r\n */\r\n public static void writeImageMap(PrintWriter writer, String name,\r\n ChartRenderingInfo info,\r\n ToolTipTagFragmentGenerator toolTipTagFragmentGenerator,\r\n URLTagFragmentGenerator urlTagFragmentGenerator)\r\n throws IOException {\r\n\r\n writer.println(ImageMapUtilities.getImageMap(name, info,\r\n toolTipTagFragmentGenerator, urlTagFragmentGenerator));\r\n }\r\n\r\n /**\r\n * Creates an HTML image map. This method maps to\r\n * {@link ImageMapUtilities#getImageMap(String, ChartRenderingInfo,\r\n * ToolTipTagFragmentGenerator, URLTagFragmentGenerator)}, using default\r\n * generators.\r\n *\r\n * @param name the map name (<code>null</code> not permitted).\r\n * @param info the chart rendering info (<code>null</code> not permitted).\r\n *\r\n * @return The map tag.\r\n */\r\n public static String getImageMap(String name, ChartRenderingInfo info) {\r\n return ImageMapUtilities.getImageMap(name, info,\r\n new StandardToolTipTagFragmentGenerator(),\r\n new StandardURLTagFragmentGenerator());\r\n }\r\n\r\n /**\r\n * Creates an HTML image map. This method maps directly to\r\n * {@link ImageMapUtilities#getImageMap(String, ChartRenderingInfo,\r\n * ToolTipTagFragmentGenerator, URLTagFragmentGenerator)}.\r\n *\r\n * @param name the map name (<code>null</code> not permitted).\r\n * @param info the chart rendering info (<code>null</code> not permitted).\r\n * @param toolTipTagFragmentGenerator a generator for the HTML fragment\r\n * that will contain the tooltip text (<code>null</code> not permitted\r\n * if <code>info</code> contains tooltip information).\r\n * @param urlTagFragmentGenerator a generator for the HTML fragment that\r\n * will contain the URL reference (<code>null</code> not permitted if\r\n * <code>info</code> contains URLs).\r\n *\r\n * @return The map tag.\r\n */\r\n public static String getImageMap(String name, ChartRenderingInfo info,\r\n ToolTipTagFragmentGenerator toolTipTagFragmentGenerator,\r\n URLTagFragmentGenerator urlTagFragmentGenerator) {\r\n\r\n return ImageMapUtilities.getImageMap(name, info,\r\n toolTipTagFragmentGenerator, urlTagFragmentGenerator);\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "JFreeChart", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/JFreeChart.java", "snippet": "public class JFreeChart implements Drawable, TitleChangeListener,\r\n PlotChangeListener, Serializable, Cloneable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -3470703747817429120L;\r\n\r\n /** Information about the project. */\r\n public static final ProjectInfo INFO = new JFreeChartInfo();\r\n\r\n /** The default font for titles. */\r\n public static final Font DEFAULT_TITLE_FONT\r\n = new Font(\"SansSerif\", Font.BOLD, 18);\r\n\r\n /** The default background color. */\r\n public static final Paint DEFAULT_BACKGROUND_PAINT\r\n = UIManager.getColor(\"Panel.background\");\r\n\r\n /** The default background image. */\r\n public static final Image DEFAULT_BACKGROUND_IMAGE = null;\r\n\r\n /** The default background image alignment. */\r\n public static final int DEFAULT_BACKGROUND_IMAGE_ALIGNMENT = Align.FIT;\r\n\r\n /** The default background image alpha. */\r\n public static final float DEFAULT_BACKGROUND_IMAGE_ALPHA = 0.5f;\r\n\r\n /**\r\n * The key for a rendering hint that can suppress the generation of a \r\n * shadow effect when drawing the chart. The hint value must be a \r\n * Boolean.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static final RenderingHints.Key KEY_SUPPRESS_SHADOW_GENERATION\r\n = new RenderingHints.Key(0) {\r\n @Override\r\n public boolean isCompatibleValue(Object val) {\r\n return val instanceof Boolean;\r\n }\r\n };\r\n \r\n /**\r\n * Rendering hints that will be used for chart drawing. This should never\r\n * be <code>null</code>.\r\n */\r\n private transient RenderingHints renderingHints;\r\n\r\n /** A flag that controls whether or not the chart border is drawn. */\r\n private boolean borderVisible;\r\n\r\n /** The stroke used to draw the chart border (if visible). */\r\n private transient Stroke borderStroke;\r\n\r\n /** The paint used to draw the chart border (if visible). */\r\n private transient Paint borderPaint;\r\n\r\n /** The padding between the chart border and the chart drawing area. */\r\n private RectangleInsets padding;\r\n\r\n /** The chart title (optional). */\r\n private TextTitle title;\r\n\r\n /**\r\n * The chart subtitles (zero, one or many). This field should never be\r\n * <code>null</code>.\r\n */\r\n private List subtitles;\r\n\r\n /** Draws the visual representation of the data. */\r\n private Plot plot;\r\n\r\n /** Paint used to draw the background of the chart. */\r\n private transient Paint backgroundPaint;\r\n\r\n /** An optional background image for the chart. */\r\n private transient Image backgroundImage; // todo: not serialized yet\r\n\r\n /** The alignment for the background image. */\r\n private int backgroundImageAlignment = Align.FIT;\r\n\r\n /** The alpha transparency for the background image. */\r\n private float backgroundImageAlpha = 0.5f;\r\n\r\n /** Storage for registered change listeners. */\r\n private transient EventListenerList changeListeners;\r\n\r\n /** Storage for registered progress listeners. */\r\n private transient EventListenerList progressListeners;\r\n\r\n /**\r\n * A flag that can be used to enable/disable notification of chart change\r\n * events.\r\n */\r\n private boolean notify;\r\n\r\n /**\r\n * Creates a new chart based on the supplied plot. The chart will have\r\n * a legend added automatically, but no title (although you can easily add\r\n * one later).\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(Plot plot) {\r\n this(null, null, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. A default font\r\n * ({@link #DEFAULT_TITLE_FONT}) is used for the title, and the chart will\r\n * have a legend added automatically.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(String title, Plot plot) {\r\n this(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. The\r\n * <code>createLegend</code> argument specifies whether or not a legend\r\n * should be added to the chart.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param titleFont the font for displaying the chart title\r\n * (<code>null</code> permitted).\r\n * @param plot controller of the visual representation of the data\r\n * (<code>null</code> not permitted).\r\n * @param createLegend a flag indicating whether or not a legend should\r\n * be created for the chart.\r\n */\r\n public JFreeChart(String title, Font titleFont, Plot plot,\r\n boolean createLegend) {\r\n\r\n ParamChecks.nullNotPermitted(plot, \"plot\");\r\n\r\n // create storage for listeners...\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.notify = true; // default is to notify listeners when the\r\n // chart changes\r\n\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n // added the following hint because of \r\n // http://stackoverflow.com/questions/7785082/\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n this.borderVisible = false;\r\n this.borderStroke = new BasicStroke(1.0f);\r\n this.borderPaint = Color.black;\r\n\r\n this.padding = RectangleInsets.ZERO_INSETS;\r\n\r\n this.plot = plot;\r\n plot.addChangeListener(this);\r\n\r\n this.subtitles = new ArrayList();\r\n\r\n // create a legend, if requested...\r\n if (createLegend) {\r\n LegendTitle legend = new LegendTitle(this.plot);\r\n legend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));\r\n legend.setFrame(new LineBorder());\r\n legend.setBackgroundPaint(Color.white);\r\n legend.setPosition(RectangleEdge.BOTTOM);\r\n this.subtitles.add(legend);\r\n legend.addChangeListener(this);\r\n }\r\n\r\n // add the chart title, if one has been specified...\r\n if (title != null) {\r\n if (titleFont == null) {\r\n titleFont = DEFAULT_TITLE_FONT;\r\n }\r\n this.title = new TextTitle(title, titleFont);\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n this.backgroundPaint = DEFAULT_BACKGROUND_PAINT;\r\n\r\n this.backgroundImage = DEFAULT_BACKGROUND_IMAGE;\r\n this.backgroundImageAlignment = DEFAULT_BACKGROUND_IMAGE_ALIGNMENT;\r\n this.backgroundImageAlpha = DEFAULT_BACKGROUND_IMAGE_ALPHA;\r\n\r\n }\r\n\r\n /**\r\n * Returns the collection of rendering hints for the chart.\r\n *\r\n * @return The rendering hints for the chart (never <code>null</code>).\r\n *\r\n * @see #setRenderingHints(RenderingHints)\r\n */\r\n public RenderingHints getRenderingHints() {\r\n return this.renderingHints;\r\n }\r\n\r\n /**\r\n * Sets the rendering hints for the chart. These will be added (using the\r\n * {@code Graphics2D.addRenderingHints()} method) near the start of the\r\n * {@code JFreeChart.draw()} method.\r\n *\r\n * @param renderingHints the rendering hints ({@code null} not permitted).\r\n *\r\n * @see #getRenderingHints()\r\n */\r\n public void setRenderingHints(RenderingHints renderingHints) {\r\n ParamChecks.nullNotPermitted(renderingHints, \"renderingHints\");\r\n this.renderingHints = renderingHints;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setBorderVisible(boolean)\r\n */\r\n public boolean isBorderVisible() {\r\n return this.borderVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isBorderVisible()\r\n */\r\n public void setBorderVisible(boolean visible) {\r\n this.borderVisible = visible;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the chart border (if visible).\r\n *\r\n * @return The border stroke.\r\n *\r\n * @see #setBorderStroke(Stroke)\r\n */\r\n public Stroke getBorderStroke() {\r\n return this.borderStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the chart border (if visible).\r\n *\r\n * @param stroke the stroke.\r\n *\r\n * @see #getBorderStroke()\r\n */\r\n public void setBorderStroke(Stroke stroke) {\r\n this.borderStroke = stroke;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the chart border (if visible).\r\n *\r\n * @return The border paint.\r\n *\r\n * @see #setBorderPaint(Paint)\r\n */\r\n public Paint getBorderPaint() {\r\n return this.borderPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the chart border (if visible).\r\n *\r\n * @param paint the paint.\r\n *\r\n * @see #getBorderPaint()\r\n */\r\n public void setBorderPaint(Paint paint) {\r\n this.borderPaint = paint;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the padding between the chart border and the chart drawing area.\r\n *\r\n * @return The padding (never <code>null</code>).\r\n *\r\n * @see #setPadding(RectangleInsets)\r\n */\r\n public RectangleInsets getPadding() {\r\n return this.padding;\r\n }\r\n\r\n /**\r\n * Sets the padding between the chart border and the chart drawing area,\r\n * and sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param padding the padding (<code>null</code> not permitted).\r\n *\r\n * @see #getPadding()\r\n */\r\n public void setPadding(RectangleInsets padding) {\r\n ParamChecks.nullNotPermitted(padding, \"padding\");\r\n this.padding = padding;\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the main chart title. Very often a chart will have just one\r\n * title, so we make this case simple by providing accessor methods for\r\n * the main title. However, multiple titles are supported - see the\r\n * {@link #addSubtitle(Title)} method.\r\n *\r\n * @return The chart title (possibly <code>null</code>).\r\n *\r\n * @see #setTitle(TextTitle)\r\n */\r\n public TextTitle getTitle() {\r\n return this.title;\r\n }\r\n\r\n /**\r\n * Sets the main title for the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners. If you do not want a title for the\r\n * chart, set it to <code>null</code>. If you want more than one title on\r\n * a chart, use the {@link #addSubtitle(Title)} method.\r\n *\r\n * @param title the title (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(TextTitle title) {\r\n if (this.title != null) {\r\n this.title.removeChangeListener(this);\r\n }\r\n this.title = title;\r\n if (title != null) {\r\n title.addChangeListener(this);\r\n }\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Sets the chart title and sends a {@link ChartChangeEvent} to all\r\n * registered listeners. This is a convenience method that ends up calling\r\n * the {@link #setTitle(TextTitle)} method. If there is an existing title,\r\n * its text is updated, otherwise a new title using the default font is\r\n * added to the chart. If <code>text</code> is <code>null</code> the chart\r\n * title is set to <code>null</code>.\r\n *\r\n * @param text the title text (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(String text) {\r\n if (text != null) {\r\n if (this.title == null) {\r\n setTitle(new TextTitle(text, JFreeChart.DEFAULT_TITLE_FONT));\r\n }\r\n else {\r\n this.title.setText(text);\r\n }\r\n }\r\n else {\r\n setTitle((TextTitle) null);\r\n }\r\n }\r\n\r\n /**\r\n * Adds a legend to the plot and sends a {@link ChartChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param legend the legend (<code>null</code> not permitted).\r\n *\r\n * @see #removeLegend()\r\n */\r\n public void addLegend(LegendTitle legend) {\r\n addSubtitle(legend);\r\n }\r\n\r\n /**\r\n * Returns the legend for the chart, if there is one. Note that a chart\r\n * can have more than one legend - this method returns the first.\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #getLegend(int)\r\n */\r\n public LegendTitle getLegend() {\r\n return getLegend(0);\r\n }\r\n\r\n /**\r\n * Returns the nth legend for a chart, or <code>null</code>.\r\n *\r\n * @param index the legend index (zero-based).\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #addLegend(LegendTitle)\r\n */\r\n public LegendTitle getLegend(int index) {\r\n int seen = 0;\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title subtitle = (Title) iterator.next();\r\n if (subtitle instanceof LegendTitle) {\r\n if (seen == index) {\r\n return (LegendTitle) subtitle;\r\n }\r\n else {\r\n seen++;\r\n }\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Removes the first legend in the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @see #getLegend()\r\n */\r\n public void removeLegend() {\r\n removeSubtitle(getLegend());\r\n }\r\n\r\n /**\r\n * Returns the list of subtitles for the chart.\r\n *\r\n * @return The subtitle list (possibly empty, but never <code>null</code>).\r\n *\r\n * @see #setSubtitles(List)\r\n */\r\n public List getSubtitles() {\r\n return new ArrayList(this.subtitles);\r\n }\r\n\r\n /**\r\n * Sets the title list for the chart (completely replaces any existing\r\n * titles) and sends a {@link ChartChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param subtitles the new list of subtitles (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public void setSubtitles(List subtitles) {\r\n if (subtitles == null) {\r\n throw new NullPointerException(\"Null 'subtitles' argument.\");\r\n }\r\n setNotify(false);\r\n clearSubtitles();\r\n Iterator iterator = subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n if (t != null) {\r\n addSubtitle(t);\r\n }\r\n }\r\n setNotify(true); // this fires a ChartChangeEvent\r\n }\r\n\r\n /**\r\n * Returns the number of titles for the chart.\r\n *\r\n * @return The number of titles for the chart.\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public int getSubtitleCount() {\r\n return this.subtitles.size();\r\n }\r\n\r\n /**\r\n * Returns a chart subtitle.\r\n *\r\n * @param index the index of the chart subtitle (zero based).\r\n *\r\n * @return A chart subtitle.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public Title getSubtitle(int index) {\r\n if ((index < 0) || (index >= getSubtitleCount())) {\r\n throw new IllegalArgumentException(\"Index out of range.\");\r\n }\r\n return (Title) this.subtitles.get(index);\r\n }\r\n\r\n /**\r\n * Adds a chart subtitle, and notifies registered listeners that the chart\r\n * has been modified.\r\n *\r\n * @param subtitle the subtitle (<code>null</code> not permitted).\r\n *\r\n * @see #getSubtitle(int)\r\n */\r\n public void addSubtitle(Title subtitle) {\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Adds a subtitle at a particular position in the subtitle list, and sends\r\n * a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param index the index (in the range 0 to {@link #getSubtitleCount()}).\r\n * @param subtitle the subtitle to add (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.6\r\n */\r\n public void addSubtitle(int index, Title subtitle) {\r\n if (index < 0 || index > getSubtitleCount()) {\r\n throw new IllegalArgumentException(\r\n \"The 'index' argument is out of range.\");\r\n }\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(index, subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Clears all subtitles from the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void clearSubtitles() {\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n t.removeChangeListener(this);\r\n }\r\n this.subtitles.clear();\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Removes the specified subtitle and sends a {@link ChartChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param title the title.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void removeSubtitle(Title title) {\r\n this.subtitles.remove(title);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the plot for the chart. The plot is a class responsible for\r\n * coordinating the visual representation of the data, including the axes\r\n * (if any).\r\n *\r\n * @return The plot.\r\n */\r\n public Plot getPlot() {\r\n return this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as a {@link CategoryPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link CategoryPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public CategoryPlot getCategoryPlot() {\r\n return (CategoryPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as an {@link XYPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link XYPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public XYPlot getXYPlot() {\r\n return (XYPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns a flag that indicates whether or not anti-aliasing is used when\r\n * the chart is drawn.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAntiAlias(boolean)\r\n */\r\n public boolean getAntiAlias() {\r\n Object val = this.renderingHints.get(RenderingHints.KEY_ANTIALIASING);\r\n return RenderingHints.VALUE_ANTIALIAS_ON.equals(val);\r\n }\r\n\r\n /**\r\n * Sets a flag that indicates whether or not anti-aliasing is used when the\r\n * chart is drawn.\r\n * <P>\r\n * Anti-aliasing usually improves the appearance of charts, but is slower.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #getAntiAlias()\r\n */\r\n public void setAntiAlias(boolean flag) {\r\n Object hint = flag ? RenderingHints.VALUE_ANTIALIAS_ON \r\n : RenderingHints.VALUE_ANTIALIAS_OFF;\r\n this.renderingHints.put(RenderingHints.KEY_ANTIALIASING, hint);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the current value stored in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING}.\r\n *\r\n * @return The hint value (possibly <code>null</code>).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public Object getTextAntiAlias() {\r\n return this.renderingHints.get(RenderingHints.KEY_TEXT_ANTIALIASING);\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} to either\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_ON} or\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_OFF}, then sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public void setTextAntiAlias(boolean flag) {\r\n if (flag) {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\r\n }\r\n else {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);\r\n }\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param val the new value (<code>null</code> permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(boolean)\r\n */\r\n public void setTextAntiAlias(Object val) {\r\n this.renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, val);\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the paint used for the chart background.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundPaint(Paint)\r\n */\r\n public Paint getBackgroundPaint() {\r\n return this.backgroundPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to fill the chart background and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundPaint()\r\n */\r\n public void setBackgroundPaint(Paint paint) {\r\n\r\n if (this.backgroundPaint != null) {\r\n if (!this.backgroundPaint.equals(paint)) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (paint != null) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image for the chart, or <code>null</code> if\r\n * there is no image.\r\n *\r\n * @return The image (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundImage(Image)\r\n */\r\n public Image getBackgroundImage() {\r\n return this.backgroundImage;\r\n }\r\n\r\n /**\r\n * Sets the background image for the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param image the image (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundImage()\r\n */\r\n public void setBackgroundImage(Image image) {\r\n\r\n if (this.backgroundImage != null) {\r\n if (!this.backgroundImage.equals(image)) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (image != null) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image alignment. Alignment constants are defined\r\n * in the <code>org.jfree.ui.Align</code> class in the JCommon class\r\n * library.\r\n *\r\n * @return The alignment.\r\n *\r\n * @see #setBackgroundImageAlignment(int)\r\n */\r\n public int getBackgroundImageAlignment() {\r\n return this.backgroundImageAlignment;\r\n }\r\n\r\n /**\r\n * Sets the background alignment. Alignment options are defined by the\r\n * {@link org.jfree.ui.Align} class.\r\n *\r\n * @param alignment the alignment.\r\n *\r\n * @see #getBackgroundImageAlignment()\r\n */\r\n public void setBackgroundImageAlignment(int alignment) {\r\n if (this.backgroundImageAlignment != alignment) {\r\n this.backgroundImageAlignment = alignment;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha-transparency for the chart's background image.\r\n *\r\n * @return The alpha-transparency.\r\n *\r\n * @see #setBackgroundImageAlpha(float)\r\n */\r\n public float getBackgroundImageAlpha() {\r\n return this.backgroundImageAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha-transparency for the chart's background image.\r\n * Registered listeners are notified that the chart has been changed.\r\n *\r\n * @param alpha the alpha value.\r\n *\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void setBackgroundImageAlpha(float alpha) {\r\n\r\n if (this.backgroundImageAlpha != alpha) {\r\n this.backgroundImageAlpha = alpha;\r\n fireChartChanged();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not change events are sent to\r\n * registered listeners.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNotify(boolean)\r\n */\r\n public boolean isNotify() {\r\n return this.notify;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not listeners receive\r\n * {@link ChartChangeEvent} notifications.\r\n *\r\n * @param notify a boolean.\r\n *\r\n * @see #isNotify()\r\n */\r\n public void setNotify(boolean notify) {\r\n this.notify = notify;\r\n // if the flag is being set to true, there may be queued up changes...\r\n if (notify) {\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area) {\r\n draw(g2, area, null, null);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer). This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D area, ChartRenderingInfo info) {\r\n draw(g2, area, null, info);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param chartArea the area within which the chart should be drawn.\r\n * @param anchor the anchor point (in Java2D space) for the chart\r\n * (<code>null</code> permitted).\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D chartArea, Point2D anchor,\r\n ChartRenderingInfo info) {\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_STARTED, 0));\r\n \r\n EntityCollection entities = null;\r\n // record the chart area, if info is requested...\r\n if (info != null) {\r\n info.clear();\r\n info.setChartArea(chartArea);\r\n entities = info.getEntityCollection();\r\n }\r\n if (entities != null) {\r\n entities.add(new JFreeChartEntity((Rectangle2D) chartArea.clone(),\r\n this));\r\n }\r\n\r\n // ensure no drawing occurs outside chart area...\r\n Shape savedClip = g2.getClip();\r\n g2.clip(chartArea);\r\n\r\n g2.addRenderingHints(this.renderingHints);\r\n\r\n // draw the chart background...\r\n if (this.backgroundPaint != null) {\r\n g2.setPaint(this.backgroundPaint);\r\n g2.fill(chartArea);\r\n }\r\n\r\n if (this.backgroundImage != null) {\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundImageAlpha));\r\n Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,\r\n this.backgroundImage.getWidth(null),\r\n this.backgroundImage.getHeight(null));\r\n Align.align(dest, chartArea, this.backgroundImageAlignment);\r\n g2.drawImage(this.backgroundImage, (int) dest.getX(),\r\n (int) dest.getY(), (int) dest.getWidth(),\r\n (int) dest.getHeight(), null);\r\n g2.setComposite(originalComposite);\r\n }\r\n\r\n if (isBorderVisible()) {\r\n Paint paint = getBorderPaint();\r\n Stroke stroke = getBorderStroke();\r\n if (paint != null && stroke != null) {\r\n Rectangle2D borderArea = new Rectangle2D.Double(\r\n chartArea.getX(), chartArea.getY(),\r\n chartArea.getWidth() - 1.0, chartArea.getHeight()\r\n - 1.0);\r\n g2.setPaint(paint);\r\n g2.setStroke(stroke);\r\n g2.draw(borderArea);\r\n }\r\n }\r\n\r\n // draw the title and subtitles...\r\n Rectangle2D nonTitleArea = new Rectangle2D.Double();\r\n nonTitleArea.setRect(chartArea);\r\n this.padding.trim(nonTitleArea);\r\n\r\n if (this.title != null && this.title.isVisible()) {\r\n EntityCollection e = drawTitle(this.title, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title currentTitle = (Title) iterator.next();\r\n if (currentTitle.isVisible()) {\r\n EntityCollection e = drawTitle(currentTitle, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n }\r\n\r\n Rectangle2D plotArea = nonTitleArea;\r\n\r\n // draw the plot (axes and data visualisation)\r\n PlotRenderingInfo plotInfo = null;\r\n if (info != null) {\r\n plotInfo = info.getPlotInfo();\r\n }\r\n this.plot.draw(g2, plotArea, anchor, null, plotInfo);\r\n\r\n g2.setClip(savedClip);\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_FINISHED, 100));\r\n }\r\n\r\n /**\r\n * Creates a rectangle that is aligned to the frame.\r\n *\r\n * @param dimensions the dimensions for the rectangle.\r\n * @param frame the frame to align to.\r\n * @param hAlign the horizontal alignment.\r\n * @param vAlign the vertical alignment.\r\n *\r\n * @return A rectangle.\r\n */\r\n private Rectangle2D createAlignedRectangle2D(Size2D dimensions,\r\n Rectangle2D frame, HorizontalAlignment hAlign,\r\n VerticalAlignment vAlign) {\r\n double x = Double.NaN;\r\n double y = Double.NaN;\r\n if (hAlign == HorizontalAlignment.LEFT) {\r\n x = frame.getX();\r\n }\r\n else if (hAlign == HorizontalAlignment.CENTER) {\r\n x = frame.getCenterX() - (dimensions.width / 2.0);\r\n }\r\n else if (hAlign == HorizontalAlignment.RIGHT) {\r\n x = frame.getMaxX() - dimensions.width;\r\n }\r\n if (vAlign == VerticalAlignment.TOP) {\r\n y = frame.getY();\r\n }\r\n else if (vAlign == VerticalAlignment.CENTER) {\r\n y = frame.getCenterY() - (dimensions.height / 2.0);\r\n }\r\n else if (vAlign == VerticalAlignment.BOTTOM) {\r\n y = frame.getMaxY() - dimensions.height;\r\n }\r\n\r\n return new Rectangle2D.Double(x, y, dimensions.width,\r\n dimensions.height);\r\n }\r\n\r\n /**\r\n * Draws a title. The title should be drawn at the top, bottom, left or\r\n * right of the specified area, and the area should be updated to reflect\r\n * the amount of space used by the title.\r\n *\r\n * @param t the title (<code>null</code> not permitted).\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param area the chart area, excluding any existing titles\r\n * (<code>null</code> not permitted).\r\n * @param entities a flag that controls whether or not an entity\r\n * collection is returned for the title.\r\n *\r\n * @return An entity collection for the title (possibly <code>null</code>).\r\n */\r\n protected EntityCollection drawTitle(Title t, Graphics2D g2,\r\n Rectangle2D area, boolean entities) {\r\n\r\n ParamChecks.nullNotPermitted(t, \"t\");\r\n ParamChecks.nullNotPermitted(area, \"area\");\r\n Rectangle2D titleArea;\r\n RectangleEdge position = t.getPosition();\r\n double ww = area.getWidth();\r\n if (ww <= 0.0) {\r\n return null;\r\n }\r\n double hh = area.getHeight();\r\n if (hh <= 0.0) {\r\n return null;\r\n }\r\n RectangleConstraint constraint = new RectangleConstraint(ww,\r\n new Range(0.0, ww), LengthConstraintType.RANGE, hh,\r\n new Range(0.0, hh), LengthConstraintType.RANGE);\r\n Object retValue = null;\r\n BlockParams p = new BlockParams();\r\n p.setGenerateEntities(entities);\r\n if (position == RectangleEdge.TOP) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.TOP);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), Math.min(area.getY() + size.height,\r\n area.getMaxY()), area.getWidth(), Math.max(area.getHeight()\r\n - size.height, 0));\r\n }\r\n else if (position == RectangleEdge.BOTTOM) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.BOTTOM);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth(),\r\n area.getHeight() - size.height);\r\n }\r\n else if (position == RectangleEdge.RIGHT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.RIGHT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n\r\n else if (position == RectangleEdge.LEFT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.LEFT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX() + size.width, area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n else {\r\n throw new RuntimeException(\"Unrecognised title position.\");\r\n }\r\n EntityCollection result = null;\r\n if (retValue instanceof EntityBlockResult) {\r\n EntityBlockResult ebr = (EntityBlockResult) retValue;\r\n result = ebr.getEntityCollection();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height) {\r\n return createBufferedImage(width, height, null);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n ChartRenderingInfo info) {\r\n return createBufferedImage(width, height, BufferedImage.TYPE_INT_ARGB,\r\n info);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param imageType the image type.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n int imageType,\r\n ChartRenderingInfo info) {\r\n BufferedImage image = new BufferedImage(width, height, imageType);\r\n Graphics2D g2 = image.createGraphics();\r\n draw(g2, new Rectangle2D.Double(0, 0, width, height), null, info);\r\n g2.dispose();\r\n return image;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param imageWidth the image width.\r\n * @param imageHeight the image height.\r\n * @param drawWidth the width for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param drawHeight the height for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param info optional object for collection chart dimension and entity\r\n * information.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int imageWidth,\r\n int imageHeight,\r\n double drawWidth,\r\n double drawHeight,\r\n ChartRenderingInfo info) {\r\n\r\n BufferedImage image = new BufferedImage(imageWidth, imageHeight,\r\n BufferedImage.TYPE_INT_ARGB);\r\n Graphics2D g2 = image.createGraphics();\r\n double scaleX = imageWidth / drawWidth;\r\n double scaleY = imageHeight / drawHeight;\r\n AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);\r\n g2.transform(st);\r\n draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,\r\n info);\r\n g2.dispose();\r\n return image;\r\n\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the chart. JFreeChart is not a UI component, so\r\n * some other object (for example, {@link ChartPanel}) needs to capture\r\n * the click event and pass it onto the JFreeChart object.\r\n * If you are not using JFreeChart in a client application, then this\r\n * method is not required.\r\n *\r\n * @param x x-coordinate of the click (in Java2D space).\r\n * @param y y-coordinate of the click (in Java2D space).\r\n * @param info contains chart dimension and entity information\r\n * (<code>null</code> not permitted).\r\n */\r\n public void handleClick(int x, int y, ChartRenderingInfo info) {\r\n\r\n // pass the click on to the plot...\r\n // rely on the plot to post a plot change event and redraw the chart...\r\n this.plot.handleClick(x, y, info.getPlotInfo());\r\n\r\n }\r\n\r\n /**\r\n * Registers an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted).\r\n *\r\n * @see #removeChangeListener(ChartChangeListener)\r\n */\r\n public void addChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.add(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted)\r\n *\r\n * @see #addChangeListener(ChartChangeListener)\r\n */\r\n public void removeChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.remove(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a default {@link ChartChangeEvent} to all registered listeners.\r\n * <P>\r\n * This method is for convenience only.\r\n */\r\n public void fireChartChanged() {\r\n ChartChangeEvent event = new ChartChangeEvent(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartChangeEvent event) {\r\n if (this.notify) {\r\n Object[] listeners = this.changeListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartChangeListener.class) {\r\n ((ChartChangeListener) listeners[i + 1]).chartChanged(\r\n event);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Registers an object for notification of progress events relating to the\r\n * chart.\r\n *\r\n * @param listener the object being registered.\r\n *\r\n * @see #removeProgressListener(ChartProgressListener)\r\n */\r\n public void addProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.add(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the object being deregistered.\r\n *\r\n * @see #addProgressListener(ChartProgressListener)\r\n */\r\n public void removeProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.remove(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartProgressEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartProgressEvent event) {\r\n\r\n Object[] listeners = this.progressListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartProgressListener.class) {\r\n ((ChartProgressListener) listeners[i + 1]).chartProgress(event);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Receives notification that a chart title has changed, and passes this\r\n * on to registered listeners.\r\n *\r\n * @param event information about the chart title change.\r\n */\r\n @Override\r\n public void titleChanged(TitleChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Receives notification that the plot has changed, and passes this on to\r\n * registered listeners.\r\n *\r\n * @param event information about the plot change.\r\n */\r\n @Override\r\n public void plotChanged(PlotChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Tests this chart for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof JFreeChart)) {\r\n return false;\r\n }\r\n JFreeChart that = (JFreeChart) obj;\r\n if (!this.renderingHints.equals(that.renderingHints)) {\r\n return false;\r\n }\r\n if (this.borderVisible != that.borderVisible) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.borderStroke, that.borderStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.borderPaint, that.borderPaint)) {\r\n return false;\r\n }\r\n if (!this.padding.equals(that.padding)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.title, that.title)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.subtitles, that.subtitles)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.plot, that.plot)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(\r\n this.backgroundPaint, that.backgroundPaint\r\n )) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundImage,\r\n that.backgroundImage)) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlignment != that.backgroundImageAlignment) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlpha != that.backgroundImageAlpha) {\r\n return false;\r\n }\r\n if (this.notify != that.notify) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.borderStroke, stream);\r\n SerialUtilities.writePaint(this.borderPaint, stream);\r\n SerialUtilities.writePaint(this.backgroundPaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.borderStroke = SerialUtilities.readStroke(stream);\r\n this.borderPaint = SerialUtilities.readPaint(stream);\r\n this.backgroundPaint = SerialUtilities.readPaint(stream);\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n // register as a listener with sub-components...\r\n if (this.title != null) {\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n getSubtitle(i).addChangeListener(this);\r\n }\r\n this.plot.addChangeListener(this);\r\n }\r\n\r\n /**\r\n * Prints information about JFreeChart to standard output.\r\n *\r\n * @param args no arguments are honored.\r\n */\r\n public static void main(String[] args) {\r\n System.out.println(JFreeChart.INFO.toString());\r\n }\r\n\r\n /**\r\n * Clones the object, and takes care of listeners.\r\n * Note: caller shall register its own listeners on cloned graph.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the chart is not cloneable.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n JFreeChart chart = (JFreeChart) super.clone();\r\n\r\n chart.renderingHints = (RenderingHints) this.renderingHints.clone();\r\n // private boolean borderVisible;\r\n // private transient Stroke borderStroke;\r\n // private transient Paint borderPaint;\r\n\r\n if (this.title != null) {\r\n chart.title = (TextTitle) this.title.clone();\r\n chart.title.addChangeListener(chart);\r\n }\r\n\r\n chart.subtitles = new ArrayList();\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n Title subtitle = (Title) getSubtitle(i).clone();\r\n chart.subtitles.add(subtitle);\r\n subtitle.addChangeListener(chart);\r\n }\r\n\r\n if (this.plot != null) {\r\n chart.plot = (Plot) this.plot.clone();\r\n chart.plot.addChangeListener(chart);\r\n }\r\n\r\n chart.progressListeners = new EventListenerList();\r\n chart.changeListeners = new EventListenerList();\r\n return chart;\r\n }\r\n\r\n}\r" }, { "identifier": "ChartEntity", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/entity/ChartEntity.java", "snippet": "public class ChartEntity implements Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -4445994133561919083L;\r\n\r\n /** The area occupied by the entity (in Java 2D space). */\r\n private transient Shape area;\r\n\r\n /** The tool tip text for the entity. */\r\n private String toolTipText;\r\n\r\n /** The URL text for the entity. */\r\n private String urlText;\r\n\r\n /**\r\n * Creates a new chart entity.\r\n *\r\n * @param area the area (<code>null</code> not permitted).\r\n */\r\n public ChartEntity(Shape area) {\r\n // defer argument checks...\r\n this(area, null);\r\n }\r\n\r\n /**\r\n * Creates a new chart entity.\r\n *\r\n * @param area the area (<code>null</code> not permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n */\r\n public ChartEntity(Shape area, String toolTipText) {\r\n // defer argument checks...\r\n this(area, toolTipText, null);\r\n }\r\n\r\n /**\r\n * Creates a new entity.\r\n *\r\n * @param area the area (<code>null</code> not permitted).\r\n * @param toolTipText the tool tip text (<code>null</code> permitted).\r\n * @param urlText the URL text for HTML image maps (<code>null</code>\r\n * permitted).\r\n */\r\n public ChartEntity(Shape area, String toolTipText, String urlText) {\r\n ParamChecks.nullNotPermitted(area, \"area\");\r\n this.area = area;\r\n this.toolTipText = toolTipText;\r\n this.urlText = urlText;\r\n }\r\n\r\n /**\r\n * Returns the area occupied by the entity (in Java 2D space).\r\n *\r\n * @return The area (never <code>null</code>).\r\n */\r\n public Shape getArea() {\r\n return this.area;\r\n }\r\n\r\n /**\r\n * Sets the area for the entity.\r\n * <P>\r\n * This class conveys information about chart entities back to a client.\r\n * Setting this area doesn't change the entity (which has already been\r\n * drawn).\r\n *\r\n * @param area the area (<code>null</code> not permitted).\r\n */\r\n public void setArea(Shape area) {\r\n ParamChecks.nullNotPermitted(area, \"area\");\r\n this.area = area;\r\n }\r\n\r\n /**\r\n * Returns the tool tip text for the entity. Be aware that this text\r\n * may have been generated from user supplied data, so for security\r\n * reasons some form of filtering should be applied before incorporating\r\n * this text into any HTML output.\r\n *\r\n * @return The tool tip text (possibly <code>null</code>).\r\n */\r\n public String getToolTipText() {\r\n return this.toolTipText;\r\n }\r\n\r\n /**\r\n * Sets the tool tip text.\r\n *\r\n * @param text the text (<code>null</code> permitted).\r\n */\r\n public void setToolTipText(String text) {\r\n this.toolTipText = text;\r\n }\r\n\r\n /**\r\n * Returns the URL text for the entity. Be aware that this text\r\n * may have been generated from user supplied data, so some form of\r\n * filtering should be applied before this \"URL\" is used in any output.\r\n *\r\n * @return The URL text (possibly <code>null</code>).\r\n */\r\n public String getURLText() {\r\n return this.urlText;\r\n }\r\n\r\n /**\r\n * Sets the URL text.\r\n *\r\n * @param text the text (<code>null</code> permitted).\r\n */\r\n public void setURLText(String text) {\r\n this.urlText = text;\r\n }\r\n\r\n /**\r\n * Returns a string describing the entity area. This string is intended\r\n * for use in an AREA tag when generating an image map.\r\n *\r\n * @return The shape type (never <code>null</code>).\r\n */\r\n public String getShapeType() {\r\n if (this.area instanceof Rectangle2D) {\r\n return \"rect\";\r\n }\r\n else {\r\n return \"poly\";\r\n }\r\n }\r\n\r\n /**\r\n * Returns the shape coordinates as a string.\r\n *\r\n * @return The shape coordinates (never <code>null</code>).\r\n */\r\n public String getShapeCoords() {\r\n if (this.area instanceof Rectangle2D) {\r\n return getRectCoords((Rectangle2D) this.area);\r\n }\r\n else {\r\n return getPolyCoords(this.area);\r\n }\r\n }\r\n\r\n /**\r\n * Returns a string containing the coordinates (x1, y1, x2, y2) for a given\r\n * rectangle. This string is intended for use in an image map.\r\n *\r\n * @param rectangle the rectangle (<code>null</code> not permitted).\r\n *\r\n * @return Upper left and lower right corner of a rectangle.\r\n */\r\n private String getRectCoords(Rectangle2D rectangle) {\r\n ParamChecks.nullNotPermitted(rectangle, \"rectangle\");\r\n int x1 = (int) rectangle.getX();\r\n int y1 = (int) rectangle.getY();\r\n int x2 = x1 + (int) rectangle.getWidth();\r\n int y2 = y1 + (int) rectangle.getHeight();\r\n // fix by rfuller\r\n if (x2 == x1) {\r\n x2++;\r\n }\r\n if (y2 == y1) {\r\n y2++;\r\n }\r\n // end fix by rfuller\r\n return x1 + \",\" + y1 + \",\" + x2 + \",\" + y2;\r\n }\r\n\r\n /**\r\n * Returns a string containing the coordinates for a given shape. This\r\n * string is intended for use in an image map.\r\n *\r\n * @param shape the shape (<code>null</code> not permitted).\r\n *\r\n * @return The coordinates for a given shape as string.\r\n */\r\n private String getPolyCoords(Shape shape) {\r\n ParamChecks.nullNotPermitted(shape, \"shape\");\r\n StringBuilder result = new StringBuilder();\r\n boolean first = true;\r\n float[] coords = new float[6];\r\n PathIterator pi = shape.getPathIterator(null, 1.0);\r\n while (!pi.isDone()) {\r\n pi.currentSegment(coords);\r\n if (first) {\r\n first = false;\r\n result.append((int) coords[0]);\r\n result.append(\",\").append((int) coords[1]);\r\n }\r\n else {\r\n result.append(\",\");\r\n result.append((int) coords[0]);\r\n result.append(\",\");\r\n result.append((int) coords[1]);\r\n }\r\n pi.next();\r\n }\r\n return result.toString();\r\n }\r\n\r\n /**\r\n * Returns an HTML image map tag for this entity. The returned fragment\r\n * should be <code>XHTML 1.0</code> compliant.\r\n *\r\n * @param toolTipTagFragmentGenerator a generator for the HTML fragment\r\n * that will contain the tooltip text (<code>null</code> not permitted\r\n * if this entity contains tooltip information).\r\n * @param urlTagFragmentGenerator a generator for the HTML fragment that\r\n * will contain the URL reference (<code>null</code> not permitted if\r\n * this entity has a URL).\r\n *\r\n * @return The HTML tag.\r\n */\r\n public String getImageMapAreaTag(\r\n ToolTipTagFragmentGenerator toolTipTagFragmentGenerator,\r\n URLTagFragmentGenerator urlTagFragmentGenerator) {\r\n\r\n StringBuilder tag = new StringBuilder();\r\n boolean hasURL = (this.urlText == null ? false\r\n : !this.urlText.equals(\"\"));\r\n boolean hasToolTip = (this.toolTipText == null ? false\r\n : !this.toolTipText.equals(\"\"));\r\n if (hasURL || hasToolTip) {\r\n tag.append(\"<area shape=\\\"\").append(getShapeType()).append(\"\\\"\")\r\n .append(\" coords=\\\"\").append(getShapeCoords()).append(\"\\\"\");\r\n if (hasToolTip) {\r\n tag.append(toolTipTagFragmentGenerator.generateToolTipFragment(\r\n this.toolTipText));\r\n }\r\n if (hasURL) {\r\n tag.append(urlTagFragmentGenerator.generateURLFragment(\r\n this.urlText));\r\n }\r\n else {\r\n tag.append(\" nohref=\\\"nohref\\\"\");\r\n }\r\n // if there is a tool tip, we expect it to generate the title and\r\n // alt values, so we only add an empty alt if there is no tooltip\r\n if (!hasToolTip) {\r\n tag.append(\" alt=\\\"\\\"\");\r\n }\r\n tag.append(\"/>\");\r\n }\r\n return tag.toString();\r\n }\r\n\r\n /**\r\n * Returns a string representation of the chart entity, useful for\r\n * debugging.\r\n *\r\n * @return A string.\r\n */\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"ChartEntity: \");\r\n sb.append(\"tooltip = \");\r\n sb.append(this.toolTipText);\r\n return sb.toString();\r\n }\r\n\r\n /**\r\n * Tests the entity for equality with an arbitrary object.\r\n *\r\n * @param obj the object to test against (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof ChartEntity)) {\r\n return false;\r\n }\r\n ChartEntity that = (ChartEntity) obj;\r\n if (!this.area.equals(that.area)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.toolTipText, that.toolTipText)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.urlText, that.urlText)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code for this instance.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result = 37;\r\n result = HashUtilities.hashCode(result, this.toolTipText);\r\n result = HashUtilities.hashCode(result, this.urlText);\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a clone of the entity.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if there is a problem cloning the\r\n * entity.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n return super.clone();\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeShape(this.area, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.area = SerialUtilities.readShape(stream);\r\n }\r\n\r\n}\r" }, { "identifier": "EntityCollection", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/entity/EntityCollection.java", "snippet": "public interface EntityCollection {\r\n\r\n /**\r\n * Clears all entities.\r\n */\r\n public void clear();\r\n\r\n /**\r\n * Adds an entity to the collection.\r\n *\r\n * @param entity the entity (<code>null</code> not permitted).\r\n */\r\n public void add(ChartEntity entity);\r\n\r\n /**\r\n * Adds the entities from another collection to this collection.\r\n *\r\n * @param collection the other collection.\r\n */\r\n public void addAll(EntityCollection collection);\r\n\r\n /**\r\n * Returns an entity whose area contains the specified point.\r\n *\r\n * @param x the x coordinate.\r\n * @param y the y coordinate.\r\n *\r\n * @return The entity.\r\n */\r\n public ChartEntity getEntity(double x, double y);\r\n\r\n /**\r\n * Returns an entity from the collection.\r\n *\r\n * @param index the index (zero-based).\r\n *\r\n * @return An entity.\r\n */\r\n public ChartEntity getEntity(int index);\r\n\r\n /**\r\n * Returns the entity count.\r\n *\r\n * @return The entity count.\r\n */\r\n public int getEntityCount();\r\n\r\n /**\r\n * Returns the entities in an unmodifiable collection.\r\n *\r\n * @return The entities.\r\n */\r\n public Collection getEntities();\r\n\r\n /**\r\n * Returns an iterator for the entities in the collection.\r\n *\r\n * @return An iterator.\r\n */\r\n public Iterator iterator();\r\n\r\n}\r" }, { "identifier": "ChartChangeEvent", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/event/ChartChangeEvent.java", "snippet": "public class ChartChangeEvent extends EventObject {\r\n\r\n /** The type of event. */\r\n private ChartChangeEventType type;\r\n\r\n /** The chart that generated the event. */\r\n private JFreeChart chart;\r\n\r\n /**\r\n * Creates a new chart change event.\r\n *\r\n * @param source the source of the event (could be the chart, a title,\r\n * an axis etc.)\r\n */\r\n public ChartChangeEvent(Object source) {\r\n this(source, null, ChartChangeEventType.GENERAL);\r\n }\r\n\r\n /**\r\n * Creates a new chart change event.\r\n *\r\n * @param source the source of the event (could be the chart, a title, an\r\n * axis etc.)\r\n * @param chart the chart that generated the event.\r\n */\r\n public ChartChangeEvent(Object source, JFreeChart chart) {\r\n this(source, chart, ChartChangeEventType.GENERAL);\r\n }\r\n\r\n /**\r\n * Creates a new chart change event.\r\n *\r\n * @param source the source of the event (could be the chart, a title, an\r\n axis etc.)\r\n * @param chart the chart that generated the event.\r\n * @param type the type of event.\r\n */\r\n public ChartChangeEvent(Object source, JFreeChart chart,\r\n ChartChangeEventType type) {\r\n super(source);\r\n this.chart = chart;\r\n this.type = type;\r\n }\r\n\r\n /**\r\n * Returns the chart that generated the change event.\r\n *\r\n * @return The chart that generated the change event.\r\n */\r\n public JFreeChart getChart() {\r\n return this.chart;\r\n }\r\n\r\n /**\r\n * Sets the chart that generated the change event.\r\n *\r\n * @param chart the chart that generated the event.\r\n */\r\n public void setChart(JFreeChart chart) {\r\n this.chart = chart;\r\n }\r\n\r\n /**\r\n * Returns the event type.\r\n *\r\n * @return The event type.\r\n */\r\n public ChartChangeEventType getType() {\r\n return this.type;\r\n }\r\n\r\n /**\r\n * Sets the event type.\r\n *\r\n * @param type the event type.\r\n */\r\n public void setType(ChartChangeEventType type) {\r\n this.type = type;\r\n }\r\n\r\n}\r" }, { "identifier": "ChartChangeListener", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/event/ChartChangeListener.java", "snippet": "public interface ChartChangeListener extends EventListener {\r\n\r\n /**\r\n * Receives notification of a chart change event.\r\n *\r\n * @param event the event.\r\n */\r\n public void chartChanged(ChartChangeEvent event);\r\n\r\n}\r" }, { "identifier": "ChartProgressEvent", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/event/ChartProgressEvent.java", "snippet": "public class ChartProgressEvent extends java.util.EventObject {\r\n\r\n /** Indicates drawing has started. */\r\n public static final int DRAWING_STARTED = 1;\r\n\r\n /** Indicates drawing has finished. */\r\n public static final int DRAWING_FINISHED = 2;\r\n\r\n /** The type of event. */\r\n private int type;\r\n\r\n /** The percentage of completion. */\r\n private int percent;\r\n\r\n /** The chart that generated the event. */\r\n private JFreeChart chart;\r\n\r\n /**\r\n * Creates a new chart change event.\r\n *\r\n * @param source the source of the event (could be the chart, a title, an\r\n * axis etc.)\r\n * @param chart the chart that generated the event.\r\n * @param type the type of event.\r\n * @param percent the percentage of completion.\r\n */\r\n public ChartProgressEvent(Object source, JFreeChart chart, int type,\r\n int percent) {\r\n super(source);\r\n this.chart = chart;\r\n this.type = type;\r\n this.percent = percent;\r\n }\r\n\r\n /**\r\n * Returns the chart that generated the change event.\r\n *\r\n * @return The chart that generated the change event.\r\n */\r\n public JFreeChart getChart() {\r\n return this.chart;\r\n }\r\n\r\n /**\r\n * Sets the chart that generated the change event.\r\n *\r\n * @param chart the chart that generated the event.\r\n */\r\n public void setChart(JFreeChart chart) {\r\n this.chart = chart;\r\n }\r\n\r\n /**\r\n * Returns the event type.\r\n *\r\n * @return The event type.\r\n */\r\n public int getType() {\r\n return this.type;\r\n }\r\n\r\n /**\r\n * Sets the event type.\r\n *\r\n * @param type the event type.\r\n */\r\n public void setType(int type) {\r\n this.type = type;\r\n }\r\n\r\n /**\r\n * Returns the percentage complete.\r\n *\r\n * @return The percentage complete.\r\n */\r\n public int getPercent() {\r\n return this.percent;\r\n }\r\n\r\n /**\r\n * Sets the percentage complete.\r\n *\r\n * @param percent the percentage.\r\n */\r\n public void setPercent(int percent) {\r\n this.percent = percent;\r\n }\r\n\r\n}\r" }, { "identifier": "ChartProgressListener", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/event/ChartProgressListener.java", "snippet": "public interface ChartProgressListener extends EventListener {\r\n\r\n /**\r\n * Receives notification of a chart progress event.\r\n *\r\n * @param event the event.\r\n */\r\n public void chartProgress(ChartProgressEvent event);\r\n\r\n}\r" }, { "identifier": "Plot", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/Plot.java", "snippet": "public abstract class Plot implements AxisChangeListener,\r\n DatasetChangeListener, AnnotationChangeListener, MarkerChangeListener,\r\n LegendItemSource, PublicCloneable, Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -8831571430103671324L;\r\n\r\n /** Useful constant representing zero. */\r\n public static final Number ZERO = new Integer(0);\r\n\r\n /** The default insets. */\r\n public static final RectangleInsets DEFAULT_INSETS\r\n = new RectangleInsets(4.0, 8.0, 4.0, 8.0);\r\n\r\n /** The default outline stroke. */\r\n public static final Stroke DEFAULT_OUTLINE_STROKE = new BasicStroke(0.5f,\r\n BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);\r\n\r\n /** The default outline color. */\r\n public static final Paint DEFAULT_OUTLINE_PAINT = Color.gray;\r\n\r\n /** The default foreground alpha transparency. */\r\n public static final float DEFAULT_FOREGROUND_ALPHA = 1.0f;\r\n\r\n /** The default background alpha transparency. */\r\n public static final float DEFAULT_BACKGROUND_ALPHA = 1.0f;\r\n\r\n /** The default background color. */\r\n public static final Paint DEFAULT_BACKGROUND_PAINT = Color.white;\r\n\r\n /** The minimum width at which the plot should be drawn. */\r\n public static final int MINIMUM_WIDTH_TO_DRAW = 10;\r\n\r\n /** The minimum height at which the plot should be drawn. */\r\n public static final int MINIMUM_HEIGHT_TO_DRAW = 10;\r\n\r\n /** A default box shape for legend items. */\r\n public static final Shape DEFAULT_LEGEND_ITEM_BOX\r\n = new Rectangle2D.Double(-4.0, -4.0, 8.0, 8.0);\r\n\r\n /** A default circle shape for legend items. */\r\n public static final Shape DEFAULT_LEGEND_ITEM_CIRCLE\r\n = new Ellipse2D.Double(-4.0, -4.0, 8.0, 8.0);\r\n\r\n /** The parent plot (<code>null</code> if this is the root plot). */\r\n private Plot parent;\r\n\r\n /** The dataset group (to be used for thread synchronisation). */\r\n private DatasetGroup datasetGroup;\r\n\r\n /** The message to display if no data is available. */\r\n private String noDataMessage;\r\n\r\n /** The font used to display the 'no data' message. */\r\n private Font noDataMessageFont;\r\n\r\n /** The paint used to draw the 'no data' message. */\r\n private transient Paint noDataMessagePaint;\r\n\r\n /** Amount of blank space around the plot area. */\r\n private RectangleInsets insets;\r\n\r\n /**\r\n * A flag that controls whether or not the plot outline is drawn.\r\n *\r\n * @since 1.0.6\r\n */\r\n private boolean outlineVisible;\r\n\r\n /** The Stroke used to draw an outline around the plot. */\r\n private transient Stroke outlineStroke;\r\n\r\n /** The Paint used to draw an outline around the plot. */\r\n private transient Paint outlinePaint;\r\n\r\n /** An optional color used to fill the plot background. */\r\n private transient Paint backgroundPaint;\r\n\r\n /** An optional image for the plot background. */\r\n private transient Image backgroundImage; // not currently serialized\r\n\r\n /** The alignment for the background image. */\r\n private int backgroundImageAlignment = Align.FIT;\r\n\r\n /** The alpha value used to draw the background image. */\r\n private float backgroundImageAlpha = 0.5f;\r\n\r\n /** The alpha-transparency for the plot. */\r\n private float foregroundAlpha;\r\n\r\n /** The alpha transparency for the background paint. */\r\n private float backgroundAlpha;\r\n\r\n /** The drawing supplier. */\r\n private DrawingSupplier drawingSupplier;\r\n\r\n /** Storage for registered change listeners. */\r\n private transient EventListenerList listenerList;\r\n\r\n /**\r\n * A flag that controls whether or not the plot will notify listeners\r\n * of changes (defaults to true, but sometimes it is useful to disable\r\n * this).\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean notify;\r\n\r\n /**\r\n * Creates a new plot.\r\n */\r\n protected Plot() {\r\n\r\n this.parent = null;\r\n this.insets = DEFAULT_INSETS;\r\n this.backgroundPaint = DEFAULT_BACKGROUND_PAINT;\r\n this.backgroundAlpha = DEFAULT_BACKGROUND_ALPHA;\r\n this.backgroundImage = null;\r\n this.outlineVisible = true;\r\n this.outlineStroke = DEFAULT_OUTLINE_STROKE;\r\n this.outlinePaint = DEFAULT_OUTLINE_PAINT;\r\n this.foregroundAlpha = DEFAULT_FOREGROUND_ALPHA;\r\n\r\n this.noDataMessage = null;\r\n this.noDataMessageFont = new Font(\"SansSerif\", Font.PLAIN, 12);\r\n this.noDataMessagePaint = Color.black;\r\n\r\n this.drawingSupplier = new DefaultDrawingSupplier();\r\n\r\n this.notify = true;\r\n this.listenerList = new EventListenerList();\r\n\r\n }\r\n\r\n /**\r\n * Returns the dataset group for the plot (not currently used).\r\n *\r\n * @return The dataset group.\r\n *\r\n * @see #setDatasetGroup(DatasetGroup)\r\n */\r\n public DatasetGroup getDatasetGroup() {\r\n return this.datasetGroup;\r\n }\r\n\r\n /**\r\n * Sets the dataset group (not currently used).\r\n *\r\n * @param group the dataset group (<code>null</code> permitted).\r\n *\r\n * @see #getDatasetGroup()\r\n */\r\n protected void setDatasetGroup(DatasetGroup group) {\r\n this.datasetGroup = group;\r\n }\r\n\r\n /**\r\n * Returns the string that is displayed when the dataset is empty or\r\n * <code>null</code>.\r\n *\r\n * @return The 'no data' message (<code>null</code> possible).\r\n *\r\n * @see #setNoDataMessage(String)\r\n * @see #getNoDataMessageFont()\r\n * @see #getNoDataMessagePaint()\r\n */\r\n public String getNoDataMessage() {\r\n return this.noDataMessage;\r\n }\r\n\r\n /**\r\n * Sets the message that is displayed when the dataset is empty or\r\n * <code>null</code>, and sends a {@link PlotChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param message the message (<code>null</code> permitted).\r\n *\r\n * @see #getNoDataMessage()\r\n */\r\n public void setNoDataMessage(String message) {\r\n this.noDataMessage = message;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the font used to display the 'no data' message.\r\n *\r\n * @return The font (never <code>null</code>).\r\n *\r\n * @see #setNoDataMessageFont(Font)\r\n * @see #getNoDataMessage()\r\n */\r\n public Font getNoDataMessageFont() {\r\n return this.noDataMessageFont;\r\n }\r\n\r\n /**\r\n * Sets the font used to display the 'no data' message and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param font the font (<code>null</code> not permitted).\r\n *\r\n * @see #getNoDataMessageFont()\r\n */\r\n public void setNoDataMessageFont(Font font) {\r\n ParamChecks.nullNotPermitted(font, \"font\");\r\n this.noDataMessageFont = font;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used to display the 'no data' message.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setNoDataMessagePaint(Paint)\r\n * @see #getNoDataMessage()\r\n */\r\n public Paint getNoDataMessagePaint() {\r\n return this.noDataMessagePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to display the 'no data' message and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getNoDataMessagePaint()\r\n */\r\n public void setNoDataMessagePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.noDataMessagePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a short string describing the plot type.\r\n * <P>\r\n * Note: this gets used in the chart property editing user interface,\r\n * but there needs to be a better mechanism for identifying the plot type.\r\n *\r\n * @return A short string describing the plot type (never\r\n * <code>null</code>).\r\n */\r\n public abstract String getPlotType();\r\n\r\n /**\r\n * Returns the parent plot (or <code>null</code> if this plot is not part\r\n * of a combined plot).\r\n *\r\n * @return The parent plot.\r\n *\r\n * @see #setParent(Plot)\r\n * @see #getRootPlot()\r\n */\r\n public Plot getParent() {\r\n return this.parent;\r\n }\r\n\r\n /**\r\n * Sets the parent plot. This method is intended for internal use, you\r\n * shouldn't need to call it directly.\r\n *\r\n * @param parent the parent plot (<code>null</code> permitted).\r\n *\r\n * @see #getParent()\r\n */\r\n public void setParent(Plot parent) {\r\n this.parent = parent;\r\n }\r\n\r\n /**\r\n * Returns the root plot.\r\n *\r\n * @return The root plot.\r\n *\r\n * @see #getParent()\r\n */\r\n public Plot getRootPlot() {\r\n\r\n Plot p = getParent();\r\n if (p == null) {\r\n return this;\r\n }\r\n return p.getRootPlot();\r\n\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this plot is part of a combined plot\r\n * structure (that is, {@link #getParent()} returns a non-<code>null</code>\r\n * value), and <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> if this plot is part of a combined plot\r\n * structure.\r\n *\r\n * @see #getParent()\r\n */\r\n public boolean isSubplot() {\r\n return (getParent() != null);\r\n }\r\n\r\n /**\r\n * Returns the insets for the plot area.\r\n *\r\n * @return The insets (never <code>null</code>).\r\n *\r\n * @see #setInsets(RectangleInsets)\r\n */\r\n public RectangleInsets getInsets() {\r\n return this.insets;\r\n }\r\n\r\n /**\r\n * Sets the insets for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param insets the new insets (<code>null</code> not permitted).\r\n *\r\n * @see #getInsets()\r\n * @see #setInsets(RectangleInsets, boolean)\r\n */\r\n public void setInsets(RectangleInsets insets) {\r\n setInsets(insets, true);\r\n }\r\n\r\n /**\r\n * Sets the insets for the plot and, if requested, and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param insets the new insets (<code>null</code> not permitted).\r\n * @param notify a flag that controls whether the registered listeners are\r\n * notified.\r\n *\r\n * @see #getInsets()\r\n * @see #setInsets(RectangleInsets)\r\n */\r\n public void setInsets(RectangleInsets insets, boolean notify) {\r\n ParamChecks.nullNotPermitted(insets, \"insets\");\r\n if (!this.insets.equals(insets)) {\r\n this.insets = insets;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background color of the plot area.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundPaint(Paint)\r\n */\r\n public Paint getBackgroundPaint() {\r\n return this.backgroundPaint;\r\n }\r\n\r\n /**\r\n * Sets the background color of the plot area and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundPaint()\r\n */\r\n public void setBackgroundPaint(Paint paint) {\r\n\r\n if (paint == null) {\r\n if (this.backgroundPaint != null) {\r\n this.backgroundPaint = null;\r\n fireChangeEvent();\r\n }\r\n }\r\n else {\r\n if (this.backgroundPaint != null) {\r\n if (this.backgroundPaint.equals(paint)) {\r\n return; // nothing to do\r\n }\r\n }\r\n this.backgroundPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the alpha transparency of the plot area background.\r\n *\r\n * @return The alpha transparency.\r\n *\r\n * @see #setBackgroundAlpha(float)\r\n */\r\n public float getBackgroundAlpha() {\r\n return this.backgroundAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha transparency of the plot area background, and notifies\r\n * registered listeners that the plot has been modified.\r\n *\r\n * @param alpha the new alpha value (in the range 0.0f to 1.0f).\r\n *\r\n * @see #getBackgroundAlpha()\r\n */\r\n public void setBackgroundAlpha(float alpha) {\r\n if (this.backgroundAlpha != alpha) {\r\n this.backgroundAlpha = alpha;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the drawing supplier for the plot.\r\n *\r\n * @return The drawing supplier (possibly <code>null</code>).\r\n *\r\n * @see #setDrawingSupplier(DrawingSupplier)\r\n */\r\n public DrawingSupplier getDrawingSupplier() {\r\n DrawingSupplier result;\r\n Plot p = getParent();\r\n if (p != null) {\r\n result = p.getDrawingSupplier();\r\n }\r\n else {\r\n result = this.drawingSupplier;\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the drawing supplier for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. The drawing\r\n * supplier is responsible for supplying a limitless (possibly repeating)\r\n * sequence of <code>Paint</code>, <code>Stroke</code> and\r\n * <code>Shape</code> objects that the plot's renderer(s) can use to\r\n * populate its (their) tables.\r\n *\r\n * @param supplier the new supplier.\r\n *\r\n * @see #getDrawingSupplier()\r\n */\r\n public void setDrawingSupplier(DrawingSupplier supplier) {\r\n this.drawingSupplier = supplier;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Sets the drawing supplier for the plot and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners. The drawing\r\n * supplier is responsible for supplying a limitless (possibly repeating)\r\n * sequence of <code>Paint</code>, <code>Stroke</code> and\r\n * <code>Shape</code> objects that the plot's renderer(s) can use to\r\n * populate its (their) tables.\r\n *\r\n * @param supplier the new supplier.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDrawingSupplier()\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setDrawingSupplier(DrawingSupplier supplier, boolean notify) {\r\n this.drawingSupplier = supplier;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the background image that is used to fill the plot's background\r\n * area.\r\n *\r\n * @return The image (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundImage(Image)\r\n */\r\n public Image getBackgroundImage() {\r\n return this.backgroundImage;\r\n }\r\n\r\n /**\r\n * Sets the background image for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param image the image (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundImage()\r\n */\r\n public void setBackgroundImage(Image image) {\r\n this.backgroundImage = image;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the background image alignment. Alignment constants are defined\r\n * in the <code>org.jfree.ui.Align</code> class in the JCommon class\r\n * library.\r\n *\r\n * @return The alignment.\r\n *\r\n * @see #setBackgroundImageAlignment(int)\r\n */\r\n public int getBackgroundImageAlignment() {\r\n return this.backgroundImageAlignment;\r\n }\r\n\r\n /**\r\n * Sets the alignment for the background image and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. Alignment options\r\n * are defined by the {@link org.jfree.ui.Align} class in the JCommon\r\n * class library.\r\n *\r\n * @param alignment the alignment.\r\n *\r\n * @see #getBackgroundImageAlignment()\r\n */\r\n public void setBackgroundImageAlignment(int alignment) {\r\n if (this.backgroundImageAlignment != alignment) {\r\n this.backgroundImageAlignment = alignment;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha transparency used to draw the background image. This\r\n * is a value in the range 0.0f to 1.0f, where 0.0f is fully transparent\r\n * and 1.0f is fully opaque.\r\n *\r\n * @return The alpha transparency.\r\n *\r\n * @see #setBackgroundImageAlpha(float)\r\n */\r\n public float getBackgroundImageAlpha() {\r\n return this.backgroundImageAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha transparency used when drawing the background image.\r\n *\r\n * @param alpha the alpha transparency (in the range 0.0f to 1.0f, where\r\n * 0.0f is fully transparent, and 1.0f is fully opaque).\r\n *\r\n * @throws IllegalArgumentException if <code>alpha</code> is not within\r\n * the specified range.\r\n *\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void setBackgroundImageAlpha(float alpha) {\r\n if (alpha < 0.0f || alpha > 1.0f) {\r\n throw new IllegalArgumentException(\r\n \"The 'alpha' value must be in the range 0.0f to 1.0f.\");\r\n }\r\n if (this.backgroundImageAlpha != alpha) {\r\n this.backgroundImageAlpha = alpha;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the plot outline is\r\n * drawn. The default value is <code>true</code>. Note that for\r\n * historical reasons, the plot's outline paint and stroke can take on\r\n * <code>null</code> values, in which case the outline will not be drawn\r\n * even if this flag is set to <code>true</code>.\r\n *\r\n * @return The outline visibility flag.\r\n *\r\n * @since 1.0.6\r\n *\r\n * @see #setOutlineVisible(boolean)\r\n */\r\n public boolean isOutlineVisible() {\r\n return this.outlineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the plot's outline is\r\n * drawn, and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the new flag value.\r\n *\r\n * @since 1.0.6\r\n *\r\n * @see #isOutlineVisible()\r\n */\r\n public void setOutlineVisible(boolean visible) {\r\n this.outlineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to outline the plot area.\r\n *\r\n * @return The stroke (possibly <code>null</code>).\r\n *\r\n * @see #setOutlineStroke(Stroke)\r\n */\r\n public Stroke getOutlineStroke() {\r\n return this.outlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to outline the plot area and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. If you set this\r\n * attribute to <code>null</code>, no outline will be drawn.\r\n *\r\n * @param stroke the stroke (<code>null</code> permitted).\r\n *\r\n * @see #getOutlineStroke()\r\n */\r\n public void setOutlineStroke(Stroke stroke) {\r\n if (stroke == null) {\r\n if (this.outlineStroke != null) {\r\n this.outlineStroke = null;\r\n fireChangeEvent();\r\n }\r\n }\r\n else {\r\n if (this.outlineStroke != null) {\r\n if (this.outlineStroke.equals(stroke)) {\r\n return; // nothing to do\r\n }\r\n }\r\n this.outlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the color used to draw the outline of the plot area.\r\n *\r\n * @return The color (possibly <code>null</code>).\r\n *\r\n * @see #setOutlinePaint(Paint)\r\n */\r\n public Paint getOutlinePaint() {\r\n return this.outlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the outline of the plot area and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. If you set this\r\n * attribute to <code>null</code>, no outline will be drawn.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getOutlinePaint()\r\n */\r\n public void setOutlinePaint(Paint paint) {\r\n if (paint == null) {\r\n if (this.outlinePaint != null) {\r\n this.outlinePaint = null;\r\n fireChangeEvent();\r\n }\r\n }\r\n else {\r\n if (this.outlinePaint != null) {\r\n if (this.outlinePaint.equals(paint)) {\r\n return; // nothing to do\r\n }\r\n }\r\n this.outlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha-transparency for the plot foreground.\r\n *\r\n * @return The alpha-transparency.\r\n *\r\n * @see #setForegroundAlpha(float)\r\n */\r\n public float getForegroundAlpha() {\r\n return this.foregroundAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha-transparency for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param alpha the new alpha transparency.\r\n *\r\n * @see #getForegroundAlpha()\r\n */\r\n public void setForegroundAlpha(float alpha) {\r\n if (this.foregroundAlpha != alpha) {\r\n this.foregroundAlpha = alpha;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the legend items for the plot. By default, this method returns\r\n * <code>null</code>. Subclasses should override to return a\r\n * {@link LegendItemCollection}.\r\n *\r\n * @return The legend items for the plot (possibly <code>null</code>).\r\n */\r\n @Override\r\n public LegendItemCollection getLegendItems() {\r\n return null;\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not change events are sent to\r\n * registered listeners.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNotify(boolean)\r\n *\r\n * @since 1.0.13\r\n */\r\n public boolean isNotify() {\r\n return this.notify;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not listeners receive\r\n * {@link PlotChangeEvent} notifications.\r\n *\r\n * @param notify a boolean.\r\n *\r\n * @see #isNotify()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setNotify(boolean notify) {\r\n this.notify = notify;\r\n // if the flag is being set to true, there may be queued up changes...\r\n if (notify) {\r\n notifyListeners(new PlotChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Registers an object for notification of changes to the plot.\r\n *\r\n * @param listener the object to be registered.\r\n *\r\n * @see #removeChangeListener(PlotChangeListener)\r\n */\r\n public void addChangeListener(PlotChangeListener listener) {\r\n this.listenerList.add(PlotChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Unregisters an object for notification of changes to the plot.\r\n *\r\n * @param listener the object to be unregistered.\r\n *\r\n * @see #addChangeListener(PlotChangeListener)\r\n */\r\n public void removeChangeListener(PlotChangeListener listener) {\r\n this.listenerList.remove(PlotChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Notifies all registered listeners that the plot has been modified.\r\n *\r\n * @param event information about the change event.\r\n */\r\n public void notifyListeners(PlotChangeEvent event) {\r\n // if the 'notify' flag has been switched to false, we don't notify\r\n // the listeners\r\n if (!this.notify) {\r\n return;\r\n }\r\n Object[] listeners = this.listenerList.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == PlotChangeListener.class) {\r\n ((PlotChangeListener) listeners[i + 1]).plotChanged(event);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @since 1.0.10\r\n */\r\n protected void fireChangeEvent() {\r\n notifyListeners(new PlotChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Draws the plot within the specified area. The anchor is a point on the\r\n * chart that is specified externally (for instance, it may be the last\r\n * point of the last mouse click performed by the user) - plots can use or\r\n * ignore this value as they see fit.\r\n * <br><br>\r\n * Subclasses need to provide an implementation of this method, obviously.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the plot area.\r\n * @param anchor the anchor point (<code>null</code> permitted).\r\n * @param parentState the parent state (if any).\r\n * @param info carries back plot rendering info.\r\n */\r\n public abstract void draw(Graphics2D g2,\r\n Rectangle2D area,\r\n Point2D anchor,\r\n PlotState parentState,\r\n PlotRenderingInfo info);\r\n\r\n /**\r\n * Draws the plot background (the background color and/or image).\r\n * <P>\r\n * This method will be called during the chart drawing process and is\r\n * declared public so that it can be accessed by the renderers used by\r\n * certain subclasses. You shouldn't need to call this method directly.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot should be drawn.\r\n */\r\n public void drawBackground(Graphics2D g2, Rectangle2D area) {\r\n // some subclasses override this method completely, so don't put\r\n // anything here that *must* be done\r\n fillBackground(g2, area);\r\n drawBackgroundImage(g2, area);\r\n }\r\n\r\n /**\r\n * Fills the specified area with the background paint.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n *\r\n * @see #getBackgroundPaint()\r\n * @see #getBackgroundAlpha()\r\n * @see #fillBackground(Graphics2D, Rectangle2D, PlotOrientation)\r\n */\r\n protected void fillBackground(Graphics2D g2, Rectangle2D area) {\r\n fillBackground(g2, area, PlotOrientation.VERTICAL);\r\n }\r\n\r\n /**\r\n * Fills the specified area with the background paint. If the background\r\n * paint is an instance of <code>GradientPaint</code>, the gradient will\r\n * run in the direction suggested by the plot's orientation.\r\n *\r\n * @param g2 the graphics target.\r\n * @param area the plot area.\r\n * @param orientation the plot orientation (<code>null</code> not\r\n * permitted).\r\n *\r\n * @since 1.0.6\r\n */\r\n protected void fillBackground(Graphics2D g2, Rectangle2D area,\r\n PlotOrientation orientation) {\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n if (this.backgroundPaint == null) {\r\n return;\r\n }\r\n Paint p = this.backgroundPaint;\r\n if (p instanceof GradientPaint) {\r\n GradientPaint gp = (GradientPaint) p;\r\n if (orientation == PlotOrientation.VERTICAL) {\r\n p = new GradientPaint((float) area.getCenterX(),\r\n (float) area.getMaxY(), gp.getColor1(),\r\n (float) area.getCenterX(), (float) area.getMinY(),\r\n gp.getColor2());\r\n }\r\n else if (orientation == PlotOrientation.HORIZONTAL) {\r\n p = new GradientPaint((float) area.getMinX(),\r\n (float) area.getCenterY(), gp.getColor1(),\r\n (float) area.getMaxX(), (float) area.getCenterY(),\r\n gp.getColor2());\r\n }\r\n }\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundAlpha));\r\n g2.setPaint(p);\r\n g2.fill(area);\r\n g2.setComposite(originalComposite);\r\n }\r\n\r\n /**\r\n * Draws the background image (if there is one) aligned within the\r\n * specified area.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n *\r\n * @see #getBackgroundImage()\r\n * @see #getBackgroundImageAlignment()\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void drawBackgroundImage(Graphics2D g2, Rectangle2D area) {\r\n if (this.backgroundImage == null) {\r\n return; // nothing to do\r\n }\r\n Composite savedComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundImageAlpha));\r\n Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,\r\n this.backgroundImage.getWidth(null),\r\n this.backgroundImage.getHeight(null));\r\n Align.align(dest, area, this.backgroundImageAlignment);\r\n Shape savedClip = g2.getClip();\r\n g2.clip(area);\r\n g2.drawImage(this.backgroundImage, (int) dest.getX(),\r\n (int) dest.getY(), (int) dest.getWidth() + 1,\r\n (int) dest.getHeight() + 1, null);\r\n g2.setClip(savedClip);\r\n g2.setComposite(savedComposite);\r\n }\r\n\r\n /**\r\n * Draws the plot outline. This method will be called during the chart\r\n * drawing process and is declared public so that it can be accessed by the\r\n * renderers used by certain subclasses. You shouldn't need to call this\r\n * method directly.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot should be drawn.\r\n */\r\n public void drawOutline(Graphics2D g2, Rectangle2D area) {\r\n if (!this.outlineVisible) {\r\n return;\r\n }\r\n if ((this.outlineStroke != null) && (this.outlinePaint != null)) {\r\n g2.setStroke(this.outlineStroke);\r\n g2.setPaint(this.outlinePaint);\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);\r\n g2.draw(area);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n }\r\n\r\n /**\r\n * Draws a message to state that there is no data to plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot should be drawn.\r\n */\r\n protected void drawNoDataMessage(Graphics2D g2, Rectangle2D area) {\r\n Shape savedClip = g2.getClip();\r\n g2.clip(area);\r\n String message = this.noDataMessage;\r\n if (message != null) {\r\n g2.setFont(this.noDataMessageFont);\r\n g2.setPaint(this.noDataMessagePaint);\r\n TextBlock block = TextUtilities.createTextBlock(\r\n this.noDataMessage, this.noDataMessageFont,\r\n this.noDataMessagePaint, 0.9f * (float) area.getWidth(),\r\n new G2TextMeasurer(g2));\r\n block.draw(g2, (float) area.getCenterX(),\r\n (float) area.getCenterY(), TextBlockAnchor.CENTER);\r\n }\r\n g2.setClip(savedClip);\r\n }\r\n\r\n /**\r\n * Creates a plot entity that contains a reference to the plot and the\r\n * data area as shape.\r\n *\r\n * @param dataArea the data area used as hot spot for the entity.\r\n * @param plotState the plot rendering info containing a reference to the\r\n * EntityCollection.\r\n * @param toolTip the tool tip (defined in the respective Plot\r\n * subclass) (<code>null</code> permitted).\r\n * @param urlText the url (defined in the respective Plot subclass)\r\n * (<code>null</code> permitted).\r\n *\r\n * @since 1.0.13\r\n */\r\n protected void createAndAddEntity(Rectangle2D dataArea,\r\n PlotRenderingInfo plotState, String toolTip, String urlText) {\r\n if (plotState != null && plotState.getOwner() != null) {\r\n EntityCollection e = plotState.getOwner().getEntityCollection();\r\n if (e != null) {\r\n e.add(new PlotEntity(dataArea, this, toolTip, urlText));\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the plot. Since the plot does not maintain any\r\n * information about where it has been drawn, the plot rendering info is\r\n * supplied as an argument so that the plot dimensions can be determined.\r\n *\r\n * @param x the x coordinate (in Java2D space).\r\n * @param y the y coordinate (in Java2D space).\r\n * @param info an object containing information about the dimensions of\r\n * the plot.\r\n */\r\n public void handleClick(int x, int y, PlotRenderingInfo info) {\r\n // provides a 'no action' default\r\n }\r\n\r\n /**\r\n * Performs a zoom on the plot. Subclasses should override if zooming is\r\n * appropriate for the type of plot.\r\n *\r\n * @param percent the zoom percentage.\r\n */\r\n public void zoom(double percent) {\r\n // do nothing by default.\r\n }\r\n\r\n /**\r\n * Receives notification of a change to an {@link Annotation} added to\r\n * this plot.\r\n *\r\n * @param event information about the event (not used here).\r\n *\r\n * @since 1.0.14\r\n */\r\n @Override\r\n public void annotationChanged(AnnotationChangeEvent event) {\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Receives notification of a change to one of the plot's axes.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void axisChanged(AxisChangeEvent event) {\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Receives notification of a change to the plot's dataset.\r\n * <P>\r\n * The plot reacts by passing on a plot change event to all registered\r\n * listeners.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void datasetChanged(DatasetChangeEvent event) {\r\n PlotChangeEvent newEvent = new PlotChangeEvent(this);\r\n newEvent.setType(ChartChangeEventType.DATASET_UPDATED);\r\n notifyListeners(newEvent);\r\n }\r\n\r\n /**\r\n * Receives notification of a change to a marker that is assigned to the\r\n * plot.\r\n *\r\n * @param event the event.\r\n *\r\n * @since 1.0.3\r\n */\r\n @Override\r\n public void markerChanged(MarkerChangeEvent event) {\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adjusts the supplied x-value.\r\n *\r\n * @param x the x-value.\r\n * @param w1 width 1.\r\n * @param w2 width 2.\r\n * @param edge the edge (left or right).\r\n *\r\n * @return The adjusted x-value.\r\n */\r\n protected double getRectX(double x, double w1, double w2,\r\n RectangleEdge edge) {\r\n\r\n double result = x;\r\n if (edge == RectangleEdge.LEFT) {\r\n result = result + w1;\r\n }\r\n else if (edge == RectangleEdge.RIGHT) {\r\n result = result + w2;\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Adjusts the supplied y-value.\r\n *\r\n * @param y the x-value.\r\n * @param h1 height 1.\r\n * @param h2 height 2.\r\n * @param edge the edge (top or bottom).\r\n *\r\n * @return The adjusted y-value.\r\n */\r\n protected double getRectY(double y, double h1, double h2,\r\n RectangleEdge edge) {\r\n\r\n double result = y;\r\n if (edge == RectangleEdge.TOP) {\r\n result = result + h1;\r\n }\r\n else if (edge == RectangleEdge.BOTTOM) {\r\n result = result + h2;\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Tests this plot for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof Plot)) {\r\n return false;\r\n }\r\n Plot that = (Plot) obj;\r\n if (!ObjectUtilities.equal(this.noDataMessage, that.noDataMessage)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(\r\n this.noDataMessageFont, that.noDataMessageFont\r\n )) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.noDataMessagePaint,\r\n that.noDataMessagePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.insets, that.insets)) {\r\n return false;\r\n }\r\n if (this.outlineVisible != that.outlineVisible) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.outlineStroke, that.outlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.backgroundPaint, that.backgroundPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundImage,\r\n that.backgroundImage)) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlignment != that.backgroundImageAlignment) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlpha != that.backgroundImageAlpha) {\r\n return false;\r\n }\r\n if (this.foregroundAlpha != that.foregroundAlpha) {\r\n return false;\r\n }\r\n if (this.backgroundAlpha != that.backgroundAlpha) {\r\n return false;\r\n }\r\n if (!this.drawingSupplier.equals(that.drawingSupplier)) {\r\n return false;\r\n }\r\n if (this.notify != that.notify) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Creates a clone of the plot.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if some component of the plot does not\r\n * support cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n\r\n Plot clone = (Plot) super.clone();\r\n // private Plot parent <-- don't clone the parent plot, but take care\r\n // childs in combined plots instead\r\n if (this.datasetGroup != null) {\r\n clone.datasetGroup\r\n = (DatasetGroup) ObjectUtilities.clone(this.datasetGroup);\r\n }\r\n clone.drawingSupplier\r\n = (DrawingSupplier) ObjectUtilities.clone(this.drawingSupplier);\r\n clone.listenerList = new EventListenerList();\r\n return clone;\r\n\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writePaint(this.noDataMessagePaint, stream);\r\n SerialUtilities.writeStroke(this.outlineStroke, stream);\r\n SerialUtilities.writePaint(this.outlinePaint, stream);\r\n // backgroundImage\r\n SerialUtilities.writePaint(this.backgroundPaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.noDataMessagePaint = SerialUtilities.readPaint(stream);\r\n this.outlineStroke = SerialUtilities.readStroke(stream);\r\n this.outlinePaint = SerialUtilities.readPaint(stream);\r\n // backgroundImage\r\n this.backgroundPaint = SerialUtilities.readPaint(stream);\r\n\r\n this.listenerList = new EventListenerList();\r\n\r\n }\r\n\r\n /**\r\n * Resolves a domain axis location for a given plot orientation.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param orientation the orientation (<code>null</code> not permitted).\r\n *\r\n * @return The edge (never <code>null</code>).\r\n */\r\n public static RectangleEdge resolveDomainAxisLocation(\r\n AxisLocation location, PlotOrientation orientation) {\r\n\r\n ParamChecks.nullNotPermitted(location, \"location\");\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n\r\n RectangleEdge result = null;\r\n if (location == AxisLocation.TOP_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n }\r\n else if (location == AxisLocation.TOP_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n }\r\n // the above should cover all the options...\r\n if (result == null) {\r\n throw new IllegalStateException(\"resolveDomainAxisLocation()\");\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Resolves a range axis location for a given plot orientation.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param orientation the orientation (<code>null</code> not permitted).\r\n *\r\n * @return The edge (never <code>null</code>).\r\n */\r\n public static RectangleEdge resolveRangeAxisLocation(\r\n AxisLocation location, PlotOrientation orientation) {\r\n\r\n ParamChecks.nullNotPermitted(location, \"location\");\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n\r\n RectangleEdge result = null;\r\n if (location == AxisLocation.TOP_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n }\r\n else if (location == AxisLocation.TOP_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n }\r\n\r\n // the above should cover all the options...\r\n if (result == null) {\r\n throw new IllegalStateException(\"resolveRangeAxisLocation()\");\r\n }\r\n return result;\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "PlotOrientation", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/PlotOrientation.java", "snippet": "public final class PlotOrientation implements Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -2508771828190337782L;\r\n\r\n /** For a plot where the range axis is horizontal. */\r\n public static final PlotOrientation HORIZONTAL\r\n = new PlotOrientation(\"PlotOrientation.HORIZONTAL\");\r\n\r\n /** For a plot where the range axis is vertical. */\r\n public static final PlotOrientation VERTICAL\r\n = new PlotOrientation(\"PlotOrientation.VERTICAL\");\r\n\r\n /** The name. */\r\n private String name;\r\n\r\n /**\r\n * Private constructor.\r\n *\r\n * @param name the name.\r\n */\r\n private PlotOrientation(String name) {\r\n this.name = name;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this orientation is <code>HORIZONTAL</code>,\r\n * and <code>false</code> otherwise. \r\n * \r\n * @return A boolean.\r\n * \r\n * @since 1.0.18\r\n */\r\n public boolean isHorizontal() {\r\n return this.equals(PlotOrientation.HORIZONTAL);\r\n }\r\n \r\n /**\r\n * Returns <code>true</code> if this orientation is <code>VERTICAL</code>,\r\n * and <code>false</code> otherwise.\r\n * \r\n * @return A boolean.\r\n * \r\n * @since 1.0.18\r\n */\r\n public boolean isVertical() {\r\n return this.equals(PlotOrientation.VERTICAL);\r\n }\r\n \r\n /**\r\n * Returns a string representing the object.\r\n *\r\n * @return The string.\r\n */\r\n @Override\r\n public String toString() {\r\n return this.name;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this object is equal to the specified\r\n * object, and <code>false</code> otherwise.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) {\r\n return true;\r\n }\r\n if (!(obj instanceof PlotOrientation)) {\r\n return false;\r\n }\r\n PlotOrientation orientation = (PlotOrientation) obj;\r\n if (!this.name.equals(orientation.toString())) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code for this instance.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n return this.name.hashCode();\r\n }\r\n\r\n /**\r\n * Ensures that serialization returns the unique instances.\r\n *\r\n * @return The object.\r\n *\r\n * @throws ObjectStreamException if there is a problem.\r\n */\r\n private Object readResolve() throws ObjectStreamException {\r\n Object result = null;\r\n if (this.equals(PlotOrientation.HORIZONTAL)) {\r\n result = PlotOrientation.HORIZONTAL;\r\n }\r\n else if (this.equals(PlotOrientation.VERTICAL)) {\r\n result = PlotOrientation.VERTICAL;\r\n }\r\n return result;\r\n }\r\n\r\n}\r" }, { "identifier": "PlotRenderingInfo", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/PlotRenderingInfo.java", "snippet": "public class PlotRenderingInfo implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 8446720134379617220L;\r\n\r\n /** The owner of this info. */\r\n private ChartRenderingInfo owner;\r\n\r\n /** The plot area. */\r\n private transient Rectangle2D plotArea;\r\n\r\n /** The data area. */\r\n private transient Rectangle2D dataArea;\r\n\r\n /**\r\n * Storage for the plot rendering info objects belonging to the subplots.\r\n */\r\n private List subplotInfo;\r\n\r\n /**\r\n * Creates a new instance.\r\n *\r\n * @param owner the owner (<code>null</code> permitted).\r\n */\r\n public PlotRenderingInfo(ChartRenderingInfo owner) {\r\n this.owner = owner;\r\n this.dataArea = new Rectangle2D.Double();\r\n this.subplotInfo = new java.util.ArrayList();\r\n }\r\n\r\n /**\r\n * Returns the owner (as specified in the constructor).\r\n *\r\n * @return The owner (possibly <code>null</code>).\r\n */\r\n public ChartRenderingInfo getOwner() {\r\n return this.owner;\r\n }\r\n\r\n /**\r\n * Returns the plot area (in Java2D space).\r\n *\r\n * @return The plot area (possibly <code>null</code>).\r\n *\r\n * @see #setPlotArea(Rectangle2D)\r\n */\r\n public Rectangle2D getPlotArea() {\r\n return this.plotArea;\r\n }\r\n\r\n /**\r\n * Sets the plot area.\r\n *\r\n * @param area the plot area (in Java2D space, <code>null</code>\r\n * permitted but discouraged)\r\n *\r\n * @see #getPlotArea()\r\n */\r\n public void setPlotArea(Rectangle2D area) {\r\n this.plotArea = area;\r\n }\r\n\r\n /**\r\n * Returns the plot's data area (in Java2D space).\r\n *\r\n * @return The data area (possibly <code>null</code>).\r\n *\r\n * @see #setDataArea(Rectangle2D)\r\n */\r\n public Rectangle2D getDataArea() {\r\n return this.dataArea;\r\n }\r\n\r\n /**\r\n * Sets the data area.\r\n *\r\n * @param area the data area (in Java2D space, <code>null</code> permitted\r\n * but discouraged).\r\n *\r\n * @see #getDataArea()\r\n */\r\n public void setDataArea(Rectangle2D area) {\r\n this.dataArea = area;\r\n }\r\n\r\n /**\r\n * Returns the number of subplots (possibly zero).\r\n *\r\n * @return The subplot count.\r\n */\r\n public int getSubplotCount() {\r\n return this.subplotInfo.size();\r\n }\r\n\r\n /**\r\n * Adds the info for a subplot.\r\n *\r\n * @param info the subplot info.\r\n *\r\n * @see #getSubplotInfo(int)\r\n */\r\n public void addSubplotInfo(PlotRenderingInfo info) {\r\n this.subplotInfo.add(info);\r\n }\r\n\r\n /**\r\n * Returns the info for a subplot.\r\n *\r\n * @param index the subplot index.\r\n *\r\n * @return The info.\r\n *\r\n * @see #addSubplotInfo(PlotRenderingInfo)\r\n */\r\n public PlotRenderingInfo getSubplotInfo(int index) {\r\n return (PlotRenderingInfo) this.subplotInfo.get(index);\r\n }\r\n\r\n /**\r\n * Returns the index of the subplot that contains the specified\r\n * (x, y) point (the \"source\" point). The source point will usually\r\n * come from a mouse click on a {@link org.jfree.chart.ChartPanel},\r\n * and this method is then used to determine the subplot that\r\n * contains the source point.\r\n *\r\n * @param source the source point (in Java2D space, <code>null</code> not\r\n * permitted).\r\n *\r\n * @return The subplot index (or -1 if no subplot contains\r\n * <code>source</code>).\r\n */\r\n public int getSubplotIndex(Point2D source) {\r\n ParamChecks.nullNotPermitted(source, \"source\");\r\n int subplotCount = getSubplotCount();\r\n for (int i = 0; i < subplotCount; i++) {\r\n PlotRenderingInfo info = getSubplotInfo(i);\r\n Rectangle2D area = info.getDataArea();\r\n if (area.contains(source)) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Tests this instance for equality against an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) {\r\n return true;\r\n }\r\n if (!(obj instanceof PlotRenderingInfo)) {\r\n return false;\r\n }\r\n PlotRenderingInfo that = (PlotRenderingInfo) obj;\r\n if (!ObjectUtilities.equal(this.dataArea, that.dataArea)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.plotArea, that.plotArea)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.subplotInfo, that.subplotInfo)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a clone of this object.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if there is a problem cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n PlotRenderingInfo clone = (PlotRenderingInfo) super.clone();\r\n if (this.plotArea != null) {\r\n clone.plotArea = (Rectangle2D) this.plotArea.clone();\r\n }\r\n if (this.dataArea != null) {\r\n clone.dataArea = (Rectangle2D) this.dataArea.clone();\r\n }\r\n clone.subplotInfo = new java.util.ArrayList(this.subplotInfo.size());\r\n for (int i = 0; i < this.subplotInfo.size(); i++) {\r\n PlotRenderingInfo info\r\n = (PlotRenderingInfo) this.subplotInfo.get(i);\r\n clone.subplotInfo.add(info.clone());\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeShape(this.dataArea, stream);\r\n SerialUtilities.writeShape(this.plotArea, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.dataArea = (Rectangle2D) SerialUtilities.readShape(stream);\r\n this.plotArea = (Rectangle2D) SerialUtilities.readShape(stream);\r\n }\r\n\r\n}\r" }, { "identifier": "ValueAxisPlot", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/ValueAxisPlot.java", "snippet": "public interface ValueAxisPlot {\r\n\r\n /**\r\n * Returns the data range that should apply for the specified axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The data range.\r\n */\r\n public Range getDataRange(ValueAxis axis);\r\n\r\n}\r" }, { "identifier": "Zoomable", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/Zoomable.java", "snippet": "public interface Zoomable {\r\n\r\n /**\r\n * Returns <code>true</code> if the plot's domain is zoomable, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isRangeZoomable()\r\n */\r\n public boolean isDomainZoomable();\r\n\r\n /**\r\n * Returns <code>true</code> if the plot's range is zoomable, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isDomainZoomable()\r\n */\r\n public boolean isRangeZoomable();\r\n\r\n /**\r\n * Returns the orientation of the plot.\r\n *\r\n * @return The orientation.\r\n */\r\n public PlotOrientation getOrientation();\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n * The <code>source</code> point can be used in some cases to identify a\r\n * subplot, or to determine the center of zooming (refer to the\r\n * documentation of the implementing class for details).\r\n *\r\n * @param factor the zoom factor.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D coordinates).\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D)\r\n */\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo state,\r\n Point2D source);\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n * The <code>source</code> point can be used in some cases to identify a\r\n * subplot, or to determine the center of zooming (refer to the\r\n * documentation of the implementing class for details).\r\n *\r\n * @param factor the zoom factor.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D coordinates).\r\n * @param useAnchor use source point as zoom anchor?\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo state,\r\n Point2D source, boolean useAnchor);\r\n\r\n /**\r\n * Zooms in on the domain axes. The <code>source</code> point can be used\r\n * in some cases to identify a subplot for zooming.\r\n *\r\n * @param lowerPercent the new lower bound.\r\n * @param upperPercent the new upper bound.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D coordinates).\r\n *\r\n * @see #zoomRangeAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n public void zoomDomainAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo state, Point2D source);\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n * The <code>source</code> point can be used in some cases to identify a\r\n * subplot, or to determine the center of zooming (refer to the\r\n * documentation of the implementing class for details).\r\n *\r\n * @param factor the zoom factor.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D coordinates).\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D)\r\n */\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo state,\r\n Point2D source);\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n * The <code>source</code> point can be used in some cases to identify a\r\n * subplot, or to determine the center of zooming (refer to the\r\n * documentation of the implementing class for details).\r\n *\r\n * @param factor the zoom factor.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D coordinates).\r\n * @param useAnchor use source point as zoom anchor?\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D)\r\n *\r\n * @since 1.0.7\r\n */\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo state,\r\n Point2D source, boolean useAnchor);\r\n\r\n /**\r\n * Zooms in on the range axes. The <code>source</code> point can be used\r\n * in some cases to identify a subplot for zooming.\r\n *\r\n * @param lowerPercent the new lower bound.\r\n * @param upperPercent the new upper bound.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D coordinates).\r\n *\r\n * @see #zoomDomainAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n public void zoomRangeAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo state, Point2D source);\r\n\r\n}\r" }, { "identifier": "ResourceBundleWrapper", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/util/ResourceBundleWrapper.java", "snippet": "public class ResourceBundleWrapper {\r\n\r\n /**\r\n * A special class loader with no code base lookup. This field may be\r\n * <code>null</code> (the field is only initialised if removeCodeBase() is\r\n * called from an applet).\r\n */\r\n private static URLClassLoader noCodeBaseClassLoader;\r\n\r\n /**\r\n * Private constructor.\r\n */\r\n private ResourceBundleWrapper() {\r\n // all methods are static, no need to instantiate\r\n }\r\n\r\n /**\r\n * Instantiate a {@link URLClassLoader} for resource lookups where the\r\n * codeBase URL is removed. This method is typically called from an\r\n * applet's init() method. If this method is never called, the\r\n * <code>getBundle()</code> methods map to the standard\r\n * {@link ResourceBundle} lookup methods.\r\n *\r\n * @param codeBase the codeBase URL.\r\n * @param urlClassLoader the class loader.\r\n */\r\n public static void removeCodeBase(URL codeBase,\r\n URLClassLoader urlClassLoader) {\r\n List urlsNoBase = new ArrayList();\r\n\r\n URL[] urls = urlClassLoader.getURLs();\r\n for (int i = 0; i < urls.length; i++) {\r\n if (!urls[i].sameFile(codeBase)) {\r\n urlsNoBase.add(urls[i]);\r\n }\r\n }\r\n // substitute the filtered URL list\r\n URL[] urlsNoBaseArray = (URL[]) urlsNoBase.toArray(new URL[0]);\r\n noCodeBaseClassLoader = URLClassLoader.newInstance(urlsNoBaseArray);\r\n }\r\n\r\n /**\r\n * Finds and returns the specified resource bundle.\r\n *\r\n * @param baseName the base name.\r\n *\r\n * @return The resource bundle.\r\n */\r\n public static ResourceBundle getBundle(String baseName) {\r\n // the noCodeBaseClassLoader is configured by a call to the\r\n // removeCodeBase() method, typically in the init() method of an\r\n // applet...\r\n if (noCodeBaseClassLoader != null) {\r\n return ResourceBundle.getBundle(baseName, Locale.getDefault(),\r\n noCodeBaseClassLoader);\r\n }\r\n else {\r\n // standard ResourceBundle behaviour\r\n return ResourceBundle.getBundle(baseName);\r\n }\r\n }\r\n\r\n /**\r\n * Finds and returns the specified resource bundle.\r\n *\r\n * @param baseName the base name.\r\n * @param locale the locale.\r\n *\r\n * @return The resource bundle.\r\n */\r\n public static ResourceBundle getBundle(String baseName, Locale locale) {\r\n\r\n // the noCodeBaseClassLoader is configured by a call to the\r\n // removeCodeBase() method, typically in the init() method of an\r\n // applet...\r\n if (noCodeBaseClassLoader != null) {\r\n return ResourceBundle.getBundle(baseName, locale,\r\n noCodeBaseClassLoader);\r\n }\r\n else {\r\n // standard ResourceBundle behaviour\r\n return ResourceBundle.getBundle(baseName, locale);\r\n }\r\n }\r\n\r\n /**\r\n * Maps directly to <code>ResourceBundle.getBundle(baseName, locale,\r\n * loader)</code>.\r\n *\r\n * @param baseName the base name.\r\n * @param locale the locale.\r\n * @param loader the class loader.\r\n *\r\n * @return The resource bundle.\r\n */\r\n public static ResourceBundle getBundle(String baseName, Locale locale,\r\n ClassLoader loader) {\r\n return ResourceBundle.getBundle(baseName, locale, loader);\r\n }\r\n\r\n}\r" }, { "identifier": "SWTChartEditor", "path": "lib/jfreechart-1.0.19/swt/org/jfree/experimental/chart/swt/editor/SWTChartEditor.java", "snippet": "public class SWTChartEditor implements ChartEditor {\n\n /** The shell */\n private Shell shell;\n\n /** The chart which the properties have to be edited */\n private JFreeChart chart;\n\n /** A composite for displaying/editing the properties of the title. */\n private SWTTitleEditor titleEditor;\n\n /** A composite for displaying/editing the properties of the plot. */\n private SWTPlotEditor plotEditor;\n\n /** A composite for displaying/editing the other properties of the chart. */\n private SWTOtherEditor otherEditor;\n\n /** The resourceBundle for the localization. */\n protected static ResourceBundle localizationResources\n = ResourceBundleWrapper.getBundle(\n \"org.jfree.chart.editor.LocalizationBundle\");\n\n /**\n * Creates a new editor.\n *\n * @param display the display.\n * @param chart2edit the chart to edit.\n */\n public SWTChartEditor(Display display, JFreeChart chart2edit) {\n this.shell = new Shell(display, SWT.DIALOG_TRIM);\n this.shell.setSize(400, 500);\n this.chart = chart2edit;\n this.shell.setText(ResourceBundleWrapper.getBundle(\n \"org.jfree.chart.LocalizationBundle\").getString(\n \"Chart_Properties\"));\n GridLayout layout = new GridLayout(2, true);\n layout.marginLeft = layout.marginTop = layout.marginRight\n = layout.marginBottom = 5;\n this.shell.setLayout(layout);\n Composite main = new Composite(this.shell, SWT.NONE);\n main.setLayout(new FillLayout());\n main.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));\n\n TabFolder tab = new TabFolder(main, SWT.BORDER);\n // build first tab\n TabItem item1 = new TabItem(tab, SWT.NONE);\n item1.setText(\" \" + localizationResources.getString(\"Title\") + \" \");\n this.titleEditor = new SWTTitleEditor(tab, SWT.NONE,\n this.chart.getTitle());\n item1.setControl(this.titleEditor);\n // build second tab\n TabItem item2 = new TabItem(tab, SWT.NONE);\n item2.setText(\" \" + localizationResources.getString(\"Plot\") + \" \");\n this.plotEditor = new SWTPlotEditor(tab, SWT.NONE,\n this.chart.getPlot());\n item2.setControl(this.plotEditor);\n // build the third tab\n TabItem item3 = new TabItem(tab, SWT.NONE);\n item3.setText(\" \" + localizationResources.getString(\"Other\") + \" \");\n this.otherEditor = new SWTOtherEditor(tab, SWT.NONE, this.chart);\n item3.setControl(this.otherEditor);\n\n // ok and cancel buttons\n Button ok = new Button(this.shell, SWT.PUSH | SWT.OK);\n ok.setText(\" Ok \");\n ok.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));\n ok.addSelectionListener(new SelectionAdapter() {\n public void widgetSelected(SelectionEvent e) {\n updateChart(SWTChartEditor.this.chart);\n SWTChartEditor.this.shell.dispose();\n }\n });\n Button cancel = new Button(this.shell, SWT.PUSH);\n cancel.setText(\" Cancel \");\n cancel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));\n cancel.addSelectionListener(new SelectionAdapter() {\n public void widgetSelected(SelectionEvent e) {\n SWTChartEditor.this.shell.dispose();\n }\n });\n }\n\n /**\n * Opens the editor.\n */\n public void open() {\n this.shell.open();\n this.shell.layout();\n while (!this.shell.isDisposed()) {\n if (!this.shell.getDisplay().readAndDispatch()) {\n this.shell.getDisplay().sleep();\n }\n }\n }\n\n /**\n * Updates the chart properties.\n *\n * @param chart the chart.\n */\n public void updateChart(JFreeChart chart)\n {\n this.titleEditor.setTitleProperties(chart);\n this.plotEditor.updatePlotProperties(chart.getPlot());\n this.otherEditor.updateChartProperties(chart);\n }\n\n}" }, { "identifier": "SWTGraphics2D", "path": "lib/jfreechart-1.0.19/swt/org/jfree/experimental/swt/SWTGraphics2D.java", "snippet": "public class SWTGraphics2D extends Graphics2D {\n\n /** The swt graphic composite */\n private GC gc;\n\n /**\n * The rendering hints. For now, these are not used, but at least the\n * basic mechanism is present.\n */\n private RenderingHints hints;\n\n /** A reference to the compositing rule to apply. This is necessary\n * due to the poor compositing interface of the SWT toolkit. */\n private java.awt.Composite composite;\n\n /** A HashMap to store the Swt color resources. */\n private Map colorsPool = new HashMap();\n\n /** A HashMap to store the Swt font resources. */\n private Map fontsPool = new HashMap();\n\n /** A HashMap to store the Swt transform resources. */\n private Map transformsPool = new HashMap();\n\n /** A List to store the Swt resources. */\n private List resourcePool = new ArrayList();\n\n /**\n * Creates a new instance.\n *\n * @param gc the graphics context.\n */\n public SWTGraphics2D(GC gc) {\n super();\n this.gc = gc;\n this.hints = new RenderingHints(null);\n this.composite = AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f);\n setStroke(new BasicStroke());\n }\n\n /**\n * Not implemented yet - see {@link Graphics#create()}.\n *\n * @return <code>null</code>.\n */\n public Graphics create() {\n // TODO Auto-generated method stub\n return null;\n }\n\n /**\n * Not implemented yet - see {@link Graphics2D#getDeviceConfiguration()}.\n *\n * @return <code>null</code>.\n */\n public GraphicsConfiguration getDeviceConfiguration() {\n // TODO Auto-generated method stub\n return null;\n }\n\n /**\n * Returns the current value for the specified hint key, or\n * <code>null</code> if no value is set.\n *\n * @param hintKey the hint key (<code>null</code> permitted).\n *\n * @return The hint value, or <code>null</code>.\n *\n * @see #setRenderingHint(RenderingHints.Key, Object)\n */\n public Object getRenderingHint(Key hintKey) {\n return this.hints.get(hintKey);\n }\n\n /**\n * Sets the value for a rendering hint. For now, this graphics context\n * ignores all hints.\n *\n * @param hintKey the key (<code>null</code> not permitted).\n * @param hintValue the value (must be compatible with the specified key).\n *\n * @throws IllegalArgumentException if <code>hintValue</code> is not\n * compatible with the <code>hintKey</code>.\n *\n * @see #getRenderingHint(RenderingHints.Key)\n */\n public void setRenderingHint(Key hintKey, Object hintValue) {\n this.hints.put(hintKey, hintValue);\n }\n\n /**\n * Returns a copy of the hints collection for this graphics context.\n *\n * @return A copy of the hints collection.\n */\n public RenderingHints getRenderingHints() {\n return (RenderingHints) this.hints.clone();\n }\n\n /**\n * Adds the hints in the specified map to the graphics context, replacing\n * any existing hints. For now, this graphics context ignores all hints.\n *\n * @param hints the hints (<code>null</code> not permitted).\n *\n * @see #setRenderingHints(Map)\n */\n public void addRenderingHints(Map hints) {\n this.hints.putAll(hints);\n }\n\n /**\n * Replaces the existing hints with those contained in the specified\n * map. Note that, for now, this graphics context ignores all hints.\n *\n * @param hints the hints (<code>null</code> not permitted).\n *\n * @see #addRenderingHints(Map)\n */\n public void setRenderingHints(Map hints) {\n if (hints == null) {\n throw new NullPointerException(\"Null 'hints' argument.\");\n }\n this.hints = new RenderingHints(hints);\n }\n\n /**\n * Returns the current paint for this graphics context.\n *\n * @return The current paint.\n *\n * @see #setPaint(Paint)\n */\n public Paint getPaint() {\n // TODO: it might be a good idea to keep a reference to the color\n // specified in setPaint() or setColor(), rather than creating a\n // new object every time getPaint() is called.\n return SWTUtils.toAwtColor(this.gc.getForeground());\n }\n\n /**\n * Sets the paint for this graphics context. For now, this graphics\n * context only supports instances of {@link Color} or\n * {@link GradientPaint} (in the latter case there is no real gradient\n * support, the paint used is the <code>Color</code> returned by\n * <code>getColor1()</code>).\n *\n * @param paint the paint (<code>null</code> permitted, ignored).\n *\n * @see #getPaint()\n * @see #setColor(Color)\n */\n public void setPaint(Paint paint) {\n if (paint == null) {\n return; // to be consistent with other Graphics2D implementations\n }\n if (paint instanceof Color) {\n setColor((Color) paint);\n }\n else if (paint instanceof GradientPaint) {\n GradientPaint gp = (GradientPaint) paint;\n setColor(gp.getColor1());\n }\n else {\n throw new RuntimeException(\"Can only handle 'Color' at present.\");\n }\n }\n\n /**\n * Returns the current color for this graphics context.\n *\n * @return The current color.\n *\n * @see #setColor(Color)\n */\n public Color getColor() {\n // TODO: it might be a good idea to keep a reference to the color\n // specified in setPaint() or setColor(), rather than creating a\n // new object every time getPaint() is called.\n return SWTUtils.toAwtColor(this.gc.getForeground());\n }\n\n /**\n * Sets the current color for this graphics context.\n *\n * @param color the color (<code>null</code> permitted but ignored).\n *\n * @see #getColor()\n */\n public void setColor(Color color) {\n if (color == null) {\n return;\n }\n org.eclipse.swt.graphics.Color swtColor = getSwtColorFromPool(color);\n this.gc.setForeground(swtColor);\n // handle transparency and compositing.\n if (this.composite instanceof AlphaComposite) {\n AlphaComposite acomp = (AlphaComposite) this.composite;\n switch (acomp.getRule()) {\n case AlphaComposite.SRC_OVER:\n this.gc.setAlpha((int) (color.getAlpha() * acomp.getAlpha()));\n break;\n default:\n this.gc.setAlpha(color.getAlpha());\n break;\n }\n }\n }\n\n private Color backgroundColor;\n \n /**\n * Sets the background colour.\n *\n * @param color the colour.\n */\n public void setBackground(Color color) {\n // since this is only used by clearRect(), we don't update the GC yet\n this.backgroundColor = color;\n }\n\n /**\n * Returns the background colour.\n *\n * @return The background colour (possibly <code>null</code>)..\n */\n public Color getBackground() {\n return this.backgroundColor;\n }\n\n /**\n * Not implemented - see {@link Graphics#setPaintMode()}.\n */\n public void setPaintMode() {\n // TODO Auto-generated method stub\n }\n\n /**\n * Not implemented - see {@link Graphics#setXORMode(Color)}.\n *\n * @param color the colour.\n */\n public void setXORMode(Color color) {\n // TODO Auto-generated method stub\n }\n\n /**\n * Returns the current composite.\n *\n * @return The current composite.\n *\n * @see #setComposite(Composite)\n */\n public Composite getComposite() {\n return this.composite;\n }\n\n /**\n * Sets the current composite. This implementation currently supports\n * only the {@link AlphaComposite} class.\n *\n * @param comp the composite (<code>null</code> not permitted).\n */\n public void setComposite(Composite comp) {\n if (comp == null) {\n throw new IllegalArgumentException(\"Null 'comp' argument.\");\n }\n this.composite = comp;\n if (comp instanceof AlphaComposite) {\n AlphaComposite acomp = (AlphaComposite) comp;\n int alpha = (int) (acomp.getAlpha() * 0xFF);\n this.gc.setAlpha(alpha);\n }\n }\n\n /**\n * Returns the current stroke for this graphics context.\n *\n * @return The current stroke.\n *\n * @see #setStroke(Stroke)\n */\n public Stroke getStroke() {\n return new BasicStroke(this.gc.getLineWidth(),\n toAwtLineCap(this.gc.getLineCap()),\n toAwtLineJoin(this.gc.getLineJoin()));\n }\n\n /**\n * Sets the stroke for this graphics context. For now, this implementation\n * only recognises the {@link BasicStroke} class.\n *\n * @param stroke the stroke (<code>null</code> not permitted).\n *\n * @see #getStroke()\n */\n public void setStroke(Stroke stroke) {\n if (stroke == null) {\n throw new IllegalArgumentException(\"Null 'stroke' argument.\");\n }\n if (stroke instanceof BasicStroke) {\n BasicStroke bs = (BasicStroke) stroke;\n this.gc.setLineWidth((int) bs.getLineWidth());\n this.gc.setLineJoin(toSwtLineJoin(bs.getLineJoin()));\n this.gc.setLineCap(toSwtLineCap(bs.getEndCap()));\n\n // set the line style to solid by default\n this.gc.setLineStyle(SWT.LINE_SOLID);\n\n // apply dash style if any\n float[] dashes = bs.getDashArray();\n if (dashes != null) {\n int[] swtDashes = new int[dashes.length];\n for (int i = 0; i < swtDashes.length; i++) {\n swtDashes[i] = (int) dashes[i];\n }\n this.gc.setLineDash(swtDashes);\n }\n }\n else {\n throw new RuntimeException(\n \"Can only handle 'Basic Stroke' at present.\");\n }\n }\n\n /**\n * Applies the specified clip.\n *\n * @param s the shape for the clip.\n */\n public void clip(Shape s) {\n Path path = toSwtPath(s);\n this.gc.setClipping(path);\n path.dispose();\n }\n\n /**\n * Returns the clip bounds.\n *\n * @return The clip bounds.\n */\n public Rectangle getClipBounds() {\n org.eclipse.swt.graphics.Rectangle clip = this.gc.getClipping();\n return new Rectangle(clip.x, clip.y, clip.width, clip.height);\n }\n\n /**\n * Sets the clipping to the intersection of the current clip region and\n * the specified rectangle.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the width.\n * @param height the height.\n */\n public void clipRect(int x, int y, int width, int height) {\n org.eclipse.swt.graphics.Rectangle clip = this.gc.getClipping();\n org.eclipse.swt.graphics.Rectangle r \n = new org.eclipse.swt.graphics.Rectangle(x, y, width, height);\n clip.intersect(r);\n this.gc.setClipping(clip);\n }\n\n /**\n * Returns the current clip.\n *\n * @return The current clip.\n */\n public Shape getClip() {\n return SWTUtils.toAwtRectangle(this.gc.getClipping());\n }\n\n /**\n * Sets the clip region.\n *\n * @param clip the clip.\n */\n public void setClip(Shape clip) {\n if (clip == null) {\n return;\n }\n Path clipPath = toSwtPath(clip);\n this.gc.setClipping(clipPath);\n clipPath.dispose();\n }\n\n /**\n * Sets the clip region to the specified rectangle.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the width.\n * @param height the height.\n */\n public void setClip(int x, int y, int width, int height) {\n this.gc.setClipping(x, y, width, height);\n }\n\n /**\n * Returns the current transform.\n *\n * @return The current transform.\n */\n public AffineTransform getTransform() {\n Transform swtTransform = new Transform(this.gc.getDevice());\n this.gc.getTransform(swtTransform);\n AffineTransform awtTransform = toAwtTransform(swtTransform);\n swtTransform.dispose();\n return awtTransform;\n }\n\n /**\n * Sets the current transform.\n *\n * @param t the transform.\n */\n public void setTransform(AffineTransform t) {\n Transform transform = getSwtTransformFromPool(t);\n this.gc.setTransform(transform);\n }\n\n /**\n * Concatenates the specified transform to the existing transform.\n *\n * @param t the transform.\n */\n public void transform(AffineTransform t) {\n Transform swtTransform = new Transform(this.gc.getDevice());\n this.gc.getTransform(swtTransform);\n swtTransform.multiply(getSwtTransformFromPool(t));\n this.gc.setTransform(swtTransform);\n swtTransform.dispose();\n }\n\n /**\n * Applies a translation.\n *\n * @param x the translation along the x-axis.\n * @param y the translation along the y-axis.\n */\n public void translate(int x, int y) {\n Transform swtTransform = new Transform(this.gc.getDevice());\n this.gc.getTransform(swtTransform);\n swtTransform.translate(x, y);\n this.gc.setTransform(swtTransform);\n swtTransform.dispose();\n }\n\n /**\n * Applies a translation.\n *\n * @param tx the translation along the x-axis.\n * @param ty the translation along the y-axis.\n */\n public void translate(double tx, double ty) {\n translate((int) tx, (int) ty);\n }\n\n /**\n * Applies a rotation transform.\n *\n * @param theta the angle of rotation.\n */\n public void rotate(double theta) {\n AffineTransform t = getTransform();\n t.rotate(theta);\n setTransform(t);\n }\n\n /**\n * Not implemented - see {@link Graphics2D#rotate(double, double, double)}.\n *\n * @see java.awt.Graphics2D#rotate(double, double, double)\n */\n public void rotate(double theta, double x, double y) {\n translate(x, y);\n rotate(theta);\n translate(-x, -y);\n }\n\n /**\n * Applies a scale transform.\n *\n * @param scaleX the scale factor along the x-axis.\n * @param scaleY the scale factor along the y-axis.\n */\n public void scale(double scaleX, double scaleY) {\n Transform swtTransform = new Transform(this.gc.getDevice());\n this.gc.getTransform(swtTransform);\n swtTransform.scale((float) scaleX, (float) scaleY);\n this.gc.setTransform(swtTransform);\n swtTransform.dispose();\n }\n\n /**\n * Applies a shear transform.\n *\n * @param shearX the x-factor.\n * @param shearY the y-factor.\n */\n public void shear(double shearX, double shearY) {\n transform(AffineTransform.getShearInstance(shearX, shearY));\n }\n\n /**\n * Draws the outline of the specified shape using the current stroke and\n * paint settings.\n *\n * @param shape the shape (<code>null</code> not permitted).\n *\n * @see #getPaint()\n * @see #getStroke()\n * @see #fill(Shape)\n */\n public void draw(Shape shape) {\n Path path = toSwtPath(shape);\n this.gc.drawPath(path);\n path.dispose();\n }\n\n /**\n * Draws a line from (x1, y1) to (x2, y2) using the current stroke\n * and paint settings.\n *\n * @param x1 the x-coordinate for the starting point.\n * @param y1 the y-coordinate for the starting point.\n * @param x2 the x-coordinate for the ending point.\n * @param y2 the y-coordinate for the ending point.\n *\n * @see #draw(Shape)\n */\n public void drawLine(int x1, int y1, int x2, int y2) {\n this.gc.drawLine(x1, y1, x2, y2);\n }\n\n /**\n * Draws the outline of the polygon specified by the given points, using\n * the current paint and stroke settings.\n *\n * @param xPoints the x-coordinates.\n * @param yPoints the y-coordinates.\n * @param npoints the number of points in the polygon.\n *\n * @see #draw(Shape)\n */\n public void drawPolygon(int [] xPoints, int [] yPoints, int npoints) {\n drawPolyline(xPoints, yPoints, npoints);\n if (npoints > 1) {\n this.gc.drawLine(xPoints[npoints - 1], yPoints[npoints - 1],\n xPoints[0], yPoints[0]);\n }\n }\n\n /**\n * Draws a sequence of connected lines specified by the given points, using\n * the current paint and stroke settings.\n *\n * @param xPoints the x-coordinates.\n * @param yPoints the y-coordinates.\n * @param npoints the number of points in the polygon.\n *\n * @see #draw(Shape)\n */\n public void drawPolyline(int [] xPoints, int [] yPoints, int npoints) {\n if (npoints > 1) {\n int x0 = xPoints[0];\n int y0 = yPoints[0];\n int x1 = 0, y1 = 0;\n for (int i = 1; i < npoints; i++) {\n x1 = xPoints[i];\n y1 = yPoints[i];\n this.gc.drawLine(x0, y0, x1, y1);\n x0 = x1;\n y0 = y1;\n }\n }\n }\n\n /**\n * Draws an oval that fits within the specified rectangular region.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the frame width.\n * @param height the frame height.\n *\n * @see #fillOval(int, int, int, int)\n * @see #draw(Shape)\n */\n public void drawOval(int x, int y, int width, int height) {\n this.gc.drawOval(x, y, width - 1, height - 1);\n }\n\n /**\n * Draws an arc that is part of an ellipse that fits within the specified\n * framing rectangle.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the frame width.\n * @param height the frame height.\n * @param arcStart the arc starting point, in degrees.\n * @param arcAngle the extent of the arc.\n *\n * @see #fillArc(int, int, int, int, int, int)\n */\n public void drawArc(int x, int y, int width, int height, int arcStart,\n int arcAngle) {\n this.gc.drawArc(x, y, width - 1, height - 1, arcStart, arcAngle);\n }\n\n /**\n * Draws a rectangle with rounded corners that fits within the specified\n * framing rectangle.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the frame width.\n * @param height the frame height.\n * @param arcWidth the width of the arc defining the roundedness of the\n * rectangle's corners.\n * @param arcHeight the height of the arc defining the roundedness of the\n * rectangle's corners.\n *\n * @see #fillRoundRect(int, int, int, int, int, int)\n */\n public void drawRoundRect(int x, int y, int width, int height,\n int arcWidth, int arcHeight) {\n this.gc.drawRoundRectangle(x, y, width - 1, height - 1, arcWidth,\n arcHeight);\n }\n\n /**\n * Fills the specified shape using the current paint.\n *\n * @param shape the shape (<code>null</code> not permitted).\n *\n * @see #getPaint()\n * @see #draw(Shape)\n */\n public void fill(Shape shape) {\n Path path = toSwtPath(shape);\n // Note that for consistency with the AWT implementation, it is\n // necessary to switch temporarily the foreground and background\n // colours\n switchColors();\n this.gc.fillPath(path);\n switchColors();\n path.dispose();\n }\n\n /**\n * Fill a rectangle area on the swt graphic composite.\n * The <code>fillRectangle</code> method of the <code>GC</code>\n * class uses the background color so we must switch colors.\n * @see java.awt.Graphics#fillRect(int, int, int, int)\n */\n public void fillRect(int x, int y, int width, int height) {\n this.switchColors();\n this.gc.fillRectangle(x, y, width, height);\n this.switchColors();\n }\n\n /**\n * Fills the specified rectangle with the current background colour.\n *\n * @param x the x-coordinate for the rectangle.\n * @param y the y-coordinate for the rectangle.\n * @param width the width.\n * @param height the height.\n *\n * @see #fillRect(int, int, int, int)\n */\n public void clearRect(int x, int y, int width, int height) {\n Color bgcolor = getBackground();\n if (bgcolor == null) {\n return; // we can't do anything\n }\n Paint saved = getPaint();\n setPaint(bgcolor);\n fillRect(x, y, width, height);\n setPaint(saved);\n }\n\n /**\n * Fills the specified polygon.\n *\n * @param xPoints the x-coordinates.\n * @param yPoints the y-coordinates.\n * @param npoints the number of points.\n */\n public void fillPolygon(int[] xPoints, int[] yPoints, int npoints) {\n int[] pointArray = new int[npoints * 2];\n for (int i = 0; i < npoints; i++) {\n pointArray[2 * i] = xPoints[i];\n pointArray[2 * i + 1] = yPoints[i];\n }\n switchColors();\n this.gc.fillPolygon(pointArray);\n switchColors();\n }\n\n /**\n * Draws a rectangle with rounded corners that fits within the specified\n * framing rectangle.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the frame width.\n * @param height the frame height.\n * @param arcWidth the width of the arc defining the roundedness of the\n * rectangle's corners.\n * @param arcHeight the height of the arc defining the roundedness of the\n * rectangle's corners.\n *\n * @see #drawRoundRect(int, int, int, int, int, int)\n */\n public void fillRoundRect(int x, int y, int width, int height,\n int arcWidth, int arcHeight) {\n switchColors();\n this.gc.fillRoundRectangle(x, y, width - 1, height - 1, arcWidth,\n arcHeight);\n switchColors();\n }\n\n /**\n * Fills an oval that fits within the specified rectangular region.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the frame width.\n * @param height the frame height.\n *\n * @see #drawOval(int, int, int, int)\n * @see #fill(Shape)\n */\n public void fillOval(int x, int y, int width, int height) {\n switchColors();\n this.gc.fillOval(x, y, width - 1, height - 1);\n switchColors();\n }\n\n /**\n * Fills an arc that is part of an ellipse that fits within the specified\n * framing rectangle.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the frame width.\n * @param height the frame height.\n * @param arcStart the arc starting point, in degrees.\n * @param arcAngle the extent of the arc.\n *\n * @see #drawArc(int, int, int, int, int, int)\n */\n public void fillArc(int x, int y, int width, int height, int arcStart,\n int arcAngle) {\n switchColors();\n this.gc.fillArc(x, y, width - 1, height - 1, arcStart, arcAngle);\n switchColors();\n }\n\n /**\n * Returns the font in form of an awt font created\n * with the parameters of the font of the swt graphic\n * composite.\n * @see java.awt.Graphics#getFont()\n */\n public Font getFont() {\n // retrieve the swt font description in an os indept way\n FontData[] fontData = this.gc.getFont().getFontData();\n // create a new awt font with the appropiate data\n return SWTUtils.toAwtFont(this.gc.getDevice(), fontData[0], true);\n }\n\n /**\n * Set the font swt graphic composite from the specified\n * awt font. Be careful that the newly created swt font\n * must be disposed separately.\n * @see java.awt.Graphics#setFont(java.awt.Font)\n */\n public void setFont(Font font) {\n org.eclipse.swt.graphics.Font swtFont = getSwtFontFromPool(font);\n this.gc.setFont(swtFont);\n }\n\n /**\n * Returns the font metrics.\n *\n * @param font the font.\n *\n * @return The font metrics.\n */\n public FontMetrics getFontMetrics(Font font) {\n return SWTUtils.DUMMY_PANEL.getFontMetrics(font);\n }\n\n /**\n * Returns the font render context.\n *\n * @return The font render context.\n */\n public FontRenderContext getFontRenderContext() {\n FontRenderContext fontRenderContext = new FontRenderContext(\n new AffineTransform(), true, true);\n return fontRenderContext;\n }\n\n /**\n * Draws the specified glyph vector at the location <code>(x, y)</code>.\n * \n * @param g the glyph vector (<code>null</code> not permitted).\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n */\n public void drawGlyphVector(GlyphVector g, float x, float y) {\n fill(g.getOutline(x, y));\n }\n\n /**\n * Draws a string on the receiver. note that\n * to be consistent with the awt method,\n * the y has to be modified with the ascent of the font.\n *\n * @see java.awt.Graphics#drawString(java.lang.String, int, int)\n */\n public void drawString(String text, int x, int y) {\n drawString(text, (float) x, (float) y);\n }\n\n /**\n * Draws a string at the specified position.\n *\n * @param text the string.\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n */\n public void drawString(String text, float x, float y) {\n if (text == null) {\n throw new NullPointerException(\"Null 'text' argument.\");\n }\n float fm = this.gc.getFontMetrics().getAscent();\n this.gc.drawString(text, (int) x, (int) (y - fm), true);\n }\n\n /**\n * Draws a string at the specified position.\n *\n * @param iterator the string.\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n */\n public void drawString(AttributedCharacterIterator iterator, int x, int y) {\n // for now we simply want to extract the chars from the iterator\n // and call an unstyled text renderer\n StringBuffer sb = new StringBuffer();\n int numChars = iterator.getEndIndex() - iterator.getBeginIndex();\n char c = iterator.first();\n for (int i = 0; i < numChars; i++) {\n sb.append(c);\n c = iterator.next();\n }\n drawString(new String(sb),x,y);\n }\n\n /**\n * Draws a string at the specified position.\n *\n * @param iterator the string.\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n */\n public void drawString(AttributedCharacterIterator iterator, float x,\n float y) {\n drawString(iterator, (int) x, (int) y);\n }\n\n /**\n * Returns <code>true</code> if the rectangle (in device space) intersects\n * with the shape (the interior, if <code>onStroke</code> is false, \n * otherwise the stroked outline of the shape).\n * \n * @param rect a rectangle (in device space).\n * @param s the shape.\n * @param onStroke test the stroked outline only?\n * \n * @return A boolean. \n */\n @Override\n public boolean hit(Rectangle rect, Shape s, boolean onStroke) {\n AffineTransform transform = getTransform();\n Shape ts;\n if (onStroke) {\n Stroke stroke = getStroke();\n ts = transform.createTransformedShape(stroke.createStrokedShape(s));\n } else {\n ts = transform.createTransformedShape(s);\n }\n if (!rect.getBounds2D().intersects(ts.getBounds2D())) {\n return false;\n }\n Area a1 = new Area(rect);\n Area a2 = new Area(ts);\n a1.intersect(a2);\n return !a1.isEmpty();\n }\n\n /**\n * Not implemented - see {@link Graphics#copyArea(int, int, int, int, int,\n * int)}.\n */\n public void copyArea(int x, int y, int width, int height, int dx, int dy) {\n // TODO Auto-generated method stub\n }\n\n /**\n * Not implemented - see {@link Graphics2D#drawImage(Image,\n * AffineTransform, ImageObserver)}.\n *\n * @param image the image.\n * @param xform the transform.\n * @param obs an image observer.\n *\n * @return A boolean.\n */\n public boolean drawImage(Image image, AffineTransform xform,\n ImageObserver obs) {\n // TODO Auto-generated method stub\n return false;\n }\n\n /**\n * Draws an image.\n *\n * @param image the image.\n * @param op the image operation.\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n */\n public void drawImage(BufferedImage image, BufferedImageOp op, int x,\n int y) {\n org.eclipse.swt.graphics.Image im = new org.eclipse.swt.graphics.Image(\n this.gc.getDevice(), SWTUtils.convertToSWT(image));\n this.gc.drawImage(im, x, y);\n im.dispose();\n }\n\n /**\n * Draws an SWT image with the top left corner of the image aligned to the\n * point (x, y).\n *\n * @param image the image.\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n */\n public void drawImage(org.eclipse.swt.graphics.Image image, int x, int y) {\n this.gc.drawImage(image, x, y);\n }\n\n /**\n * Not implemented - see {@link Graphics2D#drawRenderedImage(RenderedImage,\n * AffineTransform)}.\n *\n * @param image the image.\n * @param xform the transform.\n */\n public void drawRenderedImage(RenderedImage image, AffineTransform xform) {\n // TODO Auto-generated method stub\n }\n\n /**\n * Not implemented - see {@link Graphics2D#drawRenderableImage(\n * RenderableImage, AffineTransform)}.\n *\n * @param image the image.\n * @param xform the transform.\n */\n public void drawRenderableImage(RenderableImage image,\n AffineTransform xform) {\n // TODO Auto-generated method stub\n\n }\n\n /**\n * Draws an image with the top left corner aligned to the point (x, y).\n *\n * @param image the image.\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param observer ignored here.\n *\n * @return <code>true</code> if the image has been drawn.\n */\n public boolean drawImage(Image image, int x, int y,\n ImageObserver observer) {\n ImageData data = SWTUtils.convertAWTImageToSWT(image);\n if (data == null) {\n return false;\n }\n org.eclipse.swt.graphics.Image im = new org.eclipse.swt.graphics.Image(\n this.gc.getDevice(), data);\n this.gc.drawImage(im, x, y);\n im.dispose();\n return true;\n }\n\n /**\n * Draws an image with the top left corner aligned to the point (x, y),\n * and scaled to the specified width and height.\n *\n * @param image the image.\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the width for the rendered image.\n * @param height the height for the rendered image.\n * @param observer ignored here.\n *\n * @return <code>true</code> if the image has been drawn.\n */\n public boolean drawImage(Image image, int x, int y, int width, int height,\n ImageObserver observer) {\n ImageData data = SWTUtils.convertAWTImageToSWT(image);\n if (data == null) {\n return false;\n }\n org.eclipse.swt.graphics.Image im = new org.eclipse.swt.graphics.Image(\n this.gc.getDevice(), data);\n org.eclipse.swt.graphics.Rectangle bounds = im.getBounds();\n this.gc.drawImage(im, 0, 0, bounds.width, bounds.height, x, y, width,\n height);\n im.dispose();\n return true;\n }\n\n /**\n * Draws an image.\n *\n * @param image (<code>null</code> not permitted).\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param bgcolor the background color.\n * @param observer an image observer.\n *\n * @return A boolean.\n */\n public boolean drawImage(Image image, int x, int y, Color bgcolor,\n ImageObserver observer) {\n ParamChecks.nullNotPermitted(image, \"image\");\n int w = image.getWidth(null);\n int h = image.getHeight(null);\n if (w == -1 || h == -1) {\n return false;\n }\n Paint savedPaint = getPaint();\n fill(new Rectangle2D.Double(x, y, w, h));\n setPaint(savedPaint);\n return drawImage(image, x, y, observer);\n }\n\n /**\n * Draws an image.\n *\n * @param image the image (<code>null</code> not permitted).\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param width the width.\n * @param height the height.\n * @param bgcolor the background colour.\n * @param observer an image observer.\n *\n * @return A boolean.\n */\n public boolean drawImage(Image image, int x, int y, int width, int height,\n Color bgcolor, ImageObserver observer) {\n ParamChecks.nullNotPermitted(image, \"image\");\n int w = image.getWidth(null);\n int h = image.getHeight(null);\n if (w == -1 || h == -1) {\n return false;\n }\n Paint savedPaint = getPaint();\n fill(new Rectangle2D.Double(x, y, w, h));\n setPaint(savedPaint);\n return drawImage(image, x, y, width, height, observer);\n }\n\n /**\n * Not implemented - see {@link Graphics#drawImage(Image, int, int, int,\n * int, int, int, int, int, ImageObserver)}.\n *\n * @param image the image.\n * @param dx1\n * @param dy1\n * @param dx2\n * @param dy2\n * @param sx1\n * @param sy1\n * @param sx2\n * @param sy2\n * @param observer\n */\n public boolean drawImage(Image image, int dx1, int dy1, int dx2, int dy2,\n int sx1, int sy1, int sx2, int sy2, ImageObserver observer) {\n // TODO Auto-generated method stub\n return false;\n }\n\n /**\n * Not implemented - see {@link Graphics#drawImage(Image, int, int, int,\n * int, int, int, int, int, Color, ImageObserver)}.\n *\n * @param image the image.\n * @param dx1\n * @param dy1\n * @param dx2\n * @param dy2\n * @param sx1\n * @param sy1\n * @param sx2\n * @param sy2\n * @param bgcolor\n * @param observer\n */\n public boolean drawImage(Image image, int dx1, int dy1, int dx2, int dy2,\n int sx1, int sy1, int sx2, int sy2, Color bgcolor,\n ImageObserver observer) {\n // TODO Auto-generated method stub\n return false;\n }\n\n /**\n * Releases resources held by this instance (but note that the caller\n * must dispose of the 'GC' passed to the constructor).\n *\n * @see java.awt.Graphics#dispose()\n */\n public void dispose() {\n // we dispose resources we own but user must dispose gc\n disposeResourcePool();\n }\n\n /**\n * Add given swt resource to the resource pool. All resources added\n * to the resource pool will be disposed when {@link #dispose()} is called.\n *\n * @param resource the resource to add to the pool.\n * @return the swt <code>Resource</code> just added.\n */\n private Resource addToResourcePool(Resource resource) {\n this.resourcePool.add(resource);\n return resource;\n }\n\n /**\n * Dispose the resource pool.\n */\n private void disposeResourcePool() {\n for (Iterator it = this.resourcePool.iterator(); it.hasNext();) {\n Resource resource = (Resource) it.next();\n resource.dispose();\n }\n this.fontsPool.clear();\n this.colorsPool.clear();\n this.transformsPool.clear();\n this.resourcePool.clear();\n }\n\n /**\n * Internal method to convert a AWT font object into\n * a SWT font resource. If a corresponding SWT font\n * instance is already in the pool, it will be used\n * instead of creating a new one. This is used in\n * {@link #setFont()} for instance.\n *\n * @param font The AWT font to convert.\n * @return The SWT font instance.\n */\n private org.eclipse.swt.graphics.Font getSwtFontFromPool(Font font) {\n org.eclipse.swt.graphics.Font swtFont = (org.eclipse.swt.graphics.Font)\n this.fontsPool.get(font);\n if (swtFont == null) {\n swtFont = new org.eclipse.swt.graphics.Font(this.gc.getDevice(),\n SWTUtils.toSwtFontData(this.gc.getDevice(), font, true));\n addToResourcePool(swtFont);\n this.fontsPool.put(font, swtFont);\n }\n return swtFont;\n }\n\n /**\n * Internal method to convert a AWT color object into\n * a SWT color resource. If a corresponding SWT color\n * instance is already in the pool, it will be used\n * instead of creating a new one. This is used in\n * {@link #setColor()} for instance.\n *\n * @param awtColor The AWT color to convert.\n * @return A SWT color instance.\n */\n private org.eclipse.swt.graphics.Color getSwtColorFromPool(Color awtColor) {\n org.eclipse.swt.graphics.Color swtColor =\n (org.eclipse.swt.graphics.Color)\n // we can't use the following valueOf() method, because it\n // won't compile with JDK1.4\n // this.colorsPool.get(Integer.valueOf(awtColor.getRGB()));\n this.colorsPool.get(new Integer(awtColor.getRGB()));\n if (swtColor == null) {\n swtColor = SWTUtils.toSwtColor(this.gc.getDevice(), awtColor);\n addToResourcePool(swtColor);\n // see comment above\n //this.colorsPool.put(Integer.valueOf(awtColor.getRGB()), swtColor);\n this.colorsPool.put(new Integer(awtColor.getRGB()), swtColor);\n }\n return swtColor;\n }\n\n /**\n * Internal method to convert a AWT transform object into\n * a SWT transform resource. If a corresponding SWT transform\n * instance is already in the pool, it will be used\n * instead of creating a new one. This is used in\n * {@link #setTransform()} for instance.\n *\n * @param awtTransform The AWT transform to convert.\n * @return A SWT transform instance.\n */\n private Transform getSwtTransformFromPool(AffineTransform awtTransform) {\n Transform t = (Transform) this.transformsPool.get(awtTransform);\n if (t == null) {\n t = new Transform(this.gc.getDevice());\n double[] matrix = new double[6];\n awtTransform.getMatrix(matrix);\n t.setElements((float) matrix[0], (float) matrix[1],\n (float) matrix[2], (float) matrix[3],\n (float) matrix[4], (float) matrix[5]);\n addToResourcePool(t);\n this.transformsPool.put(awtTransform, t);\n }\n return t;\n }\n\n /**\n * Perform a switch between foreground and background\n * color of gc. This is needed for consistency with\n * the awt behaviour, and is required notably for the\n * filling methods.\n */\n private void switchColors() {\n org.eclipse.swt.graphics.Color bg = this.gc.getBackground();\n org.eclipse.swt.graphics.Color fg = this.gc.getForeground();\n this.gc.setBackground(fg);\n this.gc.setForeground(bg);\n }\n\n /**\n * Converts an AWT <code>Shape</code> into a SWT <code>Path</code>.\n *\n * @param shape the shape (<code>null</code> not permitted).\n *\n * @return The path.\n */\n private Path toSwtPath(Shape shape) {\n int type;\n float[] coords = new float[6];\n Path path = new Path(this.gc.getDevice());\n PathIterator pit = shape.getPathIterator(null);\n while (!pit.isDone()) {\n type = pit.currentSegment(coords);\n switch (type) {\n case (PathIterator.SEG_MOVETO):\n path.moveTo(coords[0], coords[1]);\n break;\n case (PathIterator.SEG_LINETO):\n path.lineTo(coords[0], coords[1]);\n break;\n case (PathIterator.SEG_QUADTO):\n path.quadTo(coords[0], coords[1], coords[2], coords[3]);\n break;\n case (PathIterator.SEG_CUBICTO):\n path.cubicTo(coords[0], coords[1], coords[2],\n coords[3], coords[4], coords[5]);\n break;\n case (PathIterator.SEG_CLOSE):\n path.close();\n break;\n default:\n break;\n }\n pit.next();\n }\n return path;\n }\n\n /**\n * Converts an SWT transform into the equivalent AWT transform.\n *\n * @param swtTransform the SWT transform.\n *\n * @return The AWT transform.\n */\n private AffineTransform toAwtTransform(Transform swtTransform) {\n float[] elements = new float[6];\n swtTransform.getElements(elements);\n AffineTransform awtTransform = new AffineTransform(elements);\n return awtTransform;\n }\n\n /**\n * Returns the AWT line cap corresponding to the specified SWT line cap.\n *\n * @param swtLineCap the SWT line cap.\n *\n * @return The AWT line cap.\n */\n private int toAwtLineCap(int swtLineCap) {\n if (swtLineCap == SWT.CAP_FLAT) {\n return BasicStroke.CAP_BUTT;\n }\n else if (swtLineCap == SWT.CAP_ROUND) {\n return BasicStroke.CAP_ROUND;\n }\n else if (swtLineCap == SWT.CAP_SQUARE) {\n return BasicStroke.CAP_SQUARE;\n }\n else {\n throw new IllegalArgumentException(\"SWT LineCap \" + swtLineCap\n + \" not recognised\");\n }\n }\n\n /**\n * Returns the AWT line join corresponding to the specified SWT line join.\n *\n * @param swtLineJoin the SWT line join.\n *\n * @return The AWT line join.\n */\n private int toAwtLineJoin(int swtLineJoin) {\n if (swtLineJoin == SWT.JOIN_BEVEL) {\n return BasicStroke.JOIN_BEVEL;\n }\n else if (swtLineJoin == SWT.JOIN_MITER) {\n return BasicStroke.JOIN_MITER;\n }\n else if (swtLineJoin == SWT.JOIN_ROUND) {\n return BasicStroke.JOIN_ROUND;\n }\n else {\n throw new IllegalArgumentException(\"SWT LineJoin \" + swtLineJoin\n + \" not recognised\");\n }\n }\n\n /**\n * Returns the SWT line cap corresponding to the specified AWT line cap.\n *\n * @param awtLineCap the AWT line cap.\n *\n * @return The SWT line cap.\n */\n private int toSwtLineCap(int awtLineCap) {\n if (awtLineCap == BasicStroke.CAP_BUTT) {\n return SWT.CAP_FLAT;\n }\n else if (awtLineCap == BasicStroke.CAP_ROUND) {\n return SWT.CAP_ROUND;\n }\n else if (awtLineCap == BasicStroke.CAP_SQUARE) {\n return SWT.CAP_SQUARE;\n }\n else {\n throw new IllegalArgumentException(\"AWT LineCap \" + awtLineCap\n + \" not recognised\");\n }\n }\n\n /**\n * Returns the SWT line join corresponding to the specified AWT line join.\n *\n * @param awtLineJoin the AWT line join.\n *\n * @return The SWT line join.\n */\n private int toSwtLineJoin(int awtLineJoin) {\n if (awtLineJoin == BasicStroke.JOIN_BEVEL) {\n return SWT.JOIN_BEVEL;\n }\n else if (awtLineJoin == BasicStroke.JOIN_MITER) {\n return SWT.JOIN_MITER;\n }\n else if (awtLineJoin == BasicStroke.JOIN_ROUND) {\n return SWT.JOIN_ROUND;\n }\n else {\n throw new IllegalArgumentException(\"AWT LineJoin \" + awtLineJoin\n + \" not recognised\");\n }\n }\n}" }, { "identifier": "SWTUtils", "path": "lib/jfreechart-1.0.19/swt/org/jfree/experimental/swt/SWTUtils.java", "snippet": "public class SWTUtils {\n\n private final static String Az = \"ABCpqr\";\n\n /** A dummy JPanel used to provide font metrics. */\n protected static final JPanel DUMMY_PANEL = new JPanel();\n\n /**\n * Create a <code>FontData</code> object which encapsulate\n * the essential data to create a swt font. The data is taken\n * from the provided awt Font.\n * <p>Generally speaking, given a font size, the returned swt font\n * will display differently on the screen than the awt one.\n * Because the SWT toolkit use native graphical resources whenever\n * it is possible, this fact is platform dependent. To address\n * this issue, it is possible to enforce the method to return\n * a font with the same size (or at least as close as possible)\n * as the awt one.\n * <p>When the object is no more used, the user must explicitly\n * call the dispose method on the returned font to free the\n * operating system resources (the garbage collector won't do it).\n *\n * @param device The swt device to draw on (display or gc device).\n * @param font The awt font from which to get the data.\n * @param ensureSameSize A boolean used to enforce the same size\n * (in pixels) between the awt font and the newly created swt font.\n * @return a <code>FontData</code> object.\n */\n public static FontData toSwtFontData(Device device, java.awt.Font font,\n boolean ensureSameSize) {\n FontData fontData = new FontData();\n fontData.setName(font.getFamily());\n // SWT and AWT share the same style constants.\n fontData.setStyle(font.getStyle());\n // convert the font size (in pt for awt) to height in pixels for swt\n int height = (int) Math.round(font.getSize() * 72.0\n / device.getDPI().y);\n fontData.setHeight(height);\n // hack to ensure the newly created swt fonts will be rendered with the\n // same height as the awt one\n if (ensureSameSize) {\n GC tmpGC = new GC(device);\n Font tmpFont = new Font(device, fontData);\n tmpGC.setFont(tmpFont);\n if (tmpGC.textExtent(Az).x\n > DUMMY_PANEL.getFontMetrics(font).stringWidth(Az)) {\n while (tmpGC.textExtent(Az).x\n > DUMMY_PANEL.getFontMetrics(font).stringWidth(Az)) {\n tmpFont.dispose();\n height--;\n fontData.setHeight(height);\n tmpFont = new Font(device, fontData);\n tmpGC.setFont(tmpFont);\n }\n }\n else if (tmpGC.textExtent(Az).x\n < DUMMY_PANEL.getFontMetrics(font).stringWidth(Az)) {\n while (tmpGC.textExtent(Az).x\n < DUMMY_PANEL.getFontMetrics(font).stringWidth(Az)) {\n tmpFont.dispose();\n height++;\n fontData.setHeight(height);\n tmpFont = new Font(device, fontData);\n tmpGC.setFont(tmpFont);\n }\n }\n tmpFont.dispose();\n tmpGC.dispose();\n }\n return fontData;\n }\n\n /**\n * Create an awt font by converting as much information\n * as possible from the provided swt <code>FontData</code>.\n * <p>Generally speaking, given a font size, an swt font will\n * display differently on the screen than the corresponding awt\n * one. Because the SWT toolkit use native graphical ressources whenever\n * it is possible, this fact is platform dependent. To address\n * this issue, it is possible to enforce the method to return\n * an awt font with the same height as the swt one.\n *\n * @param device The swt device being drawn on (display or gc device).\n * @param fontData The swt font to convert.\n * @param ensureSameSize A boolean used to enforce the same size\n * (in pixels) between the swt font and the newly created awt font.\n * @return An awt font converted from the provided swt font.\n */\n public static java.awt.Font toAwtFont(Device device, FontData fontData,\n boolean ensureSameSize) {\n int height = (int) Math.round(fontData.getHeight() * device.getDPI().y\n / 72.0);\n // hack to ensure the newly created awt fonts will be rendered with the\n // same height as the swt one\n if (ensureSameSize) {\n GC tmpGC = new GC(device);\n Font tmpFont = new Font(device, fontData);\n tmpGC.setFont(tmpFont);\n JPanel DUMMY_PANEL = new JPanel();\n java.awt.Font tmpAwtFont = new java.awt.Font(fontData.getName(),\n fontData.getStyle(), height);\n if (DUMMY_PANEL.getFontMetrics(tmpAwtFont).stringWidth(Az)\n > tmpGC.textExtent(Az).x) {\n while (DUMMY_PANEL.getFontMetrics(tmpAwtFont).stringWidth(Az)\n > tmpGC.textExtent(Az).x) {\n height--;\n tmpAwtFont = new java.awt.Font(fontData.getName(),\n fontData.getStyle(), height);\n }\n }\n else if (DUMMY_PANEL.getFontMetrics(tmpAwtFont).stringWidth(Az)\n < tmpGC.textExtent(Az).x) {\n while (DUMMY_PANEL.getFontMetrics(tmpAwtFont).stringWidth(Az)\n < tmpGC.textExtent(Az).x) {\n height++;\n tmpAwtFont = new java.awt.Font(fontData.getName(),\n fontData.getStyle(), height);\n }\n }\n tmpFont.dispose();\n tmpGC.dispose();\n }\n return new java.awt.Font(fontData.getName(), fontData.getStyle(),\n height);\n }\n\n /**\n * Create an awt font by converting as much information\n * as possible from the provided swt <code>Font</code>.\n *\n * @param device The swt device to draw on (display or gc device).\n * @param font The swt font to convert.\n * @return An awt font converted from the provided swt font.\n */\n public static java.awt.Font toAwtFont(Device device, Font font) {\n FontData fontData = font.getFontData()[0];\n return toAwtFont(device, fontData, true);\n }\n\n /**\n * Creates an awt color instance to match the rgb values\n * of the specified swt color.\n *\n * @param color The swt color to match.\n * @return an awt color abject.\n */\n public static java.awt.Color toAwtColor(Color color) {\n return new java.awt.Color(color.getRed(), color.getGreen(),\n color.getBlue());\n }\n\n /**\n * Creates a swt color instance to match the rgb values\n * of the specified awt paint. For now, this method test\n * if the paint is a color and then return the adequate\n * swt color. Otherwise plain black is assumed.\n *\n * @param device The swt device to draw on (display or gc device).\n * @param paint The awt color to match.\n * @return a swt color object.\n */\n public static Color toSwtColor(Device device, java.awt.Paint paint) {\n java.awt.Color color;\n if (paint instanceof java.awt.Color) {\n color = (java.awt.Color) paint;\n }\n else {\n try {\n throw new Exception(\"only color is supported at present... \"\n + \"setting paint to uniform black color\");\n }\n catch (Exception e) {\n e.printStackTrace();\n color = new java.awt.Color(0, 0, 0);\n }\n }\n return new org.eclipse.swt.graphics.Color(device,\n color.getRed(), color.getGreen(), color.getBlue());\n }\n\n /**\n * Creates a swt color instance to match the rgb values\n * of the specified awt color. alpha channel is not supported.\n * Note that the dispose method will need to be called on the\n * returned object.\n *\n * @param device The swt device to draw on (display or gc device).\n * @param color The awt color to match.\n * @return a swt color object.\n */\n public static Color toSwtColor(Device device, java.awt.Color color) {\n return new org.eclipse.swt.graphics.Color(device,\n color.getRed(), color.getGreen(), color.getBlue());\n }\n\n /**\n * Transform an awt Rectangle2d instance into a swt one.\n * The coordinates are rounded to integer for the swt object.\n * @param rect2d The awt rectangle to map.\n * @return an swt <code>Rectangle</code> object.\n */\n public static Rectangle toSwtRectangle(Rectangle2D rect2d) {\n return new Rectangle(\n (int) Math.round(rect2d.getMinX()),\n (int) Math.round(rect2d.getMinY()),\n (int) Math.round(rect2d.getWidth()),\n (int) Math.round(rect2d.getHeight()));\n }\n\n /**\n * Transform a swt Rectangle instance into an awt one.\n * @param rect the swt <code>Rectangle</code>\n * @return a Rectangle2D.Double instance with\n * the eappropriate location and size.\n */\n public static Rectangle2D toAwtRectangle(Rectangle rect) {\n Rectangle2D rect2d = new Rectangle2D.Double();\n rect2d.setRect(rect.x, rect.y, rect.width, rect.height);\n return rect2d;\n }\n\n /**\n * Returns an AWT point with the same coordinates as the specified\n * SWT point.\n *\n * @param p the SWT point (<code>null</code> not permitted).\n *\n * @return An AWT point with the same coordinates as <code>p</code>.\n *\n * @see #toSwtPoint(java.awt.Point)\n */\n public static Point2D toAwtPoint(Point p) {\n return new java.awt.Point(p.x, p.y);\n }\n\n /**\n * Returns an SWT point with the same coordinates as the specified\n * AWT point.\n *\n * @param p the AWT point (<code>null</code> not permitted).\n *\n * @return An SWT point with the same coordinates as <code>p</code>.\n *\n * @see #toAwtPoint(Point)\n */\n public static Point toSwtPoint(java.awt.Point p) {\n return new Point(p.x, p.y);\n }\n\n /**\n * Returns an SWT point with the same coordinates as the specified AWT\n * point (rounded to integer values).\n *\n * @param p the AWT point (<code>null</code> not permitted).\n *\n * @return An SWT point with the same coordinates as <code>p</code>.\n *\n * @see #toAwtPoint(Point)\n */\n public static Point toSwtPoint(java.awt.geom.Point2D p) {\n return new Point((int) Math.round(p.getX()),\n (int) Math.round(p.getY()));\n }\n\n /**\n * Creates an AWT <code>MouseEvent</code> from a swt event.\n * This method helps passing SWT mouse event to awt components.\n * @param event The swt event.\n * @return A AWT mouse event based on the given SWT event.\n */\n public static MouseEvent toAwtMouseEvent(org.eclipse.swt.events.MouseEvent event) {\n int button = MouseEvent.NOBUTTON;\n switch (event.button) {\n case 1: button = MouseEvent.BUTTON1; break;\n case 2: button = MouseEvent.BUTTON2; break;\n case 3: button = MouseEvent.BUTTON3; break;\n }\n int modifiers = 0;\n if ((event.stateMask & SWT.CTRL) != 0) {\n modifiers |= InputEvent.CTRL_DOWN_MASK;\n }\n if ((event.stateMask & SWT.SHIFT) != 0) {\n modifiers |= InputEvent.SHIFT_DOWN_MASK;\n }\n if ((event.stateMask & SWT.ALT) != 0) {\n modifiers |= InputEvent.ALT_DOWN_MASK;\n }\n MouseEvent awtMouseEvent = new MouseEvent(DUMMY_PANEL, event.hashCode(),\n event.time, modifiers, event.x, event.y, 1, false, button);\n return awtMouseEvent;\n }\n\n /**\n * Converts an AWT image to SWT.\n *\n * @param image the image (<code>null</code> not permitted).\n *\n * @return Image data.\n */\n public static ImageData convertAWTImageToSWT(Image image) {\n ParamChecks.nullNotPermitted(image, \"image\");\n int w = image.getWidth(null);\n int h = image.getHeight(null);\n if (w == -1 || h == -1) {\n return null;\n }\n BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);\n Graphics g = bi.getGraphics();\n g.drawImage(image, 0, 0, null);\n g.dispose();\n return convertToSWT(bi);\n }\n\n /**\n * Converts a buffered image to SWT <code>ImageData</code>.\n *\n * @param bufferedImage the buffered image (<code>null</code> not\n * permitted).\n *\n * @return The image data.\n */\n public static ImageData convertToSWT(BufferedImage bufferedImage) {\n if (bufferedImage.getColorModel() instanceof DirectColorModel) {\n DirectColorModel colorModel\n = (DirectColorModel) bufferedImage.getColorModel();\n PaletteData palette = new PaletteData(colorModel.getRedMask(),\n colorModel.getGreenMask(), colorModel.getBlueMask());\n ImageData data = new ImageData(bufferedImage.getWidth(),\n bufferedImage.getHeight(), colorModel.getPixelSize(),\n palette);\n WritableRaster raster = bufferedImage.getRaster();\n int[] pixelArray = new int[3];\n for (int y = 0; y < data.height; y++) {\n for (int x = 0; x < data.width; x++) {\n raster.getPixel(x, y, pixelArray);\n int pixel = palette.getPixel(new RGB(pixelArray[0],\n pixelArray[1], pixelArray[2]));\n data.setPixel(x, y, pixel);\n }\n }\n return data;\n }\n else if (bufferedImage.getColorModel() instanceof IndexColorModel) {\n IndexColorModel colorModel = (IndexColorModel)\n bufferedImage.getColorModel();\n int size = colorModel.getMapSize();\n byte[] reds = new byte[size];\n byte[] greens = new byte[size];\n byte[] blues = new byte[size];\n colorModel.getReds(reds);\n colorModel.getGreens(greens);\n colorModel.getBlues(blues);\n RGB[] rgbs = new RGB[size];\n for (int i = 0; i < rgbs.length; i++) {\n rgbs[i] = new RGB(reds[i] & 0xFF, greens[i] & 0xFF,\n blues[i] & 0xFF);\n }\n PaletteData palette = new PaletteData(rgbs);\n ImageData data = new ImageData(bufferedImage.getWidth(),\n bufferedImage.getHeight(), colorModel.getPixelSize(),\n palette);\n data.transparentPixel = colorModel.getTransparentPixel();\n WritableRaster raster = bufferedImage.getRaster();\n int[] pixelArray = new int[1];\n for (int y = 0; y < data.height; y++) {\n for (int x = 0; x < data.width; x++) {\n raster.getPixel(x, y, pixelArray);\n data.setPixel(x, y, pixelArray[0]);\n }\n }\n return data;\n }\n return null;\n }\n\n}" } ]
import org.jfree.chart.entity.ChartEntity; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.ChartChangeEvent; import org.jfree.chart.event.ChartChangeListener; import org.jfree.chart.event.ChartProgressEvent; import org.jfree.chart.event.ChartProgressListener; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.ValueAxisPlot; import org.jfree.chart.plot.Zoomable; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.experimental.chart.swt.editor.SWTChartEditor; import org.jfree.experimental.swt.SWTGraphics2D; import org.jfree.experimental.swt.SWTUtils; import java.awt.Graphics; import java.awt.Point; import java.awt.RenderingHints; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.io.File; import java.io.IOException; import java.util.EventListener; import java.util.ResourceBundle; import javax.swing.event.EventListenerList; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.HelpListener; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.MouseTrackListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.jfree.chart.ChartMouseEvent; import org.jfree.chart.ChartMouseListener; import org.jfree.chart.ChartRenderingInfo; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart;
59,454
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------- * ChartComposite.java * ------------------- * (C) Copyright 2006-2012, by Henry Proudhon and Contributors. * * Original Author: Henry Proudhon (henry.proudhon AT ensmp.fr); * Contributor(s): David Gilbert (for Object Refinery Limited); * Cedric Chabanois (cchabanois AT no-log.org); * Christoph Beck; * Sebastiao Correia (patch 3463807); * Jonas Rüttimann (bug fix 2963199); * Bernard Sarter; * * Changes * ------- * 19-Jun-2006 : New class (HP); * 06-Nov-2006 : Added accessor methods for zoomInFactor and zoomOutFactor (DG); * 28-Nov-2006 : Added support for trace lines (HP); * 30-Nov-2006 : Improved zoom box handling (HP); * 06-Dec-2006 : Added (simplified) tool tip support (HP); * 11-Dec-2006 : Fixed popup menu location by fgiust, bug 1612770 (HP); * 31-Jan-2007 : Fixed some issues with the trace lines, fixed cross hair not * being drawn, added getter and setter methods for the trace * lines (HP); * 07-Apr-2007 : Changed this.redraw() into canvas.redraw() to fix redraw * problems (HP); * 19-May-2007 : Small fix in paintControl to check for null charts, bug * 1719260 (HP); * 19-May-2007 : Corrected bug with scaling when the drawing region is larger * than maximum draw width/height (HP); * 23-May-2007 : Added some dispose call to free SWT resources, patch sent by * Cédric Chabanois (CC); * 06-Jun-2007 : Fixed minor issues with tooltips. bug reported and fix * proposed by Christoph Beck, bug 1726404 (HP); * 22-Oct-2007 : Added addChartMouseListener and removeChartMouseListener * methods as suggested by Christoph Beck, bug 1742002 (HP); * 22-Oct-2007 : Fixed bug in zooming with multiple plots (HP); * 22-Oct-2007 : Check for null zoom point when restoring auto range and domain * bounds (HP); * 22-Oct-2007 : Pass mouse moved events to listening ChartMouseListeners (HP); * 22-Oct-2007 : Refactored class, now implements PaintListener, MouseListener, * MouseMoveListener. Made the chart field be private again and * added new method addSWTListener to allow custom behavior. * 14-Nov-2007 : Create canvas with SWT.DOUBLE_BUFFER, added * getChartRenderingInfo(), is/setDomainZoomable() and * is/setRangeZoomable() as per feature request (DG); * 11-Jul-2008 : Bug 1994355 fix (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see patch 1607918 by * Jess Thrysoee (DG); * 08-Jan-2012 : Dispose popup-menu (patch 3463807 by Sebastiao Correia) (DG) * 05-Jul-2012 : Fix SWT print (bug 2963199 by Jonas Rüttimann); * 26-Jul-2013 : Fix memory leak (patch in forum from Bernard Sarter) (DG); * */ package org.jfree.experimental.chart.swt; /** * A SWT GUI composite for displaying a {@link JFreeChart} object. * <p> * The composite listens to the chart to receive notification of changes to any * component of the chart. The chart is redrawn automatically whenever this * notification is received. */ public class ChartComposite extends Composite implements ChartChangeListener, ChartProgressListener, PaintListener, SelectionListener, MouseListener, MouseMoveListener, Printable { /** Default setting for buffer usage. */ public static final boolean DEFAULT_BUFFER_USED = false; /** The default panel width. */ public static final int DEFAULT_WIDTH = 680; /** The default panel height. */ public static final int DEFAULT_HEIGHT = 420; /** The default limit below which chart scaling kicks in. */ public static final int DEFAULT_MINIMUM_DRAW_WIDTH = 300; /** The default limit below which chart scaling kicks in. */ public static final int DEFAULT_MINIMUM_DRAW_HEIGHT = 200; /** The default limit below which chart scaling kicks in. */ public static final int DEFAULT_MAXIMUM_DRAW_WIDTH = 800; /** The default limit below which chart scaling kicks in. */ public static final int DEFAULT_MAXIMUM_DRAW_HEIGHT = 600; /** The minimum size required to perform a zoom on a rectangle */ public static final int DEFAULT_ZOOM_TRIGGER_DISTANCE = 10; /** Properties action command. */ public static final String PROPERTIES_COMMAND = "PROPERTIES"; /** Save action command. */ public static final String SAVE_COMMAND = "SAVE"; /** Print action command. */ public static final String PRINT_COMMAND = "PRINT"; /** Zoom in (both axes) action command. */ public static final String ZOOM_IN_BOTH_COMMAND = "ZOOM_IN_BOTH"; /** Zoom in (domain axis only) action command. */ public static final String ZOOM_IN_DOMAIN_COMMAND = "ZOOM_IN_DOMAIN"; /** Zoom in (range axis only) action command. */ public static final String ZOOM_IN_RANGE_COMMAND = "ZOOM_IN_RANGE"; /** Zoom out (both axes) action command. */ public static final String ZOOM_OUT_BOTH_COMMAND = "ZOOM_OUT_BOTH"; /** Zoom out (domain axis only) action command. */ public static final String ZOOM_OUT_DOMAIN_COMMAND = "ZOOM_DOMAIN_BOTH"; /** Zoom out (range axis only) action command. */ public static final String ZOOM_OUT_RANGE_COMMAND = "ZOOM_RANGE_BOTH"; /** Zoom reset (both axes) action command. */ public static final String ZOOM_RESET_BOTH_COMMAND = "ZOOM_RESET_BOTH"; /** Zoom reset (domain axis only) action command. */ public static final String ZOOM_RESET_DOMAIN_COMMAND = "ZOOM_RESET_DOMAIN"; /** Zoom reset (range axis only) action command. */ public static final String ZOOM_RESET_RANGE_COMMAND = "ZOOM_RESET_RANGE"; /** The chart that is displayed in the panel. */
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------- * ChartComposite.java * ------------------- * (C) Copyright 2006-2012, by Henry Proudhon and Contributors. * * Original Author: Henry Proudhon (henry.proudhon AT ensmp.fr); * Contributor(s): David Gilbert (for Object Refinery Limited); * Cedric Chabanois (cchabanois AT no-log.org); * Christoph Beck; * Sebastiao Correia (patch 3463807); * Jonas Rüttimann (bug fix 2963199); * Bernard Sarter; * * Changes * ------- * 19-Jun-2006 : New class (HP); * 06-Nov-2006 : Added accessor methods for zoomInFactor and zoomOutFactor (DG); * 28-Nov-2006 : Added support for trace lines (HP); * 30-Nov-2006 : Improved zoom box handling (HP); * 06-Dec-2006 : Added (simplified) tool tip support (HP); * 11-Dec-2006 : Fixed popup menu location by fgiust, bug 1612770 (HP); * 31-Jan-2007 : Fixed some issues with the trace lines, fixed cross hair not * being drawn, added getter and setter methods for the trace * lines (HP); * 07-Apr-2007 : Changed this.redraw() into canvas.redraw() to fix redraw * problems (HP); * 19-May-2007 : Small fix in paintControl to check for null charts, bug * 1719260 (HP); * 19-May-2007 : Corrected bug with scaling when the drawing region is larger * than maximum draw width/height (HP); * 23-May-2007 : Added some dispose call to free SWT resources, patch sent by * Cédric Chabanois (CC); * 06-Jun-2007 : Fixed minor issues with tooltips. bug reported and fix * proposed by Christoph Beck, bug 1726404 (HP); * 22-Oct-2007 : Added addChartMouseListener and removeChartMouseListener * methods as suggested by Christoph Beck, bug 1742002 (HP); * 22-Oct-2007 : Fixed bug in zooming with multiple plots (HP); * 22-Oct-2007 : Check for null zoom point when restoring auto range and domain * bounds (HP); * 22-Oct-2007 : Pass mouse moved events to listening ChartMouseListeners (HP); * 22-Oct-2007 : Refactored class, now implements PaintListener, MouseListener, * MouseMoveListener. Made the chart field be private again and * added new method addSWTListener to allow custom behavior. * 14-Nov-2007 : Create canvas with SWT.DOUBLE_BUFFER, added * getChartRenderingInfo(), is/setDomainZoomable() and * is/setRangeZoomable() as per feature request (DG); * 11-Jul-2008 : Bug 1994355 fix (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see patch 1607918 by * Jess Thrysoee (DG); * 08-Jan-2012 : Dispose popup-menu (patch 3463807 by Sebastiao Correia) (DG) * 05-Jul-2012 : Fix SWT print (bug 2963199 by Jonas Rüttimann); * 26-Jul-2013 : Fix memory leak (patch in forum from Bernard Sarter) (DG); * */ package org.jfree.experimental.chart.swt; /** * A SWT GUI composite for displaying a {@link JFreeChart} object. * <p> * The composite listens to the chart to receive notification of changes to any * component of the chart. The chart is redrawn automatically whenever this * notification is received. */ public class ChartComposite extends Composite implements ChartChangeListener, ChartProgressListener, PaintListener, SelectionListener, MouseListener, MouseMoveListener, Printable { /** Default setting for buffer usage. */ public static final boolean DEFAULT_BUFFER_USED = false; /** The default panel width. */ public static final int DEFAULT_WIDTH = 680; /** The default panel height. */ public static final int DEFAULT_HEIGHT = 420; /** The default limit below which chart scaling kicks in. */ public static final int DEFAULT_MINIMUM_DRAW_WIDTH = 300; /** The default limit below which chart scaling kicks in. */ public static final int DEFAULT_MINIMUM_DRAW_HEIGHT = 200; /** The default limit below which chart scaling kicks in. */ public static final int DEFAULT_MAXIMUM_DRAW_WIDTH = 800; /** The default limit below which chart scaling kicks in. */ public static final int DEFAULT_MAXIMUM_DRAW_HEIGHT = 600; /** The minimum size required to perform a zoom on a rectangle */ public static final int DEFAULT_ZOOM_TRIGGER_DISTANCE = 10; /** Properties action command. */ public static final String PROPERTIES_COMMAND = "PROPERTIES"; /** Save action command. */ public static final String SAVE_COMMAND = "SAVE"; /** Print action command. */ public static final String PRINT_COMMAND = "PRINT"; /** Zoom in (both axes) action command. */ public static final String ZOOM_IN_BOTH_COMMAND = "ZOOM_IN_BOTH"; /** Zoom in (domain axis only) action command. */ public static final String ZOOM_IN_DOMAIN_COMMAND = "ZOOM_IN_DOMAIN"; /** Zoom in (range axis only) action command. */ public static final String ZOOM_IN_RANGE_COMMAND = "ZOOM_IN_RANGE"; /** Zoom out (both axes) action command. */ public static final String ZOOM_OUT_BOTH_COMMAND = "ZOOM_OUT_BOTH"; /** Zoom out (domain axis only) action command. */ public static final String ZOOM_OUT_DOMAIN_COMMAND = "ZOOM_DOMAIN_BOTH"; /** Zoom out (range axis only) action command. */ public static final String ZOOM_OUT_RANGE_COMMAND = "ZOOM_RANGE_BOTH"; /** Zoom reset (both axes) action command. */ public static final String ZOOM_RESET_BOTH_COMMAND = "ZOOM_RESET_BOTH"; /** Zoom reset (domain axis only) action command. */ public static final String ZOOM_RESET_DOMAIN_COMMAND = "ZOOM_RESET_DOMAIN"; /** Zoom reset (range axis only) action command. */ public static final String ZOOM_RESET_RANGE_COMMAND = "ZOOM_RESET_RANGE"; /** The chart that is displayed in the panel. */
private JFreeChart chart;
4
2023-12-24 12:36:47+00:00
128k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/tests/org/jfree/chart/renderer/category/IntervalBarRendererTest.java
[ { "identifier": "JFreeChart", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/JFreeChart.java", "snippet": "public class JFreeChart implements Drawable, TitleChangeListener,\r\n PlotChangeListener, Serializable, Cloneable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -3470703747817429120L;\r\n\r\n /** Information about the project. */\r\n public static final ProjectInfo INFO = new JFreeChartInfo();\r\n\r\n /** The default font for titles. */\r\n public static final Font DEFAULT_TITLE_FONT\r\n = new Font(\"SansSerif\", Font.BOLD, 18);\r\n\r\n /** The default background color. */\r\n public static final Paint DEFAULT_BACKGROUND_PAINT\r\n = UIManager.getColor(\"Panel.background\");\r\n\r\n /** The default background image. */\r\n public static final Image DEFAULT_BACKGROUND_IMAGE = null;\r\n\r\n /** The default background image alignment. */\r\n public static final int DEFAULT_BACKGROUND_IMAGE_ALIGNMENT = Align.FIT;\r\n\r\n /** The default background image alpha. */\r\n public static final float DEFAULT_BACKGROUND_IMAGE_ALPHA = 0.5f;\r\n\r\n /**\r\n * The key for a rendering hint that can suppress the generation of a \r\n * shadow effect when drawing the chart. The hint value must be a \r\n * Boolean.\r\n * \r\n * @since 1.0.16\r\n */\r\n public static final RenderingHints.Key KEY_SUPPRESS_SHADOW_GENERATION\r\n = new RenderingHints.Key(0) {\r\n @Override\r\n public boolean isCompatibleValue(Object val) {\r\n return val instanceof Boolean;\r\n }\r\n };\r\n \r\n /**\r\n * Rendering hints that will be used for chart drawing. This should never\r\n * be <code>null</code>.\r\n */\r\n private transient RenderingHints renderingHints;\r\n\r\n /** A flag that controls whether or not the chart border is drawn. */\r\n private boolean borderVisible;\r\n\r\n /** The stroke used to draw the chart border (if visible). */\r\n private transient Stroke borderStroke;\r\n\r\n /** The paint used to draw the chart border (if visible). */\r\n private transient Paint borderPaint;\r\n\r\n /** The padding between the chart border and the chart drawing area. */\r\n private RectangleInsets padding;\r\n\r\n /** The chart title (optional). */\r\n private TextTitle title;\r\n\r\n /**\r\n * The chart subtitles (zero, one or many). This field should never be\r\n * <code>null</code>.\r\n */\r\n private List subtitles;\r\n\r\n /** Draws the visual representation of the data. */\r\n private Plot plot;\r\n\r\n /** Paint used to draw the background of the chart. */\r\n private transient Paint backgroundPaint;\r\n\r\n /** An optional background image for the chart. */\r\n private transient Image backgroundImage; // todo: not serialized yet\r\n\r\n /** The alignment for the background image. */\r\n private int backgroundImageAlignment = Align.FIT;\r\n\r\n /** The alpha transparency for the background image. */\r\n private float backgroundImageAlpha = 0.5f;\r\n\r\n /** Storage for registered change listeners. */\r\n private transient EventListenerList changeListeners;\r\n\r\n /** Storage for registered progress listeners. */\r\n private transient EventListenerList progressListeners;\r\n\r\n /**\r\n * A flag that can be used to enable/disable notification of chart change\r\n * events.\r\n */\r\n private boolean notify;\r\n\r\n /**\r\n * Creates a new chart based on the supplied plot. The chart will have\r\n * a legend added automatically, but no title (although you can easily add\r\n * one later).\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(Plot plot) {\r\n this(null, null, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. A default font\r\n * ({@link #DEFAULT_TITLE_FONT}) is used for the title, and the chart will\r\n * have a legend added automatically.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param plot the plot (<code>null</code> not permitted).\r\n */\r\n public JFreeChart(String title, Plot plot) {\r\n this(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);\r\n }\r\n\r\n /**\r\n * Creates a new chart with the given title and plot. The\r\n * <code>createLegend</code> argument specifies whether or not a legend\r\n * should be added to the chart.\r\n * <br><br>\r\n * Note that the {@link ChartFactory} class contains a range\r\n * of static methods that will return ready-made charts, and often this\r\n * is a more convenient way to create charts than using this constructor.\r\n *\r\n * @param title the chart title (<code>null</code> permitted).\r\n * @param titleFont the font for displaying the chart title\r\n * (<code>null</code> permitted).\r\n * @param plot controller of the visual representation of the data\r\n * (<code>null</code> not permitted).\r\n * @param createLegend a flag indicating whether or not a legend should\r\n * be created for the chart.\r\n */\r\n public JFreeChart(String title, Font titleFont, Plot plot,\r\n boolean createLegend) {\r\n\r\n ParamChecks.nullNotPermitted(plot, \"plot\");\r\n\r\n // create storage for listeners...\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.notify = true; // default is to notify listeners when the\r\n // chart changes\r\n\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n // added the following hint because of \r\n // http://stackoverflow.com/questions/7785082/\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n this.borderVisible = false;\r\n this.borderStroke = new BasicStroke(1.0f);\r\n this.borderPaint = Color.black;\r\n\r\n this.padding = RectangleInsets.ZERO_INSETS;\r\n\r\n this.plot = plot;\r\n plot.addChangeListener(this);\r\n\r\n this.subtitles = new ArrayList();\r\n\r\n // create a legend, if requested...\r\n if (createLegend) {\r\n LegendTitle legend = new LegendTitle(this.plot);\r\n legend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));\r\n legend.setFrame(new LineBorder());\r\n legend.setBackgroundPaint(Color.white);\r\n legend.setPosition(RectangleEdge.BOTTOM);\r\n this.subtitles.add(legend);\r\n legend.addChangeListener(this);\r\n }\r\n\r\n // add the chart title, if one has been specified...\r\n if (title != null) {\r\n if (titleFont == null) {\r\n titleFont = DEFAULT_TITLE_FONT;\r\n }\r\n this.title = new TextTitle(title, titleFont);\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n this.backgroundPaint = DEFAULT_BACKGROUND_PAINT;\r\n\r\n this.backgroundImage = DEFAULT_BACKGROUND_IMAGE;\r\n this.backgroundImageAlignment = DEFAULT_BACKGROUND_IMAGE_ALIGNMENT;\r\n this.backgroundImageAlpha = DEFAULT_BACKGROUND_IMAGE_ALPHA;\r\n\r\n }\r\n\r\n /**\r\n * Returns the collection of rendering hints for the chart.\r\n *\r\n * @return The rendering hints for the chart (never <code>null</code>).\r\n *\r\n * @see #setRenderingHints(RenderingHints)\r\n */\r\n public RenderingHints getRenderingHints() {\r\n return this.renderingHints;\r\n }\r\n\r\n /**\r\n * Sets the rendering hints for the chart. These will be added (using the\r\n * {@code Graphics2D.addRenderingHints()} method) near the start of the\r\n * {@code JFreeChart.draw()} method.\r\n *\r\n * @param renderingHints the rendering hints ({@code null} not permitted).\r\n *\r\n * @see #getRenderingHints()\r\n */\r\n public void setRenderingHints(RenderingHints renderingHints) {\r\n ParamChecks.nullNotPermitted(renderingHints, \"renderingHints\");\r\n this.renderingHints = renderingHints;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setBorderVisible(boolean)\r\n */\r\n public boolean isBorderVisible() {\r\n return this.borderVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not a border is drawn around the\r\n * outside of the chart.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isBorderVisible()\r\n */\r\n public void setBorderVisible(boolean visible) {\r\n this.borderVisible = visible;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the chart border (if visible).\r\n *\r\n * @return The border stroke.\r\n *\r\n * @see #setBorderStroke(Stroke)\r\n */\r\n public Stroke getBorderStroke() {\r\n return this.borderStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the chart border (if visible).\r\n *\r\n * @param stroke the stroke.\r\n *\r\n * @see #getBorderStroke()\r\n */\r\n public void setBorderStroke(Stroke stroke) {\r\n this.borderStroke = stroke;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the chart border (if visible).\r\n *\r\n * @return The border paint.\r\n *\r\n * @see #setBorderPaint(Paint)\r\n */\r\n public Paint getBorderPaint() {\r\n return this.borderPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the chart border (if visible).\r\n *\r\n * @param paint the paint.\r\n *\r\n * @see #getBorderPaint()\r\n */\r\n public void setBorderPaint(Paint paint) {\r\n this.borderPaint = paint;\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the padding between the chart border and the chart drawing area.\r\n *\r\n * @return The padding (never <code>null</code>).\r\n *\r\n * @see #setPadding(RectangleInsets)\r\n */\r\n public RectangleInsets getPadding() {\r\n return this.padding;\r\n }\r\n\r\n /**\r\n * Sets the padding between the chart border and the chart drawing area,\r\n * and sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param padding the padding (<code>null</code> not permitted).\r\n *\r\n * @see #getPadding()\r\n */\r\n public void setPadding(RectangleInsets padding) {\r\n ParamChecks.nullNotPermitted(padding, \"padding\");\r\n this.padding = padding;\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the main chart title. Very often a chart will have just one\r\n * title, so we make this case simple by providing accessor methods for\r\n * the main title. However, multiple titles are supported - see the\r\n * {@link #addSubtitle(Title)} method.\r\n *\r\n * @return The chart title (possibly <code>null</code>).\r\n *\r\n * @see #setTitle(TextTitle)\r\n */\r\n public TextTitle getTitle() {\r\n return this.title;\r\n }\r\n\r\n /**\r\n * Sets the main title for the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners. If you do not want a title for the\r\n * chart, set it to <code>null</code>. If you want more than one title on\r\n * a chart, use the {@link #addSubtitle(Title)} method.\r\n *\r\n * @param title the title (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(TextTitle title) {\r\n if (this.title != null) {\r\n this.title.removeChangeListener(this);\r\n }\r\n this.title = title;\r\n if (title != null) {\r\n title.addChangeListener(this);\r\n }\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Sets the chart title and sends a {@link ChartChangeEvent} to all\r\n * registered listeners. This is a convenience method that ends up calling\r\n * the {@link #setTitle(TextTitle)} method. If there is an existing title,\r\n * its text is updated, otherwise a new title using the default font is\r\n * added to the chart. If <code>text</code> is <code>null</code> the chart\r\n * title is set to <code>null</code>.\r\n *\r\n * @param text the title text (<code>null</code> permitted).\r\n *\r\n * @see #getTitle()\r\n */\r\n public void setTitle(String text) {\r\n if (text != null) {\r\n if (this.title == null) {\r\n setTitle(new TextTitle(text, JFreeChart.DEFAULT_TITLE_FONT));\r\n }\r\n else {\r\n this.title.setText(text);\r\n }\r\n }\r\n else {\r\n setTitle((TextTitle) null);\r\n }\r\n }\r\n\r\n /**\r\n * Adds a legend to the plot and sends a {@link ChartChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param legend the legend (<code>null</code> not permitted).\r\n *\r\n * @see #removeLegend()\r\n */\r\n public void addLegend(LegendTitle legend) {\r\n addSubtitle(legend);\r\n }\r\n\r\n /**\r\n * Returns the legend for the chart, if there is one. Note that a chart\r\n * can have more than one legend - this method returns the first.\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #getLegend(int)\r\n */\r\n public LegendTitle getLegend() {\r\n return getLegend(0);\r\n }\r\n\r\n /**\r\n * Returns the nth legend for a chart, or <code>null</code>.\r\n *\r\n * @param index the legend index (zero-based).\r\n *\r\n * @return The legend (possibly <code>null</code>).\r\n *\r\n * @see #addLegend(LegendTitle)\r\n */\r\n public LegendTitle getLegend(int index) {\r\n int seen = 0;\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title subtitle = (Title) iterator.next();\r\n if (subtitle instanceof LegendTitle) {\r\n if (seen == index) {\r\n return (LegendTitle) subtitle;\r\n }\r\n else {\r\n seen++;\r\n }\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Removes the first legend in the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @see #getLegend()\r\n */\r\n public void removeLegend() {\r\n removeSubtitle(getLegend());\r\n }\r\n\r\n /**\r\n * Returns the list of subtitles for the chart.\r\n *\r\n * @return The subtitle list (possibly empty, but never <code>null</code>).\r\n *\r\n * @see #setSubtitles(List)\r\n */\r\n public List getSubtitles() {\r\n return new ArrayList(this.subtitles);\r\n }\r\n\r\n /**\r\n * Sets the title list for the chart (completely replaces any existing\r\n * titles) and sends a {@link ChartChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param subtitles the new list of subtitles (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public void setSubtitles(List subtitles) {\r\n if (subtitles == null) {\r\n throw new NullPointerException(\"Null 'subtitles' argument.\");\r\n }\r\n setNotify(false);\r\n clearSubtitles();\r\n Iterator iterator = subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n if (t != null) {\r\n addSubtitle(t);\r\n }\r\n }\r\n setNotify(true); // this fires a ChartChangeEvent\r\n }\r\n\r\n /**\r\n * Returns the number of titles for the chart.\r\n *\r\n * @return The number of titles for the chart.\r\n *\r\n * @see #getSubtitles()\r\n */\r\n public int getSubtitleCount() {\r\n return this.subtitles.size();\r\n }\r\n\r\n /**\r\n * Returns a chart subtitle.\r\n *\r\n * @param index the index of the chart subtitle (zero based).\r\n *\r\n * @return A chart subtitle.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public Title getSubtitle(int index) {\r\n if ((index < 0) || (index >= getSubtitleCount())) {\r\n throw new IllegalArgumentException(\"Index out of range.\");\r\n }\r\n return (Title) this.subtitles.get(index);\r\n }\r\n\r\n /**\r\n * Adds a chart subtitle, and notifies registered listeners that the chart\r\n * has been modified.\r\n *\r\n * @param subtitle the subtitle (<code>null</code> not permitted).\r\n *\r\n * @see #getSubtitle(int)\r\n */\r\n public void addSubtitle(Title subtitle) {\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Adds a subtitle at a particular position in the subtitle list, and sends\r\n * a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param index the index (in the range 0 to {@link #getSubtitleCount()}).\r\n * @param subtitle the subtitle to add (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.6\r\n */\r\n public void addSubtitle(int index, Title subtitle) {\r\n if (index < 0 || index > getSubtitleCount()) {\r\n throw new IllegalArgumentException(\r\n \"The 'index' argument is out of range.\");\r\n }\r\n ParamChecks.nullNotPermitted(subtitle, \"subtitle\");\r\n this.subtitles.add(index, subtitle);\r\n subtitle.addChangeListener(this);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Clears all subtitles from the chart and sends a {@link ChartChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void clearSubtitles() {\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title t = (Title) iterator.next();\r\n t.removeChangeListener(this);\r\n }\r\n this.subtitles.clear();\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Removes the specified subtitle and sends a {@link ChartChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param title the title.\r\n *\r\n * @see #addSubtitle(Title)\r\n */\r\n public void removeSubtitle(Title title) {\r\n this.subtitles.remove(title);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the plot for the chart. The plot is a class responsible for\r\n * coordinating the visual representation of the data, including the axes\r\n * (if any).\r\n *\r\n * @return The plot.\r\n */\r\n public Plot getPlot() {\r\n return this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as a {@link CategoryPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link CategoryPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public CategoryPlot getCategoryPlot() {\r\n return (CategoryPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns the plot cast as an {@link XYPlot}.\r\n * <p>\r\n * NOTE: if the plot is not an instance of {@link XYPlot}, then a\r\n * <code>ClassCastException</code> is thrown.\r\n *\r\n * @return The plot.\r\n *\r\n * @see #getPlot()\r\n */\r\n public XYPlot getXYPlot() {\r\n return (XYPlot) this.plot;\r\n }\r\n\r\n /**\r\n * Returns a flag that indicates whether or not anti-aliasing is used when\r\n * the chart is drawn.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAntiAlias(boolean)\r\n */\r\n public boolean getAntiAlias() {\r\n Object val = this.renderingHints.get(RenderingHints.KEY_ANTIALIASING);\r\n return RenderingHints.VALUE_ANTIALIAS_ON.equals(val);\r\n }\r\n\r\n /**\r\n * Sets a flag that indicates whether or not anti-aliasing is used when the\r\n * chart is drawn.\r\n * <P>\r\n * Anti-aliasing usually improves the appearance of charts, but is slower.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #getAntiAlias()\r\n */\r\n public void setAntiAlias(boolean flag) {\r\n Object hint = flag ? RenderingHints.VALUE_ANTIALIAS_ON \r\n : RenderingHints.VALUE_ANTIALIAS_OFF;\r\n this.renderingHints.put(RenderingHints.KEY_ANTIALIASING, hint);\r\n fireChartChanged();\r\n }\r\n\r\n /**\r\n * Returns the current value stored in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING}.\r\n *\r\n * @return The hint value (possibly <code>null</code>).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public Object getTextAntiAlias() {\r\n return this.renderingHints.get(RenderingHints.KEY_TEXT_ANTIALIASING);\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} to either\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_ON} or\r\n * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_OFF}, then sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(Object)\r\n */\r\n public void setTextAntiAlias(boolean flag) {\r\n if (flag) {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\r\n }\r\n else {\r\n setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);\r\n }\r\n }\r\n\r\n /**\r\n * Sets the value in the rendering hints table for\r\n * {@link RenderingHints#KEY_TEXT_ANTIALIASING} and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param val the new value (<code>null</code> permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getTextAntiAlias()\r\n * @see #setTextAntiAlias(boolean)\r\n */\r\n public void setTextAntiAlias(Object val) {\r\n this.renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, val);\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the paint used for the chart background.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundPaint(Paint)\r\n */\r\n public Paint getBackgroundPaint() {\r\n return this.backgroundPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to fill the chart background and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundPaint()\r\n */\r\n public void setBackgroundPaint(Paint paint) {\r\n\r\n if (this.backgroundPaint != null) {\r\n if (!this.backgroundPaint.equals(paint)) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (paint != null) {\r\n this.backgroundPaint = paint;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image for the chart, or <code>null</code> if\r\n * there is no image.\r\n *\r\n * @return The image (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundImage(Image)\r\n */\r\n public Image getBackgroundImage() {\r\n return this.backgroundImage;\r\n }\r\n\r\n /**\r\n * Sets the background image for the chart and sends a\r\n * {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param image the image (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundImage()\r\n */\r\n public void setBackgroundImage(Image image) {\r\n\r\n if (this.backgroundImage != null) {\r\n if (!this.backgroundImage.equals(image)) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n else {\r\n if (image != null) {\r\n this.backgroundImage = image;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background image alignment. Alignment constants are defined\r\n * in the <code>org.jfree.ui.Align</code> class in the JCommon class\r\n * library.\r\n *\r\n * @return The alignment.\r\n *\r\n * @see #setBackgroundImageAlignment(int)\r\n */\r\n public int getBackgroundImageAlignment() {\r\n return this.backgroundImageAlignment;\r\n }\r\n\r\n /**\r\n * Sets the background alignment. Alignment options are defined by the\r\n * {@link org.jfree.ui.Align} class.\r\n *\r\n * @param alignment the alignment.\r\n *\r\n * @see #getBackgroundImageAlignment()\r\n */\r\n public void setBackgroundImageAlignment(int alignment) {\r\n if (this.backgroundImageAlignment != alignment) {\r\n this.backgroundImageAlignment = alignment;\r\n fireChartChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha-transparency for the chart's background image.\r\n *\r\n * @return The alpha-transparency.\r\n *\r\n * @see #setBackgroundImageAlpha(float)\r\n */\r\n public float getBackgroundImageAlpha() {\r\n return this.backgroundImageAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha-transparency for the chart's background image.\r\n * Registered listeners are notified that the chart has been changed.\r\n *\r\n * @param alpha the alpha value.\r\n *\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void setBackgroundImageAlpha(float alpha) {\r\n\r\n if (this.backgroundImageAlpha != alpha) {\r\n this.backgroundImageAlpha = alpha;\r\n fireChartChanged();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not change events are sent to\r\n * registered listeners.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNotify(boolean)\r\n */\r\n public boolean isNotify() {\r\n return this.notify;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not listeners receive\r\n * {@link ChartChangeEvent} notifications.\r\n *\r\n * @param notify a boolean.\r\n *\r\n * @see #isNotify()\r\n */\r\n public void setNotify(boolean notify) {\r\n this.notify = notify;\r\n // if the flag is being set to true, there may be queued up changes...\r\n if (notify) {\r\n notifyListeners(new ChartChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area) {\r\n draw(g2, area, null, null);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer). This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the chart should be drawn.\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D area, ChartRenderingInfo info) {\r\n draw(g2, area, null, info);\r\n }\r\n\r\n /**\r\n * Draws the chart on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * This method is the focus of the entire JFreeChart library.\r\n *\r\n * @param g2 the graphics device.\r\n * @param chartArea the area within which the chart should be drawn.\r\n * @param anchor the anchor point (in Java2D space) for the chart\r\n * (<code>null</code> permitted).\r\n * @param info records info about the drawing (null means collect no info).\r\n */\r\n public void draw(Graphics2D g2, Rectangle2D chartArea, Point2D anchor,\r\n ChartRenderingInfo info) {\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_STARTED, 0));\r\n \r\n EntityCollection entities = null;\r\n // record the chart area, if info is requested...\r\n if (info != null) {\r\n info.clear();\r\n info.setChartArea(chartArea);\r\n entities = info.getEntityCollection();\r\n }\r\n if (entities != null) {\r\n entities.add(new JFreeChartEntity((Rectangle2D) chartArea.clone(),\r\n this));\r\n }\r\n\r\n // ensure no drawing occurs outside chart area...\r\n Shape savedClip = g2.getClip();\r\n g2.clip(chartArea);\r\n\r\n g2.addRenderingHints(this.renderingHints);\r\n\r\n // draw the chart background...\r\n if (this.backgroundPaint != null) {\r\n g2.setPaint(this.backgroundPaint);\r\n g2.fill(chartArea);\r\n }\r\n\r\n if (this.backgroundImage != null) {\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundImageAlpha));\r\n Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,\r\n this.backgroundImage.getWidth(null),\r\n this.backgroundImage.getHeight(null));\r\n Align.align(dest, chartArea, this.backgroundImageAlignment);\r\n g2.drawImage(this.backgroundImage, (int) dest.getX(),\r\n (int) dest.getY(), (int) dest.getWidth(),\r\n (int) dest.getHeight(), null);\r\n g2.setComposite(originalComposite);\r\n }\r\n\r\n if (isBorderVisible()) {\r\n Paint paint = getBorderPaint();\r\n Stroke stroke = getBorderStroke();\r\n if (paint != null && stroke != null) {\r\n Rectangle2D borderArea = new Rectangle2D.Double(\r\n chartArea.getX(), chartArea.getY(),\r\n chartArea.getWidth() - 1.0, chartArea.getHeight()\r\n - 1.0);\r\n g2.setPaint(paint);\r\n g2.setStroke(stroke);\r\n g2.draw(borderArea);\r\n }\r\n }\r\n\r\n // draw the title and subtitles...\r\n Rectangle2D nonTitleArea = new Rectangle2D.Double();\r\n nonTitleArea.setRect(chartArea);\r\n this.padding.trim(nonTitleArea);\r\n\r\n if (this.title != null && this.title.isVisible()) {\r\n EntityCollection e = drawTitle(this.title, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n\r\n Iterator iterator = this.subtitles.iterator();\r\n while (iterator.hasNext()) {\r\n Title currentTitle = (Title) iterator.next();\r\n if (currentTitle.isVisible()) {\r\n EntityCollection e = drawTitle(currentTitle, g2, nonTitleArea,\r\n (entities != null));\r\n if (e != null && entities != null) {\r\n entities.addAll(e);\r\n }\r\n }\r\n }\r\n\r\n Rectangle2D plotArea = nonTitleArea;\r\n\r\n // draw the plot (axes and data visualisation)\r\n PlotRenderingInfo plotInfo = null;\r\n if (info != null) {\r\n plotInfo = info.getPlotInfo();\r\n }\r\n this.plot.draw(g2, plotArea, anchor, null, plotInfo);\r\n\r\n g2.setClip(savedClip);\r\n\r\n notifyListeners(new ChartProgressEvent(this, this,\r\n ChartProgressEvent.DRAWING_FINISHED, 100));\r\n }\r\n\r\n /**\r\n * Creates a rectangle that is aligned to the frame.\r\n *\r\n * @param dimensions the dimensions for the rectangle.\r\n * @param frame the frame to align to.\r\n * @param hAlign the horizontal alignment.\r\n * @param vAlign the vertical alignment.\r\n *\r\n * @return A rectangle.\r\n */\r\n private Rectangle2D createAlignedRectangle2D(Size2D dimensions,\r\n Rectangle2D frame, HorizontalAlignment hAlign,\r\n VerticalAlignment vAlign) {\r\n double x = Double.NaN;\r\n double y = Double.NaN;\r\n if (hAlign == HorizontalAlignment.LEFT) {\r\n x = frame.getX();\r\n }\r\n else if (hAlign == HorizontalAlignment.CENTER) {\r\n x = frame.getCenterX() - (dimensions.width / 2.0);\r\n }\r\n else if (hAlign == HorizontalAlignment.RIGHT) {\r\n x = frame.getMaxX() - dimensions.width;\r\n }\r\n if (vAlign == VerticalAlignment.TOP) {\r\n y = frame.getY();\r\n }\r\n else if (vAlign == VerticalAlignment.CENTER) {\r\n y = frame.getCenterY() - (dimensions.height / 2.0);\r\n }\r\n else if (vAlign == VerticalAlignment.BOTTOM) {\r\n y = frame.getMaxY() - dimensions.height;\r\n }\r\n\r\n return new Rectangle2D.Double(x, y, dimensions.width,\r\n dimensions.height);\r\n }\r\n\r\n /**\r\n * Draws a title. The title should be drawn at the top, bottom, left or\r\n * right of the specified area, and the area should be updated to reflect\r\n * the amount of space used by the title.\r\n *\r\n * @param t the title (<code>null</code> not permitted).\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param area the chart area, excluding any existing titles\r\n * (<code>null</code> not permitted).\r\n * @param entities a flag that controls whether or not an entity\r\n * collection is returned for the title.\r\n *\r\n * @return An entity collection for the title (possibly <code>null</code>).\r\n */\r\n protected EntityCollection drawTitle(Title t, Graphics2D g2,\r\n Rectangle2D area, boolean entities) {\r\n\r\n ParamChecks.nullNotPermitted(t, \"t\");\r\n ParamChecks.nullNotPermitted(area, \"area\");\r\n Rectangle2D titleArea;\r\n RectangleEdge position = t.getPosition();\r\n double ww = area.getWidth();\r\n if (ww <= 0.0) {\r\n return null;\r\n }\r\n double hh = area.getHeight();\r\n if (hh <= 0.0) {\r\n return null;\r\n }\r\n RectangleConstraint constraint = new RectangleConstraint(ww,\r\n new Range(0.0, ww), LengthConstraintType.RANGE, hh,\r\n new Range(0.0, hh), LengthConstraintType.RANGE);\r\n Object retValue = null;\r\n BlockParams p = new BlockParams();\r\n p.setGenerateEntities(entities);\r\n if (position == RectangleEdge.TOP) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.TOP);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), Math.min(area.getY() + size.height,\r\n area.getMaxY()), area.getWidth(), Math.max(area.getHeight()\r\n - size.height, 0));\r\n }\r\n else if (position == RectangleEdge.BOTTOM) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n t.getHorizontalAlignment(), VerticalAlignment.BOTTOM);\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth(),\r\n area.getHeight() - size.height);\r\n }\r\n else if (position == RectangleEdge.RIGHT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.RIGHT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX(), area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n\r\n else if (position == RectangleEdge.LEFT) {\r\n Size2D size = t.arrange(g2, constraint);\r\n titleArea = createAlignedRectangle2D(size, area,\r\n HorizontalAlignment.LEFT, t.getVerticalAlignment());\r\n retValue = t.draw(g2, titleArea, p);\r\n area.setRect(area.getX() + size.width, area.getY(), area.getWidth()\r\n - size.width, area.getHeight());\r\n }\r\n else {\r\n throw new RuntimeException(\"Unrecognised title position.\");\r\n }\r\n EntityCollection result = null;\r\n if (retValue instanceof EntityBlockResult) {\r\n EntityBlockResult ebr = (EntityBlockResult) retValue;\r\n result = ebr.getEntityCollection();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height) {\r\n return createBufferedImage(width, height, null);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n ChartRenderingInfo info) {\r\n return createBufferedImage(width, height, BufferedImage.TYPE_INT_ARGB,\r\n info);\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param width the width.\r\n * @param height the height.\r\n * @param imageType the image type.\r\n * @param info carries back chart state information (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int width, int height,\r\n int imageType,\r\n ChartRenderingInfo info) {\r\n BufferedImage image = new BufferedImage(width, height, imageType);\r\n Graphics2D g2 = image.createGraphics();\r\n draw(g2, new Rectangle2D.Double(0, 0, width, height), null, info);\r\n g2.dispose();\r\n return image;\r\n }\r\n\r\n /**\r\n * Creates and returns a buffered image into which the chart has been drawn.\r\n *\r\n * @param imageWidth the image width.\r\n * @param imageHeight the image height.\r\n * @param drawWidth the width for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param drawHeight the height for drawing the chart (will be scaled to\r\n * fit image).\r\n * @param info optional object for collection chart dimension and entity\r\n * information.\r\n *\r\n * @return A buffered image.\r\n */\r\n public BufferedImage createBufferedImage(int imageWidth,\r\n int imageHeight,\r\n double drawWidth,\r\n double drawHeight,\r\n ChartRenderingInfo info) {\r\n\r\n BufferedImage image = new BufferedImage(imageWidth, imageHeight,\r\n BufferedImage.TYPE_INT_ARGB);\r\n Graphics2D g2 = image.createGraphics();\r\n double scaleX = imageWidth / drawWidth;\r\n double scaleY = imageHeight / drawHeight;\r\n AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);\r\n g2.transform(st);\r\n draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,\r\n info);\r\n g2.dispose();\r\n return image;\r\n\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the chart. JFreeChart is not a UI component, so\r\n * some other object (for example, {@link ChartPanel}) needs to capture\r\n * the click event and pass it onto the JFreeChart object.\r\n * If you are not using JFreeChart in a client application, then this\r\n * method is not required.\r\n *\r\n * @param x x-coordinate of the click (in Java2D space).\r\n * @param y y-coordinate of the click (in Java2D space).\r\n * @param info contains chart dimension and entity information\r\n * (<code>null</code> not permitted).\r\n */\r\n public void handleClick(int x, int y, ChartRenderingInfo info) {\r\n\r\n // pass the click on to the plot...\r\n // rely on the plot to post a plot change event and redraw the chart...\r\n this.plot.handleClick(x, y, info.getPlotInfo());\r\n\r\n }\r\n\r\n /**\r\n * Registers an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted).\r\n *\r\n * @see #removeChangeListener(ChartChangeListener)\r\n */\r\n public void addChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.add(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the listener (<code>null</code> not permitted)\r\n *\r\n * @see #addChangeListener(ChartChangeListener)\r\n */\r\n public void removeChangeListener(ChartChangeListener listener) {\r\n ParamChecks.nullNotPermitted(listener, \"listener\");\r\n this.changeListeners.remove(ChartChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a default {@link ChartChangeEvent} to all registered listeners.\r\n * <P>\r\n * This method is for convenience only.\r\n */\r\n public void fireChartChanged() {\r\n ChartChangeEvent event = new ChartChangeEvent(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartChangeEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartChangeEvent event) {\r\n if (this.notify) {\r\n Object[] listeners = this.changeListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartChangeListener.class) {\r\n ((ChartChangeListener) listeners[i + 1]).chartChanged(\r\n event);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Registers an object for notification of progress events relating to the\r\n * chart.\r\n *\r\n * @param listener the object being registered.\r\n *\r\n * @see #removeProgressListener(ChartProgressListener)\r\n */\r\n public void addProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.add(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Deregisters an object for notification of changes to the chart.\r\n *\r\n * @param listener the object being deregistered.\r\n *\r\n * @see #addProgressListener(ChartProgressListener)\r\n */\r\n public void removeProgressListener(ChartProgressListener listener) {\r\n this.progressListeners.remove(ChartProgressListener.class, listener);\r\n }\r\n\r\n /**\r\n * Sends a {@link ChartProgressEvent} to all registered listeners.\r\n *\r\n * @param event information about the event that triggered the\r\n * notification.\r\n */\r\n protected void notifyListeners(ChartProgressEvent event) {\r\n\r\n Object[] listeners = this.progressListeners.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == ChartProgressListener.class) {\r\n ((ChartProgressListener) listeners[i + 1]).chartProgress(event);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Receives notification that a chart title has changed, and passes this\r\n * on to registered listeners.\r\n *\r\n * @param event information about the chart title change.\r\n */\r\n @Override\r\n public void titleChanged(TitleChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Receives notification that the plot has changed, and passes this on to\r\n * registered listeners.\r\n *\r\n * @param event information about the plot change.\r\n */\r\n @Override\r\n public void plotChanged(PlotChangeEvent event) {\r\n event.setChart(this);\r\n notifyListeners(event);\r\n }\r\n\r\n /**\r\n * Tests this chart for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof JFreeChart)) {\r\n return false;\r\n }\r\n JFreeChart that = (JFreeChart) obj;\r\n if (!this.renderingHints.equals(that.renderingHints)) {\r\n return false;\r\n }\r\n if (this.borderVisible != that.borderVisible) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.borderStroke, that.borderStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.borderPaint, that.borderPaint)) {\r\n return false;\r\n }\r\n if (!this.padding.equals(that.padding)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.title, that.title)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.subtitles, that.subtitles)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.plot, that.plot)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(\r\n this.backgroundPaint, that.backgroundPaint\r\n )) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundImage,\r\n that.backgroundImage)) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlignment != that.backgroundImageAlignment) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlpha != that.backgroundImageAlpha) {\r\n return false;\r\n }\r\n if (this.notify != that.notify) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.borderStroke, stream);\r\n SerialUtilities.writePaint(this.borderPaint, stream);\r\n SerialUtilities.writePaint(this.backgroundPaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.borderStroke = SerialUtilities.readStroke(stream);\r\n this.borderPaint = SerialUtilities.readPaint(stream);\r\n this.backgroundPaint = SerialUtilities.readPaint(stream);\r\n this.progressListeners = new EventListenerList();\r\n this.changeListeners = new EventListenerList();\r\n this.renderingHints = new RenderingHints(\r\n RenderingHints.KEY_ANTIALIASING,\r\n RenderingHints.VALUE_ANTIALIAS_ON);\r\n this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,\r\n RenderingHints.VALUE_STROKE_PURE);\r\n \r\n // register as a listener with sub-components...\r\n if (this.title != null) {\r\n this.title.addChangeListener(this);\r\n }\r\n\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n getSubtitle(i).addChangeListener(this);\r\n }\r\n this.plot.addChangeListener(this);\r\n }\r\n\r\n /**\r\n * Prints information about JFreeChart to standard output.\r\n *\r\n * @param args no arguments are honored.\r\n */\r\n public static void main(String[] args) {\r\n System.out.println(JFreeChart.INFO.toString());\r\n }\r\n\r\n /**\r\n * Clones the object, and takes care of listeners.\r\n * Note: caller shall register its own listeners on cloned graph.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the chart is not cloneable.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n JFreeChart chart = (JFreeChart) super.clone();\r\n\r\n chart.renderingHints = (RenderingHints) this.renderingHints.clone();\r\n // private boolean borderVisible;\r\n // private transient Stroke borderStroke;\r\n // private transient Paint borderPaint;\r\n\r\n if (this.title != null) {\r\n chart.title = (TextTitle) this.title.clone();\r\n chart.title.addChangeListener(chart);\r\n }\r\n\r\n chart.subtitles = new ArrayList();\r\n for (int i = 0; i < getSubtitleCount(); i++) {\r\n Title subtitle = (Title) getSubtitle(i).clone();\r\n chart.subtitles.add(subtitle);\r\n subtitle.addChangeListener(chart);\r\n }\r\n\r\n if (this.plot != null) {\r\n chart.plot = (Plot) this.plot.clone();\r\n chart.plot.addChangeListener(chart);\r\n }\r\n\r\n chart.progressListeners = new EventListenerList();\r\n chart.changeListeners = new EventListenerList();\r\n return chart;\r\n }\r\n\r\n}\r" }, { "identifier": "TestUtilities", "path": "lib/jfreechart-1.0.19/tests/org/jfree/chart/TestUtilities.java", "snippet": "public class TestUtilities {\n\n /**\n * Returns <code>true</code> if the collections contains any object that\n * is an instance of the specified class, and <code>false</code> otherwise.\n *\n * @param collection the collection.\n * @param c the class.\n *\n * @return A boolean.\n */\n public static boolean containsInstanceOf(Collection collection, Class c) {\n Iterator iterator = collection.iterator();\n while (iterator.hasNext()) {\n Object obj = iterator.next();\n if (obj != null && obj.getClass().equals(c)) {\n return true;\n }\n }\n return false;\n }\n\n public static Object serialised(Object original) {\n Object result = null;\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n ObjectOutput out;\n try {\n out = new ObjectOutputStream(buffer);\n out.writeObject(original);\n out.close();\n ObjectInput in = new ObjectInputStream(\n new ByteArrayInputStream(buffer.toByteArray()));\n result = in.readObject();\n in.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n return result;\n }\n \n}" }, { "identifier": "CategoryAxis", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/axis/CategoryAxis.java", "snippet": "public class CategoryAxis extends Axis implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 5886554608114265863L;\r\n\r\n /**\r\n * The default margin for the axis (used for both lower and upper margins).\r\n */\r\n public static final double DEFAULT_AXIS_MARGIN = 0.05;\r\n\r\n /**\r\n * The default margin between categories (a percentage of the overall axis\r\n * length).\r\n */\r\n public static final double DEFAULT_CATEGORY_MARGIN = 0.20;\r\n\r\n /** The amount of space reserved at the start of the axis. */\r\n private double lowerMargin;\r\n\r\n /** The amount of space reserved at the end of the axis. */\r\n private double upperMargin;\r\n\r\n /** The amount of space reserved between categories. */\r\n private double categoryMargin;\r\n\r\n /** The maximum number of lines for category labels. */\r\n private int maximumCategoryLabelLines;\r\n\r\n /**\r\n * A ratio that is multiplied by the width of one category to determine the\r\n * maximum label width.\r\n */\r\n private float maximumCategoryLabelWidthRatio;\r\n\r\n /** The category label offset. */\r\n private int categoryLabelPositionOffset;\r\n\r\n /**\r\n * A structure defining the category label positions for each axis\r\n * location.\r\n */\r\n private CategoryLabelPositions categoryLabelPositions;\r\n\r\n /** Storage for tick label font overrides (if any). */\r\n private Map tickLabelFontMap;\r\n\r\n /** Storage for tick label paint overrides (if any). */\r\n private transient Map tickLabelPaintMap;\r\n\r\n /** Storage for the category label tooltips (if any). */\r\n private Map categoryLabelToolTips;\r\n\r\n /** Storage for the category label URLs (if any). */\r\n private Map categoryLabelURLs;\r\n \r\n /**\r\n * Creates a new category axis with no label.\r\n */\r\n public CategoryAxis() {\r\n this(null);\r\n }\r\n\r\n /**\r\n * Constructs a category axis, using default values where necessary.\r\n *\r\n * @param label the axis label (<code>null</code> permitted).\r\n */\r\n public CategoryAxis(String label) {\r\n super(label);\r\n\r\n this.lowerMargin = DEFAULT_AXIS_MARGIN;\r\n this.upperMargin = DEFAULT_AXIS_MARGIN;\r\n this.categoryMargin = DEFAULT_CATEGORY_MARGIN;\r\n this.maximumCategoryLabelLines = 1;\r\n this.maximumCategoryLabelWidthRatio = 0.0f;\r\n\r\n this.categoryLabelPositionOffset = 4;\r\n this.categoryLabelPositions = CategoryLabelPositions.STANDARD;\r\n this.tickLabelFontMap = new HashMap();\r\n this.tickLabelPaintMap = new HashMap();\r\n this.categoryLabelToolTips = new HashMap();\r\n this.categoryLabelURLs = new HashMap();\r\n }\r\n\r\n /**\r\n * Returns the lower margin for the axis.\r\n *\r\n * @return The margin.\r\n *\r\n * @see #getUpperMargin()\r\n * @see #setLowerMargin(double)\r\n */\r\n public double getLowerMargin() {\r\n return this.lowerMargin;\r\n }\r\n\r\n /**\r\n * Sets the lower margin for the axis and sends an {@link AxisChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param margin the margin as a percentage of the axis length (for\r\n * example, 0.05 is five percent).\r\n *\r\n * @see #getLowerMargin()\r\n */\r\n public void setLowerMargin(double margin) {\r\n this.lowerMargin = margin;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the upper margin for the axis.\r\n *\r\n * @return The margin.\r\n *\r\n * @see #getLowerMargin()\r\n * @see #setUpperMargin(double)\r\n */\r\n public double getUpperMargin() {\r\n return this.upperMargin;\r\n }\r\n\r\n /**\r\n * Sets the upper margin for the axis and sends an {@link AxisChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param margin the margin as a percentage of the axis length (for\r\n * example, 0.05 is five percent).\r\n *\r\n * @see #getUpperMargin()\r\n */\r\n public void setUpperMargin(double margin) {\r\n this.upperMargin = margin;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the category margin.\r\n *\r\n * @return The margin.\r\n *\r\n * @see #setCategoryMargin(double)\r\n */\r\n public double getCategoryMargin() {\r\n return this.categoryMargin;\r\n }\r\n\r\n /**\r\n * Sets the category margin and sends an {@link AxisChangeEvent} to all\r\n * registered listeners. The overall category margin is distributed over\r\n * N-1 gaps, where N is the number of categories on the axis.\r\n *\r\n * @param margin the margin as a percentage of the axis length (for\r\n * example, 0.05 is five percent).\r\n *\r\n * @see #getCategoryMargin()\r\n */\r\n public void setCategoryMargin(double margin) {\r\n this.categoryMargin = margin;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the maximum number of lines to use for each category label.\r\n *\r\n * @return The maximum number of lines.\r\n *\r\n * @see #setMaximumCategoryLabelLines(int)\r\n */\r\n public int getMaximumCategoryLabelLines() {\r\n return this.maximumCategoryLabelLines;\r\n }\r\n\r\n /**\r\n * Sets the maximum number of lines to use for each category label and\r\n * sends an {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param lines the maximum number of lines.\r\n *\r\n * @see #getMaximumCategoryLabelLines()\r\n */\r\n public void setMaximumCategoryLabelLines(int lines) {\r\n this.maximumCategoryLabelLines = lines;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the category label width ratio.\r\n *\r\n * @return The ratio.\r\n *\r\n * @see #setMaximumCategoryLabelWidthRatio(float)\r\n */\r\n public float getMaximumCategoryLabelWidthRatio() {\r\n return this.maximumCategoryLabelWidthRatio;\r\n }\r\n\r\n /**\r\n * Sets the maximum category label width ratio and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param ratio the ratio.\r\n *\r\n * @see #getMaximumCategoryLabelWidthRatio()\r\n */\r\n public void setMaximumCategoryLabelWidthRatio(float ratio) {\r\n this.maximumCategoryLabelWidthRatio = ratio;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the offset between the axis and the category labels (before\r\n * label positioning is taken into account).\r\n *\r\n * @return The offset (in Java2D units).\r\n *\r\n * @see #setCategoryLabelPositionOffset(int)\r\n */\r\n public int getCategoryLabelPositionOffset() {\r\n return this.categoryLabelPositionOffset;\r\n }\r\n\r\n /**\r\n * Sets the offset between the axis and the category labels (before label\r\n * positioning is taken into account) and sends a change event to all \r\n * registered listeners.\r\n *\r\n * @param offset the offset (in Java2D units).\r\n *\r\n * @see #getCategoryLabelPositionOffset()\r\n */\r\n public void setCategoryLabelPositionOffset(int offset) {\r\n this.categoryLabelPositionOffset = offset;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the category label position specification (this contains label\r\n * positioning info for all four possible axis locations).\r\n *\r\n * @return The positions (never <code>null</code>).\r\n *\r\n * @see #setCategoryLabelPositions(CategoryLabelPositions)\r\n */\r\n public CategoryLabelPositions getCategoryLabelPositions() {\r\n return this.categoryLabelPositions;\r\n }\r\n\r\n /**\r\n * Sets the category label position specification for the axis and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param positions the positions (<code>null</code> not permitted).\r\n *\r\n * @see #getCategoryLabelPositions()\r\n */\r\n public void setCategoryLabelPositions(CategoryLabelPositions positions) {\r\n ParamChecks.nullNotPermitted(positions, \"positions\");\r\n this.categoryLabelPositions = positions;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the font for the tick label for the given category.\r\n *\r\n * @param category the category (<code>null</code> not permitted).\r\n *\r\n * @return The font (never <code>null</code>).\r\n *\r\n * @see #setTickLabelFont(Comparable, Font)\r\n */\r\n public Font getTickLabelFont(Comparable category) {\r\n ParamChecks.nullNotPermitted(category, \"category\");\r\n Font result = (Font) this.tickLabelFontMap.get(category);\r\n // if there is no specific font, use the general one...\r\n if (result == null) {\r\n result = getTickLabelFont();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the font for the tick label for the specified category and sends\r\n * an {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param category the category (<code>null</code> not permitted).\r\n * @param font the font (<code>null</code> permitted).\r\n *\r\n * @see #getTickLabelFont(Comparable)\r\n */\r\n public void setTickLabelFont(Comparable category, Font font) {\r\n ParamChecks.nullNotPermitted(category, \"category\");\r\n if (font == null) {\r\n this.tickLabelFontMap.remove(category);\r\n }\r\n else {\r\n this.tickLabelFontMap.put(category, font);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the tick label for the given category.\r\n *\r\n * @param category the category (<code>null</code> not permitted).\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setTickLabelPaint(Paint)\r\n */\r\n public Paint getTickLabelPaint(Comparable category) {\r\n ParamChecks.nullNotPermitted(category, \"category\");\r\n Paint result = (Paint) this.tickLabelPaintMap.get(category);\r\n // if there is no specific paint, use the general one...\r\n if (result == null) {\r\n result = getTickLabelPaint();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the paint for the tick label for the specified category and sends\r\n * an {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param category the category (<code>null</code> not permitted).\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getTickLabelPaint(Comparable)\r\n */\r\n public void setTickLabelPaint(Comparable category, Paint paint) {\r\n ParamChecks.nullNotPermitted(category, \"category\");\r\n if (paint == null) {\r\n this.tickLabelPaintMap.remove(category);\r\n }\r\n else {\r\n this.tickLabelPaintMap.put(category, paint);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a tooltip to the specified category and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param category the category (<code>null</code> not permitted).\r\n * @param tooltip the tooltip text (<code>null</code> permitted).\r\n *\r\n * @see #removeCategoryLabelToolTip(Comparable)\r\n */\r\n public void addCategoryLabelToolTip(Comparable category, String tooltip) {\r\n ParamChecks.nullNotPermitted(category, \"category\");\r\n this.categoryLabelToolTips.put(category, tooltip);\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the tool tip text for the label belonging to the specified\r\n * category.\r\n *\r\n * @param category the category (<code>null</code> not permitted).\r\n *\r\n * @return The tool tip text (possibly <code>null</code>).\r\n *\r\n * @see #addCategoryLabelToolTip(Comparable, String)\r\n * @see #removeCategoryLabelToolTip(Comparable)\r\n */\r\n public String getCategoryLabelToolTip(Comparable category) {\r\n ParamChecks.nullNotPermitted(category, \"category\");\r\n return (String) this.categoryLabelToolTips.get(category);\r\n }\r\n\r\n /**\r\n * Removes the tooltip for the specified category and, if there was a value\r\n * associated with that category, sends an {@link AxisChangeEvent} to all \r\n * registered listeners.\r\n *\r\n * @param category the category (<code>null</code> not permitted).\r\n *\r\n * @see #addCategoryLabelToolTip(Comparable, String)\r\n * @see #clearCategoryLabelToolTips()\r\n */\r\n public void removeCategoryLabelToolTip(Comparable category) {\r\n ParamChecks.nullNotPermitted(category, \"category\");\r\n if (this.categoryLabelToolTips.remove(category) != null) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Clears the category label tooltips and sends an {@link AxisChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #addCategoryLabelToolTip(Comparable, String)\r\n * @see #removeCategoryLabelToolTip(Comparable)\r\n */\r\n public void clearCategoryLabelToolTips() {\r\n this.categoryLabelToolTips.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a URL (to be used in image maps) to the specified category and \r\n * sends an {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param category the category (<code>null</code> not permitted).\r\n * @param url the URL text (<code>null</code> permitted).\r\n *\r\n * @see #removeCategoryLabelURL(Comparable)\r\n * \r\n * @since 1.0.16\r\n */\r\n public void addCategoryLabelURL(Comparable category, String url) {\r\n ParamChecks.nullNotPermitted(category, \"category\");\r\n this.categoryLabelURLs.put(category, url);\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the URL for the label belonging to the specified category.\r\n *\r\n * @param category the category (<code>null</code> not permitted).\r\n *\r\n * @return The URL text (possibly <code>null</code>).\r\n * \r\n * @see #addCategoryLabelURL(Comparable, String)\r\n * @see #removeCategoryLabelURL(Comparable)\r\n * \r\n * @since 1.0.16\r\n */\r\n public String getCategoryLabelURL(Comparable category) {\r\n ParamChecks.nullNotPermitted(category, \"category\");\r\n return (String) this.categoryLabelURLs.get(category);\r\n }\r\n\r\n /**\r\n * Removes the URL for the specified category and, if there was a URL \r\n * associated with that category, sends an {@link AxisChangeEvent} to all \r\n * registered listeners.\r\n *\r\n * @param category the category (<code>null</code> not permitted).\r\n *\r\n * @see #addCategoryLabelURL(Comparable, String)\r\n * @see #clearCategoryLabelURLs()\r\n * \r\n * @since 1.0.16\r\n */\r\n public void removeCategoryLabelURL(Comparable category) {\r\n ParamChecks.nullNotPermitted(category, \"category\");\r\n if (this.categoryLabelURLs.remove(category) != null) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Clears the category label URLs and sends an {@link AxisChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #addCategoryLabelURL(Comparable, String)\r\n * @see #removeCategoryLabelURL(Comparable)\r\n * \r\n * @since 1.0.16\r\n */\r\n public void clearCategoryLabelURLs() {\r\n this.categoryLabelURLs.clear();\r\n fireChangeEvent();\r\n }\r\n \r\n /**\r\n * Returns the Java 2D coordinate for a category.\r\n *\r\n * @param anchor the anchor point.\r\n * @param category the category index.\r\n * @param categoryCount the category count.\r\n * @param area the data area.\r\n * @param edge the location of the axis.\r\n *\r\n * @return The coordinate.\r\n */\r\n public double getCategoryJava2DCoordinate(CategoryAnchor anchor, \r\n int category, int categoryCount, Rectangle2D area, \r\n RectangleEdge edge) {\r\n\r\n double result = 0.0;\r\n if (anchor == CategoryAnchor.START) {\r\n result = getCategoryStart(category, categoryCount, area, edge);\r\n }\r\n else if (anchor == CategoryAnchor.MIDDLE) {\r\n result = getCategoryMiddle(category, categoryCount, area, edge);\r\n }\r\n else if (anchor == CategoryAnchor.END) {\r\n result = getCategoryEnd(category, categoryCount, area, edge);\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Returns the starting coordinate for the specified category.\r\n *\r\n * @param category the category.\r\n * @param categoryCount the number of categories.\r\n * @param area the data area.\r\n * @param edge the axis location.\r\n *\r\n * @return The coordinate.\r\n *\r\n * @see #getCategoryMiddle(int, int, Rectangle2D, RectangleEdge)\r\n * @see #getCategoryEnd(int, int, Rectangle2D, RectangleEdge)\r\n */\r\n public double getCategoryStart(int category, int categoryCount, \r\n Rectangle2D area, RectangleEdge edge) {\r\n\r\n double result = 0.0;\r\n if ((edge == RectangleEdge.TOP) || (edge == RectangleEdge.BOTTOM)) {\r\n result = area.getX() + area.getWidth() * getLowerMargin();\r\n }\r\n else if ((edge == RectangleEdge.LEFT)\r\n || (edge == RectangleEdge.RIGHT)) {\r\n result = area.getMinY() + area.getHeight() * getLowerMargin();\r\n }\r\n\r\n double categorySize = calculateCategorySize(categoryCount, area, edge);\r\n double categoryGapWidth = calculateCategoryGapSize(categoryCount, area,\r\n edge);\r\n\r\n result = result + category * (categorySize + categoryGapWidth);\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the middle coordinate for the specified category.\r\n *\r\n * @param category the category.\r\n * @param categoryCount the number of categories.\r\n * @param area the data area.\r\n * @param edge the axis location.\r\n *\r\n * @return The coordinate.\r\n *\r\n * @see #getCategoryStart(int, int, Rectangle2D, RectangleEdge)\r\n * @see #getCategoryEnd(int, int, Rectangle2D, RectangleEdge)\r\n */\r\n public double getCategoryMiddle(int category, int categoryCount,\r\n Rectangle2D area, RectangleEdge edge) {\r\n\r\n if (category < 0 || category >= categoryCount) {\r\n throw new IllegalArgumentException(\"Invalid category index: \"\r\n + category);\r\n }\r\n return getCategoryStart(category, categoryCount, area, edge)\r\n + calculateCategorySize(categoryCount, area, edge) / 2;\r\n\r\n }\r\n\r\n /**\r\n * Returns the end coordinate for the specified category.\r\n *\r\n * @param category the category.\r\n * @param categoryCount the number of categories.\r\n * @param area the data area.\r\n * @param edge the axis location.\r\n *\r\n * @return The coordinate.\r\n *\r\n * @see #getCategoryStart(int, int, Rectangle2D, RectangleEdge)\r\n * @see #getCategoryMiddle(int, int, Rectangle2D, RectangleEdge)\r\n */\r\n public double getCategoryEnd(int category, int categoryCount,\r\n Rectangle2D area, RectangleEdge edge) {\r\n return getCategoryStart(category, categoryCount, area, edge)\r\n + calculateCategorySize(categoryCount, area, edge);\r\n }\r\n\r\n /**\r\n * A convenience method that returns the axis coordinate for the centre of\r\n * a category.\r\n *\r\n * @param category the category key (<code>null</code> not permitted).\r\n * @param categories the categories (<code>null</code> not permitted).\r\n * @param area the data area (<code>null</code> not permitted).\r\n * @param edge the edge along which the axis lies (<code>null</code> not\r\n * permitted).\r\n *\r\n * @return The centre coordinate.\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #getCategorySeriesMiddle(Comparable, Comparable, CategoryDataset,\r\n * double, Rectangle2D, RectangleEdge)\r\n */\r\n public double getCategoryMiddle(Comparable category,\r\n List categories, Rectangle2D area, RectangleEdge edge) {\r\n ParamChecks.nullNotPermitted(categories, \"categories\");\r\n int categoryIndex = categories.indexOf(category);\r\n int categoryCount = categories.size();\r\n return getCategoryMiddle(categoryIndex, categoryCount, area, edge);\r\n }\r\n\r\n /**\r\n * Returns the middle coordinate (in Java2D space) for a series within a\r\n * category.\r\n *\r\n * @param category the category (<code>null</code> not permitted).\r\n * @param seriesKey the series key (<code>null</code> not permitted).\r\n * @param dataset the dataset (<code>null</code> not permitted).\r\n * @param itemMargin the item margin (0.0 &lt;= itemMargin &lt; 1.0);\r\n * @param area the area (<code>null</code> not permitted).\r\n * @param edge the edge (<code>null</code> not permitted).\r\n *\r\n * @return The coordinate in Java2D space.\r\n *\r\n * @since 1.0.7\r\n */\r\n public double getCategorySeriesMiddle(Comparable category,\r\n Comparable seriesKey, CategoryDataset dataset, double itemMargin,\r\n Rectangle2D area, RectangleEdge edge) {\r\n\r\n int categoryIndex = dataset.getColumnIndex(category);\r\n int categoryCount = dataset.getColumnCount();\r\n int seriesIndex = dataset.getRowIndex(seriesKey);\r\n int seriesCount = dataset.getRowCount();\r\n double start = getCategoryStart(categoryIndex, categoryCount, area,\r\n edge);\r\n double end = getCategoryEnd(categoryIndex, categoryCount, area, edge);\r\n double width = end - start;\r\n if (seriesCount == 1) {\r\n return start + width / 2.0;\r\n }\r\n else {\r\n double gap = (width * itemMargin) / (seriesCount - 1);\r\n double ww = (width * (1 - itemMargin)) / seriesCount;\r\n return start + (seriesIndex * (ww + gap)) + ww / 2.0;\r\n }\r\n }\r\n\r\n /**\r\n * Returns the middle coordinate (in Java2D space) for a series within a\r\n * category.\r\n *\r\n * @param categoryIndex the category index.\r\n * @param categoryCount the category count.\r\n * @param seriesIndex the series index.\r\n * @param seriesCount the series count.\r\n * @param itemMargin the item margin (0.0 &lt;= itemMargin &lt; 1.0);\r\n * @param area the area (<code>null</code> not permitted).\r\n * @param edge the edge (<code>null</code> not permitted).\r\n *\r\n * @return The coordinate in Java2D space.\r\n *\r\n * @since 1.0.13\r\n */\r\n public double getCategorySeriesMiddle(int categoryIndex, int categoryCount,\r\n int seriesIndex, int seriesCount, double itemMargin,\r\n Rectangle2D area, RectangleEdge edge) {\r\n\r\n double start = getCategoryStart(categoryIndex, categoryCount, area,\r\n edge);\r\n double end = getCategoryEnd(categoryIndex, categoryCount, area, edge);\r\n double width = end - start;\r\n if (seriesCount == 1) {\r\n return start + width / 2.0;\r\n }\r\n else {\r\n double gap = (width * itemMargin) / (seriesCount - 1);\r\n double ww = (width * (1 - itemMargin)) / seriesCount;\r\n return start + (seriesIndex * (ww + gap)) + ww / 2.0;\r\n }\r\n }\r\n\r\n /**\r\n * Calculates the size (width or height, depending on the location of the\r\n * axis) of a category.\r\n *\r\n * @param categoryCount the number of categories.\r\n * @param area the area within which the categories will be drawn.\r\n * @param edge the axis location.\r\n *\r\n * @return The category size.\r\n */\r\n protected double calculateCategorySize(int categoryCount, Rectangle2D area,\r\n RectangleEdge edge) {\r\n double result;\r\n double available = 0.0;\r\n\r\n if ((edge == RectangleEdge.TOP) || (edge == RectangleEdge.BOTTOM)) {\r\n available = area.getWidth();\r\n }\r\n else if ((edge == RectangleEdge.LEFT)\r\n || (edge == RectangleEdge.RIGHT)) {\r\n available = area.getHeight();\r\n }\r\n if (categoryCount > 1) {\r\n result = available * (1 - getLowerMargin() - getUpperMargin()\r\n - getCategoryMargin());\r\n result = result / categoryCount;\r\n }\r\n else {\r\n result = available * (1 - getLowerMargin() - getUpperMargin());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Calculates the size (width or height, depending on the location of the\r\n * axis) of a category gap.\r\n *\r\n * @param categoryCount the number of categories.\r\n * @param area the area within which the categories will be drawn.\r\n * @param edge the axis location.\r\n *\r\n * @return The category gap width.\r\n */\r\n protected double calculateCategoryGapSize(int categoryCount, \r\n Rectangle2D area, RectangleEdge edge) {\r\n\r\n double result = 0.0;\r\n double available = 0.0;\r\n\r\n if ((edge == RectangleEdge.TOP) || (edge == RectangleEdge.BOTTOM)) {\r\n available = area.getWidth();\r\n }\r\n else if ((edge == RectangleEdge.LEFT)\r\n || (edge == RectangleEdge.RIGHT)) {\r\n available = area.getHeight();\r\n }\r\n\r\n if (categoryCount > 1) {\r\n result = available * getCategoryMargin() / (categoryCount - 1);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Estimates the space required for the axis, given a specific drawing area.\r\n *\r\n * @param g2 the graphics device (used to obtain font information).\r\n * @param plot the plot that the axis belongs to.\r\n * @param plotArea the area within which the axis should be drawn.\r\n * @param edge the axis location (top or bottom).\r\n * @param space the space already reserved.\r\n *\r\n * @return The space required to draw the axis.\r\n */\r\n @Override\r\n public AxisSpace reserveSpace(Graphics2D g2, Plot plot, \r\n Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) {\r\n\r\n // create a new space object if one wasn't supplied...\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // if the axis is not visible, no additional space is required...\r\n if (!isVisible()) {\r\n return space;\r\n }\r\n\r\n // calculate the max size of the tick labels (if visible)...\r\n double tickLabelHeight = 0.0;\r\n double tickLabelWidth = 0.0;\r\n if (isTickLabelsVisible()) {\r\n g2.setFont(getTickLabelFont());\r\n AxisState state = new AxisState();\r\n // we call refresh ticks just to get the maximum width or height\r\n refreshTicks(g2, state, plotArea, edge);\r\n if (edge == RectangleEdge.TOP) {\r\n tickLabelHeight = state.getMax();\r\n }\r\n else if (edge == RectangleEdge.BOTTOM) {\r\n tickLabelHeight = state.getMax();\r\n }\r\n else if (edge == RectangleEdge.LEFT) {\r\n tickLabelWidth = state.getMax();\r\n }\r\n else if (edge == RectangleEdge.RIGHT) {\r\n tickLabelWidth = state.getMax();\r\n }\r\n }\r\n\r\n // get the axis label size and update the space object...\r\n Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge);\r\n double labelHeight, labelWidth;\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n labelHeight = labelEnclosure.getHeight();\r\n space.add(labelHeight + tickLabelHeight\r\n + this.categoryLabelPositionOffset, edge);\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n labelWidth = labelEnclosure.getWidth();\r\n space.add(labelWidth + tickLabelWidth\r\n + this.categoryLabelPositionOffset, edge);\r\n }\r\n return space;\r\n }\r\n\r\n /**\r\n * Configures the axis against the current plot.\r\n */\r\n @Override\r\n public void configure() {\r\n // nothing required\r\n }\r\n\r\n /**\r\n * Draws the axis on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param cursor the cursor location.\r\n * @param plotArea the area within which the axis should be drawn\r\n * (<code>null</code> not permitted).\r\n * @param dataArea the area within which the plot is being drawn\r\n * (<code>null</code> not permitted).\r\n * @param edge the location of the axis (<code>null</code> not permitted).\r\n * @param plotState collects information about the plot\r\n * (<code>null</code> permitted).\r\n *\r\n * @return The axis state (never <code>null</code>).\r\n */\r\n @Override\r\n public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,\r\n Rectangle2D dataArea, RectangleEdge edge,\r\n PlotRenderingInfo plotState) {\r\n\r\n // if the axis is not visible, don't draw it...\r\n if (!isVisible()) {\r\n return new AxisState(cursor);\r\n }\r\n\r\n if (isAxisLineVisible()) {\r\n drawAxisLine(g2, cursor, dataArea, edge);\r\n }\r\n AxisState state = new AxisState(cursor);\r\n if (isTickMarksVisible()) {\r\n drawTickMarks(g2, cursor, dataArea, edge, state);\r\n }\r\n\r\n createAndAddEntity(cursor, state, dataArea, edge, plotState);\r\n\r\n // draw the category labels and axis label\r\n state = drawCategoryLabels(g2, plotArea, dataArea, edge, state,\r\n plotState);\r\n if (getAttributedLabel() != null) {\r\n state = drawAttributedLabel(getAttributedLabel(), g2, plotArea, \r\n dataArea, edge, state);\r\n \r\n } else {\r\n state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);\r\n }\r\n return state;\r\n\r\n }\r\n\r\n /**\r\n * Draws the category labels and returns the updated axis state.\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param plotArea the plot area (<code>null</code> not permitted).\r\n * @param dataArea the area inside the axes (<code>null</code> not\r\n * permitted).\r\n * @param edge the axis location (<code>null</code> not permitted).\r\n * @param state the axis state (<code>null</code> not permitted).\r\n * @param plotState collects information about the plot (<code>null</code>\r\n * permitted).\r\n *\r\n * @return The updated axis state (never <code>null</code>).\r\n */\r\n protected AxisState drawCategoryLabels(Graphics2D g2, Rectangle2D plotArea,\r\n Rectangle2D dataArea, RectangleEdge edge, AxisState state,\r\n PlotRenderingInfo plotState) {\r\n\r\n ParamChecks.nullNotPermitted(state, \"state\");\r\n if (!isTickLabelsVisible()) {\r\n return state;\r\n }\r\n \r\n List ticks = refreshTicks(g2, state, plotArea, edge);\r\n state.setTicks(ticks);\r\n int categoryIndex = 0;\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n CategoryTick tick = (CategoryTick) iterator.next();\r\n g2.setFont(getTickLabelFont(tick.getCategory()));\r\n g2.setPaint(getTickLabelPaint(tick.getCategory()));\r\n\r\n CategoryLabelPosition position\r\n = this.categoryLabelPositions.getLabelPosition(edge);\r\n double x0 = 0.0;\r\n double x1 = 0.0;\r\n double y0 = 0.0;\r\n double y1 = 0.0;\r\n if (edge == RectangleEdge.TOP) {\r\n x0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, \r\n edge);\r\n x1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea, \r\n edge);\r\n y1 = state.getCursor() - this.categoryLabelPositionOffset;\r\n y0 = y1 - state.getMax();\r\n }\r\n else if (edge == RectangleEdge.BOTTOM) {\r\n x0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, \r\n edge);\r\n x1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea, \r\n edge);\r\n y0 = state.getCursor() + this.categoryLabelPositionOffset;\r\n y1 = y0 + state.getMax();\r\n }\r\n else if (edge == RectangleEdge.LEFT) {\r\n y0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, \r\n edge);\r\n y1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea,\r\n edge);\r\n x1 = state.getCursor() - this.categoryLabelPositionOffset;\r\n x0 = x1 - state.getMax();\r\n }\r\n else if (edge == RectangleEdge.RIGHT) {\r\n y0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, \r\n edge);\r\n y1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea,\r\n edge);\r\n x0 = state.getCursor() + this.categoryLabelPositionOffset;\r\n x1 = x0 - state.getMax();\r\n }\r\n Rectangle2D area = new Rectangle2D.Double(x0, y0, (x1 - x0),\r\n (y1 - y0));\r\n Point2D anchorPoint = RectangleAnchor.coordinates(area,\r\n position.getCategoryAnchor());\r\n TextBlock block = tick.getLabel();\r\n block.draw(g2, (float) anchorPoint.getX(),\r\n (float) anchorPoint.getY(), position.getLabelAnchor(),\r\n (float) anchorPoint.getX(), (float) anchorPoint.getY(),\r\n position.getAngle());\r\n Shape bounds = block.calculateBounds(g2,\r\n (float) anchorPoint.getX(), (float) anchorPoint.getY(),\r\n position.getLabelAnchor(), (float) anchorPoint.getX(),\r\n (float) anchorPoint.getY(), position.getAngle());\r\n if (plotState != null && plotState.getOwner() != null) {\r\n EntityCollection entities = plotState.getOwner()\r\n .getEntityCollection();\r\n if (entities != null) {\r\n String tooltip = getCategoryLabelToolTip(\r\n tick.getCategory());\r\n String url = getCategoryLabelURL(tick.getCategory());\r\n entities.add(new CategoryLabelEntity(tick.getCategory(),\r\n bounds, tooltip, url));\r\n }\r\n }\r\n categoryIndex++;\r\n }\r\n\r\n if (edge.equals(RectangleEdge.TOP)) {\r\n double h = state.getMax() + this.categoryLabelPositionOffset;\r\n state.cursorUp(h);\r\n }\r\n else if (edge.equals(RectangleEdge.BOTTOM)) {\r\n double h = state.getMax() + this.categoryLabelPositionOffset;\r\n state.cursorDown(h);\r\n }\r\n else if (edge == RectangleEdge.LEFT) {\r\n double w = state.getMax() + this.categoryLabelPositionOffset;\r\n state.cursorLeft(w);\r\n }\r\n else if (edge == RectangleEdge.RIGHT) {\r\n double w = state.getMax() + this.categoryLabelPositionOffset;\r\n state.cursorRight(w);\r\n }\r\n return state;\r\n }\r\n\r\n /**\r\n * Creates a temporary list of ticks that can be used when drawing the axis.\r\n *\r\n * @param g2 the graphics device (used to get font measurements).\r\n * @param state the axis state.\r\n * @param dataArea the area inside the axes.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n @Override\r\n public List refreshTicks(Graphics2D g2, AxisState state, \r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List ticks = new java.util.ArrayList();\r\n\r\n // sanity check for data area...\r\n if (dataArea.getHeight() <= 0.0 || dataArea.getWidth() < 0.0) {\r\n return ticks;\r\n }\r\n\r\n CategoryPlot plot = (CategoryPlot) getPlot();\r\n List categories = plot.getCategoriesForAxis(this);\r\n double max = 0.0;\r\n\r\n if (categories != null) {\r\n CategoryLabelPosition position\r\n = this.categoryLabelPositions.getLabelPosition(edge);\r\n float r = this.maximumCategoryLabelWidthRatio;\r\n if (r <= 0.0) {\r\n r = position.getWidthRatio();\r\n }\r\n\r\n float l;\r\n if (position.getWidthType() == CategoryLabelWidthType.CATEGORY) {\r\n l = (float) calculateCategorySize(categories.size(), dataArea,\r\n edge);\r\n }\r\n else {\r\n if (RectangleEdge.isLeftOrRight(edge)) {\r\n l = (float) dataArea.getWidth();\r\n }\r\n else {\r\n l = (float) dataArea.getHeight();\r\n }\r\n }\r\n int categoryIndex = 0;\r\n Iterator iterator = categories.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable category = (Comparable) iterator.next();\r\n g2.setFont(getTickLabelFont(category));\r\n TextBlock label = createLabel(category, l * r, edge, g2);\r\n if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {\r\n max = Math.max(max, calculateTextBlockHeight(label,\r\n position, g2));\r\n }\r\n else if (edge == RectangleEdge.LEFT\r\n || edge == RectangleEdge.RIGHT) {\r\n max = Math.max(max, calculateTextBlockWidth(label,\r\n position, g2));\r\n }\r\n Tick tick = new CategoryTick(category, label,\r\n position.getLabelAnchor(),\r\n position.getRotationAnchor(), position.getAngle());\r\n ticks.add(tick);\r\n categoryIndex = categoryIndex + 1;\r\n }\r\n }\r\n state.setMax(max);\r\n return ticks;\r\n\r\n }\r\n\r\n /**\r\n * Draws the tick marks.\r\n * \r\n * @param g2 the graphics target.\r\n * @param cursor the cursor position (an offset when drawing multiple axes)\r\n * @param dataArea the area for plotting the data.\r\n * @param edge the location of the axis.\r\n * @param state the axis state.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void drawTickMarks(Graphics2D g2, double cursor,\r\n Rectangle2D dataArea, RectangleEdge edge, AxisState state) {\r\n\r\n Plot p = getPlot();\r\n if (p == null) {\r\n return;\r\n }\r\n CategoryPlot plot = (CategoryPlot) p;\r\n double il = getTickMarkInsideLength();\r\n double ol = getTickMarkOutsideLength();\r\n Line2D line = new Line2D.Double();\r\n List categories = plot.getCategoriesForAxis(this);\r\n g2.setPaint(getTickMarkPaint());\r\n g2.setStroke(getTickMarkStroke());\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n if (edge.equals(RectangleEdge.TOP)) {\r\n Iterator iterator = categories.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable key = (Comparable) iterator.next();\r\n double x = getCategoryMiddle(key, categories, dataArea, edge);\r\n line.setLine(x, cursor, x, cursor + il);\r\n g2.draw(line);\r\n line.setLine(x, cursor, x, cursor - ol);\r\n g2.draw(line);\r\n }\r\n state.cursorUp(ol);\r\n } else if (edge.equals(RectangleEdge.BOTTOM)) {\r\n Iterator iterator = categories.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable key = (Comparable) iterator.next();\r\n double x = getCategoryMiddle(key, categories, dataArea, edge);\r\n line.setLine(x, cursor, x, cursor - il);\r\n g2.draw(line);\r\n line.setLine(x, cursor, x, cursor + ol);\r\n g2.draw(line);\r\n }\r\n state.cursorDown(ol);\r\n } else if (edge.equals(RectangleEdge.LEFT)) {\r\n Iterator iterator = categories.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable key = (Comparable) iterator.next();\r\n double y = getCategoryMiddle(key, categories, dataArea, edge);\r\n line.setLine(cursor, y, cursor + il, y);\r\n g2.draw(line);\r\n line.setLine(cursor, y, cursor - ol, y);\r\n g2.draw(line);\r\n }\r\n state.cursorLeft(ol);\r\n } else if (edge.equals(RectangleEdge.RIGHT)) {\r\n Iterator iterator = categories.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable key = (Comparable) iterator.next();\r\n double y = getCategoryMiddle(key, categories, dataArea, edge);\r\n line.setLine(cursor, y, cursor - il, y);\r\n g2.draw(line);\r\n line.setLine(cursor, y, cursor + ol, y);\r\n g2.draw(line);\r\n }\r\n state.cursorRight(ol);\r\n }\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n\r\n /**\r\n * Creates a label.\r\n *\r\n * @param category the category.\r\n * @param width the available width.\r\n * @param edge the edge on which the axis appears.\r\n * @param g2 the graphics device.\r\n *\r\n * @return A label.\r\n */\r\n protected TextBlock createLabel(Comparable category, float width,\r\n RectangleEdge edge, Graphics2D g2) {\r\n TextBlock label = TextUtilities.createTextBlock(category.toString(),\r\n getTickLabelFont(category), getTickLabelPaint(category), width,\r\n this.maximumCategoryLabelLines, new G2TextMeasurer(g2));\r\n return label;\r\n }\r\n\r\n /**\r\n * A utility method for determining the width of a text block.\r\n *\r\n * @param block the text block.\r\n * @param position the position.\r\n * @param g2 the graphics device.\r\n *\r\n * @return The width.\r\n */\r\n protected double calculateTextBlockWidth(TextBlock block,\r\n CategoryLabelPosition position, Graphics2D g2) {\r\n RectangleInsets insets = getTickLabelInsets();\r\n Size2D size = block.calculateDimensions(g2);\r\n Rectangle2D box = new Rectangle2D.Double(0.0, 0.0, size.getWidth(),\r\n size.getHeight());\r\n Shape rotatedBox = ShapeUtilities.rotateShape(box, position.getAngle(),\r\n 0.0f, 0.0f);\r\n double w = rotatedBox.getBounds2D().getWidth() + insets.getLeft()\r\n + insets.getRight();\r\n return w;\r\n }\r\n\r\n /**\r\n * A utility method for determining the height of a text block.\r\n *\r\n * @param block the text block.\r\n * @param position the label position.\r\n * @param g2 the graphics device.\r\n *\r\n * @return The height.\r\n */\r\n protected double calculateTextBlockHeight(TextBlock block,\r\n CategoryLabelPosition position, Graphics2D g2) {\r\n RectangleInsets insets = getTickLabelInsets();\r\n Size2D size = block.calculateDimensions(g2);\r\n Rectangle2D box = new Rectangle2D.Double(0.0, 0.0, size.getWidth(),\r\n size.getHeight());\r\n Shape rotatedBox = ShapeUtilities.rotateShape(box, position.getAngle(),\r\n 0.0f, 0.0f);\r\n double h = rotatedBox.getBounds2D().getHeight()\r\n + insets.getTop() + insets.getBottom();\r\n return h;\r\n }\r\n\r\n /**\r\n * Creates a clone of the axis.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if some component of the axis does\r\n * not support cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n CategoryAxis clone = (CategoryAxis) super.clone();\r\n clone.tickLabelFontMap = new HashMap(this.tickLabelFontMap);\r\n clone.tickLabelPaintMap = new HashMap(this.tickLabelPaintMap);\r\n clone.categoryLabelToolTips = new HashMap(this.categoryLabelToolTips);\r\n clone.categoryLabelURLs = new HashMap(this.categoryLabelToolTips);\r\n return clone;\r\n }\r\n\r\n /**\r\n * Tests this axis for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof CategoryAxis)) {\r\n return false;\r\n }\r\n if (!super.equals(obj)) {\r\n return false;\r\n }\r\n CategoryAxis that = (CategoryAxis) obj;\r\n if (that.lowerMargin != this.lowerMargin) {\r\n return false;\r\n }\r\n if (that.upperMargin != this.upperMargin) {\r\n return false;\r\n }\r\n if (that.categoryMargin != this.categoryMargin) {\r\n return false;\r\n }\r\n if (that.maximumCategoryLabelWidthRatio\r\n != this.maximumCategoryLabelWidthRatio) {\r\n return false;\r\n }\r\n if (that.categoryLabelPositionOffset\r\n != this.categoryLabelPositionOffset) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(that.categoryLabelPositions,\r\n this.categoryLabelPositions)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(that.categoryLabelToolTips,\r\n this.categoryLabelToolTips)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.categoryLabelURLs, \r\n that.categoryLabelURLs)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.tickLabelFontMap,\r\n that.tickLabelFontMap)) {\r\n return false;\r\n }\r\n if (!equalPaintMaps(this.tickLabelPaintMap, that.tickLabelPaintMap)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code for this object.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n return super.hashCode();\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n writePaintMap(this.tickLabelPaintMap, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.tickLabelPaintMap = readPaintMap(stream);\r\n }\r\n\r\n /**\r\n * Reads a <code>Map</code> of (<code>Comparable</code>, <code>Paint</code>)\r\n * elements from a stream.\r\n *\r\n * @param in the input stream.\r\n *\r\n * @return The map.\r\n *\r\n * @throws IOException\r\n * @throws ClassNotFoundException\r\n *\r\n * @see #writePaintMap(Map, ObjectOutputStream)\r\n */\r\n private Map readPaintMap(ObjectInputStream in)\r\n throws IOException, ClassNotFoundException {\r\n boolean isNull = in.readBoolean();\r\n if (isNull) {\r\n return null;\r\n }\r\n Map result = new HashMap();\r\n int count = in.readInt();\r\n for (int i = 0; i < count; i++) {\r\n Comparable category = (Comparable) in.readObject();\r\n Paint paint = SerialUtilities.readPaint(in);\r\n result.put(category, paint);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Writes a map of (<code>Comparable</code>, <code>Paint</code>)\r\n * elements to a stream.\r\n *\r\n * @param map the map (<code>null</code> permitted).\r\n *\r\n * @param out\r\n * @throws IOException\r\n *\r\n * @see #readPaintMap(ObjectInputStream)\r\n */\r\n private void writePaintMap(Map map, ObjectOutputStream out)\r\n throws IOException {\r\n if (map == null) {\r\n out.writeBoolean(true);\r\n }\r\n else {\r\n out.writeBoolean(false);\r\n Set keys = map.keySet();\r\n int count = keys.size();\r\n out.writeInt(count);\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable key = (Comparable) iterator.next();\r\n out.writeObject(key);\r\n SerialUtilities.writePaint((Paint) map.get(key), out);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Tests two maps containing (<code>Comparable</code>, <code>Paint</code>)\r\n * elements for equality.\r\n *\r\n * @param map1 the first map (<code>null</code> not permitted).\r\n * @param map2 the second map (<code>null</code> not permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n private boolean equalPaintMaps(Map map1, Map map2) {\r\n if (map1.size() != map2.size()) {\r\n return false;\r\n }\r\n Set entries = map1.entrySet();\r\n Iterator iterator = entries.iterator();\r\n while (iterator.hasNext()) {\r\n Map.Entry entry = (Map.Entry) iterator.next();\r\n Paint p1 = (Paint) entry.getValue();\r\n Paint p2 = (Paint) map2.get(entry.getKey());\r\n if (!PaintUtilities.equal(p1, p2)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Draws the category labels and returns the updated axis state.\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param dataArea the area inside the axes (<code>null</code> not\r\n * permitted).\r\n * @param edge the axis location (<code>null</code> not permitted).\r\n * @param state the axis state (<code>null</code> not permitted).\r\n * @param plotState collects information about the plot (<code>null</code>\r\n * permitted).\r\n *\r\n * @return The updated axis state (never <code>null</code>).\r\n *\r\n * @deprecated Use {@link #drawCategoryLabels(Graphics2D, Rectangle2D,\r\n * Rectangle2D, RectangleEdge, AxisState, PlotRenderingInfo)}.\r\n */\r\n protected AxisState drawCategoryLabels(Graphics2D g2, Rectangle2D dataArea,\r\n RectangleEdge edge, AxisState state, PlotRenderingInfo plotState) {\r\n // this method is deprecated because we really need the plotArea\r\n // when drawing the labels - see bug 1277726\r\n return drawCategoryLabels(g2, dataArea, dataArea, edge, state,\r\n plotState);\r\n }\r\n\r\n}\r" }, { "identifier": "NumberAxis", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/axis/NumberAxis.java", "snippet": "public class NumberAxis extends ValueAxis implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 2805933088476185789L;\r\n\r\n /** The default value for the autoRangeIncludesZero flag. */\r\n public static final boolean DEFAULT_AUTO_RANGE_INCLUDES_ZERO = true;\r\n\r\n /** The default value for the autoRangeStickyZero flag. */\r\n public static final boolean DEFAULT_AUTO_RANGE_STICKY_ZERO = true;\r\n\r\n /** The default tick unit. */\r\n public static final NumberTickUnit DEFAULT_TICK_UNIT = new NumberTickUnit(\r\n 1.0, new DecimalFormat(\"0\"));\r\n\r\n /** The default setting for the vertical tick labels flag. */\r\n public static final boolean DEFAULT_VERTICAL_TICK_LABELS = false;\r\n\r\n /**\r\n * The range type (can be used to force the axis to display only positive\r\n * values or only negative values).\r\n */\r\n private RangeType rangeType;\r\n\r\n /**\r\n * A flag that affects the axis range when the range is determined\r\n * automatically. If the auto range does NOT include zero and this flag\r\n * is TRUE, then the range is changed to include zero.\r\n */\r\n private boolean autoRangeIncludesZero;\r\n\r\n /**\r\n * A flag that affects the size of the margins added to the axis range when\r\n * the range is determined automatically. If the value 0 falls within the\r\n * margin and this flag is TRUE, then the margin is truncated at zero.\r\n */\r\n private boolean autoRangeStickyZero;\r\n\r\n /** The tick unit for the axis. */\r\n private NumberTickUnit tickUnit;\r\n\r\n /** The override number format. */\r\n private NumberFormat numberFormatOverride;\r\n\r\n /** An optional band for marking regions on the axis. */\r\n private MarkerAxisBand markerBand;\r\n\r\n /**\r\n * Default constructor.\r\n */\r\n public NumberAxis() {\r\n this(null);\r\n }\r\n\r\n /**\r\n * Constructs a number axis, using default values where necessary.\r\n *\r\n * @param label the axis label (<code>null</code> permitted).\r\n */\r\n public NumberAxis(String label) {\r\n super(label, NumberAxis.createStandardTickUnits());\r\n this.rangeType = RangeType.FULL;\r\n this.autoRangeIncludesZero = DEFAULT_AUTO_RANGE_INCLUDES_ZERO;\r\n this.autoRangeStickyZero = DEFAULT_AUTO_RANGE_STICKY_ZERO;\r\n this.tickUnit = DEFAULT_TICK_UNIT;\r\n this.numberFormatOverride = null;\r\n this.markerBand = null;\r\n }\r\n\r\n /**\r\n * Returns the axis range type.\r\n *\r\n * @return The axis range type (never <code>null</code>).\r\n *\r\n * @see #setRangeType(RangeType)\r\n */\r\n public RangeType getRangeType() {\r\n return this.rangeType;\r\n }\r\n\r\n /**\r\n * Sets the axis range type.\r\n *\r\n * @param rangeType the range type (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeType()\r\n */\r\n public void setRangeType(RangeType rangeType) {\r\n ParamChecks.nullNotPermitted(rangeType, \"rangeType\");\r\n this.rangeType = rangeType;\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the flag that indicates whether or not the automatic axis range\r\n * (if indeed it is determined automatically) is forced to include zero.\r\n *\r\n * @return The flag.\r\n */\r\n public boolean getAutoRangeIncludesZero() {\r\n return this.autoRangeIncludesZero;\r\n }\r\n\r\n /**\r\n * Sets the flag that indicates whether or not the axis range, if\r\n * automatically calculated, is forced to include zero.\r\n * <p>\r\n * If the flag is changed to <code>true</code>, the axis range is\r\n * recalculated.\r\n * <p>\r\n * Any change to the flag will trigger an {@link AxisChangeEvent}.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #getAutoRangeIncludesZero()\r\n */\r\n public void setAutoRangeIncludesZero(boolean flag) {\r\n if (this.autoRangeIncludesZero != flag) {\r\n this.autoRangeIncludesZero = flag;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag that affects the auto-range when zero falls outside the\r\n * data range but inside the margins defined for the axis.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAutoRangeStickyZero(boolean)\r\n */\r\n public boolean getAutoRangeStickyZero() {\r\n return this.autoRangeStickyZero;\r\n }\r\n\r\n /**\r\n * Sets a flag that affects the auto-range when zero falls outside the data\r\n * range but inside the margins defined for the axis.\r\n *\r\n * @param flag the new flag.\r\n *\r\n * @see #getAutoRangeStickyZero()\r\n */\r\n public void setAutoRangeStickyZero(boolean flag) {\r\n if (this.autoRangeStickyZero != flag) {\r\n this.autoRangeStickyZero = flag;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the tick unit for the axis.\r\n * <p>\r\n * Note: if the <code>autoTickUnitSelection</code> flag is\r\n * <code>true</code> the tick unit may be changed while the axis is being\r\n * drawn, so in that case the return value from this method may be\r\n * irrelevant if the method is called before the axis has been drawn.\r\n *\r\n * @return The tick unit for the axis.\r\n *\r\n * @see #setTickUnit(NumberTickUnit)\r\n * @see ValueAxis#isAutoTickUnitSelection()\r\n */\r\n public NumberTickUnit getTickUnit() {\r\n return this.tickUnit;\r\n }\r\n\r\n /**\r\n * Sets the tick unit for the axis and sends an {@link AxisChangeEvent} to\r\n * all registered listeners. A side effect of calling this method is that\r\n * the \"auto-select\" feature for tick units is switched off (you can\r\n * restore it using the {@link ValueAxis#setAutoTickUnitSelection(boolean)}\r\n * method).\r\n *\r\n * @param unit the new tick unit (<code>null</code> not permitted).\r\n *\r\n * @see #getTickUnit()\r\n * @see #setTickUnit(NumberTickUnit, boolean, boolean)\r\n */\r\n public void setTickUnit(NumberTickUnit unit) {\r\n // defer argument checking...\r\n setTickUnit(unit, true, true);\r\n }\r\n\r\n /**\r\n * Sets the tick unit for the axis and, if requested, sends an\r\n * {@link AxisChangeEvent} to all registered listeners. In addition, an\r\n * option is provided to turn off the \"auto-select\" feature for tick units\r\n * (you can restore it using the\r\n * {@link ValueAxis#setAutoTickUnitSelection(boolean)} method).\r\n *\r\n * @param unit the new tick unit (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n * @param turnOffAutoSelect turn off the auto-tick selection?\r\n */\r\n public void setTickUnit(NumberTickUnit unit, boolean notify,\r\n boolean turnOffAutoSelect) {\r\n\r\n ParamChecks.nullNotPermitted(unit, \"unit\");\r\n this.tickUnit = unit;\r\n if (turnOffAutoSelect) {\r\n setAutoTickUnitSelection(false, false);\r\n }\r\n if (notify) {\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the number format override. If this is non-null, then it will\r\n * be used to format the numbers on the axis.\r\n *\r\n * @return The number formatter (possibly <code>null</code>).\r\n *\r\n * @see #setNumberFormatOverride(NumberFormat)\r\n */\r\n public NumberFormat getNumberFormatOverride() {\r\n return this.numberFormatOverride;\r\n }\r\n\r\n /**\r\n * Sets the number format override. If this is non-null, then it will be\r\n * used to format the numbers on the axis.\r\n *\r\n * @param formatter the number formatter (<code>null</code> permitted).\r\n *\r\n * @see #getNumberFormatOverride()\r\n */\r\n public void setNumberFormatOverride(NumberFormat formatter) {\r\n this.numberFormatOverride = formatter;\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Returns the (optional) marker band for the axis.\r\n *\r\n * @return The marker band (possibly <code>null</code>).\r\n *\r\n * @see #setMarkerBand(MarkerAxisBand)\r\n */\r\n public MarkerAxisBand getMarkerBand() {\r\n return this.markerBand;\r\n }\r\n\r\n /**\r\n * Sets the marker band for the axis.\r\n * <P>\r\n * The marker band is optional, leave it set to <code>null</code> if you\r\n * don't require it.\r\n *\r\n * @param band the new band (<code>null</code> permitted).\r\n *\r\n * @see #getMarkerBand()\r\n */\r\n public void setMarkerBand(MarkerAxisBand band) {\r\n this.markerBand = band;\r\n notifyListeners(new AxisChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Configures the axis to work with the specified plot. If the axis has\r\n * auto-scaling, then sets the maximum and minimum values.\r\n */\r\n @Override\r\n public void configure() {\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n }\r\n\r\n /**\r\n * Rescales the axis to ensure that all data is visible.\r\n */\r\n @Override\r\n protected void autoAdjustRange() {\r\n\r\n Plot plot = getPlot();\r\n if (plot == null) {\r\n return; // no plot, no data\r\n }\r\n\r\n if (plot instanceof ValueAxisPlot) {\r\n ValueAxisPlot vap = (ValueAxisPlot) plot;\r\n\r\n Range r = vap.getDataRange(this);\r\n if (r == null) {\r\n r = getDefaultAutoRange();\r\n }\r\n\r\n double upper = r.getUpperBound();\r\n double lower = r.getLowerBound();\r\n if (this.rangeType == RangeType.POSITIVE) {\r\n lower = Math.max(0.0, lower);\r\n upper = Math.max(0.0, upper);\r\n }\r\n else if (this.rangeType == RangeType.NEGATIVE) {\r\n lower = Math.min(0.0, lower);\r\n upper = Math.min(0.0, upper);\r\n }\r\n\r\n if (getAutoRangeIncludesZero()) {\r\n lower = Math.min(lower, 0.0);\r\n upper = Math.max(upper, 0.0);\r\n }\r\n double range = upper - lower;\r\n\r\n // if fixed auto range, then derive lower bound...\r\n double fixedAutoRange = getFixedAutoRange();\r\n if (fixedAutoRange > 0.0) {\r\n lower = upper - fixedAutoRange;\r\n }\r\n else {\r\n // ensure the autorange is at least <minRange> in size...\r\n double minRange = getAutoRangeMinimumSize();\r\n if (range < minRange) {\r\n double expand = (minRange - range) / 2;\r\n upper = upper + expand;\r\n lower = lower - expand;\r\n if (lower == upper) { // see bug report 1549218\r\n double adjust = Math.abs(lower) / 10.0;\r\n lower = lower - adjust;\r\n upper = upper + adjust;\r\n }\r\n if (this.rangeType == RangeType.POSITIVE) {\r\n if (lower < 0.0) {\r\n upper = upper - lower;\r\n lower = 0.0;\r\n }\r\n }\r\n else if (this.rangeType == RangeType.NEGATIVE) {\r\n if (upper > 0.0) {\r\n lower = lower - upper;\r\n upper = 0.0;\r\n }\r\n }\r\n }\r\n\r\n if (getAutoRangeStickyZero()) {\r\n if (upper <= 0.0) {\r\n upper = Math.min(0.0, upper + getUpperMargin() * range);\r\n }\r\n else {\r\n upper = upper + getUpperMargin() * range;\r\n }\r\n if (lower >= 0.0) {\r\n lower = Math.max(0.0, lower - getLowerMargin() * range);\r\n }\r\n else {\r\n lower = lower - getLowerMargin() * range;\r\n }\r\n }\r\n else {\r\n upper = upper + getUpperMargin() * range;\r\n lower = lower - getLowerMargin() * range;\r\n }\r\n }\r\n\r\n setRange(new Range(lower, upper), false, false);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Converts a data value to a coordinate in Java2D space, assuming that the\r\n * axis runs along one edge of the specified dataArea.\r\n * <p>\r\n * Note that it is possible for the coordinate to fall outside the plotArea.\r\n *\r\n * @param value the data value.\r\n * @param area the area for plotting the data.\r\n * @param edge the axis location.\r\n *\r\n * @return The Java2D coordinate.\r\n *\r\n * @see #java2DToValue(double, Rectangle2D, RectangleEdge)\r\n */\r\n @Override\r\n public double valueToJava2D(double value, Rectangle2D area,\r\n RectangleEdge edge) {\r\n\r\n Range range = getRange();\r\n double axisMin = range.getLowerBound();\r\n double axisMax = range.getUpperBound();\r\n\r\n double min = 0.0;\r\n double max = 0.0;\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n min = area.getX();\r\n max = area.getMaxX();\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n max = area.getMinY();\r\n min = area.getMaxY();\r\n }\r\n if (isInverted()) {\r\n return max\r\n - ((value - axisMin) / (axisMax - axisMin)) * (max - min);\r\n }\r\n else {\r\n return min\r\n + ((value - axisMin) / (axisMax - axisMin)) * (max - min);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Converts a coordinate in Java2D space to the corresponding data value,\r\n * assuming that the axis runs along one edge of the specified dataArea.\r\n *\r\n * @param java2DValue the coordinate in Java2D space.\r\n * @param area the area in which the data is plotted.\r\n * @param edge the location.\r\n *\r\n * @return The data value.\r\n *\r\n * @see #valueToJava2D(double, Rectangle2D, RectangleEdge)\r\n */\r\n @Override\r\n public double java2DToValue(double java2DValue, Rectangle2D area,\r\n RectangleEdge edge) {\r\n\r\n Range range = getRange();\r\n double axisMin = range.getLowerBound();\r\n double axisMax = range.getUpperBound();\r\n\r\n double min = 0.0;\r\n double max = 0.0;\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n min = area.getX();\r\n max = area.getMaxX();\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n min = area.getMaxY();\r\n max = area.getY();\r\n }\r\n if (isInverted()) {\r\n return axisMax\r\n - (java2DValue - min) / (max - min) * (axisMax - axisMin);\r\n }\r\n else {\r\n return axisMin\r\n + (java2DValue - min) / (max - min) * (axisMax - axisMin);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Calculates the value of the lowest visible tick on the axis.\r\n *\r\n * @return The value of the lowest visible tick on the axis.\r\n *\r\n * @see #calculateHighestVisibleTickValue()\r\n */\r\n protected double calculateLowestVisibleTickValue() {\r\n double unit = getTickUnit().getSize();\r\n double index = Math.ceil(getRange().getLowerBound() / unit);\r\n return index * unit;\r\n }\r\n\r\n /**\r\n * Calculates the value of the highest visible tick on the axis.\r\n *\r\n * @return The value of the highest visible tick on the axis.\r\n *\r\n * @see #calculateLowestVisibleTickValue()\r\n */\r\n protected double calculateHighestVisibleTickValue() {\r\n double unit = getTickUnit().getSize();\r\n double index = Math.floor(getRange().getUpperBound() / unit);\r\n return index * unit;\r\n }\r\n\r\n /**\r\n * Calculates the number of visible ticks.\r\n *\r\n * @return The number of visible ticks on the axis.\r\n */\r\n protected int calculateVisibleTickCount() {\r\n double unit = getTickUnit().getSize();\r\n Range range = getRange();\r\n return (int) (Math.floor(range.getUpperBound() / unit)\r\n - Math.ceil(range.getLowerBound() / unit) + 1);\r\n }\r\n\r\n /**\r\n * Draws the axis on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param cursor the cursor location.\r\n * @param plotArea the area within which the axes and data should be drawn\r\n * (<code>null</code> not permitted).\r\n * @param dataArea the area within which the data should be drawn\r\n * (<code>null</code> not permitted).\r\n * @param edge the location of the axis (<code>null</code> not permitted).\r\n * @param plotState collects information about the plot\r\n * (<code>null</code> permitted).\r\n *\r\n * @return The axis state (never <code>null</code>).\r\n */\r\n @Override\r\n public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,\r\n Rectangle2D dataArea, RectangleEdge edge,\r\n PlotRenderingInfo plotState) {\r\n\r\n AxisState state;\r\n // if the axis is not visible, don't draw it...\r\n if (!isVisible()) {\r\n state = new AxisState(cursor);\r\n // even though the axis is not visible, we need ticks for the\r\n // gridlines...\r\n List ticks = refreshTicks(g2, state, dataArea, edge);\r\n state.setTicks(ticks);\r\n return state;\r\n }\r\n\r\n // draw the tick marks and labels...\r\n state = drawTickMarksAndLabels(g2, cursor, plotArea, dataArea, edge);\r\n\r\n if (getAttributedLabel() != null) {\r\n state = drawAttributedLabel(getAttributedLabel(), g2, plotArea, \r\n dataArea, edge, state);\r\n \r\n } else {\r\n state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);\r\n }\r\n createAndAddEntity(cursor, state, dataArea, edge, plotState);\r\n return state;\r\n\r\n }\r\n\r\n /**\r\n * Creates the standard tick units.\r\n * <P>\r\n * If you don't like these defaults, create your own instance of TickUnits\r\n * and then pass it to the setStandardTickUnits() method in the\r\n * NumberAxis class.\r\n *\r\n * @return The standard tick units.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n * @see #createIntegerTickUnits()\r\n */\r\n public static TickUnitSource createStandardTickUnits() {\r\n return new NumberTickUnitSource();\r\n }\r\n\r\n /**\r\n * Returns a collection of tick units for integer values.\r\n *\r\n * @return A collection of tick units for integer values.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n * @see #createStandardTickUnits()\r\n */\r\n public static TickUnitSource createIntegerTickUnits() {\r\n return new NumberTickUnitSource(true);\r\n }\r\n\r\n /**\r\n * Creates a collection of standard tick units. The supplied locale is\r\n * used to create the number formatter (a localised instance of\r\n * <code>NumberFormat</code>).\r\n * <P>\r\n * If you don't like these defaults, create your own instance of\r\n * {@link TickUnits} and then pass it to the\r\n * <code>setStandardTickUnits()</code> method.\r\n *\r\n * @param locale the locale.\r\n *\r\n * @return A tick unit collection.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n */\r\n public static TickUnitSource createStandardTickUnits(Locale locale) {\r\n NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);\r\n return new NumberTickUnitSource(false, numberFormat);\r\n }\r\n\r\n /**\r\n * Returns a collection of tick units for integer values.\r\n * Uses a given Locale to create the DecimalFormats.\r\n *\r\n * @param locale the locale to use to represent Numbers.\r\n *\r\n * @return A collection of tick units for integer values.\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n */\r\n public static TickUnitSource createIntegerTickUnits(Locale locale) {\r\n NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);\r\n return new NumberTickUnitSource(true, numberFormat);\r\n }\r\n\r\n /**\r\n * Estimates the maximum tick label height.\r\n *\r\n * @param g2 the graphics device.\r\n *\r\n * @return The maximum height.\r\n */\r\n protected double estimateMaximumTickLabelHeight(Graphics2D g2) {\r\n RectangleInsets tickLabelInsets = getTickLabelInsets();\r\n double result = tickLabelInsets.getTop() + tickLabelInsets.getBottom();\r\n\r\n Font tickLabelFont = getTickLabelFont();\r\n FontRenderContext frc = g2.getFontRenderContext();\r\n result += tickLabelFont.getLineMetrics(\"123\", frc).getHeight();\r\n return result;\r\n }\r\n\r\n /**\r\n * Estimates the maximum width of the tick labels, assuming the specified\r\n * tick unit is used.\r\n * <P>\r\n * Rather than computing the string bounds of every tick on the axis, we\r\n * just look at two values: the lower bound and the upper bound for the\r\n * axis. These two values will usually be representative.\r\n *\r\n * @param g2 the graphics device.\r\n * @param unit the tick unit to use for calculation.\r\n *\r\n * @return The estimated maximum width of the tick labels.\r\n */\r\n protected double estimateMaximumTickLabelWidth(Graphics2D g2,\r\n TickUnit unit) {\r\n\r\n RectangleInsets tickLabelInsets = getTickLabelInsets();\r\n double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();\r\n\r\n if (isVerticalTickLabels()) {\r\n // all tick labels have the same width (equal to the height of the\r\n // font)...\r\n FontRenderContext frc = g2.getFontRenderContext();\r\n LineMetrics lm = getTickLabelFont().getLineMetrics(\"0\", frc);\r\n result += lm.getHeight();\r\n }\r\n else {\r\n // look at lower and upper bounds...\r\n FontMetrics fm = g2.getFontMetrics(getTickLabelFont());\r\n Range range = getRange();\r\n double lower = range.getLowerBound();\r\n double upper = range.getUpperBound();\r\n String lowerStr, upperStr;\r\n NumberFormat formatter = getNumberFormatOverride();\r\n if (formatter != null) {\r\n lowerStr = formatter.format(lower);\r\n upperStr = formatter.format(upper);\r\n }\r\n else {\r\n lowerStr = unit.valueToString(lower);\r\n upperStr = unit.valueToString(upper);\r\n }\r\n double w1 = fm.stringWidth(lowerStr);\r\n double w2 = fm.stringWidth(upperStr);\r\n result += Math.max(w1, w2);\r\n }\r\n\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Selects an appropriate tick value for the axis. The strategy is to\r\n * display as many ticks as possible (selected from an array of 'standard'\r\n * tick units) without the labels overlapping.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area defined by the axes.\r\n * @param edge the axis location.\r\n */\r\n protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea,\r\n RectangleEdge edge) {\r\n\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n selectHorizontalAutoTickUnit(g2, dataArea, edge);\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n selectVerticalAutoTickUnit(g2, dataArea, edge);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Selects an appropriate tick value for the axis. The strategy is to\r\n * display as many ticks as possible (selected from an array of 'standard'\r\n * tick units) without the labels overlapping.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area defined by the axes.\r\n * @param edge the axis location.\r\n */\r\n protected void selectHorizontalAutoTickUnit(Graphics2D g2,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n double tickLabelWidth = estimateMaximumTickLabelWidth(g2,\r\n getTickUnit());\r\n\r\n // start with the current tick unit...\r\n TickUnitSource tickUnits = getStandardTickUnits();\r\n TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());\r\n double unit1Width = lengthToJava2D(unit1.getSize(), dataArea, edge);\r\n\r\n // then extrapolate...\r\n double guess = (tickLabelWidth / unit1Width) * unit1.getSize();\r\n\r\n NumberTickUnit unit2 = (NumberTickUnit) tickUnits.getCeilingTickUnit(\r\n guess);\r\n double unit2Width = lengthToJava2D(unit2.getSize(), dataArea, edge);\r\n\r\n tickLabelWidth = estimateMaximumTickLabelWidth(g2, unit2);\r\n if (tickLabelWidth > unit2Width) {\r\n unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);\r\n }\r\n\r\n setTickUnit(unit2, false, false);\r\n\r\n }\r\n\r\n /**\r\n * Selects an appropriate tick value for the axis. The strategy is to\r\n * display as many ticks as possible (selected from an array of 'standard'\r\n * tick units) without the labels overlapping.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area in which the plot should be drawn.\r\n * @param edge the axis location.\r\n */\r\n protected void selectVerticalAutoTickUnit(Graphics2D g2, \r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n double tickLabelHeight = estimateMaximumTickLabelHeight(g2);\r\n\r\n // start with the current tick unit...\r\n TickUnitSource tickUnits = getStandardTickUnits();\r\n TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());\r\n double unitHeight = lengthToJava2D(unit1.getSize(), dataArea, edge);\r\n double guess = unit1.getSize();\r\n if (unitHeight > 0) {\r\n // then extrapolate...\r\n guess = (tickLabelHeight / unitHeight) * unit1.getSize();\r\n }\r\n NumberTickUnit unit2 = (NumberTickUnit) tickUnits.getCeilingTickUnit(\r\n guess);\r\n double unit2Height = lengthToJava2D(unit2.getSize(), dataArea, edge);\r\n\r\n tickLabelHeight = estimateMaximumTickLabelHeight(g2);\r\n if (tickLabelHeight > unit2Height) {\r\n unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);\r\n }\r\n\r\n setTickUnit(unit2, false, false);\r\n\r\n }\r\n\r\n /**\r\n * Calculates the positions of the tick labels for the axis, storing the\r\n * results in the tick label list (ready for drawing).\r\n *\r\n * @param g2 the graphics device.\r\n * @param state the axis state.\r\n * @param dataArea the area in which the plot should be drawn.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n @Override\r\n public List refreshTicks(Graphics2D g2, AxisState state, \r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List result = new java.util.ArrayList();\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n result = refreshTicksHorizontal(g2, dataArea, edge);\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n result = refreshTicksVertical(g2, dataArea, edge);\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the positions of the tick labels for the axis, storing the\r\n * results in the tick label list (ready for drawing).\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area in which the data should be drawn.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n protected List refreshTicksHorizontal(Graphics2D g2,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List result = new java.util.ArrayList();\r\n\r\n Font tickLabelFont = getTickLabelFont();\r\n g2.setFont(tickLabelFont);\r\n\r\n if (isAutoTickUnitSelection()) {\r\n selectAutoTickUnit(g2, dataArea, edge);\r\n }\r\n\r\n TickUnit tu = getTickUnit();\r\n double size = tu.getSize();\r\n int count = calculateVisibleTickCount();\r\n double lowestTickValue = calculateLowestVisibleTickValue();\r\n\r\n if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {\r\n int minorTickSpaces = getMinorTickCount();\r\n if (minorTickSpaces <= 0) {\r\n minorTickSpaces = tu.getMinorTickCount();\r\n }\r\n for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {\r\n double minorTickValue = lowestTickValue \r\n - size * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR, minorTickValue,\r\n \"\", TextAnchor.TOP_CENTER, TextAnchor.CENTER,\r\n 0.0));\r\n }\r\n }\r\n for (int i = 0; i < count; i++) {\r\n double currentTickValue = lowestTickValue + (i * size);\r\n String tickLabel;\r\n NumberFormat formatter = getNumberFormatOverride();\r\n if (formatter != null) {\r\n tickLabel = formatter.format(currentTickValue);\r\n }\r\n else {\r\n tickLabel = getTickUnit().valueToString(currentTickValue);\r\n }\r\n TextAnchor anchor, rotationAnchor;\r\n double angle = 0.0;\r\n if (isVerticalTickLabels()) {\r\n anchor = TextAnchor.CENTER_RIGHT;\r\n rotationAnchor = TextAnchor.CENTER_RIGHT;\r\n if (edge == RectangleEdge.TOP) {\r\n angle = Math.PI / 2.0;\r\n }\r\n else {\r\n angle = -Math.PI / 2.0;\r\n }\r\n }\r\n else {\r\n if (edge == RectangleEdge.TOP) {\r\n anchor = TextAnchor.BOTTOM_CENTER;\r\n rotationAnchor = TextAnchor.BOTTOM_CENTER;\r\n }\r\n else {\r\n anchor = TextAnchor.TOP_CENTER;\r\n rotationAnchor = TextAnchor.TOP_CENTER;\r\n }\r\n }\r\n\r\n Tick tick = new NumberTick(new Double(currentTickValue),\r\n tickLabel, anchor, rotationAnchor, angle);\r\n result.add(tick);\r\n double nextTickValue = lowestTickValue + ((i + 1) * size);\r\n for (int minorTick = 1; minorTick < minorTickSpaces;\r\n minorTick++) {\r\n double minorTickValue = currentTickValue\r\n + (nextTickValue - currentTickValue)\r\n * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR,\r\n minorTickValue, \"\", TextAnchor.TOP_CENTER,\r\n TextAnchor.CENTER, 0.0));\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the positions of the tick labels for the axis, storing the\r\n * results in the tick label list (ready for drawing).\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area in which the plot should be drawn.\r\n * @param edge the location of the axis.\r\n *\r\n * @return A list of ticks.\r\n */\r\n protected List refreshTicksVertical(Graphics2D g2,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n List result = new java.util.ArrayList();\r\n result.clear();\r\n\r\n Font tickLabelFont = getTickLabelFont();\r\n g2.setFont(tickLabelFont);\r\n if (isAutoTickUnitSelection()) {\r\n selectAutoTickUnit(g2, dataArea, edge);\r\n }\r\n\r\n TickUnit tu = getTickUnit();\r\n double size = tu.getSize();\r\n int count = calculateVisibleTickCount();\r\n double lowestTickValue = calculateLowestVisibleTickValue();\r\n\r\n if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {\r\n int minorTickSpaces = getMinorTickCount();\r\n if (minorTickSpaces <= 0) {\r\n minorTickSpaces = tu.getMinorTickCount();\r\n }\r\n for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {\r\n double minorTickValue = lowestTickValue\r\n - size * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR, minorTickValue,\r\n \"\", TextAnchor.TOP_CENTER, TextAnchor.CENTER,\r\n 0.0));\r\n }\r\n }\r\n\r\n for (int i = 0; i < count; i++) {\r\n double currentTickValue = lowestTickValue + (i * size);\r\n String tickLabel;\r\n NumberFormat formatter = getNumberFormatOverride();\r\n if (formatter != null) {\r\n tickLabel = formatter.format(currentTickValue);\r\n }\r\n else {\r\n tickLabel = getTickUnit().valueToString(currentTickValue);\r\n }\r\n\r\n TextAnchor anchor;\r\n TextAnchor rotationAnchor;\r\n double angle = 0.0;\r\n if (isVerticalTickLabels()) {\r\n if (edge == RectangleEdge.LEFT) {\r\n anchor = TextAnchor.BOTTOM_CENTER;\r\n rotationAnchor = TextAnchor.BOTTOM_CENTER;\r\n angle = -Math.PI / 2.0;\r\n }\r\n else {\r\n anchor = TextAnchor.BOTTOM_CENTER;\r\n rotationAnchor = TextAnchor.BOTTOM_CENTER;\r\n angle = Math.PI / 2.0;\r\n }\r\n }\r\n else {\r\n if (edge == RectangleEdge.LEFT) {\r\n anchor = TextAnchor.CENTER_RIGHT;\r\n rotationAnchor = TextAnchor.CENTER_RIGHT;\r\n }\r\n else {\r\n anchor = TextAnchor.CENTER_LEFT;\r\n rotationAnchor = TextAnchor.CENTER_LEFT;\r\n }\r\n }\r\n\r\n Tick tick = new NumberTick(new Double(currentTickValue),\r\n tickLabel, anchor, rotationAnchor, angle);\r\n result.add(tick);\r\n\r\n double nextTickValue = lowestTickValue + ((i + 1) * size);\r\n for (int minorTick = 1; minorTick < minorTickSpaces;\r\n minorTick++) {\r\n double minorTickValue = currentTickValue\r\n + (nextTickValue - currentTickValue)\r\n * minorTick / minorTickSpaces;\r\n if (getRange().contains(minorTickValue)) {\r\n result.add(new NumberTick(TickType.MINOR,\r\n minorTickValue, \"\", TextAnchor.TOP_CENTER,\r\n TextAnchor.CENTER, 0.0));\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Returns a clone of the axis.\r\n *\r\n * @return A clone\r\n *\r\n * @throws CloneNotSupportedException if some component of the axis does\r\n * not support cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n NumberAxis clone = (NumberAxis) super.clone();\r\n if (this.numberFormatOverride != null) {\r\n clone.numberFormatOverride\r\n = (NumberFormat) this.numberFormatOverride.clone();\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * Tests the axis for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof NumberAxis)) {\r\n return false;\r\n }\r\n NumberAxis that = (NumberAxis) obj;\r\n if (this.autoRangeIncludesZero != that.autoRangeIncludesZero) {\r\n return false;\r\n }\r\n if (this.autoRangeStickyZero != that.autoRangeStickyZero) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.tickUnit, that.tickUnit)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.numberFormatOverride,\r\n that.numberFormatOverride)) {\r\n return false;\r\n }\r\n if (!this.rangeType.equals(that.rangeType)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a hash code for this object.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n return super.hashCode();\r\n }\r\n\r\n}\r" }, { "identifier": "CategoryPlot", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/CategoryPlot.java", "snippet": "public class CategoryPlot extends Plot implements ValueAxisPlot, Pannable,\r\n Zoomable, AnnotationChangeListener, RendererChangeListener,\r\n Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -3537691700434728188L;\r\n\r\n /**\r\n * The default visibility of the grid lines plotted against the domain\r\n * axis.\r\n */\r\n public static final boolean DEFAULT_DOMAIN_GRIDLINES_VISIBLE = false;\r\n\r\n /**\r\n * The default visibility of the grid lines plotted against the range\r\n * axis.\r\n */\r\n public static final boolean DEFAULT_RANGE_GRIDLINES_VISIBLE = true;\r\n\r\n /** The default grid line stroke. */\r\n public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f,\r\n BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f, new float[]\r\n {2.0f, 2.0f}, 0.0f);\r\n\r\n /** The default grid line paint. */\r\n public static final Paint DEFAULT_GRIDLINE_PAINT = Color.lightGray;\r\n\r\n /** The default value label font. */\r\n public static final Font DEFAULT_VALUE_LABEL_FONT = new Font(\"SansSerif\",\r\n Font.PLAIN, 10);\r\n\r\n /**\r\n * The default crosshair visibility.\r\n *\r\n * @since 1.0.5\r\n */\r\n public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false;\r\n\r\n /**\r\n * The default crosshair stroke.\r\n *\r\n * @since 1.0.5\r\n */\r\n public static final Stroke DEFAULT_CROSSHAIR_STROKE\r\n = DEFAULT_GRIDLINE_STROKE;\r\n\r\n /**\r\n * The default crosshair paint.\r\n *\r\n * @since 1.0.5\r\n */\r\n public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.blue;\r\n\r\n /** The resourceBundle for the localization. */\r\n protected static ResourceBundle localizationResources\r\n = ResourceBundleWrapper.getBundle(\r\n \"org.jfree.chart.plot.LocalizationBundle\");\r\n\r\n /** The plot orientation. */\r\n private PlotOrientation orientation;\r\n\r\n /** The offset between the data area and the axes. */\r\n private RectangleInsets axisOffset;\r\n\r\n /** Storage for the domain axes. */\r\n private Map<Integer, CategoryAxis> domainAxes;\r\n\r\n /** Storage for the domain axis locations. */\r\n private Map<Integer, AxisLocation> domainAxisLocations;\r\n\r\n /**\r\n * A flag that controls whether or not the shared domain axis is drawn\r\n * (only relevant when the plot is being used as a subplot).\r\n */\r\n private boolean drawSharedDomainAxis;\r\n\r\n /** Storage for the range axes. */\r\n private Map<Integer, ValueAxis> rangeAxes;\r\n\r\n /** Storage for the range axis locations. */\r\n private Map<Integer, AxisLocation> rangeAxisLocations;\r\n\r\n /** Storage for the datasets. */\r\n private Map<Integer, CategoryDataset> datasets;\r\n\r\n /** Storage for keys that map datasets to domain axes. */\r\n private TreeMap datasetToDomainAxesMap;\r\n\r\n /** Storage for keys that map datasets to range axes. */\r\n private TreeMap datasetToRangeAxesMap;\r\n\r\n /** Storage for the renderers. */\r\n private Map<Integer, CategoryItemRenderer> renderers;\r\n\r\n /** The dataset rendering order. */\r\n private DatasetRenderingOrder renderingOrder\r\n = DatasetRenderingOrder.REVERSE;\r\n\r\n /**\r\n * Controls the order in which the columns are traversed when rendering the\r\n * data items.\r\n */\r\n private SortOrder columnRenderingOrder = SortOrder.ASCENDING;\r\n\r\n /**\r\n * Controls the order in which the rows are traversed when rendering the\r\n * data items.\r\n */\r\n private SortOrder rowRenderingOrder = SortOrder.ASCENDING;\r\n\r\n /**\r\n * A flag that controls whether the grid-lines for the domain axis are\r\n * visible.\r\n */\r\n private boolean domainGridlinesVisible;\r\n\r\n /** The position of the domain gridlines relative to the category. */\r\n private CategoryAnchor domainGridlinePosition;\r\n\r\n /** The stroke used to draw the domain grid-lines. */\r\n private transient Stroke domainGridlineStroke;\r\n\r\n /** The paint used to draw the domain grid-lines. */\r\n private transient Paint domainGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not the zero baseline against the range\r\n * axis is visible.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean rangeZeroBaselineVisible;\r\n\r\n /**\r\n * The stroke used for the zero baseline against the range axis.\r\n *\r\n * @since 1.0.13\r\n */\r\n private transient Stroke rangeZeroBaselineStroke;\r\n\r\n /**\r\n * The paint used for the zero baseline against the range axis.\r\n *\r\n * @since 1.0.13\r\n */\r\n private transient Paint rangeZeroBaselinePaint;\r\n\r\n /**\r\n * A flag that controls whether the grid-lines for the range axis are\r\n * visible.\r\n */\r\n private boolean rangeGridlinesVisible;\r\n\r\n /** The stroke used to draw the range axis grid-lines. */\r\n private transient Stroke rangeGridlineStroke;\r\n\r\n /** The paint used to draw the range axis grid-lines. */\r\n private transient Paint rangeGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not gridlines are shown for the minor\r\n * tick values on the primary range axis.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean rangeMinorGridlinesVisible;\r\n\r\n /**\r\n * The stroke used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.13\r\n */\r\n private transient Stroke rangeMinorGridlineStroke;\r\n\r\n /**\r\n * The paint used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.13\r\n */\r\n private transient Paint rangeMinorGridlinePaint;\r\n\r\n /** The anchor value. */\r\n private double anchorValue;\r\n\r\n /**\r\n * The index for the dataset that the crosshairs are linked to (this\r\n * determines which axes the crosshairs are plotted against).\r\n *\r\n * @since 1.0.11\r\n */\r\n private int crosshairDatasetIndex;\r\n\r\n /**\r\n * A flag that controls the visibility of the domain crosshair.\r\n *\r\n * @since 1.0.11\r\n */\r\n private boolean domainCrosshairVisible;\r\n\r\n /**\r\n * The row key for the crosshair point.\r\n *\r\n * @since 1.0.11\r\n */\r\n private Comparable domainCrosshairRowKey;\r\n\r\n /**\r\n * The column key for the crosshair point.\r\n *\r\n * @since 1.0.11\r\n */\r\n private Comparable domainCrosshairColumnKey;\r\n\r\n /**\r\n * The stroke used to draw the domain crosshair if it is visible.\r\n *\r\n * @since 1.0.11\r\n */\r\n private transient Stroke domainCrosshairStroke;\r\n\r\n /**\r\n * The paint used to draw the domain crosshair if it is visible.\r\n *\r\n * @since 1.0.11\r\n */\r\n private transient Paint domainCrosshairPaint;\r\n\r\n /** A flag that controls whether or not a range crosshair is drawn. */\r\n private boolean rangeCrosshairVisible;\r\n\r\n /** The range crosshair value. */\r\n private double rangeCrosshairValue;\r\n\r\n /** The pen/brush used to draw the crosshair (if any). */\r\n private transient Stroke rangeCrosshairStroke;\r\n\r\n /** The color used to draw the crosshair (if any). */\r\n private transient Paint rangeCrosshairPaint;\r\n\r\n /**\r\n * A flag that controls whether or not the crosshair locks onto actual\r\n * data points.\r\n */\r\n private boolean rangeCrosshairLockedOnData = true;\r\n\r\n /** A map containing lists of markers for the domain axes. */\r\n private Map foregroundDomainMarkers;\r\n\r\n /** A map containing lists of markers for the domain axes. */\r\n private Map backgroundDomainMarkers;\r\n\r\n /** A map containing lists of markers for the range axes. */\r\n private Map foregroundRangeMarkers;\r\n\r\n /** A map containing lists of markers for the range axes. */\r\n private Map backgroundRangeMarkers;\r\n\r\n /**\r\n * A (possibly empty) list of annotations for the plot. The list should\r\n * be initialised in the constructor and never allowed to be\r\n * <code>null</code>.\r\n */\r\n private List annotations;\r\n\r\n /**\r\n * The weight for the plot (only relevant when the plot is used as a subplot\r\n * within a combined plot).\r\n */\r\n private int weight;\r\n\r\n /** The fixed space for the domain axis. */\r\n private AxisSpace fixedDomainAxisSpace;\r\n\r\n /** The fixed space for the range axis. */\r\n private AxisSpace fixedRangeAxisSpace;\r\n\r\n /**\r\n * An optional collection of legend items that can be returned by the\r\n * getLegendItems() method.\r\n */\r\n private LegendItemCollection fixedLegendItems;\r\n\r\n /**\r\n * A flag that controls whether or not panning is enabled for the\r\n * range axis/axes.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean rangePannable;\r\n\r\n /**\r\n * The shadow generator for the plot (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n private ShadowGenerator shadowGenerator;\r\n\r\n /**\r\n * Default constructor.\r\n */\r\n public CategoryPlot() {\r\n this(null, null, null, null);\r\n }\r\n\r\n /**\r\n * Creates a new plot.\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n * @param domainAxis the domain axis (<code>null</code> permitted).\r\n * @param rangeAxis the range axis (<code>null</code> permitted).\r\n * @param renderer the item renderer (<code>null</code> permitted).\r\n *\r\n */\r\n public CategoryPlot(CategoryDataset dataset, CategoryAxis domainAxis,\r\n ValueAxis rangeAxis, CategoryItemRenderer renderer) {\r\n\r\n super();\r\n\r\n this.orientation = PlotOrientation.VERTICAL;\r\n\r\n // allocate storage for dataset, axes and renderers\r\n this.domainAxes = new HashMap<Integer, CategoryAxis>();\r\n this.domainAxisLocations = new HashMap<Integer, AxisLocation>();\r\n this.rangeAxes = new HashMap<Integer, ValueAxis>();\r\n this.rangeAxisLocations = new HashMap<Integer, AxisLocation>();\r\n\r\n this.datasetToDomainAxesMap = new TreeMap();\r\n this.datasetToRangeAxesMap = new TreeMap();\r\n\r\n this.renderers = new HashMap<Integer, CategoryItemRenderer>();\r\n\r\n this.datasets = new HashMap<Integer, CategoryDataset>();\r\n this.datasets.put(0, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n\r\n this.axisOffset = RectangleInsets.ZERO_INSETS;\r\n this.domainAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT);\r\n this.rangeAxisLocations.put(0, AxisLocation.TOP_OR_LEFT);\r\n\r\n this.renderers.put(0, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n\r\n this.domainAxes.put(0, domainAxis);\r\n mapDatasetToDomainAxis(0, 0);\r\n if (domainAxis != null) {\r\n domainAxis.setPlot(this);\r\n domainAxis.addChangeListener(this);\r\n }\r\n this.drawSharedDomainAxis = false;\r\n\r\n this.rangeAxes.put(0, rangeAxis);\r\n mapDatasetToRangeAxis(0, 0);\r\n if (rangeAxis != null) {\r\n rangeAxis.setPlot(this);\r\n rangeAxis.addChangeListener(this);\r\n }\r\n\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n\r\n this.domainGridlinesVisible = DEFAULT_DOMAIN_GRIDLINES_VISIBLE;\r\n this.domainGridlinePosition = CategoryAnchor.MIDDLE;\r\n this.domainGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.domainGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.rangeZeroBaselineVisible = false;\r\n this.rangeZeroBaselinePaint = Color.black;\r\n this.rangeZeroBaselineStroke = new BasicStroke(0.5f);\r\n\r\n this.rangeGridlinesVisible = DEFAULT_RANGE_GRIDLINES_VISIBLE;\r\n this.rangeGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.rangeMinorGridlinesVisible = false;\r\n this.rangeMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeMinorGridlinePaint = Color.white;\r\n\r\n this.foregroundDomainMarkers = new HashMap();\r\n this.backgroundDomainMarkers = new HashMap();\r\n this.foregroundRangeMarkers = new HashMap();\r\n this.backgroundRangeMarkers = new HashMap();\r\n\r\n this.anchorValue = 0.0;\r\n\r\n this.domainCrosshairVisible = false;\r\n this.domainCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.domainCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n\r\n this.rangeCrosshairVisible = DEFAULT_CROSSHAIR_VISIBLE;\r\n this.rangeCrosshairValue = 0.0;\r\n this.rangeCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.rangeCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n\r\n this.annotations = new java.util.ArrayList();\r\n\r\n this.rangePannable = false;\r\n this.shadowGenerator = null;\r\n }\r\n\r\n /**\r\n * Returns a string describing the type of plot.\r\n *\r\n * @return The type.\r\n */\r\n @Override\r\n public String getPlotType() {\r\n return localizationResources.getString(\"Category_Plot\");\r\n }\r\n\r\n /**\r\n * Returns the orientation of the plot.\r\n *\r\n * @return The orientation of the plot (never <code>null</code>).\r\n *\r\n * @see #setOrientation(PlotOrientation)\r\n */\r\n @Override\r\n public PlotOrientation getOrientation() {\r\n return this.orientation;\r\n }\r\n\r\n /**\r\n * Sets the orientation for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param orientation the orientation (<code>null</code> not permitted).\r\n *\r\n * @see #getOrientation()\r\n */\r\n public void setOrientation(PlotOrientation orientation) {\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n this.orientation = orientation;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the axis offset.\r\n *\r\n * @return The axis offset (never <code>null</code>).\r\n *\r\n * @see #setAxisOffset(RectangleInsets)\r\n */\r\n public RectangleInsets getAxisOffset() {\r\n return this.axisOffset;\r\n }\r\n\r\n /**\r\n * Sets the axis offsets (gap between the data area and the axes) and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param offset the offset (<code>null</code> not permitted).\r\n *\r\n * @see #getAxisOffset()\r\n */\r\n public void setAxisOffset(RectangleInsets offset) {\r\n ParamChecks.nullNotPermitted(offset, \"offset\");\r\n this.axisOffset = offset;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the domain axis for the plot. If the domain axis for this plot\r\n * is <code>null</code>, then the method will return the parent plot's\r\n * domain axis (if there is a parent plot).\r\n *\r\n * @return The domain axis (<code>null</code> permitted).\r\n *\r\n * @see #setDomainAxis(CategoryAxis)\r\n */\r\n public CategoryAxis getDomainAxis() {\r\n return getDomainAxis(0);\r\n }\r\n\r\n /**\r\n * Returns a domain axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The axis (<code>null</code> possible).\r\n *\r\n * @see #setDomainAxis(int, CategoryAxis)\r\n */\r\n public CategoryAxis getDomainAxis(int index) {\r\n CategoryAxis result = (CategoryAxis) this.domainAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof CategoryPlot) {\r\n CategoryPlot cp = (CategoryPlot) parent;\r\n result = cp.getDomainAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the domain axis for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis()\r\n */\r\n public void setDomainAxis(CategoryAxis axis) {\r\n setDomainAxis(0, axis);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis(int)\r\n */\r\n public void setDomainAxis(int index, CategoryAxis axis) {\r\n setDomainAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n */\r\n public void setDomainAxis(int index, CategoryAxis axis, boolean notify) {\r\n CategoryAxis existing = (CategoryAxis) this.domainAxes.get(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.domainAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the domain axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setRangeAxes(ValueAxis[])\r\n */\r\n public void setDomainAxes(CategoryAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setDomainAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified axis, or <code>-1</code> if the axis\r\n * is not assigned to the plot.\r\n *\r\n * @param axis the axis (<code>null</code> not permitted).\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getDomainAxis(int)\r\n * @see #getRangeAxisIndex(ValueAxis)\r\n *\r\n * @since 1.0.3\r\n */\r\n public int getDomainAxisIndex(CategoryAxis axis) {\r\n ParamChecks.nullNotPermitted(axis, \"axis\");\r\n for (Entry<Integer, CategoryAxis> entry : this.domainAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the domain axis location for the primary domain axis.\r\n *\r\n * @return The location (never <code>null</code>).\r\n *\r\n * @see #getRangeAxisLocation()\r\n */\r\n public AxisLocation getDomainAxisLocation() {\r\n return getDomainAxisLocation(0);\r\n }\r\n\r\n /**\r\n * Returns the location for a domain axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The location.\r\n *\r\n * @see #setDomainAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getDomainAxisLocation(int index) {\r\n AxisLocation result = this.domainAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getDomainAxisLocation(0));\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location of the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param location the axis location (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainAxisLocation()\r\n * @see #setDomainAxisLocation(int, AxisLocation)\r\n */\r\n public void setDomainAxisLocation(AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the axis location (<code>null</code> not permitted).\r\n * @param notify a flag that controls whether listeners are notified.\r\n */\r\n public void setDomainAxisLocation(AxisLocation location, boolean notify) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Sets the location for a domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location.\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n * @see #setRangeAxisLocation(int, AxisLocation)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location for a domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location.\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n * @see #setRangeAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.domainAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the domain axis edge. This is derived from the axis location\r\n * and the plot orientation.\r\n *\r\n * @return The edge (never <code>null</code>).\r\n */\r\n public RectangleEdge getDomainAxisEdge() {\r\n return getDomainAxisEdge(0);\r\n }\r\n\r\n /**\r\n * Returns the edge for a domain axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge (never <code>null</code>).\r\n */\r\n public RectangleEdge getDomainAxisEdge(int index) {\r\n RectangleEdge result;\r\n AxisLocation location = getDomainAxisLocation(index);\r\n if (location != null) {\r\n result = Plot.resolveDomainAxisLocation(location, this.orientation);\r\n } else {\r\n result = RectangleEdge.opposite(getDomainAxisEdge(0));\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the number of domain axes.\r\n *\r\n * @return The axis count.\r\n */\r\n public int getDomainAxisCount() {\r\n return this.domainAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the domain axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n */\r\n public void clearDomainAxes() {\r\n for (CategoryAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n xAxis.removeChangeListener(this);\r\n }\r\n }\r\n this.domainAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the domain axes.\r\n */\r\n public void configureDomainAxes() {\r\n for (CategoryAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n xAxis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range axis for the plot. If the range axis for this plot is\r\n * null, then the method will return the parent plot's range axis (if there\r\n * is a parent plot).\r\n *\r\n * @return The range axis (possibly <code>null</code>).\r\n */\r\n public ValueAxis getRangeAxis() {\r\n return getRangeAxis(0);\r\n }\r\n\r\n /**\r\n * Returns a range axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The axis (<code>null</code> possible).\r\n */\r\n public ValueAxis getRangeAxis(int index) {\r\n ValueAxis result = this.rangeAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof CategoryPlot) {\r\n CategoryPlot cp = (CategoryPlot) parent;\r\n result = cp.getRangeAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the range axis for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param axis the axis (<code>null</code> permitted).\r\n */\r\n public void setRangeAxis(ValueAxis axis) {\r\n setRangeAxis(0, axis);\r\n }\r\n\r\n /**\r\n * Sets a range axis and sends a {@link PlotChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis.\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis) {\r\n setRangeAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a range axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis.\r\n * @param notify notify listeners?\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis, boolean notify) {\r\n ValueAxis existing = this.rangeAxes.get(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.rangeAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the range axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setDomainAxes(CategoryAxis[])\r\n */\r\n public void setRangeAxes(ValueAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setRangeAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified axis, or <code>-1</code> if the axis\r\n * is not assigned to the plot.\r\n *\r\n * @param axis the axis (<code>null</code> not permitted).\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getRangeAxis(int)\r\n * @see #getDomainAxisIndex(CategoryAxis)\r\n *\r\n * @since 1.0.7\r\n */\r\n public int getRangeAxisIndex(ValueAxis axis) {\r\n ParamChecks.nullNotPermitted(axis, \"axis\");\r\n int result = findRangeAxisIndex(axis);\r\n if (result < 0) { // try the parent plot\r\n Plot parent = getParent();\r\n if (parent instanceof CategoryPlot) {\r\n CategoryPlot p = (CategoryPlot) parent;\r\n result = p.getRangeAxisIndex(axis);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n private int findRangeAxisIndex(ValueAxis axis) {\r\n for (Entry<Integer, ValueAxis> entry : this.rangeAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n \r\n /**\r\n * Returns the range axis location.\r\n *\r\n * @return The location (never <code>null</code>).\r\n */\r\n public AxisLocation getRangeAxisLocation() {\r\n return getRangeAxisLocation(0);\r\n }\r\n\r\n /**\r\n * Returns the location for a range axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The location.\r\n *\r\n * @see #setRangeAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getRangeAxisLocation(int index) {\r\n AxisLocation result = this.rangeAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getRangeAxisLocation(0));\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location of the range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n *\r\n * @see #setRangeAxisLocation(AxisLocation, boolean)\r\n * @see #setDomainAxisLocation(AxisLocation)\r\n */\r\n public void setRangeAxisLocation(AxisLocation location) {\r\n // defer argument checking...\r\n setRangeAxisLocation(location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the range axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #setDomainAxisLocation(AxisLocation, boolean)\r\n */\r\n public void setRangeAxisLocation(AxisLocation location, boolean notify) {\r\n setRangeAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Sets the location for a range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location.\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #setRangeAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location) {\r\n setRangeAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location for a range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #setDomainAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.rangeAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the edge where the primary range axis is located.\r\n *\r\n * @return The edge (never <code>null</code>).\r\n */\r\n public RectangleEdge getRangeAxisEdge() {\r\n return getRangeAxisEdge(0);\r\n }\r\n\r\n /**\r\n * Returns the edge for a range axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge.\r\n */\r\n public RectangleEdge getRangeAxisEdge(int index) {\r\n AxisLocation location = getRangeAxisLocation(index);\r\n return Plot.resolveRangeAxisLocation(location, this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the number of range axes.\r\n *\r\n * @return The axis count.\r\n */\r\n public int getRangeAxisCount() {\r\n return this.rangeAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the range axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n */\r\n public void clearRangeAxes() {\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.removeChangeListener(this);\r\n }\r\n }\r\n this.rangeAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the range axes.\r\n */\r\n public void configureRangeAxes() {\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the primary dataset for the plot.\r\n *\r\n * @return The primary dataset (possibly <code>null</code>).\r\n *\r\n * @see #setDataset(CategoryDataset)\r\n */\r\n public CategoryDataset getDataset() {\r\n return getDataset(0);\r\n }\r\n\r\n /**\r\n * Returns the dataset with the given index, or {@code null} if there is\r\n * no dataset.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The dataset (possibly {@code null}).\r\n *\r\n * @see #setDataset(int, CategoryDataset)\r\n */\r\n public CategoryDataset getDataset(int index) {\r\n return this.datasets.get(index);\r\n }\r\n\r\n /**\r\n * Sets the dataset for the plot, replacing the existing dataset, if there\r\n * is one. This method also calls the\r\n * {@link #datasetChanged(DatasetChangeEvent)} method, which adjusts the\r\n * axis ranges if necessary and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n *\r\n * @see #getDataset()\r\n */\r\n public void setDataset(CategoryDataset dataset) {\r\n setDataset(0, dataset);\r\n }\r\n\r\n /**\r\n * Sets a dataset for the plot and sends a change notification to all\r\n * registered listeners.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n * @param dataset the dataset ({@code null} permitted).\r\n *\r\n * @see #getDataset(int)\r\n */\r\n public void setDataset(int index, CategoryDataset dataset) {\r\n CategoryDataset existing = (CategoryDataset) this.datasets.get(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.datasets.put(index, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n // send a dataset change event to self...\r\n DatasetChangeEvent event = new DatasetChangeEvent(this, dataset);\r\n datasetChanged(event);\r\n }\r\n\r\n /**\r\n * Returns the number of datasets.\r\n *\r\n * @return The number of datasets.\r\n *\r\n * @since 1.0.2\r\n */\r\n public int getDatasetCount() {\r\n return this.datasets.size();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified dataset, or <code>-1</code> if the\r\n * dataset does not belong to the plot.\r\n *\r\n * @param dataset the dataset ({@code null} not permitted).\r\n *\r\n * @return The index.\r\n *\r\n * @since 1.0.11\r\n */\r\n public int indexOf(CategoryDataset dataset) {\r\n for (Entry<Integer, CategoryDataset> entry: this.datasets.entrySet()) {\r\n if (entry.getValue() == dataset) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular domain axis.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index (zero-based).\r\n *\r\n * @see #getDomainAxisForDataset(int)\r\n */\r\n public void mapDatasetToDomainAxis(int index, int axisIndex) {\r\n List<Integer> axisIndices = new java.util.ArrayList<Integer>(1);\r\n axisIndices.add(axisIndex);\r\n mapDatasetToDomainAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToDomainAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n this.datasetToDomainAxesMap.put(index, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * This method is used to perform argument checking on the list of\r\n * axis indices passed to mapDatasetToDomainAxes() and\r\n * mapDatasetToRangeAxes().\r\n *\r\n * @param indices the list of indices (<code>null</code> permitted).\r\n */\r\n private void checkAxisIndices(List indices) {\r\n // axisIndices can be:\r\n // 1. null;\r\n // 2. non-empty, containing only Integer objects that are unique.\r\n if (indices == null) {\r\n return; // OK\r\n }\r\n int count = indices.size();\r\n if (count == 0) {\r\n throw new IllegalArgumentException(\"Empty list not permitted.\");\r\n }\r\n HashSet set = new HashSet();\r\n for (int i = 0; i < count; i++) {\r\n Object item = indices.get(i);\r\n if (!(item instanceof Integer)) {\r\n throw new IllegalArgumentException(\r\n \"Indices must be Integer instances.\");\r\n }\r\n if (set.contains(item)) {\r\n throw new IllegalArgumentException(\"Indices must be unique.\");\r\n }\r\n set.add(item);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the domain axis for a dataset. You can change the axis for a\r\n * dataset using the {@link #mapDatasetToDomainAxis(int, int)} method.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The domain axis.\r\n *\r\n * @see #mapDatasetToDomainAxis(int, int)\r\n */\r\n public CategoryAxis getDomainAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n CategoryAxis axis;\r\n List axisIndices = (List) this.datasetToDomainAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n axis = getDomainAxis(axisIndex.intValue());\r\n } else {\r\n axis = getDomainAxis(0);\r\n }\r\n return axis;\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular range axis.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index (zero-based).\r\n *\r\n * @see #getRangeAxisForDataset(int)\r\n */\r\n public void mapDatasetToRangeAxis(int index, int axisIndex) {\r\n List axisIndices = new java.util.ArrayList(1);\r\n axisIndices.add(new Integer(axisIndex));\r\n mapDatasetToRangeAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToRangeAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n this.datasetToRangeAxesMap.put(index, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * Returns the range axis for a dataset. You can change the axis for a\r\n * dataset using the {@link #mapDatasetToRangeAxis(int, int)} method.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The range axis.\r\n *\r\n * @see #mapDatasetToRangeAxis(int, int)\r\n */\r\n public ValueAxis getRangeAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n ValueAxis axis;\r\n List axisIndices = (List) this.datasetToRangeAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n axis = getRangeAxis(axisIndex.intValue());\r\n } else {\r\n axis = getRangeAxis(0);\r\n }\r\n return axis;\r\n }\r\n\r\n /**\r\n * Returns the number of renderer slots for this plot.\r\n *\r\n * @return The number of renderer slots.\r\n *\r\n * @since 1.0.11\r\n */\r\n public int getRendererCount() {\r\n return this.renderers.size();\r\n }\r\n\r\n /**\r\n * Returns a reference to the renderer for the plot.\r\n *\r\n * @return The renderer.\r\n *\r\n * @see #setRenderer(CategoryItemRenderer)\r\n */\r\n public CategoryItemRenderer getRenderer() {\r\n return getRenderer(0);\r\n }\r\n\r\n /**\r\n * Returns the renderer at the given index.\r\n *\r\n * @param index the renderer index.\r\n *\r\n * @return The renderer (possibly {@code null}).\r\n *\r\n * @see #setRenderer(int, CategoryItemRenderer)\r\n */\r\n public CategoryItemRenderer getRenderer(int index) {\r\n CategoryItemRenderer renderer = this.renderers.get(index);\r\n if (renderer == null) {\r\n return this.renderers.get(0);\r\n }\r\n return renderer;\r\n }\r\n\r\n /**\r\n * Sets the renderer at index 0 (sometimes referred to as the \"primary\"\r\n * renderer) and sends a change event to all registered listeners.\r\n *\r\n * @param renderer the renderer (<code>null</code> permitted.\r\n *\r\n * @see #getRenderer()\r\n */\r\n public void setRenderer(CategoryItemRenderer renderer) {\r\n setRenderer(0, renderer, true);\r\n }\r\n\r\n /**\r\n * Sets the renderer at index 0 (sometimes referred to as the \"primary\"\r\n * renderer) and, if requested, sends a change event to all registered \r\n * listeners.\r\n * <p>\r\n * You can set the renderer to <code>null</code>, but this is not\r\n * recommended because:\r\n * <ul>\r\n * <li>no data will be displayed;</li>\r\n * <li>the plot background will not be painted;</li>\r\n * </ul>\r\n *\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRenderer()\r\n */\r\n public void setRenderer(CategoryItemRenderer renderer, boolean notify) {\r\n setRenderer(0, renderer, notify);\r\n }\r\n\r\n /**\r\n * Sets the renderer to use for the dataset with the specified index and\r\n * sends a change event to all registered listeners. Note that each\r\n * dataset should have its own renderer, you should not use one renderer\r\n * for multiple datasets.\r\n *\r\n * @param index the index.\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n *\r\n * @see #getRenderer(int)\r\n * @see #setRenderer(int, CategoryItemRenderer, boolean)\r\n */\r\n public void setRenderer(int index, CategoryItemRenderer renderer) {\r\n setRenderer(index, renderer, true);\r\n }\r\n\r\n /**\r\n * Sets the renderer to use for the dataset with the specified index and,\r\n * if requested, sends a change event to all registered listeners. Note \r\n * that each dataset should have its own renderer, you should not use one \r\n * renderer for multiple datasets.\r\n *\r\n * @param index the index.\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRenderer(int)\r\n */\r\n public void setRenderer(int index, CategoryItemRenderer renderer,\r\n boolean notify) {\r\n CategoryItemRenderer existing = this.renderers.get(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.renderers.put(index, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the renderers for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param renderers the renderers.\r\n */\r\n public void setRenderers(CategoryItemRenderer[] renderers) {\r\n for (int i = 0; i < renderers.length; i++) {\r\n setRenderer(i, renderers[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the renderer for the specified dataset. If the dataset doesn't\r\n * belong to the plot, this method will return <code>null</code>.\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n *\r\n * @return The renderer (possibly <code>null</code>).\r\n */\r\n public CategoryItemRenderer getRendererForDataset(CategoryDataset dataset) {\r\n int datasetIndex = indexOf(dataset);\r\n if (datasetIndex < 0) {\r\n return null;\r\n } \r\n CategoryItemRenderer renderer = this.renderers.get(datasetIndex);\r\n if (renderer == null) {\r\n return getRenderer();\r\n }\r\n return renderer;\r\n }\r\n\r\n /**\r\n * Returns the index of the specified renderer, or <code>-1</code> if the\r\n * renderer is not assigned to this plot.\r\n *\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n *\r\n * @return The renderer index.\r\n */\r\n public int getIndexOf(CategoryItemRenderer renderer) {\r\n for (Entry<Integer, CategoryItemRenderer> entry \r\n : this.renderers.entrySet()) {\r\n if (entry.getValue() == renderer) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the dataset rendering order.\r\n *\r\n * @return The order (never <code>null</code>).\r\n *\r\n * @see #setDatasetRenderingOrder(DatasetRenderingOrder)\r\n */\r\n public DatasetRenderingOrder getDatasetRenderingOrder() {\r\n return this.renderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the rendering order and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. By default, the plot renders the primary dataset\r\n * last (so that the primary dataset overlays the secondary datasets). You\r\n * can reverse this if you want to.\r\n *\r\n * @param order the rendering order (<code>null</code> not permitted).\r\n *\r\n * @see #getDatasetRenderingOrder()\r\n */\r\n public void setDatasetRenderingOrder(DatasetRenderingOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.renderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the order in which the columns are rendered. The default value\r\n * is <code>SortOrder.ASCENDING</code>.\r\n *\r\n * @return The column rendering order (never <code>null</code>).\r\n *\r\n * @see #setColumnRenderingOrder(SortOrder)\r\n */\r\n public SortOrder getColumnRenderingOrder() {\r\n return this.columnRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the column order in which the items in each dataset should be\r\n * rendered and sends a {@link PlotChangeEvent} to all registered\r\n * listeners. Note that this affects the order in which items are drawn,\r\n * NOT their position in the chart.\r\n *\r\n * @param order the order (<code>null</code> not permitted).\r\n *\r\n * @see #getColumnRenderingOrder()\r\n * @see #setRowRenderingOrder(SortOrder)\r\n */\r\n public void setColumnRenderingOrder(SortOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.columnRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the order in which the rows should be rendered. The default\r\n * value is <code>SortOrder.ASCENDING</code>.\r\n *\r\n * @return The order (never <code>null</code>).\r\n *\r\n * @see #setRowRenderingOrder(SortOrder)\r\n */\r\n public SortOrder getRowRenderingOrder() {\r\n return this.rowRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the row order in which the items in each dataset should be\r\n * rendered and sends a {@link PlotChangeEvent} to all registered\r\n * listeners. Note that this affects the order in which items are drawn,\r\n * NOT their position in the chart.\r\n *\r\n * @param order the order (<code>null</code> not permitted).\r\n *\r\n * @see #getRowRenderingOrder()\r\n * @see #setColumnRenderingOrder(SortOrder)\r\n */\r\n public void setRowRenderingOrder(SortOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.rowRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether the domain grid-lines are visible.\r\n *\r\n * @return The <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setDomainGridlinesVisible(boolean)\r\n */\r\n public boolean isDomainGridlinesVisible() {\r\n return this.domainGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not grid-lines are drawn against\r\n * the domain axis.\r\n * <p>\r\n * If the flag value changes, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isDomainGridlinesVisible()\r\n */\r\n public void setDomainGridlinesVisible(boolean visible) {\r\n if (this.domainGridlinesVisible != visible) {\r\n this.domainGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the position used for the domain gridlines.\r\n *\r\n * @return The gridline position (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlinePosition(CategoryAnchor)\r\n */\r\n public CategoryAnchor getDomainGridlinePosition() {\r\n return this.domainGridlinePosition;\r\n }\r\n\r\n /**\r\n * Sets the position used for the domain gridlines and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param position the position (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainGridlinePosition()\r\n */\r\n public void setDomainGridlinePosition(CategoryAnchor position) {\r\n ParamChecks.nullNotPermitted(position, \"position\");\r\n this.domainGridlinePosition = position;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw grid-lines against the domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlineStroke(Stroke)\r\n */\r\n public Stroke getDomainGridlineStroke() {\r\n return this.domainGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw grid-lines against the domain axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainGridlineStroke()\r\n */\r\n public void setDomainGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw grid-lines against the domain axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlinePaint(Paint)\r\n */\r\n public Paint getDomainGridlinePaint() {\r\n return this.domainGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the grid-lines (if any) against the domain\r\n * axis and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainGridlinePaint()\r\n */\r\n public void setDomainGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a zero baseline is\r\n * displayed for the range axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n *\r\n * @since 1.0.13\r\n */\r\n public boolean isRangeZeroBaselineVisible() {\r\n return this.rangeZeroBaselineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the zero baseline is\r\n * displayed for the range axis, and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isRangeZeroBaselineVisible()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangeZeroBaselineVisible(boolean visible) {\r\n this.rangeZeroBaselineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used for the zero baseline against the range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselineStroke(Stroke)\r\n *\r\n * @since 1.0.13\r\n */\r\n public Stroke getRangeZeroBaselineStroke() {\r\n return this.rangeZeroBaselineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the zero baseline for the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselineStroke()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangeZeroBaselineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeZeroBaselineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the zero baseline (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselinePaint(Paint)\r\n *\r\n * @since 1.0.13\r\n */\r\n public Paint getRangeZeroBaselinePaint() {\r\n return this.rangeZeroBaselinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the zero baseline plotted against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselinePaint()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangeZeroBaselinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeZeroBaselinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether the range grid-lines are visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeGridlinesVisible(boolean)\r\n */\r\n public boolean isRangeGridlinesVisible() {\r\n return this.rangeGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not grid-lines are drawn against\r\n * the range axis. If the flag changes value, a {@link PlotChangeEvent} is\r\n * sent to all registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeGridlinesVisible()\r\n */\r\n public void setRangeGridlinesVisible(boolean visible) {\r\n if (this.rangeGridlinesVisible != visible) {\r\n this.rangeGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the grid-lines against the range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlineStroke(Stroke)\r\n */\r\n public Stroke getRangeGridlineStroke() {\r\n return this.rangeGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the grid-lines against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlineStroke()\r\n */\r\n public void setRangeGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the grid-lines against the range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlinePaint(Paint)\r\n */\r\n public Paint getRangeGridlinePaint() {\r\n return this.rangeGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the grid lines against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlinePaint()\r\n */\r\n public void setRangeGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range axis minor grid is visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeMinorGridlinesVisible(boolean)\r\n *\r\n * @since 1.0.13\r\n */\r\n public boolean isRangeMinorGridlinesVisible() {\r\n return this.rangeMinorGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the range axis minor grid\r\n * lines are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeMinorGridlinesVisible()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangeMinorGridlinesVisible(boolean visible) {\r\n if (this.rangeMinorGridlinesVisible != visible) {\r\n this.rangeMinorGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlineStroke(Stroke)\r\n *\r\n * @since 1.0.13\r\n */\r\n public Stroke getRangeMinorGridlineStroke() {\r\n return this.rangeMinorGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the minor grid lines plotted against the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlineStroke()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangeMinorGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeMinorGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlinePaint(Paint)\r\n *\r\n * @since 1.0.13\r\n */\r\n public Paint getRangeMinorGridlinePaint() {\r\n return this.rangeMinorGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the minor grid lines plotted against the range axis\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlinePaint()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangeMinorGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeMinorGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the fixed legend items, if any.\r\n *\r\n * @return The legend items (possibly <code>null</code>).\r\n *\r\n * @see #setFixedLegendItems(LegendItemCollection)\r\n */\r\n public LegendItemCollection getFixedLegendItems() {\r\n return this.fixedLegendItems;\r\n }\r\n\r\n /**\r\n * Sets the fixed legend items for the plot. Leave this set to\r\n * <code>null</code> if you prefer the legend items to be created\r\n * automatically.\r\n *\r\n * @param items the legend items (<code>null</code> permitted).\r\n *\r\n * @see #getFixedLegendItems()\r\n */\r\n public void setFixedLegendItems(LegendItemCollection items) {\r\n this.fixedLegendItems = items;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the legend items for the plot. By default, this method creates\r\n * a legend item for each series in each of the datasets. You can change\r\n * this behaviour by overriding this method.\r\n *\r\n * @return The legend items.\r\n */\r\n @Override\r\n public LegendItemCollection getLegendItems() {\r\n if (this.fixedLegendItems != null) {\r\n return this.fixedLegendItems;\r\n }\r\n LegendItemCollection result = new LegendItemCollection();\r\n // get the legend items for the datasets...\r\n for (CategoryDataset dataset: this.datasets.values()) {\r\n if (dataset != null) {\r\n int datasetIndex = indexOf(dataset);\r\n CategoryItemRenderer renderer = getRenderer(datasetIndex);\r\n if (renderer != null) {\r\n result.addAll(renderer.getLegendItems());\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the plot by updating the anchor value.\r\n *\r\n * @param x x-coordinate of the click (in Java2D space).\r\n * @param y y-coordinate of the click (in Java2D space).\r\n * @param info information about the plot's dimensions.\r\n *\r\n */\r\n @Override\r\n public void handleClick(int x, int y, PlotRenderingInfo info) {\r\n\r\n Rectangle2D dataArea = info.getDataArea();\r\n if (dataArea.contains(x, y)) {\r\n // set the anchor value for the range axis...\r\n double java2D = 0.0;\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n java2D = x;\r\n } else if (this.orientation == PlotOrientation.VERTICAL) {\r\n java2D = y;\r\n }\r\n RectangleEdge edge = Plot.resolveRangeAxisLocation(\r\n getRangeAxisLocation(), this.orientation);\r\n double value = getRangeAxis().java2DToValue(\r\n java2D, info.getDataArea(), edge);\r\n setAnchorValue(value);\r\n setRangeCrosshairValue(value);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Zooms (in or out) on the plot's value axis.\r\n * <p>\r\n * If the value 0.0 is passed in as the zoom percent, the auto-range\r\n * calculation for the axis is restored (which sets the range to include\r\n * the minimum and maximum data values, thus displaying all the data).\r\n *\r\n * @param percent the zoom amount.\r\n */\r\n @Override\r\n public void zoom(double percent) {\r\n if (percent > 0.0) {\r\n double range = getRangeAxis().getRange().getLength();\r\n double scaledRange = range * percent;\r\n getRangeAxis().setRange(this.anchorValue - scaledRange / 2.0,\r\n this.anchorValue + scaledRange / 2.0);\r\n }\r\n else {\r\n getRangeAxis().setAutoRange(true);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a change to an {@link Annotation} added to\r\n * this plot.\r\n *\r\n * @param event information about the event (not used here).\r\n *\r\n * @since 1.0.14\r\n */\r\n @Override\r\n public void annotationChanged(AnnotationChangeEvent event) {\r\n if (getParent() != null) {\r\n getParent().annotationChanged(event);\r\n } else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a change to the plot's dataset.\r\n * <P>\r\n * The range axis bounds will be recalculated if necessary.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void datasetChanged(DatasetChangeEvent event) {\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.configure();\r\n }\r\n }\r\n if (getParent() != null) {\r\n getParent().datasetChanged(event);\r\n } else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n e.setType(ChartChangeEventType.DATASET_UPDATED);\r\n notifyListeners(e);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Receives notification of a renderer change event.\r\n *\r\n * @param event the event.\r\n */\r\n @Override\r\n public void rendererChanged(RendererChangeEvent event) {\r\n Plot parent = getParent();\r\n if (parent != null) {\r\n if (parent instanceof RendererChangeListener) {\r\n RendererChangeListener rcl = (RendererChangeListener) parent;\r\n rcl.rendererChanged(event);\r\n } else {\r\n // this should never happen with the existing code, but throw\r\n // an exception in case future changes make it possible...\r\n throw new RuntimeException(\r\n \"The renderer has changed and I don't know what to do!\");\r\n }\r\n } else {\r\n configureRangeAxes();\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Adds a marker for display (in the foreground) against the domain axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners. Typically a\r\n * marker will be drawn by the renderer as a line perpendicular to the\r\n * domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #removeDomainMarker(Marker)\r\n */\r\n public void addDomainMarker(CategoryMarker marker) {\r\n addDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for display against the domain axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. Typically a marker\r\n * will be drawn by the renderer as a line perpendicular to the domain\r\n * axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background) (<code>null</code>\r\n * not permitted).\r\n *\r\n * @see #removeDomainMarker(Marker, Layer)\r\n */\r\n public void addDomainMarker(CategoryMarker marker, Layer layer) {\r\n addDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Adds a marker for display by a particular renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to a domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (<code>null</code> not permitted).\r\n *\r\n * @see #removeDomainMarker(int, Marker, Layer)\r\n */\r\n public void addDomainMarker(int index, CategoryMarker marker, Layer layer) {\r\n addDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for display by a particular renderer and, if requested,\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to a domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n *\r\n * @see #removeDomainMarker(int, Marker, Layer, boolean)\r\n */\r\n public void addDomainMarker(int index, CategoryMarker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ParamChecks.nullNotPermitted(layer, \"layer\");\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n } else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Clears all the domain markers for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @see #clearRangeMarkers()\r\n */\r\n public void clearDomainMarkers() {\r\n if (this.backgroundDomainMarkers != null) {\r\n Set keys = this.backgroundDomainMarkers.keySet();\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Integer key = (Integer) iterator.next();\r\n clearDomainMarkers(key.intValue());\r\n }\r\n this.backgroundDomainMarkers.clear();\r\n }\r\n if (this.foregroundDomainMarkers != null) {\r\n Set keys = this.foregroundDomainMarkers.keySet();\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Integer key = (Integer) iterator.next();\r\n clearDomainMarkers(key.intValue());\r\n }\r\n this.foregroundDomainMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the list of domain markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of domain markers.\r\n */\r\n public Collection getDomainMarkers(Layer layer) {\r\n return getDomainMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns a collection of domain markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n */\r\n public Collection getDomainMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundDomainMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundDomainMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Clears all the domain markers for the specified renderer.\r\n *\r\n * @param index the renderer index.\r\n *\r\n * @see #clearRangeMarkers(int)\r\n */\r\n public void clearDomainMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundDomainMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundDomainMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker) {\r\n return removeDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker, Layer layer) {\r\n return removeDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer) {\r\n return removeDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and, if requested,\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ArrayList markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (ArrayList) this.foregroundDomainMarkers.get(new Integer(\r\n index));\r\n } else {\r\n markers = (ArrayList) this.backgroundDomainMarkers.get(new Integer(\r\n index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Adds a marker for display (in the foreground) against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners. Typically a\r\n * marker will be drawn by the renderer as a line perpendicular to the\r\n * range axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #removeRangeMarker(Marker)\r\n */\r\n public void addRangeMarker(Marker marker) {\r\n addRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for display against the range axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. Typically a marker\r\n * will be drawn by the renderer as a line perpendicular to the range axis,\r\n * however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background) (<code>null</code>\r\n * not permitted).\r\n *\r\n * @see #removeRangeMarker(Marker, Layer)\r\n */\r\n public void addRangeMarker(Marker marker, Layer layer) {\r\n addRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Adds a marker for display by a particular renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to a range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer.\r\n *\r\n * @see #removeRangeMarker(int, Marker, Layer)\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer) {\r\n addRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for display by a particular renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to a range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer.\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n *\r\n * @see #removeRangeMarker(int, Marker, Layer, boolean)\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n } else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Clears all the range markers for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @see #clearDomainMarkers()\r\n */\r\n public void clearRangeMarkers() {\r\n if (this.backgroundRangeMarkers != null) {\r\n Set keys = this.backgroundRangeMarkers.keySet();\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Integer key = (Integer) iterator.next();\r\n clearRangeMarkers(key.intValue());\r\n }\r\n this.backgroundRangeMarkers.clear();\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Set keys = this.foregroundRangeMarkers.keySet();\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Integer key = (Integer) iterator.next();\r\n clearRangeMarkers(key.intValue());\r\n }\r\n this.foregroundRangeMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the list of range markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of range markers.\r\n *\r\n * @see #getRangeMarkers(int, Layer)\r\n */\r\n public Collection getRangeMarkers(Layer layer) {\r\n return getRangeMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns a collection of range markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n */\r\n public Collection getRangeMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundRangeMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundRangeMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Clears all the range markers for the specified renderer.\r\n *\r\n * @param index the renderer index.\r\n *\r\n * @see #clearDomainMarkers(int)\r\n */\r\n public void clearRangeMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n *\r\n * @see #addRangeMarker(Marker)\r\n */\r\n public boolean removeRangeMarker(Marker marker) {\r\n return removeRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n *\r\n * @see #addRangeMarker(Marker, Layer)\r\n */\r\n public boolean removeRangeMarker(Marker marker, Layer layer) {\r\n return removeRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n *\r\n * @see #addRangeMarker(int, Marker, Layer)\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer) {\r\n return removeRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n *\r\n * @see #addRangeMarker(int, Marker, Layer, boolean)\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ArrayList markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (ArrayList) this.foregroundRangeMarkers.get(new Integer(\r\n index));\r\n } else {\r\n markers = (ArrayList) this.backgroundRangeMarkers.get(new Integer(\r\n index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the domain crosshair is\r\n * displayed by the plot.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #setDomainCrosshairVisible(boolean)\r\n */\r\n public boolean isDomainCrosshairVisible() {\r\n return this.domainCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the domain crosshair is\r\n * displayed by the plot, and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param flag the new flag value.\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #isDomainCrosshairVisible()\r\n * @see #setRangeCrosshairVisible(boolean)\r\n */\r\n public void setDomainCrosshairVisible(boolean flag) {\r\n if (this.domainCrosshairVisible != flag) {\r\n this.domainCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the row key for the domain crosshair.\r\n *\r\n * @return The row key.\r\n *\r\n * @since 1.0.11\r\n */\r\n public Comparable getDomainCrosshairRowKey() {\r\n return this.domainCrosshairRowKey;\r\n }\r\n\r\n /**\r\n * Sets the row key for the domain crosshair and sends a\r\n * {PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param key the key.\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setDomainCrosshairRowKey(Comparable key) {\r\n setDomainCrosshairRowKey(key, true);\r\n }\r\n\r\n /**\r\n * Sets the row key for the domain crosshair and, if requested, sends a\r\n * {PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param key the key.\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setDomainCrosshairRowKey(Comparable key, boolean notify) {\r\n this.domainCrosshairRowKey = key;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the column key for the domain crosshair.\r\n *\r\n * @return The column key.\r\n *\r\n * @since 1.0.11\r\n */\r\n public Comparable getDomainCrosshairColumnKey() {\r\n return this.domainCrosshairColumnKey;\r\n }\r\n\r\n /**\r\n * Sets the column key for the domain crosshair and sends\r\n * a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param key the key.\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setDomainCrosshairColumnKey(Comparable key) {\r\n setDomainCrosshairColumnKey(key, true);\r\n }\r\n\r\n /**\r\n * Sets the column key for the domain crosshair and, if requested, sends\r\n * a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param key the key.\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setDomainCrosshairColumnKey(Comparable key, boolean notify) {\r\n this.domainCrosshairColumnKey = key;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the dataset index for the crosshair.\r\n *\r\n * @return The dataset index.\r\n *\r\n * @since 1.0.11\r\n */\r\n public int getCrosshairDatasetIndex() {\r\n return this.crosshairDatasetIndex;\r\n }\r\n\r\n /**\r\n * Sets the dataset index for the crosshair and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the index.\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setCrosshairDatasetIndex(int index) {\r\n setCrosshairDatasetIndex(index, true);\r\n }\r\n\r\n /**\r\n * Sets the dataset index for the crosshair and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the index.\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setCrosshairDatasetIndex(int index, boolean notify) {\r\n this.crosshairDatasetIndex = index;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the domain crosshair.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #setDomainCrosshairPaint(Paint)\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public Paint getDomainCrosshairPaint() {\r\n return this.domainCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the domain crosshair.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public void setDomainCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the domain crosshair.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #setDomainCrosshairStroke(Stroke)\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public Stroke getDomainCrosshairStroke() {\r\n return this.domainCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the domain crosshair, and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.11\r\n *\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public void setDomainCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainCrosshairStroke = stroke;\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the range crosshair is visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairVisible(boolean)\r\n */\r\n public boolean isRangeCrosshairVisible() {\r\n return this.rangeCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair is visible.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isRangeCrosshairVisible()\r\n */\r\n public void setRangeCrosshairVisible(boolean flag) {\r\n if (this.rangeCrosshairVisible != flag) {\r\n this.rangeCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the crosshair should \"lock-on\"\r\n * to actual data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairLockedOnData(boolean)\r\n */\r\n public boolean isRangeCrosshairLockedOnData() {\r\n return this.rangeCrosshairLockedOnData;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair should\r\n * \"lock-on\" to actual data values, and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isRangeCrosshairLockedOnData()\r\n */\r\n public void setRangeCrosshairLockedOnData(boolean flag) {\r\n if (this.rangeCrosshairLockedOnData != flag) {\r\n this.rangeCrosshairLockedOnData = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range crosshair value.\r\n *\r\n * @return The value.\r\n *\r\n * @see #setRangeCrosshairValue(double)\r\n */\r\n public double getRangeCrosshairValue() {\r\n return this.rangeCrosshairValue;\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value and, if the crosshair is visible, sends\r\n * a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param value the new value.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value) {\r\n setRangeCrosshairValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners (but only if the\r\n * crosshair is visible).\r\n *\r\n * @param value the new value.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value, boolean notify) {\r\n this.rangeCrosshairValue = value;\r\n if (isRangeCrosshairVisible() && notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the pen-style (<code>Stroke</code>) used to draw the crosshair\r\n * (if visible).\r\n *\r\n * @return The crosshair stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairStroke(Stroke)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public Stroke getRangeCrosshairStroke() {\r\n return this.rangeCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the pen-style (<code>Stroke</code>) used to draw the range\r\n * crosshair (if visible), and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param stroke the new crosshair stroke (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public void setRangeCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeCrosshairStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used to draw the range crosshair.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairPaint(Paint)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public Paint getRangeCrosshairPaint() {\r\n return this.rangeCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the range crosshair (if visible) and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public void setRangeCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the list of annotations.\r\n *\r\n * @return The list of annotations (never <code>null</code>).\r\n *\r\n * @see #addAnnotation(CategoryAnnotation)\r\n * @see #clearAnnotations()\r\n */\r\n public List getAnnotations() {\r\n return this.annotations;\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @see #removeAnnotation(CategoryAnnotation)\r\n */\r\n public void addAnnotation(CategoryAnnotation annotation) {\r\n addAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addAnnotation(CategoryAnnotation annotation, boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n this.annotations.add(annotation);\r\n annotation.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @see #addAnnotation(CategoryAnnotation)\r\n */\r\n public boolean removeAnnotation(CategoryAnnotation annotation) {\r\n return removeAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeAnnotation(CategoryAnnotation annotation,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n boolean removed = this.annotations.remove(annotation);\r\n annotation.removeChangeListener(this);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Clears all the annotations and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n */\r\n public void clearAnnotations() {\r\n for (int i = 0; i < this.annotations.size(); i++) {\r\n CategoryAnnotation annotation\r\n = (CategoryAnnotation) this.annotations.get(i);\r\n annotation.removeChangeListener(this);\r\n }\r\n this.annotations.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the shadow generator for the plot, if any.\r\n *\r\n * @return The shadow generator (possibly <code>null</code>).\r\n *\r\n * @since 1.0.14\r\n */\r\n public ShadowGenerator getShadowGenerator() {\r\n return this.shadowGenerator;\r\n }\r\n\r\n /**\r\n * Sets the shadow generator for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setShadowGenerator(ShadowGenerator generator) {\r\n this.shadowGenerator = generator;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Calculates the space required for the domain axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateDomainAxisSpace(Graphics2D g2,\r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the domain axis...\r\n if (this.fixedDomainAxisSpace != null) {\r\n if (this.orientation.isHorizontal()) {\r\n space.ensureAtLeast(\r\n this.fixedDomainAxisSpace.getLeft(), RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n } else if (this.orientation.isVertical()) {\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n }\r\n }\r\n else {\r\n // reserve space for the primary domain axis...\r\n RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(\r\n getDomainAxisLocation(), this.orientation);\r\n if (this.drawSharedDomainAxis) {\r\n space = getDomainAxis().reserveSpace(g2, this, plotArea,\r\n domainEdge, space);\r\n }\r\n\r\n // reserve space for any domain axes...\r\n for (CategoryAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n int i = getDomainAxisIndex(xAxis);\r\n RectangleEdge edge = getDomainAxisEdge(i);\r\n space = xAxis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the space required for the range axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateRangeAxisSpace(Graphics2D g2,\r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the range axis...\r\n if (this.fixedRangeAxisSpace != null) {\r\n if (this.orientation.isHorizontal()) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n } else if (this.orientation == PlotOrientation.VERTICAL) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getLeft(),\r\n RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n }\r\n } else {\r\n // reserve space for the range axes (if any)...\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n int i = findRangeAxisIndex(yAxis);\r\n RectangleEdge edge = getRangeAxisEdge(i);\r\n space = yAxis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Trims a rectangle to integer coordinates.\r\n *\r\n * @param rect the incoming rectangle.\r\n *\r\n * @return A rectangle with integer coordinates.\r\n */\r\n private Rectangle integerise(Rectangle2D rect) {\r\n int x0 = (int) Math.ceil(rect.getMinX());\r\n int y0 = (int) Math.ceil(rect.getMinY());\r\n int x1 = (int) Math.floor(rect.getMaxX());\r\n int y1 = (int) Math.floor(rect.getMaxY());\r\n return new Rectangle(x0, y0, (x1 - x0), (y1 - y0));\r\n }\r\n\r\n /**\r\n * Calculates the space required for the axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n *\r\n * @return The space required for the axes.\r\n */\r\n protected AxisSpace calculateAxisSpace(Graphics2D g2, \r\n Rectangle2D plotArea) {\r\n AxisSpace space = new AxisSpace();\r\n space = calculateRangeAxisSpace(g2, plotArea, space);\r\n space = calculateDomainAxisSpace(g2, plotArea, space);\r\n return space;\r\n }\r\n\r\n /**\r\n * Draws the plot on a Java 2D graphics device (such as the screen or a\r\n * printer).\r\n * <P>\r\n * At your option, you may supply an instance of {@link PlotRenderingInfo}.\r\n * If you do, it will be populated with information about the drawing,\r\n * including various plot dimensions and tooltip info.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot (including axes) should\r\n * be drawn.\r\n * @param anchor the anchor point (<code>null</code> permitted).\r\n * @param parentState the state from the parent plot, if there is one.\r\n * @param state collects info as the chart is drawn (possibly\r\n * <code>null</code>).\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor,\r\n PlotState parentState, PlotRenderingInfo state) {\r\n\r\n // if the plot area is too small, just return...\r\n boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW);\r\n boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW);\r\n if (b1 || b2) {\r\n return;\r\n }\r\n\r\n // record the plot area...\r\n if (state == null) {\r\n // if the incoming state is null, no information will be passed\r\n // back to the caller - but we create a temporary state to record\r\n // the plot area, since that is used later by the axes\r\n state = new PlotRenderingInfo(null);\r\n }\r\n state.setPlotArea(area);\r\n\r\n // adjust the drawing area for the plot insets (if any)...\r\n RectangleInsets insets = getInsets();\r\n insets.trim(area);\r\n\r\n // calculate the data area...\r\n AxisSpace space = calculateAxisSpace(g2, area);\r\n Rectangle2D dataArea = space.shrink(area, null);\r\n this.axisOffset.trim(dataArea);\r\n dataArea = integerise(dataArea);\r\n if (dataArea.isEmpty()) {\r\n return;\r\n }\r\n state.setDataArea(dataArea);\r\n createAndAddEntity((Rectangle2D) dataArea.clone(), state, null, null);\r\n\r\n // if there is a renderer, it draws the background, otherwise use the\r\n // default background...\r\n if (getRenderer() != null) {\r\n getRenderer().drawBackground(g2, this, dataArea);\r\n } else {\r\n drawBackground(g2, dataArea);\r\n }\r\n\r\n Map axisStateMap = drawAxes(g2, area, dataArea, state);\r\n\r\n // the anchor point is typically the point where the mouse last\r\n // clicked - the crosshairs will be driven off this point...\r\n if (anchor != null && !dataArea.contains(anchor)) {\r\n anchor = ShapeUtilities.getPointInRectangle(anchor.getX(),\r\n anchor.getY(), dataArea);\r\n }\r\n CategoryCrosshairState crosshairState = new CategoryCrosshairState();\r\n crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY);\r\n crosshairState.setAnchor(anchor);\r\n\r\n // specify the anchor X and Y coordinates in Java2D space, for the\r\n // cases where these are not updated during rendering (i.e. no lock\r\n // on data)\r\n crosshairState.setAnchorX(Double.NaN);\r\n crosshairState.setAnchorY(Double.NaN);\r\n if (anchor != null) {\r\n ValueAxis rangeAxis = getRangeAxis();\r\n if (rangeAxis != null) {\r\n double y;\r\n if (getOrientation() == PlotOrientation.VERTICAL) {\r\n y = rangeAxis.java2DToValue(anchor.getY(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n else {\r\n y = rangeAxis.java2DToValue(anchor.getX(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n crosshairState.setAnchorY(y);\r\n }\r\n }\r\n crosshairState.setRowKey(getDomainCrosshairRowKey());\r\n crosshairState.setColumnKey(getDomainCrosshairColumnKey());\r\n crosshairState.setCrosshairY(getRangeCrosshairValue());\r\n\r\n // don't let anyone draw outside the data area\r\n Shape savedClip = g2.getClip();\r\n g2.clip(dataArea);\r\n\r\n drawDomainGridlines(g2, dataArea);\r\n\r\n AxisState rangeAxisState = (AxisState) axisStateMap.get(getRangeAxis());\r\n if (rangeAxisState == null) {\r\n if (parentState != null) {\r\n rangeAxisState = (AxisState) parentState.getSharedAxisStates()\r\n .get(getRangeAxis());\r\n }\r\n }\r\n if (rangeAxisState != null) {\r\n drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks());\r\n drawZeroRangeBaseline(g2, dataArea);\r\n }\r\n\r\n Graphics2D savedG2 = g2;\r\n BufferedImage dataImage = null;\r\n boolean suppressShadow = Boolean.TRUE.equals(g2.getRenderingHint(\r\n JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION));\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n dataImage = new BufferedImage((int) dataArea.getWidth(),\r\n (int)dataArea.getHeight(), BufferedImage.TYPE_INT_ARGB);\r\n g2 = dataImage.createGraphics();\r\n g2.translate(-dataArea.getX(), -dataArea.getY());\r\n g2.setRenderingHints(savedG2.getRenderingHints());\r\n }\r\n\r\n // draw the markers...\r\n for (CategoryItemRenderer renderer : this.renderers.values()) {\r\n int i = getIndexOf(renderer);\r\n drawDomainMarkers(g2, dataArea, i, Layer.BACKGROUND);\r\n }\r\n for (CategoryItemRenderer renderer : this.renderers.values()) {\r\n int i = getIndexOf(renderer);\r\n drawRangeMarkers(g2, dataArea, i, Layer.BACKGROUND);\r\n }\r\n\r\n // now render data items...\r\n boolean foundData = false;\r\n\r\n // set up the alpha-transparency...\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(\r\n AlphaComposite.SRC_OVER, getForegroundAlpha()));\r\n\r\n DatasetRenderingOrder order = getDatasetRenderingOrder();\r\n List<Integer> datasetIndices = getDatasetIndices(order);\r\n for (int i : datasetIndices) {\r\n foundData = render(g2, dataArea, i, state, crosshairState)\r\n || foundData;\r\n }\r\n\r\n // draw the foreground markers...\r\n List<Integer> rendererIndices = getRendererIndices(order);\r\n for (int i : rendererIndices) {\r\n drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n for (int i : rendererIndices) {\r\n drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n\r\n // draw the annotations (if any)...\r\n drawAnnotations(g2, dataArea);\r\n\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n BufferedImage shadowImage = this.shadowGenerator.createDropShadow(\r\n dataImage);\r\n g2 = savedG2;\r\n g2.drawImage(shadowImage, (int) dataArea.getX()\r\n + this.shadowGenerator.calculateOffsetX(),\r\n (int) dataArea.getY()\r\n + this.shadowGenerator.calculateOffsetY(), null);\r\n g2.drawImage(dataImage, (int) dataArea.getX(),\r\n (int) dataArea.getY(), null);\r\n }\r\n g2.setClip(savedClip);\r\n g2.setComposite(originalComposite);\r\n\r\n if (!foundData) {\r\n drawNoDataMessage(g2, dataArea);\r\n }\r\n\r\n int datasetIndex = crosshairState.getDatasetIndex();\r\n setCrosshairDatasetIndex(datasetIndex, false);\r\n\r\n // draw domain crosshair if required...\r\n Comparable rowKey = crosshairState.getRowKey();\r\n Comparable columnKey = crosshairState.getColumnKey();\r\n setDomainCrosshairRowKey(rowKey, false);\r\n setDomainCrosshairColumnKey(columnKey, false);\r\n if (isDomainCrosshairVisible() && columnKey != null) {\r\n Paint paint = getDomainCrosshairPaint();\r\n Stroke stroke = getDomainCrosshairStroke();\r\n drawDomainCrosshair(g2, dataArea, this.orientation,\r\n datasetIndex, rowKey, columnKey, stroke, paint);\r\n }\r\n\r\n // draw range crosshair if required...\r\n ValueAxis yAxis = getRangeAxisForDataset(datasetIndex);\r\n RectangleEdge yAxisEdge = getRangeAxisEdge();\r\n if (!this.rangeCrosshairLockedOnData && anchor != null) {\r\n double yy;\r\n if (getOrientation() == PlotOrientation.VERTICAL) {\r\n yy = yAxis.java2DToValue(anchor.getY(), dataArea, yAxisEdge);\r\n }\r\n else {\r\n yy = yAxis.java2DToValue(anchor.getX(), dataArea, yAxisEdge);\r\n }\r\n crosshairState.setCrosshairY(yy);\r\n }\r\n setRangeCrosshairValue(crosshairState.getCrosshairY(), false);\r\n if (isRangeCrosshairVisible()) {\r\n double y = getRangeCrosshairValue();\r\n Paint paint = getRangeCrosshairPaint();\r\n Stroke stroke = getRangeCrosshairStroke();\r\n drawRangeCrosshair(g2, dataArea, getOrientation(), y, yAxis,\r\n stroke, paint);\r\n }\r\n\r\n // draw an outline around the plot area...\r\n if (isOutlineVisible()) {\r\n if (getRenderer() != null) {\r\n getRenderer().drawOutline(g2, this, dataArea);\r\n }\r\n else {\r\n drawOutline(g2, dataArea);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the indices of the non-null datasets in the specified order.\r\n * \r\n * @param order the order ({@code null} not permitted).\r\n * \r\n * @return The list of indices. \r\n */\r\n private List<Integer> getDatasetIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Map.Entry<Integer, CategoryDataset> entry : \r\n this.datasets.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result;\r\n }\r\n \r\n /**\r\n * Returns the indices of the non-null renderers for the plot, in the \r\n * specified order.\r\n * \r\n * @param order the rendering order {@code null} not permitted).\r\n * \r\n * @return A list of indices.\r\n */\r\n private List<Integer> getRendererIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Map.Entry<Integer, CategoryItemRenderer> entry: \r\n this.renderers.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result; \r\n }\r\n \r\n /**\r\n * Draws the plot background (the background color and/or image).\r\n * <P>\r\n * This method will be called during the chart drawing process and is\r\n * declared public so that it can be accessed by the renderers used by\r\n * certain subclasses. You shouldn't need to call this method directly.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot should be drawn.\r\n */\r\n @Override\r\n public void drawBackground(Graphics2D g2, Rectangle2D area) {\r\n fillBackground(g2, area, this.orientation);\r\n drawBackgroundImage(g2, area);\r\n }\r\n\r\n /**\r\n * A utility method for drawing the plot's axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param dataArea the data area.\r\n * @param plotState collects information about the plot (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A map containing the axis states.\r\n */\r\n protected Map drawAxes(Graphics2D g2, Rectangle2D plotArea, \r\n Rectangle2D dataArea, PlotRenderingInfo plotState) {\r\n\r\n AxisCollection axisCollection = new AxisCollection();\r\n\r\n // add domain axes to lists...\r\n for (CategoryAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n int index = getDomainAxisIndex(xAxis);\r\n axisCollection.add(xAxis, getDomainAxisEdge(index));\r\n }\r\n }\r\n\r\n // add range axes to lists...\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n int index = findRangeAxisIndex(yAxis);\r\n axisCollection.add(yAxis, getRangeAxisEdge(index));\r\n }\r\n }\r\n\r\n Map axisStateMap = new HashMap();\r\n\r\n // draw the top axes\r\n double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset(\r\n dataArea.getHeight());\r\n Iterator iterator = axisCollection.getAxesAtTop().iterator();\r\n while (iterator.hasNext()) {\r\n Axis axis = (Axis) iterator.next();\r\n if (axis != null) {\r\n AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.TOP, plotState);\r\n cursor = axisState.getCursor();\r\n axisStateMap.put(axis, axisState);\r\n }\r\n }\r\n\r\n // draw the bottom axes\r\n cursor = dataArea.getMaxY()\r\n + this.axisOffset.calculateBottomOutset(dataArea.getHeight());\r\n iterator = axisCollection.getAxesAtBottom().iterator();\r\n while (iterator.hasNext()) {\r\n Axis axis = (Axis) iterator.next();\r\n if (axis != null) {\r\n AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.BOTTOM, plotState);\r\n cursor = axisState.getCursor();\r\n axisStateMap.put(axis, axisState);\r\n }\r\n }\r\n\r\n // draw the left axes\r\n cursor = dataArea.getMinX()\r\n - this.axisOffset.calculateLeftOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtLeft().iterator();\r\n while (iterator.hasNext()) {\r\n Axis axis = (Axis) iterator.next();\r\n if (axis != null) {\r\n AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.LEFT, plotState);\r\n cursor = axisState.getCursor();\r\n axisStateMap.put(axis, axisState);\r\n }\r\n }\r\n\r\n // draw the right axes\r\n cursor = dataArea.getMaxX()\r\n + this.axisOffset.calculateRightOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtRight().iterator();\r\n while (iterator.hasNext()) {\r\n Axis axis = (Axis) iterator.next();\r\n if (axis != null) {\r\n AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.RIGHT, plotState);\r\n cursor = axisState.getCursor();\r\n axisStateMap.put(axis, axisState);\r\n }\r\n }\r\n\r\n return axisStateMap;\r\n\r\n }\r\n\r\n /**\r\n * Draws a representation of a dataset within the dataArea region using the\r\n * appropriate renderer.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the region in which the data is to be drawn.\r\n * @param index the dataset and renderer index.\r\n * @param info an optional object for collection dimension information.\r\n * @param crosshairState a state object for tracking crosshair info\r\n * (<code>null</code> permitted).\r\n *\r\n * @return A boolean that indicates whether or not real data was found.\r\n *\r\n * @since 1.0.11\r\n */\r\n public boolean render(Graphics2D g2, Rectangle2D dataArea, int index,\r\n PlotRenderingInfo info, CategoryCrosshairState crosshairState) {\r\n\r\n boolean foundData = false;\r\n CategoryDataset currentDataset = getDataset(index);\r\n CategoryItemRenderer renderer = getRenderer(index);\r\n CategoryAxis domainAxis = getDomainAxisForDataset(index);\r\n ValueAxis rangeAxis = getRangeAxisForDataset(index);\r\n boolean hasData = !DatasetUtilities.isEmptyOrNull(currentDataset);\r\n if (hasData && renderer != null) {\r\n\r\n foundData = true;\r\n CategoryItemRendererState state = renderer.initialise(g2, dataArea,\r\n this, index, info);\r\n state.setCrosshairState(crosshairState);\r\n int columnCount = currentDataset.getColumnCount();\r\n int rowCount = currentDataset.getRowCount();\r\n int passCount = renderer.getPassCount();\r\n for (int pass = 0; pass < passCount; pass++) {\r\n if (this.columnRenderingOrder == SortOrder.ASCENDING) {\r\n for (int column = 0; column < columnCount; column++) {\r\n if (this.rowRenderingOrder == SortOrder.ASCENDING) {\r\n for (int row = 0; row < rowCount; row++) {\r\n renderer.drawItem(g2, state, dataArea, this,\r\n domainAxis, rangeAxis, currentDataset,\r\n row, column, pass);\r\n }\r\n }\r\n else {\r\n for (int row = rowCount - 1; row >= 0; row--) {\r\n renderer.drawItem(g2, state, dataArea, this,\r\n domainAxis, rangeAxis, currentDataset,\r\n row, column, pass);\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n for (int column = columnCount - 1; column >= 0; column--) {\r\n if (this.rowRenderingOrder == SortOrder.ASCENDING) {\r\n for (int row = 0; row < rowCount; row++) {\r\n renderer.drawItem(g2, state, dataArea, this,\r\n domainAxis, rangeAxis, currentDataset,\r\n row, column, pass);\r\n }\r\n }\r\n else {\r\n for (int row = rowCount - 1; row >= 0; row--) {\r\n renderer.drawItem(g2, state, dataArea, this,\r\n domainAxis, rangeAxis, currentDataset,\r\n row, column, pass);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return foundData;\r\n\r\n }\r\n\r\n /**\r\n * Draws the domain gridlines for the plot, if they are visible.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area inside the axes.\r\n *\r\n * @see #drawRangeGridlines(Graphics2D, Rectangle2D, List)\r\n */\r\n protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea) {\r\n\r\n if (!isDomainGridlinesVisible()) {\r\n return;\r\n }\r\n CategoryAnchor anchor = getDomainGridlinePosition();\r\n RectangleEdge domainAxisEdge = getDomainAxisEdge();\r\n CategoryDataset dataset = getDataset();\r\n if (dataset == null) {\r\n return;\r\n }\r\n CategoryAxis axis = getDomainAxis();\r\n if (axis != null) {\r\n int columnCount = dataset.getColumnCount();\r\n for (int c = 0; c < columnCount; c++) {\r\n double xx = axis.getCategoryJava2DCoordinate(anchor, c,\r\n columnCount, dataArea, domainAxisEdge);\r\n CategoryItemRenderer renderer1 = getRenderer();\r\n if (renderer1 != null) {\r\n renderer1.drawDomainGridline(g2, this, dataArea, xx);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws the range gridlines for the plot, if they are visible.\r\n *\r\n * @param g2 the graphics device ({@code null} not permitted).\r\n * @param dataArea the area inside the axes ({@code null} not permitted).\r\n * @param ticks the ticks.\r\n *\r\n * @see #drawDomainGridlines(Graphics2D, Rectangle2D)\r\n */\r\n protected void drawRangeGridlines(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n // draw the range grid lines, if any...\r\n if (!isRangeGridlinesVisible() && !isRangeMinorGridlinesVisible()) {\r\n return;\r\n }\r\n // no axis, no gridlines...\r\n ValueAxis axis = getRangeAxis();\r\n if (axis == null) {\r\n return;\r\n }\r\n // no renderer, no gridlines...\r\n CategoryItemRenderer r = getRenderer();\r\n if (r == null) {\r\n return;\r\n }\r\n\r\n Stroke gridStroke = null;\r\n Paint gridPaint = null;\r\n boolean paintLine;\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n paintLine = false;\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if ((tick.getTickType() == TickType.MINOR)\r\n && isRangeMinorGridlinesVisible()) {\r\n gridStroke = getRangeMinorGridlineStroke();\r\n gridPaint = getRangeMinorGridlinePaint();\r\n paintLine = true;\r\n }\r\n else if ((tick.getTickType() == TickType.MAJOR)\r\n && isRangeGridlinesVisible()) {\r\n gridStroke = getRangeGridlineStroke();\r\n gridPaint = getRangeGridlinePaint();\r\n paintLine = true;\r\n }\r\n if (((tick.getValue() != 0.0)\r\n || !isRangeZeroBaselineVisible()) && paintLine) {\r\n // the method we want isn't in the CategoryItemRenderer\r\n // interface...\r\n if (r instanceof AbstractCategoryItemRenderer) {\r\n AbstractCategoryItemRenderer aci\r\n = (AbstractCategoryItemRenderer) r;\r\n aci.drawRangeLine(g2, this, axis, dataArea,\r\n tick.getValue(), gridPaint, gridStroke);\r\n }\r\n else {\r\n // we'll have to use the method in the interface, but\r\n // this doesn't have the paint and stroke settings...\r\n r.drawRangeGridline(g2, this, axis, dataArea,\r\n tick.getValue());\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws a base line across the chart at value zero on the range axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n *\r\n * @since 1.0.13\r\n */\r\n protected void drawZeroRangeBaseline(Graphics2D g2, Rectangle2D area) {\r\n if (!isRangeZeroBaselineVisible()) {\r\n return;\r\n }\r\n CategoryItemRenderer r = getRenderer();\r\n if (r instanceof AbstractCategoryItemRenderer) {\r\n AbstractCategoryItemRenderer aci = (AbstractCategoryItemRenderer) r;\r\n aci.drawRangeLine(g2, this, getRangeAxis(), area, 0.0,\r\n this.rangeZeroBaselinePaint, this.rangeZeroBaselineStroke);\r\n }\r\n else {\r\n r.drawRangeGridline(g2, this, getRangeAxis(), area, 0.0);\r\n }\r\n }\r\n\r\n /**\r\n * Draws the annotations.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n */\r\n protected void drawAnnotations(Graphics2D g2, Rectangle2D dataArea) {\r\n\r\n if (getAnnotations() != null) {\r\n Iterator iterator = getAnnotations().iterator();\r\n while (iterator.hasNext()) {\r\n CategoryAnnotation annotation\r\n = (CategoryAnnotation) iterator.next();\r\n annotation.draw(g2, this, dataArea, getDomainAxis(),\r\n getRangeAxis());\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the domain markers (if any) for an axis and layer. This method is\r\n * typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the renderer index.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #drawRangeMarkers(Graphics2D, Rectangle2D, int, Layer)\r\n */\r\n protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n CategoryItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n\r\n Collection markers = getDomainMarkers(index, layer);\r\n CategoryAxis axis = getDomainAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n CategoryMarker marker = (CategoryMarker) iterator.next();\r\n r.drawDomainMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the range markers (if any) for an axis and layer. This method is\r\n * typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the renderer index.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #drawDomainMarkers(Graphics2D, Rectangle2D, int, Layer)\r\n */\r\n protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n CategoryItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n\r\n Collection markers = getRangeMarkers(index, layer);\r\n ValueAxis axis = getRangeAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker marker = (Marker) iterator.next();\r\n r.drawRangeMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Utility method for drawing a line perpendicular to the range axis (used\r\n * for crosshairs).\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the area defined by the axes.\r\n * @param value the data value.\r\n * @param stroke the line stroke (<code>null</code> not permitted).\r\n * @param paint the line paint (<code>null</code> not permitted).\r\n */\r\n protected void drawRangeLine(Graphics2D g2, Rectangle2D dataArea,\r\n double value, Stroke stroke, Paint paint) {\r\n\r\n double java2D = getRangeAxis().valueToJava2D(value, dataArea,\r\n getRangeAxisEdge());\r\n Line2D line = null;\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n line = new Line2D.Double(java2D, dataArea.getMinY(), java2D,\r\n dataArea.getMaxY());\r\n }\r\n else if (this.orientation == PlotOrientation.VERTICAL) {\r\n line = new Line2D.Double(dataArea.getMinX(), java2D,\r\n dataArea.getMaxX(), java2D);\r\n }\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n\r\n }\r\n\r\n /**\r\n * Draws a domain crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param datasetIndex the dataset index.\r\n * @param rowKey the row key.\r\n * @param columnKey the column key.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @see #drawRangeCrosshair(Graphics2D, Rectangle2D, PlotOrientation,\r\n * double, ValueAxis, Stroke, Paint)\r\n *\r\n * @since 1.0.11\r\n */\r\n protected void drawDomainCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, int datasetIndex,\r\n Comparable rowKey, Comparable columnKey, Stroke stroke,\r\n Paint paint) {\r\n\r\n CategoryDataset dataset = getDataset(datasetIndex);\r\n CategoryAxis axis = getDomainAxisForDataset(datasetIndex);\r\n CategoryItemRenderer renderer = getRenderer(datasetIndex);\r\n Line2D line;\r\n if (orientation == PlotOrientation.VERTICAL) {\r\n double xx = renderer.getItemMiddle(rowKey, columnKey, dataset, axis,\r\n dataArea, RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n }\r\n else {\r\n double yy = renderer.getItemMiddle(rowKey, columnKey, dataset, axis,\r\n dataArea, RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n\r\n }\r\n\r\n /**\r\n * Draws a range crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param value the crosshair value.\r\n * @param axis the axis against which the value is measured.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @see #drawDomainCrosshair(Graphics2D, Rectangle2D, PlotOrientation, int,\r\n * Comparable, Comparable, Stroke, Paint)\r\n *\r\n * @since 1.0.5\r\n */\r\n protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, double value, ValueAxis axis,\r\n Stroke stroke, Paint paint) {\r\n\r\n if (!axis.getRange().contains(value)) {\r\n return;\r\n }\r\n Line2D line;\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n double xx = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n }\r\n else {\r\n double yy = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n\r\n }\r\n\r\n /**\r\n * Returns the range of data values that will be plotted against the range\r\n * axis. If the dataset is <code>null</code>, this method returns\r\n * <code>null</code>.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The data range.\r\n */\r\n @Override\r\n public Range getDataRange(ValueAxis axis) {\r\n Range result = null;\r\n List<CategoryDataset> mappedDatasets = new ArrayList<CategoryDataset>();\r\n int rangeIndex = findRangeAxisIndex(axis);\r\n if (rangeIndex >= 0) {\r\n mappedDatasets.addAll(datasetsMappedToRangeAxis(rangeIndex));\r\n }\r\n else if (axis == getRangeAxis()) {\r\n mappedDatasets.addAll(datasetsMappedToRangeAxis(0));\r\n }\r\n\r\n // iterate through the datasets that map to the axis and get the union\r\n // of the ranges.\r\n for (CategoryDataset d : mappedDatasets) {\r\n CategoryItemRenderer r = getRendererForDataset(d);\r\n if (r != null) {\r\n result = Range.combine(result, r.findRangeBounds(d));\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a list of the datasets that are mapped to the axis with the\r\n * specified index.\r\n *\r\n * @param axisIndex the axis index.\r\n *\r\n * @return The list (possibly empty, but never <code>null</code>).\r\n *\r\n * @since 1.0.3\r\n */\r\n private List<CategoryDataset> datasetsMappedToDomainAxis(int axisIndex) {\r\n Integer key = new Integer(axisIndex);\r\n List<CategoryDataset> result = new ArrayList<CategoryDataset>();\r\n for (CategoryDataset dataset : this.datasets.values()) {\r\n if (dataset == null) {\r\n continue;\r\n }\r\n int i = indexOf(dataset);\r\n List mappedAxes = (List) this.datasetToDomainAxesMap.get(\r\n new Integer(i));\r\n if (mappedAxes == null) {\r\n if (key.equals(ZERO)) {\r\n result.add(dataset);\r\n }\r\n } else {\r\n if (mappedAxes.contains(key)) {\r\n result.add(dataset);\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * A utility method that returns a list of datasets that are mapped to a\r\n * given range axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return A list of datasets.\r\n */\r\n private List datasetsMappedToRangeAxis(int index) {\r\n Integer key = new Integer(index);\r\n List result = new ArrayList();\r\n for (CategoryDataset dataset : this.datasets.values()) {\r\n int i = indexOf(dataset);\r\n List mappedAxes = (List) this.datasetToRangeAxesMap.get(\r\n new Integer(i));\r\n if (mappedAxes == null) {\r\n if (key.equals(ZERO)) {\r\n result.add(this.datasets.get(i));\r\n }\r\n } else {\r\n if (mappedAxes.contains(key)) {\r\n result.add(this.datasets.get(i));\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the weight for this plot when it is used as a subplot within a\r\n * combined plot.\r\n *\r\n * @return The weight.\r\n *\r\n * @see #setWeight(int)\r\n */\r\n public int getWeight() {\r\n return this.weight;\r\n }\r\n\r\n /**\r\n * Sets the weight for the plot and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param weight the weight.\r\n *\r\n * @see #getWeight()\r\n */\r\n public void setWeight(int weight) {\r\n this.weight = weight;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the fixed domain axis space.\r\n *\r\n * @return The fixed domain axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedDomainAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedDomainAxisSpace() {\r\n return this.fixedDomainAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space) {\r\n setFixedDomainAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n *\r\n * @since 1.0.7\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedDomainAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the fixed range axis space.\r\n *\r\n * @return The fixed range axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedRangeAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedRangeAxisSpace() {\r\n return this.fixedRangeAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space) {\r\n setFixedRangeAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n *\r\n * @since 1.0.7\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedRangeAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a list of the categories in the plot's primary dataset.\r\n *\r\n * @return A list of the categories in the plot's primary dataset.\r\n *\r\n * @see #getCategoriesForAxis(CategoryAxis)\r\n */\r\n public List getCategories() {\r\n List result = null;\r\n if (getDataset() != null) {\r\n result = Collections.unmodifiableList(getDataset().getColumnKeys());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a list of the categories that should be displayed for the\r\n * specified axis.\r\n *\r\n * @param axis the axis (<code>null</code> not permitted)\r\n *\r\n * @return The categories.\r\n *\r\n * @since 1.0.3\r\n */\r\n public List getCategoriesForAxis(CategoryAxis axis) {\r\n List result = new ArrayList();\r\n int axisIndex = getDomainAxisIndex(axis);\r\n for (CategoryDataset dataset : datasetsMappedToDomainAxis(axisIndex)) {\r\n // add the unique categories from this dataset\r\n for (int i = 0; i < dataset.getColumnCount(); i++) {\r\n Comparable category = dataset.getColumnKey(i);\r\n if (!result.contains(category)) {\r\n result.add(category);\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the shared domain axis is\r\n * drawn for each subplot.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setDrawSharedDomainAxis(boolean)\r\n */\r\n public boolean getDrawSharedDomainAxis() {\r\n return this.drawSharedDomainAxis;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether the shared domain axis is drawn when\r\n * this plot is being used as a subplot.\r\n *\r\n * @param draw a boolean.\r\n *\r\n * @see #getDrawSharedDomainAxis()\r\n */\r\n public void setDrawSharedDomainAxis(boolean draw) {\r\n this.drawSharedDomainAxis = draw;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>false</code> always, because the plot cannot be panned\r\n * along the domain axis/axes.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isRangePannable()\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isDomainPannable() {\r\n return false;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if panning is enabled for the range axes,\r\n * and <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangePannable(boolean)\r\n * @see #isDomainPannable()\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isRangePannable() {\r\n return this.rangePannable;\r\n }\r\n\r\n /**\r\n * Sets the flag that enables or disables panning of the plot along\r\n * the range axes.\r\n *\r\n * @param pannable the new flag value.\r\n *\r\n * @see #isRangePannable()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangePannable(boolean pannable) {\r\n this.rangePannable = pannable;\r\n }\r\n\r\n /**\r\n * Pans the domain axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panDomainAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n // do nothing, because the plot is not pannable along the domain axes\r\n }\r\n\r\n /**\r\n * Pans the range axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panRangeAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n if (!isRangePannable()) {\r\n return;\r\n }\r\n for (ValueAxis axis : this.rangeAxes.values()) {\r\n if (axis == null) {\r\n continue;\r\n }\r\n double length = axis.getRange().getLength();\r\n double adj = percent * length;\r\n if (axis.isInverted()) {\r\n adj = -adj;\r\n }\r\n axis.setRange(axis.getLowerBound() + adj,\r\n axis.getUpperBound() + adj);\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>false</code> to indicate that the domain axes are not\r\n * zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isRangeZoomable()\r\n */\r\n @Override\r\n public boolean isDomainZoomable() {\r\n return false;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> to indicate that the range axes are zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isDomainZoomable()\r\n */\r\n @Override\r\n public boolean isRangeZoomable() {\r\n return true;\r\n }\r\n\r\n /**\r\n * This method does nothing, because <code>CategoryPlot</code> doesn't\r\n * support zooming on the domain.\r\n *\r\n * @param factor the zoom factor.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D space) for the zoom.\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo state,\r\n Point2D source) {\r\n // can't zoom domain axis\r\n }\r\n\r\n /**\r\n * This method does nothing, because <code>CategoryPlot</code> doesn't\r\n * support zooming on the domain.\r\n *\r\n * @param lowerPercent the lower bound.\r\n * @param upperPercent the upper bound.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D space) for the zoom.\r\n */\r\n @Override\r\n public void zoomDomainAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo state, Point2D source) {\r\n // can't zoom domain axis\r\n }\r\n\r\n /**\r\n * This method does nothing, because <code>CategoryPlot</code> doesn't\r\n * support zooming on the domain.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point (in Java2D space).\r\n * @param useAnchor use source point as zoom anchor?\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n // can't zoom domain axis\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D space) for the zoom.\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo state,\r\n Point2D source) {\r\n // delegate to other method\r\n zoomRangeAxes(factor, state, source, false);\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n * @param useAnchor a flag that controls whether or not the source point\r\n * is used for the zoom anchor.\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n\r\n // perform the zoom on each range axis\r\n for (ValueAxis rangeAxis : this.rangeAxes.values()) {\r\n if (rangeAxis == null) {\r\n continue;\r\n }\r\n if (useAnchor) {\r\n // get the relevant source coordinate given the plot orientation\r\n double sourceY = source.getY();\r\n if (this.orientation.isHorizontal()) {\r\n sourceY = source.getX();\r\n }\r\n double anchorY = rangeAxis.java2DToValue(sourceY,\r\n info.getDataArea(), getRangeAxisEdge());\r\n rangeAxis.resizeRange2(factor, anchorY);\r\n } else {\r\n rangeAxis.resizeRange(factor);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the range axes.\r\n *\r\n * @param lowerPercent the lower bound.\r\n * @param upperPercent the upper bound.\r\n * @param state the plot state.\r\n * @param source the source point (in Java2D space) for the zoom.\r\n */\r\n @Override\r\n public void zoomRangeAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo state, Point2D source) {\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.zoomRange(lowerPercent, upperPercent);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the anchor value.\r\n *\r\n * @return The anchor value.\r\n *\r\n * @see #setAnchorValue(double)\r\n */\r\n public double getAnchorValue() {\r\n return this.anchorValue;\r\n }\r\n\r\n /**\r\n * Sets the anchor value and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param value the anchor value.\r\n *\r\n * @see #getAnchorValue()\r\n */\r\n public void setAnchorValue(double value) {\r\n setAnchorValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the anchor value and, if requested, sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param value the value.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getAnchorValue()\r\n */\r\n public void setAnchorValue(double value, boolean notify) {\r\n this.anchorValue = value;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Tests the plot for equality with an arbitrary object.\r\n *\r\n * @param obj the object to test against (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof CategoryPlot)) {\r\n return false;\r\n }\r\n CategoryPlot that = (CategoryPlot) obj;\r\n if (this.orientation != that.orientation) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.axisOffset, that.axisOffset)) {\r\n return false;\r\n }\r\n if (!this.domainAxes.equals(that.domainAxes)) {\r\n return false;\r\n }\r\n if (!this.domainAxisLocations.equals(that.domainAxisLocations)) {\r\n return false;\r\n }\r\n if (this.drawSharedDomainAxis != that.drawSharedDomainAxis) {\r\n return false;\r\n }\r\n if (!this.rangeAxes.equals(that.rangeAxes)) {\r\n return false;\r\n }\r\n if (!this.rangeAxisLocations.equals(that.rangeAxisLocations)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToDomainAxesMap,\r\n that.datasetToDomainAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToRangeAxesMap,\r\n that.datasetToRangeAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.renderers, that.renderers)) {\r\n return false;\r\n }\r\n if (this.renderingOrder != that.renderingOrder) {\r\n return false;\r\n }\r\n if (this.columnRenderingOrder != that.columnRenderingOrder) {\r\n return false;\r\n }\r\n if (this.rowRenderingOrder != that.rowRenderingOrder) {\r\n return false;\r\n }\r\n if (this.domainGridlinesVisible != that.domainGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.domainGridlinePosition != that.domainGridlinePosition) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainGridlineStroke,\r\n that.domainGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainGridlinePaint,\r\n that.domainGridlinePaint)) {\r\n return false;\r\n }\r\n if (this.rangeGridlinesVisible != that.rangeGridlinesVisible) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeGridlineStroke,\r\n that.rangeGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeGridlinePaint,\r\n that.rangeGridlinePaint)) {\r\n return false;\r\n }\r\n if (this.anchorValue != that.anchorValue) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairVisible != that.rangeCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairValue != that.rangeCrosshairValue) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeCrosshairStroke,\r\n that.rangeCrosshairStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeCrosshairPaint,\r\n that.rangeCrosshairPaint)) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairLockedOnData\r\n != that.rangeCrosshairLockedOnData) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundDomainMarkers,\r\n that.foregroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundDomainMarkers,\r\n that.backgroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundRangeMarkers,\r\n that.foregroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundRangeMarkers,\r\n that.backgroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.annotations, that.annotations)) {\r\n return false;\r\n }\r\n if (this.weight != that.weight) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.fixedDomainAxisSpace,\r\n that.fixedDomainAxisSpace)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.fixedRangeAxisSpace,\r\n that.fixedRangeAxisSpace)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.fixedLegendItems,\r\n that.fixedLegendItems)) {\r\n return false;\r\n }\r\n if (this.domainCrosshairVisible != that.domainCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.crosshairDatasetIndex != that.crosshairDatasetIndex) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainCrosshairColumnKey,\r\n that.domainCrosshairColumnKey)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainCrosshairRowKey,\r\n that.domainCrosshairRowKey)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainCrosshairPaint,\r\n that.domainCrosshairPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainCrosshairStroke,\r\n that.domainCrosshairStroke)) {\r\n return false;\r\n }\r\n if (this.rangeMinorGridlinesVisible\r\n != that.rangeMinorGridlinesVisible) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeMinorGridlinePaint,\r\n that.rangeMinorGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeMinorGridlineStroke,\r\n that.rangeMinorGridlineStroke)) {\r\n return false;\r\n }\r\n if (this.rangeZeroBaselineVisible != that.rangeZeroBaselineVisible) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeZeroBaselinePaint,\r\n that.rangeZeroBaselinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeZeroBaselineStroke,\r\n that.rangeZeroBaselineStroke)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.shadowGenerator,\r\n that.shadowGenerator)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a clone of the plot.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if the cloning is not supported.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n CategoryPlot clone = (CategoryPlot) super.clone();\r\n clone.domainAxes = CloneUtils.cloneMapValues(this.domainAxes);\r\n for (CategoryAxis axis : clone.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n clone.rangeAxes = CloneUtils.cloneMapValues(this.rangeAxes);\r\n for (ValueAxis axis : clone.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n\r\n // AxisLocation is immutable, so we can just copy the maps\r\n clone.domainAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.domainAxisLocations);\r\n clone.rangeAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.rangeAxisLocations);\r\n\r\n clone.datasets = new HashMap<Integer, CategoryDataset>(this.datasets);\r\n for (CategoryDataset dataset : clone.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(clone);\r\n }\r\n }\r\n clone.datasetToDomainAxesMap = new TreeMap();\r\n clone.datasetToDomainAxesMap.putAll(this.datasetToDomainAxesMap);\r\n clone.datasetToRangeAxesMap = new TreeMap();\r\n clone.datasetToRangeAxesMap.putAll(this.datasetToRangeAxesMap);\r\n\r\n clone.renderers = CloneUtils.cloneMapValues(this.renderers);\r\n for (CategoryItemRenderer renderer : clone.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.setPlot(clone);\r\n renderer.addChangeListener(clone);\r\n }\r\n }\r\n if (this.fixedDomainAxisSpace != null) {\r\n clone.fixedDomainAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedDomainAxisSpace);\r\n }\r\n if (this.fixedRangeAxisSpace != null) {\r\n clone.fixedRangeAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedRangeAxisSpace);\r\n }\r\n\r\n clone.annotations = (List) ObjectUtilities.deepClone(this.annotations);\r\n clone.foregroundDomainMarkers = cloneMarkerMap(\r\n this.foregroundDomainMarkers);\r\n clone.backgroundDomainMarkers = cloneMarkerMap(\r\n this.backgroundDomainMarkers);\r\n clone.foregroundRangeMarkers = cloneMarkerMap(\r\n this.foregroundRangeMarkers);\r\n clone.backgroundRangeMarkers = cloneMarkerMap(\r\n this.backgroundRangeMarkers);\r\n if (this.fixedLegendItems != null) {\r\n clone.fixedLegendItems\r\n = (LegendItemCollection) this.fixedLegendItems.clone();\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * A utility method to clone the marker maps.\r\n *\r\n * @param map the map to clone.\r\n *\r\n * @return A clone of the map.\r\n *\r\n * @throws CloneNotSupportedException if there is some problem cloning the\r\n * map.\r\n */\r\n private Map cloneMarkerMap(Map map) throws CloneNotSupportedException {\r\n Map clone = new HashMap();\r\n Set keys = map.keySet();\r\n Iterator iterator = keys.iterator();\r\n while (iterator.hasNext()) {\r\n Object key = iterator.next();\r\n List entry = (List) map.get(key);\r\n Object toAdd = ObjectUtilities.deepClone(entry);\r\n clone.put(key, toAdd);\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.domainGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.domainGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.rangeCrosshairPaint, stream);\r\n SerialUtilities.writeStroke(this.domainCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.domainCrosshairPaint, stream);\r\n SerialUtilities.writeStroke(this.rangeMinorGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeMinorGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeZeroBaselineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeZeroBaselinePaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n\r\n stream.defaultReadObject();\r\n this.domainGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.domainGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.rangeCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.domainCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.domainCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.rangeMinorGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeMinorGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeZeroBaselineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeZeroBaselinePaint = SerialUtilities.readPaint(stream);\r\n\r\n for (CategoryAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n xAxis.setPlot(this);\r\n xAxis.addChangeListener(this);\r\n }\r\n }\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.setPlot(this);\r\n yAxis.addChangeListener(this);\r\n }\r\n }\r\n for (CategoryDataset dataset : this.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n }\r\n for (CategoryItemRenderer renderer : this.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.addChangeListener(this);\r\n }\r\n }\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "Range", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/Range.java", "snippet": "public strictfp class Range implements Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -906333695431863380L;\r\n\r\n /** The lower bound of the range. */\r\n private double lower;\r\n\r\n /** The upper bound of the range. */\r\n private double upper;\r\n\r\n /**\r\n * Creates a new range.\r\n *\r\n * @param lower the lower bound (must be &lt;= upper bound).\r\n * @param upper the upper bound (must be &gt;= lower bound).\r\n */\r\n public Range(double lower, double upper) {\r\n if (lower > upper) {\r\n String msg = \"Range(double, double): require lower (\" + lower\r\n + \") <= upper (\" + upper + \").\";\r\n throw new IllegalArgumentException(msg);\r\n }\r\n this.lower = lower;\r\n this.upper = upper;\r\n }\r\n\r\n /**\r\n * Returns the lower bound for the range.\r\n *\r\n * @return The lower bound.\r\n */\r\n public double getLowerBound() {\r\n return this.lower;\r\n }\r\n\r\n /**\r\n * Returns the upper bound for the range.\r\n *\r\n * @return The upper bound.\r\n */\r\n public double getUpperBound() {\r\n return this.upper;\r\n }\r\n\r\n /**\r\n * Returns the length of the range.\r\n *\r\n * @return The length.\r\n */\r\n public double getLength() {\r\n return this.upper - this.lower;\r\n }\r\n\r\n /**\r\n * Returns the central value for the range.\r\n *\r\n * @return The central value.\r\n */\r\n public double getCentralValue() {\r\n return this.lower / 2.0 + this.upper / 2.0;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range contains the specified value and\r\n * <code>false</code> otherwise.\r\n *\r\n * @param value the value to lookup.\r\n *\r\n * @return <code>true</code> if the range contains the specified value.\r\n */\r\n public boolean contains(double value) {\r\n return (value >= this.lower && value <= this.upper);\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range intersects with the specified\r\n * range, and <code>false</code> otherwise.\r\n *\r\n * @param b0 the lower bound (should be &lt;= b1).\r\n * @param b1 the upper bound (should be &gt;= b0).\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean intersects(double b0, double b1) {\r\n if (b0 <= this.lower) {\r\n return (b1 > this.lower);\r\n }\r\n else {\r\n return (b0 < this.upper && b1 >= b0);\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range intersects with the specified\r\n * range, and <code>false</code> otherwise.\r\n *\r\n * @param range another range (<code>null</code> not permitted).\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.9\r\n */\r\n public boolean intersects(Range range) {\r\n return intersects(range.getLowerBound(), range.getUpperBound());\r\n }\r\n\r\n /**\r\n * Returns the value within the range that is closest to the specified\r\n * value.\r\n *\r\n * @param value the value.\r\n *\r\n * @return The constrained value.\r\n */\r\n public double constrain(double value) {\r\n double result = value;\r\n if (!contains(value)) {\r\n if (value > this.upper) {\r\n result = this.upper;\r\n }\r\n else if (value < this.lower) {\r\n result = this.lower;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates a new range by combining two existing ranges.\r\n * <P>\r\n * Note that:\r\n * <ul>\r\n * <li>either range can be <code>null</code>, in which case the other\r\n * range is returned;</li>\r\n * <li>if both ranges are <code>null</code> the return value is\r\n * <code>null</code>.</li>\r\n * </ul>\r\n *\r\n * @param range1 the first range (<code>null</code> permitted).\r\n * @param range2 the second range (<code>null</code> permitted).\r\n *\r\n * @return A new range (possibly <code>null</code>).\r\n */\r\n public static Range combine(Range range1, Range range2) {\r\n if (range1 == null) {\r\n return range2;\r\n }\r\n if (range2 == null) {\r\n return range1;\r\n }\r\n double l = Math.min(range1.getLowerBound(), range2.getLowerBound());\r\n double u = Math.max(range1.getUpperBound(), range2.getUpperBound());\r\n return new Range(l, u);\r\n }\r\n\r\n /**\r\n * Returns a new range that spans both <code>range1</code> and \r\n * <code>range2</code>. This method has a special handling to ignore\r\n * Double.NaN values.\r\n *\r\n * @param range1 the first range (<code>null</code> permitted).\r\n * @param range2 the second range (<code>null</code> permitted).\r\n *\r\n * @return A new range (possibly <code>null</code>).\r\n *\r\n * @since 1.0.15\r\n */\r\n public static Range combineIgnoringNaN(Range range1, Range range2) {\r\n if (range1 == null) {\r\n if (range2 != null && range2.isNaNRange()) {\r\n return null;\r\n }\r\n return range2;\r\n }\r\n if (range2 == null) {\r\n if (range1.isNaNRange()) {\r\n return null;\r\n }\r\n return range1;\r\n }\r\n double l = min(range1.getLowerBound(), range2.getLowerBound());\r\n double u = max(range1.getUpperBound(), range2.getUpperBound());\r\n if (Double.isNaN(l) && Double.isNaN(u)) {\r\n return null;\r\n }\r\n return new Range(l, u);\r\n }\r\n \r\n /**\r\n * Returns the minimum value. If either value is NaN, the other value is \r\n * returned. If both are NaN, NaN is returned.\r\n * \r\n * @param d1 value 1.\r\n * @param d2 value 2.\r\n * \r\n * @return The minimum of the two values. \r\n */\r\n private static double min(double d1, double d2) {\r\n if (Double.isNaN(d1)) {\r\n return d2;\r\n }\r\n if (Double.isNaN(d2)) {\r\n return d1;\r\n }\r\n return Math.min(d1, d2);\r\n }\r\n\r\n private static double max(double d1, double d2) {\r\n if (Double.isNaN(d1)) {\r\n return d2;\r\n }\r\n if (Double.isNaN(d2)) {\r\n return d1;\r\n }\r\n return Math.max(d1, d2);\r\n }\r\n\r\n /**\r\n * Returns a range that includes all the values in the specified\r\n * <code>range</code> AND the specified <code>value</code>.\r\n *\r\n * @param range the range (<code>null</code> permitted).\r\n * @param value the value that must be included.\r\n *\r\n * @return A range.\r\n *\r\n * @since 1.0.1\r\n */\r\n public static Range expandToInclude(Range range, double value) {\r\n if (range == null) {\r\n return new Range(value, value);\r\n }\r\n if (value < range.getLowerBound()) {\r\n return new Range(value, range.getUpperBound());\r\n }\r\n else if (value > range.getUpperBound()) {\r\n return new Range(range.getLowerBound(), value);\r\n }\r\n else {\r\n return range;\r\n }\r\n }\r\n\r\n /**\r\n * Creates a new range by adding margins to an existing range.\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n * @param lowerMargin the lower margin (expressed as a percentage of the\r\n * range length).\r\n * @param upperMargin the upper margin (expressed as a percentage of the\r\n * range length).\r\n *\r\n * @return The expanded range.\r\n */\r\n public static Range expand(Range range,\r\n double lowerMargin, double upperMargin) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n double length = range.getLength();\r\n double lower = range.getLowerBound() - length * lowerMargin;\r\n double upper = range.getUpperBound() + length * upperMargin;\r\n if (lower > upper) {\r\n lower = lower / 2.0 + upper / 2.0;\r\n upper = lower;\r\n }\r\n return new Range(lower, upper);\r\n }\r\n\r\n /**\r\n * Shifts the range by the specified amount.\r\n *\r\n * @param base the base range (<code>null</code> not permitted).\r\n * @param delta the shift amount.\r\n *\r\n * @return A new range.\r\n */\r\n public static Range shift(Range base, double delta) {\r\n return shift(base, delta, false);\r\n }\r\n\r\n /**\r\n * Shifts the range by the specified amount.\r\n *\r\n * @param base the base range (<code>null</code> not permitted).\r\n * @param delta the shift amount.\r\n * @param allowZeroCrossing a flag that determines whether or not the\r\n * bounds of the range are allowed to cross\r\n * zero after adjustment.\r\n *\r\n * @return A new range.\r\n */\r\n public static Range shift(Range base, double delta,\r\n boolean allowZeroCrossing) {\r\n ParamChecks.nullNotPermitted(base, \"base\");\r\n if (allowZeroCrossing) {\r\n return new Range(base.getLowerBound() + delta,\r\n base.getUpperBound() + delta);\r\n }\r\n else {\r\n return new Range(shiftWithNoZeroCrossing(base.getLowerBound(),\r\n delta), shiftWithNoZeroCrossing(base.getUpperBound(),\r\n delta));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the given <code>value</code> adjusted by <code>delta</code> but\r\n * with a check to prevent the result from crossing <code>0.0</code>.\r\n *\r\n * @param value the value.\r\n * @param delta the adjustment.\r\n *\r\n * @return The adjusted value.\r\n */\r\n private static double shiftWithNoZeroCrossing(double value, double delta) {\r\n if (value > 0.0) {\r\n return Math.max(value + delta, 0.0);\r\n }\r\n else if (value < 0.0) {\r\n return Math.min(value + delta, 0.0);\r\n }\r\n else {\r\n return value + delta;\r\n }\r\n }\r\n\r\n /**\r\n * Scales the range by the specified factor.\r\n *\r\n * @param base the base range (<code>null</code> not permitted).\r\n * @param factor the scaling factor (must be non-negative).\r\n *\r\n * @return A new range.\r\n *\r\n * @since 1.0.9\r\n */\r\n public static Range scale(Range base, double factor) {\r\n ParamChecks.nullNotPermitted(base, \"base\");\r\n if (factor < 0) {\r\n throw new IllegalArgumentException(\"Negative 'factor' argument.\");\r\n }\r\n return new Range(base.getLowerBound() * factor,\r\n base.getUpperBound() * factor);\r\n }\r\n\r\n /**\r\n * Tests this object for equality with an arbitrary object.\r\n *\r\n * @param obj the object to test against (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (!(obj instanceof Range)) {\r\n return false;\r\n }\r\n Range range = (Range) obj;\r\n if (!(this.lower == range.lower)) {\r\n return false;\r\n }\r\n if (!(this.upper == range.upper)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if both the lower and upper bounds are \r\n * <code>Double.NaN</code>, and <code>false</code> otherwise.\r\n * \r\n * @return A boolean.\r\n * \r\n * @since 1.0.18\r\n */\r\n public boolean isNaNRange() {\r\n return Double.isNaN(this.lower) && Double.isNaN(this.upper);\r\n }\r\n \r\n /**\r\n * Returns a hash code.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result;\r\n long temp;\r\n temp = Double.doubleToLongBits(this.lower);\r\n result = (int) (temp ^ (temp >>> 32));\r\n temp = Double.doubleToLongBits(this.upper);\r\n result = 29 * result + (int) (temp ^ (temp >>> 32));\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a string representation of this Range.\r\n *\r\n * @return A String \"Range[lower,upper]\" where lower=lower range and\r\n * upper=upper range.\r\n */\r\n @Override\r\n public String toString() {\r\n return (\"Range[\" + this.lower + \",\" + this.upper + \"]\");\r\n }\r\n\r\n}\r" }, { "identifier": "DefaultIntervalCategoryDataset", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/category/DefaultIntervalCategoryDataset.java", "snippet": "public class DefaultIntervalCategoryDataset extends AbstractSeriesDataset\r\n implements IntervalCategoryDataset {\r\n\r\n /** The series keys. */\r\n private Comparable[] seriesKeys;\r\n\r\n /** The category keys. */\r\n private Comparable[] categoryKeys;\r\n\r\n /** Storage for the start value data. */\r\n private Number[][] startData;\r\n\r\n /** Storage for the end value data. */\r\n private Number[][] endData;\r\n\r\n /**\r\n * Creates a new dataset using the specified data values and automatically\r\n * generated series and category keys.\r\n *\r\n * @param starts the starting values for the intervals (<code>null</code>\r\n * not permitted).\r\n * @param ends the ending values for the intervals (<code>null</code> not\r\n * permitted).\r\n */\r\n public DefaultIntervalCategoryDataset(double[][] starts, double[][] ends) {\r\n this(DataUtilities.createNumberArray2D(starts),\r\n DataUtilities.createNumberArray2D(ends));\r\n }\r\n\r\n /**\r\n * Constructs a dataset and populates it with data from the array.\r\n * <p>\r\n * The arrays are indexed as data[series][category]. Series and category\r\n * names are automatically generated - you can change them using the\r\n * {@link #setSeriesKeys(Comparable[])} and\r\n * {@link #setCategoryKeys(Comparable[])} methods.\r\n *\r\n * @param starts the start values data.\r\n * @param ends the end values data.\r\n */\r\n public DefaultIntervalCategoryDataset(Number[][] starts, Number[][] ends) {\r\n this(null, null, starts, ends);\r\n }\r\n\r\n /**\r\n * Constructs a DefaultIntervalCategoryDataset, populates it with data\r\n * from the arrays, and uses the supplied names for the series.\r\n * <p>\r\n * Category names are generated automatically (\"Category 1\", \"Category 2\",\r\n * etc).\r\n *\r\n * @param seriesNames the series names (if <code>null</code>, series names\r\n * will be generated automatically).\r\n * @param starts the start values data, indexed as data[series][category].\r\n * @param ends the end values data, indexed as data[series][category].\r\n */\r\n public DefaultIntervalCategoryDataset(String[] seriesNames,\r\n Number[][] starts,\r\n Number[][] ends) {\r\n\r\n this(seriesNames, null, starts, ends);\r\n\r\n }\r\n\r\n /**\r\n * Constructs a DefaultIntervalCategoryDataset, populates it with data\r\n * from the arrays, and uses the supplied names for the series and the\r\n * supplied objects for the categories.\r\n *\r\n * @param seriesKeys the series keys (if <code>null</code>, series keys\r\n * will be generated automatically).\r\n * @param categoryKeys the category keys (if <code>null</code>, category\r\n * keys will be generated automatically).\r\n * @param starts the start values data, indexed as data[series][category].\r\n * @param ends the end values data, indexed as data[series][category].\r\n */\r\n public DefaultIntervalCategoryDataset(Comparable[] seriesKeys,\r\n Comparable[] categoryKeys,\r\n Number[][] starts,\r\n Number[][] ends) {\r\n\r\n this.startData = starts;\r\n this.endData = ends;\r\n\r\n if (starts != null && ends != null) {\r\n\r\n String baseName = \"org.jfree.data.resources.DataPackageResources\";\r\n ResourceBundle resources = ResourceBundleWrapper.getBundle(\r\n baseName);\r\n\r\n int seriesCount = starts.length;\r\n if (seriesCount != ends.length) {\r\n String errMsg = \"DefaultIntervalCategoryDataset: the number \"\r\n + \"of series in the start value dataset does \"\r\n + \"not match the number of series in the end \"\r\n + \"value dataset.\";\r\n throw new IllegalArgumentException(errMsg);\r\n }\r\n if (seriesCount > 0) {\r\n\r\n // set up the series names...\r\n if (seriesKeys != null) {\r\n\r\n if (seriesKeys.length != seriesCount) {\r\n throw new IllegalArgumentException(\r\n \"The number of series keys does not \"\r\n + \"match the number of series in the data.\");\r\n }\r\n\r\n this.seriesKeys = seriesKeys;\r\n }\r\n else {\r\n String prefix = resources.getString(\r\n \"series.default-prefix\") + \" \";\r\n this.seriesKeys = generateKeys(seriesCount, prefix);\r\n }\r\n\r\n // set up the category names...\r\n int categoryCount = starts[0].length;\r\n if (categoryCount != ends[0].length) {\r\n String errMsg = \"DefaultIntervalCategoryDataset: the \"\r\n + \"number of categories in the start value \"\r\n + \"dataset does not match the number of \"\r\n + \"categories in the end value dataset.\";\r\n throw new IllegalArgumentException(errMsg);\r\n }\r\n if (categoryKeys != null) {\r\n if (categoryKeys.length != categoryCount) {\r\n throw new IllegalArgumentException(\r\n \"The number of category keys does not match \"\r\n + \"the number of categories in the data.\");\r\n }\r\n this.categoryKeys = categoryKeys;\r\n }\r\n else {\r\n String prefix = resources.getString(\r\n \"categories.default-prefix\") + \" \";\r\n this.categoryKeys = generateKeys(categoryCount, prefix);\r\n }\r\n\r\n }\r\n else {\r\n this.seriesKeys = new Comparable[0];\r\n this.categoryKeys = new Comparable[0];\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the number of series in the dataset (possibly zero).\r\n *\r\n * @return The number of series in the dataset.\r\n *\r\n * @see #getRowCount()\r\n * @see #getCategoryCount()\r\n */\r\n @Override\r\n public int getSeriesCount() {\r\n int result = 0;\r\n if (this.startData != null) {\r\n result = this.startData.length;\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a series index.\r\n *\r\n * @param seriesKey the series key.\r\n *\r\n * @return The series index.\r\n *\r\n * @see #getRowIndex(Comparable)\r\n * @see #getSeriesKey(int)\r\n */\r\n public int getSeriesIndex(Comparable seriesKey) {\r\n int result = -1;\r\n for (int i = 0; i < this.seriesKeys.length; i++) {\r\n if (seriesKey.equals(this.seriesKeys[i])) {\r\n result = i;\r\n break;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the name of the specified series.\r\n *\r\n * @param series the index of the required series (zero-based).\r\n *\r\n * @return The name of the specified series.\r\n *\r\n * @see #getSeriesIndex(Comparable)\r\n */\r\n @Override\r\n public Comparable getSeriesKey(int series) {\r\n if ((series >= getSeriesCount()) || (series < 0)) {\r\n throw new IllegalArgumentException(\"No such series : \" + series);\r\n }\r\n return this.seriesKeys[series];\r\n }\r\n\r\n /**\r\n * Sets the names of the series in the dataset.\r\n *\r\n * @param seriesKeys the new keys (<code>null</code> not permitted, the\r\n * length of the array must match the number of series in the\r\n * dataset).\r\n *\r\n * @see #setCategoryKeys(Comparable[])\r\n */\r\n public void setSeriesKeys(Comparable[] seriesKeys) {\r\n ParamChecks.nullNotPermitted(seriesKeys, \"seriesKeys\");\r\n if (seriesKeys.length != getSeriesCount()) {\r\n throw new IllegalArgumentException(\r\n \"The number of series keys does not match the data.\");\r\n }\r\n this.seriesKeys = seriesKeys;\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns the number of categories in the dataset.\r\n *\r\n * @return The number of categories in the dataset.\r\n *\r\n * @see #getColumnCount()\r\n */\r\n public int getCategoryCount() {\r\n int result = 0;\r\n if (this.startData != null) {\r\n if (getSeriesCount() > 0) {\r\n result = this.startData[0].length;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a list of the categories in the dataset. This method supports\r\n * the {@link CategoryDataset} interface.\r\n *\r\n * @return A list of the categories in the dataset.\r\n *\r\n * @see #getRowKeys()\r\n */\r\n @Override\r\n public List getColumnKeys() {\r\n // the CategoryDataset interface expects a list of categories, but\r\n // we've stored them in an array...\r\n if (this.categoryKeys == null) {\r\n return new ArrayList();\r\n }\r\n else {\r\n return Collections.unmodifiableList(Arrays.asList(\r\n this.categoryKeys));\r\n }\r\n }\r\n\r\n /**\r\n * Sets the categories for the dataset.\r\n *\r\n * @param categoryKeys an array of objects representing the categories in\r\n * the dataset.\r\n *\r\n * @see #getRowKeys()\r\n * @see #setSeriesKeys(Comparable[])\r\n */\r\n public void setCategoryKeys(Comparable[] categoryKeys) {\r\n ParamChecks.nullNotPermitted(categoryKeys, \"categoryKeys\");\r\n if (categoryKeys.length != getCategoryCount()) {\r\n throw new IllegalArgumentException(\r\n \"The number of categories does not match the data.\");\r\n }\r\n for (int i = 0; i < categoryKeys.length; i++) {\r\n if (categoryKeys[i] == null) {\r\n throw new IllegalArgumentException(\r\n \"DefaultIntervalCategoryDataset.setCategoryKeys(): \"\r\n + \"null category not permitted.\");\r\n }\r\n }\r\n this.categoryKeys = categoryKeys;\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Returns the data value for one category in a series.\r\n * <P>\r\n * This method is part of the CategoryDataset interface. Not particularly\r\n * meaningful for this class...returns the end value.\r\n *\r\n * @param series The required series (zero based index).\r\n * @param category The required category.\r\n *\r\n * @return The data value for one category in a series (null possible).\r\n *\r\n * @see #getEndValue(Comparable, Comparable)\r\n */\r\n @Override\r\n public Number getValue(Comparable series, Comparable category) {\r\n int seriesIndex = getSeriesIndex(series);\r\n if (seriesIndex < 0) {\r\n throw new UnknownKeyException(\"Unknown 'series' key.\");\r\n }\r\n int itemIndex = getColumnIndex(category);\r\n if (itemIndex < 0) {\r\n throw new UnknownKeyException(\"Unknown 'category' key.\");\r\n }\r\n return getValue(seriesIndex, itemIndex);\r\n }\r\n\r\n /**\r\n * Returns the data value for one category in a series.\r\n * <P>\r\n * This method is part of the CategoryDataset interface. Not particularly\r\n * meaningful for this class...returns the end value.\r\n *\r\n * @param series the required series (zero based index).\r\n * @param category the required category.\r\n *\r\n * @return The data value for one category in a series (null possible).\r\n *\r\n * @see #getEndValue(int, int)\r\n */\r\n @Override\r\n public Number getValue(int series, int category) {\r\n return getEndValue(series, category);\r\n }\r\n\r\n /**\r\n * Returns the start data value for one category in a series.\r\n *\r\n * @param series the required series.\r\n * @param category the required category.\r\n *\r\n * @return The start data value for one category in a series\r\n * (possibly <code>null</code>).\r\n *\r\n * @see #getStartValue(int, int)\r\n */\r\n @Override\r\n public Number getStartValue(Comparable series, Comparable category) {\r\n int seriesIndex = getSeriesIndex(series);\r\n if (seriesIndex < 0) {\r\n throw new UnknownKeyException(\"Unknown 'series' key.\");\r\n }\r\n int itemIndex = getColumnIndex(category);\r\n if (itemIndex < 0) {\r\n throw new UnknownKeyException(\"Unknown 'category' key.\");\r\n }\r\n return getStartValue(seriesIndex, itemIndex);\r\n }\r\n\r\n /**\r\n * Returns the start data value for one category in a series.\r\n *\r\n * @param series the required series (zero based index).\r\n * @param category the required category.\r\n *\r\n * @return The start data value for one category in a series\r\n * (possibly <code>null</code>).\r\n *\r\n * @see #getStartValue(Comparable, Comparable)\r\n */\r\n @Override\r\n public Number getStartValue(int series, int category) {\r\n\r\n // check arguments...\r\n if ((series < 0) || (series >= getSeriesCount())) {\r\n throw new IllegalArgumentException(\r\n \"DefaultIntervalCategoryDataset.getValue(): \"\r\n + \"series index out of range.\");\r\n }\r\n\r\n if ((category < 0) || (category >= getCategoryCount())) {\r\n throw new IllegalArgumentException(\r\n \"DefaultIntervalCategoryDataset.getValue(): \"\r\n + \"category index out of range.\");\r\n }\r\n\r\n // fetch the value...\r\n return this.startData[series][category];\r\n\r\n }\r\n\r\n /**\r\n * Returns the end data value for one category in a series.\r\n *\r\n * @param series the required series.\r\n * @param category the required category.\r\n *\r\n * @return The end data value for one category in a series (null possible).\r\n *\r\n * @see #getEndValue(int, int)\r\n */\r\n @Override\r\n public Number getEndValue(Comparable series, Comparable category) {\r\n int seriesIndex = getSeriesIndex(series);\r\n if (seriesIndex < 0) {\r\n throw new UnknownKeyException(\"Unknown 'series' key.\");\r\n }\r\n int itemIndex = getColumnIndex(category);\r\n if (itemIndex < 0) {\r\n throw new UnknownKeyException(\"Unknown 'category' key.\");\r\n }\r\n return getEndValue(seriesIndex, itemIndex);\r\n }\r\n\r\n /**\r\n * Returns the end data value for one category in a series.\r\n *\r\n * @param series the required series (zero based index).\r\n * @param category the required category.\r\n *\r\n * @return The end data value for one category in a series (null possible).\r\n *\r\n * @see #getEndValue(Comparable, Comparable)\r\n */\r\n @Override\r\n public Number getEndValue(int series, int category) {\r\n if ((series < 0) || (series >= getSeriesCount())) {\r\n throw new IllegalArgumentException(\r\n \"DefaultIntervalCategoryDataset.getValue(): \"\r\n + \"series index out of range.\");\r\n }\r\n\r\n if ((category < 0) || (category >= getCategoryCount())) {\r\n throw new IllegalArgumentException(\r\n \"DefaultIntervalCategoryDataset.getValue(): \"\r\n + \"category index out of range.\");\r\n }\r\n\r\n return this.endData[series][category];\r\n }\r\n\r\n /**\r\n * Sets the start data value for one category in a series.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param category the category.\r\n *\r\n * @param value The value.\r\n *\r\n * @see #setEndValue(int, Comparable, Number)\r\n */\r\n public void setStartValue(int series, Comparable category, Number value) {\r\n\r\n // does the series exist?\r\n if ((series < 0) || (series > getSeriesCount() - 1)) {\r\n throw new IllegalArgumentException(\r\n \"DefaultIntervalCategoryDataset.setValue: \"\r\n + \"series outside valid range.\");\r\n }\r\n\r\n // is the category valid?\r\n int categoryIndex = getCategoryIndex(category);\r\n if (categoryIndex < 0) {\r\n throw new IllegalArgumentException(\r\n \"DefaultIntervalCategoryDataset.setValue: \"\r\n + \"unrecognised category.\");\r\n }\r\n\r\n // update the data...\r\n this.startData[series][categoryIndex] = value;\r\n fireDatasetChanged();\r\n\r\n }\r\n\r\n /**\r\n * Sets the end data value for one category in a series.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param category the category.\r\n *\r\n * @param value the value.\r\n *\r\n * @see #setStartValue(int, Comparable, Number)\r\n */\r\n public void setEndValue(int series, Comparable category, Number value) {\r\n\r\n // does the series exist?\r\n if ((series < 0) || (series > getSeriesCount() - 1)) {\r\n throw new IllegalArgumentException(\r\n \"DefaultIntervalCategoryDataset.setValue: \"\r\n + \"series outside valid range.\");\r\n }\r\n\r\n // is the category valid?\r\n int categoryIndex = getCategoryIndex(category);\r\n if (categoryIndex < 0) {\r\n throw new IllegalArgumentException(\r\n \"DefaultIntervalCategoryDataset.setValue: \"\r\n + \"unrecognised category.\");\r\n }\r\n\r\n // update the data...\r\n this.endData[series][categoryIndex] = value;\r\n fireDatasetChanged();\r\n\r\n }\r\n\r\n /**\r\n * Returns the index for the given category.\r\n *\r\n * @param category the category (<code>null</code> not permitted).\r\n *\r\n * @return The index.\r\n *\r\n * @see #getColumnIndex(Comparable)\r\n */\r\n public int getCategoryIndex(Comparable category) {\r\n int result = -1;\r\n for (int i = 0; i < this.categoryKeys.length; i++) {\r\n if (category.equals(this.categoryKeys[i])) {\r\n result = i;\r\n break;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Generates an array of keys, by appending a space plus an integer\r\n * (starting with 1) to the supplied prefix string.\r\n *\r\n * @param count the number of keys required.\r\n * @param prefix the name prefix.\r\n *\r\n * @return An array of <i>prefixN</i> with N = { 1 .. count}.\r\n */\r\n private Comparable[] generateKeys(int count, String prefix) {\r\n Comparable[] result = new Comparable[count];\r\n String name;\r\n for (int i = 0; i < count; i++) {\r\n name = prefix + (i + 1);\r\n result[i] = name;\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a column key.\r\n *\r\n * @param column the column index.\r\n *\r\n * @return The column key.\r\n *\r\n * @see #getRowKey(int)\r\n */\r\n @Override\r\n public Comparable getColumnKey(int column) {\r\n return this.categoryKeys[column];\r\n }\r\n\r\n /**\r\n * Returns a column index.\r\n *\r\n * @param columnKey the column key (<code>null</code> not permitted).\r\n *\r\n * @return The column index.\r\n *\r\n * @see #getCategoryIndex(Comparable)\r\n */\r\n @Override\r\n public int getColumnIndex(Comparable columnKey) {\r\n ParamChecks.nullNotPermitted(columnKey, \"columnKey\");\r\n return getCategoryIndex(columnKey);\r\n }\r\n\r\n /**\r\n * Returns a row index.\r\n *\r\n * @param rowKey the row key.\r\n *\r\n * @return The row index.\r\n *\r\n * @see #getSeriesIndex(Comparable)\r\n */\r\n @Override\r\n public int getRowIndex(Comparable rowKey) {\r\n return getSeriesIndex(rowKey);\r\n }\r\n\r\n /**\r\n * Returns a list of the series in the dataset. This method supports the\r\n * {@link CategoryDataset} interface.\r\n *\r\n * @return A list of the series in the dataset.\r\n *\r\n * @see #getColumnKeys()\r\n */\r\n @Override\r\n public List getRowKeys() {\r\n // the CategoryDataset interface expects a list of series, but\r\n // we've stored them in an array...\r\n if (this.seriesKeys == null) {\r\n return new java.util.ArrayList();\r\n }\r\n else {\r\n return Collections.unmodifiableList(Arrays.asList(this.seriesKeys));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the name of the specified series.\r\n *\r\n * @param row the index of the required row/series (zero-based).\r\n *\r\n * @return The name of the specified series.\r\n *\r\n * @see #getColumnKey(int)\r\n */\r\n @Override\r\n public Comparable getRowKey(int row) {\r\n if ((row >= getRowCount()) || (row < 0)) {\r\n throw new IllegalArgumentException(\r\n \"The 'row' argument is out of bounds.\");\r\n }\r\n return this.seriesKeys[row];\r\n }\r\n\r\n /**\r\n * Returns the number of categories in the dataset. This method is part of\r\n * the {@link CategoryDataset} interface.\r\n *\r\n * @return The number of categories in the dataset.\r\n *\r\n * @see #getCategoryCount()\r\n * @see #getRowCount()\r\n */\r\n @Override\r\n public int getColumnCount() {\r\n return this.categoryKeys.length;\r\n }\r\n\r\n /**\r\n * Returns the number of series in the dataset (possibly zero).\r\n *\r\n * @return The number of series in the dataset.\r\n *\r\n * @see #getSeriesCount()\r\n * @see #getColumnCount()\r\n */\r\n @Override\r\n public int getRowCount() {\r\n return this.seriesKeys.length;\r\n }\r\n\r\n /**\r\n * Tests this dataset for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof DefaultIntervalCategoryDataset)) {\r\n return false;\r\n }\r\n DefaultIntervalCategoryDataset that\r\n = (DefaultIntervalCategoryDataset) obj;\r\n if (!Arrays.equals(this.seriesKeys, that.seriesKeys)) {\r\n return false;\r\n }\r\n if (!Arrays.equals(this.categoryKeys, that.categoryKeys)) {\r\n return false;\r\n }\r\n if (!equal(this.startData, that.startData)) {\r\n return false;\r\n }\r\n if (!equal(this.endData, that.endData)) {\r\n return false;\r\n }\r\n // seem to be the same...\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a clone of this dataset.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if there is a problem cloning the\r\n * dataset.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n DefaultIntervalCategoryDataset clone\r\n = (DefaultIntervalCategoryDataset) super.clone();\r\n clone.categoryKeys = (Comparable[]) this.categoryKeys.clone();\r\n clone.seriesKeys = (Comparable[]) this.seriesKeys.clone();\r\n clone.startData = clone(this.startData);\r\n clone.endData = clone(this.endData);\r\n return clone;\r\n }\r\n\r\n /**\r\n * Tests two double[][] arrays for equality.\r\n *\r\n * @param array1 the first array (<code>null</code> permitted).\r\n * @param array2 the second arrray (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n private static boolean equal(Number[][] array1, Number[][] array2) {\r\n if (array1 == null) {\r\n return (array2 == null);\r\n }\r\n if (array2 == null) {\r\n return false;\r\n }\r\n if (array1.length != array2.length) {\r\n return false;\r\n }\r\n for (int i = 0; i < array1.length; i++) {\r\n if (!Arrays.equals(array1[i], array2[i])) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Clones a two dimensional array of <code>Number</code> objects.\r\n *\r\n * @param array the array (<code>null</code> not permitted).\r\n *\r\n * @return A clone of the array.\r\n */\r\n private static Number[][] clone(Number[][] array) {\r\n ParamChecks.nullNotPermitted(array, \"array\");\r\n Number[][] result = new Number[array.length][];\r\n for (int i = 0; i < array.length; i++) {\r\n Number[] child = array[i];\r\n Number[] copychild = new Number[child.length];\r\n System.arraycopy(child, 0, copychild, 0, child.length);\r\n result[i] = copychild;\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a list of the series in the dataset.\r\n *\r\n * @return A list of the series in the dataset.\r\n *\r\n * @deprecated Use {@link #getRowKeys()} instead.\r\n */\r\n public List getSeries() {\r\n if (this.seriesKeys == null) {\r\n return new java.util.ArrayList();\r\n }\r\n else {\r\n return Collections.unmodifiableList(Arrays.asList(this.seriesKeys));\r\n }\r\n }\r\n\r\n /**\r\n * Returns a list of the categories in the dataset.\r\n *\r\n * @return A list of the categories in the dataset.\r\n *\r\n * @deprecated Use {@link #getColumnKeys()} instead.\r\n */\r\n public List getCategories() {\r\n return getColumnKeys();\r\n }\r\n\r\n /**\r\n * Returns the item count.\r\n *\r\n * @return The item count.\r\n *\r\n * @deprecated Use {@link #getCategoryCount()} instead.\r\n */\r\n public int getItemCount() {\r\n return this.categoryKeys.length;\r\n }\r\n\r\n}\r" } ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import org.jfree.chart.JFreeChart; import org.jfree.chart.TestUtilities; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.data.Range; import org.jfree.data.category.DefaultIntervalCategoryDataset; import org.jfree.util.PublicCloneable; import org.junit.Test;
84,557
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------------- * IntervalBarRendererTest.java * ---------------------------- * (C) Copyright 2003-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 25-Mar-2003 : Version 1 (DG); * 23-Apr-2008 : Added testPublicCloneable (DG); * 16-May-2009 : Added testFindRangeBounds() (DG); * */ package org.jfree.chart.renderer.category; /** * Tests for the {@link IntervalBarRenderer} class. */ public class IntervalBarRendererTest { /** * Problem that the equals() method distinguishes all fields. */ @Test public void testEquals() { IntervalBarRenderer r1 = new IntervalBarRenderer(); IntervalBarRenderer r2 = new IntervalBarRenderer(); assertEquals(r1, r2); // the renderer should not be equal to a BarRenderer BarRenderer br = new BarRenderer(); assertFalse(r1.equals(br)); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashcode() { IntervalBarRenderer r1 = new IntervalBarRenderer(); IntervalBarRenderer r2 = new IntervalBarRenderer(); assertTrue(r1.equals(r2)); int h1 = r1.hashCode(); int h2 = r2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { IntervalBarRenderer r1 = new IntervalBarRenderer(); IntervalBarRenderer r2 = (IntervalBarRenderer) r1.clone(); assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); } /** * Check that this class implements PublicCloneable. */ @Test public void testPublicCloneable() { IntervalBarRenderer r1 = new IntervalBarRenderer(); assertTrue(r1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { IntervalBarRenderer r1 = new IntervalBarRenderer(); IntervalBarRenderer r2 = (IntervalBarRenderer) TestUtilities.serialised(r1); assertEquals(r1, r2); } /** * Draws the chart with a <code>null</code> info object to make sure that * no exceptions are thrown (particularly by code in the renderer). */ @Test public void testDrawWithNullInfo() { try { double[][] starts = new double[][] {{0.1, 0.2, 0.3}, {0.3, 0.4, 0.5}}; double[][] ends = new double[][] {{0.5, 0.6, 0.7}, {0.7, 0.8, 0.9}}; DefaultIntervalCategoryDataset dataset = new DefaultIntervalCategoryDataset(starts, ends); IntervalBarRenderer renderer = new IntervalBarRenderer(); CategoryPlot plot = new CategoryPlot(dataset,
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------------- * IntervalBarRendererTest.java * ---------------------------- * (C) Copyright 2003-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 25-Mar-2003 : Version 1 (DG); * 23-Apr-2008 : Added testPublicCloneable (DG); * 16-May-2009 : Added testFindRangeBounds() (DG); * */ package org.jfree.chart.renderer.category; /** * Tests for the {@link IntervalBarRenderer} class. */ public class IntervalBarRendererTest { /** * Problem that the equals() method distinguishes all fields. */ @Test public void testEquals() { IntervalBarRenderer r1 = new IntervalBarRenderer(); IntervalBarRenderer r2 = new IntervalBarRenderer(); assertEquals(r1, r2); // the renderer should not be equal to a BarRenderer BarRenderer br = new BarRenderer(); assertFalse(r1.equals(br)); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashcode() { IntervalBarRenderer r1 = new IntervalBarRenderer(); IntervalBarRenderer r2 = new IntervalBarRenderer(); assertTrue(r1.equals(r2)); int h1 = r1.hashCode(); int h2 = r2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { IntervalBarRenderer r1 = new IntervalBarRenderer(); IntervalBarRenderer r2 = (IntervalBarRenderer) r1.clone(); assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); } /** * Check that this class implements PublicCloneable. */ @Test public void testPublicCloneable() { IntervalBarRenderer r1 = new IntervalBarRenderer(); assertTrue(r1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { IntervalBarRenderer r1 = new IntervalBarRenderer(); IntervalBarRenderer r2 = (IntervalBarRenderer) TestUtilities.serialised(r1); assertEquals(r1, r2); } /** * Draws the chart with a <code>null</code> info object to make sure that * no exceptions are thrown (particularly by code in the renderer). */ @Test public void testDrawWithNullInfo() { try { double[][] starts = new double[][] {{0.1, 0.2, 0.3}, {0.3, 0.4, 0.5}}; double[][] ends = new double[][] {{0.5, 0.6, 0.7}, {0.7, 0.8, 0.9}}; DefaultIntervalCategoryDataset dataset = new DefaultIntervalCategoryDataset(starts, ends); IntervalBarRenderer renderer = new IntervalBarRenderer(); CategoryPlot plot = new CategoryPlot(dataset,
new CategoryAxis("Category"), new NumberAxis("Value"),
3
2023-12-24 12:36:47+00:00
128k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/source/org/jfree/chart/annotations/XYDataImageAnnotation.java
[ { "identifier": "AxisLocation", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/axis/AxisLocation.java", "snippet": "public final class AxisLocation implements Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -3276922179323563410L;\r\n\r\n /** Axis at the top or left. */\r\n public static final AxisLocation TOP_OR_LEFT = new AxisLocation(\r\n \"AxisLocation.TOP_OR_LEFT\");\r\n\r\n /** Axis at the top or right. */\r\n public static final AxisLocation TOP_OR_RIGHT = new AxisLocation(\r\n \"AxisLocation.TOP_OR_RIGHT\");\r\n\r\n /** Axis at the bottom or left. */\r\n public static final AxisLocation BOTTOM_OR_LEFT = new AxisLocation(\r\n \"AxisLocation.BOTTOM_OR_LEFT\");\r\n\r\n /** Axis at the bottom or right. */\r\n public static final AxisLocation BOTTOM_OR_RIGHT = new AxisLocation(\r\n \"AxisLocation.BOTTOM_OR_RIGHT\");\r\n\r\n /** The name. */\r\n private String name;\r\n\r\n /**\r\n * Private constructor.\r\n *\r\n * @param name the name.\r\n */\r\n private AxisLocation(String name) {\r\n this.name = name;\r\n }\r\n\r\n /**\r\n * Returns the location that is opposite to this location.\r\n *\r\n * @return The opposite location.\r\n *\r\n * @since 1.0.5\r\n */\r\n public AxisLocation getOpposite() {\r\n return getOpposite(this);\r\n }\r\n\r\n /**\r\n * Returns a string representing the object.\r\n *\r\n * @return The string.\r\n */\r\n @Override\r\n public String toString() {\r\n return this.name;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this object is equal to the specified\r\n * object, and <code>false</code> otherwise.\r\n *\r\n * @param obj the other object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) {\r\n return true;\r\n }\r\n if (!(obj instanceof AxisLocation)) {\r\n return false;\r\n }\r\n AxisLocation location = (AxisLocation) obj;\r\n if (!this.name.equals(location.toString())) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code for this instance.\r\n * \r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int hash = 5;\r\n hash = 83 * hash + this.name.hashCode();\r\n return hash;\r\n }\r\n\r\n /**\r\n * Returns the location that is opposite to the supplied location.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n *\r\n * @return The opposite location.\r\n */\r\n public static AxisLocation getOpposite(AxisLocation location) {\r\n ParamChecks.nullNotPermitted(location, \"location\");\r\n AxisLocation result = null;\r\n if (location == AxisLocation.TOP_OR_LEFT) {\r\n result = AxisLocation.BOTTOM_OR_RIGHT;\r\n }\r\n else if (location == AxisLocation.TOP_OR_RIGHT) {\r\n result = AxisLocation.BOTTOM_OR_LEFT;\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_LEFT) {\r\n result = AxisLocation.TOP_OR_RIGHT;\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_RIGHT) {\r\n result = AxisLocation.TOP_OR_LEFT;\r\n }\r\n else {\r\n throw new IllegalStateException(\"AxisLocation not recognised.\");\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Ensures that serialization returns the unique instances.\r\n *\r\n * @return The object.\r\n *\r\n * @throws ObjectStreamException if there is a problem.\r\n */\r\n private Object readResolve() throws ObjectStreamException {\r\n if (this.equals(AxisLocation.TOP_OR_RIGHT)) {\r\n return AxisLocation.TOP_OR_RIGHT;\r\n }\r\n else if (this.equals(AxisLocation.BOTTOM_OR_RIGHT)) {\r\n return AxisLocation.BOTTOM_OR_RIGHT;\r\n }\r\n else if (this.equals(AxisLocation.TOP_OR_LEFT)) {\r\n return AxisLocation.TOP_OR_LEFT;\r\n }\r\n else if (this.equals(AxisLocation.BOTTOM_OR_LEFT)) {\r\n return AxisLocation.BOTTOM_OR_LEFT;\r\n }\r\n return null;\r\n }\r\n\r\n}\r" }, { "identifier": "ValueAxis", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/axis/ValueAxis.java", "snippet": "public abstract class ValueAxis extends Axis\r\n implements Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 3698345477322391456L;\r\n\r\n /** The default axis range. */\r\n public static final Range DEFAULT_RANGE = new Range(0.0, 1.0);\r\n\r\n /** The default auto-range value. */\r\n public static final boolean DEFAULT_AUTO_RANGE = true;\r\n\r\n /** The default inverted flag setting. */\r\n public static final boolean DEFAULT_INVERTED = false;\r\n\r\n /** The default minimum auto range. */\r\n public static final double DEFAULT_AUTO_RANGE_MINIMUM_SIZE = 0.00000001;\r\n\r\n /** The default value for the lower margin (0.05 = 5%). */\r\n public static final double DEFAULT_LOWER_MARGIN = 0.05;\r\n\r\n /** The default value for the upper margin (0.05 = 5%). */\r\n public static final double DEFAULT_UPPER_MARGIN = 0.05;\r\n\r\n /**\r\n * The default lower bound for the axis.\r\n *\r\n * @deprecated From 1.0.5 onwards, the axis defines a defaultRange\r\n * attribute (see {@link #getDefaultAutoRange()}).\r\n */\r\n public static final double DEFAULT_LOWER_BOUND = 0.0;\r\n\r\n /**\r\n * The default upper bound for the axis.\r\n *\r\n * @deprecated From 1.0.5 onwards, the axis defines a defaultRange\r\n * attribute (see {@link #getDefaultAutoRange()}).\r\n */\r\n public static final double DEFAULT_UPPER_BOUND = 1.0;\r\n\r\n /** The default auto-tick-unit-selection value. */\r\n public static final boolean DEFAULT_AUTO_TICK_UNIT_SELECTION = true;\r\n\r\n /** The maximum tick count. */\r\n public static final int MAXIMUM_TICK_COUNT = 500;\r\n\r\n /**\r\n * A flag that controls whether an arrow is drawn at the positive end of\r\n * the axis line.\r\n */\r\n private boolean positiveArrowVisible;\r\n\r\n /**\r\n * A flag that controls whether an arrow is drawn at the negative end of\r\n * the axis line.\r\n */\r\n private boolean negativeArrowVisible;\r\n\r\n /** The shape used for an up arrow. */\r\n private transient Shape upArrow;\r\n\r\n /** The shape used for a down arrow. */\r\n private transient Shape downArrow;\r\n\r\n /** The shape used for a left arrow. */\r\n private transient Shape leftArrow;\r\n\r\n /** The shape used for a right arrow. */\r\n private transient Shape rightArrow;\r\n\r\n /** A flag that affects the orientation of the values on the axis. */\r\n private boolean inverted;\r\n\r\n /** The axis range. */\r\n private Range range;\r\n\r\n /**\r\n * Flag that indicates whether the axis automatically scales to fit the\r\n * chart data.\r\n */\r\n private boolean autoRange;\r\n\r\n /** The minimum size for the 'auto' axis range (excluding margins). */\r\n private double autoRangeMinimumSize;\r\n\r\n /**\r\n * The default range is used when the dataset is empty and the axis needs\r\n * to determine the auto range.\r\n *\r\n * @since 1.0.5\r\n */\r\n private Range defaultAutoRange;\r\n\r\n /**\r\n * The upper margin percentage. This indicates the amount by which the\r\n * maximum axis value exceeds the maximum data value (as a percentage of\r\n * the range on the axis) when the axis range is determined automatically.\r\n */\r\n private double upperMargin;\r\n\r\n /**\r\n * The lower margin. This is a percentage that indicates the amount by\r\n * which the minimum axis value is \"less than\" the minimum data value when\r\n * the axis range is determined automatically.\r\n */\r\n private double lowerMargin;\r\n\r\n /**\r\n * If this value is positive, the amount is subtracted from the maximum\r\n * data value to determine the lower axis range. This can be used to\r\n * provide a fixed \"window\" on dynamic data.\r\n */\r\n private double fixedAutoRange;\r\n\r\n /**\r\n * Flag that indicates whether or not the tick unit is selected\r\n * automatically.\r\n */\r\n private boolean autoTickUnitSelection;\r\n\r\n /** The standard tick units for the axis. */\r\n private TickUnitSource standardTickUnits;\r\n\r\n /** An index into an array of standard tick values. */\r\n private int autoTickIndex;\r\n\r\n /**\r\n * The number of minor ticks per major tick unit. This is an override\r\n * field, if the value is &gt; 0 it is used, otherwise the axis refers to the\r\n * minorTickCount in the current tickUnit.\r\n */\r\n private int minorTickCount;\r\n\r\n /** A flag indicating whether or not tick labels are rotated to vertical. */\r\n private boolean verticalTickLabels;\r\n\r\n /**\r\n * Constructs a value axis.\r\n *\r\n * @param label the axis label (<code>null</code> permitted).\r\n * @param standardTickUnits the source for standard tick units\r\n * (<code>null</code> permitted).\r\n */\r\n protected ValueAxis(String label, TickUnitSource standardTickUnits) {\r\n\r\n super(label);\r\n\r\n this.positiveArrowVisible = false;\r\n this.negativeArrowVisible = false;\r\n\r\n this.range = DEFAULT_RANGE;\r\n this.autoRange = DEFAULT_AUTO_RANGE;\r\n this.defaultAutoRange = DEFAULT_RANGE;\r\n\r\n this.inverted = DEFAULT_INVERTED;\r\n this.autoRangeMinimumSize = DEFAULT_AUTO_RANGE_MINIMUM_SIZE;\r\n\r\n this.lowerMargin = DEFAULT_LOWER_MARGIN;\r\n this.upperMargin = DEFAULT_UPPER_MARGIN;\r\n\r\n this.fixedAutoRange = 0.0;\r\n\r\n this.autoTickUnitSelection = DEFAULT_AUTO_TICK_UNIT_SELECTION;\r\n this.standardTickUnits = standardTickUnits;\r\n\r\n Polygon p1 = new Polygon();\r\n p1.addPoint(0, 0);\r\n p1.addPoint(-2, 2);\r\n p1.addPoint(2, 2);\r\n\r\n this.upArrow = p1;\r\n\r\n Polygon p2 = new Polygon();\r\n p2.addPoint(0, 0);\r\n p2.addPoint(-2, -2);\r\n p2.addPoint(2, -2);\r\n\r\n this.downArrow = p2;\r\n\r\n Polygon p3 = new Polygon();\r\n p3.addPoint(0, 0);\r\n p3.addPoint(-2, -2);\r\n p3.addPoint(-2, 2);\r\n\r\n this.rightArrow = p3;\r\n\r\n Polygon p4 = new Polygon();\r\n p4.addPoint(0, 0);\r\n p4.addPoint(2, -2);\r\n p4.addPoint(2, 2);\r\n\r\n this.leftArrow = p4;\r\n\r\n this.verticalTickLabels = false;\r\n this.minorTickCount = 0;\r\n\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the tick labels should be rotated (to\r\n * vertical), and <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setVerticalTickLabels(boolean)\r\n */\r\n public boolean isVerticalTickLabels() {\r\n return this.verticalTickLabels;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether the tick labels are displayed\r\n * vertically (that is, rotated 90 degrees from horizontal). If the flag\r\n * is changed, an {@link AxisChangeEvent} is sent to all registered\r\n * listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isVerticalTickLabels()\r\n */\r\n public void setVerticalTickLabels(boolean flag) {\r\n if (this.verticalTickLabels != flag) {\r\n this.verticalTickLabels = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not the axis line has an arrow\r\n * drawn that points in the positive direction for the axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setPositiveArrowVisible(boolean)\r\n */\r\n public boolean isPositiveArrowVisible() {\r\n return this.positiveArrowVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not the axis lines has an arrow\r\n * drawn that points in the positive direction for the axis, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isPositiveArrowVisible()\r\n */\r\n public void setPositiveArrowVisible(boolean visible) {\r\n this.positiveArrowVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not the axis line has an arrow\r\n * drawn that points in the negative direction for the axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNegativeArrowVisible(boolean)\r\n */\r\n public boolean isNegativeArrowVisible() {\r\n return this.negativeArrowVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not the axis lines has an arrow\r\n * drawn that points in the negative direction for the axis, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #setNegativeArrowVisible(boolean)\r\n */\r\n public void setNegativeArrowVisible(boolean visible) {\r\n this.negativeArrowVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing upwards at\r\n * the end of an axis line.\r\n *\r\n * @return A shape (never <code>null</code>).\r\n *\r\n * @see #setUpArrow(Shape)\r\n */\r\n public Shape getUpArrow() {\r\n return this.upArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing upwards at\r\n * the end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (<code>null</code> not permitted).\r\n *\r\n * @see #getUpArrow()\r\n */\r\n public void setUpArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.upArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing downwards at\r\n * the end of an axis line.\r\n *\r\n * @return A shape (never <code>null</code>).\r\n *\r\n * @see #setDownArrow(Shape)\r\n */\r\n public Shape getDownArrow() {\r\n return this.downArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing downwards at\r\n * the end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (<code>null</code> not permitted).\r\n *\r\n * @see #getDownArrow()\r\n */\r\n public void setDownArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.downArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing left at the\r\n * end of an axis line.\r\n *\r\n * @return A shape (never <code>null</code>).\r\n *\r\n * @see #setLeftArrow(Shape)\r\n */\r\n public Shape getLeftArrow() {\r\n return this.leftArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing left at the\r\n * end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (<code>null</code> not permitted).\r\n *\r\n * @see #getLeftArrow()\r\n */\r\n public void setLeftArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.leftArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing right at the\r\n * end of an axis line.\r\n *\r\n * @return A shape (never <code>null</code>).\r\n *\r\n * @see #setRightArrow(Shape)\r\n */\r\n public Shape getRightArrow() {\r\n return this.rightArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing rightwards at\r\n * the end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (<code>null</code> not permitted).\r\n *\r\n * @see #getRightArrow()\r\n */\r\n public void setRightArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.rightArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Draws an axis line at the current cursor position and edge.\r\n *\r\n * @param g2 the graphics device ({@code null} not permitted).\r\n * @param cursor the cursor position.\r\n * @param dataArea the data area.\r\n * @param edge the edge.\r\n */\r\n @Override\r\n protected void drawAxisLine(Graphics2D g2, double cursor,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n Line2D axisLine = null;\r\n double c = cursor;\r\n if (edge == RectangleEdge.TOP) {\r\n axisLine = new Line2D.Double(dataArea.getX(), c, dataArea.getMaxX(),\r\n c);\r\n } else if (edge == RectangleEdge.BOTTOM) {\r\n axisLine = new Line2D.Double(dataArea.getX(), c, dataArea.getMaxX(),\r\n c);\r\n } else if (edge == RectangleEdge.LEFT) {\r\n axisLine = new Line2D.Double(c, dataArea.getY(), c, \r\n dataArea.getMaxY());\r\n } else if (edge == RectangleEdge.RIGHT) {\r\n axisLine = new Line2D.Double(c, dataArea.getY(), c,\r\n dataArea.getMaxY());\r\n }\r\n g2.setPaint(getAxisLinePaint());\r\n g2.setStroke(getAxisLineStroke());\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n g2.draw(axisLine);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n\r\n boolean drawUpOrRight = false;\r\n boolean drawDownOrLeft = false;\r\n if (this.positiveArrowVisible) {\r\n if (this.inverted) {\r\n drawDownOrLeft = true;\r\n }\r\n else {\r\n drawUpOrRight = true;\r\n }\r\n }\r\n if (this.negativeArrowVisible) {\r\n if (this.inverted) {\r\n drawUpOrRight = true;\r\n } else {\r\n drawDownOrLeft = true;\r\n }\r\n }\r\n if (drawUpOrRight) {\r\n double x = 0.0;\r\n double y = 0.0;\r\n Shape arrow = null;\r\n if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {\r\n x = dataArea.getMaxX();\r\n y = cursor;\r\n arrow = this.rightArrow;\r\n } else if (edge == RectangleEdge.LEFT\r\n || edge == RectangleEdge.RIGHT) {\r\n x = cursor;\r\n y = dataArea.getMinY();\r\n arrow = this.upArrow;\r\n }\r\n\r\n // draw the arrow...\r\n AffineTransform transformer = new AffineTransform();\r\n transformer.setToTranslation(x, y);\r\n Shape shape = transformer.createTransformedShape(arrow);\r\n g2.fill(shape);\r\n g2.draw(shape);\r\n }\r\n\r\n if (drawDownOrLeft) {\r\n double x = 0.0;\r\n double y = 0.0;\r\n Shape arrow = null;\r\n if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {\r\n x = dataArea.getMinX();\r\n y = cursor;\r\n arrow = this.leftArrow;\r\n } else if (edge == RectangleEdge.LEFT\r\n || edge == RectangleEdge.RIGHT) {\r\n x = cursor;\r\n y = dataArea.getMaxY();\r\n arrow = this.downArrow;\r\n }\r\n\r\n // draw the arrow...\r\n AffineTransform transformer = new AffineTransform();\r\n transformer.setToTranslation(x, y);\r\n Shape shape = transformer.createTransformedShape(arrow);\r\n g2.fill(shape);\r\n g2.draw(shape);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Calculates the anchor point for a tick label.\r\n *\r\n * @param tick the tick.\r\n * @param cursor the cursor.\r\n * @param dataArea the data area.\r\n * @param edge the edge on which the axis is drawn.\r\n *\r\n * @return The x and y coordinates of the anchor point.\r\n */\r\n protected float[] calculateAnchorPoint(ValueTick tick, double cursor,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n RectangleInsets insets = getTickLabelInsets();\r\n float[] result = new float[2];\r\n if (edge == RectangleEdge.TOP) {\r\n result[0] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n result[1] = (float) (cursor - insets.getBottom() - 2.0);\r\n }\r\n else if (edge == RectangleEdge.BOTTOM) {\r\n result[0] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n result[1] = (float) (cursor + insets.getTop() + 2.0);\r\n }\r\n else if (edge == RectangleEdge.LEFT) {\r\n result[0] = (float) (cursor - insets.getLeft() - 2.0);\r\n result[1] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n }\r\n else if (edge == RectangleEdge.RIGHT) {\r\n result[0] = (float) (cursor + insets.getRight() + 2.0);\r\n result[1] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Draws the axis line, tick marks and tick mark labels.\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param cursor the cursor.\r\n * @param plotArea the plot area (<code>null</code> not permitted).\r\n * @param dataArea the data area (<code>null</code> not permitted).\r\n * @param edge the edge that the axis is aligned with (<code>null</code> \r\n * not permitted).\r\n *\r\n * @return The width or height used to draw the axis.\r\n */\r\n protected AxisState drawTickMarksAndLabels(Graphics2D g2,\r\n double cursor, Rectangle2D plotArea, Rectangle2D dataArea,\r\n RectangleEdge edge) {\r\n\r\n AxisState state = new AxisState(cursor);\r\n if (isAxisLineVisible()) {\r\n drawAxisLine(g2, cursor, dataArea, edge);\r\n }\r\n List ticks = refreshTicks(g2, state, dataArea, edge);\r\n state.setTicks(ticks);\r\n g2.setFont(getTickLabelFont());\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if (isTickLabelsVisible()) {\r\n g2.setPaint(getTickLabelPaint());\r\n float[] anchorPoint = calculateAnchorPoint(tick, cursor,\r\n dataArea, edge);\r\n if (tick instanceof LogTick) {\r\n LogTick lt = (LogTick) tick;\r\n if (lt.getAttributedLabel() == null) {\r\n continue;\r\n }\r\n AttrStringUtils.drawRotatedString(lt.getAttributedLabel(), \r\n g2, anchorPoint[0], anchorPoint[1], \r\n tick.getTextAnchor(), tick.getAngle(), \r\n tick.getRotationAnchor());\r\n } else {\r\n if (tick.getText() == null) {\r\n continue;\r\n }\r\n TextUtilities.drawRotatedString(tick.getText(), g2,\r\n anchorPoint[0], anchorPoint[1], \r\n tick.getTextAnchor(), tick.getAngle(), \r\n tick.getRotationAnchor());\r\n }\r\n }\r\n\r\n if ((isTickMarksVisible() && tick.getTickType().equals(\r\n TickType.MAJOR)) || (isMinorTickMarksVisible()\r\n && tick.getTickType().equals(TickType.MINOR))) {\r\n\r\n double ol = (tick.getTickType().equals(TickType.MINOR)) \r\n ? getMinorTickMarkOutsideLength()\r\n : getTickMarkOutsideLength();\r\n\r\n double il = (tick.getTickType().equals(TickType.MINOR)) \r\n ? getMinorTickMarkInsideLength()\r\n : getTickMarkInsideLength();\r\n\r\n float xx = (float) valueToJava2D(tick.getValue(), dataArea,\r\n edge);\r\n Line2D mark = null;\r\n g2.setStroke(getTickMarkStroke());\r\n g2.setPaint(getTickMarkPaint());\r\n if (edge == RectangleEdge.LEFT) {\r\n mark = new Line2D.Double(cursor - ol, xx, cursor + il, xx);\r\n }\r\n else if (edge == RectangleEdge.RIGHT) {\r\n mark = new Line2D.Double(cursor + ol, xx, cursor - il, xx);\r\n }\r\n else if (edge == RectangleEdge.TOP) {\r\n mark = new Line2D.Double(xx, cursor - ol, xx, cursor + il);\r\n }\r\n else if (edge == RectangleEdge.BOTTOM) {\r\n mark = new Line2D.Double(xx, cursor + ol, xx, cursor - il);\r\n }\r\n g2.draw(mark);\r\n }\r\n }\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n \r\n // need to work out the space used by the tick labels...\r\n // so we can update the cursor...\r\n double used = 0.0;\r\n if (isTickLabelsVisible()) {\r\n if (edge == RectangleEdge.LEFT) {\r\n used += findMaximumTickLabelWidth(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorLeft(used);\r\n } else if (edge == RectangleEdge.RIGHT) {\r\n used = findMaximumTickLabelWidth(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorRight(used);\r\n } else if (edge == RectangleEdge.TOP) {\r\n used = findMaximumTickLabelHeight(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorUp(used);\r\n } else if (edge == RectangleEdge.BOTTOM) {\r\n used = findMaximumTickLabelHeight(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorDown(used);\r\n }\r\n }\r\n\r\n return state;\r\n }\r\n\r\n /**\r\n * Returns the space required to draw the axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plot the plot that the axis belongs to.\r\n * @param plotArea the area within which the plot should be drawn.\r\n * @param edge the axis location.\r\n * @param space the space already reserved (for other axes).\r\n *\r\n * @return The space required to draw the axis (including pre-reserved\r\n * space).\r\n */\r\n @Override\r\n public AxisSpace reserveSpace(Graphics2D g2, Plot plot, \r\n Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) {\r\n\r\n // create a new space object if one wasn't supplied...\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // if the axis is not visible, no additional space is required...\r\n if (!isVisible()) {\r\n return space;\r\n }\r\n\r\n // if the axis has a fixed dimension, return it...\r\n double dimension = getFixedDimension();\r\n if (dimension > 0.0) {\r\n space.add(dimension, edge);\r\n return space;\r\n }\r\n\r\n // calculate the max size of the tick labels (if visible)...\r\n double tickLabelHeight = 0.0;\r\n double tickLabelWidth = 0.0;\r\n if (isTickLabelsVisible()) {\r\n g2.setFont(getTickLabelFont());\r\n List ticks = refreshTicks(g2, new AxisState(), plotArea, edge);\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n tickLabelHeight = findMaximumTickLabelHeight(ticks, g2,\r\n plotArea, isVerticalTickLabels());\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n tickLabelWidth = findMaximumTickLabelWidth(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n }\r\n }\r\n\r\n // get the axis label size and update the space object...\r\n Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge);\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n double labelHeight = labelEnclosure.getHeight();\r\n space.add(labelHeight + tickLabelHeight, edge);\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n double labelWidth = labelEnclosure.getWidth();\r\n space.add(labelWidth + tickLabelWidth, edge);\r\n }\r\n\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * A utility method for determining the height of the tallest tick label.\r\n *\r\n * @param ticks the ticks.\r\n * @param g2 the graphics device.\r\n * @param drawArea the area within which the plot and axes should be drawn.\r\n * @param vertical a flag that indicates whether or not the tick labels\r\n * are 'vertical'.\r\n *\r\n * @return The height of the tallest tick label.\r\n */\r\n protected double findMaximumTickLabelHeight(List ticks, Graphics2D g2,\r\n Rectangle2D drawArea, boolean vertical) {\r\n\r\n RectangleInsets insets = getTickLabelInsets();\r\n Font font = getTickLabelFont();\r\n g2.setFont(font);\r\n double maxHeight = 0.0;\r\n if (vertical) {\r\n FontMetrics fm = g2.getFontMetrics(font);\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n Tick tick = (Tick) iterator.next();\r\n Rectangle2D labelBounds = null;\r\n if (tick instanceof LogTick) {\r\n LogTick lt = (LogTick) tick;\r\n if (lt.getAttributedLabel() != null) {\r\n labelBounds = AttrStringUtils.getTextBounds(\r\n lt.getAttributedLabel(), g2);\r\n }\r\n } else if (tick.getText() != null) {\r\n labelBounds = TextUtilities.getTextBounds(\r\n tick.getText(), g2, fm);\r\n }\r\n if (labelBounds != null && labelBounds.getWidth() \r\n + insets.getTop() + insets.getBottom() > maxHeight) {\r\n maxHeight = labelBounds.getWidth()\r\n + insets.getTop() + insets.getBottom();\r\n }\r\n }\r\n } else {\r\n LineMetrics metrics = font.getLineMetrics(\"ABCxyz\",\r\n g2.getFontRenderContext());\r\n maxHeight = metrics.getHeight()\r\n + insets.getTop() + insets.getBottom();\r\n }\r\n return maxHeight;\r\n\r\n }\r\n\r\n /**\r\n * A utility method for determining the width of the widest tick label.\r\n *\r\n * @param ticks the ticks.\r\n * @param g2 the graphics device.\r\n * @param drawArea the area within which the plot and axes should be drawn.\r\n * @param vertical a flag that indicates whether or not the tick labels\r\n * are 'vertical'.\r\n *\r\n * @return The width of the tallest tick label.\r\n */\r\n protected double findMaximumTickLabelWidth(List ticks, Graphics2D g2,\r\n Rectangle2D drawArea, boolean vertical) {\r\n\r\n RectangleInsets insets = getTickLabelInsets();\r\n Font font = getTickLabelFont();\r\n double maxWidth = 0.0;\r\n if (!vertical) {\r\n FontMetrics fm = g2.getFontMetrics(font);\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n Tick tick = (Tick) iterator.next();\r\n Rectangle2D labelBounds = null;\r\n if (tick instanceof LogTick) {\r\n LogTick lt = (LogTick) tick;\r\n if (lt.getAttributedLabel() != null) {\r\n labelBounds = AttrStringUtils.getTextBounds(\r\n lt.getAttributedLabel(), g2);\r\n }\r\n } else if (tick.getText() != null) {\r\n labelBounds = TextUtilities.getTextBounds(tick.getText(), \r\n g2, fm);\r\n }\r\n if (labelBounds != null \r\n && labelBounds.getWidth() + insets.getLeft()\r\n + insets.getRight() > maxWidth) {\r\n maxWidth = labelBounds.getWidth()\r\n + insets.getLeft() + insets.getRight();\r\n }\r\n }\r\n } else {\r\n LineMetrics metrics = font.getLineMetrics(\"ABCxyz\",\r\n g2.getFontRenderContext());\r\n maxWidth = metrics.getHeight()\r\n + insets.getTop() + insets.getBottom();\r\n }\r\n return maxWidth;\r\n\r\n }\r\n\r\n /**\r\n * Returns a flag that controls the direction of values on the axis.\r\n * <P>\r\n * For a regular axis, values increase from left to right (for a horizontal\r\n * axis) and bottom to top (for a vertical axis). When the axis is\r\n * 'inverted', the values increase in the opposite direction.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setInverted(boolean)\r\n */\r\n public boolean isInverted() {\r\n return this.inverted;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls the direction of values on the axis, and\r\n * notifies registered listeners that the axis has changed.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isInverted()\r\n */\r\n public void setInverted(boolean flag) {\r\n if (this.inverted != flag) {\r\n this.inverted = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the axis range is\r\n * automatically adjusted to fit the data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAutoRange(boolean)\r\n */\r\n public boolean isAutoRange() {\r\n return this.autoRange;\r\n }\r\n\r\n /**\r\n * Sets a flag that determines whether or not the axis range is\r\n * automatically adjusted to fit the data, and notifies registered\r\n * listeners that the axis has been modified.\r\n *\r\n * @param auto the new value of the flag.\r\n *\r\n * @see #isAutoRange()\r\n */\r\n public void setAutoRange(boolean auto) {\r\n setAutoRange(auto, true);\r\n }\r\n\r\n /**\r\n * Sets the auto range attribute. If the <code>notify</code> flag is set,\r\n * an {@link AxisChangeEvent} is sent to registered listeners.\r\n *\r\n * @param auto the flag.\r\n * @param notify notify listeners?\r\n *\r\n * @see #isAutoRange()\r\n */\r\n protected void setAutoRange(boolean auto, boolean notify) {\r\n if (this.autoRange != auto) {\r\n this.autoRange = auto;\r\n if (this.autoRange) {\r\n autoAdjustRange();\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the minimum size allowed for the axis range when it is\r\n * automatically calculated.\r\n *\r\n * @return The minimum range.\r\n *\r\n * @see #setAutoRangeMinimumSize(double)\r\n */\r\n public double getAutoRangeMinimumSize() {\r\n return this.autoRangeMinimumSize;\r\n }\r\n\r\n /**\r\n * Sets the auto range minimum size and sends an {@link AxisChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param size the size.\r\n *\r\n * @see #getAutoRangeMinimumSize()\r\n */\r\n public void setAutoRangeMinimumSize(double size) {\r\n setAutoRangeMinimumSize(size, true);\r\n }\r\n\r\n /**\r\n * Sets the minimum size allowed for the axis range when it is\r\n * automatically calculated.\r\n * <p>\r\n * If requested, an {@link AxisChangeEvent} is forwarded to all registered\r\n * listeners.\r\n *\r\n * @param size the new minimum.\r\n * @param notify notify listeners?\r\n */\r\n public void setAutoRangeMinimumSize(double size, boolean notify) {\r\n if (size <= 0.0) {\r\n throw new IllegalArgumentException(\r\n \"NumberAxis.setAutoRangeMinimumSize(double): must be > 0.0.\");\r\n }\r\n if (this.autoRangeMinimumSize != size) {\r\n this.autoRangeMinimumSize = size;\r\n if (this.autoRange) {\r\n autoAdjustRange();\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the default auto range.\r\n *\r\n * @return The default auto range (never <code>null</code>).\r\n *\r\n * @see #setDefaultAutoRange(Range)\r\n *\r\n * @since 1.0.5\r\n */\r\n public Range getDefaultAutoRange() {\r\n return this.defaultAutoRange;\r\n }\r\n\r\n /**\r\n * Sets the default auto range and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n *\r\n * @see #getDefaultAutoRange()\r\n *\r\n * @since 1.0.5\r\n */\r\n public void setDefaultAutoRange(Range range) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n this.defaultAutoRange = range;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the lower margin for the axis, expressed as a percentage of the\r\n * axis range. This controls the space added to the lower end of the axis\r\n * when the axis range is automatically calculated (it is ignored when the\r\n * axis range is set explicitly). The default value is 0.05 (five percent).\r\n *\r\n * @return The lower margin.\r\n *\r\n * @see #setLowerMargin(double)\r\n */\r\n public double getLowerMargin() {\r\n return this.lowerMargin;\r\n }\r\n\r\n /**\r\n * Sets the lower margin for the axis (as a percentage of the axis range)\r\n * and sends an {@link AxisChangeEvent} to all registered listeners. This\r\n * margin is added only when the axis range is auto-calculated - if you set\r\n * the axis range manually, the margin is ignored.\r\n *\r\n * @param margin the margin percentage (for example, 0.05 is five percent).\r\n *\r\n * @see #getLowerMargin()\r\n * @see #setUpperMargin(double)\r\n */\r\n public void setLowerMargin(double margin) {\r\n this.lowerMargin = margin;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the upper margin for the axis, expressed as a percentage of the\r\n * axis range. This controls the space added to the lower end of the axis\r\n * when the axis range is automatically calculated (it is ignored when the\r\n * axis range is set explicitly). The default value is 0.05 (five percent).\r\n *\r\n * @return The upper margin.\r\n *\r\n * @see #setUpperMargin(double)\r\n */\r\n public double getUpperMargin() {\r\n return this.upperMargin;\r\n }\r\n\r\n /**\r\n * Sets the upper margin for the axis (as a percentage of the axis range)\r\n * and sends an {@link AxisChangeEvent} to all registered listeners. This\r\n * margin is added only when the axis range is auto-calculated - if you set\r\n * the axis range manually, the margin is ignored.\r\n *\r\n * @param margin the margin percentage (for example, 0.05 is five percent).\r\n *\r\n * @see #getLowerMargin()\r\n * @see #setLowerMargin(double)\r\n */\r\n public void setUpperMargin(double margin) {\r\n this.upperMargin = margin;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the fixed auto range.\r\n *\r\n * @return The length.\r\n *\r\n * @see #setFixedAutoRange(double)\r\n */\r\n public double getFixedAutoRange() {\r\n return this.fixedAutoRange;\r\n }\r\n\r\n /**\r\n * Sets the fixed auto range for the axis.\r\n *\r\n * @param length the range length.\r\n *\r\n * @see #getFixedAutoRange()\r\n */\r\n public void setFixedAutoRange(double length) {\r\n this.fixedAutoRange = length;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the lower bound of the axis range.\r\n *\r\n * @return The lower bound.\r\n *\r\n * @see #setLowerBound(double)\r\n */\r\n public double getLowerBound() {\r\n return this.range.getLowerBound();\r\n }\r\n\r\n /**\r\n * Sets the lower bound for the axis range. An {@link AxisChangeEvent} is\r\n * sent to all registered listeners.\r\n *\r\n * @param min the new minimum.\r\n *\r\n * @see #getLowerBound()\r\n */\r\n public void setLowerBound(double min) {\r\n if (this.range.getUpperBound() > min) {\r\n setRange(new Range(min, this.range.getUpperBound()));\r\n }\r\n else {\r\n setRange(new Range(min, min + 1.0));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the upper bound for the axis range.\r\n *\r\n * @return The upper bound.\r\n *\r\n * @see #setUpperBound(double)\r\n */\r\n public double getUpperBound() {\r\n return this.range.getUpperBound();\r\n }\r\n\r\n /**\r\n * Sets the upper bound for the axis range, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param max the new maximum.\r\n *\r\n * @see #getUpperBound()\r\n */\r\n public void setUpperBound(double max) {\r\n if (this.range.getLowerBound() < max) {\r\n setRange(new Range(this.range.getLowerBound(), max));\r\n }\r\n else {\r\n setRange(max - 1.0, max);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range for the axis.\r\n *\r\n * @return The axis range (never <code>null</code>).\r\n *\r\n * @see #setRange(Range)\r\n */\r\n public Range getRange() {\r\n return this.range;\r\n }\r\n\r\n /**\r\n * Sets the range for the axis and sends a change event to all registered \r\n * listeners. As a side-effect, the auto-range flag is set to\r\n * <code>false</code>.\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n *\r\n * @see #getRange()\r\n */\r\n public void setRange(Range range) {\r\n // defer argument checking\r\n setRange(range, true, true);\r\n }\r\n\r\n /**\r\n * Sets the range for the axis and, if requested, sends a change event to \r\n * all registered listeners. Furthermore, if <code>turnOffAutoRange</code>\r\n * is <code>true</code>, the auto-range flag is set to <code>false</code> \r\n * (normally when setting the axis range manually the caller expects that\r\n * range to remain in force).\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n * @param turnOffAutoRange a flag that controls whether or not the auto\r\n * range is turned off.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n *\r\n * @see #getRange()\r\n */\r\n public void setRange(Range range, boolean turnOffAutoRange, \r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n if (range.getLength() <= 0.0) {\r\n throw new IllegalArgumentException(\r\n \"A positive range length is required: \" + range);\r\n }\r\n if (turnOffAutoRange) {\r\n this.autoRange = false;\r\n }\r\n this.range = range;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the range for the axis and sends a change event to all registered \r\n * listeners. As a side-effect, the auto-range flag is set to\r\n * <code>false</code>.\r\n *\r\n * @param lower the lower axis limit.\r\n * @param upper the upper axis limit.\r\n *\r\n * @see #getRange()\r\n * @see #setRange(Range)\r\n */\r\n public void setRange(double lower, double upper) {\r\n setRange(new Range(lower, upper));\r\n }\r\n\r\n /**\r\n * Sets the range for the axis (after first adding the current margins to\r\n * the specified range) and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n */\r\n public void setRangeWithMargins(Range range) {\r\n setRangeWithMargins(range, true, true);\r\n }\r\n\r\n /**\r\n * Sets the range for the axis after first adding the current margins to\r\n * the range and, if requested, sends an {@link AxisChangeEvent} to all\r\n * registered listeners. As a side-effect, the auto-range flag is set to\r\n * <code>false</code> (optional).\r\n *\r\n * @param range the range (excluding margins, <code>null</code> not\r\n * permitted).\r\n * @param turnOffAutoRange a flag that controls whether or not the auto\r\n * range is turned off.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n */\r\n public void setRangeWithMargins(Range range, boolean turnOffAutoRange,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n setRange(Range.expand(range, getLowerMargin(), getUpperMargin()),\r\n turnOffAutoRange, notify);\r\n }\r\n\r\n /**\r\n * Sets the axis range (after first adding the current margins to the\r\n * range) and sends an {@link AxisChangeEvent} to all registered listeners.\r\n * As a side-effect, the auto-range flag is set to <code>false</code>.\r\n *\r\n * @param lower the lower axis limit.\r\n * @param upper the upper axis limit.\r\n */\r\n public void setRangeWithMargins(double lower, double upper) {\r\n setRangeWithMargins(new Range(lower, upper));\r\n }\r\n\r\n /**\r\n * Sets the axis range, where the new range is 'size' in length, and\r\n * centered on 'value'.\r\n *\r\n * @param value the central value.\r\n * @param length the range length.\r\n */\r\n public void setRangeAboutValue(double value, double length) {\r\n setRange(new Range(value - length / 2, value + length / 2));\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the tick unit is automatically\r\n * selected from a range of standard tick units.\r\n *\r\n * @return A flag indicating whether or not the tick unit is automatically\r\n * selected.\r\n *\r\n * @see #setAutoTickUnitSelection(boolean)\r\n */\r\n public boolean isAutoTickUnitSelection() {\r\n return this.autoTickUnitSelection;\r\n }\r\n\r\n /**\r\n * Sets a flag indicating whether or not the tick unit is automatically\r\n * selected from a range of standard tick units. If the flag is changed,\r\n * registered listeners are notified that the chart has changed.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isAutoTickUnitSelection()\r\n */\r\n public void setAutoTickUnitSelection(boolean flag) {\r\n setAutoTickUnitSelection(flag, true);\r\n }\r\n\r\n /**\r\n * Sets a flag indicating whether or not the tick unit is automatically\r\n * selected from a range of standard tick units.\r\n *\r\n * @param flag the new value of the flag.\r\n * @param notify notify listeners?\r\n *\r\n * @see #isAutoTickUnitSelection()\r\n */\r\n public void setAutoTickUnitSelection(boolean flag, boolean notify) {\r\n\r\n if (this.autoTickUnitSelection != flag) {\r\n this.autoTickUnitSelection = flag;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the source for obtaining standard tick units for the axis.\r\n *\r\n * @return The source (possibly <code>null</code>).\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n */\r\n public TickUnitSource getStandardTickUnits() {\r\n return this.standardTickUnits;\r\n }\r\n\r\n /**\r\n * Sets the source for obtaining standard tick units for the axis and sends\r\n * an {@link AxisChangeEvent} to all registered listeners. The axis will\r\n * try to select the smallest tick unit from the source that does not cause\r\n * the tick labels to overlap (see also the\r\n * {@link #setAutoTickUnitSelection(boolean)} method.\r\n *\r\n * @param source the source for standard tick units (<code>null</code>\r\n * permitted).\r\n *\r\n * @see #getStandardTickUnits()\r\n */\r\n public void setStandardTickUnits(TickUnitSource source) {\r\n this.standardTickUnits = source;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the number of minor tick marks to display.\r\n *\r\n * @return The number of minor tick marks to display.\r\n *\r\n * @see #setMinorTickCount(int)\r\n *\r\n * @since 1.0.12\r\n */\r\n public int getMinorTickCount() {\r\n return this.minorTickCount;\r\n }\r\n\r\n /**\r\n * Sets the number of minor tick marks to display, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param count the count.\r\n *\r\n * @see #getMinorTickCount()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setMinorTickCount(int count) {\r\n this.minorTickCount = count;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Converts a data value to a coordinate in Java2D space, assuming that the\r\n * axis runs along one edge of the specified dataArea.\r\n * <p>\r\n * Note that it is possible for the coordinate to fall outside the area.\r\n *\r\n * @param value the data value.\r\n * @param area the area for plotting the data.\r\n * @param edge the edge along which the axis lies.\r\n *\r\n * @return The Java2D coordinate.\r\n *\r\n * @see #java2DToValue(double, Rectangle2D, RectangleEdge)\r\n */\r\n public abstract double valueToJava2D(double value, Rectangle2D area,\r\n RectangleEdge edge);\r\n\r\n /**\r\n * Converts a length in data coordinates into the corresponding length in\r\n * Java2D coordinates.\r\n *\r\n * @param length the length.\r\n * @param area the plot area.\r\n * @param edge the edge along which the axis lies.\r\n *\r\n * @return The length in Java2D coordinates.\r\n */\r\n public double lengthToJava2D(double length, Rectangle2D area,\r\n RectangleEdge edge) {\r\n double zero = valueToJava2D(0.0, area, edge);\r\n double l = valueToJava2D(length, area, edge);\r\n return Math.abs(l - zero);\r\n }\r\n\r\n /**\r\n * Converts a coordinate in Java2D space to the corresponding data value,\r\n * assuming that the axis runs along one edge of the specified dataArea.\r\n *\r\n * @param java2DValue the coordinate in Java2D space.\r\n * @param area the area in which the data is plotted.\r\n * @param edge the edge along which the axis lies.\r\n *\r\n * @return The data value.\r\n *\r\n * @see #valueToJava2D(double, Rectangle2D, RectangleEdge)\r\n */\r\n public abstract double java2DToValue(double java2DValue, Rectangle2D area, \r\n RectangleEdge edge);\r\n\r\n /**\r\n * Automatically sets the axis range to fit the range of values in the\r\n * dataset. Sometimes this can depend on the renderer used as well (for\r\n * example, the renderer may \"stack\" values, requiring an axis range\r\n * greater than otherwise necessary).\r\n */\r\n protected abstract void autoAdjustRange();\r\n\r\n /**\r\n * Centers the axis range about the specified value and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param value the center value.\r\n */\r\n public void centerRange(double value) {\r\n double central = this.range.getCentralValue();\r\n Range adjusted = new Range(this.range.getLowerBound() + value - central,\r\n this.range.getUpperBound() + value - central);\r\n setRange(adjusted);\r\n }\r\n\r\n /**\r\n * Increases or decreases the axis range by the specified percentage about\r\n * the central value and sends an {@link AxisChangeEvent} to all registered\r\n * listeners.\r\n * <P>\r\n * To double the length of the axis range, use 200% (2.0).\r\n * To halve the length of the axis range, use 50% (0.5).\r\n *\r\n * @param percent the resize factor.\r\n *\r\n * @see #resizeRange(double, double)\r\n */\r\n public void resizeRange(double percent) {\r\n resizeRange(percent, this.range.getCentralValue());\r\n }\r\n\r\n /**\r\n * Increases or decreases the axis range by the specified percentage about\r\n * the specified anchor value and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n * <P>\r\n * To double the length of the axis range, use 200% (2.0).\r\n * To halve the length of the axis range, use 50% (0.5).\r\n *\r\n * @param percent the resize factor.\r\n * @param anchorValue the new central value after the resize.\r\n *\r\n * @see #resizeRange(double)\r\n */\r\n public void resizeRange(double percent, double anchorValue) {\r\n if (percent > 0.0) {\r\n double halfLength = this.range.getLength() * percent / 2;\r\n Range adjusted = new Range(anchorValue - halfLength,\r\n anchorValue + halfLength);\r\n setRange(adjusted);\r\n }\r\n else {\r\n setAutoRange(true);\r\n }\r\n }\r\n\r\n /**\r\n * Increases or decreases the axis range by the specified percentage about\r\n * the specified anchor value and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n * <P>\r\n * To double the length of the axis range, use 200% (2.0).\r\n * To halve the length of the axis range, use 50% (0.5).\r\n *\r\n * @param percent the resize factor.\r\n * @param anchorValue the new central value after the resize.\r\n *\r\n * @see #resizeRange(double)\r\n *\r\n * @since 1.0.13\r\n */\r\n public void resizeRange2(double percent, double anchorValue) {\r\n if (percent > 0.0) {\r\n double left = anchorValue - getLowerBound();\r\n double right = getUpperBound() - anchorValue;\r\n Range adjusted = new Range(anchorValue - left * percent,\r\n anchorValue + right * percent);\r\n setRange(adjusted);\r\n }\r\n else {\r\n setAutoRange(true);\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the current range.\r\n *\r\n * @param lowerPercent the new lower bound.\r\n * @param upperPercent the new upper bound.\r\n */\r\n public void zoomRange(double lowerPercent, double upperPercent) {\r\n double start = this.range.getLowerBound();\r\n double length = this.range.getLength();\r\n double r0, r1;\r\n if (isInverted()) {\r\n r0 = start + (length * (1 - upperPercent));\r\n r1 = start + (length * (1 - lowerPercent));\r\n }\r\n else {\r\n r0 = start + length * lowerPercent;\r\n r1 = start + length * upperPercent;\r\n }\r\n if ((r1 > r0) && !Double.isInfinite(r1 - r0)) {\r\n setRange(new Range(r0, r1));\r\n }\r\n }\r\n\r\n /**\r\n * Slides the axis range by the specified percentage.\r\n *\r\n * @param percent the percentage.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void pan(double percent) {\r\n Range r = getRange();\r\n double length = range.getLength();\r\n double adj = length * percent;\r\n double lower = r.getLowerBound() + adj;\r\n double upper = r.getUpperBound() + adj;\r\n setRange(lower, upper);\r\n }\r\n\r\n /**\r\n * Returns the auto tick index.\r\n *\r\n * @return The auto tick index.\r\n *\r\n * @see #setAutoTickIndex(int)\r\n */\r\n protected int getAutoTickIndex() {\r\n return this.autoTickIndex;\r\n }\r\n\r\n /**\r\n * Sets the auto tick index.\r\n *\r\n * @param index the new value.\r\n *\r\n * @see #getAutoTickIndex()\r\n */\r\n protected void setAutoTickIndex(int index) {\r\n this.autoTickIndex = index;\r\n }\r\n\r\n /**\r\n * Tests the axis for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof ValueAxis)) {\r\n return false;\r\n }\r\n ValueAxis that = (ValueAxis) obj;\r\n if (this.positiveArrowVisible != that.positiveArrowVisible) {\r\n return false;\r\n }\r\n if (this.negativeArrowVisible != that.negativeArrowVisible) {\r\n return false;\r\n }\r\n if (this.inverted != that.inverted) {\r\n return false;\r\n }\r\n // if autoRange is true, then the current range is irrelevant\r\n if (!this.autoRange && !ObjectUtilities.equal(this.range, that.range)) {\r\n return false;\r\n }\r\n if (this.autoRange != that.autoRange) {\r\n return false;\r\n }\r\n if (this.autoRangeMinimumSize != that.autoRangeMinimumSize) {\r\n return false;\r\n }\r\n if (!this.defaultAutoRange.equals(that.defaultAutoRange)) {\r\n return false;\r\n }\r\n if (this.upperMargin != that.upperMargin) {\r\n return false;\r\n }\r\n if (this.lowerMargin != that.lowerMargin) {\r\n return false;\r\n }\r\n if (this.fixedAutoRange != that.fixedAutoRange) {\r\n return false;\r\n }\r\n if (this.autoTickUnitSelection != that.autoTickUnitSelection) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.standardTickUnits,\r\n that.standardTickUnits)) {\r\n return false;\r\n }\r\n if (this.verticalTickLabels != that.verticalTickLabels) {\r\n return false;\r\n }\r\n if (this.minorTickCount != that.minorTickCount) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a clone of the object.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if some component of the axis does\r\n * not support cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n ValueAxis clone = (ValueAxis) super.clone();\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeShape(this.upArrow, stream);\r\n SerialUtilities.writeShape(this.downArrow, stream);\r\n SerialUtilities.writeShape(this.leftArrow, stream);\r\n SerialUtilities.writeShape(this.rightArrow, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n\r\n stream.defaultReadObject();\r\n this.upArrow = SerialUtilities.readShape(stream);\r\n this.downArrow = SerialUtilities.readShape(stream);\r\n this.leftArrow = SerialUtilities.readShape(stream);\r\n this.rightArrow = SerialUtilities.readShape(stream);\r\n }\r\n\r\n}\r" }, { "identifier": "Plot", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/Plot.java", "snippet": "public abstract class Plot implements AxisChangeListener,\r\n DatasetChangeListener, AnnotationChangeListener, MarkerChangeListener,\r\n LegendItemSource, PublicCloneable, Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -8831571430103671324L;\r\n\r\n /** Useful constant representing zero. */\r\n public static final Number ZERO = new Integer(0);\r\n\r\n /** The default insets. */\r\n public static final RectangleInsets DEFAULT_INSETS\r\n = new RectangleInsets(4.0, 8.0, 4.0, 8.0);\r\n\r\n /** The default outline stroke. */\r\n public static final Stroke DEFAULT_OUTLINE_STROKE = new BasicStroke(0.5f,\r\n BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);\r\n\r\n /** The default outline color. */\r\n public static final Paint DEFAULT_OUTLINE_PAINT = Color.gray;\r\n\r\n /** The default foreground alpha transparency. */\r\n public static final float DEFAULT_FOREGROUND_ALPHA = 1.0f;\r\n\r\n /** The default background alpha transparency. */\r\n public static final float DEFAULT_BACKGROUND_ALPHA = 1.0f;\r\n\r\n /** The default background color. */\r\n public static final Paint DEFAULT_BACKGROUND_PAINT = Color.white;\r\n\r\n /** The minimum width at which the plot should be drawn. */\r\n public static final int MINIMUM_WIDTH_TO_DRAW = 10;\r\n\r\n /** The minimum height at which the plot should be drawn. */\r\n public static final int MINIMUM_HEIGHT_TO_DRAW = 10;\r\n\r\n /** A default box shape for legend items. */\r\n public static final Shape DEFAULT_LEGEND_ITEM_BOX\r\n = new Rectangle2D.Double(-4.0, -4.0, 8.0, 8.0);\r\n\r\n /** A default circle shape for legend items. */\r\n public static final Shape DEFAULT_LEGEND_ITEM_CIRCLE\r\n = new Ellipse2D.Double(-4.0, -4.0, 8.0, 8.0);\r\n\r\n /** The parent plot (<code>null</code> if this is the root plot). */\r\n private Plot parent;\r\n\r\n /** The dataset group (to be used for thread synchronisation). */\r\n private DatasetGroup datasetGroup;\r\n\r\n /** The message to display if no data is available. */\r\n private String noDataMessage;\r\n\r\n /** The font used to display the 'no data' message. */\r\n private Font noDataMessageFont;\r\n\r\n /** The paint used to draw the 'no data' message. */\r\n private transient Paint noDataMessagePaint;\r\n\r\n /** Amount of blank space around the plot area. */\r\n private RectangleInsets insets;\r\n\r\n /**\r\n * A flag that controls whether or not the plot outline is drawn.\r\n *\r\n * @since 1.0.6\r\n */\r\n private boolean outlineVisible;\r\n\r\n /** The Stroke used to draw an outline around the plot. */\r\n private transient Stroke outlineStroke;\r\n\r\n /** The Paint used to draw an outline around the plot. */\r\n private transient Paint outlinePaint;\r\n\r\n /** An optional color used to fill the plot background. */\r\n private transient Paint backgroundPaint;\r\n\r\n /** An optional image for the plot background. */\r\n private transient Image backgroundImage; // not currently serialized\r\n\r\n /** The alignment for the background image. */\r\n private int backgroundImageAlignment = Align.FIT;\r\n\r\n /** The alpha value used to draw the background image. */\r\n private float backgroundImageAlpha = 0.5f;\r\n\r\n /** The alpha-transparency for the plot. */\r\n private float foregroundAlpha;\r\n\r\n /** The alpha transparency for the background paint. */\r\n private float backgroundAlpha;\r\n\r\n /** The drawing supplier. */\r\n private DrawingSupplier drawingSupplier;\r\n\r\n /** Storage for registered change listeners. */\r\n private transient EventListenerList listenerList;\r\n\r\n /**\r\n * A flag that controls whether or not the plot will notify listeners\r\n * of changes (defaults to true, but sometimes it is useful to disable\r\n * this).\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean notify;\r\n\r\n /**\r\n * Creates a new plot.\r\n */\r\n protected Plot() {\r\n\r\n this.parent = null;\r\n this.insets = DEFAULT_INSETS;\r\n this.backgroundPaint = DEFAULT_BACKGROUND_PAINT;\r\n this.backgroundAlpha = DEFAULT_BACKGROUND_ALPHA;\r\n this.backgroundImage = null;\r\n this.outlineVisible = true;\r\n this.outlineStroke = DEFAULT_OUTLINE_STROKE;\r\n this.outlinePaint = DEFAULT_OUTLINE_PAINT;\r\n this.foregroundAlpha = DEFAULT_FOREGROUND_ALPHA;\r\n\r\n this.noDataMessage = null;\r\n this.noDataMessageFont = new Font(\"SansSerif\", Font.PLAIN, 12);\r\n this.noDataMessagePaint = Color.black;\r\n\r\n this.drawingSupplier = new DefaultDrawingSupplier();\r\n\r\n this.notify = true;\r\n this.listenerList = new EventListenerList();\r\n\r\n }\r\n\r\n /**\r\n * Returns the dataset group for the plot (not currently used).\r\n *\r\n * @return The dataset group.\r\n *\r\n * @see #setDatasetGroup(DatasetGroup)\r\n */\r\n public DatasetGroup getDatasetGroup() {\r\n return this.datasetGroup;\r\n }\r\n\r\n /**\r\n * Sets the dataset group (not currently used).\r\n *\r\n * @param group the dataset group (<code>null</code> permitted).\r\n *\r\n * @see #getDatasetGroup()\r\n */\r\n protected void setDatasetGroup(DatasetGroup group) {\r\n this.datasetGroup = group;\r\n }\r\n\r\n /**\r\n * Returns the string that is displayed when the dataset is empty or\r\n * <code>null</code>.\r\n *\r\n * @return The 'no data' message (<code>null</code> possible).\r\n *\r\n * @see #setNoDataMessage(String)\r\n * @see #getNoDataMessageFont()\r\n * @see #getNoDataMessagePaint()\r\n */\r\n public String getNoDataMessage() {\r\n return this.noDataMessage;\r\n }\r\n\r\n /**\r\n * Sets the message that is displayed when the dataset is empty or\r\n * <code>null</code>, and sends a {@link PlotChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param message the message (<code>null</code> permitted).\r\n *\r\n * @see #getNoDataMessage()\r\n */\r\n public void setNoDataMessage(String message) {\r\n this.noDataMessage = message;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the font used to display the 'no data' message.\r\n *\r\n * @return The font (never <code>null</code>).\r\n *\r\n * @see #setNoDataMessageFont(Font)\r\n * @see #getNoDataMessage()\r\n */\r\n public Font getNoDataMessageFont() {\r\n return this.noDataMessageFont;\r\n }\r\n\r\n /**\r\n * Sets the font used to display the 'no data' message and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param font the font (<code>null</code> not permitted).\r\n *\r\n * @see #getNoDataMessageFont()\r\n */\r\n public void setNoDataMessageFont(Font font) {\r\n ParamChecks.nullNotPermitted(font, \"font\");\r\n this.noDataMessageFont = font;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used to display the 'no data' message.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setNoDataMessagePaint(Paint)\r\n * @see #getNoDataMessage()\r\n */\r\n public Paint getNoDataMessagePaint() {\r\n return this.noDataMessagePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to display the 'no data' message and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getNoDataMessagePaint()\r\n */\r\n public void setNoDataMessagePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.noDataMessagePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a short string describing the plot type.\r\n * <P>\r\n * Note: this gets used in the chart property editing user interface,\r\n * but there needs to be a better mechanism for identifying the plot type.\r\n *\r\n * @return A short string describing the plot type (never\r\n * <code>null</code>).\r\n */\r\n public abstract String getPlotType();\r\n\r\n /**\r\n * Returns the parent plot (or <code>null</code> if this plot is not part\r\n * of a combined plot).\r\n *\r\n * @return The parent plot.\r\n *\r\n * @see #setParent(Plot)\r\n * @see #getRootPlot()\r\n */\r\n public Plot getParent() {\r\n return this.parent;\r\n }\r\n\r\n /**\r\n * Sets the parent plot. This method is intended for internal use, you\r\n * shouldn't need to call it directly.\r\n *\r\n * @param parent the parent plot (<code>null</code> permitted).\r\n *\r\n * @see #getParent()\r\n */\r\n public void setParent(Plot parent) {\r\n this.parent = parent;\r\n }\r\n\r\n /**\r\n * Returns the root plot.\r\n *\r\n * @return The root plot.\r\n *\r\n * @see #getParent()\r\n */\r\n public Plot getRootPlot() {\r\n\r\n Plot p = getParent();\r\n if (p == null) {\r\n return this;\r\n }\r\n return p.getRootPlot();\r\n\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this plot is part of a combined plot\r\n * structure (that is, {@link #getParent()} returns a non-<code>null</code>\r\n * value), and <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> if this plot is part of a combined plot\r\n * structure.\r\n *\r\n * @see #getParent()\r\n */\r\n public boolean isSubplot() {\r\n return (getParent() != null);\r\n }\r\n\r\n /**\r\n * Returns the insets for the plot area.\r\n *\r\n * @return The insets (never <code>null</code>).\r\n *\r\n * @see #setInsets(RectangleInsets)\r\n */\r\n public RectangleInsets getInsets() {\r\n return this.insets;\r\n }\r\n\r\n /**\r\n * Sets the insets for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param insets the new insets (<code>null</code> not permitted).\r\n *\r\n * @see #getInsets()\r\n * @see #setInsets(RectangleInsets, boolean)\r\n */\r\n public void setInsets(RectangleInsets insets) {\r\n setInsets(insets, true);\r\n }\r\n\r\n /**\r\n * Sets the insets for the plot and, if requested, and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param insets the new insets (<code>null</code> not permitted).\r\n * @param notify a flag that controls whether the registered listeners are\r\n * notified.\r\n *\r\n * @see #getInsets()\r\n * @see #setInsets(RectangleInsets)\r\n */\r\n public void setInsets(RectangleInsets insets, boolean notify) {\r\n ParamChecks.nullNotPermitted(insets, \"insets\");\r\n if (!this.insets.equals(insets)) {\r\n this.insets = insets;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the background color of the plot area.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundPaint(Paint)\r\n */\r\n public Paint getBackgroundPaint() {\r\n return this.backgroundPaint;\r\n }\r\n\r\n /**\r\n * Sets the background color of the plot area and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundPaint()\r\n */\r\n public void setBackgroundPaint(Paint paint) {\r\n\r\n if (paint == null) {\r\n if (this.backgroundPaint != null) {\r\n this.backgroundPaint = null;\r\n fireChangeEvent();\r\n }\r\n }\r\n else {\r\n if (this.backgroundPaint != null) {\r\n if (this.backgroundPaint.equals(paint)) {\r\n return; // nothing to do\r\n }\r\n }\r\n this.backgroundPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the alpha transparency of the plot area background.\r\n *\r\n * @return The alpha transparency.\r\n *\r\n * @see #setBackgroundAlpha(float)\r\n */\r\n public float getBackgroundAlpha() {\r\n return this.backgroundAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha transparency of the plot area background, and notifies\r\n * registered listeners that the plot has been modified.\r\n *\r\n * @param alpha the new alpha value (in the range 0.0f to 1.0f).\r\n *\r\n * @see #getBackgroundAlpha()\r\n */\r\n public void setBackgroundAlpha(float alpha) {\r\n if (this.backgroundAlpha != alpha) {\r\n this.backgroundAlpha = alpha;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the drawing supplier for the plot.\r\n *\r\n * @return The drawing supplier (possibly <code>null</code>).\r\n *\r\n * @see #setDrawingSupplier(DrawingSupplier)\r\n */\r\n public DrawingSupplier getDrawingSupplier() {\r\n DrawingSupplier result;\r\n Plot p = getParent();\r\n if (p != null) {\r\n result = p.getDrawingSupplier();\r\n }\r\n else {\r\n result = this.drawingSupplier;\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the drawing supplier for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. The drawing\r\n * supplier is responsible for supplying a limitless (possibly repeating)\r\n * sequence of <code>Paint</code>, <code>Stroke</code> and\r\n * <code>Shape</code> objects that the plot's renderer(s) can use to\r\n * populate its (their) tables.\r\n *\r\n * @param supplier the new supplier.\r\n *\r\n * @see #getDrawingSupplier()\r\n */\r\n public void setDrawingSupplier(DrawingSupplier supplier) {\r\n this.drawingSupplier = supplier;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Sets the drawing supplier for the plot and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners. The drawing\r\n * supplier is responsible for supplying a limitless (possibly repeating)\r\n * sequence of <code>Paint</code>, <code>Stroke</code> and\r\n * <code>Shape</code> objects that the plot's renderer(s) can use to\r\n * populate its (their) tables.\r\n *\r\n * @param supplier the new supplier.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDrawingSupplier()\r\n *\r\n * @since 1.0.11\r\n */\r\n public void setDrawingSupplier(DrawingSupplier supplier, boolean notify) {\r\n this.drawingSupplier = supplier;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the background image that is used to fill the plot's background\r\n * area.\r\n *\r\n * @return The image (possibly <code>null</code>).\r\n *\r\n * @see #setBackgroundImage(Image)\r\n */\r\n public Image getBackgroundImage() {\r\n return this.backgroundImage;\r\n }\r\n\r\n /**\r\n * Sets the background image for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param image the image (<code>null</code> permitted).\r\n *\r\n * @see #getBackgroundImage()\r\n */\r\n public void setBackgroundImage(Image image) {\r\n this.backgroundImage = image;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the background image alignment. Alignment constants are defined\r\n * in the <code>org.jfree.ui.Align</code> class in the JCommon class\r\n * library.\r\n *\r\n * @return The alignment.\r\n *\r\n * @see #setBackgroundImageAlignment(int)\r\n */\r\n public int getBackgroundImageAlignment() {\r\n return this.backgroundImageAlignment;\r\n }\r\n\r\n /**\r\n * Sets the alignment for the background image and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. Alignment options\r\n * are defined by the {@link org.jfree.ui.Align} class in the JCommon\r\n * class library.\r\n *\r\n * @param alignment the alignment.\r\n *\r\n * @see #getBackgroundImageAlignment()\r\n */\r\n public void setBackgroundImageAlignment(int alignment) {\r\n if (this.backgroundImageAlignment != alignment) {\r\n this.backgroundImageAlignment = alignment;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha transparency used to draw the background image. This\r\n * is a value in the range 0.0f to 1.0f, where 0.0f is fully transparent\r\n * and 1.0f is fully opaque.\r\n *\r\n * @return The alpha transparency.\r\n *\r\n * @see #setBackgroundImageAlpha(float)\r\n */\r\n public float getBackgroundImageAlpha() {\r\n return this.backgroundImageAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha transparency used when drawing the background image.\r\n *\r\n * @param alpha the alpha transparency (in the range 0.0f to 1.0f, where\r\n * 0.0f is fully transparent, and 1.0f is fully opaque).\r\n *\r\n * @throws IllegalArgumentException if <code>alpha</code> is not within\r\n * the specified range.\r\n *\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void setBackgroundImageAlpha(float alpha) {\r\n if (alpha < 0.0f || alpha > 1.0f) {\r\n throw new IllegalArgumentException(\r\n \"The 'alpha' value must be in the range 0.0f to 1.0f.\");\r\n }\r\n if (this.backgroundImageAlpha != alpha) {\r\n this.backgroundImageAlpha = alpha;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the plot outline is\r\n * drawn. The default value is <code>true</code>. Note that for\r\n * historical reasons, the plot's outline paint and stroke can take on\r\n * <code>null</code> values, in which case the outline will not be drawn\r\n * even if this flag is set to <code>true</code>.\r\n *\r\n * @return The outline visibility flag.\r\n *\r\n * @since 1.0.6\r\n *\r\n * @see #setOutlineVisible(boolean)\r\n */\r\n public boolean isOutlineVisible() {\r\n return this.outlineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the plot's outline is\r\n * drawn, and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the new flag value.\r\n *\r\n * @since 1.0.6\r\n *\r\n * @see #isOutlineVisible()\r\n */\r\n public void setOutlineVisible(boolean visible) {\r\n this.outlineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used to outline the plot area.\r\n *\r\n * @return The stroke (possibly <code>null</code>).\r\n *\r\n * @see #setOutlineStroke(Stroke)\r\n */\r\n public Stroke getOutlineStroke() {\r\n return this.outlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to outline the plot area and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. If you set this\r\n * attribute to <code>null</code>, no outline will be drawn.\r\n *\r\n * @param stroke the stroke (<code>null</code> permitted).\r\n *\r\n * @see #getOutlineStroke()\r\n */\r\n public void setOutlineStroke(Stroke stroke) {\r\n if (stroke == null) {\r\n if (this.outlineStroke != null) {\r\n this.outlineStroke = null;\r\n fireChangeEvent();\r\n }\r\n }\r\n else {\r\n if (this.outlineStroke != null) {\r\n if (this.outlineStroke.equals(stroke)) {\r\n return; // nothing to do\r\n }\r\n }\r\n this.outlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the color used to draw the outline of the plot area.\r\n *\r\n * @return The color (possibly <code>null</code>).\r\n *\r\n * @see #setOutlinePaint(Paint)\r\n */\r\n public Paint getOutlinePaint() {\r\n return this.outlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the outline of the plot area and sends a\r\n * {@link PlotChangeEvent} to all registered listeners. If you set this\r\n * attribute to <code>null</code>, no outline will be drawn.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getOutlinePaint()\r\n */\r\n public void setOutlinePaint(Paint paint) {\r\n if (paint == null) {\r\n if (this.outlinePaint != null) {\r\n this.outlinePaint = null;\r\n fireChangeEvent();\r\n }\r\n }\r\n else {\r\n if (this.outlinePaint != null) {\r\n if (this.outlinePaint.equals(paint)) {\r\n return; // nothing to do\r\n }\r\n }\r\n this.outlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the alpha-transparency for the plot foreground.\r\n *\r\n * @return The alpha-transparency.\r\n *\r\n * @see #setForegroundAlpha(float)\r\n */\r\n public float getForegroundAlpha() {\r\n return this.foregroundAlpha;\r\n }\r\n\r\n /**\r\n * Sets the alpha-transparency for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param alpha the new alpha transparency.\r\n *\r\n * @see #getForegroundAlpha()\r\n */\r\n public void setForegroundAlpha(float alpha) {\r\n if (this.foregroundAlpha != alpha) {\r\n this.foregroundAlpha = alpha;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the legend items for the plot. By default, this method returns\r\n * <code>null</code>. Subclasses should override to return a\r\n * {@link LegendItemCollection}.\r\n *\r\n * @return The legend items for the plot (possibly <code>null</code>).\r\n */\r\n @Override\r\n public LegendItemCollection getLegendItems() {\r\n return null;\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not change events are sent to\r\n * registered listeners.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNotify(boolean)\r\n *\r\n * @since 1.0.13\r\n */\r\n public boolean isNotify() {\r\n return this.notify;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not listeners receive\r\n * {@link PlotChangeEvent} notifications.\r\n *\r\n * @param notify a boolean.\r\n *\r\n * @see #isNotify()\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setNotify(boolean notify) {\r\n this.notify = notify;\r\n // if the flag is being set to true, there may be queued up changes...\r\n if (notify) {\r\n notifyListeners(new PlotChangeEvent(this));\r\n }\r\n }\r\n\r\n /**\r\n * Registers an object for notification of changes to the plot.\r\n *\r\n * @param listener the object to be registered.\r\n *\r\n * @see #removeChangeListener(PlotChangeListener)\r\n */\r\n public void addChangeListener(PlotChangeListener listener) {\r\n this.listenerList.add(PlotChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Unregisters an object for notification of changes to the plot.\r\n *\r\n * @param listener the object to be unregistered.\r\n *\r\n * @see #addChangeListener(PlotChangeListener)\r\n */\r\n public void removeChangeListener(PlotChangeListener listener) {\r\n this.listenerList.remove(PlotChangeListener.class, listener);\r\n }\r\n\r\n /**\r\n * Notifies all registered listeners that the plot has been modified.\r\n *\r\n * @param event information about the change event.\r\n */\r\n public void notifyListeners(PlotChangeEvent event) {\r\n // if the 'notify' flag has been switched to false, we don't notify\r\n // the listeners\r\n if (!this.notify) {\r\n return;\r\n }\r\n Object[] listeners = this.listenerList.getListenerList();\r\n for (int i = listeners.length - 2; i >= 0; i -= 2) {\r\n if (listeners[i] == PlotChangeListener.class) {\r\n ((PlotChangeListener) listeners[i + 1]).plotChanged(event);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @since 1.0.10\r\n */\r\n protected void fireChangeEvent() {\r\n notifyListeners(new PlotChangeEvent(this));\r\n }\r\n\r\n /**\r\n * Draws the plot within the specified area. The anchor is a point on the\r\n * chart that is specified externally (for instance, it may be the last\r\n * point of the last mouse click performed by the user) - plots can use or\r\n * ignore this value as they see fit.\r\n * <br><br>\r\n * Subclasses need to provide an implementation of this method, obviously.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the plot area.\r\n * @param anchor the anchor point (<code>null</code> permitted).\r\n * @param parentState the parent state (if any).\r\n * @param info carries back plot rendering info.\r\n */\r\n public abstract void draw(Graphics2D g2,\r\n Rectangle2D area,\r\n Point2D anchor,\r\n PlotState parentState,\r\n PlotRenderingInfo info);\r\n\r\n /**\r\n * Draws the plot background (the background color and/or image).\r\n * <P>\r\n * This method will be called during the chart drawing process and is\r\n * declared public so that it can be accessed by the renderers used by\r\n * certain subclasses. You shouldn't need to call this method directly.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot should be drawn.\r\n */\r\n public void drawBackground(Graphics2D g2, Rectangle2D area) {\r\n // some subclasses override this method completely, so don't put\r\n // anything here that *must* be done\r\n fillBackground(g2, area);\r\n drawBackgroundImage(g2, area);\r\n }\r\n\r\n /**\r\n * Fills the specified area with the background paint.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n *\r\n * @see #getBackgroundPaint()\r\n * @see #getBackgroundAlpha()\r\n * @see #fillBackground(Graphics2D, Rectangle2D, PlotOrientation)\r\n */\r\n protected void fillBackground(Graphics2D g2, Rectangle2D area) {\r\n fillBackground(g2, area, PlotOrientation.VERTICAL);\r\n }\r\n\r\n /**\r\n * Fills the specified area with the background paint. If the background\r\n * paint is an instance of <code>GradientPaint</code>, the gradient will\r\n * run in the direction suggested by the plot's orientation.\r\n *\r\n * @param g2 the graphics target.\r\n * @param area the plot area.\r\n * @param orientation the plot orientation (<code>null</code> not\r\n * permitted).\r\n *\r\n * @since 1.0.6\r\n */\r\n protected void fillBackground(Graphics2D g2, Rectangle2D area,\r\n PlotOrientation orientation) {\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n if (this.backgroundPaint == null) {\r\n return;\r\n }\r\n Paint p = this.backgroundPaint;\r\n if (p instanceof GradientPaint) {\r\n GradientPaint gp = (GradientPaint) p;\r\n if (orientation == PlotOrientation.VERTICAL) {\r\n p = new GradientPaint((float) area.getCenterX(),\r\n (float) area.getMaxY(), gp.getColor1(),\r\n (float) area.getCenterX(), (float) area.getMinY(),\r\n gp.getColor2());\r\n }\r\n else if (orientation == PlotOrientation.HORIZONTAL) {\r\n p = new GradientPaint((float) area.getMinX(),\r\n (float) area.getCenterY(), gp.getColor1(),\r\n (float) area.getMaxX(), (float) area.getCenterY(),\r\n gp.getColor2());\r\n }\r\n }\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundAlpha));\r\n g2.setPaint(p);\r\n g2.fill(area);\r\n g2.setComposite(originalComposite);\r\n }\r\n\r\n /**\r\n * Draws the background image (if there is one) aligned within the\r\n * specified area.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n *\r\n * @see #getBackgroundImage()\r\n * @see #getBackgroundImageAlignment()\r\n * @see #getBackgroundImageAlpha()\r\n */\r\n public void drawBackgroundImage(Graphics2D g2, Rectangle2D area) {\r\n if (this.backgroundImage == null) {\r\n return; // nothing to do\r\n }\r\n Composite savedComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n this.backgroundImageAlpha));\r\n Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,\r\n this.backgroundImage.getWidth(null),\r\n this.backgroundImage.getHeight(null));\r\n Align.align(dest, area, this.backgroundImageAlignment);\r\n Shape savedClip = g2.getClip();\r\n g2.clip(area);\r\n g2.drawImage(this.backgroundImage, (int) dest.getX(),\r\n (int) dest.getY(), (int) dest.getWidth() + 1,\r\n (int) dest.getHeight() + 1, null);\r\n g2.setClip(savedClip);\r\n g2.setComposite(savedComposite);\r\n }\r\n\r\n /**\r\n * Draws the plot outline. This method will be called during the chart\r\n * drawing process and is declared public so that it can be accessed by the\r\n * renderers used by certain subclasses. You shouldn't need to call this\r\n * method directly.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot should be drawn.\r\n */\r\n public void drawOutline(Graphics2D g2, Rectangle2D area) {\r\n if (!this.outlineVisible) {\r\n return;\r\n }\r\n if ((this.outlineStroke != null) && (this.outlinePaint != null)) {\r\n g2.setStroke(this.outlineStroke);\r\n g2.setPaint(this.outlinePaint);\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);\r\n g2.draw(area);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n }\r\n\r\n /**\r\n * Draws a message to state that there is no data to plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area within which the plot should be drawn.\r\n */\r\n protected void drawNoDataMessage(Graphics2D g2, Rectangle2D area) {\r\n Shape savedClip = g2.getClip();\r\n g2.clip(area);\r\n String message = this.noDataMessage;\r\n if (message != null) {\r\n g2.setFont(this.noDataMessageFont);\r\n g2.setPaint(this.noDataMessagePaint);\r\n TextBlock block = TextUtilities.createTextBlock(\r\n this.noDataMessage, this.noDataMessageFont,\r\n this.noDataMessagePaint, 0.9f * (float) area.getWidth(),\r\n new G2TextMeasurer(g2));\r\n block.draw(g2, (float) area.getCenterX(),\r\n (float) area.getCenterY(), TextBlockAnchor.CENTER);\r\n }\r\n g2.setClip(savedClip);\r\n }\r\n\r\n /**\r\n * Creates a plot entity that contains a reference to the plot and the\r\n * data area as shape.\r\n *\r\n * @param dataArea the data area used as hot spot for the entity.\r\n * @param plotState the plot rendering info containing a reference to the\r\n * EntityCollection.\r\n * @param toolTip the tool tip (defined in the respective Plot\r\n * subclass) (<code>null</code> permitted).\r\n * @param urlText the url (defined in the respective Plot subclass)\r\n * (<code>null</code> permitted).\r\n *\r\n * @since 1.0.13\r\n */\r\n protected void createAndAddEntity(Rectangle2D dataArea,\r\n PlotRenderingInfo plotState, String toolTip, String urlText) {\r\n if (plotState != null && plotState.getOwner() != null) {\r\n EntityCollection e = plotState.getOwner().getEntityCollection();\r\n if (e != null) {\r\n e.add(new PlotEntity(dataArea, this, toolTip, urlText));\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the plot. Since the plot does not maintain any\r\n * information about where it has been drawn, the plot rendering info is\r\n * supplied as an argument so that the plot dimensions can be determined.\r\n *\r\n * @param x the x coordinate (in Java2D space).\r\n * @param y the y coordinate (in Java2D space).\r\n * @param info an object containing information about the dimensions of\r\n * the plot.\r\n */\r\n public void handleClick(int x, int y, PlotRenderingInfo info) {\r\n // provides a 'no action' default\r\n }\r\n\r\n /**\r\n * Performs a zoom on the plot. Subclasses should override if zooming is\r\n * appropriate for the type of plot.\r\n *\r\n * @param percent the zoom percentage.\r\n */\r\n public void zoom(double percent) {\r\n // do nothing by default.\r\n }\r\n\r\n /**\r\n * Receives notification of a change to an {@link Annotation} added to\r\n * this plot.\r\n *\r\n * @param event information about the event (not used here).\r\n *\r\n * @since 1.0.14\r\n */\r\n @Override\r\n public void annotationChanged(AnnotationChangeEvent event) {\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Receives notification of a change to one of the plot's axes.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void axisChanged(AxisChangeEvent event) {\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Receives notification of a change to the plot's dataset.\r\n * <P>\r\n * The plot reacts by passing on a plot change event to all registered\r\n * listeners.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void datasetChanged(DatasetChangeEvent event) {\r\n PlotChangeEvent newEvent = new PlotChangeEvent(this);\r\n newEvent.setType(ChartChangeEventType.DATASET_UPDATED);\r\n notifyListeners(newEvent);\r\n }\r\n\r\n /**\r\n * Receives notification of a change to a marker that is assigned to the\r\n * plot.\r\n *\r\n * @param event the event.\r\n *\r\n * @since 1.0.3\r\n */\r\n @Override\r\n public void markerChanged(MarkerChangeEvent event) {\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adjusts the supplied x-value.\r\n *\r\n * @param x the x-value.\r\n * @param w1 width 1.\r\n * @param w2 width 2.\r\n * @param edge the edge (left or right).\r\n *\r\n * @return The adjusted x-value.\r\n */\r\n protected double getRectX(double x, double w1, double w2,\r\n RectangleEdge edge) {\r\n\r\n double result = x;\r\n if (edge == RectangleEdge.LEFT) {\r\n result = result + w1;\r\n }\r\n else if (edge == RectangleEdge.RIGHT) {\r\n result = result + w2;\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Adjusts the supplied y-value.\r\n *\r\n * @param y the x-value.\r\n * @param h1 height 1.\r\n * @param h2 height 2.\r\n * @param edge the edge (top or bottom).\r\n *\r\n * @return The adjusted y-value.\r\n */\r\n protected double getRectY(double y, double h1, double h2,\r\n RectangleEdge edge) {\r\n\r\n double result = y;\r\n if (edge == RectangleEdge.TOP) {\r\n result = result + h1;\r\n }\r\n else if (edge == RectangleEdge.BOTTOM) {\r\n result = result + h2;\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Tests this plot for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof Plot)) {\r\n return false;\r\n }\r\n Plot that = (Plot) obj;\r\n if (!ObjectUtilities.equal(this.noDataMessage, that.noDataMessage)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(\r\n this.noDataMessageFont, that.noDataMessageFont\r\n )) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.noDataMessagePaint,\r\n that.noDataMessagePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.insets, that.insets)) {\r\n return false;\r\n }\r\n if (this.outlineVisible != that.outlineVisible) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.outlineStroke, that.outlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.backgroundPaint, that.backgroundPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundImage,\r\n that.backgroundImage)) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlignment != that.backgroundImageAlignment) {\r\n return false;\r\n }\r\n if (this.backgroundImageAlpha != that.backgroundImageAlpha) {\r\n return false;\r\n }\r\n if (this.foregroundAlpha != that.foregroundAlpha) {\r\n return false;\r\n }\r\n if (this.backgroundAlpha != that.backgroundAlpha) {\r\n return false;\r\n }\r\n if (!this.drawingSupplier.equals(that.drawingSupplier)) {\r\n return false;\r\n }\r\n if (this.notify != that.notify) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Creates a clone of the plot.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if some component of the plot does not\r\n * support cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n\r\n Plot clone = (Plot) super.clone();\r\n // private Plot parent <-- don't clone the parent plot, but take care\r\n // childs in combined plots instead\r\n if (this.datasetGroup != null) {\r\n clone.datasetGroup\r\n = (DatasetGroup) ObjectUtilities.clone(this.datasetGroup);\r\n }\r\n clone.drawingSupplier\r\n = (DrawingSupplier) ObjectUtilities.clone(this.drawingSupplier);\r\n clone.listenerList = new EventListenerList();\r\n return clone;\r\n\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writePaint(this.noDataMessagePaint, stream);\r\n SerialUtilities.writeStroke(this.outlineStroke, stream);\r\n SerialUtilities.writePaint(this.outlinePaint, stream);\r\n // backgroundImage\r\n SerialUtilities.writePaint(this.backgroundPaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.noDataMessagePaint = SerialUtilities.readPaint(stream);\r\n this.outlineStroke = SerialUtilities.readStroke(stream);\r\n this.outlinePaint = SerialUtilities.readPaint(stream);\r\n // backgroundImage\r\n this.backgroundPaint = SerialUtilities.readPaint(stream);\r\n\r\n this.listenerList = new EventListenerList();\r\n\r\n }\r\n\r\n /**\r\n * Resolves a domain axis location for a given plot orientation.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param orientation the orientation (<code>null</code> not permitted).\r\n *\r\n * @return The edge (never <code>null</code>).\r\n */\r\n public static RectangleEdge resolveDomainAxisLocation(\r\n AxisLocation location, PlotOrientation orientation) {\r\n\r\n ParamChecks.nullNotPermitted(location, \"location\");\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n\r\n RectangleEdge result = null;\r\n if (location == AxisLocation.TOP_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n }\r\n else if (location == AxisLocation.TOP_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n }\r\n // the above should cover all the options...\r\n if (result == null) {\r\n throw new IllegalStateException(\"resolveDomainAxisLocation()\");\r\n }\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Resolves a range axis location for a given plot orientation.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param orientation the orientation (<code>null</code> not permitted).\r\n *\r\n * @return The edge (never <code>null</code>).\r\n */\r\n public static RectangleEdge resolveRangeAxisLocation(\r\n AxisLocation location, PlotOrientation orientation) {\r\n\r\n ParamChecks.nullNotPermitted(location, \"location\");\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n\r\n RectangleEdge result = null;\r\n if (location == AxisLocation.TOP_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n }\r\n else if (location == AxisLocation.TOP_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.TOP;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_RIGHT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.RIGHT;\r\n }\r\n }\r\n else if (location == AxisLocation.BOTTOM_OR_LEFT) {\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n result = RectangleEdge.BOTTOM;\r\n }\r\n else if (orientation == PlotOrientation.VERTICAL) {\r\n result = RectangleEdge.LEFT;\r\n }\r\n }\r\n\r\n // the above should cover all the options...\r\n if (result == null) {\r\n throw new IllegalStateException(\"resolveRangeAxisLocation()\");\r\n }\r\n return result;\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "PlotOrientation", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/PlotOrientation.java", "snippet": "public final class PlotOrientation implements Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -2508771828190337782L;\r\n\r\n /** For a plot where the range axis is horizontal. */\r\n public static final PlotOrientation HORIZONTAL\r\n = new PlotOrientation(\"PlotOrientation.HORIZONTAL\");\r\n\r\n /** For a plot where the range axis is vertical. */\r\n public static final PlotOrientation VERTICAL\r\n = new PlotOrientation(\"PlotOrientation.VERTICAL\");\r\n\r\n /** The name. */\r\n private String name;\r\n\r\n /**\r\n * Private constructor.\r\n *\r\n * @param name the name.\r\n */\r\n private PlotOrientation(String name) {\r\n this.name = name;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this orientation is <code>HORIZONTAL</code>,\r\n * and <code>false</code> otherwise. \r\n * \r\n * @return A boolean.\r\n * \r\n * @since 1.0.18\r\n */\r\n public boolean isHorizontal() {\r\n return this.equals(PlotOrientation.HORIZONTAL);\r\n }\r\n \r\n /**\r\n * Returns <code>true</code> if this orientation is <code>VERTICAL</code>,\r\n * and <code>false</code> otherwise.\r\n * \r\n * @return A boolean.\r\n * \r\n * @since 1.0.18\r\n */\r\n public boolean isVertical() {\r\n return this.equals(PlotOrientation.VERTICAL);\r\n }\r\n \r\n /**\r\n * Returns a string representing the object.\r\n *\r\n * @return The string.\r\n */\r\n @Override\r\n public String toString() {\r\n return this.name;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this object is equal to the specified\r\n * object, and <code>false</code> otherwise.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) {\r\n return true;\r\n }\r\n if (!(obj instanceof PlotOrientation)) {\r\n return false;\r\n }\r\n PlotOrientation orientation = (PlotOrientation) obj;\r\n if (!this.name.equals(orientation.toString())) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code for this instance.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n return this.name.hashCode();\r\n }\r\n\r\n /**\r\n * Ensures that serialization returns the unique instances.\r\n *\r\n * @return The object.\r\n *\r\n * @throws ObjectStreamException if there is a problem.\r\n */\r\n private Object readResolve() throws ObjectStreamException {\r\n Object result = null;\r\n if (this.equals(PlotOrientation.HORIZONTAL)) {\r\n result = PlotOrientation.HORIZONTAL;\r\n }\r\n else if (this.equals(PlotOrientation.VERTICAL)) {\r\n result = PlotOrientation.VERTICAL;\r\n }\r\n return result;\r\n }\r\n\r\n}\r" }, { "identifier": "PlotRenderingInfo", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/PlotRenderingInfo.java", "snippet": "public class PlotRenderingInfo implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 8446720134379617220L;\r\n\r\n /** The owner of this info. */\r\n private ChartRenderingInfo owner;\r\n\r\n /** The plot area. */\r\n private transient Rectangle2D plotArea;\r\n\r\n /** The data area. */\r\n private transient Rectangle2D dataArea;\r\n\r\n /**\r\n * Storage for the plot rendering info objects belonging to the subplots.\r\n */\r\n private List subplotInfo;\r\n\r\n /**\r\n * Creates a new instance.\r\n *\r\n * @param owner the owner (<code>null</code> permitted).\r\n */\r\n public PlotRenderingInfo(ChartRenderingInfo owner) {\r\n this.owner = owner;\r\n this.dataArea = new Rectangle2D.Double();\r\n this.subplotInfo = new java.util.ArrayList();\r\n }\r\n\r\n /**\r\n * Returns the owner (as specified in the constructor).\r\n *\r\n * @return The owner (possibly <code>null</code>).\r\n */\r\n public ChartRenderingInfo getOwner() {\r\n return this.owner;\r\n }\r\n\r\n /**\r\n * Returns the plot area (in Java2D space).\r\n *\r\n * @return The plot area (possibly <code>null</code>).\r\n *\r\n * @see #setPlotArea(Rectangle2D)\r\n */\r\n public Rectangle2D getPlotArea() {\r\n return this.plotArea;\r\n }\r\n\r\n /**\r\n * Sets the plot area.\r\n *\r\n * @param area the plot area (in Java2D space, <code>null</code>\r\n * permitted but discouraged)\r\n *\r\n * @see #getPlotArea()\r\n */\r\n public void setPlotArea(Rectangle2D area) {\r\n this.plotArea = area;\r\n }\r\n\r\n /**\r\n * Returns the plot's data area (in Java2D space).\r\n *\r\n * @return The data area (possibly <code>null</code>).\r\n *\r\n * @see #setDataArea(Rectangle2D)\r\n */\r\n public Rectangle2D getDataArea() {\r\n return this.dataArea;\r\n }\r\n\r\n /**\r\n * Sets the data area.\r\n *\r\n * @param area the data area (in Java2D space, <code>null</code> permitted\r\n * but discouraged).\r\n *\r\n * @see #getDataArea()\r\n */\r\n public void setDataArea(Rectangle2D area) {\r\n this.dataArea = area;\r\n }\r\n\r\n /**\r\n * Returns the number of subplots (possibly zero).\r\n *\r\n * @return The subplot count.\r\n */\r\n public int getSubplotCount() {\r\n return this.subplotInfo.size();\r\n }\r\n\r\n /**\r\n * Adds the info for a subplot.\r\n *\r\n * @param info the subplot info.\r\n *\r\n * @see #getSubplotInfo(int)\r\n */\r\n public void addSubplotInfo(PlotRenderingInfo info) {\r\n this.subplotInfo.add(info);\r\n }\r\n\r\n /**\r\n * Returns the info for a subplot.\r\n *\r\n * @param index the subplot index.\r\n *\r\n * @return The info.\r\n *\r\n * @see #addSubplotInfo(PlotRenderingInfo)\r\n */\r\n public PlotRenderingInfo getSubplotInfo(int index) {\r\n return (PlotRenderingInfo) this.subplotInfo.get(index);\r\n }\r\n\r\n /**\r\n * Returns the index of the subplot that contains the specified\r\n * (x, y) point (the \"source\" point). The source point will usually\r\n * come from a mouse click on a {@link org.jfree.chart.ChartPanel},\r\n * and this method is then used to determine the subplot that\r\n * contains the source point.\r\n *\r\n * @param source the source point (in Java2D space, <code>null</code> not\r\n * permitted).\r\n *\r\n * @return The subplot index (or -1 if no subplot contains\r\n * <code>source</code>).\r\n */\r\n public int getSubplotIndex(Point2D source) {\r\n ParamChecks.nullNotPermitted(source, \"source\");\r\n int subplotCount = getSubplotCount();\r\n for (int i = 0; i < subplotCount; i++) {\r\n PlotRenderingInfo info = getSubplotInfo(i);\r\n Rectangle2D area = info.getDataArea();\r\n if (area.contains(source)) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Tests this instance for equality against an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) {\r\n return true;\r\n }\r\n if (!(obj instanceof PlotRenderingInfo)) {\r\n return false;\r\n }\r\n PlotRenderingInfo that = (PlotRenderingInfo) obj;\r\n if (!ObjectUtilities.equal(this.dataArea, that.dataArea)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.plotArea, that.plotArea)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.subplotInfo, that.subplotInfo)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a clone of this object.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if there is a problem cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n PlotRenderingInfo clone = (PlotRenderingInfo) super.clone();\r\n if (this.plotArea != null) {\r\n clone.plotArea = (Rectangle2D) this.plotArea.clone();\r\n }\r\n if (this.dataArea != null) {\r\n clone.dataArea = (Rectangle2D) this.dataArea.clone();\r\n }\r\n clone.subplotInfo = new java.util.ArrayList(this.subplotInfo.size());\r\n for (int i = 0; i < this.subplotInfo.size(); i++) {\r\n PlotRenderingInfo info\r\n = (PlotRenderingInfo) this.subplotInfo.get(i);\r\n clone.subplotInfo.add(info.clone());\r\n }\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeShape(this.dataArea, stream);\r\n SerialUtilities.writeShape(this.plotArea, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n stream.defaultReadObject();\r\n this.dataArea = (Rectangle2D) SerialUtilities.readShape(stream);\r\n this.plotArea = (Rectangle2D) SerialUtilities.readShape(stream);\r\n }\r\n\r\n}\r" }, { "identifier": "XYPlot", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/XYPlot.java", "snippet": "public class XYPlot extends Plot implements ValueAxisPlot, Pannable, Zoomable,\r\n RendererChangeListener, Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 7044148245716569264L;\r\n\r\n /** The default grid line stroke. */\r\n public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f,\r\n BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f,\r\n new float[] {2.0f, 2.0f}, 0.0f);\r\n\r\n /** The default grid line paint. */\r\n public static final Paint DEFAULT_GRIDLINE_PAINT = Color.lightGray;\r\n\r\n /** The default crosshair visibility. */\r\n public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false;\r\n\r\n /** The default crosshair stroke. */\r\n public static final Stroke DEFAULT_CROSSHAIR_STROKE\r\n = DEFAULT_GRIDLINE_STROKE;\r\n\r\n /** The default crosshair paint. */\r\n public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.blue;\r\n\r\n /** The resourceBundle for the localization. */\r\n protected static ResourceBundle localizationResources\r\n = ResourceBundleWrapper.getBundle(\r\n \"org.jfree.chart.plot.LocalizationBundle\");\r\n\r\n /** The plot orientation. */\r\n private PlotOrientation orientation;\r\n\r\n /** The offset between the data area and the axes. */\r\n private RectangleInsets axisOffset;\r\n\r\n /** The domain axis / axes (used for the x-values). */\r\n private Map<Integer, ValueAxis> domainAxes;\r\n\r\n /** The domain axis locations. */\r\n private Map<Integer, AxisLocation> domainAxisLocations;\r\n\r\n /** The range axis (used for the y-values). */\r\n private Map<Integer, ValueAxis> rangeAxes;\r\n\r\n /** The range axis location. */\r\n private Map<Integer, AxisLocation> rangeAxisLocations;\r\n\r\n /** Storage for the datasets. */\r\n private Map<Integer, XYDataset> datasets;\r\n\r\n /** Storage for the renderers. */\r\n private Map<Integer, XYItemRenderer> renderers;\r\n\r\n /**\r\n * Storage for the mapping between datasets/renderers and domain axes. The\r\n * keys in the map are Integer objects, corresponding to the dataset\r\n * index. The values in the map are List objects containing Integer\r\n * objects (corresponding to the axis indices). If the map contains no\r\n * entry for a dataset, it is assumed to map to the primary domain axis\r\n * (index = 0).\r\n */\r\n private Map<Integer, List<Integer>> datasetToDomainAxesMap;\r\n\r\n /**\r\n * Storage for the mapping between datasets/renderers and range axes. The\r\n * keys in the map are Integer objects, corresponding to the dataset\r\n * index. The values in the map are List objects containing Integer\r\n * objects (corresponding to the axis indices). If the map contains no\r\n * entry for a dataset, it is assumed to map to the primary domain axis\r\n * (index = 0).\r\n */\r\n private Map<Integer, List<Integer>> datasetToRangeAxesMap;\r\n\r\n /** The origin point for the quadrants (if drawn). */\r\n private transient Point2D quadrantOrigin = new Point2D.Double(0.0, 0.0);\r\n\r\n /** The paint used for each quadrant. */\r\n private transient Paint[] quadrantPaint\r\n = new Paint[] {null, null, null, null};\r\n\r\n /** A flag that controls whether the domain grid-lines are visible. */\r\n private boolean domainGridlinesVisible;\r\n\r\n /** The stroke used to draw the domain grid-lines. */\r\n private transient Stroke domainGridlineStroke;\r\n\r\n /** The paint used to draw the domain grid-lines. */\r\n private transient Paint domainGridlinePaint;\r\n\r\n /** A flag that controls whether the range grid-lines are visible. */\r\n private boolean rangeGridlinesVisible;\r\n\r\n /** The stroke used to draw the range grid-lines. */\r\n private transient Stroke rangeGridlineStroke;\r\n\r\n /** The paint used to draw the range grid-lines. */\r\n private transient Paint rangeGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether the domain minor grid-lines are visible.\r\n *\r\n * @since 1.0.12\r\n */\r\n private boolean domainMinorGridlinesVisible;\r\n\r\n /**\r\n * The stroke used to draw the domain minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Stroke domainMinorGridlineStroke;\r\n\r\n /**\r\n * The paint used to draw the domain minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Paint domainMinorGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether the range minor grid-lines are visible.\r\n *\r\n * @since 1.0.12\r\n */\r\n private boolean rangeMinorGridlinesVisible;\r\n\r\n /**\r\n * The stroke used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Stroke rangeMinorGridlineStroke;\r\n\r\n /**\r\n * The paint used to draw the range minor grid-lines.\r\n *\r\n * @since 1.0.12\r\n */\r\n private transient Paint rangeMinorGridlinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not the zero baseline against the domain\r\n * axis is visible.\r\n *\r\n * @since 1.0.5\r\n */\r\n private boolean domainZeroBaselineVisible;\r\n\r\n /**\r\n * The stroke used for the zero baseline against the domain axis.\r\n *\r\n * @since 1.0.5\r\n */\r\n private transient Stroke domainZeroBaselineStroke;\r\n\r\n /**\r\n * The paint used for the zero baseline against the domain axis.\r\n *\r\n * @since 1.0.5\r\n */\r\n private transient Paint domainZeroBaselinePaint;\r\n\r\n /**\r\n * A flag that controls whether or not the zero baseline against the range\r\n * axis is visible.\r\n */\r\n private boolean rangeZeroBaselineVisible;\r\n\r\n /** The stroke used for the zero baseline against the range axis. */\r\n private transient Stroke rangeZeroBaselineStroke;\r\n\r\n /** The paint used for the zero baseline against the range axis. */\r\n private transient Paint rangeZeroBaselinePaint;\r\n\r\n /** A flag that controls whether or not a domain crosshair is drawn..*/\r\n private boolean domainCrosshairVisible;\r\n\r\n /** The domain crosshair value. */\r\n private double domainCrosshairValue;\r\n\r\n /** The pen/brush used to draw the crosshair (if any). */\r\n private transient Stroke domainCrosshairStroke;\r\n\r\n /** The color used to draw the crosshair (if any). */\r\n private transient Paint domainCrosshairPaint;\r\n\r\n /**\r\n * A flag that controls whether or not the crosshair locks onto actual\r\n * data points.\r\n */\r\n private boolean domainCrosshairLockedOnData = true;\r\n\r\n /** A flag that controls whether or not a range crosshair is drawn..*/\r\n private boolean rangeCrosshairVisible;\r\n\r\n /** The range crosshair value. */\r\n private double rangeCrosshairValue;\r\n\r\n /** The pen/brush used to draw the crosshair (if any). */\r\n private transient Stroke rangeCrosshairStroke;\r\n\r\n /** The color used to draw the crosshair (if any). */\r\n private transient Paint rangeCrosshairPaint;\r\n\r\n /**\r\n * A flag that controls whether or not the crosshair locks onto actual\r\n * data points.\r\n */\r\n private boolean rangeCrosshairLockedOnData = true;\r\n\r\n /** A map of lists of foreground markers (optional) for the domain axes. */\r\n private Map foregroundDomainMarkers;\r\n\r\n /** A map of lists of background markers (optional) for the domain axes. */\r\n private Map backgroundDomainMarkers;\r\n\r\n /** A map of lists of foreground markers (optional) for the range axes. */\r\n private Map foregroundRangeMarkers;\r\n\r\n /** A map of lists of background markers (optional) for the range axes. */\r\n private Map backgroundRangeMarkers;\r\n\r\n /**\r\n * A (possibly empty) list of annotations for the plot. The list should\r\n * be initialised in the constructor and never allowed to be\r\n * <code>null</code>.\r\n */\r\n private List<XYAnnotation> annotations;\r\n\r\n /** The paint used for the domain tick bands (if any). */\r\n private transient Paint domainTickBandPaint;\r\n\r\n /** The paint used for the range tick bands (if any). */\r\n private transient Paint rangeTickBandPaint;\r\n\r\n /** The fixed domain axis space. */\r\n private AxisSpace fixedDomainAxisSpace;\r\n\r\n /** The fixed range axis space. */\r\n private AxisSpace fixedRangeAxisSpace;\r\n\r\n /**\r\n * The order of the dataset rendering (REVERSE draws the primary dataset\r\n * last so that it appears to be on top).\r\n */\r\n private DatasetRenderingOrder datasetRenderingOrder\r\n = DatasetRenderingOrder.REVERSE;\r\n\r\n /**\r\n * The order of the series rendering (REVERSE draws the primary series\r\n * last so that it appears to be on top).\r\n */\r\n private SeriesRenderingOrder seriesRenderingOrder\r\n = SeriesRenderingOrder.REVERSE;\r\n\r\n /**\r\n * The weight for this plot (only relevant if this is a subplot in a\r\n * combined plot).\r\n */\r\n private int weight;\r\n\r\n /**\r\n * An optional collection of legend items that can be returned by the\r\n * getLegendItems() method.\r\n */\r\n private LegendItemCollection fixedLegendItems;\r\n\r\n /**\r\n * A flag that controls whether or not panning is enabled for the domain\r\n * axis/axes.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean domainPannable;\r\n\r\n /**\r\n * A flag that controls whether or not panning is enabled for the range\r\n * axis/axes.\r\n *\r\n * @since 1.0.13\r\n */\r\n private boolean rangePannable;\r\n\r\n /**\r\n * The shadow generator (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n private ShadowGenerator shadowGenerator;\r\n\r\n /**\r\n * Creates a new <code>XYPlot</code> instance with no dataset, no axes and\r\n * no renderer. You should specify these items before using the plot.\r\n */\r\n public XYPlot() {\r\n this(null, null, null, null);\r\n }\r\n\r\n /**\r\n * Creates a new plot with the specified dataset, axes and renderer. Any\r\n * of the arguments can be <code>null</code>, but in that case you should\r\n * take care to specify the value before using the plot (otherwise a\r\n * <code>NullPointerException</code> may be thrown).\r\n *\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n * @param domainAxis the domain axis (<code>null</code> permitted).\r\n * @param rangeAxis the range axis (<code>null</code> permitted).\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n */\r\n public XYPlot(XYDataset dataset, ValueAxis domainAxis, ValueAxis rangeAxis,\r\n XYItemRenderer renderer) {\r\n super();\r\n this.orientation = PlotOrientation.VERTICAL;\r\n this.weight = 1; // only relevant when this is a subplot\r\n this.axisOffset = RectangleInsets.ZERO_INSETS;\r\n\r\n // allocate storage for datasets, axes and renderers (all optional)\r\n this.domainAxes = new HashMap<Integer, ValueAxis>();\r\n this.domainAxisLocations = new HashMap<Integer, AxisLocation>();\r\n this.foregroundDomainMarkers = new HashMap();\r\n this.backgroundDomainMarkers = new HashMap();\r\n\r\n this.rangeAxes = new HashMap<Integer, ValueAxis>();\r\n this.rangeAxisLocations = new HashMap<Integer, AxisLocation>();\r\n this.foregroundRangeMarkers = new HashMap();\r\n this.backgroundRangeMarkers = new HashMap();\r\n\r\n this.datasets = new HashMap<Integer, XYDataset>();\r\n this.renderers = new HashMap<Integer, XYItemRenderer>();\r\n\r\n this.datasetToDomainAxesMap = new TreeMap();\r\n this.datasetToRangeAxesMap = new TreeMap();\r\n\r\n this.annotations = new java.util.ArrayList();\r\n\r\n this.datasets.put(0, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n\r\n this.renderers.put(0, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n\r\n this.domainAxes.put(0, domainAxis);\r\n mapDatasetToDomainAxis(0, 0);\r\n if (domainAxis != null) {\r\n domainAxis.setPlot(this);\r\n domainAxis.addChangeListener(this);\r\n }\r\n this.domainAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT);\r\n\r\n this.rangeAxes.put(0, rangeAxis);\r\n mapDatasetToRangeAxis(0, 0);\r\n if (rangeAxis != null) {\r\n rangeAxis.setPlot(this);\r\n rangeAxis.addChangeListener(this);\r\n }\r\n this.rangeAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT);\r\n\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n\r\n this.domainGridlinesVisible = true;\r\n this.domainGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.domainGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.domainMinorGridlinesVisible = false;\r\n this.domainMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.domainMinorGridlinePaint = Color.white;\r\n\r\n this.domainZeroBaselineVisible = false;\r\n this.domainZeroBaselinePaint = Color.black;\r\n this.domainZeroBaselineStroke = new BasicStroke(0.5f);\r\n\r\n this.rangeGridlinesVisible = true;\r\n this.rangeGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeGridlinePaint = DEFAULT_GRIDLINE_PAINT;\r\n\r\n this.rangeMinorGridlinesVisible = false;\r\n this.rangeMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE;\r\n this.rangeMinorGridlinePaint = Color.white;\r\n\r\n this.rangeZeroBaselineVisible = false;\r\n this.rangeZeroBaselinePaint = Color.black;\r\n this.rangeZeroBaselineStroke = new BasicStroke(0.5f);\r\n\r\n this.domainCrosshairVisible = false;\r\n this.domainCrosshairValue = 0.0;\r\n this.domainCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.domainCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n\r\n this.rangeCrosshairVisible = false;\r\n this.rangeCrosshairValue = 0.0;\r\n this.rangeCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;\r\n this.rangeCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;\r\n this.shadowGenerator = null;\r\n }\r\n\r\n /**\r\n * Returns the plot type as a string.\r\n *\r\n * @return A short string describing the type of plot.\r\n */\r\n @Override\r\n public String getPlotType() {\r\n return localizationResources.getString(\"XY_Plot\");\r\n }\r\n\r\n /**\r\n * Returns the orientation of the plot.\r\n *\r\n * @return The orientation (never <code>null</code>).\r\n *\r\n * @see #setOrientation(PlotOrientation)\r\n */\r\n @Override\r\n public PlotOrientation getOrientation() {\r\n return this.orientation;\r\n }\r\n\r\n /**\r\n * Sets the orientation for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param orientation the orientation (<code>null</code> not allowed).\r\n *\r\n * @see #getOrientation()\r\n */\r\n public void setOrientation(PlotOrientation orientation) {\r\n ParamChecks.nullNotPermitted(orientation, \"orientation\");\r\n if (orientation != this.orientation) {\r\n this.orientation = orientation;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the axis offset.\r\n *\r\n * @return The axis offset (never <code>null</code>).\r\n *\r\n * @see #setAxisOffset(RectangleInsets)\r\n */\r\n public RectangleInsets getAxisOffset() {\r\n return this.axisOffset;\r\n }\r\n\r\n /**\r\n * Sets the axis offsets (gap between the data area and the axes) and sends\r\n * a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param offset the offset (<code>null</code> not permitted).\r\n *\r\n * @see #getAxisOffset()\r\n */\r\n public void setAxisOffset(RectangleInsets offset) {\r\n ParamChecks.nullNotPermitted(offset, \"offset\");\r\n this.axisOffset = offset;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the domain axis with index 0. If the domain axis for this plot\r\n * is <code>null</code>, then the method will return the parent plot's\r\n * domain axis (if there is a parent plot).\r\n *\r\n * @return The domain axis (possibly <code>null</code>).\r\n *\r\n * @see #getDomainAxis(int)\r\n * @see #setDomainAxis(ValueAxis)\r\n */\r\n public ValueAxis getDomainAxis() {\r\n return getDomainAxis(0);\r\n }\r\n\r\n /**\r\n * Returns the domain axis with the specified index, or {@code null} if \r\n * there is no axis with that index.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The axis ({@code null} possible).\r\n *\r\n * @see #setDomainAxis(int, ValueAxis)\r\n */\r\n public ValueAxis getDomainAxis(int index) {\r\n ValueAxis result = this.domainAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot xy = (XYPlot) parent;\r\n result = xy.getDomainAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the domain axis for the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axis the new axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis()\r\n * @see #setDomainAxis(int, ValueAxis)\r\n */\r\n public void setDomainAxis(ValueAxis axis) {\r\n setDomainAxis(0, axis);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getDomainAxis(int)\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public void setDomainAxis(int index, ValueAxis axis) {\r\n setDomainAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a domain axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainAxis(int)\r\n */\r\n public void setDomainAxis(int index, ValueAxis axis, boolean notify) {\r\n ValueAxis existing = getDomainAxis(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.domainAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the domain axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setRangeAxes(ValueAxis[])\r\n */\r\n public void setDomainAxes(ValueAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setDomainAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the location of the primary domain axis.\r\n *\r\n * @return The location (never <code>null</code>).\r\n *\r\n * @see #setDomainAxisLocation(AxisLocation)\r\n */\r\n public AxisLocation getDomainAxisLocation() {\r\n return (AxisLocation) this.domainAxisLocations.get(0);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary domain axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainAxisLocation()\r\n */\r\n public void setDomainAxisLocation(AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainAxisLocation()\r\n */\r\n public void setDomainAxisLocation(AxisLocation location, boolean notify) {\r\n // delegate...\r\n setDomainAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Returns the edge for the primary domain axis (taking into account the\r\n * plot's orientation).\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getDomainAxisLocation()\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getDomainAxisEdge() {\r\n return Plot.resolveDomainAxisLocation(getDomainAxisLocation(),\r\n this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the number of domain axes.\r\n *\r\n * @return The axis count.\r\n *\r\n * @see #getRangeAxisCount()\r\n */\r\n public int getDomainAxisCount() {\r\n return this.domainAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the domain axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #clearRangeAxes()\r\n */\r\n public void clearDomainAxes() {\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.removeChangeListener(this);\r\n }\r\n }\r\n this.domainAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the domain axes.\r\n */\r\n public void configureDomainAxes() {\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the location for a domain axis. If this hasn't been set\r\n * explicitly, the method returns the location that is opposite to the\r\n * primary domain axis location.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The location (never {@code null}).\r\n *\r\n * @see #setDomainAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getDomainAxisLocation(int index) {\r\n AxisLocation result = this.domainAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getDomainAxisLocation());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location for a domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> not permitted for index\r\n * 0).\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location) {\r\n // delegate...\r\n setDomainAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the axis location for a domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n * @param location the location (<code>null</code> not permitted for\r\n * index 0).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getDomainAxisLocation(int)\r\n * @see #setRangeAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setDomainAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.domainAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the edge for a domain axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getRangeAxisEdge(int)\r\n */\r\n public RectangleEdge getDomainAxisEdge(int index) {\r\n AxisLocation location = getDomainAxisLocation(index);\r\n return Plot.resolveDomainAxisLocation(location, this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the range axis for the plot. If the range axis for this plot is\r\n * <code>null</code>, then the method will return the parent plot's range\r\n * axis (if there is a parent plot).\r\n *\r\n * @return The range axis.\r\n *\r\n * @see #getRangeAxis(int)\r\n * @see #setRangeAxis(ValueAxis)\r\n */\r\n public ValueAxis getRangeAxis() {\r\n return getRangeAxis(0);\r\n }\r\n\r\n /**\r\n * Sets the range axis for the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxis()\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public void setRangeAxis(ValueAxis axis) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n // plot is likely registered as a listener with the existing axis...\r\n ValueAxis existing = getRangeAxis();\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.rangeAxes.put(0, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the location of the primary range axis.\r\n *\r\n * @return The location (never <code>null</code>).\r\n *\r\n * @see #setRangeAxisLocation(AxisLocation)\r\n */\r\n public AxisLocation getRangeAxisLocation() {\r\n return (AxisLocation) this.rangeAxisLocations.get(0);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary range axis and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeAxisLocation()\r\n */\r\n public void setRangeAxisLocation(AxisLocation location) {\r\n // delegate...\r\n setRangeAxisLocation(0, location, true);\r\n }\r\n\r\n /**\r\n * Sets the location of the primary range axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param location the location (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRangeAxisLocation()\r\n */\r\n public void setRangeAxisLocation(AxisLocation location, boolean notify) {\r\n // delegate...\r\n setRangeAxisLocation(0, location, notify);\r\n }\r\n\r\n /**\r\n * Returns the edge for the primary range axis.\r\n *\r\n * @return The range axis edge.\r\n *\r\n * @see #getRangeAxisLocation()\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getRangeAxisEdge() {\r\n return Plot.resolveRangeAxisLocation(getRangeAxisLocation(),\r\n this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the range axis with the specified index, or {@code null} if \r\n * there is no axis with that index.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The axis ({@code null} possible).\r\n *\r\n * @see #setRangeAxis(int, ValueAxis)\r\n */\r\n public ValueAxis getRangeAxis(int index) {\r\n ValueAxis result = this.rangeAxes.get(index);\r\n if (result == null) {\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot xy = (XYPlot) parent;\r\n result = xy.getRangeAxis(index);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets a range axis and sends a {@link PlotChangeEvent} to all registered\r\n * listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxis(int)\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis) {\r\n setRangeAxis(index, axis, true);\r\n }\r\n\r\n /**\r\n * Sets a range axis and, if requested, sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param axis the axis (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRangeAxis(int)\r\n */\r\n public void setRangeAxis(int index, ValueAxis axis, boolean notify) {\r\n ValueAxis existing = getRangeAxis(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n }\r\n this.rangeAxes.put(index, axis);\r\n if (axis != null) {\r\n axis.configure();\r\n axis.addChangeListener(this);\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the range axes for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param axes the axes (<code>null</code> not permitted).\r\n *\r\n * @see #setDomainAxes(ValueAxis[])\r\n */\r\n public void setRangeAxes(ValueAxis[] axes) {\r\n for (int i = 0; i < axes.length; i++) {\r\n setRangeAxis(i, axes[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the number of range axes.\r\n *\r\n * @return The axis count.\r\n *\r\n * @see #getDomainAxisCount()\r\n */\r\n public int getRangeAxisCount() {\r\n return this.rangeAxes.size();\r\n }\r\n\r\n /**\r\n * Clears the range axes from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @see #clearDomainAxes()\r\n */\r\n public void clearRangeAxes() {\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.removeChangeListener(this);\r\n }\r\n }\r\n this.rangeAxes.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Configures the range axes.\r\n *\r\n * @see #configureDomainAxes()\r\n */\r\n public void configureRangeAxes() {\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.configure();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the location for a range axis. If this hasn't been set\r\n * explicitly, the method returns the location that is opposite to the\r\n * primary range axis location.\r\n *\r\n * @param index the axis index (must be &gt;= 0).\r\n *\r\n * @return The location (never {@code null}).\r\n *\r\n * @see #setRangeAxisLocation(int, AxisLocation)\r\n */\r\n public AxisLocation getRangeAxisLocation(int index) {\r\n AxisLocation result = this.rangeAxisLocations.get(index);\r\n if (result == null) {\r\n result = AxisLocation.getOpposite(getRangeAxisLocation());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sets the location for a range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> permitted).\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location) {\r\n // delegate...\r\n setRangeAxisLocation(index, location, true);\r\n }\r\n\r\n /**\r\n * Sets the axis location for a domain axis and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the axis index.\r\n * @param location the location (<code>null</code> not permitted for\r\n * index 0).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #setDomainAxisLocation(int, AxisLocation, boolean)\r\n */\r\n public void setRangeAxisLocation(int index, AxisLocation location,\r\n boolean notify) {\r\n if (index == 0 && location == null) {\r\n throw new IllegalArgumentException(\r\n \"Null 'location' for index 0 not permitted.\");\r\n }\r\n this.rangeAxisLocations.put(index, location);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the edge for a range axis.\r\n *\r\n * @param index the axis index.\r\n *\r\n * @return The edge.\r\n *\r\n * @see #getRangeAxisLocation(int)\r\n * @see #getOrientation()\r\n */\r\n public RectangleEdge getRangeAxisEdge(int index) {\r\n AxisLocation location = getRangeAxisLocation(index);\r\n return Plot.resolveRangeAxisLocation(location, this.orientation);\r\n }\r\n\r\n /**\r\n * Returns the primary dataset for the plot.\r\n *\r\n * @return The primary dataset (possibly <code>null</code>).\r\n *\r\n * @see #getDataset(int)\r\n * @see #setDataset(XYDataset)\r\n */\r\n public XYDataset getDataset() {\r\n return getDataset(0);\r\n }\r\n\r\n /**\r\n * Returns the dataset with the specified index, or {@code null} if there\r\n * is no dataset with that index.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The dataset (possibly {@code null}).\r\n *\r\n * @see #setDataset(int, XYDataset)\r\n */\r\n public XYDataset getDataset(int index) {\r\n return (XYDataset) this.datasets.get(index);\r\n }\r\n\r\n /**\r\n * Sets the primary dataset for the plot, replacing the existing dataset if\r\n * there is one.\r\n *\r\n * @param dataset the dataset ({@code null} permitted).\r\n *\r\n * @see #getDataset()\r\n * @see #setDataset(int, XYDataset)\r\n */\r\n public void setDataset(XYDataset dataset) {\r\n setDataset(0, dataset);\r\n }\r\n\r\n /**\r\n * Sets a dataset for the plot and sends a change event to all registered\r\n * listeners.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n * @param dataset the dataset (<code>null</code> permitted).\r\n *\r\n * @see #getDataset(int)\r\n */\r\n public void setDataset(int index, XYDataset dataset) {\r\n XYDataset existing = getDataset(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.datasets.put(index, dataset);\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n\r\n // send a dataset change event to self...\r\n DatasetChangeEvent event = new DatasetChangeEvent(this, dataset);\r\n datasetChanged(event);\r\n }\r\n\r\n /**\r\n * Returns the number of datasets.\r\n *\r\n * @return The number of datasets.\r\n */\r\n public int getDatasetCount() {\r\n return this.datasets.size();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified dataset, or {@code -1} if the\r\n * dataset does not belong to the plot.\r\n *\r\n * @param dataset the dataset ({@code null} not permitted).\r\n *\r\n * @return The index or -1.\r\n */\r\n public int indexOf(XYDataset dataset) {\r\n for (Map.Entry<Integer, XYDataset> entry: this.datasets.entrySet()) {\r\n if (dataset == entry.getValue()) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular domain axis. All data will be plotted\r\n * against axis zero by default, no mapping is required for this case.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index.\r\n *\r\n * @see #mapDatasetToRangeAxis(int, int)\r\n */\r\n public void mapDatasetToDomainAxis(int index, int axisIndex) {\r\n List axisIndices = new java.util.ArrayList(1);\r\n axisIndices.add(new Integer(axisIndex));\r\n mapDatasetToDomainAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToDomainAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n Integer key = new Integer(index);\r\n this.datasetToDomainAxesMap.put(key, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * Maps a dataset to a particular range axis. All data will be plotted\r\n * against axis zero by default, no mapping is required for this case.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndex the axis index.\r\n *\r\n * @see #mapDatasetToDomainAxis(int, int)\r\n */\r\n public void mapDatasetToRangeAxis(int index, int axisIndex) {\r\n List axisIndices = new java.util.ArrayList(1);\r\n axisIndices.add(new Integer(axisIndex));\r\n mapDatasetToRangeAxes(index, axisIndices);\r\n }\r\n\r\n /**\r\n * Maps the specified dataset to the axes in the list. Note that the\r\n * conversion of data values into Java2D space is always performed using\r\n * the first axis in the list.\r\n *\r\n * @param index the dataset index (zero-based).\r\n * @param axisIndices the axis indices (<code>null</code> permitted).\r\n *\r\n * @since 1.0.12\r\n */\r\n public void mapDatasetToRangeAxes(int index, List axisIndices) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n checkAxisIndices(axisIndices);\r\n Integer key = new Integer(index);\r\n this.datasetToRangeAxesMap.put(key, new ArrayList(axisIndices));\r\n // fake a dataset change event to update axes...\r\n datasetChanged(new DatasetChangeEvent(this, getDataset(index)));\r\n }\r\n\r\n /**\r\n * This method is used to perform argument checking on the list of\r\n * axis indices passed to mapDatasetToDomainAxes() and\r\n * mapDatasetToRangeAxes().\r\n *\r\n * @param indices the list of indices (<code>null</code> permitted).\r\n */\r\n private void checkAxisIndices(List<Integer> indices) {\r\n // axisIndices can be:\r\n // 1. null;\r\n // 2. non-empty, containing only Integer objects that are unique.\r\n if (indices == null) {\r\n return; // OK\r\n }\r\n int count = indices.size();\r\n if (count == 0) {\r\n throw new IllegalArgumentException(\"Empty list not permitted.\");\r\n }\r\n Set<Integer> set = new HashSet<Integer>();\r\n for (Integer item : indices) {\r\n if (set.contains(item)) {\r\n throw new IllegalArgumentException(\"Indices must be unique.\");\r\n }\r\n set.add(item);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the number of renderer slots for this plot.\r\n *\r\n * @return The number of renderer slots.\r\n *\r\n * @since 1.0.11\r\n */\r\n public int getRendererCount() {\r\n return this.renderers.size();\r\n }\r\n\r\n /**\r\n * Returns the renderer for the primary dataset.\r\n *\r\n * @return The item renderer (possibly <code>null</code>).\r\n *\r\n * @see #setRenderer(XYItemRenderer)\r\n */\r\n public XYItemRenderer getRenderer() {\r\n return getRenderer(0);\r\n }\r\n\r\n /**\r\n * Returns the renderer with the specified index, or {@code null}.\r\n *\r\n * @param index the renderer index (must be &gt;= 0).\r\n *\r\n * @return The renderer (possibly {@code null}).\r\n *\r\n * @see #setRenderer(int, XYItemRenderer)\r\n */\r\n public XYItemRenderer getRenderer(int index) {\r\n return (XYItemRenderer) this.renderers.get(index);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the primary dataset and sends a change event to \r\n * all registered listeners. If the renderer is set to <code>null</code>, \r\n * no data will be displayed.\r\n *\r\n * @param renderer the renderer ({@code null} permitted).\r\n *\r\n * @see #getRenderer()\r\n */\r\n public void setRenderer(XYItemRenderer renderer) {\r\n setRenderer(0, renderer);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the dataset with the specified index and sends a \r\n * change event to all registered listeners. Note that each dataset should \r\n * have its own renderer, you should not use one renderer for multiple \r\n * datasets.\r\n *\r\n * @param index the index (must be &gt;= 0).\r\n * @param renderer the renderer.\r\n *\r\n * @see #getRenderer(int)\r\n */\r\n public void setRenderer(int index, XYItemRenderer renderer) {\r\n setRenderer(index, renderer, true);\r\n }\r\n\r\n /**\r\n * Sets the renderer for the dataset with the specified index and, if \r\n * requested, sends a change event to all registered listeners. Note that \r\n * each dataset should have its own renderer, you should not use one \r\n * renderer for multiple datasets.\r\n *\r\n * @param index the index (must be &gt;= 0).\r\n * @param renderer the renderer.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getRenderer(int)\r\n */\r\n public void setRenderer(int index, XYItemRenderer renderer, \r\n boolean notify) {\r\n XYItemRenderer existing = getRenderer(index);\r\n if (existing != null) {\r\n existing.removeChangeListener(this);\r\n }\r\n this.renderers.put(index, renderer);\r\n if (renderer != null) {\r\n renderer.setPlot(this);\r\n renderer.addChangeListener(this);\r\n }\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the renderers for this plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param renderers the renderers (<code>null</code> not permitted).\r\n */\r\n public void setRenderers(XYItemRenderer[] renderers) {\r\n for (int i = 0; i < renderers.length; i++) {\r\n setRenderer(i, renderers[i], false);\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the dataset rendering order.\r\n *\r\n * @return The order (never <code>null</code>).\r\n *\r\n * @see #setDatasetRenderingOrder(DatasetRenderingOrder)\r\n */\r\n public DatasetRenderingOrder getDatasetRenderingOrder() {\r\n return this.datasetRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the rendering order and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. By default, the plot renders the primary dataset\r\n * last (so that the primary dataset overlays the secondary datasets).\r\n * You can reverse this if you want to.\r\n *\r\n * @param order the rendering order (<code>null</code> not permitted).\r\n *\r\n * @see #getDatasetRenderingOrder()\r\n */\r\n public void setDatasetRenderingOrder(DatasetRenderingOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.datasetRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the series rendering order.\r\n *\r\n * @return the order (never <code>null</code>).\r\n *\r\n * @see #setSeriesRenderingOrder(SeriesRenderingOrder)\r\n */\r\n public SeriesRenderingOrder getSeriesRenderingOrder() {\r\n return this.seriesRenderingOrder;\r\n }\r\n\r\n /**\r\n * Sets the series order and sends a {@link PlotChangeEvent} to all\r\n * registered listeners. By default, the plot renders the primary series\r\n * last (so that the primary series appears to be on top).\r\n * You can reverse this if you want to.\r\n *\r\n * @param order the rendering order (<code>null</code> not permitted).\r\n *\r\n * @see #getSeriesRenderingOrder()\r\n */\r\n public void setSeriesRenderingOrder(SeriesRenderingOrder order) {\r\n ParamChecks.nullNotPermitted(order, \"order\");\r\n this.seriesRenderingOrder = order;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified renderer, or <code>-1</code> if the\r\n * renderer is not assigned to this plot.\r\n *\r\n * @param renderer the renderer (<code>null</code> permitted).\r\n *\r\n * @return The renderer index.\r\n */\r\n public int getIndexOf(XYItemRenderer renderer) {\r\n for (Map.Entry<Integer, XYItemRenderer> entry \r\n : this.renderers.entrySet()) {\r\n if (entry.getValue() == renderer) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the renderer for the specified dataset (this is either the\r\n * renderer with the same index as the dataset or, if there isn't a \r\n * renderer with the same index, the default renderer). If the dataset\r\n * does not belong to the plot, this method will return {@code null}.\r\n *\r\n * @param dataset the dataset ({@code null} permitted).\r\n *\r\n * @return The renderer (possibly {@code null}).\r\n */\r\n public XYItemRenderer getRendererForDataset(XYDataset dataset) {\r\n int datasetIndex = indexOf(dataset);\r\n if (datasetIndex < 0) {\r\n return null;\r\n } \r\n XYItemRenderer result = this.renderers.get(datasetIndex);\r\n if (result == null) {\r\n result = getRenderer();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the weight for this plot when it is used as a subplot within a\r\n * combined plot.\r\n *\r\n * @return The weight.\r\n *\r\n * @see #setWeight(int)\r\n */\r\n public int getWeight() {\r\n return this.weight;\r\n }\r\n\r\n /**\r\n * Sets the weight for the plot and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param weight the weight.\r\n *\r\n * @see #getWeight()\r\n */\r\n public void setWeight(int weight) {\r\n this.weight = weight;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the domain gridlines are visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setDomainGridlinesVisible(boolean)\r\n */\r\n public boolean isDomainGridlinesVisible() {\r\n return this.domainGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the domain grid-lines are\r\n * visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isDomainGridlinesVisible()\r\n */\r\n public void setDomainGridlinesVisible(boolean visible) {\r\n if (this.domainGridlinesVisible != visible) {\r\n this.domainGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the domain minor gridlines are visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n *\r\n * @see #setDomainMinorGridlinesVisible(boolean)\r\n *\r\n * @since 1.0.12\r\n */\r\n public boolean isDomainMinorGridlinesVisible() {\r\n return this.domainMinorGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the domain minor grid-lines\r\n * are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isDomainMinorGridlinesVisible()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlinesVisible(boolean visible) {\r\n if (this.domainMinorGridlinesVisible != visible) {\r\n this.domainMinorGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the grid-lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlineStroke(Stroke)\r\n */\r\n public Stroke getDomainGridlineStroke() {\r\n return this.domainGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the grid lines plotted against the domain axis, and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>stroke</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainGridlineStroke()\r\n */\r\n public void setDomainGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke for the minor grid-lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainMinorGridlineStroke(Stroke)\r\n *\r\n * @since 1.0.12\r\n */\r\n\r\n public Stroke getDomainMinorGridlineStroke() {\r\n return this.domainMinorGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the minor grid lines plotted against the domain\r\n * axis, and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>stroke</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainMinorGridlineStroke()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainMinorGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the grid lines (if any) plotted against the domain\r\n * axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainGridlinePaint(Paint)\r\n */\r\n public Paint getDomainGridlinePaint() {\r\n return this.domainGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the grid lines plotted against the domain axis, and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>paint</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainGridlinePaint()\r\n */\r\n public void setDomainGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the minor grid lines (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainMinorGridlinePaint(Paint)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Paint getDomainMinorGridlinePaint() {\r\n return this.domainMinorGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the minor grid lines plotted against the domain axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @throws IllegalArgumentException if <code>paint</code> is\r\n * <code>null</code>.\r\n *\r\n * @see #getDomainMinorGridlinePaint()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setDomainMinorGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainMinorGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range axis grid is visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeGridlinesVisible(boolean)\r\n */\r\n public boolean isRangeGridlinesVisible() {\r\n return this.rangeGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the range axis grid lines\r\n * are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeGridlinesVisible()\r\n */\r\n public void setRangeGridlinesVisible(boolean visible) {\r\n if (this.rangeGridlinesVisible != visible) {\r\n this.rangeGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlineStroke(Stroke)\r\n */\r\n public Stroke getRangeGridlineStroke() {\r\n return this.rangeGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the grid lines plotted against the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlineStroke()\r\n */\r\n public void setRangeGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the grid lines (if any) plotted against the range\r\n * axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeGridlinePaint(Paint)\r\n */\r\n public Paint getRangeGridlinePaint() {\r\n return this.rangeGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the grid lines plotted against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeGridlinePaint()\r\n */\r\n public void setRangeGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range axis minor grid is visible, and\r\n * <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeMinorGridlinesVisible(boolean)\r\n *\r\n * @since 1.0.12\r\n */\r\n public boolean isRangeMinorGridlinesVisible() {\r\n return this.rangeMinorGridlinesVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the range axis minor grid\r\n * lines are visible.\r\n * <p>\r\n * If the flag value is changed, a {@link PlotChangeEvent} is sent to all\r\n * registered listeners.\r\n *\r\n * @param visible the new value of the flag.\r\n *\r\n * @see #isRangeMinorGridlinesVisible()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlinesVisible(boolean visible) {\r\n if (this.rangeMinorGridlinesVisible != visible) {\r\n this.rangeMinorGridlinesVisible = visible;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlineStroke(Stroke)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Stroke getRangeMinorGridlineStroke() {\r\n return this.rangeMinorGridlineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the minor grid lines plotted against the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlineStroke()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeMinorGridlineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the minor grid lines (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeMinorGridlinePaint(Paint)\r\n *\r\n * @since 1.0.12\r\n */\r\n public Paint getRangeMinorGridlinePaint() {\r\n return this.rangeMinorGridlinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the minor grid lines plotted against the range axis\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeMinorGridlinePaint()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setRangeMinorGridlinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeMinorGridlinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a zero baseline is\r\n * displayed for the domain axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setDomainZeroBaselineVisible(boolean)\r\n */\r\n public boolean isDomainZeroBaselineVisible() {\r\n return this.domainZeroBaselineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the zero baseline is\r\n * displayed for the domain axis, and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #isDomainZeroBaselineVisible()\r\n */\r\n public void setDomainZeroBaselineVisible(boolean visible) {\r\n this.domainZeroBaselineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used for the zero baseline against the domain axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #setDomainZeroBaselineStroke(Stroke)\r\n */\r\n public Stroke getDomainZeroBaselineStroke() {\r\n return this.domainZeroBaselineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the zero baseline for the domain axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getRangeZeroBaselineStroke()\r\n */\r\n public void setDomainZeroBaselineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainZeroBaselineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the zero baseline (if any) plotted against the\r\n * domain axis.\r\n *\r\n * @since 1.0.5\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setDomainZeroBaselinePaint(Paint)\r\n */\r\n public Paint getDomainZeroBaselinePaint() {\r\n return this.domainZeroBaselinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the zero baseline plotted against the domain axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.5\r\n *\r\n * @see #getDomainZeroBaselinePaint()\r\n */\r\n public void setDomainZeroBaselinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainZeroBaselinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not a zero baseline is\r\n * displayed for the range axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n */\r\n public boolean isRangeZeroBaselineVisible() {\r\n return this.rangeZeroBaselineVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether or not the zero baseline is\r\n * displayed for the range axis, and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isRangeZeroBaselineVisible()\r\n */\r\n public void setRangeZeroBaselineVisible(boolean visible) {\r\n this.rangeZeroBaselineVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the stroke used for the zero baseline against the range axis.\r\n *\r\n * @return The stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselineStroke(Stroke)\r\n */\r\n public Stroke getRangeZeroBaselineStroke() {\r\n return this.rangeZeroBaselineStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke for the zero baseline for the range axis,\r\n * and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the stroke (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselineStroke()\r\n */\r\n public void setRangeZeroBaselineStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeZeroBaselineStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint for the zero baseline (if any) plotted against the\r\n * range axis.\r\n *\r\n * @return The paint (never <code>null</code>).\r\n *\r\n * @see #setRangeZeroBaselinePaint(Paint)\r\n */\r\n public Paint getRangeZeroBaselinePaint() {\r\n return this.rangeZeroBaselinePaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the zero baseline plotted against the range axis and\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeZeroBaselinePaint()\r\n */\r\n public void setRangeZeroBaselinePaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeZeroBaselinePaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the domain tick bands. If this is\r\n * <code>null</code>, no tick bands will be drawn.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setDomainTickBandPaint(Paint)\r\n */\r\n public Paint getDomainTickBandPaint() {\r\n return this.domainTickBandPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the domain tick bands.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getDomainTickBandPaint()\r\n */\r\n public void setDomainTickBandPaint(Paint paint) {\r\n this.domainTickBandPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the range tick bands. If this is\r\n * <code>null</code>, no tick bands will be drawn.\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setRangeTickBandPaint(Paint)\r\n */\r\n public Paint getRangeTickBandPaint() {\r\n return this.rangeTickBandPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint for the range tick bands.\r\n *\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getRangeTickBandPaint()\r\n */\r\n public void setRangeTickBandPaint(Paint paint) {\r\n this.rangeTickBandPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the origin for the quadrants that can be displayed on the plot.\r\n * This defaults to (0, 0).\r\n *\r\n * @return The origin point (never <code>null</code>).\r\n *\r\n * @see #setQuadrantOrigin(Point2D)\r\n */\r\n public Point2D getQuadrantOrigin() {\r\n return this.quadrantOrigin;\r\n }\r\n\r\n /**\r\n * Sets the quadrant origin and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param origin the origin (<code>null</code> not permitted).\r\n *\r\n * @see #getQuadrantOrigin()\r\n */\r\n public void setQuadrantOrigin(Point2D origin) {\r\n ParamChecks.nullNotPermitted(origin, \"origin\");\r\n this.quadrantOrigin = origin;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the paint used for the specified quadrant.\r\n *\r\n * @param index the quadrant index (0-3).\r\n *\r\n * @return The paint (possibly <code>null</code>).\r\n *\r\n * @see #setQuadrantPaint(int, Paint)\r\n */\r\n public Paint getQuadrantPaint(int index) {\r\n if (index < 0 || index > 3) {\r\n throw new IllegalArgumentException(\"The index value (\" + index\r\n + \") should be in the range 0 to 3.\");\r\n }\r\n return this.quadrantPaint[index];\r\n }\r\n\r\n /**\r\n * Sets the paint used for the specified quadrant and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the quadrant index (0-3).\r\n * @param paint the paint (<code>null</code> permitted).\r\n *\r\n * @see #getQuadrantPaint(int)\r\n */\r\n public void setQuadrantPaint(int index, Paint paint) {\r\n if (index < 0 || index > 3) {\r\n throw new IllegalArgumentException(\"The index value (\" + index\r\n + \") should be in the range 0 to 3.\");\r\n }\r\n this.quadrantPaint[index] = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #addDomainMarker(Marker, Layer)\r\n * @see #clearDomainMarkers()\r\n */\r\n public void addDomainMarker(Marker marker) {\r\n // defer argument checking...\r\n addDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for the domain axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void addDomainMarker(Marker marker, Layer layer) {\r\n addDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Clears all the (foreground and background) domain markers and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void clearDomainMarkers() {\r\n if (this.backgroundDomainMarkers != null) {\r\n Set<Integer> keys = this.backgroundDomainMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearDomainMarkers(key);\r\n }\r\n this.backgroundDomainMarkers.clear();\r\n }\r\n if (this.foregroundDomainMarkers != null) {\r\n Set<Integer> keys = this.foregroundDomainMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearDomainMarkers(key);\r\n }\r\n this.foregroundDomainMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Clears the (foreground and background) domain markers for a particular\r\n * renderer and sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the renderer index.\r\n *\r\n * @see #clearRangeMarkers(int)\r\n */\r\n public void clearDomainMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundDomainMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundDomainMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis (that the renderer is mapped to), however this is\r\n * entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #clearDomainMarkers(int)\r\n * @see #addRangeMarker(int, Marker, Layer)\r\n */\r\n public void addDomainMarker(int index, Marker marker, Layer layer) {\r\n addDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the domain axis (that the renderer is mapped to), however this is\r\n * entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addDomainMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ParamChecks.nullNotPermitted(layer, \"layer\");\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundDomainMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundDomainMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker) {\r\n return removeDomainMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the domain axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(Marker marker, Layer layer) {\r\n return removeDomainMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer) {\r\n return removeDomainMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and, if requested,\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeDomainMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ArrayList markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (ArrayList) this.foregroundDomainMarkers.get(\r\n new Integer(index));\r\n }\r\n else {\r\n markers = (ArrayList) this.backgroundDomainMarkers.get(\r\n new Integer(index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Adds a marker for the range axis and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n *\r\n * @see #addRangeMarker(Marker, Layer)\r\n */\r\n public void addRangeMarker(Marker marker) {\r\n addRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Adds a marker for the range axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #addRangeMarker(int, Marker, Layer)\r\n */\r\n public void addRangeMarker(Marker marker, Layer layer) {\r\n addRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Clears all the range markers and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @see #clearRangeMarkers()\r\n */\r\n public void clearRangeMarkers() {\r\n if (this.backgroundRangeMarkers != null) {\r\n Set<Integer> keys = this.backgroundRangeMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearRangeMarkers(key);\r\n }\r\n this.backgroundRangeMarkers.clear();\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Set<Integer> keys = this.foregroundRangeMarkers.keySet();\r\n for (Integer key : keys) {\r\n clearRangeMarkers(key);\r\n }\r\n this.foregroundRangeMarkers.clear();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @see #clearRangeMarkers(int)\r\n * @see #addDomainMarker(int, Marker, Layer)\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer) {\r\n addRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Adds a marker for a specific dataset/renderer and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n * <P>\r\n * Typically a marker will be drawn by the renderer as a line perpendicular\r\n * to the range axis, however this is entirely up to the renderer.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker.\r\n * @param layer the layer (foreground or background).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n Collection markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (Collection) this.foregroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.foregroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n markers = (Collection) this.backgroundRangeMarkers.get(\r\n new Integer(index));\r\n if (markers == null) {\r\n markers = new java.util.ArrayList();\r\n this.backgroundRangeMarkers.put(new Integer(index), markers);\r\n }\r\n markers.add(marker);\r\n }\r\n marker.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Clears the (foreground and background) range markers for a particular\r\n * renderer.\r\n *\r\n * @param index the renderer index.\r\n */\r\n public void clearRangeMarkers(int index) {\r\n Integer key = new Integer(index);\r\n if (this.backgroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.backgroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n if (this.foregroundRangeMarkers != null) {\r\n Collection markers\r\n = (Collection) this.foregroundRangeMarkers.get(key);\r\n if (markers != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker m = (Marker) iterator.next();\r\n m.removeChangeListener(this);\r\n }\r\n markers.clear();\r\n }\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param marker the marker.\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(Marker marker) {\r\n return removeRangeMarker(marker, Layer.FOREGROUND);\r\n }\r\n\r\n /**\r\n * Removes a marker for the range axis in the specified layer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(Marker marker, Layer layer) {\r\n return removeRangeMarker(0, marker, layer);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.7\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer) {\r\n return removeRangeMarker(index, marker, layer, true);\r\n }\r\n\r\n /**\r\n * Removes a marker for a specific dataset/renderer and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param index the dataset/renderer index.\r\n * @param marker the marker (<code>null</code> not permitted).\r\n * @param layer the layer (foreground or background) (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean indicating whether or not the marker was actually\r\n * removed.\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeRangeMarker(int index, Marker marker, Layer layer,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(marker, \"marker\");\r\n ParamChecks.nullNotPermitted(layer, \"layer\");\r\n List markers;\r\n if (layer == Layer.FOREGROUND) {\r\n markers = (List) this.foregroundRangeMarkers.get(\r\n new Integer(index));\r\n }\r\n else {\r\n markers = (List) this.backgroundRangeMarkers.get(\r\n new Integer(index));\r\n }\r\n if (markers == null) {\r\n return false;\r\n }\r\n boolean removed = markers.remove(marker);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @see #getAnnotations()\r\n * @see #removeAnnotation(XYAnnotation)\r\n */\r\n public void addAnnotation(XYAnnotation annotation) {\r\n addAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Adds an annotation to the plot and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @since 1.0.10\r\n */\r\n public void addAnnotation(XYAnnotation annotation, boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n this.annotations.add(annotation);\r\n annotation.addChangeListener(this);\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n * @see #getAnnotations()\r\n */\r\n public boolean removeAnnotation(XYAnnotation annotation) {\r\n return removeAnnotation(annotation, true);\r\n }\r\n\r\n /**\r\n * Removes an annotation from the plot and sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param annotation the annotation (<code>null</code> not permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @return A boolean (indicates whether or not the annotation was removed).\r\n *\r\n * @since 1.0.10\r\n */\r\n public boolean removeAnnotation(XYAnnotation annotation, boolean notify) {\r\n ParamChecks.nullNotPermitted(annotation, \"annotation\");\r\n boolean removed = this.annotations.remove(annotation);\r\n annotation.removeChangeListener(this);\r\n if (removed && notify) {\r\n fireChangeEvent();\r\n }\r\n return removed;\r\n }\r\n\r\n /**\r\n * Returns the list of annotations.\r\n *\r\n * @return The list of annotations.\r\n *\r\n * @since 1.0.1\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n */\r\n public List getAnnotations() {\r\n return new ArrayList(this.annotations);\r\n }\r\n\r\n /**\r\n * Clears all the annotations and sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @see #addAnnotation(XYAnnotation)\r\n */\r\n public void clearAnnotations() {\r\n for (XYAnnotation annotation : this.annotations) {\r\n annotation.removeChangeListener(this);\r\n }\r\n this.annotations.clear();\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the shadow generator for the plot, if any.\r\n *\r\n * @return The shadow generator (possibly <code>null</code>).\r\n *\r\n * @since 1.0.14\r\n */\r\n public ShadowGenerator getShadowGenerator() {\r\n return this.shadowGenerator;\r\n }\r\n\r\n /**\r\n * Sets the shadow generator for the plot and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param generator the generator (<code>null</code> permitted).\r\n *\r\n * @since 1.0.14\r\n */\r\n public void setShadowGenerator(ShadowGenerator generator) {\r\n this.shadowGenerator = generator;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Calculates the space required for all the axes in the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateAxisSpace(Graphics2D g2,\r\n Rectangle2D plotArea) {\r\n AxisSpace space = new AxisSpace();\r\n space = calculateRangeAxisSpace(g2, plotArea, space);\r\n Rectangle2D revPlotArea = space.shrink(plotArea, null);\r\n space = calculateDomainAxisSpace(g2, revPlotArea, space);\r\n return space;\r\n }\r\n\r\n /**\r\n * Calculates the space required for the domain axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateDomainAxisSpace(Graphics2D g2, \r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the domain axis...\r\n if (this.fixedDomainAxisSpace != null) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getLeft(),\r\n RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n }\r\n else if (this.orientation == PlotOrientation.VERTICAL) {\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedDomainAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n }\r\n }\r\n else {\r\n // reserve space for the domain axes...\r\n for (ValueAxis axis: this.domainAxes.values()) {\r\n if (axis != null) {\r\n RectangleEdge edge = getDomainAxisEdge(\r\n findDomainAxisIndex(axis));\r\n space = axis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Calculates the space required for the range axis/axes.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plotArea the plot area.\r\n * @param space a carrier for the result (<code>null</code> permitted).\r\n *\r\n * @return The required space.\r\n */\r\n protected AxisSpace calculateRangeAxisSpace(Graphics2D g2, \r\n Rectangle2D plotArea, AxisSpace space) {\r\n\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // reserve some space for the range axis...\r\n if (this.fixedRangeAxisSpace != null) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getTop(),\r\n RectangleEdge.TOP);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getBottom(),\r\n RectangleEdge.BOTTOM);\r\n }\r\n else if (this.orientation == PlotOrientation.VERTICAL) {\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getLeft(),\r\n RectangleEdge.LEFT);\r\n space.ensureAtLeast(this.fixedRangeAxisSpace.getRight(),\r\n RectangleEdge.RIGHT);\r\n }\r\n }\r\n else {\r\n // reserve space for the range axes...\r\n for (ValueAxis axis: this.rangeAxes.values()) {\r\n if (axis != null) {\r\n RectangleEdge edge = getRangeAxisEdge(\r\n findRangeAxisIndex(axis));\r\n space = axis.reserveSpace(g2, this, plotArea, edge, space);\r\n }\r\n }\r\n }\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * Trims a rectangle to integer coordinates.\r\n *\r\n * @param rect the incoming rectangle.\r\n *\r\n * @return A rectangle with integer coordinates.\r\n */\r\n private Rectangle integerise(Rectangle2D rect) {\r\n int x0 = (int) Math.ceil(rect.getMinX());\r\n int y0 = (int) Math.ceil(rect.getMinY());\r\n int x1 = (int) Math.floor(rect.getMaxX());\r\n int y1 = (int) Math.floor(rect.getMaxY());\r\n return new Rectangle(x0, y0, (x1 - x0), (y1 - y0));\r\n }\r\n\r\n /**\r\n * Draws the plot within the specified area on a graphics device.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the plot area (in Java2D space).\r\n * @param anchor an anchor point in Java2D space (<code>null</code>\r\n * permitted).\r\n * @param parentState the state from the parent plot, if there is one\r\n * (<code>null</code> permitted).\r\n * @param info collects chart drawing information (<code>null</code>\r\n * permitted).\r\n */\r\n @Override\r\n public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor,\r\n PlotState parentState, PlotRenderingInfo info) {\r\n\r\n // if the plot area is too small, just return...\r\n boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW);\r\n boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW);\r\n if (b1 || b2) {\r\n return;\r\n }\r\n\r\n // record the plot area...\r\n if (info != null) {\r\n info.setPlotArea(area);\r\n }\r\n\r\n // adjust the drawing area for the plot insets (if any)...\r\n RectangleInsets insets = getInsets();\r\n insets.trim(area);\r\n\r\n AxisSpace space = calculateAxisSpace(g2, area);\r\n Rectangle2D dataArea = space.shrink(area, null);\r\n this.axisOffset.trim(dataArea);\r\n\r\n dataArea = integerise(dataArea);\r\n if (dataArea.isEmpty()) {\r\n return;\r\n }\r\n createAndAddEntity((Rectangle2D) dataArea.clone(), info, null, null);\r\n if (info != null) {\r\n info.setDataArea(dataArea);\r\n }\r\n\r\n // draw the plot background and axes...\r\n drawBackground(g2, dataArea);\r\n Map axisStateMap = drawAxes(g2, area, dataArea, info);\r\n\r\n PlotOrientation orient = getOrientation();\r\n\r\n // the anchor point is typically the point where the mouse last\r\n // clicked - the crosshairs will be driven off this point...\r\n if (anchor != null && !dataArea.contains(anchor)) {\r\n anchor = null;\r\n }\r\n CrosshairState crosshairState = new CrosshairState();\r\n crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY);\r\n crosshairState.setAnchor(anchor);\r\n\r\n crosshairState.setAnchorX(Double.NaN);\r\n crosshairState.setAnchorY(Double.NaN);\r\n if (anchor != null) {\r\n ValueAxis domainAxis = getDomainAxis();\r\n if (domainAxis != null) {\r\n double x;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n x = domainAxis.java2DToValue(anchor.getX(), dataArea,\r\n getDomainAxisEdge());\r\n }\r\n else {\r\n x = domainAxis.java2DToValue(anchor.getY(), dataArea,\r\n getDomainAxisEdge());\r\n }\r\n crosshairState.setAnchorX(x);\r\n }\r\n ValueAxis rangeAxis = getRangeAxis();\r\n if (rangeAxis != null) {\r\n double y;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n y = rangeAxis.java2DToValue(anchor.getY(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n else {\r\n y = rangeAxis.java2DToValue(anchor.getX(), dataArea,\r\n getRangeAxisEdge());\r\n }\r\n crosshairState.setAnchorY(y);\r\n }\r\n }\r\n crosshairState.setCrosshairX(getDomainCrosshairValue());\r\n crosshairState.setCrosshairY(getRangeCrosshairValue());\r\n Shape originalClip = g2.getClip();\r\n Composite originalComposite = g2.getComposite();\r\n\r\n g2.clip(dataArea);\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n getForegroundAlpha()));\r\n\r\n AxisState domainAxisState = (AxisState) axisStateMap.get(\r\n getDomainAxis());\r\n if (domainAxisState == null) {\r\n if (parentState != null) {\r\n domainAxisState = (AxisState) parentState.getSharedAxisStates()\r\n .get(getDomainAxis());\r\n }\r\n }\r\n\r\n AxisState rangeAxisState = (AxisState) axisStateMap.get(getRangeAxis());\r\n if (rangeAxisState == null) {\r\n if (parentState != null) {\r\n rangeAxisState = (AxisState) parentState.getSharedAxisStates()\r\n .get(getRangeAxis());\r\n }\r\n }\r\n if (domainAxisState != null) {\r\n drawDomainTickBands(g2, dataArea, domainAxisState.getTicks());\r\n }\r\n if (rangeAxisState != null) {\r\n drawRangeTickBands(g2, dataArea, rangeAxisState.getTicks());\r\n }\r\n if (domainAxisState != null) {\r\n drawDomainGridlines(g2, dataArea, domainAxisState.getTicks());\r\n drawZeroDomainBaseline(g2, dataArea);\r\n }\r\n if (rangeAxisState != null) {\r\n drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks());\r\n drawZeroRangeBaseline(g2, dataArea);\r\n }\r\n\r\n Graphics2D savedG2 = g2;\r\n BufferedImage dataImage = null;\r\n boolean suppressShadow = Boolean.TRUE.equals(g2.getRenderingHint(\r\n JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION));\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n dataImage = new BufferedImage((int) dataArea.getWidth(),\r\n (int)dataArea.getHeight(), BufferedImage.TYPE_INT_ARGB);\r\n g2 = dataImage.createGraphics();\r\n g2.translate(-dataArea.getX(), -dataArea.getY());\r\n g2.setRenderingHints(savedG2.getRenderingHints());\r\n }\r\n\r\n // draw the markers that are associated with a specific dataset...\r\n for (XYDataset dataset: this.datasets.values()) {\r\n int datasetIndex = indexOf(dataset);\r\n drawDomainMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND);\r\n }\r\n for (XYDataset dataset: this.datasets.values()) {\r\n int datasetIndex = indexOf(dataset);\r\n drawRangeMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND);\r\n }\r\n\r\n // now draw annotations and render data items...\r\n boolean foundData = false;\r\n DatasetRenderingOrder order = getDatasetRenderingOrder();\r\n List<Integer> rendererIndices = getRendererIndices(order);\r\n List<Integer> datasetIndices = getDatasetIndices(order);\r\n // draw background annotations\r\n for (int i : rendererIndices) {\r\n XYItemRenderer renderer = getRenderer(i);\r\n if (renderer != null) {\r\n ValueAxis domainAxis = getDomainAxisForDataset(i);\r\n ValueAxis rangeAxis = getRangeAxisForDataset(i);\r\n renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, \r\n Layer.BACKGROUND, info);\r\n }\r\n }\r\n\r\n // render data items...\r\n for (int datasetIndex : datasetIndices) {\r\n XYDataset dataset = this.getDataset(datasetIndex);\r\n foundData = render(g2, dataArea, datasetIndex, info, \r\n crosshairState) || foundData;\r\n }\r\n\r\n // draw foreground annotations\r\n for (int i : rendererIndices) {\r\n XYItemRenderer renderer = getRenderer(i);\r\n if (renderer != null) {\r\n ValueAxis domainAxis = getDomainAxisForDataset(i);\r\n ValueAxis rangeAxis = getRangeAxisForDataset(i);\r\n renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, \r\n Layer.FOREGROUND, info);\r\n }\r\n }\r\n\r\n // draw domain crosshair if required...\r\n int datasetIndex = crosshairState.getDatasetIndex();\r\n ValueAxis xAxis = this.getDomainAxisForDataset(datasetIndex);\r\n RectangleEdge xAxisEdge = getDomainAxisEdge(getDomainAxisIndex(xAxis));\r\n if (!this.domainCrosshairLockedOnData && anchor != null) {\r\n double xx;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n xx = xAxis.java2DToValue(anchor.getX(), dataArea, xAxisEdge);\r\n }\r\n else {\r\n xx = xAxis.java2DToValue(anchor.getY(), dataArea, xAxisEdge);\r\n }\r\n crosshairState.setCrosshairX(xx);\r\n }\r\n setDomainCrosshairValue(crosshairState.getCrosshairX(), false);\r\n if (isDomainCrosshairVisible()) {\r\n double x = getDomainCrosshairValue();\r\n Paint paint = getDomainCrosshairPaint();\r\n Stroke stroke = getDomainCrosshairStroke();\r\n drawDomainCrosshair(g2, dataArea, orient, x, xAxis, stroke, paint);\r\n }\r\n\r\n // draw range crosshair if required...\r\n ValueAxis yAxis = getRangeAxisForDataset(datasetIndex);\r\n RectangleEdge yAxisEdge = getRangeAxisEdge(getRangeAxisIndex(yAxis));\r\n if (!this.rangeCrosshairLockedOnData && anchor != null) {\r\n double yy;\r\n if (orient == PlotOrientation.VERTICAL) {\r\n yy = yAxis.java2DToValue(anchor.getY(), dataArea, yAxisEdge);\r\n } else {\r\n yy = yAxis.java2DToValue(anchor.getX(), dataArea, yAxisEdge);\r\n }\r\n crosshairState.setCrosshairY(yy);\r\n }\r\n setRangeCrosshairValue(crosshairState.getCrosshairY(), false);\r\n if (isRangeCrosshairVisible()) {\r\n double y = getRangeCrosshairValue();\r\n Paint paint = getRangeCrosshairPaint();\r\n Stroke stroke = getRangeCrosshairStroke();\r\n drawRangeCrosshair(g2, dataArea, orient, y, yAxis, stroke, paint);\r\n }\r\n\r\n if (!foundData) {\r\n drawNoDataMessage(g2, dataArea);\r\n }\r\n\r\n for (int i : rendererIndices) { \r\n drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n for (int i : rendererIndices) {\r\n drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND);\r\n }\r\n\r\n drawAnnotations(g2, dataArea, info);\r\n if (this.shadowGenerator != null && !suppressShadow) {\r\n BufferedImage shadowImage\r\n = this.shadowGenerator.createDropShadow(dataImage);\r\n g2 = savedG2;\r\n g2.drawImage(shadowImage, (int) dataArea.getX()\r\n + this.shadowGenerator.calculateOffsetX(),\r\n (int) dataArea.getY()\r\n + this.shadowGenerator.calculateOffsetY(), null);\r\n g2.drawImage(dataImage, (int) dataArea.getX(),\r\n (int) dataArea.getY(), null);\r\n }\r\n g2.setClip(originalClip);\r\n g2.setComposite(originalComposite);\r\n\r\n drawOutline(g2, dataArea);\r\n\r\n }\r\n\r\n /**\r\n * Returns the indices of the non-null datasets in the specified order.\r\n * \r\n * @param order the order (<code>null</code> not permitted).\r\n * \r\n * @return The list of indices. \r\n */\r\n private List<Integer> getDatasetIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result;\r\n }\r\n \r\n private List<Integer> getRendererIndices(DatasetRenderingOrder order) {\r\n List<Integer> result = new ArrayList<Integer>();\r\n for (Entry<Integer, XYItemRenderer> entry : this.renderers.entrySet()) {\r\n if (entry.getValue() != null) {\r\n result.add(entry.getKey());\r\n }\r\n }\r\n Collections.sort(result);\r\n if (order == DatasetRenderingOrder.REVERSE) {\r\n Collections.reverse(result);\r\n }\r\n return result; \r\n }\r\n \r\n /**\r\n * Draws the background for the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n */\r\n @Override\r\n public void drawBackground(Graphics2D g2, Rectangle2D area) {\r\n fillBackground(g2, area, this.orientation);\r\n drawQuadrants(g2, area);\r\n drawBackgroundImage(g2, area);\r\n }\r\n\r\n /**\r\n * Draws the quadrants.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the area.\r\n *\r\n * @see #setQuadrantOrigin(Point2D)\r\n * @see #setQuadrantPaint(int, Paint)\r\n */\r\n protected void drawQuadrants(Graphics2D g2, Rectangle2D area) {\r\n // 0 | 1\r\n // --+--\r\n // 2 | 3\r\n boolean somethingToDraw = false;\r\n\r\n ValueAxis xAxis = getDomainAxis();\r\n if (xAxis == null) { // we can't draw quadrants without a valid x-axis\r\n return;\r\n }\r\n double x = xAxis.getRange().constrain(this.quadrantOrigin.getX());\r\n double xx = xAxis.valueToJava2D(x, area, getDomainAxisEdge());\r\n\r\n ValueAxis yAxis = getRangeAxis();\r\n if (yAxis == null) { // we can't draw quadrants without a valid y-axis\r\n return;\r\n }\r\n double y = yAxis.getRange().constrain(this.quadrantOrigin.getY());\r\n double yy = yAxis.valueToJava2D(y, area, getRangeAxisEdge());\r\n\r\n double xmin = xAxis.getLowerBound();\r\n double xxmin = xAxis.valueToJava2D(xmin, area, getDomainAxisEdge());\r\n\r\n double xmax = xAxis.getUpperBound();\r\n double xxmax = xAxis.valueToJava2D(xmax, area, getDomainAxisEdge());\r\n\r\n double ymin = yAxis.getLowerBound();\r\n double yymin = yAxis.valueToJava2D(ymin, area, getRangeAxisEdge());\r\n\r\n double ymax = yAxis.getUpperBound();\r\n double yymax = yAxis.valueToJava2D(ymax, area, getRangeAxisEdge());\r\n\r\n Rectangle2D[] r = new Rectangle2D[] {null, null, null, null};\r\n if (this.quadrantPaint[0] != null) {\r\n if (x > xmin && y < ymax) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[0] = new Rectangle2D.Double(Math.min(yymax, yy),\r\n Math.min(xxmin, xx), Math.abs(yy - yymax),\r\n Math.abs(xx - xxmin));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[0] = new Rectangle2D.Double(Math.min(xxmin, xx),\r\n Math.min(yymax, yy), Math.abs(xx - xxmin),\r\n Math.abs(yy - yymax));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[1] != null) {\r\n if (x < xmax && y < ymax) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[1] = new Rectangle2D.Double(Math.min(yymax, yy),\r\n Math.min(xxmax, xx), Math.abs(yy - yymax),\r\n Math.abs(xx - xxmax));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[1] = new Rectangle2D.Double(Math.min(xx, xxmax),\r\n Math.min(yymax, yy), Math.abs(xx - xxmax),\r\n Math.abs(yy - yymax));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[2] != null) {\r\n if (x > xmin && y > ymin) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[2] = new Rectangle2D.Double(Math.min(yymin, yy),\r\n Math.min(xxmin, xx), Math.abs(yy - yymin),\r\n Math.abs(xx - xxmin));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[2] = new Rectangle2D.Double(Math.min(xxmin, xx),\r\n Math.min(yymin, yy), Math.abs(xx - xxmin),\r\n Math.abs(yy - yymin));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (this.quadrantPaint[3] != null) {\r\n if (x < xmax && y > ymin) {\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n r[3] = new Rectangle2D.Double(Math.min(yymin, yy),\r\n Math.min(xxmax, xx), Math.abs(yy - yymin),\r\n Math.abs(xx - xxmax));\r\n }\r\n else { // PlotOrientation.VERTICAL\r\n r[3] = new Rectangle2D.Double(Math.min(xx, xxmax),\r\n Math.min(yymin, yy), Math.abs(xx - xxmax),\r\n Math.abs(yy - yymin));\r\n }\r\n somethingToDraw = true;\r\n }\r\n }\r\n if (somethingToDraw) {\r\n Composite originalComposite = g2.getComposite();\r\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,\r\n getBackgroundAlpha()));\r\n for (int i = 0; i < 4; i++) {\r\n if (this.quadrantPaint[i] != null && r[i] != null) {\r\n g2.setPaint(this.quadrantPaint[i]);\r\n g2.fill(r[i]);\r\n }\r\n }\r\n g2.setComposite(originalComposite);\r\n }\r\n }\r\n\r\n /**\r\n * Draws the domain tick bands, if any.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #setDomainTickBandPaint(Paint)\r\n */\r\n public void drawDomainTickBands(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n Paint bandPaint = getDomainTickBandPaint();\r\n if (bandPaint != null) {\r\n boolean fillBand = false;\r\n ValueAxis xAxis = getDomainAxis();\r\n double previous = xAxis.getLowerBound();\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n double current = tick.getValue();\r\n if (fillBand) {\r\n getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea,\r\n previous, current);\r\n }\r\n previous = current;\r\n fillBand = !fillBand;\r\n }\r\n double end = xAxis.getUpperBound();\r\n if (fillBand) {\r\n getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea,\r\n previous, end);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws the range tick bands, if any.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #setRangeTickBandPaint(Paint)\r\n */\r\n public void drawRangeTickBands(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n Paint bandPaint = getRangeTickBandPaint();\r\n if (bandPaint != null) {\r\n boolean fillBand = false;\r\n ValueAxis axis = getRangeAxis();\r\n double previous = axis.getLowerBound();\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n double current = tick.getValue();\r\n if (fillBand) {\r\n getRenderer().fillRangeGridBand(g2, this, axis, dataArea,\r\n previous, current);\r\n }\r\n previous = current;\r\n fillBand = !fillBand;\r\n }\r\n double end = axis.getUpperBound();\r\n if (fillBand) {\r\n getRenderer().fillRangeGridBand(g2, this, axis, dataArea,\r\n previous, end);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * A utility method for drawing the axes.\r\n *\r\n * @param g2 the graphics device (<code>null</code> not permitted).\r\n * @param plotArea the plot area (<code>null</code> not permitted).\r\n * @param dataArea the data area (<code>null</code> not permitted).\r\n * @param plotState collects information about the plot (<code>null</code>\r\n * permitted).\r\n *\r\n * @return A map containing the state for each axis drawn.\r\n */\r\n protected Map<Axis, AxisState> drawAxes(Graphics2D g2, Rectangle2D plotArea,\r\n Rectangle2D dataArea, PlotRenderingInfo plotState) {\r\n\r\n AxisCollection axisCollection = new AxisCollection();\r\n\r\n // add domain axes to lists...\r\n for (ValueAxis axis : this.domainAxes.values()) {\r\n if (axis != null) {\r\n int axisIndex = findDomainAxisIndex(axis);\r\n axisCollection.add(axis, getDomainAxisEdge(axisIndex));\r\n }\r\n }\r\n\r\n // add range axes to lists...\r\n for (ValueAxis axis : this.rangeAxes.values()) {\r\n if (axis != null) {\r\n int axisIndex = findRangeAxisIndex(axis);\r\n axisCollection.add(axis, getRangeAxisEdge(axisIndex));\r\n }\r\n }\r\n\r\n Map axisStateMap = new HashMap();\r\n\r\n // draw the top axes\r\n double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset(\r\n dataArea.getHeight());\r\n Iterator iterator = axisCollection.getAxesAtTop().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.TOP, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the bottom axes\r\n cursor = dataArea.getMaxY()\r\n + this.axisOffset.calculateBottomOutset(dataArea.getHeight());\r\n iterator = axisCollection.getAxesAtBottom().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.BOTTOM, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the left axes\r\n cursor = dataArea.getMinX()\r\n - this.axisOffset.calculateLeftOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtLeft().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.LEFT, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n // draw the right axes\r\n cursor = dataArea.getMaxX()\r\n + this.axisOffset.calculateRightOutset(dataArea.getWidth());\r\n iterator = axisCollection.getAxesAtRight().iterator();\r\n while (iterator.hasNext()) {\r\n ValueAxis axis = (ValueAxis) iterator.next();\r\n AxisState info = axis.draw(g2, cursor, plotArea, dataArea,\r\n RectangleEdge.RIGHT, plotState);\r\n cursor = info.getCursor();\r\n axisStateMap.put(axis, info);\r\n }\r\n\r\n return axisStateMap;\r\n }\r\n\r\n /**\r\n * Draws a representation of the data within the dataArea region, using the\r\n * current renderer.\r\n * <P>\r\n * The <code>info</code> and <code>crosshairState</code> arguments may be\r\n * <code>null</code>.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the region in which the data is to be drawn.\r\n * @param index the dataset index.\r\n * @param info an optional object for collection dimension information.\r\n * @param crosshairState collects crosshair information\r\n * (<code>null</code> permitted).\r\n *\r\n * @return A flag that indicates whether any data was actually rendered.\r\n */\r\n public boolean render(Graphics2D g2, Rectangle2D dataArea, int index,\r\n PlotRenderingInfo info, CrosshairState crosshairState) {\r\n\r\n boolean foundData = false;\r\n XYDataset dataset = getDataset(index);\r\n if (!DatasetUtilities.isEmptyOrNull(dataset)) {\r\n foundData = true;\r\n ValueAxis xAxis = getDomainAxisForDataset(index);\r\n ValueAxis yAxis = getRangeAxisForDataset(index);\r\n if (xAxis == null || yAxis == null) {\r\n return foundData; // can't render anything without axes\r\n }\r\n XYItemRenderer renderer = getRenderer(index);\r\n if (renderer == null) {\r\n renderer = getRenderer();\r\n if (renderer == null) { // no default renderer available\r\n return foundData;\r\n }\r\n }\r\n\r\n XYItemRendererState state = renderer.initialise(g2, dataArea, this,\r\n dataset, info);\r\n int passCount = renderer.getPassCount();\r\n\r\n SeriesRenderingOrder seriesOrder = getSeriesRenderingOrder();\r\n if (seriesOrder == SeriesRenderingOrder.REVERSE) {\r\n //render series in reverse order\r\n for (int pass = 0; pass < passCount; pass++) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = seriesCount - 1; series >= 0; series--) {\r\n int firstItem = 0;\r\n int lastItem = dataset.getItemCount(series) - 1;\r\n if (lastItem == -1) {\r\n continue;\r\n }\r\n if (state.getProcessVisibleItemsOnly()) {\r\n int[] itemBounds = RendererUtilities.findLiveItems(\r\n dataset, series, xAxis.getLowerBound(),\r\n xAxis.getUpperBound());\r\n firstItem = Math.max(itemBounds[0] - 1, 0);\r\n lastItem = Math.min(itemBounds[1] + 1, lastItem);\r\n }\r\n state.startSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n for (int item = firstItem; item <= lastItem; item++) {\r\n renderer.drawItem(g2, state, dataArea, info,\r\n this, xAxis, yAxis, dataset, series, item,\r\n crosshairState, pass);\r\n }\r\n state.endSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n }\r\n }\r\n }\r\n else {\r\n //render series in forward order\r\n for (int pass = 0; pass < passCount; pass++) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int series = 0; series < seriesCount; series++) {\r\n int firstItem = 0;\r\n int lastItem = dataset.getItemCount(series) - 1;\r\n if (state.getProcessVisibleItemsOnly()) {\r\n int[] itemBounds = RendererUtilities.findLiveItems(\r\n dataset, series, xAxis.getLowerBound(),\r\n xAxis.getUpperBound());\r\n firstItem = Math.max(itemBounds[0] - 1, 0);\r\n lastItem = Math.min(itemBounds[1] + 1, lastItem);\r\n }\r\n state.startSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n for (int item = firstItem; item <= lastItem; item++) {\r\n renderer.drawItem(g2, state, dataArea, info,\r\n this, xAxis, yAxis, dataset, series, item,\r\n crosshairState, pass);\r\n }\r\n state.endSeriesPass(dataset, series, firstItem,\r\n lastItem, pass, passCount);\r\n }\r\n }\r\n }\r\n }\r\n return foundData;\r\n }\r\n\r\n /**\r\n * Returns the domain axis for a dataset.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The axis.\r\n */\r\n public ValueAxis getDomainAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n ValueAxis valueAxis;\r\n List axisIndices = (List) this.datasetToDomainAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n valueAxis = getDomainAxis(axisIndex.intValue());\r\n }\r\n else {\r\n valueAxis = getDomainAxis(0);\r\n }\r\n return valueAxis;\r\n }\r\n\r\n /**\r\n * Returns the range axis for a dataset.\r\n *\r\n * @param index the dataset index (must be &gt;= 0).\r\n *\r\n * @return The axis.\r\n */\r\n public ValueAxis getRangeAxisForDataset(int index) {\r\n ParamChecks.requireNonNegative(index, \"index\");\r\n ValueAxis valueAxis;\r\n List axisIndices = (List) this.datasetToRangeAxesMap.get(\r\n new Integer(index));\r\n if (axisIndices != null) {\r\n // the first axis in the list is used for data <--> Java2D\r\n Integer axisIndex = (Integer) axisIndices.get(0);\r\n valueAxis = getRangeAxis(axisIndex.intValue());\r\n }\r\n else {\r\n valueAxis = getRangeAxis(0);\r\n }\r\n return valueAxis;\r\n }\r\n\r\n /**\r\n * Draws the gridlines for the plot, if they are visible.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #drawRangeGridlines(Graphics2D, Rectangle2D, List)\r\n */\r\n protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea,\r\n List ticks) {\r\n\r\n // no renderer, no gridlines...\r\n if (getRenderer() == null) {\r\n return;\r\n }\r\n\r\n // draw the domain grid lines, if any...\r\n if (isDomainGridlinesVisible() || isDomainMinorGridlinesVisible()) {\r\n Stroke gridStroke = null;\r\n Paint gridPaint = null;\r\n Iterator iterator = ticks.iterator();\r\n boolean paintLine;\r\n while (iterator.hasNext()) {\r\n paintLine = false;\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if ((tick.getTickType() == TickType.MINOR)\r\n && isDomainMinorGridlinesVisible()) {\r\n gridStroke = getDomainMinorGridlineStroke();\r\n gridPaint = getDomainMinorGridlinePaint();\r\n paintLine = true;\r\n } else if ((tick.getTickType() == TickType.MAJOR)\r\n && isDomainGridlinesVisible()) {\r\n gridStroke = getDomainGridlineStroke();\r\n gridPaint = getDomainGridlinePaint();\r\n paintLine = true;\r\n }\r\n XYItemRenderer r = getRenderer();\r\n if ((r instanceof AbstractXYItemRenderer) && paintLine) {\r\n ((AbstractXYItemRenderer) r).drawDomainLine(g2, this,\r\n getDomainAxis(), dataArea, tick.getValue(),\r\n gridPaint, gridStroke);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws the gridlines for the plot's primary range axis, if they are\r\n * visible.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n * @param ticks the ticks.\r\n *\r\n * @see #drawDomainGridlines(Graphics2D, Rectangle2D, List)\r\n */\r\n protected void drawRangeGridlines(Graphics2D g2, Rectangle2D area,\r\n List ticks) {\r\n\r\n // no renderer, no gridlines...\r\n if (getRenderer() == null) {\r\n return;\r\n }\r\n\r\n // draw the range grid lines, if any...\r\n if (isRangeGridlinesVisible() || isRangeMinorGridlinesVisible()) {\r\n Stroke gridStroke = null;\r\n Paint gridPaint = null;\r\n ValueAxis axis = getRangeAxis();\r\n if (axis != null) {\r\n Iterator iterator = ticks.iterator();\r\n boolean paintLine;\r\n while (iterator.hasNext()) {\r\n paintLine = false;\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if ((tick.getTickType() == TickType.MINOR)\r\n && isRangeMinorGridlinesVisible()) {\r\n gridStroke = getRangeMinorGridlineStroke();\r\n gridPaint = getRangeMinorGridlinePaint();\r\n paintLine = true;\r\n } else if ((tick.getTickType() == TickType.MAJOR)\r\n && isRangeGridlinesVisible()) {\r\n gridStroke = getRangeGridlineStroke();\r\n gridPaint = getRangeGridlinePaint();\r\n paintLine = true;\r\n }\r\n if ((tick.getValue() != 0.0\r\n || !isRangeZeroBaselineVisible()) && paintLine) {\r\n getRenderer().drawRangeLine(g2, this, getRangeAxis(),\r\n area, tick.getValue(), gridPaint, gridStroke);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws a base line across the chart at value zero on the domain axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n *\r\n * @see #setDomainZeroBaselineVisible(boolean)\r\n *\r\n * @since 1.0.5\r\n */\r\n protected void drawZeroDomainBaseline(Graphics2D g2, Rectangle2D area) {\r\n if (isDomainZeroBaselineVisible()) {\r\n XYItemRenderer r = getRenderer();\r\n // FIXME: the renderer interface doesn't have the drawDomainLine()\r\n // method, so we have to rely on the renderer being a subclass of\r\n // AbstractXYItemRenderer (which is lame)\r\n if (r instanceof AbstractXYItemRenderer) {\r\n AbstractXYItemRenderer renderer = (AbstractXYItemRenderer) r;\r\n renderer.drawDomainLine(g2, this, getDomainAxis(), area, 0.0,\r\n this.domainZeroBaselinePaint,\r\n this.domainZeroBaselineStroke);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draws a base line across the chart at value zero on the range axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param area the data area.\r\n *\r\n * @see #setRangeZeroBaselineVisible(boolean)\r\n */\r\n protected void drawZeroRangeBaseline(Graphics2D g2, Rectangle2D area) {\r\n if (isRangeZeroBaselineVisible()) {\r\n getRenderer().drawRangeLine(g2, this, getRangeAxis(), area, 0.0,\r\n this.rangeZeroBaselinePaint, this.rangeZeroBaselineStroke);\r\n }\r\n }\r\n\r\n /**\r\n * Draws the annotations for the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param info the chart rendering info.\r\n */\r\n public void drawAnnotations(Graphics2D g2, Rectangle2D dataArea,\r\n PlotRenderingInfo info) {\r\n\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n ValueAxis xAxis = getDomainAxis();\r\n ValueAxis yAxis = getRangeAxis();\r\n annotation.draw(g2, this, dataArea, xAxis, yAxis, 0, info);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the domain markers (if any) for an axis and layer. This method is\r\n * typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the dataset/renderer index.\r\n * @param layer the layer (foreground or background).\r\n */\r\n protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n XYItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n // check that the renderer has a corresponding dataset (it doesn't\r\n // matter if the dataset is null)\r\n if (index >= getDatasetCount()) {\r\n return;\r\n }\r\n Collection markers = getDomainMarkers(index, layer);\r\n ValueAxis axis = getDomainAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker marker = (Marker) iterator.next();\r\n r.drawDomainMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws the range markers (if any) for a renderer and layer. This method\r\n * is typically called from within the draw() method.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param index the renderer index.\r\n * @param layer the layer (foreground or background).\r\n */\r\n protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea,\r\n int index, Layer layer) {\r\n\r\n XYItemRenderer r = getRenderer(index);\r\n if (r == null) {\r\n return;\r\n }\r\n // check that the renderer has a corresponding dataset (it doesn't\r\n // matter if the dataset is null)\r\n if (index >= getDatasetCount()) {\r\n return;\r\n }\r\n Collection markers = getRangeMarkers(index, layer);\r\n ValueAxis axis = getRangeAxisForDataset(index);\r\n if (markers != null && axis != null) {\r\n Iterator iterator = markers.iterator();\r\n while (iterator.hasNext()) {\r\n Marker marker = (Marker) iterator.next();\r\n r.drawRangeMarker(g2, this, axis, marker, dataArea);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the list of domain markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of domain markers.\r\n *\r\n * @see #getRangeMarkers(Layer)\r\n */\r\n public Collection getDomainMarkers(Layer layer) {\r\n return getDomainMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns the list of range markers (read only) for the specified layer.\r\n *\r\n * @param layer the layer (foreground or background).\r\n *\r\n * @return The list of range markers.\r\n *\r\n * @see #getDomainMarkers(Layer)\r\n */\r\n public Collection getRangeMarkers(Layer layer) {\r\n return getRangeMarkers(0, layer);\r\n }\r\n\r\n /**\r\n * Returns a collection of domain markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n *\r\n * @see #getRangeMarkers(int, Layer)\r\n */\r\n public Collection getDomainMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundDomainMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundDomainMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a collection of range markers for a particular renderer and\r\n * layer.\r\n *\r\n * @param index the renderer index.\r\n * @param layer the layer.\r\n *\r\n * @return A collection of markers (possibly <code>null</code>).\r\n *\r\n * @see #getDomainMarkers(int, Layer)\r\n */\r\n public Collection getRangeMarkers(int index, Layer layer) {\r\n Collection result = null;\r\n Integer key = new Integer(index);\r\n if (layer == Layer.FOREGROUND) {\r\n result = (Collection) this.foregroundRangeMarkers.get(key);\r\n }\r\n else if (layer == Layer.BACKGROUND) {\r\n result = (Collection) this.backgroundRangeMarkers.get(key);\r\n }\r\n if (result != null) {\r\n result = Collections.unmodifiableCollection(result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Utility method for drawing a horizontal line across the data area of the\r\n * plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param value the coordinate, where to draw the line.\r\n * @param stroke the stroke to use.\r\n * @param paint the paint to use.\r\n */\r\n protected void drawHorizontalLine(Graphics2D g2, Rectangle2D dataArea,\r\n double value, Stroke stroke,\r\n Paint paint) {\r\n\r\n ValueAxis axis = getRangeAxis();\r\n if (getOrientation() == PlotOrientation.HORIZONTAL) {\r\n axis = getDomainAxis();\r\n }\r\n if (axis.getRange().contains(value)) {\r\n double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT);\r\n Line2D line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws a domain crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param value the crosshair value.\r\n * @param axis the axis against which the value is measured.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @since 1.0.4\r\n */\r\n protected void drawDomainCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, double value, ValueAxis axis,\r\n Stroke stroke, Paint paint) {\r\n\r\n if (!axis.getRange().contains(value)) {\r\n return;\r\n }\r\n Line2D line;\r\n if (orientation == PlotOrientation.VERTICAL) {\r\n double xx = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n } else {\r\n double yy = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n\r\n /**\r\n * Utility method for drawing a vertical line on the data area of the plot.\r\n *\r\n * @param g2 the graphics device.\r\n * @param dataArea the data area.\r\n * @param value the coordinate, where to draw the line.\r\n * @param stroke the stroke to use.\r\n * @param paint the paint to use.\r\n */\r\n protected void drawVerticalLine(Graphics2D g2, Rectangle2D dataArea,\r\n double value, Stroke stroke, Paint paint) {\r\n\r\n ValueAxis axis = getDomainAxis();\r\n if (getOrientation() == PlotOrientation.HORIZONTAL) {\r\n axis = getRangeAxis();\r\n }\r\n if (axis.getRange().contains(value)) {\r\n double xx = axis.valueToJava2D(value, dataArea,\r\n RectangleEdge.BOTTOM);\r\n Line2D line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Draws a range crosshair.\r\n *\r\n * @param g2 the graphics target.\r\n * @param dataArea the data area.\r\n * @param orientation the plot orientation.\r\n * @param value the crosshair value.\r\n * @param axis the axis against which the value is measured.\r\n * @param stroke the stroke used to draw the crosshair line.\r\n * @param paint the paint used to draw the crosshair line.\r\n *\r\n * @since 1.0.4\r\n */\r\n protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea,\r\n PlotOrientation orientation, double value, ValueAxis axis,\r\n Stroke stroke, Paint paint) {\r\n\r\n if (!axis.getRange().contains(value)) {\r\n return;\r\n }\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n Line2D line;\r\n if (orientation == PlotOrientation.HORIZONTAL) {\r\n double xx = axis.valueToJava2D(value, dataArea, \r\n RectangleEdge.BOTTOM);\r\n line = new Line2D.Double(xx, dataArea.getMinY(), xx,\r\n dataArea.getMaxY());\r\n } else {\r\n double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT);\r\n line = new Line2D.Double(dataArea.getMinX(), yy,\r\n dataArea.getMaxX(), yy);\r\n }\r\n g2.setStroke(stroke);\r\n g2.setPaint(paint);\r\n g2.draw(line);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n }\r\n\r\n /**\r\n * Handles a 'click' on the plot by updating the anchor values.\r\n *\r\n * @param x the x-coordinate, where the click occurred, in Java2D space.\r\n * @param y the y-coordinate, where the click occurred, in Java2D space.\r\n * @param info object containing information about the plot dimensions.\r\n */\r\n @Override\r\n public void handleClick(int x, int y, PlotRenderingInfo info) {\r\n\r\n Rectangle2D dataArea = info.getDataArea();\r\n if (dataArea.contains(x, y)) {\r\n // set the anchor value for the horizontal axis...\r\n ValueAxis xaxis = getDomainAxis();\r\n if (xaxis != null) {\r\n double hvalue = xaxis.java2DToValue(x, info.getDataArea(),\r\n getDomainAxisEdge());\r\n setDomainCrosshairValue(hvalue);\r\n }\r\n\r\n // set the anchor value for the vertical axis...\r\n ValueAxis yaxis = getRangeAxis();\r\n if (yaxis != null) {\r\n double vvalue = yaxis.java2DToValue(y, info.getDataArea(),\r\n getRangeAxisEdge());\r\n setRangeCrosshairValue(vvalue);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * A utility method that returns a list of datasets that are mapped to a\r\n * particular axis.\r\n *\r\n * @param axisIndex the axis index (<code>null</code> not permitted).\r\n *\r\n * @return A list of datasets.\r\n */\r\n private List<XYDataset> getDatasetsMappedToDomainAxis(Integer axisIndex) {\r\n ParamChecks.nullNotPermitted(axisIndex, \"axisIndex\");\r\n List<XYDataset> result = new ArrayList<XYDataset>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n int index = entry.getKey();\r\n List<Integer> mappedAxes = this.datasetToDomainAxesMap.get(index);\r\n if (mappedAxes == null) {\r\n if (axisIndex.equals(ZERO)) {\r\n result.add(entry.getValue());\r\n }\r\n } else {\r\n if (mappedAxes.contains(axisIndex)) {\r\n result.add(entry.getValue());\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * A utility method that returns a list of datasets that are mapped to a\r\n * particular axis.\r\n *\r\n * @param axisIndex the axis index (<code>null</code> not permitted).\r\n *\r\n * @return A list of datasets.\r\n */\r\n private List<XYDataset> getDatasetsMappedToRangeAxis(Integer axisIndex) {\r\n ParamChecks.nullNotPermitted(axisIndex, \"axisIndex\");\r\n List<XYDataset> result = new ArrayList<XYDataset>();\r\n for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) {\r\n int index = entry.getKey();\r\n List<Integer> mappedAxes = this.datasetToRangeAxesMap.get(index);\r\n if (mappedAxes == null) {\r\n if (axisIndex.equals(ZERO)) {\r\n result.add(entry.getValue());\r\n }\r\n } else {\r\n if (mappedAxes.contains(axisIndex)) {\r\n result.add(entry.getValue());\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the index of the given domain axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getRangeAxisIndex(ValueAxis)\r\n */\r\n public int getDomainAxisIndex(ValueAxis axis) {\r\n int result = findDomainAxisIndex(axis);\r\n if (result < 0) {\r\n // try the parent plot\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot p = (XYPlot) parent;\r\n result = p.getDomainAxisIndex(axis);\r\n }\r\n }\r\n return result;\r\n }\r\n \r\n private int findDomainAxisIndex(ValueAxis axis) {\r\n for (Map.Entry<Integer, ValueAxis> entry : this.domainAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the index of the given range axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The axis index.\r\n *\r\n * @see #getDomainAxisIndex(ValueAxis)\r\n */\r\n public int getRangeAxisIndex(ValueAxis axis) {\r\n int result = findRangeAxisIndex(axis);\r\n if (result < 0) {\r\n // try the parent plot\r\n Plot parent = getParent();\r\n if (parent instanceof XYPlot) {\r\n XYPlot p = (XYPlot) parent;\r\n result = p.getRangeAxisIndex(axis);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n private int findRangeAxisIndex(ValueAxis axis) {\r\n for (Map.Entry<Integer, ValueAxis> entry : this.rangeAxes.entrySet()) {\r\n if (entry.getValue() == axis) {\r\n return entry.getKey();\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Returns the range for the specified axis.\r\n *\r\n * @param axis the axis.\r\n *\r\n * @return The range.\r\n */\r\n @Override\r\n public Range getDataRange(ValueAxis axis) {\r\n\r\n Range result = null;\r\n List<XYDataset> mappedDatasets = new ArrayList<XYDataset>();\r\n List<XYAnnotation> includedAnnotations = new ArrayList<XYAnnotation>();\r\n boolean isDomainAxis = true;\r\n\r\n // is it a domain axis?\r\n int domainIndex = getDomainAxisIndex(axis);\r\n if (domainIndex >= 0) {\r\n isDomainAxis = true;\r\n mappedDatasets.addAll(getDatasetsMappedToDomainAxis(domainIndex));\r\n if (domainIndex == 0) {\r\n // grab the plot's annotations\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n if (annotation instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(annotation);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // or is it a range axis?\r\n int rangeIndex = getRangeAxisIndex(axis);\r\n if (rangeIndex >= 0) {\r\n isDomainAxis = false;\r\n mappedDatasets.addAll(getDatasetsMappedToRangeAxis(rangeIndex));\r\n if (rangeIndex == 0) {\r\n Iterator iterator = this.annotations.iterator();\r\n while (iterator.hasNext()) {\r\n XYAnnotation annotation = (XYAnnotation) iterator.next();\r\n if (annotation instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(annotation);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // iterate through the datasets that map to the axis and get the union\r\n // of the ranges.\r\n for (XYDataset d : mappedDatasets) {\r\n if (d != null) {\r\n XYItemRenderer r = getRendererForDataset(d);\r\n if (isDomainAxis) {\r\n if (r != null) {\r\n result = Range.combine(result, r.findDomainBounds(d));\r\n }\r\n else {\r\n result = Range.combine(result,\r\n DatasetUtilities.findDomainBounds(d));\r\n }\r\n }\r\n else {\r\n if (r != null) {\r\n result = Range.combine(result, r.findRangeBounds(d));\r\n }\r\n else {\r\n result = Range.combine(result,\r\n DatasetUtilities.findRangeBounds(d));\r\n }\r\n }\r\n // FIXME: the XYItemRenderer interface doesn't specify the\r\n // getAnnotations() method but it should\r\n if (r instanceof AbstractXYItemRenderer) {\r\n AbstractXYItemRenderer rr = (AbstractXYItemRenderer) r;\r\n Collection c = rr.getAnnotations();\r\n Iterator i = c.iterator();\r\n while (i.hasNext()) {\r\n XYAnnotation a = (XYAnnotation) i.next();\r\n if (a instanceof XYAnnotationBoundsInfo) {\r\n includedAnnotations.add(a);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n Iterator it = includedAnnotations.iterator();\r\n while (it.hasNext()) {\r\n XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next();\r\n if (xyabi.getIncludeInDataBounds()) {\r\n if (isDomainAxis) {\r\n result = Range.combine(result, xyabi.getXRange());\r\n }\r\n else {\r\n result = Range.combine(result, xyabi.getYRange());\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n\r\n }\r\n\r\n /**\r\n * Receives notification of a change to an {@link Annotation} added to\r\n * this plot.\r\n *\r\n * @param event information about the event (not used here).\r\n *\r\n * @since 1.0.14\r\n */\r\n @Override\r\n public void annotationChanged(AnnotationChangeEvent event) {\r\n if (getParent() != null) {\r\n getParent().annotationChanged(event);\r\n }\r\n else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a change to the plot's dataset.\r\n * <P>\r\n * The axis ranges are updated if necessary.\r\n *\r\n * @param event information about the event (not used here).\r\n */\r\n @Override\r\n public void datasetChanged(DatasetChangeEvent event) {\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n if (getParent() != null) {\r\n getParent().datasetChanged(event);\r\n }\r\n else {\r\n PlotChangeEvent e = new PlotChangeEvent(this);\r\n e.setType(ChartChangeEventType.DATASET_UPDATED);\r\n notifyListeners(e);\r\n }\r\n }\r\n\r\n /**\r\n * Receives notification of a renderer change event.\r\n *\r\n * @param event the event.\r\n */\r\n @Override\r\n public void rendererChanged(RendererChangeEvent event) {\r\n // if the event was caused by a change to series visibility, then\r\n // the axis ranges might need updating...\r\n if (event.getSeriesVisibilityChanged()) {\r\n configureDomainAxes();\r\n configureRangeAxes();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the domain crosshair is visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setDomainCrosshairVisible(boolean)\r\n */\r\n public boolean isDomainCrosshairVisible() {\r\n return this.domainCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the domain crosshair is visible\r\n * and, if the flag changes, sends a {@link PlotChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isDomainCrosshairVisible()\r\n */\r\n public void setDomainCrosshairVisible(boolean flag) {\r\n if (this.domainCrosshairVisible != flag) {\r\n this.domainCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the crosshair should \"lock-on\"\r\n * to actual data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setDomainCrosshairLockedOnData(boolean)\r\n */\r\n public boolean isDomainCrosshairLockedOnData() {\r\n return this.domainCrosshairLockedOnData;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the domain crosshair should\r\n * \"lock-on\" to actual data values. If the flag value changes, this\r\n * method sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isDomainCrosshairLockedOnData()\r\n */\r\n public void setDomainCrosshairLockedOnData(boolean flag) {\r\n if (this.domainCrosshairLockedOnData != flag) {\r\n this.domainCrosshairLockedOnData = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the domain crosshair value.\r\n *\r\n * @return The value.\r\n *\r\n * @see #setDomainCrosshairValue(double)\r\n */\r\n public double getDomainCrosshairValue() {\r\n return this.domainCrosshairValue;\r\n }\r\n\r\n /**\r\n * Sets the domain crosshair value and sends a {@link PlotChangeEvent} to\r\n * all registered listeners (provided that the domain crosshair is visible).\r\n *\r\n * @param value the value.\r\n *\r\n * @see #getDomainCrosshairValue()\r\n */\r\n public void setDomainCrosshairValue(double value) {\r\n setDomainCrosshairValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the domain crosshair value and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners (provided that the\r\n * domain crosshair is visible).\r\n *\r\n * @param value the new value.\r\n * @param notify notify listeners?\r\n *\r\n * @see #getDomainCrosshairValue()\r\n */\r\n public void setDomainCrosshairValue(double value, boolean notify) {\r\n this.domainCrosshairValue = value;\r\n if (isDomainCrosshairVisible() && notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the {@link Stroke} used to draw the crosshair (if visible).\r\n *\r\n * @return The crosshair stroke (never <code>null</code>).\r\n *\r\n * @see #setDomainCrosshairStroke(Stroke)\r\n * @see #isDomainCrosshairVisible()\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public Stroke getDomainCrosshairStroke() {\r\n return this.domainCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the Stroke used to draw the crosshairs (if visible) and notifies\r\n * registered listeners that the axis has been modified.\r\n *\r\n * @param stroke the new crosshair stroke (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public void setDomainCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.domainCrosshairStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the domain crosshair paint.\r\n *\r\n * @return The crosshair paint (never <code>null</code>).\r\n *\r\n * @see #setDomainCrosshairPaint(Paint)\r\n * @see #isDomainCrosshairVisible()\r\n * @see #getDomainCrosshairStroke()\r\n */\r\n public Paint getDomainCrosshairPaint() {\r\n return this.domainCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to draw the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the new crosshair paint (<code>null</code> not permitted).\r\n *\r\n * @see #getDomainCrosshairPaint()\r\n */\r\n public void setDomainCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.domainCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the range crosshair is visible.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairVisible(boolean)\r\n * @see #isDomainCrosshairVisible()\r\n */\r\n public boolean isRangeCrosshairVisible() {\r\n return this.rangeCrosshairVisible;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair is visible.\r\n * If the flag value changes, this method sends a {@link PlotChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isRangeCrosshairVisible()\r\n */\r\n public void setRangeCrosshairVisible(boolean flag) {\r\n if (this.rangeCrosshairVisible != flag) {\r\n this.rangeCrosshairVisible = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the crosshair should \"lock-on\"\r\n * to actual data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setRangeCrosshairLockedOnData(boolean)\r\n */\r\n public boolean isRangeCrosshairLockedOnData() {\r\n return this.rangeCrosshairLockedOnData;\r\n }\r\n\r\n /**\r\n * Sets the flag indicating whether or not the range crosshair should\r\n * \"lock-on\" to actual data values. If the flag value changes, this method\r\n * sends a {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isRangeCrosshairLockedOnData()\r\n */\r\n public void setRangeCrosshairLockedOnData(boolean flag) {\r\n if (this.rangeCrosshairLockedOnData != flag) {\r\n this.rangeCrosshairLockedOnData = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range crosshair value.\r\n *\r\n * @return The value.\r\n *\r\n * @see #setRangeCrosshairValue(double)\r\n */\r\n public double getRangeCrosshairValue() {\r\n return this.rangeCrosshairValue;\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value.\r\n * <P>\r\n * Registered listeners are notified that the plot has been modified, but\r\n * only if the crosshair is visible.\r\n *\r\n * @param value the new value.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value) {\r\n setRangeCrosshairValue(value, true);\r\n }\r\n\r\n /**\r\n * Sets the range crosshair value and sends a {@link PlotChangeEvent} to\r\n * all registered listeners, but only if the crosshair is visible.\r\n *\r\n * @param value the new value.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n *\r\n * @see #getRangeCrosshairValue()\r\n */\r\n public void setRangeCrosshairValue(double value, boolean notify) {\r\n this.rangeCrosshairValue = value;\r\n if (isRangeCrosshairVisible() && notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the stroke used to draw the crosshair (if visible).\r\n *\r\n * @return The crosshair stroke (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairStroke(Stroke)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public Stroke getRangeCrosshairStroke() {\r\n return this.rangeCrosshairStroke;\r\n }\r\n\r\n /**\r\n * Sets the stroke used to draw the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param stroke the new crosshair stroke (<code>null</code> not\r\n * permitted).\r\n *\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public void setRangeCrosshairStroke(Stroke stroke) {\r\n ParamChecks.nullNotPermitted(stroke, \"stroke\");\r\n this.rangeCrosshairStroke = stroke;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the range crosshair paint.\r\n *\r\n * @return The crosshair paint (never <code>null</code>).\r\n *\r\n * @see #setRangeCrosshairPaint(Paint)\r\n * @see #isRangeCrosshairVisible()\r\n * @see #getRangeCrosshairStroke()\r\n */\r\n public Paint getRangeCrosshairPaint() {\r\n return this.rangeCrosshairPaint;\r\n }\r\n\r\n /**\r\n * Sets the paint used to color the crosshairs (if visible) and sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param paint the new crosshair paint (<code>null</code> not permitted).\r\n *\r\n * @see #getRangeCrosshairPaint()\r\n */\r\n public void setRangeCrosshairPaint(Paint paint) {\r\n ParamChecks.nullNotPermitted(paint, \"paint\");\r\n this.rangeCrosshairPaint = paint;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the fixed domain axis space.\r\n *\r\n * @return The fixed domain axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedDomainAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedDomainAxisSpace() {\r\n return this.fixedDomainAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space) {\r\n setFixedDomainAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed domain axis space and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedDomainAxisSpace()\r\n *\r\n * @since 1.0.9\r\n */\r\n public void setFixedDomainAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedDomainAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the fixed range axis space.\r\n *\r\n * @return The fixed range axis space (possibly <code>null</code>).\r\n *\r\n * @see #setFixedRangeAxisSpace(AxisSpace)\r\n */\r\n public AxisSpace getFixedRangeAxisSpace() {\r\n return this.fixedRangeAxisSpace;\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space) {\r\n setFixedRangeAxisSpace(space, true);\r\n }\r\n\r\n /**\r\n * Sets the fixed range axis space and, if requested, sends a\r\n * {@link PlotChangeEvent} to all registered listeners.\r\n *\r\n * @param space the space (<code>null</code> permitted).\r\n * @param notify notify listeners?\r\n *\r\n * @see #getFixedRangeAxisSpace()\r\n *\r\n * @since 1.0.9\r\n */\r\n public void setFixedRangeAxisSpace(AxisSpace space, boolean notify) {\r\n this.fixedRangeAxisSpace = space;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if panning is enabled for the domain axes,\r\n * and <code>false</code> otherwise.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isDomainPannable() {\r\n return this.domainPannable;\r\n }\r\n\r\n /**\r\n * Sets the flag that enables or disables panning of the plot along the\r\n * domain axes.\r\n *\r\n * @param pannable the new flag value.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setDomainPannable(boolean pannable) {\r\n this.domainPannable = pannable;\r\n }\r\n\r\n /**\r\n * Returns {@code true} if panning is enabled for the range axis/axes,\r\n * and {@code false} otherwise. The default value is {@code false}.\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public boolean isRangePannable() {\r\n return this.rangePannable;\r\n }\r\n\r\n /**\r\n * Sets the flag that enables or disables panning of the plot along\r\n * the range axis/axes.\r\n *\r\n * @param pannable the new flag value.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void setRangePannable(boolean pannable) {\r\n this.rangePannable = pannable;\r\n }\r\n\r\n /**\r\n * Pans the domain axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panDomainAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n if (!isDomainPannable()) {\r\n return;\r\n }\r\n int domainAxisCount = getDomainAxisCount();\r\n for (int i = 0; i < domainAxisCount; i++) {\r\n ValueAxis axis = getDomainAxis(i);\r\n if (axis == null) {\r\n continue;\r\n }\r\n if (axis.isInverted()) {\r\n percent = -percent;\r\n }\r\n axis.pan(percent);\r\n }\r\n }\r\n\r\n /**\r\n * Pans the range axes by the specified percentage.\r\n *\r\n * @param percent the distance to pan (as a percentage of the axis length).\r\n * @param info the plot info\r\n * @param source the source point where the pan action started.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public void panRangeAxes(double percent, PlotRenderingInfo info,\r\n Point2D source) {\r\n if (!isRangePannable()) {\r\n return;\r\n }\r\n int rangeAxisCount = getRangeAxisCount();\r\n for (int i = 0; i < rangeAxisCount; i++) {\r\n ValueAxis axis = getRangeAxis(i);\r\n if (axis == null) {\r\n continue;\r\n }\r\n if (axis.isInverted()) {\r\n percent = -percent;\r\n }\r\n axis.pan(percent);\r\n }\r\n }\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point (in Java2D space).\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo info,\r\n Point2D source) {\r\n // delegate to other method\r\n zoomDomainAxes(factor, info, source, false);\r\n }\r\n\r\n /**\r\n * Multiplies the range on the domain axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point (in Java2D space).\r\n * @param useAnchor use source point as zoom anchor?\r\n *\r\n * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomDomainAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n\r\n // perform the zoom on each domain axis\r\n for (ValueAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis == null) {\r\n continue;\r\n }\r\n if (useAnchor) {\r\n // get the relevant source coordinate given the plot orientation\r\n double sourceX = source.getX();\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n sourceX = source.getY();\r\n }\r\n double anchorX = xAxis.java2DToValue(sourceX,\r\n info.getDataArea(), getDomainAxisEdge());\r\n xAxis.resizeRange2(factor, anchorX);\r\n } else {\r\n xAxis.resizeRange(factor);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the domain axis/axes. The new lower and upper bounds are\r\n * specified as percentages of the current axis range, where 0 percent is\r\n * the current lower bound and 100 percent is the current upper bound.\r\n *\r\n * @param lowerPercent a percentage that determines the new lower bound\r\n * for the axis (e.g. 0.20 is twenty percent).\r\n * @param upperPercent a percentage that determines the new upper bound\r\n * for the axis (e.g. 0.80 is eighty percent).\r\n * @param info the plot rendering info.\r\n * @param source the source point (ignored).\r\n *\r\n * @see #zoomRangeAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomDomainAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo info, Point2D source) {\r\n for (ValueAxis xAxis : this.domainAxes.values()) {\r\n if (xAxis != null) {\r\n xAxis.zoomRange(lowerPercent, upperPercent);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo info,\r\n Point2D source) {\r\n // delegate to other method\r\n zoomRangeAxes(factor, info, source, false);\r\n }\r\n\r\n /**\r\n * Multiplies the range on the range axis/axes by the specified factor.\r\n *\r\n * @param factor the zoom factor.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n * @param useAnchor a flag that controls whether or not the source point\r\n * is used for the zoom anchor.\r\n *\r\n * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)\r\n *\r\n * @since 1.0.7\r\n */\r\n @Override\r\n public void zoomRangeAxes(double factor, PlotRenderingInfo info,\r\n Point2D source, boolean useAnchor) {\r\n\r\n // perform the zoom on each range axis\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis == null) {\r\n continue;\r\n }\r\n if (useAnchor) {\r\n // get the relevant source coordinate given the plot orientation\r\n double sourceY = source.getY();\r\n if (this.orientation == PlotOrientation.HORIZONTAL) {\r\n sourceY = source.getX();\r\n }\r\n double anchorY = yAxis.java2DToValue(sourceY,\r\n info.getDataArea(), getRangeAxisEdge());\r\n yAxis.resizeRange2(factor, anchorY);\r\n } else {\r\n yAxis.resizeRange(factor);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the range axes.\r\n *\r\n * @param lowerPercent the lower bound.\r\n * @param upperPercent the upper bound.\r\n * @param info the plot rendering info.\r\n * @param source the source point.\r\n *\r\n * @see #zoomDomainAxes(double, double, PlotRenderingInfo, Point2D)\r\n */\r\n @Override\r\n public void zoomRangeAxes(double lowerPercent, double upperPercent,\r\n PlotRenderingInfo info, Point2D source) {\r\n for (ValueAxis yAxis : this.rangeAxes.values()) {\r\n if (yAxis != null) {\r\n yAxis.zoomRange(lowerPercent, upperPercent);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code>, indicating that the domain axis/axes for this\r\n * plot are zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isRangeZoomable()\r\n */\r\n @Override\r\n public boolean isDomainZoomable() {\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code>, indicating that the range axis/axes for this\r\n * plot are zoomable.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #isDomainZoomable()\r\n */\r\n @Override\r\n public boolean isRangeZoomable() {\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns the number of series in the primary dataset for this plot. If\r\n * the dataset is <code>null</code>, the method returns 0.\r\n *\r\n * @return The series count.\r\n */\r\n public int getSeriesCount() {\r\n int result = 0;\r\n XYDataset dataset = getDataset();\r\n if (dataset != null) {\r\n result = dataset.getSeriesCount();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the fixed legend items, if any.\r\n *\r\n * @return The legend items (possibly <code>null</code>).\r\n *\r\n * @see #setFixedLegendItems(LegendItemCollection)\r\n */\r\n public LegendItemCollection getFixedLegendItems() {\r\n return this.fixedLegendItems;\r\n }\r\n\r\n /**\r\n * Sets the fixed legend items for the plot. Leave this set to\r\n * <code>null</code> if you prefer the legend items to be created\r\n * automatically.\r\n *\r\n * @param items the legend items (<code>null</code> permitted).\r\n *\r\n * @see #getFixedLegendItems()\r\n */\r\n public void setFixedLegendItems(LegendItemCollection items) {\r\n this.fixedLegendItems = items;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the legend items for the plot. Each legend item is generated by\r\n * the plot's renderer, since the renderer is responsible for the visual\r\n * representation of the data.\r\n *\r\n * @return The legend items.\r\n */\r\n @Override\r\n public LegendItemCollection getLegendItems() {\r\n if (this.fixedLegendItems != null) {\r\n return this.fixedLegendItems;\r\n }\r\n LegendItemCollection result = new LegendItemCollection();\r\n for (XYDataset dataset : this.datasets.values()) {\r\n if (dataset == null) {\r\n continue;\r\n }\r\n int datasetIndex = indexOf(dataset);\r\n XYItemRenderer renderer = getRenderer(datasetIndex);\r\n if (renderer == null) {\r\n renderer = getRenderer(0);\r\n }\r\n if (renderer != null) {\r\n int seriesCount = dataset.getSeriesCount();\r\n for (int i = 0; i < seriesCount; i++) {\r\n if (renderer.isSeriesVisible(i)\r\n && renderer.isSeriesVisibleInLegend(i)) {\r\n LegendItem item = renderer.getLegendItem(\r\n datasetIndex, i);\r\n if (item != null) {\r\n result.add(item);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Tests this plot for equality with another object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return <code>true</code> or <code>false</code>.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof XYPlot)) {\r\n return false;\r\n }\r\n XYPlot that = (XYPlot) obj;\r\n if (this.weight != that.weight) {\r\n return false;\r\n }\r\n if (this.orientation != that.orientation) {\r\n return false;\r\n }\r\n if (!this.domainAxes.equals(that.domainAxes)) {\r\n return false;\r\n }\r\n if (!this.domainAxisLocations.equals(that.domainAxisLocations)) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairLockedOnData\r\n != that.rangeCrosshairLockedOnData) {\r\n return false;\r\n }\r\n if (this.domainGridlinesVisible != that.domainGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.rangeGridlinesVisible != that.rangeGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.domainMinorGridlinesVisible\r\n != that.domainMinorGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.rangeMinorGridlinesVisible\r\n != that.rangeMinorGridlinesVisible) {\r\n return false;\r\n }\r\n if (this.domainZeroBaselineVisible != that.domainZeroBaselineVisible) {\r\n return false;\r\n }\r\n if (this.rangeZeroBaselineVisible != that.rangeZeroBaselineVisible) {\r\n return false;\r\n }\r\n if (this.domainCrosshairVisible != that.domainCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.domainCrosshairValue != that.domainCrosshairValue) {\r\n return false;\r\n }\r\n if (this.domainCrosshairLockedOnData\r\n != that.domainCrosshairLockedOnData) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairVisible != that.rangeCrosshairVisible) {\r\n return false;\r\n }\r\n if (this.rangeCrosshairValue != that.rangeCrosshairValue) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.axisOffset, that.axisOffset)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.renderers, that.renderers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeAxes, that.rangeAxes)) {\r\n return false;\r\n }\r\n if (!this.rangeAxisLocations.equals(that.rangeAxisLocations)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToDomainAxesMap,\r\n that.datasetToDomainAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.datasetToRangeAxesMap,\r\n that.datasetToRangeAxesMap)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainGridlineStroke,\r\n that.domainGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainGridlinePaint,\r\n that.domainGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeGridlineStroke,\r\n that.rangeGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeGridlinePaint,\r\n that.rangeGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainMinorGridlineStroke,\r\n that.domainMinorGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainMinorGridlinePaint,\r\n that.domainMinorGridlinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeMinorGridlineStroke,\r\n that.rangeMinorGridlineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeMinorGridlinePaint,\r\n that.rangeMinorGridlinePaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainZeroBaselinePaint,\r\n that.domainZeroBaselinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainZeroBaselineStroke,\r\n that.domainZeroBaselineStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeZeroBaselinePaint,\r\n that.rangeZeroBaselinePaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeZeroBaselineStroke,\r\n that.rangeZeroBaselineStroke)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.domainCrosshairStroke,\r\n that.domainCrosshairStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainCrosshairPaint,\r\n that.domainCrosshairPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.rangeCrosshairStroke,\r\n that.rangeCrosshairStroke)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeCrosshairPaint,\r\n that.rangeCrosshairPaint)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundDomainMarkers,\r\n that.foregroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundDomainMarkers,\r\n that.backgroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundRangeMarkers,\r\n that.foregroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundRangeMarkers,\r\n that.backgroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundDomainMarkers,\r\n that.foregroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundDomainMarkers,\r\n that.backgroundDomainMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.foregroundRangeMarkers,\r\n that.foregroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.backgroundRangeMarkers,\r\n that.backgroundRangeMarkers)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.annotations, that.annotations)) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.fixedLegendItems,\r\n that.fixedLegendItems)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.domainTickBandPaint,\r\n that.domainTickBandPaint)) {\r\n return false;\r\n }\r\n if (!PaintUtilities.equal(this.rangeTickBandPaint,\r\n that.rangeTickBandPaint)) {\r\n return false;\r\n }\r\n if (!this.quadrantOrigin.equals(that.quadrantOrigin)) {\r\n return false;\r\n }\r\n for (int i = 0; i < 4; i++) {\r\n if (!PaintUtilities.equal(this.quadrantPaint[i],\r\n that.quadrantPaint[i])) {\r\n return false;\r\n }\r\n }\r\n if (!ObjectUtilities.equal(this.shadowGenerator,\r\n that.shadowGenerator)) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a clone of the plot.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException this can occur if some component of\r\n * the plot cannot be cloned.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n XYPlot clone = (XYPlot) super.clone();\r\n clone.domainAxes = CloneUtils.cloneMapValues(this.domainAxes);\r\n for (ValueAxis axis : clone.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n clone.rangeAxes = CloneUtils.cloneMapValues(this.rangeAxes);\r\n for (ValueAxis axis : clone.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(clone);\r\n axis.addChangeListener(clone);\r\n }\r\n }\r\n clone.domainAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.domainAxisLocations);\r\n clone.rangeAxisLocations = new HashMap<Integer, AxisLocation>(\r\n this.rangeAxisLocations);\r\n\r\n // the datasets are not cloned, but listeners need to be added...\r\n clone.datasets = new HashMap<Integer, XYDataset>(this.datasets);\r\n for (XYDataset dataset : clone.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(clone);\r\n }\r\n }\r\n\r\n clone.datasetToDomainAxesMap = new TreeMap();\r\n clone.datasetToDomainAxesMap.putAll(this.datasetToDomainAxesMap);\r\n clone.datasetToRangeAxesMap = new TreeMap();\r\n clone.datasetToRangeAxesMap.putAll(this.datasetToRangeAxesMap);\r\n\r\n clone.renderers = CloneUtils.cloneMapValues(this.renderers);\r\n for (XYItemRenderer renderer : clone.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.setPlot(clone);\r\n renderer.addChangeListener(clone);\r\n }\r\n }\r\n clone.foregroundDomainMarkers = (Map) ObjectUtilities.clone(\r\n this.foregroundDomainMarkers);\r\n clone.backgroundDomainMarkers = (Map) ObjectUtilities.clone(\r\n this.backgroundDomainMarkers);\r\n clone.foregroundRangeMarkers = (Map) ObjectUtilities.clone(\r\n this.foregroundRangeMarkers);\r\n clone.backgroundRangeMarkers = (Map) ObjectUtilities.clone(\r\n this.backgroundRangeMarkers);\r\n clone.annotations = (List) ObjectUtilities.deepClone(this.annotations);\r\n if (this.fixedDomainAxisSpace != null) {\r\n clone.fixedDomainAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedDomainAxisSpace);\r\n }\r\n if (this.fixedRangeAxisSpace != null) {\r\n clone.fixedRangeAxisSpace = (AxisSpace) ObjectUtilities.clone(\r\n this.fixedRangeAxisSpace);\r\n }\r\n if (this.fixedLegendItems != null) {\r\n clone.fixedLegendItems\r\n = (LegendItemCollection) this.fixedLegendItems.clone();\r\n }\r\n clone.quadrantOrigin = (Point2D) ObjectUtilities.clone(\r\n this.quadrantOrigin);\r\n clone.quadrantPaint = this.quadrantPaint.clone();\r\n return clone;\r\n\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeStroke(this.domainGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.domainGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.domainMinorGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.domainMinorGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeMinorGridlineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeMinorGridlinePaint, stream);\r\n SerialUtilities.writeStroke(this.rangeZeroBaselineStroke, stream);\r\n SerialUtilities.writePaint(this.rangeZeroBaselinePaint, stream);\r\n SerialUtilities.writeStroke(this.domainCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.domainCrosshairPaint, stream);\r\n SerialUtilities.writeStroke(this.rangeCrosshairStroke, stream);\r\n SerialUtilities.writePaint(this.rangeCrosshairPaint, stream);\r\n SerialUtilities.writePaint(this.domainTickBandPaint, stream);\r\n SerialUtilities.writePaint(this.rangeTickBandPaint, stream);\r\n SerialUtilities.writePoint2D(this.quadrantOrigin, stream);\r\n for (int i = 0; i < 4; i++) {\r\n SerialUtilities.writePaint(this.quadrantPaint[i], stream);\r\n }\r\n SerialUtilities.writeStroke(this.domainZeroBaselineStroke, stream);\r\n SerialUtilities.writePaint(this.domainZeroBaselinePaint, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n\r\n stream.defaultReadObject();\r\n this.domainGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.domainGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.domainMinorGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.domainMinorGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeMinorGridlineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeMinorGridlinePaint = SerialUtilities.readPaint(stream);\r\n this.rangeZeroBaselineStroke = SerialUtilities.readStroke(stream);\r\n this.rangeZeroBaselinePaint = SerialUtilities.readPaint(stream);\r\n this.domainCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.domainCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.rangeCrosshairStroke = SerialUtilities.readStroke(stream);\r\n this.rangeCrosshairPaint = SerialUtilities.readPaint(stream);\r\n this.domainTickBandPaint = SerialUtilities.readPaint(stream);\r\n this.rangeTickBandPaint = SerialUtilities.readPaint(stream);\r\n this.quadrantOrigin = SerialUtilities.readPoint2D(stream);\r\n this.quadrantPaint = new Paint[4];\r\n for (int i = 0; i < 4; i++) {\r\n this.quadrantPaint[i] = SerialUtilities.readPaint(stream);\r\n }\r\n\r\n this.domainZeroBaselineStroke = SerialUtilities.readStroke(stream);\r\n this.domainZeroBaselinePaint = SerialUtilities.readPaint(stream);\r\n\r\n // register the plot as a listener with its axes, datasets, and\r\n // renderers...\r\n for (ValueAxis axis : this.domainAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n axis.addChangeListener(this);\r\n }\r\n }\r\n for (ValueAxis axis : this.rangeAxes.values()) {\r\n if (axis != null) {\r\n axis.setPlot(this);\r\n axis.addChangeListener(this);\r\n }\r\n }\r\n for (XYDataset dataset : this.datasets.values()) {\r\n if (dataset != null) {\r\n dataset.addChangeListener(this);\r\n }\r\n }\r\n for (XYItemRenderer renderer : this.renderers.values()) {\r\n if (renderer != null) {\r\n renderer.addChangeListener(this);\r\n }\r\n }\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "ParamChecks", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/util/ParamChecks.java", "snippet": "public class ParamChecks {\r\n\r\n /**\r\n * Throws an <code>IllegalArgumentException</code> if the supplied \r\n * <code>param</code> is <code>null</code>.\r\n *\r\n * @param param the parameter to check (<code>null</code> permitted).\r\n * @param name the name of the parameter (to use in the exception message\r\n * if <code>param</code> is <code>null</code>).\r\n *\r\n * @throws IllegalArgumentException if <code>param</code> is \r\n * <code>null</code>.\r\n *\r\n * @since 1.0.14\r\n */\r\n public static void nullNotPermitted(Object param, String name) {\r\n if (param == null) {\r\n throw new IllegalArgumentException(\"Null '\" + name + \"' argument.\");\r\n }\r\n }\r\n \r\n /**\r\n * Throws an {@code IllegalArgumentException} if {@code value} is negative.\r\n * \r\n * @param value the value.\r\n * @param name the parameter name (for use in the exception message).\r\n * \r\n * @since 1.0.18\r\n */\r\n public static void requireNonNegative(int value, String name) {\r\n if (value < 0) {\r\n throw new IllegalArgumentException(\"Require '\" + name + \"' (\" \r\n + value + \") to be non-negative.\");\r\n }\r\n }\r\n}\r" }, { "identifier": "Range", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/Range.java", "snippet": "public strictfp class Range implements Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -906333695431863380L;\r\n\r\n /** The lower bound of the range. */\r\n private double lower;\r\n\r\n /** The upper bound of the range. */\r\n private double upper;\r\n\r\n /**\r\n * Creates a new range.\r\n *\r\n * @param lower the lower bound (must be &lt;= upper bound).\r\n * @param upper the upper bound (must be &gt;= lower bound).\r\n */\r\n public Range(double lower, double upper) {\r\n if (lower > upper) {\r\n String msg = \"Range(double, double): require lower (\" + lower\r\n + \") <= upper (\" + upper + \").\";\r\n throw new IllegalArgumentException(msg);\r\n }\r\n this.lower = lower;\r\n this.upper = upper;\r\n }\r\n\r\n /**\r\n * Returns the lower bound for the range.\r\n *\r\n * @return The lower bound.\r\n */\r\n public double getLowerBound() {\r\n return this.lower;\r\n }\r\n\r\n /**\r\n * Returns the upper bound for the range.\r\n *\r\n * @return The upper bound.\r\n */\r\n public double getUpperBound() {\r\n return this.upper;\r\n }\r\n\r\n /**\r\n * Returns the length of the range.\r\n *\r\n * @return The length.\r\n */\r\n public double getLength() {\r\n return this.upper - this.lower;\r\n }\r\n\r\n /**\r\n * Returns the central value for the range.\r\n *\r\n * @return The central value.\r\n */\r\n public double getCentralValue() {\r\n return this.lower / 2.0 + this.upper / 2.0;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range contains the specified value and\r\n * <code>false</code> otherwise.\r\n *\r\n * @param value the value to lookup.\r\n *\r\n * @return <code>true</code> if the range contains the specified value.\r\n */\r\n public boolean contains(double value) {\r\n return (value >= this.lower && value <= this.upper);\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range intersects with the specified\r\n * range, and <code>false</code> otherwise.\r\n *\r\n * @param b0 the lower bound (should be &lt;= b1).\r\n * @param b1 the upper bound (should be &gt;= b0).\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean intersects(double b0, double b1) {\r\n if (b0 <= this.lower) {\r\n return (b1 > this.lower);\r\n }\r\n else {\r\n return (b0 < this.upper && b1 >= b0);\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the range intersects with the specified\r\n * range, and <code>false</code> otherwise.\r\n *\r\n * @param range another range (<code>null</code> not permitted).\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.9\r\n */\r\n public boolean intersects(Range range) {\r\n return intersects(range.getLowerBound(), range.getUpperBound());\r\n }\r\n\r\n /**\r\n * Returns the value within the range that is closest to the specified\r\n * value.\r\n *\r\n * @param value the value.\r\n *\r\n * @return The constrained value.\r\n */\r\n public double constrain(double value) {\r\n double result = value;\r\n if (!contains(value)) {\r\n if (value > this.upper) {\r\n result = this.upper;\r\n }\r\n else if (value < this.lower) {\r\n result = this.lower;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates a new range by combining two existing ranges.\r\n * <P>\r\n * Note that:\r\n * <ul>\r\n * <li>either range can be <code>null</code>, in which case the other\r\n * range is returned;</li>\r\n * <li>if both ranges are <code>null</code> the return value is\r\n * <code>null</code>.</li>\r\n * </ul>\r\n *\r\n * @param range1 the first range (<code>null</code> permitted).\r\n * @param range2 the second range (<code>null</code> permitted).\r\n *\r\n * @return A new range (possibly <code>null</code>).\r\n */\r\n public static Range combine(Range range1, Range range2) {\r\n if (range1 == null) {\r\n return range2;\r\n }\r\n if (range2 == null) {\r\n return range1;\r\n }\r\n double l = Math.min(range1.getLowerBound(), range2.getLowerBound());\r\n double u = Math.max(range1.getUpperBound(), range2.getUpperBound());\r\n return new Range(l, u);\r\n }\r\n\r\n /**\r\n * Returns a new range that spans both <code>range1</code> and \r\n * <code>range2</code>. This method has a special handling to ignore\r\n * Double.NaN values.\r\n *\r\n * @param range1 the first range (<code>null</code> permitted).\r\n * @param range2 the second range (<code>null</code> permitted).\r\n *\r\n * @return A new range (possibly <code>null</code>).\r\n *\r\n * @since 1.0.15\r\n */\r\n public static Range combineIgnoringNaN(Range range1, Range range2) {\r\n if (range1 == null) {\r\n if (range2 != null && range2.isNaNRange()) {\r\n return null;\r\n }\r\n return range2;\r\n }\r\n if (range2 == null) {\r\n if (range1.isNaNRange()) {\r\n return null;\r\n }\r\n return range1;\r\n }\r\n double l = min(range1.getLowerBound(), range2.getLowerBound());\r\n double u = max(range1.getUpperBound(), range2.getUpperBound());\r\n if (Double.isNaN(l) && Double.isNaN(u)) {\r\n return null;\r\n }\r\n return new Range(l, u);\r\n }\r\n \r\n /**\r\n * Returns the minimum value. If either value is NaN, the other value is \r\n * returned. If both are NaN, NaN is returned.\r\n * \r\n * @param d1 value 1.\r\n * @param d2 value 2.\r\n * \r\n * @return The minimum of the two values. \r\n */\r\n private static double min(double d1, double d2) {\r\n if (Double.isNaN(d1)) {\r\n return d2;\r\n }\r\n if (Double.isNaN(d2)) {\r\n return d1;\r\n }\r\n return Math.min(d1, d2);\r\n }\r\n\r\n private static double max(double d1, double d2) {\r\n if (Double.isNaN(d1)) {\r\n return d2;\r\n }\r\n if (Double.isNaN(d2)) {\r\n return d1;\r\n }\r\n return Math.max(d1, d2);\r\n }\r\n\r\n /**\r\n * Returns a range that includes all the values in the specified\r\n * <code>range</code> AND the specified <code>value</code>.\r\n *\r\n * @param range the range (<code>null</code> permitted).\r\n * @param value the value that must be included.\r\n *\r\n * @return A range.\r\n *\r\n * @since 1.0.1\r\n */\r\n public static Range expandToInclude(Range range, double value) {\r\n if (range == null) {\r\n return new Range(value, value);\r\n }\r\n if (value < range.getLowerBound()) {\r\n return new Range(value, range.getUpperBound());\r\n }\r\n else if (value > range.getUpperBound()) {\r\n return new Range(range.getLowerBound(), value);\r\n }\r\n else {\r\n return range;\r\n }\r\n }\r\n\r\n /**\r\n * Creates a new range by adding margins to an existing range.\r\n *\r\n * @param range the range (<code>null</code> not permitted).\r\n * @param lowerMargin the lower margin (expressed as a percentage of the\r\n * range length).\r\n * @param upperMargin the upper margin (expressed as a percentage of the\r\n * range length).\r\n *\r\n * @return The expanded range.\r\n */\r\n public static Range expand(Range range,\r\n double lowerMargin, double upperMargin) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n double length = range.getLength();\r\n double lower = range.getLowerBound() - length * lowerMargin;\r\n double upper = range.getUpperBound() + length * upperMargin;\r\n if (lower > upper) {\r\n lower = lower / 2.0 + upper / 2.0;\r\n upper = lower;\r\n }\r\n return new Range(lower, upper);\r\n }\r\n\r\n /**\r\n * Shifts the range by the specified amount.\r\n *\r\n * @param base the base range (<code>null</code> not permitted).\r\n * @param delta the shift amount.\r\n *\r\n * @return A new range.\r\n */\r\n public static Range shift(Range base, double delta) {\r\n return shift(base, delta, false);\r\n }\r\n\r\n /**\r\n * Shifts the range by the specified amount.\r\n *\r\n * @param base the base range (<code>null</code> not permitted).\r\n * @param delta the shift amount.\r\n * @param allowZeroCrossing a flag that determines whether or not the\r\n * bounds of the range are allowed to cross\r\n * zero after adjustment.\r\n *\r\n * @return A new range.\r\n */\r\n public static Range shift(Range base, double delta,\r\n boolean allowZeroCrossing) {\r\n ParamChecks.nullNotPermitted(base, \"base\");\r\n if (allowZeroCrossing) {\r\n return new Range(base.getLowerBound() + delta,\r\n base.getUpperBound() + delta);\r\n }\r\n else {\r\n return new Range(shiftWithNoZeroCrossing(base.getLowerBound(),\r\n delta), shiftWithNoZeroCrossing(base.getUpperBound(),\r\n delta));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the given <code>value</code> adjusted by <code>delta</code> but\r\n * with a check to prevent the result from crossing <code>0.0</code>.\r\n *\r\n * @param value the value.\r\n * @param delta the adjustment.\r\n *\r\n * @return The adjusted value.\r\n */\r\n private static double shiftWithNoZeroCrossing(double value, double delta) {\r\n if (value > 0.0) {\r\n return Math.max(value + delta, 0.0);\r\n }\r\n else if (value < 0.0) {\r\n return Math.min(value + delta, 0.0);\r\n }\r\n else {\r\n return value + delta;\r\n }\r\n }\r\n\r\n /**\r\n * Scales the range by the specified factor.\r\n *\r\n * @param base the base range (<code>null</code> not permitted).\r\n * @param factor the scaling factor (must be non-negative).\r\n *\r\n * @return A new range.\r\n *\r\n * @since 1.0.9\r\n */\r\n public static Range scale(Range base, double factor) {\r\n ParamChecks.nullNotPermitted(base, \"base\");\r\n if (factor < 0) {\r\n throw new IllegalArgumentException(\"Negative 'factor' argument.\");\r\n }\r\n return new Range(base.getLowerBound() * factor,\r\n base.getUpperBound() * factor);\r\n }\r\n\r\n /**\r\n * Tests this object for equality with an arbitrary object.\r\n *\r\n * @param obj the object to test against (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (!(obj instanceof Range)) {\r\n return false;\r\n }\r\n Range range = (Range) obj;\r\n if (!(this.lower == range.lower)) {\r\n return false;\r\n }\r\n if (!(this.upper == range.upper)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if both the lower and upper bounds are \r\n * <code>Double.NaN</code>, and <code>false</code> otherwise.\r\n * \r\n * @return A boolean.\r\n * \r\n * @since 1.0.18\r\n */\r\n public boolean isNaNRange() {\r\n return Double.isNaN(this.lower) && Double.isNaN(this.upper);\r\n }\r\n \r\n /**\r\n * Returns a hash code.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result;\r\n long temp;\r\n temp = Double.doubleToLongBits(this.lower);\r\n result = (int) (temp ^ (temp >>> 32));\r\n temp = Double.doubleToLongBits(this.upper);\r\n result = 29 * result + (int) (temp ^ (temp >>> 32));\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a string representation of this Range.\r\n *\r\n * @return A String \"Range[lower,upper]\" where lower=lower range and\r\n * upper=upper range.\r\n */\r\n @Override\r\n public String toString() {\r\n return (\"Range[\" + this.lower + \",\" + this.upper + \"]\");\r\n }\r\n\r\n}\r" } ]
import java.awt.Graphics2D; import java.awt.Image; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.util.ParamChecks; import org.jfree.data.Range; import org.jfree.ui.RectangleEdge; import org.jfree.util.ObjectUtilities; import org.jfree.util.PublicCloneable;
79,271
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------------- * XYDataImageAnnotation.java * -------------------------- * (C) Copyright 2008-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Peter Kolb (patch 2809117); * * Changes: * -------- * 17-Sep-2008 : Version 1, based on XYImageAnnotation (DG); * 10-Mar-2009 : Implemented XYAnnotationBoundsInfo (DG); * */ package org.jfree.chart.annotations; /** * An annotation that allows an image to be placed within a rectangle specified * in data coordinates on an {@link XYPlot}. Note that this annotation * is not currently serializable, so don't use it if you plan on serializing * your chart(s). * * @since 1.0.11 */ public class XYDataImageAnnotation extends AbstractXYAnnotation implements Cloneable, PublicCloneable, XYAnnotationBoundsInfo { /** The image. */ private transient Image image; /** * The x-coordinate (in data space). */ private double x; /** * The y-coordinate (in data space). */ private double y; /** * The image display area width in data coordinates. */ private double w; /** * The image display area height in data coordinates. */ private double h; /** * A flag indicating whether or not the annotation should contribute to * the data range for a plot/renderer. * * @since 1.0.13 */ private boolean includeInDataBounds; /** * Creates a new annotation to be displayed within the specified rectangle. * * @param image the image (<code>null</code> not permitted). * @param x the x-coordinate (in data space). * @param y the y-coordinate (in data space). * @param w the image display area width. * @param h the image display area height. */ public XYDataImageAnnotation(Image image, double x, double y, double w, double h) { this(image, x, y, w, h, false); } /** * Creates a new annotation to be displayed within the specified rectangle. * * @param image the image (<code>null</code> not permitted). * @param x the x-coordinate (in data space). * @param y the y-coordinate (in data space). * @param w the image display area width. * @param h the image display area height. * @param includeInDataBounds a flag that controls whether or not the * annotation is included in the data bounds for the axis autoRange. * * @since 1.0.13 */ public XYDataImageAnnotation(Image image, double x, double y, double w, double h, boolean includeInDataBounds) { super(); ParamChecks.nullNotPermitted(image, "image"); this.image = image; this.x = x; this.y = y; this.w = w; this.h = h; this.includeInDataBounds = includeInDataBounds; } /** * Returns the image for the annotation. * * @return The image. */ public Image getImage() { return this.image; } /** * Returns the x-coordinate (in data space) for the annotation. * * @return The x-coordinate. */ public double getX() { return this.x; } /** * Returns the y-coordinate (in data space) for the annotation. * * @return The y-coordinate. */ public double getY() { return this.y; } /** * Returns the width (in data space) of the data rectangle into which the * image will be drawn. * * @return The width. */ public double getWidth() { return this.w; } /** * Returns the height (in data space) of the data rectangle into which the * image will be drawn. * * @return The height. */ public double getHeight() { return this.h; } /** * Returns the flag that controls whether or not the annotation should * contribute to the autoRange for the axis it is plotted against. * * @return A boolean. * * @since 1.0.13 */ @Override public boolean getIncludeInDataBounds() { return this.includeInDataBounds; } /** * Returns the x-range for the annotation. * * @return The range. * * @since 1.0.13 */ @Override public Range getXRange() { return new Range(this.x, this.x + this.w); } /** * Returns the y-range for the annotation. * * @return The range. * * @since 1.0.13 */ @Override public Range getYRange() { return new Range(this.y, this.y + this.h); } /** * Draws the annotation. This method is called by the drawing code in the * {@link XYPlot} class, you don't normally need to call this method * directly. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the data area. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param rendererIndex the renderer index. * @param info if supplied, this info object will be populated with * entity information. */ @Override public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis, int rendererIndex, PlotRenderingInfo info) { PlotOrientation orientation = plot.getOrientation();
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This 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.1 of the License, or * (at your option) any later version. * * This 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------------- * XYDataImageAnnotation.java * -------------------------- * (C) Copyright 2008-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Peter Kolb (patch 2809117); * * Changes: * -------- * 17-Sep-2008 : Version 1, based on XYImageAnnotation (DG); * 10-Mar-2009 : Implemented XYAnnotationBoundsInfo (DG); * */ package org.jfree.chart.annotations; /** * An annotation that allows an image to be placed within a rectangle specified * in data coordinates on an {@link XYPlot}. Note that this annotation * is not currently serializable, so don't use it if you plan on serializing * your chart(s). * * @since 1.0.11 */ public class XYDataImageAnnotation extends AbstractXYAnnotation implements Cloneable, PublicCloneable, XYAnnotationBoundsInfo { /** The image. */ private transient Image image; /** * The x-coordinate (in data space). */ private double x; /** * The y-coordinate (in data space). */ private double y; /** * The image display area width in data coordinates. */ private double w; /** * The image display area height in data coordinates. */ private double h; /** * A flag indicating whether or not the annotation should contribute to * the data range for a plot/renderer. * * @since 1.0.13 */ private boolean includeInDataBounds; /** * Creates a new annotation to be displayed within the specified rectangle. * * @param image the image (<code>null</code> not permitted). * @param x the x-coordinate (in data space). * @param y the y-coordinate (in data space). * @param w the image display area width. * @param h the image display area height. */ public XYDataImageAnnotation(Image image, double x, double y, double w, double h) { this(image, x, y, w, h, false); } /** * Creates a new annotation to be displayed within the specified rectangle. * * @param image the image (<code>null</code> not permitted). * @param x the x-coordinate (in data space). * @param y the y-coordinate (in data space). * @param w the image display area width. * @param h the image display area height. * @param includeInDataBounds a flag that controls whether or not the * annotation is included in the data bounds for the axis autoRange. * * @since 1.0.13 */ public XYDataImageAnnotation(Image image, double x, double y, double w, double h, boolean includeInDataBounds) { super(); ParamChecks.nullNotPermitted(image, "image"); this.image = image; this.x = x; this.y = y; this.w = w; this.h = h; this.includeInDataBounds = includeInDataBounds; } /** * Returns the image for the annotation. * * @return The image. */ public Image getImage() { return this.image; } /** * Returns the x-coordinate (in data space) for the annotation. * * @return The x-coordinate. */ public double getX() { return this.x; } /** * Returns the y-coordinate (in data space) for the annotation. * * @return The y-coordinate. */ public double getY() { return this.y; } /** * Returns the width (in data space) of the data rectangle into which the * image will be drawn. * * @return The width. */ public double getWidth() { return this.w; } /** * Returns the height (in data space) of the data rectangle into which the * image will be drawn. * * @return The height. */ public double getHeight() { return this.h; } /** * Returns the flag that controls whether or not the annotation should * contribute to the autoRange for the axis it is plotted against. * * @return A boolean. * * @since 1.0.13 */ @Override public boolean getIncludeInDataBounds() { return this.includeInDataBounds; } /** * Returns the x-range for the annotation. * * @return The range. * * @since 1.0.13 */ @Override public Range getXRange() { return new Range(this.x, this.x + this.w); } /** * Returns the y-range for the annotation. * * @return The range. * * @since 1.0.13 */ @Override public Range getYRange() { return new Range(this.y, this.y + this.h); } /** * Draws the annotation. This method is called by the drawing code in the * {@link XYPlot} class, you don't normally need to call this method * directly. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the data area. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param rendererIndex the renderer index. * @param info if supplied, this info object will be populated with * entity information. */ @Override public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis, int rendererIndex, PlotRenderingInfo info) { PlotOrientation orientation = plot.getOrientation();
AxisLocation xAxisLocation = plot.getDomainAxisLocation();
0
2023-12-24 12:36:47+00:00
128k