file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
ListBoxView.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/view/ListBoxView.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.view;
import java.util.ArrayList;
import java.util.List;
import seventh.client.gfx.Camera;
import seventh.client.gfx.Canvas;
import seventh.client.gfx.Renderable;
import seventh.math.Rectangle;
import seventh.shared.TimeStep;
import seventh.ui.Button;
import seventh.ui.ListBox;
import seventh.ui.events.ListHeaderChangedEvent;
import seventh.ui.events.ListItemChangedEvent;
import seventh.ui.events.OnListHeaderChangedListener;
import seventh.ui.events.OnListItemChangedListener;
/**
* Renders the {@link ListBox}
*
* @author Tony
*
*/
public class ListBoxView<T extends Renderable> implements Renderable {
/**
* Elements
*/
private ListBox box;
private List<ButtonView> buttonViews;
private List<ButtonView> hderButtonViews;
/**
*
*/
public ListBoxView(ListBox box) {
this.buttonViews = new ArrayList<ButtonView>();
this.hderButtonViews = new ArrayList<>();
this.box = box;
this.box.addListItemChangedListener(new OnListItemChangedListener() {
@Override
public void onListItemChanged(ListItemChangedEvent event) {
Button button = event.getButton();
if(event.isAdded()) {
buttonViews.add(new ButtonView(button));
}
else {
int removeIndex = -1;
int i = 0;
for(ButtonView view : buttonViews) {
if(view.getButton() == button) {
removeIndex = i;
break;
}
i++;
}
if(removeIndex > -1) {
buttonViews.remove(removeIndex);
}
}
}
});
this.box.addListHeaderChangedListener(new OnListHeaderChangedListener() {
@Override
public void onListHeaderChanged(ListHeaderChangedEvent event) {
Button button = event.getButton();
if(event.isAdded()) {
hderButtonViews.add(new ButtonView(button));
}
else {
hderButtonViews.remove(button);
}
}
});
for(Button btn : box.getItems()) {
buttonViews.add(new ButtonView(btn));
}
for(Button btn : box.getColumnHeaders()) {
hderButtonViews.add(new ButtonView(btn));
}
}
/**
* @return the box
*/
public ListBox getBox() {
return box;
}
/* (non-Javadoc)
* @see org.myriad.render.Renderable#render(org.myriad.render.Renderer, org.myriad.render.Camera, org.myriad.core.TimeUnit)
*/
@Override
public void render(Canvas renderer, Camera camera, float alpha) {
Rectangle bounds = box.getBounds();
int headerHeight = box.getHeaderHeight();
int headerMargin = box.getHeaderMargin();
renderer.fillRect(bounds.x - 1, bounds.y, bounds.width, bounds.height + 1, box.getBackgroundColor());
renderer.drawRect(bounds.x - 1, bounds.y, bounds.width + 1, bounds.height + 1, 0xff000000);
bounds = box.getScreenBounds();
int y = headerHeight + headerMargin;
renderer.fillRect(bounds.x - 1, bounds.y, bounds.width + 1, headerHeight + 1, 0xff282c0c);
renderer.drawRect(bounds.x - 1, bounds.y, bounds.width + 1, headerHeight + 1, 0xff000000);
int hsize = hderButtonViews.size();
for(int i = 0; i < hsize; i++) {
ButtonView view = hderButtonViews.get(i);
view.render(renderer, camera, alpha);
}
int size = buttonViews.size();
for(int i = box.getIndex(); i < size; i++) {
ButtonView view = this.buttonViews.get(i);
Button btn = view.getButton();
btn.getBounds().y = y;
Rectangle rect = btn.getScreenBounds();
if(bounds.contains(rect)) {
btn.setDisabled(false);
if(btn.isHovering()) {
renderer.fillRect(rect.x - 10, rect.y - 5, bounds.width - 10, rect.height, 0x0fffffff);
}
view.render(renderer, camera, alpha);
}
else {
btn.setDisabled(true);
}
y += rect.height + box.getMargin();
}
//Rectangle rect = box.getBounds();
//renderer.fillRect(rect.x, rect.y + box.getHeaderHeight(), rect.width, rect.height - box.getHeaderHeight(), 0x3fff0000);
}
/* (non-Javadoc)
* @see org.myriad.render.Renderable#update(org.myriad.core.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
int size = buttonViews.size();
for(int i = 0; i < size; i++) {
this.buttonViews.get(i).update(timeStep);
}
size = hderButtonViews.size();
for(int i = 0; i < size; i++) {
this.hderButtonViews.get(i).update(timeStep);
}
}
}
| 6,915 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
CheckboxView.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/view/CheckboxView.java | /*
* see license.txt
*/
package seventh.ui.view;
import seventh.client.gfx.Camera;
import seventh.client.gfx.Canvas;
import seventh.client.gfx.Renderable;
import seventh.math.Rectangle;
import seventh.shared.TimeStep;
import seventh.ui.Checkbox;
import seventh.ui.Label;
/**
* @author Tony
*
*/
public class CheckboxView implements Renderable {
private Checkbox checkbox;
private LabelView labelView;
/**
*
*/
public CheckboxView(Checkbox checkbox) {
this.checkbox = checkbox;
this.labelView = new LabelView(checkbox.getLabel());
}
/* (non-Javadoc)
* @see seventh.client.gfx.Renderable#update(seventh.shared.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
}
/* (non-Javadoc)
* @see seventh.client.gfx.Renderable#render(seventh.client.gfx.Canvas, seventh.client.gfx.Camera, long)
*/
@Override
public void render(Canvas canvas, Camera camera, float alpha) {
Rectangle bounds = checkbox.getBounds();
Label label = checkbox.getLabel();
canvas.fillRect(bounds.x, bounds.y, bounds.width, bounds.height, 0xff383e18);
canvas.setFont(label.getFont(), (int)label.getTextSize());
if(checkbox.isChecked()) {
canvas.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 0xff000000);
canvas.drawString("x", bounds.x + 5, bounds.y + canvas.getHeight("W") - 5, 0xffffffff);
}
else {
canvas.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 0xff000000);
}
if(checkbox.isHovering()) {
canvas.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, checkbox.getForegroundColor());
}
labelView.render(canvas, camera, alpha);
}
}
| 1,864 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SliderView.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/view/SliderView.java | /*
* see license.txt
*/
package seventh.ui.view;
import seventh.client.gfx.Camera;
import seventh.client.gfx.Canvas;
import seventh.client.gfx.Colors;
import seventh.client.gfx.Renderable;
import seventh.math.Rectangle;
import seventh.shared.TimeStep;
import seventh.ui.Button;
import seventh.ui.Slider;
/**
* @author Tony
*
*/
public class SliderView implements Renderable {
private ButtonView handleView;
private Slider slider;
/**
*
*/
public SliderView(Slider slider) {
this.slider = slider;
this.handleView = new ButtonView(slider.getHandle());
}
/* (non-Javadoc)
* @see seventh.client.gfx.Renderable#update(seventh.shared.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
this.handleView.update(timeStep);
}
/* (non-Javadoc)
* @see seventh.client.gfx.Renderable#render(seventh.client.gfx.Canvas, seventh.client.gfx.Camera, long)
*/
@Override
public void render(Canvas canvas, Camera camera, float alpha) {
Rectangle bounds = slider.getBounds();
canvas.fillRect(bounds.x, bounds.y, bounds.width, bounds.height, 0xff383e18);
canvas.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 0xff000000);
// if(slider.isHovering()) {
// canvas.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, Colors.setAlpha(slider.getForegroundColor(), 100));
// }
this.handleView.render(canvas, camera, alpha);
Button handle = slider.getHandle();
bounds = handle.getScreenBounds();
canvas.fillRect(bounds.x, bounds.y, bounds.width, bounds.height, 0xff383e18);
int a = 100;
if(handle.isHovering()) {
a = 240;
}
canvas.fillRect(bounds.x, bounds.y, bounds.width, bounds.height, Colors.setAlpha(slider.getForegroundColor(), a));
canvas.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 0xff000000);
}
}
| 2,013 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ImageButtonView.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/view/ImageButtonView.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.view;
import seventh.client.gfx.Camera;
import seventh.client.gfx.Canvas;
import seventh.math.Rectangle;
import seventh.math.Vector2f;
import seventh.ui.Button;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
/**
* Image for a button, with optional Text overlay.
*
* @author Tony
*
*/
public class ImageButtonView extends ButtonView {
/**
* Button Image
*/
private TextureRegion buttonImage;
/**
* Button down image
*/
private TextureRegion buttonDownImage;
/**
* Button up image
*/
private TextureRegion buttonUpImage;
/**
* @param button
* @param buttonImage
*/
public ImageButtonView(Button button, TextureRegion buttonImage) {
this(button, buttonImage, buttonImage, buttonImage);
}
/**
* @param button
* @param buttonImage
* @param buttonDownImg
*/
public ImageButtonView(Button button, TextureRegion buttonImage, TextureRegion buttonUpImg, TextureRegion buttonDownImg) {
super(button);
this.buttonImage = buttonImage;
this.buttonUpImage = buttonUpImg;
this.buttonDownImage = buttonDownImg;
button.setEnableGradiant(false);
button.setBackgroundAlpha(0);
}
/**
* @return the buttonImage
*/
public TextureRegion getButtonImage() {
return buttonImage;
}
/**
* @param buttonImage the buttonImage to set
*/
public void setButtonImage(TextureRegion buttonImage) {
this.buttonImage = buttonImage;
}
/**
* @return the buttonDownImage
*/
public TextureRegion getButtonDownImage() {
return buttonDownImage;
}
/**
* @param buttonDownImage the buttonDownImage to set
*/
public void setButtonDownImage(TextureRegion buttonDownImage) {
this.buttonDownImage = buttonDownImage;
}
/**
* @return the buttonUpImage
*/
public TextureRegion getButtonUpImage() {
return buttonUpImage;
}
/**
* @param buttonUpImage the buttonUpImage to set
*/
public void setButtonUpImage(TextureRegion buttonUpImage) {
this.buttonUpImage = buttonUpImage;
}
/* (non-Javadoc)
* @see com.fived.ricochet.ui.view.ButtonView#render(org.myriad.render.Renderer, org.myriad.render.Camera, org.myriad.core.TimeUnit)
*/
@Override
public void render(Canvas renderer, Camera camera, float alpha) {
Button button = getButton();
if ( button.isVisible() ) {
Vector2f position = button.getScreenPosition();
boolean makeBig = false;
Rectangle bounds = button.getBounds();
if(button.hasBorder()) {
if(button.isHovering()) {
renderer.drawRect((int)position.x, (int)position.y, bounds.width, bounds.height, 0xffffffff);
}
else {
renderer.drawRect((int)position.x, (int)position.y, bounds.width, bounds.height, 0xff000000);
}
}
else {
makeBig = button.isHovering();
}
int color = button.getForegroundColor();
if ( this.buttonImage != null ) {
if(this.buttonImage instanceof Sprite) {
Sprite sprite = (Sprite)this.buttonImage;
sprite.setPosition(position.x, position.y);
renderer.drawRawSprite( sprite );
}
else {
// center the button icon
int uw = this.buttonUpImage.getRegionWidth();
int uh = this.buttonUpImage.getRegionHeight();
int w = (uw / 2) - (this.buttonImage.getRegionWidth() / 2) + 1;
int h = (uh / 2) - (this.buttonImage.getRegionHeight() / 2) + 1;// + 5;
if ( button.isPressed() ) {
if ( this.buttonDownImage != null) {
renderer.drawScaledImage(this.buttonDownImage, (int)position.x, (int)position.y, uw, uh, color);
}
renderer.drawScaledImage(this.buttonImage, (int)position.x + w, (int)position.y + h + 5,
this.buttonImage.getRegionWidth(), this.buttonImage.getRegionHeight(), color);
}
else {
//renderer.drawImage(this.buttonUpImage, (int)position.x, (int)position.y, color);
renderer.drawScaledImage(this.buttonImage, (int)position.x + w, (int)position.y + h,
this.buttonImage.getRegionWidth(), this.buttonImage.getRegionHeight(), color);
}
}
}
else {
Rectangle r = button.getBounds();
if ( button.isPressed() ) {
if ( this.buttonDownImage != null) {
renderer.drawScaledImage(this.buttonDownImage, (int)position.x, (int)position.y, r.width, r.height, color);
}
else {
renderer.drawScaledImage(this.buttonUpImage, (int)position.x, (int)position.y + 5, r.width, r.height, color);
}
}
else {
if(makeBig) {
renderer.drawScaledImage(this.buttonUpImage, (int)position.x, (int)position.y, r.width + 5, r.height + 5, color);
}
else {
renderer.drawScaledImage(this.buttonUpImage, (int)position.x, (int)position.y, r.width, r.height, color);
}
}
}
super.render(renderer, camera, alpha);
}
}
}
| 7,694 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
LabelView.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/view/LabelView.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.view;
import seventh.client.gfx.Camera;
import seventh.client.gfx.Canvas;
import seventh.client.gfx.RenderFont;
import seventh.client.gfx.Renderable;
import seventh.math.Rectangle;
import seventh.shared.TimeStep;
import seventh.ui.Label;
/**
* Renders text on a label.
*
* @author Tony
*
*/
public class LabelView implements Renderable {
/**
* The label
*/
private Label label;
/**
* @param label
*/
public LabelView(Label label) {
this.label = label;
}
protected void setColor(Canvas renderer, Label label) {
renderer.setColor(label.getForegroundColor(),label.getForegroundAlpha());
}
/* (non-Javadoc)
* @see org.myriad.render.Renderable#render(org.myriad.render.Renderer, org.myriad.render.Camera, org.myriad.core.TimeUnit)
*/
public void render(Canvas renderer, Camera camera, float alpha) {
String buttonTxt = this.label.getText();
if ( buttonTxt == null || buttonTxt.equals("") || !this.label.isVisible()) {
return;
}
// Widget parent = this.label.getParent();
// if( parent != null ) {
// renderer.setColor(parent.getForegroundColor(), parent.getForegroundAlpha());
// }
// else {
// renderer.setColor(this.label.getForegroundColor(),this.label.getForegroundAlpha());
//
// }
setColor(renderer, label);
Rectangle bounds = this.label.getScreenBounds();
if ( this.label.ignoreCR() ) {
renderer.setFont(label.getFont(), (int)label.getTextSize());
float width = RenderFont.getTextWidth(renderer, buttonTxt);
int height = renderer.getHeight("W");
int vertical = bounds.y + (bounds.height / 2);
switch(this.label.getVerticalTextAlignment()) {
case BOTTOM:
vertical = bounds.y + (bounds.height - 5);
break;
case TOP:
vertical = bounds.y + height;
break;
default:
vertical = bounds.y + (bounds.height / 2);
}
switch(this.label.getHorizontalTextAlignment()) {
case LEFT:
RenderFont.drawShadedString(renderer
// renderer.drawString(
, buttonTxt
, bounds.x + 5
, vertical, null, label.isShadowed(), label.isColorEncoding(), label.isMonospaced());
break;
case RIGHT:
RenderFont.drawShadedString(renderer
// renderer.drawString(
, buttonTxt
, bounds.x + bounds.width - width
, vertical, null, label.isShadowed(), label.isColorEncoding(), label.isMonospaced());
break;
default:
RenderFont.drawShadedString(renderer
// renderer.drawString(
, buttonTxt
, bounds.x + (bounds.width / 2) - (width / 2)
, vertical, null, label.isShadowed(), label.isColorEncoding(), label.isMonospaced());
break;
}
// font.setSize(textSize);
}
else {
renderWithCR(renderer, buttonTxt, bounds);
}
}
/**
* Renders with Carriage returns.
* @param renderer
* @param buttonTxt
* @param bounds
*/
private void renderWithCR(Canvas renderer, String buttonTxt, Rectangle bounds) {
// Font font = renderer.getDefaultFont();
//
// float textSize = font.getSize();
// font.setSize(this.label.getTextSize());
// int height = font.getHeight('W');
//
// String[] strs = buttonTxt.split("\n");
// int size = strs.length;
// for(int i = 0; i < size; i++ ) {
// String txt = strs[i].trim();
// if ( txt != null ) {
// int width = font.getWidth(txt);
// switch(this.label.getTextAlignment()) {
// case LEFT:
// renderer.drawString(buttonTxt
// , bounds.x
// , bounds.y + (bounds.height/2) + (height * i) );
// break;
// case RIGHT:
// renderer.drawString(buttonTxt
// , bounds.x + bounds.width - width
// , bounds.y + (bounds.height/2) + (height * i) );
// break;
// case CENTER:
// renderer.drawString(txt
// , bounds.x + (bounds.width/2) - (width/2)
// , bounds.y + (bounds.height/2) + (height * i));
// break;
// }
//
// }
// }
// font.setSize(textSize);
}
/* (non-Javadoc)
* @see org.myriad.render.Renderable#update(org.myriad.core.TimeStep)
*/
public void update(TimeStep timeStep) {
}
}
| 6,975 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
WidgetRenderer.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/view/WidgetRenderer.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.view;
import javax.swing.Renderer;
import seventh.client.gfx.Camera;
import seventh.ui.Button;
import seventh.ui.Dialog;
import seventh.ui.Widget;
/**
* Renderer of {@link Widget}s.
*
* @author Tony
*
*/
public interface WidgetRenderer {
/**
* Renders a {@link Button}.
*
* @param button
* @param renderer
* @param camera
* @param alpha
*/
public void renderButton(Button button, Renderer renderer, Camera camera, long alpha);
/**
* Renders a {@link Dialog}.
*
* @param dialog
* @param renderer
* @param camera
* @param alpha
*/
public void renderDialog(Dialog dialog, Renderer renderer, Camera camera, long alpha);
}
| 2,317 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ImagePanelView.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/view/ImagePanelView.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.view;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import seventh.client.gfx.Camera;
import seventh.client.gfx.Canvas;
import seventh.math.Rectangle;
import seventh.ui.ImagePanel;
/**
* Renders a group of elements
*
* @author Tony
*
*/
public class ImagePanelView extends PanelView {
private ImagePanel panel;
/**
*
*/
public ImagePanelView(ImagePanel panel) {
this.panel = panel;
}
/* (non-Javadoc)
* @see seventh.ui.view.PanelView#render(seventh.client.gfx.Canvas, seventh.client.gfx.Camera, float)
*/
@Override
public void render(Canvas renderer, Camera camera, float alpha) {
Rectangle bounds = panel.getScreenBounds();
renderer.fillRect(bounds.x, bounds.y, bounds.width, bounds.height, panel.getBackgroundColor());
renderer.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, panel.getForegroundColor());
TextureRegion tex = panel.getImage();
if(tex != null) {
renderer.drawScaledImage(tex, bounds.x, bounds.y, bounds.width, bounds.height, null);
}
super.render(renderer, camera, alpha);
}
}
| 2,768 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
PanelView.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/view/PanelView.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.view;
import java.util.ArrayList;
import java.util.List;
import seventh.client.gfx.Camera;
import seventh.client.gfx.Canvas;
import seventh.client.gfx.Renderable;
import seventh.math.Rectangle;
import seventh.shared.TimeStep;
import seventh.ui.Widget;
/**
* Renders a group of elements
*
* @author Tony
*
*/
public class PanelView implements Renderable {
/**
* Elements
*/
private List<Renderable> uiElements;
private Widget panel;
public PanelView() {
this(null);
}
/**
* @param panel
*/
public PanelView(Widget panel) {
this.panel = panel;
this.uiElements = new ArrayList<>();
}
public PanelView clear() {
this.uiElements.clear();
return this;
}
/**
* Adds an element
* @param element
*/
public PanelView addElement(Renderable element) {
this.uiElements.add(element);
return this;
}
/**
* @return the uiElements
*/
public List<Renderable> getUiElements() {
return uiElements;
}
/* (non-Javadoc)
* @see org.myriad.render.Renderable#render(org.myriad.render.Renderer, org.myriad.render.Camera, org.myriad.core.TimeUnit)
*/
@Override
public void render(Canvas renderer, Camera camera, float alpha) {
if(this.panel != null && this.panel.getBorderWidth() > 0) {
Rectangle bounds = this.panel.getBounds();
int x = bounds.x;
int y = bounds.y;
int w = bounds.width;
int h = bounds.height;
int color = this.panel.getBorderColor();
renderer.fillRect(x, y, w, h, this.panel.getBackgroundColor());
for(int i = 0; i < this.panel.getBorderWidth(); i++) {
renderer.drawRect(x+i, y+i, w-i*2, h-i*2, color);
}
}
int size = this.uiElements.size();
for(int i = 0; i < size; i++) {
this.uiElements.get(i).render(renderer, camera, alpha);
}
}
/* (non-Javadoc)
* @see org.myriad.render.Renderable#update(org.myriad.core.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
int size = this.uiElements.size();
for(int i = 0; i < size; i++) {
this.uiElements.get(i).update(timeStep);
}
}
}
| 4,021 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ProgressBarView.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/view/ProgressBarView.java | /**
*
*/
package seventh.ui.view;
import seventh.client.gfx.Camera;
import seventh.client.gfx.Canvas;
import seventh.client.gfx.Renderable;
import seventh.math.Rectangle;
import seventh.shared.TimeStep;
import seventh.ui.ProgressBar;
/**
* The View of a {@link ProgressBar}
*
* @author Tony
*
*/
public class ProgressBarView implements Renderable {
private ProgressBar progressBar;
/**
*
*/
public ProgressBarView(ProgressBar progressBar) {
this.progressBar = progressBar;
}
/* (non-Javadoc)
* @see seventh.client.gfx.Renderable#update(seventh.shared.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
}
/* (non-Javadoc)
* @see seventh.client.gfx.Renderable#render(seventh.client.gfx.Canvas, seventh.client.gfx.Camera, long)
*/
@Override
public void render(Canvas canvas, Camera camera, float alpha) {
if(progressBar.isVisible()) {
Rectangle bounds = progressBar.getBounds();
canvas.fillRect(bounds.x, bounds.y, bounds.width, bounds.height, progressBar.getBackgroundColor());
int percentOfWidth = (int)(progressBar.getPercentCompleted() * bounds.width);
canvas.fillRect(bounds.x, bounds.y, percentOfWidth, bounds.height, progressBar.getForegroundColor());
canvas.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 0xff000000);
int x = bounds.x;
int y = bounds.y;
// add a shadow effect
canvas.drawLine( x, y + 1, x + bounds.width, y + 1, 0x8f000000 );
canvas.drawLine( x, y + 2, x + bounds.width, y + 2, 0x5f000000 );
canvas.drawLine( x, y + 3, x + bounds.width, y + 3, 0x2f000000 );
canvas.drawLine( x, y + 4, x + bounds.width, y + 4, 0x0f000000 );
canvas.drawLine( x, y + 5, x + bounds.width, y + 5, 0x0b000000 );
canvas.drawLine( x, y + 6, x + bounds.width, y + 6, 0x0a000000 );
y = y + 15;
canvas.drawLine( x, y - 6, x + bounds.width, y - 6, 0x0a000000 );
canvas.drawLine( x, y - 5, x + bounds.width, y - 5, 0x0b000000 );
canvas.drawLine( x, y - 4, x + bounds.width, y - 4, 0x0f000000 );
canvas.drawLine( x, y - 3, x + bounds.width, y - 3, 0x2f000000 );
canvas.drawLine( x, y - 2, x + bounds.width, y - 2, 0x5f000000 );
canvas.drawLine( x, y - 1, x + bounds.width, y - 1, 0x8f000000 );
}
}
}
| 2,578 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
TextBoxActionEvent.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/TextBoxActionEvent.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.events;
import seventh.shared.Event;
import seventh.ui.TextBox;
/**
* A {@link TextBox} had enter pressed
*
* @author Tony
*
*/
public class TextBoxActionEvent extends Event {
/**
* TextBox
*/
private TextBox textBox;
/**
* @param source
* @param textBox
*/
public TextBoxActionEvent(Object source, TextBox textBox) {
super(source);
this.textBox = textBox;
}
/**
* @return the TextBox
*/
public TextBox getTextBox() {
return textBox;
}
/**
* @param TextBox the TextBox to set
*/
public void setTextBox(TextBox textBox) {
this.textBox = textBox;
}
}
| 2,282 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
OnListItemChangedListener.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/OnListItemChangedListener.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.events;
import seventh.shared.EventListener;
import seventh.shared.EventMethod;
/**
* Listens for list item changes
*
* @author Tony
*
*/
public interface OnListItemChangedListener extends EventListener {
/**
* A list item was modified
* @param event
*/
@EventMethod
public void onListItemChanged(ListItemChangedEvent event);
}
| 1,955 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
OnScrollBarListener.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/OnScrollBarListener.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.events;
import seventh.shared.EventListener;
import seventh.shared.EventMethod;
/**
* Listens for scrollbar movements
*
* @author Tony
*
*/
public interface OnScrollBarListener extends EventListener {
/**
* A scrollbar was actioned
*
* @param event
*/
@EventMethod
public void onScrollBar(ScrollBarEvent event);
}
| 1,947 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ListHeaderChangedEvent.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/ListHeaderChangedEvent.java | /*
* see license.txt
*/
package seventh.ui.events;
import seventh.shared.Event;
import seventh.ui.Button;
/**
* @author Tony
*
*/
public class ListHeaderChangedEvent extends Event {
private Button button;
private boolean added;
/**
* @param source
*/
public ListHeaderChangedEvent(Object source, Button button, boolean added) {
super(source);
this.button = button;
this.added = added;
}
/**
* @return the button
*/
public Button getButton() {
return button;
}
/**
* @return the added
*/
public boolean isAdded() {
return added;
}
}
| 671 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SliderMovedEvent.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/SliderMovedEvent.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.events;
import seventh.shared.Event;
import seventh.ui.Slider;
/**
* A {@link Slider} was moved
*
* @author Tony
*
*/
public class SliderMovedEvent extends Event {
/**
* Slider
*/
private Slider slider;
/**
* @param source
* @param slider
*/
public SliderMovedEvent(Object source, Slider slider) {
super(source);
this.slider = slider;
}
/**
* @return the slider
*/
public Slider getSlider() {
return slider;
}
}
| 2,105 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ListItemChangedEvent.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/ListItemChangedEvent.java | /*
* see license.txt
*/
package seventh.ui.events;
import seventh.shared.Event;
import seventh.ui.Button;
/**
* @author Tony
*
*/
public class ListItemChangedEvent extends Event {
private Button button;
private boolean added;
/**
* @param source
*/
public ListItemChangedEvent(Object source, Button button, boolean added) {
super(source);
this.button = button;
this.added = added;
}
/**
* @return the button
*/
public Button getButton() {
return button;
}
/**
* @return the added
*/
public boolean isAdded() {
return added;
}
}
| 667 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
TextBoxActionListener.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/TextBoxActionListener.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.events;
import seventh.shared.EventListener;
import seventh.shared.EventMethod;
/**
* Listens for enter keys
*
* @author Tony
*
*/
public interface TextBoxActionListener extends EventListener {
/**
* The enter key was pressed
* @param event
*/
@EventMethod
public void onEnterPressed(TextBoxActionEvent event);
}
| 1,940 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
OnListHeaderChangedListener.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/OnListHeaderChangedListener.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.events;
import seventh.shared.EventListener;
import seventh.shared.EventMethod;
/**
* Listens for list header changes
*
* @author Tony
*
*/
public interface OnListHeaderChangedListener extends EventListener {
/**
* A list header was modified
* @param event
*/
@EventMethod
public void onListHeaderChanged(ListHeaderChangedEvent event);
}
| 1,965 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
OnSliderMovedListener.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/OnSliderMovedListener.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.events;
import seventh.shared.EventListener;
import seventh.shared.EventMethod;
import seventh.ui.Slider;
/**
* Listens for {@link Slider} movement
*
* @author Tony
*
*/
public interface OnSliderMovedListener extends EventListener {
/**
* The slider was moved
* @param event
*/
@EventMethod
public void onSliderMoved(SliderMovedEvent event);
}
| 1,971 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
OnHoverListener.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/OnHoverListener.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.events;
import seventh.shared.EventListener;
import seventh.shared.EventMethod;
/**
* Listens for hover overs
*
* @author Tony
*
*/
public interface OnHoverListener extends EventListener {
/**
* A widget is being hovered over
*
* @param event
*/
@EventMethod
public void onHover(HoverEvent event);
}
| 1,933 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
OnCheckboxClickedListener.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/OnCheckboxClickedListener.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.events;
import seventh.shared.EventListener;
import seventh.shared.EventMethod;
import seventh.ui.Checkbox;
/**
* Listens toggling of checkbox events
*
* @author Tony
*
*/
public interface OnCheckboxClickedListener extends EventListener {
/**
* A {@link Checkbox} was toggled
* @param event
*/
@EventMethod
public void onCheckboxClicked(CheckboxEvent event);
}
| 1,988 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
CheckboxEvent.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/CheckboxEvent.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.events;
import seventh.shared.Event;
import seventh.ui.Checkbox;
/**
* A {@link Checkbox} selection was altered
*
* @author Tony
*
*/
public class CheckboxEvent extends Event {
/**
* Checkbox
*/
private Checkbox checkbox;
/**
* @param source
* @param checkbox
*/
public CheckboxEvent(Object source, Checkbox checkbox) {
super(source);
this.checkbox = checkbox;
}
/**
* @return the checkbox
*/
public Checkbox getCheckbox() {
return checkbox;
}
}
| 2,151 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
HoverEvent.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/HoverEvent.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.events;
import seventh.shared.Event;
import seventh.ui.Widget;
/**
* A {@link Widget} is being hovered over
*
* @author Tony
*
*/
public class HoverEvent extends Event {
/**
* Widget
*/
private Widget widget;
private boolean isHovering;
/**
* @param source
* @param button
*/
public HoverEvent(Object source, Widget widget, boolean isHovering) {
super(source);
this.widget = widget;
this.isHovering = isHovering;
}
/**
* @return the isHovering
*/
public boolean isHovering() {
return isHovering;
}
/**
* @return the widget
*/
public Widget getWidget() {
return widget;
}
/**
* @param widget the widget to set
*/
public void setWidget(Widget widget) {
this.widget = widget;
}
}
| 2,465 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
OnButtonClickedListener.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/OnButtonClickedListener.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.events;
import seventh.shared.EventListener;
import seventh.shared.EventMethod;
/**
* Listens for button clicks
*
* @author Tony
*
*/
public interface OnButtonClickedListener extends EventListener {
/**
* A button was clicked.
* @param event
*/
@EventMethod
public void onButtonClicked(ButtonEvent event);
}
| 1,935 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ScrollBarEvent.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/ScrollBarEvent.java | /*
* see license.txt
*/
package seventh.ui.events;
import seventh.shared.Event;
/**
* @author Tony
*
*/
public class ScrollBarEvent extends Event {
private int movementDelta;
/**
* @param source
*/
public ScrollBarEvent(Object source, int movementDelta) {
super(source);
this.movementDelta = movementDelta;
}
/**
* @return the movementDelta
*/
public int getMovementDelta() {
return movementDelta;
}
}
| 493 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ButtonEvent.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ui/events/ButtonEvent.java | /*
**************************************************************************************
*Myriad Engine *
*Copyright (C) 2006-2007, 5d Studios (www.5d-Studios.com) *
* *
*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 *
**************************************************************************************
*/
package seventh.ui.events;
import seventh.shared.Event;
import seventh.ui.Button;
/**
* A {@link Button} was clicked.
*
* @author Tony
*
*/
public class ButtonEvent extends Event {
/**
* Button
*/
private Button button;
/**
* @param source
* @param button
*/
public ButtonEvent(Object source, Button button) {
super(source);
this.button = button;
}
/**
* @return the button
*/
public Button getButton() {
return button;
}
/**
* @param button the button to set
*/
public void setButton(Button button) {
this.button = button;
}
}
| 2,242 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
MasterServerClient.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/MasterServerClient.java | /*
* see license.txt
*/
package seventh.shared;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import leola.vm.Leola;
import leola.vm.types.LeoNull;
import leola.vm.types.LeoObject;
import seventh.game.GameInfo;
import seventh.game.PlayerInfo;
import seventh.game.PlayerInfos;
import seventh.game.net.NetGameTypeInfo;
import seventh.game.net.NetTeam;
import seventh.server.GameServer;
import seventh.server.ServerContext;
import seventh.server.ServerSeventhConfig;
/**
* API to the Master Server. The master server is responsible for keeping track of game servers
* so that client know which are available.
*
* @author Tony
*
*/
public class MasterServerClient {
/**
* Encoding
*/
private static final String ENCODING = "UTF8";
private String masterServerUrl;
private String proxyUser;
private String proxyPw;
private Proxy proxy;
/**
*
*/
public MasterServerClient(MasterServerConfig config) {
this.masterServerUrl = config.getUrl();
this.proxy = config.getProxy();
if(this.proxy != null && !this.proxy.equals(Proxy.NO_PROXY)) {
this.proxyUser = config.getProxyUser();
this.proxyPw = config.getProxyPassword();
}
}
/**
* Retrieves the Internet server listings.
*
* @param gameType
* @throws Exception
*/
public LeoObject getServerListings(String gameType) throws Exception {
LeoObject result = LeoNull.LEONULL;
String requestUrl = (gameType!=null) ? this.masterServerUrl + "?game_type=" + gameType : this.masterServerUrl;
URL url = new URL(requestUrl);
HttpURLConnection conn = connect(url);
try {
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Seventh Client");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
conn.setRequestProperty("seventh_version", GameServer.VERSION);
int responseCode = conn.getResponseCode();
if(responseCode != 200) {
Cons.println("Error response from master server: " + responseCode);
}
else {
BufferedReader istream = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
StringBuilder sb=new StringBuilder("return ");
while( (line=istream.readLine()) != null) {
sb.append(line.replace(":", "->")).append("\n");
}
sb.append(" ;");
Leola runtime = Scripting.newSandboxedRuntime();
result = runtime.eval(sb.toString());
}
}
finally {
if(conn != null) {
conn.disconnect();
}
}
return (result);
}
/**
* Sends a heart beat to the master server
* @param gameServer the game server
* @throws Exception
*/
public void sendHeartbeat(ServerContext serverContext) throws Exception {
URL url = new URL(this.masterServerUrl);
HttpURLConnection conn = connect(url);
try {
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", "Seventh Server");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
conn.setRequestProperty("seventh_version", GameServer.VERSION);
String urlParameters = populateGameServerPingParameters(serverContext);
// Send post request
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
//Cons.println("Sending heartbeat request to: " + url);
int responseCode = conn.getResponseCode();
if(responseCode != 200) {
Cons.println("Error response from master server: " + responseCode);
}
}
finally {
if(conn!=null) {
conn.disconnect();
}
}
}
/**
* Connects to the master server
* @param url
* @return
* @throws Exception
*/
private HttpURLConnection connect(URL url) throws Exception {
if(this.proxy != null && !this.proxy.equals(Proxy.NO_PROXY)) {
HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
if(this.proxyUser!=null) {
String uname_pwd = proxyUser + ":" + proxyPw;
String authString = "Basic " + Base64.encodeBytes(uname_pwd.getBytes());
connection.setRequestProperty("Proxy-Authorization", authString);
}
return connection;
}
return (HttpURLConnection) url.openConnection();
}
private String populateGameServerPingParameters(ServerContext serverContext) throws Exception {
ServerSeventhConfig config = serverContext.getConfig();
StringBuilder sb = new StringBuilder();
sb.append("server_name=").append(URLEncoder.encode(config.getServerName(), ENCODING));
sb.append("&game_type=").append(URLEncoder.encode(config.getGameType().name(), ENCODING));
if(serverContext.hasGameSession()) {
GameInfo game = serverContext.getGameSession().getGame();
sb.append("&map=").append(URLEncoder.encode(serverContext.getMapCycle().getCurrentMap().getFileName(), ENCODING));
sb.append("&time=").append(game.getGameType().getRemainingTime());
sb.append("&axis_score=").append(game.getGameType().getAxisNetTeamStats().score);
sb.append("&allied_score=").append(game.getGameType().getAlliedNetTeamStats().score);
NetGameTypeInfo info = game.getGameType().getNetGameTypeInfo();
PlayerInfos players = game.getPlayerInfos();
sb.append("&axis=");
NetTeam axis = info.axisTeam;
appendTeam(players, axis, sb);
sb.append("&allied=");
NetTeam allied = info.alliedTeam;
appendTeam(players, allied, sb);
}
sb.append("&port=").append(serverContext.getPort());
return sb.toString();
}
private void appendTeam(PlayerInfos players, NetTeam team, StringBuilder sb) throws Exception {
if(team!=null) {
for(int i = 0; i < team.playerIds.length; i++) {
PlayerInfo player = players.getPlayerInfo(team.playerIds[i]);
if(player!=null) {
sb.append("\"");
sb.append(URLEncoder.encode(player.getName().replace(",", "."), ENCODING));
sb.append("\"");
sb.append(URLEncoder.encode(",", ENCODING));
}
}
}
}
}
| 7,421 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
PrintStreamLogger.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/PrintStreamLogger.java | /*
* see license.txt
*/
package seventh.shared;
import java.io.PrintStream;
/**
* Uses a {@link PrintStream} as an implementation
*
* @author Tony
*
*/
public class PrintStreamLogger implements Logger {
private PrintStream stream;
/**
* @param stream
*/
public PrintStreamLogger(PrintStream stream) {
this.stream = stream;
}
/* (non-Javadoc)
* @see seventh.shared.Logger#print(java.lang.Object)
*/
@Override
public void print(Object msg) {
stream.print(msg);
}
/* (non-Javadoc)
* @see seventh.shared.Logger#println(java.lang.Object)
*/
@Override
public void println(Object msg) {
stream.println(msg);
}
/* (non-Javadoc)
* @see seventh.shared.Logger#printf(java.lang.Object, java.lang.Object[])
*/
@Override
public void printf(Object msg, Object... args) {
stream.printf(msg.toString(), args);
}
}
| 967 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Event.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Event.java | /*
Leola Programming Language
Author: Tony Sparks
See license.txt
*/
package seventh.shared;
/**
* A consumable event of interest.
*
* @author Tony
*
*/
public abstract class Event {
/**
* The object which this event has
* spawned from.
*/
private Object source;
/**
* If this event has been consumed
*/
private boolean consumed;
/**
* Time the event was created.
*/
// private long creationTime;
/**
* Uses the default method id.
* @param source
*/
public Event(Object source) {
this.source = source;
// /* This time is in java time */
// this.creationTime = System.currentTimeMillis();
}
/**
* Consume this event
*/
public void consume() {
this.consumed=true;
}
/**
* @return the consumed
*/
public boolean isConsumed() {
return consumed;
}
/**
* Unconsume this event.
*/
public void unconsume() {
this.consumed = false;
}
/**
* @return the creationTime
*/
// public long getCreationTime() {
// return creationTime;
// }
/**
* Get the source
* @return the source of which this event was created.
*/
public Object getSource() {
return this.source;
}
/**
* @param source the source to set
*/
public void setSource(Object source) {
this.source = source;
}
}
| 1,536 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
LANServerRegistration.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/LANServerRegistration.java | /*
* see license.txt
*/
package seventh.shared;
import java.net.DatagramPacket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import seventh.server.ServerContext;
import seventh.shared.BroadcastListener.OnMessageReceivedListener;
/**
* Registers with the LAN
*
* @author Tony
*
*/
public class LANServerRegistration implements Runnable {
private BroadcastListener listener;
private ExecutorService service;
/**
*
*/
public LANServerRegistration(final ServerContext serverContext) {
final LANServerConfig config = serverContext.getConfig().getLANServerConfig();
this.listener = new BroadcastListener(config.getMtu(), config.getBroadcastAddress(), config.getPort());
this.listener.addOnMessageReceivedListener(new OnMessageReceivedListener() {
@Override
public void onMessage(DatagramPacket packet) {
String msg = new String(packet.getData(), packet.getOffset(), packet.getLength()).trim();
if(msg.equalsIgnoreCase("ping")) {
try(Broadcaster caster = new Broadcaster(config.getMtu(), config.getBroadcastAddress(), config.getPort())) {
ServerInfo info = new ServerInfo(serverContext);
caster.broadcastMessage(info.toString());
}
catch(Exception e) {
Cons.println("*** ERROR: Unable to broadcast response: " + e);
}
}
}
});
}
/**
* Start the background process in which this listens for any LAN broadcast pings
*
*/
public void start() {
if(this.service == null) {
this.service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, "lan-server-listener");
thread.setDaemon(true);
return thread;
}
});
this.service.execute(this);
}
}
/**
* Shuts down the broadcaster
*/
public void shutdown() {
try {
this.listener.close();
}
catch(Exception e) {
Cons.println("*** ERROR: Closing out lan-server-listener: " + e);
}
finally {
if(this.service != null) {
this.service.shutdownNow();
this.service = null;
}
}
}
@Override
public void run() {
try {
listener.start();
}
catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
catch(Exception e) {
Cons.println("*** ERROR: An exception occurred during LAN BroadcastListner: " + e);
}
}
}
| 3,149 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
EventMethod.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/EventMethod.java | /*
Leola Programming Language
Author: Tony Sparks
See license.txt
*/
package seventh.shared;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Defines an event method. An {@link EventMethod} must have the
* method signature of:
*
* <pre>
* public void myEventName( Event event )
* </pre>
* Where myEventName can be anything and event class must inherit from {@link Event}.
*
* @author Tony
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface EventMethod {
}
| 691 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
FpsCounter.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/FpsCounter.java | /*
* leola-live
* see license.txt
*/
package seventh.shared;
/**
* Counts the Frames Per Seconds and average frames per second based on a sample size.
*
* @author Tony
*
*/
public class FpsCounter {
/**
* Sample size
*/
private final int sampleSize;
/**
* Average fps
*/
private long avgFPS = 0;
/**
* FPS tally
*/
private long fpsTally = 0;
/**
* The current sample
*/
private int currentSample = 0;
/**
* Frames per second
*/
private long fps;
/**
* @param sampleSize
*/
public FpsCounter(int sampleSize) {
this.sampleSize = sampleSize;
}
/**
*/
public FpsCounter() {
this(100);
}
/**
* Update the counter.
*
* @param dt
*/
public void update(long dt) {
if ( dt == 0 ) {
return;
}
this.fps = 1000 / dt;
this.currentSample++;
if ( this.currentSample > this.sampleSize ) {
this.avgFPS = (this.fpsTally / this.sampleSize);
this.fpsTally = 0;
this.currentSample=0;
}
else {
this.fpsTally += this.fps;
}
}
/**
* @return the sampleSize
*/
public int getSampleSize() {
return this.sampleSize;
}
/**
* @return the avgFPS
*/
public long getAvgFPS() {
return this.avgFPS;
}
/**
* @return the fps
*/
public long getFps() {
return this.fps;
}
}
| 1,651 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
BroadcastListener.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/BroadcastListener.java | /*
* see license.txt
*/
package seventh.shared;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A very simple multicast server socket, that listens for messages broadcast to a particular group address and port.
*
* @author Tony
*
*/
public class BroadcastListener implements AutoCloseable {
/**
* Message was received from a broadcast message
*
* @author Tony
*
*/
public static interface OnMessageReceivedListener {
public void onMessage(DatagramPacket packet);
}
private MulticastSocket socket;
private InetAddress groupAddress;
private int port;
private AtomicBoolean active;
private final int MTU;
private List<OnMessageReceivedListener> listeners;
/**
* @param mtu
* @param groupAddress
* @param port
* @throws Exception
*/
public BroadcastListener(int mtu, String groupAddress, int port) {
this.MTU = mtu;
this.port = port;
this.listeners = new ArrayList<BroadcastListener.OnMessageReceivedListener>();
this.active = new AtomicBoolean();
try {
this.groupAddress = InetAddress.getByName(groupAddress);
}
catch(Exception e) {
throw new RuntimeException(e);
}
}
/**
* Adds a {@link OnMessageReceivedListener}
*
* @param l
*/
public void addOnMessageReceivedListener(OnMessageReceivedListener l) {
this.listeners.add(l);
}
/**
* Starts listening on a port for broadcast messages.
*
* @param groupAddress
* @param port
*/
public void start() throws Exception {
if(!this.active.get()) {
this.active.set(true);
socket = null;
try {
socket = new MulticastSocket(this.port);
socket.joinGroup(this.groupAddress);
byte[] buffer = new byte[this.MTU];
while(this.active.get()) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
for(OnMessageReceivedListener l : this.listeners) {
l.onMessage(packet);
}
}
}
catch(SocketException e) {
if(!e.getMessage().equals("socket closed")) {
throw e;
}
}
finally {
if(socket != null && !socket.isClosed()) {
socket.leaveGroup(this.groupAddress);
socket.close();
}
}
}
}
@Override
public void close() throws Exception {
this.active.set(false);
if(socket != null && !socket.isClosed()) {
socket.leaveGroup(this.groupAddress);
socket.close();
}
}
}
| 3,278 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SeventhConfig.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/SeventhConfig.java | /*
* see license.txt
*/
package seventh.shared;
import java.io.IOException;
import harenet.NetConfig;
/**
* The Seventh configuration
*
* @author Tony
*
*/
public class SeventhConfig {
protected Config config;
private MasterServerConfig masterServerConfig;
/**
* @param configurationPath the path to the configuration file
* @param configurationRootNode the configuration root entry
* @throws Exception
*/
public SeventhConfig(String configurationPath, String configurationRootNode) throws Exception {
this(new Config(configurationPath, configurationRootNode));
}
/**
* @param config
*/
public SeventhConfig(Config config) {
this.config = config;
this.masterServerConfig = new MasterServerConfig(config);
}
/**
* @return the config
*/
public Config getConfig() {
return config;
}
/**
* @return the masterServerConfig
*/
public MasterServerConfig getMasterServerConfig() {
return masterServerConfig;
}
/**
* @return the {@link LANServerConfig}
*/
public LANServerConfig getLANServerConfig() {
return new LANServerConfig(this.config);
}
/**
* @return the networking configuration
*/
public NetConfig getNetConfig() {
return this.config.getNetConfig();
}
/**
* Saves off the configuration file
*
* @throws IOException
*/
public void save() throws IOException {
this.config.save();
}
/**
* Saves off the configuration file
*
* @param filename
* @throws IOException
*/
public void save(String filename) throws IOException {
this.config.save(filename);
}
}
| 1,800 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Config.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Config.java | /*
* The Seventh
* see license.txt
*/
package seventh.shared;
import java.io.DataOutput;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Map;
import harenet.NetConfig;
import leola.vm.Leola;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoNull;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoString;
import seventh.network.messages.BufferIO.SeventhNetMessageFactory;
/**
* Configuration file
*
* @author Tony
*
*/
public class Config {
private String configName;
private String fileName;
private LeoMap config;
private NetConfig netConfig;
public Config(String configName, String rootConfig) throws Exception {
this(configName, rootConfig, new Leola());
}
/**
*
*/
public Config(String configName, String rootConfig, Leola runtime) throws Exception {
this.fileName = configName;
this.configName = rootConfig;
this.config = loadConfig(runtime, configName, rootConfig);
this.netConfig = new NetConfig(new SeventhNetMessageFactory());
LeoObject net = get("net");
if(net instanceof LeoMap) {
LeoMap netMap = net.as();
LeoObject timeout = netMap.getByString("timeout");
if(timeout != null && timeout.isNumber()) {
this.netConfig.setTimeout(timeout.asInt());
}
LeoObject reliableTimeout = netMap.getByString("reliable_timeout");
if(reliableTimeout != null && reliableTimeout.isNumber()) {
this.netConfig.setReliableMessageTimeout(reliableTimeout.asInt());
}
LeoObject heartbeat = netMap.getByString("heartbeat_rate");
if(heartbeat != null && heartbeat.isNumber()) {
this.netConfig.setHeartbeatTime(heartbeat.asInt());
}
LeoObject pingRate = netMap.getByString("ping_rate");
if(pingRate != null && pingRate.isNumber()) {
this.netConfig.setPingRate(pingRate.asInt());
}
LeoObject poll_rate = netMap.getByString("poll_rate");
if(poll_rate != null && poll_rate.isNumber()) {
this.netConfig.setPollRate(poll_rate.asInt());
}
LeoObject mtu = netMap.getByString("mtu");
if(mtu != null && mtu.isNumber()) {
this.netConfig.setMtu(mtu.asInt());
}
LeoObject max_connections = netMap.getByString("max_connections");
if(max_connections != null && max_connections.isNumber()) {
this.netConfig.setMaxConnections(max_connections.asInt());
}
LeoObject loggingEnabled = netMap.getByString("enable_log");
if(loggingEnabled != null) {
this.netConfig.enableLog(LeoObject.isTrue(loggingEnabled));
}
LeoObject compressionThreshold = netMap.getByString("compression_threshold");
if(compressionThreshold != null && compressionThreshold.isNumber()) {
this.netConfig.setCompressionThreshold(compressionThreshold.asInt());
}
LeoObject useDirectBuffers = netMap.getByString("use_direct_buffers");
if(useDirectBuffers != null) {
this.netConfig.setUseDirectBuffers(LeoObject.isTrue(useDirectBuffers));
}
}
}
private LeoMap loadConfig(Leola runtime, String file, String rootConfig) throws Exception {
runtime.eval(new File(file));
LeoMap configMap = runtime.get(rootConfig).as();
return configMap;
}
/**
* @return the fileName
*/
public String getFileName() {
return fileName;
}
/**
* @return the network configuration
*/
public NetConfig getNetConfig() {
return this.netConfig;
}
/**
* @param keys
* @return the object defined by the set of keys
*/
public LeoObject get(String ... keys) {
int len = keys.length;
LeoObject obj = config;
for(int i = 0; i < len; i++) {
LeoObject nextObj = obj.getObject(LeoString.valueOf(keys[i]));
if(!LeoObject.isNull(nextObj)) {
obj = nextObj;
}
else return null;
}
return obj;
}
public float getFloat(String ...keys ) {
return getFloat(0, keys);
}
public float getFloat(float defaultValue, String ...keys) {
LeoObject obj = get(keys);
if(obj != null && obj.isNumber()) {
return obj.asFloat();
}
return defaultValue;
}
public int getInt(String ...keys ) {
LeoObject obj = get(keys);
return obj.asInt();
}
public int getInt(int defaultValue, String ...keys ) {
LeoObject obj = get(keys);
if(obj != null && obj.isNumber() ) {
return obj.asInt();
}
return defaultValue;
}
public String getStr(String defaultValue, String ...keys ) {
LeoObject obj = get(keys);
if(obj != null) {
return obj.toString();
}
return defaultValue;
}
public String getString(String ...keys ) {
LeoObject obj = get(keys);
return obj.toString();
}
public boolean getBool(boolean defaultValue, String ...keys) {
LeoObject obj = get(keys);
if(obj==null) {
return defaultValue;
}
return LeoObject.isTrue(obj);
}
public boolean getBool(String ...keys ) {
LeoObject obj = get(keys);
return LeoObject.isTrue(obj);
}
/**
* @param value
* @param keys
* @return sets a value defined by the set of keys
*/
public boolean set(Object value, String ... keys) {
int len = keys.length - 1;
LeoObject obj = config;
for(int i = 0; i < len; i++) {
LeoObject nextObj = obj.getObject(keys[i]);
if(!LeoObject.isNull(nextObj)) {
obj = nextObj;
}
else {
LeoObject newEntry = new LeoMap();
obj.$sindex(LeoString.valueOf(keys[i]), newEntry);
obj = newEntry;
}
}
obj.$sindex(LeoString.valueOf(keys[keys.length-1]), LeoObject.valueOf(value));
//obj.setObject(keys[keys.length-1], Leola.toLeoObject(value));
return true;
}
public LeoObject setIfNull(String key, Object value) {
LeoObject v = config.getByString(key);
if(v == null || v == LeoNull.LEONULL) {
v = Leola.toLeoObject(value);
config.putByString(key, v);
}
return v;
}
public boolean has(String key) {
LeoObject v = config.getByString(key);
return v != null && v != LeoNull.LEONULL;
}
/**
* Saves over this file
* @throws IOException
*/
public void save() throws IOException {
save(this.fileName);
}
/**
* Saves the configuration file
*
* @param filename
* @throws IOException
*/
public void save(String filename) throws IOException {
File file = new File(filename);
RandomAccessFile output = new RandomAccessFile(file, "rw");
try {
output.setLength(0);
output.writeBytes(this.configName + " = ");
writeOutObject(output, config, 0);
}
finally {
output.close();
}
}
private void writeTabs(DataOutput output, int numTabs) throws IOException {
for(int i = 0; i < numTabs; i++) {
output.writeBytes("\t");
}
}
private void writeLn(DataOutput output, String txt, int numTabs) throws IOException {
writeTabs(output, numTabs);
output.writeBytes(txt);
}
private void writeOutObject(DataOutput output, LeoObject obj, int numTabs) throws IOException {
switch(obj.getType()) {
case ARRAY:
LeoArray array = obj.as();
writeLn(output, "[\n", 0);
for(LeoObject e : array) {
writeOutObject(output, e, numTabs + 1);
writeLn(output, ",\n", 0);
}
writeLn(output, "]", numTabs);
break;
case BOOLEAN:
writeLn(output, obj.isTrue() ? "true" : "false", 0);
break;
case INTEGER:
case LONG:
case REAL:
writeLn(output, obj.getValue().toString(), 0);
break;
case NULL:
writeLn(output, "null", 0);
break;
case STRING:
writeLn(output, "\"" + obj.toString() + "\"", 0);
break;
case MAP:
writeLn(output, "{\n", 0);
LeoMap map = obj.as();
for(Map.Entry<LeoObject, LeoObject> entry : map.entrySet()) {
writeLn(output, entry.getKey().toString() + " -> ", numTabs+1);
writeOutObject(output, entry.getValue(), numTabs+1);
writeLn(output, ",\n", 0);
}
writeLn(output, "}", numTabs);
break;
default: {
throw new IllegalArgumentException(obj + " not supported in configuration!");
}
}
}
public static void main(String [] args) throws Exception {
Config config = new Config("./assets/client_config.leola", "client_config");
config.save("./test.leola");
}
}
| 10,288 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AssetLoader.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/AssetLoader.java | /*
* see license.txt
*/
package seventh.shared;
import java.io.IOException;
/**
* Loads an Asset
*
* @author Tony
*/
public interface AssetLoader<T> {
/**
* Loads an Asset
*
* @param filename
* @return the Asset
* @throws IOException
*/
public T loadAsset(String filename) throws IOException;
}
| 345 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ConsoleFrame.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/ConsoleFrame.java | /*
* see license.txt
*/
package seventh.shared;
import java.awt.AWTKeyStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.List;
import java.util.Stack;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
/**
* @author Tony
*
*/
public class ConsoleFrame extends JFrame implements Logger {
/**
* SUID
*/
private static final long serialVersionUID = 4136313198405978268L;
private static final int NUMBER_OF_COLUMNS = 50;
private static final int NUMBER_OF_ROWS = 40;
static {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {}
}
private String welcomeBanner;
private Console console;
private JTextArea textArea;
private JTextField textField;
private Stack<String> cmdHistory;
private int cmdHistoryIndex;
/**
* @param title
* @param welcomeBanner
* @param console
*/
public ConsoleFrame(String title, String welcomeBanner, Console console) {
this.welcomeBanner = welcomeBanner;
this.console = console;
this.console.addLogger(this);
this.console.addCommand(new Command("clear"){
/* (non-Javadoc)
* @see shared.Command#execute(shared.Console, java.lang.String[])
*/
@Override
public void execute(Console console, String... args) {
textArea.setText("");
}
});
this.console.addCommand(new Command("echo") {
/* (non-Javadoc)
* @see shared.Command#execute(shared.Console, java.lang.String[])
*/
@Override
public void execute(Console console, String... args) {
for(int i = 0; i < args.length; i++) {
if(i>0) console.print(" ");
console.print(args[i]);
}
console.print("\n");
}
});
this.cmdHistory = new Stack<String>();
this.cmdHistory.add("");
this.cmdHistoryIndex = 0;
setLocation(200, 300);
setTitle(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel(new BorderLayout());
// contentPane.setBorder(BorderLayout.);
this.setJMenuBar(setupMenu());
this.textArea = setupTextArea(contentPane);
this.textField = setupTextField(contentPane, textArea);
setContentPane(contentPane);
pack();
setVisible(true);
// enable TAB completion
setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, new HashSet<AWTKeyStroke>());
}
/*
* (non-Javadoc)
* @see shared.Logger#println(java.lang.Object)
*/
public void println(Object message) {
this.textArea.append(message.toString() + "\n");
this.textArea.select(this.textArea.getText().length(), this.textArea.getText().length());
}
/*
* (non-Javadoc)
* @see shared.Logger#printf(java.lang.Object, java.lang.Object[])
*/
public void printf(Object message, Object ... args) {
println(String.format(message.toString(), args));
}
/* (non-Javadoc)
* @see shared.Logger#print(java.lang.Object)
*/
public void print(Object msg) {
this.textArea.append(msg.toString());
this.textArea.select(this.textArea.getText().length(), this.textArea.getText().length());
}
private JMenuBar setupMenu() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem exit = new JMenuItem("Exit", KeyEvent.VK_E);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
file.add(exit);
menubar.add(file);
JMenu help = new JMenu("Help");
JMenuItem about = new JMenuItem("About", KeyEvent.VK_A);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
help.add(about);
menubar.add(help);
return menubar;
}
/**
* @return the text area
*/
private JTextArea setupTextArea(JPanel contentPane) {
JPanel textAreaPanel = new JPanel(new BorderLayout());
JTextArea text = new JTextArea(NUMBER_OF_ROWS, NUMBER_OF_COLUMNS);
text.setText(this.welcomeBanner);
text.setFont(new Font("Courier New", Font.PLAIN, 12));
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setEditable(false);
text.setBackground(Color.BLUE);
text.setForeground(Color.YELLOW);
JScrollPane scrollPane = new JScrollPane(text);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
textAreaPanel.add(scrollPane, BorderLayout.CENTER);
contentPane.add(textAreaPanel);
return text;
}
/**
* @param contentPane
* @param textArea
* @return the input field area
*/
private JTextField setupTextField(JPanel contentPane, final JTextArea textArea) {
JPanel textInput = new JPanel(new BorderLayout());
final JTextField textField = new JTextField(NUMBER_OF_COLUMNS);
textField.requestFocus();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
executeCommand();
}
});
textField.getKeymap().addActionForKeyStroke(KeyStroke.getKeyStroke("TAB"), new AbstractAction() {
/**
*/
private static final long serialVersionUID = -5702217390878105195L;
public void actionPerformed(ActionEvent e) {
List<String> cmdNames = console.find(textField.getText());
if(cmdNames.isEmpty()) {
// do nothing
}
else if(cmdNames.size() == 1) {
textField.setText(cmdNames.get(0) + " ");
}
else {
console.println("");
for(String cmd : cmdNames) {
console.println(cmd);
}
console.println("");
}
}
});
textField.getKeymap().addActionForKeyStroke(KeyStroke.getKeyStroke("UP"), new AbstractAction() {
/**
*/
private static final long serialVersionUID = -5702217390878105195L;
public void actionPerformed(ActionEvent e) {
cmdHistoryIndex++;
if(cmdHistoryIndex>=cmdHistory.size()) {
cmdHistoryIndex=0;
}
if(!cmdHistory.isEmpty()) {
textField.setText(cmdHistory.get(cmdHistoryIndex));
}
}
});
textField.getKeymap().addActionForKeyStroke(KeyStroke.getKeyStroke("DOWN"), new AbstractAction() {
/**
*/
private static final long serialVersionUID = -5702217390878105195L;
public void actionPerformed(ActionEvent e) {
cmdHistoryIndex--;
if(cmdHistoryIndex<0) {
cmdHistoryIndex=cmdHistory.size()-1;;
}
if(!cmdHistory.isEmpty()) {
textField.setText(cmdHistory.get(cmdHistoryIndex));
}
}
});
textInput.add(textField, BorderLayout.CENTER);
final JButton sendBtn = new JButton("Send");
sendBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
executeCommand();
}
});
textInput.add(sendBtn, BorderLayout.EAST);
contentPane.add(textInput, BorderLayout.PAGE_END);
return textField;
}
protected void executeCommand() {
String text = textField.getText();
//textArea.append(text + "\n");
textField.setText("");
console.execute(text);
this.cmdHistory.add(text);
this.cmdHistoryIndex = 0;
}
}
| 9,509 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
PassThruAssetWatcher.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/PassThruAssetWatcher.java | /*
* see license.txt
*/
package seventh.shared;
import java.io.IOException;
/**
* Simple pass-through implementation of {@link AssetWatcher}. This takes
* very minimal resources as its just a small wrapper around the actual Asset.
*
* @author Tony
*
*/
public class PassThruAssetWatcher implements AssetWatcher {
static class WatchedAssetImpl<T> implements WatchedAsset<T> {
private final T asset;
/**
* @param asset
*/
public WatchedAssetImpl(T asset) {
this.asset = asset;
}
@Override
public T getAsset() {
return asset;
}
@Override
public void release() {
}
@Override
public void onAssetChanged() throws IOException {
}
}
/**
*/
public PassThruAssetWatcher() {
}
@Override
public <T> WatchedAsset<T> loadAsset(String filename, AssetLoader<T> loader) throws IOException {
return new WatchedAssetImpl<T>(loader.loadAsset(filename));
}
@Override
public void removeWatchedAsset(String filename) {
}
@Override
public void clearWatched() {
}
@Override
public void startWatching() {
}
@Override
public void stopWatching() {
}
}
| 1,343 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
TimeStep.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/TimeStep.java | /*
* leola-live
* see license.txt
*/
package seventh.shared;
/**
* @author Tony
*
*/
public class TimeStep {
private long gameClock;
private long deltaTime;
/**
* @return the gameClock
*/
public long getGameClock() {
return gameClock;
}
/**
* @param gameClock the gameClock to set
*/
public void setGameClock(long gameClock) {
this.gameClock = gameClock;
}
/**
* @return the deltaTime
*/
public long getDeltaTime() {
return deltaTime;
}
/**
* @return returns the time step as a fraction
*/
public double asFraction() {
return deltaTime / 1000.0d;
}
/**
* @param deltaTime the deltaTime to set
*/
public void setDeltaTime(long deltaTime) {
this.deltaTime = deltaTime;
}
}
| 856 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Broadcaster.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Broadcaster.java | /*
* see license.txt
*/
package seventh.shared;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* A simple tool to broadcast a message to a group address using multicast.
*
* @author Tony
*
*/
public class Broadcaster implements AutoCloseable {
public static void main(String[] args) throws Exception {
try(Broadcaster caster = new Broadcaster(1500, "224.0.0.44", 4888)) {
caster.broadcastMessage("Hello Cruel World");
caster.broadcastMessage("Bye Cruel World");
}
}
private DatagramSocket socket;
private InetAddress groupAddress;
private final int port;
private final int MTU;
/**
* @param mtu
* @param groupAddress
* @param port
* @throws Exception
*/
public Broadcaster(int mtu, String groupAddress, int port) throws Exception {
this.MTU = mtu;
this.port = port;
this.groupAddress = InetAddress.getByName(groupAddress);
this.socket = new DatagramSocket();
}
/**
* Broadcast a message to the group address
*
* @param message
* @throws Exception
*/
public void broadcastMessage(String message) throws Exception {
byte[] msg = message.getBytes();
if(msg.length > this.MTU) {
throw new IllegalArgumentException("The supplied message exceeds the MTU: '" + this.MTU + "' < '" + msg.length +"'");
}
DatagramPacket packet = new DatagramPacket(msg, msg.length, this.groupAddress, this.port);
this.socket.send(packet);
}
@Override
public void close() throws Exception {
if(this.socket != null) {
this.socket.close();
}
}
}
| 1,821 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
EventListener.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/EventListener.java | /*
Leola Programming Language
Author: Tony Sparks
See license.txt
*/
package seventh.shared;
/**
* Listens for a specific type of event.
* @author Tony
*
*/
public interface EventListener {
}
| 210 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Timer.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Timer.java | /*
* see license.txt
*/
package seventh.shared;
/**
* @author Tony
*
*/
public class Timer implements Updatable {
private long currentTime;
private long endTime;
private boolean update, loop, isTime, onFirstTime;
/**
* @param loop
* @param endTime
*/
public Timer(boolean loop, long endTime) {
this.loop = loop;
this.endTime = endTime;
this.onFirstTime = false;
reset();
}
public void set(Timer timer) {
this.currentTime = timer.currentTime;
this.endTime = timer.endTime;
this.update = timer.update;
this.loop = timer.loop;
this.isTime = timer.isTime;
this.onFirstTime = timer.onFirstTime;
}
/**
* @param endTime the endTime to set
*/
public Timer setEndTime(long endTime) {
this.endTime = endTime;
return this;
}
/**
* @return the endTime
*/
public long getEndTime() {
return endTime;
}
/**
* @return the remaining time
*/
public long getRemainingTime() {
return this.endTime - this.currentTime;
}
/**
* @return true if this timer is currently being updated
*/
public boolean isUpdating() {
return update;
}
/**
* @param loop the loop to set
*/
public void setLoop(boolean loop) {
this.loop = loop;
}
/**
* @return true if set to loop
*/
public boolean isLooping() {
return loop;
}
public Timer reset() {
this.currentTime = 0;
this.update = true;
this.isTime = false;
return this;
}
public Timer stop() {
this.currentTime = 0;
this.isTime = false;
this.update = false;
return this;
}
public Timer start() {
this.update = true;
return this;
}
public Timer pause() {
this.update = false;
return this;
}
public boolean isExpired() {
return isTime && !isLooping();
}
/**
* Move the remaining time to 0
*/
public Timer expire() {
this.currentTime = this.endTime;
return this;
}
/**
* @return the isTime
*/
public boolean isTime() {
return isTime;
}
/**
* @return the onFirstTime
*/
public boolean isOnFirstTime() {
return onFirstTime;
}
/**
* You can override this method to get invoked when
* the timer has been reached
*/
public void onFinish(Timer timer) {
}
/**
* Updates the timer
* @param timeStep
*/
public void update(TimeStep timeStep) {
this.onFirstTime = false;
if (this.update) {
this.currentTime += timeStep.getDeltaTime();
if (this.currentTime >= this.endTime) {
if(this.isLooping()) {
reset();
}
else {
this.update = false;
}
this.isTime = true;
this.onFirstTime = true;
onFinish(this);
}
else {
this.isTime = false;
}
}
}
}
| 3,367 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ExecCommand.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/ExecCommand.java | /*
* see license.txt
*/
package seventh.shared;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* Executes a batch script
*
* @author Tony
*
*/
public class ExecCommand extends Command {
/**
* @param name
*/
public ExecCommand() {
super("exec");
}
/* (non-Javadoc)
* @see palisma.shared.Command#execute(palisma.shared.Console, java.lang.String[])
*/
@Override
public void execute(Console console, String... args) {
String filePath = mergeArgsDelim(" ", args);
File file = new File(filePath);
if(!file.exists()) {
console.println("The file '" + filePath + "' does not exist.");
}
else {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(file, "r");
String line = null;
while( (line=raf.readLine()) != null) {
if(!line.trim().startsWith("#")) {
console.execute(line);
}
}
} catch (IOException e) {
console.println("*** Error parsing the file: " + e);
}
finally {
if(raf!=null) {
try {
raf.close();
} catch (IOException ignore) {
}
}
}
}
}
}
| 1,452 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
State.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/State.java | /*
* see license.txt
*/
package seventh.shared;
/**
* @author Tony
*
*/
public interface State {
public void enter();
public void update(TimeStep timeStep);
public void exit();
}
| 199 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SeventhConstants.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/SeventhConstants.java | /*
* see license.txt
*/
package seventh.shared;
/**
* Shared constants between the server and client
*
* @author Tony
*
*/
public interface SeventhConstants {
/**
* Default port
*/
public static final int DEFAULT_PORT = 9844;
public static final int MAX_PRIMARY_WEAPONS = 2;
public static final int MAX_TIMERS = 32;
public static final int MAX_ENTITIES = 256;
public static final int MAX_PLAYERS = 24;
public static final int MAX_PERSISTANT_ENTITIES = 64;
public static final int MAX_SOUNDS = 32;
public static final int INVALID_PLAYER_ID = MAX_PLAYERS;
public static final int SPAWN_INVINCEABLILITY_TIME = 2_000;
public static final int PLAYER_HEARING_RADIUS = 1400;
public static final int PLAYER_WIDTH = 24;//16;
public static final int PLAYER_HEIGHT = 24;
public static final int PLAYER_SPEED = 140;
public static final int PLAYER_MIN_SPEED = 40;
public static final int RUN_DELAY_TIME = 300;
public static final int SPRINT_DELAY_TIME = 200;
public static final float WALK_SPEED_FACTOR = 0.584f;
public static final float SPRINT_SPEED_FACTOR = 1.60f; // 1.95f
public static final int ENTERING_VEHICLE_TIME = 1000;
public static final int EXITING_VEHICLE_TIME = 700;
public static final int RECOVERY_TIME = 2000;
public static final byte MAX_STAMINA = 100;
public static final float STAMINA_DECAY_RATE = 2; // 4
public static final float STAMINA_RECOVER_RATE = 1.5f;
public static final int FLAG_WIDTH = 20;
public static final int FLAG_HEIGHT = 20;
}
| 1,706 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ImageMerger.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/ImageMerger.java | /*
* see license.txt
*/
package seventh.shared;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.util.Comparator;
import javax.imageio.ImageIO;
import seventh.client.gfx.ImageUtil;
/**
* @author Tony
*
*/
public class ImageMerger {
/**
*
*/
public ImageMerger() {
// TODO Auto-generated constructor stub
}
static class Settings {
int overwriteX = 11;
int overwriteY = 0;
int overwriteWidth = 85;
int overwriteHeight = 109;
boolean scaleRow1 = true;
float scaleFactor = 0.1f;
int rows = 2;
int cols = 6;
}
static class DeathCSettings extends Settings {
public DeathCSettings() {
overwriteX = 11;
overwriteY = 0;
overwriteWidth = 85;
overwriteHeight = 109;
scaleRow1 = true;
scaleFactor = 0.1f;
rows = 2;
cols = 6;
}
}
static class DeathDSettings extends Settings {
public DeathDSettings() {
overwriteX = 0;
overwriteY = 38;
overwriteWidth = 102;
overwriteHeight = 131;
scaleRow1 = true;
scaleFactor = 0.1f;
rows = 2;
cols = 5;
}
}
static Settings activeSettings = new DeathDSettings();
/**
* @param args
*/
public static void main(String[] args) throws Exception {
String imageDir = "C:\\UnityProjects\\UnitTest\\Assets\\screencaptures";
//"C:\\Users\\Tony\\Desktop\\SpriteSheetPacker\\Test\\allied_sprint";
File imageFiles = new File(imageDir);
File[] files = imageFiles.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
//return pathname.getName().startsWith("legs");
return pathname.getName().endsWith(".png");
}
});
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return (int) (o1.lastModified() - o2.lastModified());
}
});
final int overwriteX = activeSettings.overwriteX;
final int overwriteY = activeSettings.overwriteY;
final int overwriteWidth = activeSettings.overwriteWidth;
final int overwriteHeight = activeSettings.overwriteHeight;
boolean scaleRow1 = activeSettings.scaleRow1;
float scaleFactor = activeSettings.scaleFactor;
int scaleX = (int)(overwriteWidth * scaleFactor);
int scaleY = (int)(overwriteHeight * scaleFactor);
int scaleWidth = overwriteWidth - (int)(overwriteWidth * scaleFactor);
int scaleHeight = overwriteHeight - (int)(overwriteHeight * scaleFactor);
int rows = activeSettings.rows;
int cols = activeSettings.cols;
BufferedImage[] images = new BufferedImage[rows * cols];
int j = 0;
for(File f: files) {
images[j] = ImageIO.read(f).getSubimage(overwriteX, overwriteY, overwriteWidth, overwriteHeight);
j++;
}
int width = overwriteWidth * cols;
width = nextPowerOf2(width);
int height = overwriteHeight * rows;
height = nextPowerOf2(height);
BufferedImage spritesheet = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g = (Graphics2D) spritesheet.getGraphics();
int x = 0;
int y = 0;
for(int i = 0; i < images.length; i++) {
if (x >= cols * overwriteWidth) {
x = 0;
y += overwriteHeight;////images[i].getHeight();
}
if(i < cols && scaleRow1) {
images[i] = ImageUtil.resizeImage(images[i], scaleWidth, scaleHeight);
x += scaleX;
y += scaleY;
System.out.println(x + "," + y);
g.drawImage(images[i], x, y, null);
x -= scaleX;
y -= scaleY;
}
else {
System.out.println(x + "," + y);
g.drawImage(images[i], x, y, null);
}
x += overwriteWidth;//images[i].getWidth();
}
// spritesheet = ImageUtil.applyMask(spritesheet, new Color(0xA10082));
ImageIO.write(spritesheet, "png", new File(imageFiles, "/output.png"));
}
private static int nextPowerOf2(int n) {
int k = 1;
while (k < n) {
k *= 2;
}
return k;
}
}
| 5,085 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Console.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Console.java | /*
* see license.txt
*/
package seventh.shared;
import java.util.List;
/**
* @author Tony
*
*/
public interface Console extends Logger {
/**
* @param command
*/
public void addCommand(Command command);
/**
* @param alias
* @param command
*/
public void addCommand(String alias, Command command);
/**
* @param commandName
*/
public void removeCommand(String commandName);
/**
* @param command
*/
public void removeCommand(Command command);
/**
* @param commandName
* @return the Command if found, otherwise null
*/
public Command getCommand(String commandName);
/**
* Attempts to find the best {@link Command} given the
* partial name
* @param partialName
* @return a list of command names with the partialName
*/
public List<String> find(String partialName);
/**
* @param logger
*/
public void setLogger(Logger logger);
/**
* @param logger
*/
public void addLogger(Logger logger);
/**
* Removes a {@link Logger}
* @param logger
*/
public void removeLogger(Logger logger);
/**
* Executes the commands on the game update to avoid
* concurrency issues.
*
* @param timeStep
*/
public void update(TimeStep timeStep);
/**
* @param cmd
* @param args
*/
public void execute(String cmd, String ... args);
/**
* Splits the input by " " and uses the first input as the command and the
* rest as args.
*
* @param commandLine
* @see Console#execute(String, String...)
*/
public void execute(String commandLine);
}
| 1,750 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Command.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Command.java | /*
* see license.txt
*/
package seventh.shared;
/**
* @author Tony
*
*/
public abstract class Command {
private String name;
/**
* @param name
*/
public Command(String name) {
this.name = name;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* Merges the arguments into one string
* @param args
* @return the coalesced string
*/
protected String mergeArgs(String ...args) {
return mergeArgsDelim("", args);
}
/**
* Merges the arguments into one string
* @param delimeter
* @param args
* @return the coalesced string
*/
protected String mergeArgsDelim(String delimeter, String ...args) {
return mergeArgsDelimAt(delimeter, 0, args);
}
/**
* Merges the arguments into one string
* @param delimeter
* @param args
* @return the coalesced string
*/
protected String mergeArgsDelimAt(String delimeter, int index, String ...args) {
StringBuilder sb = new StringBuilder();
for(int i = index; i < args.length; i++) {
if(i>index) sb.append(delimeter);
sb.append(args[i]);
}
return sb.toString();
}
/**
* @param console
* @param args
*/
public abstract void execute(Console console, String ... args);
}
| 1,425 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Cons.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Cons.java | /*
* see license.txt
*/
package seventh.shared;
/**
* A global instance of {@link Console} that I use so I don't have to pass Console around every where.
*
* NOTE: Switching the implementation around is NOT thread safe.
*
* @author Tony
*
*/
public class Cons {
private static Console impl = new DefaultConsole();
/**
* Sets the underlying implementation -- this should be
* set upon start up -- once.
*
* @param console
*/
public static void setImpl(Console console) {
impl = console;
}
/**
* @return the impl
*/
public static Console getImpl() {
return impl;
}
/**
* Adds a {@link Logger} to the global {@link Console}
* @param logger
*/
public static void addLogger(Logger logger) {
impl.addLogger(logger);
}
/* (non-Javadoc)
* @see palisma.shared.Console#print(java.lang.Object)
*/
public static void print(Object message) {
impl.print(message);
}
/* (non-Javadoc)
* @see palisma.shared.Console#println(java.lang.Object)
*/
public static void println(Object message) {
impl.println(message);
}
/* (non-Javadoc)
* @see palisma.shared.Console#printf(java.lang.Object, java.lang.Object[])
*/
public void printf(Object message, Object... args) {
impl.printf(message, args);
}
/* (non-Javadoc)
* @see palisma.shared.Console#execute(java.lang.String, java.lang.String[])
*/
public void execute(String command, String... args) {
impl.execute(command, args);
}
}
| 1,643 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
MasterServerConfig.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/MasterServerConfig.java | /*
* see license.txt
*/
package seventh.shared;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import leola.vm.types.LeoObject;
/**
* Master Server configuration settings
*
* @author Tony
*
*/
public class MasterServerConfig {
private Config config;
/**
* @param config
*/
public MasterServerConfig(Config config) {
this.config = config;
}
/**
* @return the master server URL
*/
public String getUrl() {
return this.config.getString("master_server", "url");
}
/**
* @param url
*/
public void setUrl(String url) {
this.config.set(url, "master_server", "url");
}
/**
* @return the frequency in minutes in which the server will ping the master server
*/
public int getPingRateMinutes() {
return this.config.getInt(1, "master_server", "ping_rate_minutes");
}
/**
* Sets the frequency in minutes in which the server will ping the master server
*
* @param minutes
*/
public void setPingRateMinutes(int minutes) {
this.config.set(minutes, "master_server", "ping_rate_minutes");
}
/**
* @return the proxy settings
*/
public Proxy getProxy() {
LeoObject proxy = this.config.get("master_server", "proxy_settings");
if(LeoObject.isTrue(proxy)) {
Proxy p = new Proxy(Type.HTTP, new InetSocketAddress(this.config.getString("master_server", "proxy_settings", "address"),
this.config.getInt(88, "master_server", "proxy_settings", "port")));
return (p);
}
return Proxy.NO_PROXY;
}
/**
* @return the proxy user name
*/
public String getProxyUser() {
return this.config.getString("master_server", "proxy_settings", "user");
}
/**
* Sets the proxy user name
*
* @param user
*/
public void setProxyUser(String user) {
this.config.set(user, "master_server", "proxy_settings", "user");
}
/**
* @return the proxy password
*/
public String getProxyPassword() {
return this.config.getString("master_server", "proxy_settings", "password");
}
/**
* Sets the proxy password
*
* @param password
*/
public void setProxyPassword(String password) {
this.config.set(password, "master_server", "proxy_settings", "password");
}
}
| 2,594 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Geom.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Geom.java | /*
* see license.txt
*/
package seventh.shared;
import static seventh.map.Tile.TILE_EAST_INVISIBLE;
import static seventh.map.Tile.TILE_INVISIBLE;
import static seventh.map.Tile.TILE_NORTH_INVISIBLE;
import static seventh.map.Tile.TILE_SOUTH_INVISIBLE;
import static seventh.map.Tile.TILE_VISIBLE;
import static seventh.map.Tile.TILE_WEST_INVISIBLE;
import java.util.List;
import seventh.map.Map;
import seventh.map.Tile;
import seventh.math.Vector2f;
/**
* @author Tony
*
*/
public class Geom {
/**
* The right vector, used for retrieving the angle
* or other vectors
*/
public static final Vector2f RIGHT_VECTOR = new Vector2f(1, 0);
/**
* Clears the visibility masks
*
* @param tiles
* @param map
*/
public static void clearMask(List<Tile> tiles, Map map) {
map.setMask(tiles, 0);
}
/**
* Utility function for calculating entity line of sight
*
* @param tiles
* @param pos
* @param facing
* @param radius
* @param map
*/
public static List<Tile> calculateLineOfSight(List<Tile> tiles, Vector2f pos, Vector2f facing, int radius, Map map, int heightMask, Vector2f cache) {
map.setMask(tiles, 0);
float fx = facing.x * radius + (facing.x * -64);
float fy = facing.y * radius + (facing.y * -64);
tiles = map.getTilesInCircle((int)(pos.x + fx), (int)(pos.y + fy), radius, tiles);
Vector2f tilePos = cache; // avoid allocation
int size = tiles.size();
for(int i = 0; i < size; i++) {
Tile tile = tiles.get(i);
tilePos.set(tile.getX() + (tile.getWidth()/2), tile.getY() + (tile.getHeight()/2));
//tilePos.set(tile.getX(), tile.getY());
if(map.lineCollides(tilePos, pos, heightMask) /*|| map.lineCollides(pos, tilePos)*/) {
tile.setMask(TILE_INVISIBLE);
}
else {
tile.setMask(TILE_VISIBLE);
}
}
return tiles;
}
public static List<Tile> addFadeEffect(Map map, List<Tile> tiles) {
int size = tiles.size();
for(int i = 0; i < size; i++) {
Tile tile = tiles.get(i);
if(tile != null) {
int width = tile.getWidth();
int height = tile.getHeight();
int x = tile.getX() + width/2;
int y = tile.getY() + height/2;
int mask = tile.getMask();
if(mask > TILE_INVISIBLE)
{
mask = tile.getMask();
Tile north = getTile(map, x, y - height, width, height);
if(north==null || north.getMask() == TILE_INVISIBLE) {
tile.setMask( mask | TILE_NORTH_INVISIBLE);
}
mask = tile.getMask();
// Tile ne = map.getTile(0, x + width, y + height);
// if(ne == null || ne.getMask() == TILE_INVISIBLE) {
// tile.setMask(mask | Tile.TILE_NE_CORNER_INVISIBLE);
// }
//
// mask = tile.getMask();
Tile east = getTile(map, x + width, y, width, height);
if(east==null || east.getMask() == TILE_INVISIBLE) {
tile.setMask( mask | TILE_EAST_INVISIBLE);
}
mask = tile.getMask();
// Tile se = map.getTile(0, x + width, y - height);
Tile south = getTile(map, x, y + height, width, height);
if(south==null || south.getMask() == TILE_INVISIBLE) {
tile.setMask( mask | TILE_SOUTH_INVISIBLE);
}
mask = tile.getMask();
// Tile sw = map.getTile(0, x - width, y - height);
Tile west = getTile(map, x - width, y, width, height);
if(west==null || west.getMask() == TILE_INVISIBLE) {
tile.setMask( mask | TILE_WEST_INVISIBLE);
}
// Tile nw = map.getTile(0, x - width, y + height);
}
}
}
return tiles;
}
private static Tile getTile(Map map, int worldX, int worldY, int tileWidth, int tileHeight) {
int x = (worldX) / tileWidth;
int y = (worldY) / tileHeight;
Tile tile = null;
if(!map.checkTileBounds(x, y)) {
tile = map.getTile(0, x, y);
}
return tile;
}
}
| 4,957 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Bits.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Bits.java | /*
* see license.txt
*/
package seventh.shared;
/**
* Simple bit operations
*
* @author Tony
*
*/
public class Bits {
/**
* Set the sign bit of a byte
* @param b
* @return the byte with its sign bit set
*/
public static byte setSignBit(byte b) {
return (byte) (b | (byte) (1 << 7));
//10000000
}
/**
* Checks to see if the sign bit is set on the byte
* @param b
* @return true if the sign bit is set
*/
public static boolean isSignBitSet(byte b) {
return ((b & (1 << 7)) > 0);
}
/**
* Get the byte value ignoring the sign bit
* @param b
* @return the byte value ignoring the sign bit
*/
public static byte getWithoutSignBit(byte b) {
return (byte) (b & ~(1 << 7));
}
public static short setSignedShort(short value, int numberOfBits) {
if(value < 0) {
return (short) (value | (short) (1<<numberOfBits-1));
}
return value;
}
public static short getSignedShort(short value, int numberOfBits) {
if((value & (1<<numberOfBits-1)) > 0) {
int mask = 0xffFFffFF;
mask >>>= Integer.SIZE - numberOfBits;
return (short) -(mask - value);
}
return value;
}
}
| 1,369 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
WatchedAsset.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/WatchedAsset.java | /*
* see license.txt
*/
package seventh.shared;
import java.io.IOException;
/**
* The asset that is being watched
*
* @author Tony
*
*/
public interface WatchedAsset<T> {
/**
* Retrieve the Asset
*
* @return the Asset in question
*/
public T getAsset();
/**
* Release this asset
*/
public void release();
/**
* The asset has changed on the file system
*
* @throws IOException
*/
public void onAssetChanged() throws IOException;
}
| 538 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
StateMachine.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/StateMachine.java | /*
* see license.txt
*/
package seventh.shared;
/**
* A very simple finite state machine
*
* @author Tony
*
*/
public class StateMachine<T extends State> {
/**
* Listens to state transitions
*
* @author Tony
*
* @param <T>
*/
public static interface StateMachineListener<T> {
public void onEnterState(T state);
public void onExitState(T state);
}
private T currentState;
private StateMachineListener<T> listener;
/**
*/
public StateMachine() {
this.currentState = null;
}
/**
* @param listener the listener to set
*/
public void setListener(StateMachineListener<T> listener) {
this.listener = listener;
}
/**
* @return the listener
*/
public StateMachineListener<T> getListener() {
return listener;
}
/**
* Updates
*
* @param timeStep
*/
public void update(TimeStep timeStep) {
if(this.currentState!=null) {
this.currentState.update(timeStep);
}
}
/**
* Changes to the new {@link State}
* @param newState
*/
public void changeState(T newState) {
if(this.currentState != null) {
this.currentState.exit();
if(this.listener != null) {
this.listener.onExitState(this.currentState);
}
}
if(newState!=null) {
newState.enter();
if(this.listener != null) {
this.listener.onEnterState(newState);
}
}
this.currentState = newState;
}
/**
* @return the currentState
*/
public T getCurrentState() {
return currentState;
}
}
| 1,901 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AssetWatcher.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/AssetWatcher.java | /*
* see license.txt
*/
package seventh.shared;
import java.io.IOException;
/**
* @author Tony
*
*/
public interface AssetWatcher {
/**
* Loads the Asset and marks it for being 'watched'
*
* @param filename
* @param loader
* @return the {@link WatchedAsset}
* @throws IOException
*/
public <T> WatchedAsset<T> loadAsset(String filename, AssetLoader<T> loader) throws IOException;
/**
* Removes the asset from being watched
*
* @param filename
*/
public void removeWatchedAsset(String filename);
/**
* Clear all watched assets
*/
public void clearWatched();
/**
* Starts watching
*/
public void startWatching();
/**
* Stops watching
*/
public void stopWatching();
} | 805 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ArrayMap.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/ArrayMap.java | /*
* see license.txt
*/
package seventh.shared;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Tony
*
*/
public class ArrayMap<K,V> implements Map<K, V> {
private static final int MIN_HASH_CAPACITY = 2;
private static final Object[] EMPTY_ARRAY = new Object[1];
/** the hash keys */
protected Object[] hashKeys;
/** the hash values */
protected Object[] hashValues;
/** the number of hash entries */
protected int hashEntries;
/** Construct empty table */
public ArrayMap() {
this(16);
}
/**
* Construct table with preset capacity.
* @param nhash capacity of hash part
*/
public ArrayMap(int nhash) {
presize(nhash);
}
public void presize(int nhash) {
if ( nhash > 0 && nhash < MIN_HASH_CAPACITY )
nhash = MIN_HASH_CAPACITY;
hashKeys = (nhash>0? new Object[nhash]: EMPTY_ARRAY);
hashValues = (nhash>0? new Object[nhash]: EMPTY_ARRAY);
hashEntries = 0;
}
@SuppressWarnings("unchecked")
protected V hashget(K key) {
if ( hashEntries > 0 ) {
V v = (V)hashValues[hashFindSlot(key)];
return v;
}
return null;
}
/** caller must ensure key is not nil */
public void set( K key, V value ) {
rawset(key, value);
}
/** caller must ensure key is not nil */
public void rawset( K key, V value ) {
hashset( key, value );
}
public int length() {
return this.hashEntries;
}
private void error(String error) {
throw new RuntimeException(error);
}
public int nexti( K key ) {
int i = 0;
do {
// find current key index
if ( key != null ) {
if ( hashKeys.length == 0 )
error( "invalid key to 'next'" );
i = hashFindSlot(key);
if ( hashKeys[i] == null )
error( "invalid key to 'next'" );
}
} while ( false );
// check hash part
for ( ; i<hashKeys.length; ++i )
if ( hashKeys[i] != null )
return i;
// nothing found, push nil, return nil.
return -1;
}
@SuppressWarnings("unchecked")
public K getKey(int index) {
return (K)hashKeys[index];
}
@SuppressWarnings("unchecked")
public V getValue(int index) {
return (V)hashValues[index];
}
@SuppressWarnings("unchecked")
public K nextKey(K key) {
int i = nexti(key);
return (K)hashKeys[i];
}
@SuppressWarnings("unchecked")
public V nextValue(K key) {
int i = nexti(key);
return (V) hashValues[i];
}
/**
* Set a hashtable value
* @param key key to set
* @param value value to set
*/
@SuppressWarnings("unchecked")
public V hashset(K key, V value) {
V r = null;
if ( value == null )
r = hashRemove(key);
else {
if ( hashKeys.length == 0 ) {
hashKeys = new Object[ MIN_HASH_CAPACITY ];
hashValues = new Object[ MIN_HASH_CAPACITY ];
}
int slot = hashFindSlot( key );
r = (V) hashValues[slot];
if ( hashFillSlot( slot, value ) )
return r;
hashKeys[slot] = key;
hashValues[slot] = value;
if ( checkLoadFactor() )
rehash();
}
return r;
}
/**
* Find the hashtable slot to use
* @param key key to look for
* @return slot to use
*/
@SuppressWarnings("unchecked")
public int hashFindSlot(K key) {
int i = ( key.hashCode() & 0x7FFFFFFF ) % hashKeys.length;
// This loop is guaranteed to terminate as long as we never allow the
// table to get 100% full.
K k;
while ( ( k = (K)hashKeys[i] ) != null && !k.equals(key) ) {
i = ( i + 1 ) % hashKeys.length;
}
return i;
}
private boolean hashFillSlot( int slot, V value ) {
hashValues[ slot ] = value;
if ( hashKeys[ slot ] != null ) {
return true;
} else {
++hashEntries;
return false;
}
}
@SuppressWarnings("unchecked")
private V hashRemove( K key ) {
V r = null;
if ( hashKeys.length > 0 ) {
int slot = hashFindSlot( key );
r = (V)hashValues[slot];
hashClearSlot( slot );
}
return r;
}
/**
* Clear a particular slot in the table
* @param i slot to clear.
*/
protected void hashClearSlot( int i ) {
if ( hashKeys[ i ] != null ) {
int j = i;
int n = hashKeys.length;
while ( hashKeys[ j = ( ( j + 1 ) % n ) ] != null ) {
final int k = ( ( hashKeys[ j ].hashCode() )& 0x7FFFFFFF ) % n;
if ( ( j > i && ( k <= i || k > j ) ) ||
( j < i && ( k <= i && k > j ) ) ) {
hashKeys[ i ] = hashKeys[ j ];
hashValues[ i ] = hashValues[ j ];
i = j;
}
}
--hashEntries;
hashKeys[ i ] = null;
hashValues[ i ] = null;
if ( hashEntries == 0 ) {
hashKeys = EMPTY_ARRAY;
hashValues = EMPTY_ARRAY;
}
}
}
private boolean checkLoadFactor() {
// Using a load factor of (n+1) >= 7/8 because that is easy to compute without
// overflow or division.
final int hashCapacity = hashKeys.length;
return hashEntries >= (hashCapacity - (hashCapacity>>3));
}
@SuppressWarnings("unchecked")
private void rehash() {
final int oldCapacity = hashKeys.length;
final int newCapacity = oldCapacity+(oldCapacity>>2)+MIN_HASH_CAPACITY;
final Object[] oldKeys = hashKeys;
final Object[] oldValues = hashValues;
hashKeys = new Object[ newCapacity ];
hashValues = new Object[ newCapacity ];
for ( int i = 0; i < oldCapacity; ++i ) {
final K k = (K) oldKeys[i];
if ( k != null ) {
final V v = (V) oldValues[i];
final int slot = hashFindSlot( k );
hashKeys[slot] = k;
hashValues[slot] = v;
}
}
}
// equality w/ metatable processing
@SuppressWarnings("rawtypes")
public boolean equal( Object val ) {
if ( val == null ) return false;
if ( this == val ) return true;
if ( getClass() != val.getClass() ) return false;
ArrayMap t = (ArrayMap)val;
return t.hashEntries==hashEntries && t.hashKeys.equals(hashKeys) && t.hashValues.equals(hashValues);
}
/* (non-Javadoc)
* @see java.util.Map#size()
*/
@Override
public int size() {
return this.hashEntries;
}
/* (non-Javadoc)
* @see java.util.Map#isEmpty()
*/
@Override
public boolean isEmpty() {
return this.hashEntries == 0;
}
/* (non-Javadoc)
* @see java.util.Map#containsKey(java.lang.Object)
*/
@SuppressWarnings("unchecked")
@Override
public boolean containsKey(Object key) {
int slot = hashFindSlot((K)key);
return this.hashValues[slot] != null;
}
/* (non-Javadoc)
* @see java.util.Map#containsValue(java.lang.Object)
*/
@SuppressWarnings("unchecked")
@Override
public boolean containsValue(Object value) {
V val = (V)value;
for(int i = 0; i < this.hashKeys.length; i++) {
if ( this.hashValues[i] != null) {
if ( this.hashValues[i].equals(val) )
return true;
}
}
return false;
}
/* (non-Javadoc)
* @see java.util.Map#get(java.lang.Object)
*/
@SuppressWarnings("unchecked")
@Override
public V get(Object key) {
return hashget((K)key);
}
/* (non-Javadoc)
* @see java.util.Map#put(java.lang.Object, java.lang.Object)
*/
@Override
public V put(K key, V value) {
return hashset(key, value);
}
/* (non-Javadoc)
* @see java.util.Map#remove(java.lang.Object)
*/
@SuppressWarnings("unchecked")
@Override
public V remove(Object key) {
return this.hashRemove((K)key);
}
/* (non-Javadoc)
* @see java.util.Map#putAll(java.util.Map)
*/
@Override
public void putAll(Map<? extends K,? extends V> m) {
for(Map.Entry<? extends K,? extends V> entry : m.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
/* (non-Javadoc)
* @see java.util.Map#clear()
*/
@Override
public void clear() {
for(int i = 0; i < this.hashKeys.length; i++) {
this.hashKeys[i] = null;
this.hashValues[i] = null;
}
this.hashEntries = 0;
}
/* (non-Javadoc)
* @see java.util.Map#keySet()
*/
@SuppressWarnings("unchecked")
@Override
public Set<K> keySet() {
Set<K> r = new HashSet<K>(this.hashEntries);
for(int i = 0; i < this.hashKeys.length; i++) {
if ( this.hashKeys[i] != null ) {
r.add( (K) this.hashKeys[i]);
}
}
return r;
}
/* (non-Javadoc)
* @see java.util.Map#values()
*/
@SuppressWarnings("unchecked")
@Override
public Collection<V> values() {
List<V> r = new ArrayList<V>(this.hashEntries);
for(int i = 0; i < this.hashValues.length; i++) {
if ( this.hashValues[i] != null ) {
r.add( (V)this.hashValues[i]);
}
}
return r;
}
/* (non-Javadoc)
* @see java.util.Map#entrySet()
*/
@Override
public Set<java.util.Map.Entry<K, V>> entrySet() {
return null;
}
}
| 10,494 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
FileSystemAssetWatcher.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/FileSystemAssetWatcher.java | /*
* see license.txt
*/
package seventh.shared;
import java.io.File;
import java.io.IOException;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* Watches a directory for any changes
*
* @author Tony
*
*/
public class FileSystemAssetWatcher implements AssetWatcher {
class WatchedAssetImpl<T> implements WatchedAsset<T> {
private AtomicReference<T> asset;
private AssetLoader<T> loader;
private File filename;
/**
* @param filename
* @param loader
*/
public WatchedAssetImpl(File filename, AssetLoader<T> loader) throws IOException {
this.asset = new AtomicReference<T>();
this.loader = loader;
this.filename = filename;
onAssetChanged();
}
@Override
public T getAsset() {
return this.asset.get();
}
@Override
public void release() {
this.asset.set(null);
removeWatchedAsset(this.filename.getAbsolutePath());
}
@Override
public void onAssetChanged() throws IOException {
this.asset.set(loader.loadAsset(filename.getAbsolutePath()));
}
}
private WatchService watchService;
private Thread watchThread;
private AtomicBoolean isActive;
private Path pathToWatch;
private Map<File, WatchedAsset<?>> watchedAssets;
/**
* @param dir
* @throws IOException
*/
public FileSystemAssetWatcher(File dir) throws IOException {
FileSystem fileSystem = FileSystems.getDefault();
this.isActive = new AtomicBoolean(false);
this.watchedAssets = new ConcurrentHashMap<File, WatchedAsset<?>>();
this.pathToWatch = dir.toPath();
this.watchService = fileSystem.newWatchService();
this.watchThread = new Thread(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
while(isActive.get()) {
try {
WatchKey key = watchService.take();
if(key.isValid()) {
List<WatchEvent<?>> events = key.pollEvents();
for(int i = 0; i < events.size(); i++) {
WatchEvent<?> event = events.get(i);
WatchEvent.Kind<?> kind = event.kind();
/* ignore overflow events */
if(kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
/* we are only listening for 'changed' events */
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Path filename = ev.context();
/* if we have a registered asset, lets go ahead and notify it */
WatchedAsset<?> watchedAsset = watchedAssets.get(new File(pathToWatch.toFile(), filename.toString()));
if(watchedAsset != null) {
try {
watchedAsset.onAssetChanged();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
key.reset();
}
catch (ClosedWatchServiceException e) {
break;
}
catch (InterruptedException e) {
break;
}
}
}
}, "watcher-thread");
this.watchThread.setDaemon(true);
this.pathToWatch.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
}
@Override
public <T> WatchedAsset<T> loadAsset(String filename, AssetLoader<T> loader) throws IOException {
File file = new File(pathToWatch.toFile(), filename.toString());
WatchedAsset<T> asset = new WatchedAssetImpl<T>(file, loader);
this.watchedAssets.put(file, asset);
return asset;
}
@Override
public void removeWatchedAsset(String filename) {
this.watchedAssets.remove(new File(filename));
}
@Override
public void clearWatched() {
this.watchedAssets.clear();
}
@Override
public void startWatching() {
this.isActive.set(true);
this.watchThread.start();
}
@Override
public void stopWatching() {
try {
this.isActive.set(false);
this.watchThread.interrupt();
}
finally {
try {
this.watchService.close();
}
catch(IOException e) {}
}
}
}
| 5,784 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Debugable.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Debugable.java | /*
* see license.txt
*/
package seventh.shared;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import seventh.server.ServerSeventhConfig;
/**
* Simple interface to pipe out to debug console
*
* @author Tony
*
*/
public interface Debugable {
/**
* {@link Debugable} hook
*
* @author Tony
*
*/
public static interface DebugableListener {
/**
* Initializes the debugger
*
* @param config
* @throws Exception
*/
void init(ServerSeventhConfig config) throws Exception;
/**
* Shuts down the debugger
*/
void shutdown();
/**
* Listens for a {@link Debugable}
*
* @param debugable
*/
void onDebugable(Debugable debugable);
}
/**
* Chain of debug entry information
*
* @author Tony
*
*/
public static class DebugInformation {
private Map<String, Object> entries;
/**
*/
public DebugInformation() {
this.entries = new HashMap<>();
}
public DebugInformation add(String key, int value) {
this.entries.put(key, value);
return this;
}
public DebugInformation add(String key, float value) {
this.entries.put(key, value);
return this;
}
public DebugInformation add(String key, double value) {
this.entries.put(key, value);
return this;
}
public DebugInformation add(String key, long value) {
this.entries.put(key, value);
return this;
}
public DebugInformation add(String key, Object value) {
this.entries.put(key, value);
return this;
}
public DebugInformation add(String key, DebugInformation chain) {
this.entries.put(key, chain);
return this;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{ ");
boolean isFirst = true;
for(Map.Entry<String, Object> e : this.entries.entrySet()) {
if(!isFirst) {
sb.append(",");
}
sb.append("\"").append(e.getKey()).append("\" : ");
Object value = e.getValue();
if(value == null) {
sb.append("null");
}
else if(value instanceof Object[]) {
sb.append(Arrays.toString((Object[])value));
}
else if(value instanceof String[][]) {
Object[][] v = (Object[][])value;
sb.append("[");
boolean innerIsFirst = true;
for(int i = 0; i < v.length; i++) {
if(!innerIsFirst) {
sb.append(",");
}
sb.append(Arrays.toString(v[i]));
innerIsFirst = false;
}
sb.append("]");
}
else if(value instanceof String) {
sb.append("\"").append(value).append("\"");
}
else {
sb.append(value);
}
isFirst = false;
}
sb.append("}");
return sb.toString();
}
}
/**
* Retrieves the debug information of this object
*
* @return the debug information
*/
public DebugInformation getDebugInformation();
}
| 3,914 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
JSON.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/JSON.java | /*
* see license.txt
*/
package seventh.shared;
import leola.vm.Leola;
import leola.vm.types.LeoObject;
/**
* Simple JSON utilities
*
* @author Tony
*
*/
public class JSON {
/**
* Parses the supplied json into a {@link LeoObject}.
*
* @param runtime
* @param json
* @return the {@link LeoObject}
* @throws Exception
*/
public static LeoObject parseJson(Leola runtime, String json) throws Exception {
/* TODO - replace with an actual JSON parser, this is
* a huge security hole
*/
String contents = "return " + json.replace(":", "->"); /* converts to leola map format */
LeoObject mapData = runtime.eval(contents);
return mapData;
}
/**
* Parses the supplied json into a {@link LeoObject}
*
* @param json
* @return the {@link LeoObject}
* @throws Exception
*/
public static LeoObject parseJson(String json) throws Exception {
return parseJson(Scripting.newSandboxedRuntime(), json);
}
}
| 1,071 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
WeaponConstants.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/WeaponConstants.java | /*
* The Seventh
* see license.txt
*/
package seventh.shared;
/**
* Placed in constants so both the server and client can reference
*
* @author Tony
*
*/
public interface WeaponConstants {
public static final int DEFAULT_LINE_OF_SIGHT = 150;
public static final int THOMPSON_LINE_OF_SIGHT = 150;
public static final int THOMPSON_WEIGHT = 5;
public static final int SPRINGFIELD_LINE_OF_SIGHT = 210;
public static final int SPRINGFIELD_WEIGHT = 28;
public static final int M1GARAND_LINE_OF_SIGHT = 190;
public static final int M1GARAND_WEIGHT = 13;
public static final int MP44_LINE_OF_SIGHT = 190;
public static final int MP44_WEIGHT = 25;
public static final int MP40_LINE_OF_SIGHT = 150;
public static final int MP40_WEIGHT = 5;
public static final int KAR98_LINE_OF_SIGHT = 210;
public static final int KAR98_WEIGHT = 15;
public static final int PISTOL_LINE_OF_SIGHT = 150;
public static final int PISTOL_WEIGHT = 2;
public static final int RPG_LINE_OF_SIGHT = 170;
public static final int RPG_WEIGHT = 40;
public static final int SHOTGUN_LINE_OF_SIGHT = 150;
public static final int SHOTGUN_WEIGHT = 12;
public static final int RISKER_LINE_OF_SIGHT = 170;
public static final int RISKER_WEIGHT = 25;
public static final int FLAME_THROWER_LINE_OF_SIGHT = 150;
public static final int FLAME_THROWER_WEIGHT = 40;
public static final int HAMMER_LINE_OF_SIGHT = 150;
public static final int HAMMER_WEIGHT = 2;
/*
* Tank properties
*/
public static final int TANK_DEFAULT_LINE_OF_SIGHT = 250;
public static final int TANK_MOVEMENT_SPEED = 90; // 50
public static final int TANK_WIDTH = 200;//225; //145
public static final int TANK_HEIGHT = 125;//145;//110
public static final int TANK_AABB_WIDTH = 295;
public static final int TANK_AABB_HEIGHT = 295;
/**
* Number of pixels the player must be away in order
* to be able to operate a vehicle by pressing the USE
* key
*/
public static final int VEHICLE_HITBOX_THRESHOLD = 15;
}
| 2,180 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
LANServerConfig.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/LANServerConfig.java | /*
* see license.txt
*/
package seventh.shared;
/**
* LAN Server configuration settings
*
* @author Tony
*
*/
public class LANServerConfig {
private Config config;
/**
* @param config
*/
public LANServerConfig(Config config) {
this.config = config;
}
/**
* @return the broadcast address
*/
public String getBroadcastAddress() {
return this.config.getStr("224.0.0.44", "lan", "broadcast_address");
}
/**
* @param url
*/
public void setBroadcastAddress(String address) {
this.config.set(address, "lan", "broadcast_address");
}
/**
* @return the LAN broadcast port
*/
public int getPort() {
return this.config.getInt(4888, "lan", "port");
}
/**
* Sets the LAN broadcast port
*
* @param port
*/
public void setPort(int port) {
this.config.set(port, "lan", "port");
}
/**
* @return the LAN broadcast mtu
*/
public int getMtu() {
return this.config.getInt(1500, "lan", "mtu");
}
/**
* Sets the LAN broadcast mtu
*
* @param mtu
*/
public void setMtu(int mtu) {
this.config.set(mtu, "lan", "mtu");
}
}
| 1,285 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
MapList.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/MapList.java | /*
* see license.txt
*/
package seventh.shared;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import seventh.game.game_types.GameType;
import seventh.game.game_types.GameType.Type;
/**
* Utility class for finding all maps in the maps directory
*
* @author Tony
*
*/
public class MapList {
public static class MapEntry {
private String displayName;
private String fileName;
/**
* @param fileName
*/
public MapEntry(String fileName) {
this(MapList.getDisplayName(fileName), fileName);
}
/**
* @param displayName
* @param fileName
*/
public MapEntry(String displayName, String fileName) {
super();
this.displayName = displayName;
this.fileName = fileName;
}
/**
* @return the displayName
*/
public String getDisplayName() {
return displayName;
}
/**
* @return the fileName
*/
public String getFileName() {
return fileName;
}
@Override
public String toString() {
return this.displayName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((displayName == null) ? 0 : displayName.hashCode());
result = prime * result + ((fileName == null) ? 0 : fileName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MapEntry other = (MapEntry) obj;
if (displayName == null) {
if (other.displayName != null)
return false;
} else if (!displayName.equals(other.displayName))
return false;
if (fileName == null) {
if (other.fileName != null)
return false;
} else if (!fileName.equals(other.fileName))
return false;
return true;
}
}
public static final String MapFilePath = "./assets/maps/";
private static File[] getMapFiles(String path) {
File dir = new File(path);
File[] maps = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".json");
}
});
return maps;
}
/**
* Look the the maps directory to see what maps are available for a
* particular game type
*
* @return the map listings
*/
public static List<MapEntry> getMapListing(GameType.Type gameType) {
File[] maps = getMapFiles(MapFilePath);
List<MapEntry> mapNames = new ArrayList<MapEntry>(maps.length);
for(File f : maps) {
File gameTypeFile = new File(MapFilePath, f.getName() + "." + gameType.name().toLowerCase() + ".leola");
if(gameType==GameType.Type.TDM || gameTypeFile.exists()) {
String displayName = stripFileExtension(f.getName());
MapEntry entry = new MapEntry(displayName, MapFilePath + f.getName());
mapNames.add(entry);
}
}
return mapNames;
}
/**
* Look the the maps directory to see what maps are available
*
* @return the map listings
*/
public static List<MapEntry> getMapListing() {
return getMapListing(Type.TDM);
}
/**
* Adds the map file extension is not present on the supplied name
* @param mapName the maps name
* @return the maps name with the file extension added if not present
* on the input
*/
public static String addFileExtension(String mapName) {
if(!mapName.toLowerCase().endsWith(".json")) {
mapName += ".json";
}
return mapName;
}
private static String getDisplayName(String mapFilePath) {
int startIndex = mapFilePath.lastIndexOf("/") + 1;
int endIndex = mapFilePath.lastIndexOf(".");
return mapFilePath.substring(startIndex, endIndex);
}
public static String stripFileExtension(String fileName) {
String displayName = fileName.replace(".json", "");
return displayName;
}
}
| 4,779 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ImageScaler.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/ImageScaler.java | /*
* see license.txt
*/
package seventh.shared;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
/**
* @author Tony
*
*/
public class ImageScaler {
/**
*
*/
public ImageScaler() {
// TODO Auto-generated constructor stub
}
static enum ScaleType {
AXIS_POSITION,
AXIS_LEGS,
AXIS_DEATH1,
AXIS_DEATH2,
ALLIED_POSITION,
ALLIED_LEGS,
ALLIED_DEATH1,
ALLIED_DEATH2,
;
}
/**
* @param args
*/
public static void main(String[] args) throws Exception {
ScaleType type = ScaleType.AXIS_POSITION;
File imageFile = null;
File destFile = null;
float scale = 1.0f;
int xOffset = 0;
int yOffset = 0;
int width = 0;
int height = 0;
switch(type) {
case AXIS_DEATH1: {
imageFile = new File("C:\\Users\\Tony\\git\\seventh\\assets\\gfx\\player\\axis_death_01.png");
scale = 0.60f;
width = 512;
height = 256;
break;
}
case AXIS_DEATH2: {
imageFile = new File("C:\\Users\\Tony\\git\\seventh\\assets\\gfx\\player\\axis_death_02.png");
scale = 0.60f;
width = 512;
height = 256;
break;
}
case AXIS_POSITION: {
imageFile = new File("C:\\Users\\Tony\\git\\seventh\\assets\\gfx\\player\\axis_positions.png");
scale = 0.77f; // TODO: 0.616f take ((77% * 256) * 80%)
xOffset = -5;
yOffset = -5;
width = 256;
height = 256;
break;
}
case AXIS_LEGS: {
imageFile = new File("C:\\Users\\Tony\\Desktop\\SpriteSheetPacker\\Test\\axis_walk\\axis_legs_walk.png");
destFile = new File("C:\\Users\\Tony\\Desktop\\SpriteSheetPacker\\Test\\axis_walk\\axis_legs_walk_scaled.png");
scale = 0.77f;
xOffset = 0;
yOffset = 0;
width = 512;
height = 256;
break;
}
case ALLIED_DEATH1: {
imageFile = new File("C:\\Users\\Tony\\git\\seventh\\assets\\gfx\\player\\allied_death_01.png");
scale = 0.60f;
width = 512;
height = 256;
break;
}
case ALLIED_DEATH2: {
imageFile = new File("C:\\Users\\Tony\\git\\seventh\\assets\\gfx\\player\\allied_death_02.png");
scale = 0.60f;
width = 512;
height = 256;
break;
}
case ALLIED_POSITION: {
imageFile = new File("C:\\Users\\Tony\\git\\seventh\\assets\\gfx\\player\\allied_positions.png");
scale = 0.77f;
xOffset = -5;
yOffset = -5;
width = 256;
height = 256;
break;
}
case ALLIED_LEGS: {
break;
}
}
BufferedImage image = ImageIO.read(imageFile);
BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g = (Graphics2D) scaledImage.getGraphics();
g.scale(scale, scale);
g.drawImage(image, xOffset, yOffset, null);
ImageIO.write(scaledImage, "png", destFile == null ? imageFile:destFile);
}
}
| 3,756 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ImageColorReplacer.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/ImageColorReplacer.java | /*
* see license.txt
*/
package seventh.shared;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.imageio.ImageIO;
/**
* Replaces the images color palate
*
* @author Tony
*
*/
public class ImageColorReplacer {
/**
*
*/
public ImageColorReplacer() {
}
static BufferedImage drawImage(Map<Integer, Integer> palette, BufferedImage image) {
BufferedImage replacedImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
int color = image.getRGB(x, y);
replacedImage.setRGB(x, y, palette.get(color));
}
}
return replacedImage;
}
static BufferedImage replaceColor(BufferedImage image) {
Map<Integer, Integer> colors = new HashMap<>();
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
int col = image.getRGB(x, y);
if(!colors.containsKey(col)) {
Color c = new Color( (col & 0x00ff0000) >> 16,
(col & 0x0000ff00) >> 8,
(col & 0x000000ff) >> 0);
int newColor = col;
/*
int rgb = col & 0x00FFFFFF;
String sColor = Integer.toHexString(rgb);
if(sColor.startsWith("a") || sColor.startsWith("e") ||
sColor.startsWith("c") || sColor.startsWith("1") ||
sColor.startsWith("b8") || sColor.startsWith("76") ) {
newColor = (col & 0xff000000);
newColor = newColor | ((col & 0x00ff0000) >> 24);
newColor = newColor | ((col & 0x0000ff00) >> 0);
newColor = newColor | ((col & 0x000000ff) << 16);
newColor = 0x00;
}*/
int fuzzy = 20;
if( Math.abs(c.getRed() - c.getBlue()) < fuzzy &&
Math.abs(c.getRed() - c.getGreen()) < fuzzy &&
Math.abs(c.getBlue() - c.getGreen()) < fuzzy ) {
newColor = (col & 0xff000000);
newColor = newColor | ((Math.min(c.getRed() + 15, 255)) << 16);
newColor = newColor | ((Math.min(c.getGreen() + 25, 255)) << 8);
newColor = newColor | ((Math.max(c.getBlue() - 30, 0)) << 0);
//newColor = 0x00;
}
fuzzy = 30;
if( c.getRed() - c.getBlue() > fuzzy &&
c.getRed() - c.getGreen() > fuzzy) {
newColor = (col & 0xff000000);
newColor = newColor | ((Math.max(c.getRed() - 110, 0)) << 16);
newColor = newColor | ((Math.min(c.getGreen() + 55, 255)) << 8);
newColor = newColor | ((Math.min(c.getBlue() + 20, 255)) << 0);
//newColor = 0x00;
}
fuzzy = 30;
if( c.getGreen() - c.getRed() > 9 &&
c.getGreen() - c.getRed() < 25 &&
c.getGreen() - c.getBlue() > 25 &&
c.getGreen() - c.getBlue() < 40 &&
c.getRed() - c.getBlue() >= 15) {
newColor = (col & 0xff000000);
newColor = newColor | ((Math.max(c.getRed() - 40, 0)) << 16);
newColor = newColor | ((Math.max(c.getGreen() - 55, 0)) << 8);
newColor = newColor | ((Math.max(c.getBlue() - 65, 0)) << 0);
//newColor = 0x00;
}
colors.put(col, newColor);
}
}
}
List<String> cStrs = new ArrayList<>();
Set<String> ss = new HashSet<>();
for(Integer color : colors.keySet()) {
int rgb = color & 0x00FFFFFF;
//cStrs.add(Integer.toHexString(rgb));
ss.add(Integer.toHexString(rgb));
//System.out.println(Integer.toHexString(rgb));
//Integer.toString(color, 16));
}
cStrs.addAll(ss);
Collections.sort(cStrs);
for(String s : cStrs) {
System.out.println(s + " : " + Integer.valueOf(s, 16));
}
return drawImage(colors, image);
}
/**
* @param args
*/
public static void main(String[] args) throws Exception {
File imageFile = new File("C:\\Users\\Tony\\Desktop\\SpriteSheetPacker\\GreenKnight\\attack");
File replacedFile = new File(imageFile.getParentFile(), imageFile.getName() + ".replaced.png");
BufferedImage image = ImageIO.read(imageFile);
Map<Integer, Integer> colors = new HashMap<>();
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
int col = image.getRGB(x, y);
if(!colors.containsKey(col)) {
Color c = new Color( (col & 0x00ff0000) >> 16,
(col & 0x0000ff00) >> 8,
(col & 0x000000ff) >> 0);
int newColor = col;
/*
int rgb = col & 0x00FFFFFF;
String sColor = Integer.toHexString(rgb);
if(sColor.startsWith("a") || sColor.startsWith("e") ||
sColor.startsWith("c") || sColor.startsWith("1") ||
sColor.startsWith("b8") || sColor.startsWith("76") ) {
newColor = (col & 0xff000000);
newColor = newColor | ((col & 0x00ff0000) >> 24);
newColor = newColor | ((col & 0x0000ff00) >> 0);
newColor = newColor | ((col & 0x000000ff) << 16);
newColor = 0x00;
}*/
int fuzzy = 20;
if( Math.abs(c.getRed() - c.getBlue()) < fuzzy &&
Math.abs(c.getRed() - c.getGreen()) < fuzzy &&
Math.abs(c.getBlue() - c.getGreen()) < fuzzy ) {
newColor = (col & 0xff000000);
newColor = newColor | ((Math.min(c.getRed() + 15, 255)) << 16);
newColor = newColor | ((Math.min(c.getGreen() + 25, 255)) << 8);
newColor = newColor | ((Math.max(c.getBlue() - 30, 0)) << 0);
//newColor = 0x00;
}
fuzzy = 30;
if( c.getRed() - c.getBlue() > fuzzy &&
c.getRed() - c.getGreen() > fuzzy) {
newColor = (col & 0xff000000);
newColor = newColor | ((Math.max(c.getRed() - 110, 0)) << 16);
newColor = newColor | ((Math.min(c.getGreen() + 55, 255)) << 8);
newColor = newColor | ((Math.min(c.getBlue() + 20, 255)) << 0);
//newColor = 0x00;
}
fuzzy = 30;
if( c.getGreen() - c.getRed() > 9 &&
c.getGreen() - c.getRed() < 25 &&
c.getGreen() - c.getBlue() > 25 &&
c.getGreen() - c.getBlue() < 40 &&
c.getRed() - c.getBlue() >= 15) {
newColor = (col & 0xff000000);
newColor = newColor | ((Math.max(c.getRed() - 40, 0)) << 16);
newColor = newColor | ((Math.max(c.getGreen() - 55, 0)) << 8);
newColor = newColor | ((Math.max(c.getBlue() - 65, 0)) << 0);
//newColor = 0x00;
}
colors.put(col, newColor);
}
}
}
List<String> cStrs = new ArrayList<>();
Set<String> ss = new HashSet<>();
for(Integer color : colors.keySet()) {
int rgb = color & 0x00FFFFFF;
//cStrs.add(Integer.toHexString(rgb));
ss.add(Integer.toHexString(rgb));
//System.out.println(Integer.toHexString(rgb));
//Integer.toString(color, 16));
}
cStrs.addAll(ss);
Collections.sort(cStrs);
for(String s : cStrs) {
System.out.println(s + " : " + Integer.valueOf(s, 16));
}
ImageIO.write(drawImage(colors, image), "png", replacedFile);
}
}
| 9,721 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SysOutLogger.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/SysOutLogger.java | /*
* see license.txt
*/
package seventh.shared;
/**
* @author Tony
*
*/
public class SysOutLogger implements Logger {
/* (non-Javadoc)
* @see shared.Console#print(java.lang.Object)
*/
public void print(Object msg) {
System.out.print(msg);
}
/* (non-Javadoc)
* @see shared.Console#println(java.lang.Object)
*/
public void println(Object msg) {
System.out.println(msg);
}
/* (non-Javadoc)
* @see shared.Console#printf(java.lang.Object, java.lang.Object[])
*/
public void printf(Object msg, Object... args) {
System.out.printf(msg.toString(), args);
}
}
| 657 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Randomizer.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Randomizer.java | /*
* see license.txt
*/
package seventh.shared;
import java.util.Random;
/**
* Utility for random numbers
*
* @author Tony
*
*/
public class Randomizer {
private Random random;
/**
* @param random
*/
public Randomizer(Random random) {
this.random = random;
}
public int nextInt(int max) {
return this.random.nextInt(max);
}
public boolean nextBoolean() {
return this.random.nextBoolean();
}
public double nextDouble() {
return this.random.nextDouble();
}
public float nextFloat() {
return this.random.nextFloat();
}
public double getRandomRange(double min, double max) {
return getRandomRange(random, min, max);
}
public double getRandomRangeMin(double min) {
return getRandomRangeMin(random, min);
}
public double getRandomRangeMax(double max) {
return getRandomRangeMax(random, max);
}
public static double getRandomRange(Random random, double min, double max) {
return min + (random.nextDouble() * (max - min));
}
public static double getRandomRangeMin(Random random, double min) {
return getRandomRange(random, min, 1.0);
}
public static double getRandomRangeMax(Random random, double max) {
return getRandomRange(random, 0.0, max);
}
}
| 1,416 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
DebugDraw.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/DebugDraw.java | /*
* see license.txt
*/
package seventh.shared;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import seventh.client.gfx.Camera;
import seventh.client.gfx.Canvas;
import seventh.math.OBB;
import seventh.math.Rectangle;
import seventh.math.Vector2f;
/**
* A helper for drawing items to the screen.
*
* @author Tony
*
*/
public class DebugDraw {
static abstract class Drawable {
boolean offsetWithCamera;
Integer color;
int drawCount;
Drawable(boolean offsetWithCamera, Integer color) {
this.offsetWithCamera = offsetWithCamera;
this.color = color;
this.drawCount = 0;
}
abstract void draw(Canvas canvas, Camera camera);
}
private static class StringDrawable extends Drawable {
String text;
int x, y;
StringDrawable(boolean offsetWithCamera, Integer color, String text, int x, int y) {
super(offsetWithCamera, color);
this.text = text;
this.x = x;
this.y = y;
this.color = color;
}
@Override
public void draw(Canvas canvas, Camera camera) {
float x = this.x;
float y = this.y;
if(offsetWithCamera) {
x -= camera.getPosition().x;
y -= camera.getPosition().y;
}
canvas.drawString(text, (int)x, (int)y, color);
}
}
private static class LineDrawable extends Drawable {
Vector2f a, b;
/**
*
*/
public LineDrawable(boolean offsetWithCamera, Integer color, Vector2f a, Vector2f b) {
super(offsetWithCamera, color);
this.a = a; this.b = b;
}
@Override
public void draw(Canvas canvas, Camera camera) {
float ax = a.x;
float ay = a.y;
float bx = b.x;
float by = b.y;
if(offsetWithCamera) {
ax -= camera.getPosition().x;
ay -= camera.getPosition().y;
bx -= camera.getPosition().x;
by -= camera.getPosition().y;
}
canvas.drawLine((int)ax, (int)ay, (int)bx, (int)by, color);
}
}
private static class RectDrawable extends Drawable {
int x;
int y;
int width;
int height;
boolean fill;
public RectDrawable(boolean offsetWithCamera, Integer color, boolean fill, int x, int y, int width, int height) {
super(offsetWithCamera, color);
this.fill = fill;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
@Override
public void draw(Canvas canvas, Camera camera) {
float x = this.x;
float y = this.y;
if(offsetWithCamera) {
x -= camera.getPosition().x;
y -= camera.getPosition().y;
}
if(fill) {
canvas.fillRect((int)x, (int)y, width, height, color);
}
else {
canvas.drawRect((int)x, (int)y, width, height, color);
}
}
}
private static Queue<Drawable> drawCalls = new ConcurrentLinkedQueue<>();
private static AtomicBoolean enabled = new AtomicBoolean(false);
/**
* Enable draw calls.
*
* @param enable
*/
public static void enable(boolean enable) {
enabled.set(enable);
if(!enabled.get()) {
drawCalls.clear();
}
}
/**
* Draws a string relative to the camera position.
*
* @param text
* @param x
* @param y
* @param color
*/
public static void drawStringRelative(String text, int x, int y, Integer color) {
if(enabled.get()) {
drawCalls.add(new StringDrawable(true, color, text, x, y));
}
}
/**
* Draws a string to the screen.
*
* @param text
* @param x
* @param y
* @param color
*/
public static void drawString(String text, int x, int y, Integer color) {
if(enabled.get()) {
drawCalls.add(new StringDrawable(false, color, text, x, y));
}
}
/**
* Draws a string relative to the camera position.
*
* @param text
* @param x
* @param y
* @param color
*/
public static void drawStringRelative(String text, Vector2f pos, Integer color) {
if(enabled.get()) {
drawCalls.add(new StringDrawable(true, color, text, (int)pos.x, (int)pos.y) );
}
}
/**
* Draws a string to the screen.
*
* @param text
* @param x
* @param y
* @param color
*/
public static void drawString(String text, Vector2f pos, Integer color) {
if(enabled.get()) {
drawCalls.add(new StringDrawable(false, color, text, (int)pos.x, (int)pos.y));
}
}
public static void drawLine(Vector2f a, Vector2f b, Integer color) {
if(enabled.get()) {
drawCalls.add(new LineDrawable(false, color, a, b));
}
}
public static void drawLineRelative(Vector2f a, Vector2f b, Integer color) {
if(enabled.get()) {
drawCalls.add(new LineDrawable(true, color, a, b));
}
}
public static void drawOOB(OBB oob, Integer color) {
if(enabled.get()) {
drawCalls.add(new LineDrawable(false, color, oob.topLeft, oob.topRight));
drawCalls.add(new LineDrawable(false, color, oob.topRight, oob.bottomRight));
drawCalls.add(new LineDrawable(false, color, oob.bottomRight, oob.bottomLeft));
drawCalls.add(new LineDrawable(false, color, oob.bottomLeft, oob.topLeft));
}
}
public static void drawOOBRelative(OBB oob, Integer color) {
if(enabled.get()) {
drawCalls.add(new LineDrawable(true, color, oob.topLeft, oob.topRight));
drawCalls.add(new LineDrawable(true, color, oob.topRight, oob.bottomRight));
drawCalls.add(new LineDrawable(true, color, oob.bottomRight, oob.bottomLeft));
drawCalls.add(new LineDrawable(true, color, oob.bottomLeft, oob.topLeft));
}
}
public static void drawRectRelative(Rectangle bounds, Integer color) {
drawRectRelative(bounds.x, bounds.y, bounds.width, bounds.height, color);
}
/**
* Draws a rectangle relative to the camera position.
*
* @param x
* @param y
* @param width
* @param height
* @param color
*/
public static void drawRectRelative(int x, int y, int width, int height, Integer color) {
if(enabled.get()) {
drawCalls.add(new RectDrawable(true, color, false, x, y, width, height));
}
}
/**
* Draws a rectangle
*
* @param x
* @param y
* @param width
* @param height
* @param color
*/
public static void drawRect(int x, int y, int width, int height, Integer color) {
if(enabled.get()) {
drawCalls.add(new RectDrawable(false, color, false, x, y, width, height));
}
}
/**
* Fills in a rectangle relative to the camera position
*
* @param x
* @param y
* @param width
* @param height
* @param color
*/
public static void fillRectRelative(int x, int y, int width, int height, Integer color) {
if(enabled.get()) {
drawCalls.add(new RectDrawable(true, color, true, x, y, width, height));
}
}
/**
* Fills in a rectangle
*
* @param x
* @param y
* @param width
* @param height
* @param color
*/
public static void fillRect(int x, int y, int width, int height, Integer color) {
if(enabled.get()) {
drawCalls.add(new RectDrawable(false, color, true, x, y, width, height));
}
}
/**
* Called by the client to do the actual rendering calls.
*
* @param canvas
* @param camera
*/
public static void render(Canvas canvas, Camera camera) {
if(enabled.get()) {
for(Drawable d : drawCalls) {
d.draw(canvas, camera);
d.drawCount++;
}
// frameCounter++;
for(Drawable d : drawCalls) {
if(d.drawCount > 3) {
drawCalls.remove(d);
}
}
// if(frameCounter >= 0)
// {
// drawCalls.clear();
// frameCounter = 0;
// }
}
}
}
| 9,038 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Scripting.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Scripting.java | /*
* see license.txt
*/
package seventh.shared;
import java.io.File;
import leola.vm.Args;
import leola.vm.Leola;
import leola.vm.types.LeoObject;
import seventh.math.Vector2f;
import seventh.server.SeventhScriptingCommonLibrary;
/**
* Scripting runtime factory methods
*
* @author Tony
*
*/
public class Scripting {
public static void execute(LeoObject function) {
if(function != null) {
LeoObject result = function.call();
if(result.isError()) {
Cons.println("*** ERROR -> " + result);
}
}
}
/**
* Attempts to load a script file
*
* @param runtime
* @param scriptFile
*/
public static LeoObject loadScript(Leola runtime, String scriptFile) {
File file = new File(scriptFile);
if(file.exists()) {
try {
return runtime.eval(file);
}
catch(Exception e) {
Cons.println("*** ERROR -> Loading " + file.getName() + ": " + e);
}
}
return LeoObject.NULL;
}
/**
* Creates a new {@link Leola} runtime that is in sandboxed mode.
*
* @return the runtime
*/
public static Leola newSandboxedRuntime() {
Leola runtime = Args.builder()
.setAllowThreadLocals(false)
.setIsDebugMode(true)
.setBarebones(true)
.setSandboxed(false) // TODO
.newRuntime();
/* load some helper functions for objective scripts */
runtime.loadStatics(SeventhScriptingCommonLibrary.class);
runtime.loadStatics(Vector2f.class);
runtime.put("console", Cons.getImpl());
return runtime;
}
/**
* Creates a new {@link Leola} runtime that is not in sandboxed mode.
*
* @return the runtime
*/
public static Leola newRuntime() {
Leola runtime = Args.builder()
.setIsDebugMode(true)
.setAllowThreadLocals(false)
.newRuntime();
/* load some helper functions for objective scripts */
runtime.loadStatics(SeventhScriptingCommonLibrary.class);
runtime.loadStatics(Vector2f.class);
runtime.put("console", Cons.getImpl());
return runtime;
}
}
| 2,527 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Updatable.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Updatable.java | /*
* leola-live
* see license.txt
*/
package seventh.shared;
/**
* @author Tony
*
*/
public interface Updatable {
/**
* @param timeStep
*/
public void update(TimeStep timeStep);
}
| 212 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
EventDispatcher.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/EventDispatcher.java | /*
Leola Programming Language
Author: Tony Sparks
See license.txt
*/
package seventh.shared;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import leola.vm.util.ClassUtil;
/**
* Dispatches events. This implementation is thread safe.
*
* @author Tony
*
*/
public class EventDispatcher {
/**
* Handle to all listeners
*/
private Map<Class<?>, Collection<EventListener>> eventListenerMap;
/**
* Queue of events
*/
private Queue<Event> eventQueue;
/**
* Cache for method look up.
*/
private Map<Class<?>, EventMethodEntry> eventMethodMap;
/**
* @author Tony
*/
private class EventMethodEntry {
Map<Class<?>, Method> invokables;
/**
* @param aListenerClass
* @param eventMethod
*/
EventMethodEntry() {
this.invokables = new ConcurrentHashMap<Class<?>, Method>();
}
/**
* Adds an event listener.
*
* @param aListenerClass
* @param eventType
*/
void addListener(Class<?> aListenerClass, Class<?> eventType) {
scan(aListenerClass, eventType);
}
/**
* Remove a listener type
* @param aListenerClass
* @param eventType
*/
void removeListener(Class<?> eventType) {
this.invokables.remove(eventType);
}
/**
* Scan the listener class for EventMethods.
*
* @param aListenerClass
*/
void scan(Class<?> aListenerClass, Class<?> eventType) {
/* Only get the public members */
Method[] methods = aListenerClass.getDeclaredMethods();
if ( methods.length > 0 ) {
for ( Method method : methods) {
/* Query for the event method annotation */
EventMethod eventMethod = ClassUtil.getAnnotation(EventMethod.class, aListenerClass, method);
if ( eventMethod != null ) {
/* Verify this only has one parameter, the Event */
Class<?>[] paramTypes = method.getParameterTypes();
if ( paramTypes.length == 1 && paramTypes[0].equals(eventType) ) {
//ClassUtil.inheritsFrom(paramTypes[0], eventType) ) {
method.setAccessible(true);
this.invokables.put(eventType, method);
break;
}
}
}
}
}
/**
* Invoke the method
*
* @param event
*/
void invoke(EventListener aListener, Event event) {
try {
Method method = this.invokables.get(event.getClass());
if ( method != null ) {
method.invoke(aListener, event);
}
}
catch(Exception e) {
System.err.println("Error invoking listener method - " + e);
e.printStackTrace(System.err);
}
}
}
/**
*/
public EventDispatcher() {
this.eventListenerMap = new ConcurrentHashMap<Class<?>, Collection<EventListener>>();
this.eventMethodMap = new ConcurrentHashMap<Class<?>, EventMethodEntry>();
this.eventQueue = new ConcurrentLinkedQueue<Event>();
}
/**
* Queues the {@link Event}
* @param event
*/
public void queueEvent(Event event) {
this.eventQueue.add(event);
}
/**
* Clear the event queue
*/
public void clearQueue() {
this.eventQueue.clear();
}
/**
* Processes the next event in the event queue.
*
* @return true processed an event, false if no events where processed (due to
* the queue being empty).
*/
public boolean processQueue() {
boolean eventProcessed = false;
/* Poll from the queue */
Event event = this.eventQueue.poll();
if ( event != null ) {
/* Send the event to the listeners */
sendNow(event);
eventProcessed = true;
}
return eventProcessed;
}
/**
* Sends the supplied event now, bypassing the queue.
* @param event
*/
public <E extends Event> void sendNow(E event) {
Class<?> eventClass = event.getClass();
if ( this.eventListenerMap.containsKey(eventClass)) {
Collection<EventListener> eventListeners = this.eventListenerMap.get(eventClass);
for(EventListener listener : eventListeners) {
Class<?> listenerClass = listener.getClass();
/* Get the method lookup cache */
EventMethodEntry entry = this.eventMethodMap.get(listenerClass);
/* Send out the event */
if(entry != null) {
entry.invoke(listener, event);
}
/* If its been consumed, don't continue */
if ( event.isConsumed() ) {
break;
}
}
}
}
/**
* Add an {@link EventListener}.
*
* @param eventClass
* @param eventListener
*/
public void addEventListener(Class<?> eventClass, EventListener eventListener) {
if ( ! this.eventListenerMap.containsKey(eventClass)) {
this.eventListenerMap.put(eventClass, new ConcurrentLinkedQueue<EventListener>());
}
/* Place the method lookup cache in place */
Class<?> listenerClass = eventListener.getClass();
if ( ! this.eventMethodMap.containsKey(listenerClass) ) {
this.eventMethodMap.put(listenerClass, new EventMethodEntry());
}
EventMethodEntry methodEntry = this.eventMethodMap.get(listenerClass);
methodEntry.addListener(listenerClass, eventClass);
/* Add the listener object */
Collection<EventListener> eventListeners = this.eventListenerMap.get(eventClass);
eventListeners.add(eventListener);
}
/**
* Removes an {@link EventListener}
*
* @param eventClass
* @param eventListener
*/
public void removeEventListener(Class<?> eventClass, EventListener eventListener) {
if ( this.eventListenerMap.containsKey(eventClass)) {
Collection<EventListener> eventListeners = this.eventListenerMap.get(eventClass);
eventListeners.remove(eventListener);
Class<?> listenerClass = eventListener.getClass();
EventMethodEntry methodEntry = this.eventMethodMap.get(listenerClass);
if ( methodEntry != null ) {
methodEntry.removeListener(eventClass);
}
}
}
/**
* Remove all the {@link EventListener}s
*
*/
public void removeAllEventListeners() {
this.eventListenerMap.clear();
this.eventMethodMap.clear();
}
/**
* Get all the {@link Event} classes that currently have listeners.
*
* @return the set of event classes
*/
public Set<Class<?>> getEventClasses() {
return this.eventListenerMap.keySet();
}
}
| 7,859 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
RconHash.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/RconHash.java | /*
* see license.txt
*/
package seventh.shared;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @author Tony
*
*/
public class RconHash {
private long token;
/**
*
*/
public RconHash(long token) {
this.token = token;
}
/**
* @param value
* @return the hashed version of the value
*/
public String hash(String value) {
String hashedValue = value;
try {
byte[] hv = hashImpl(value);
hashedValue = Base64.encodeBytes(hv);
}
catch(NoSuchAlgorithmException e) {
Cons.println("*** No hashing algorithm defined on the JVM" + e);
}
return hashedValue;
}
protected byte[] hashImpl(String password) throws NoSuchAlgorithmException {
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
byte[] passBytes = (password + Long.toString(token)).getBytes();
byte[] passHash = sha256.digest(passBytes);
return passHash;
}
}
| 1,099 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Base64.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Base64.java | package seventh.shared;
/**
* <p>Encodes and decodes to and from Base64 notation.</p>
* <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p>
*
* <p>Example:</p>
*
* <code>String encoded = Base64.encode( myByteArray );</code>
* <br />
* <code>byte[] myByteArray = Base64.decode( encoded );</code>
*
* <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass
* several pieces of information to the encoder. In the "higher level" methods such as
* encodeBytes( bytes, options ) the options parameter can be used to indicate such
* things as first gzipping the bytes before encoding them, not inserting linefeeds,
* and encoding using the URL-safe and Ordered dialects.</p>
*
* <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>,
* Section 2.1, implementations should not add line feeds unless explicitly told
* to do so. I've got Base64 set to this behavior now, although earlier versions
* broke lines by default.</p>
*
* <p>The constants defined in Base64 can be OR-ed together to combine options, so you
* might make a call like this:</p>
*
* <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code>
* <p>to compress the data before encoding it and then making the output have newline characters.</p>
* <p>Also...</p>
* <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code>
*
*
*
* <p>
* Change Log:
* </p>
* <ul>
* <li>v2.3.7 - Fixed subtle bug when base 64 input stream contained the
* value 01111111, which is an invalid base 64 character but should not
* throw an ArrayIndexOutOfBoundsException either. Led to discovery of
* mishandling (or potential for better handling) of other bad input
* characters. You should now get an IOException if you try decoding
* something that has bad characters in it.</li>
* <li>v2.3.6 - Fixed bug when breaking lines and the final byte of the encoded
* string ended in the last column; the buffer was not properly shrunk and
* contained an extra (null) byte that made it into the string.</li>
* <li>v2.3.5 - Fixed bug in {@link #encodeFromFile} where estimated buffer size
* was wrong for files of size 31, 34, and 37 bytes.</li>
* <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing
* the Base64.OutputStream closed the Base64 encoding (by padding with equals
* signs) too soon. Also added an option to suppress the automatic decoding
* of gzipped streams. Also added experimental support for specifying a
* class loader when using the
* {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)}
* method.</li>
* <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java
* footprint with its CharEncoders and so forth. Fixed some javadocs that were
* inconsistent. Removed imports and specified things like java.io.IOException
* explicitly inline.</li>
* <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the
* final encoded data will be so that the code doesn't have to create two output
* arrays: an oversized initial one and then a final, exact-sized one. Big win
* when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not
* using the gzip options which uses a different mechanism with streams and stuff).</li>
* <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some
* similar helper methods to be more efficient with memory by not returning a
* String but just a byte array.</li>
* <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments
* and bug fixes queued up and finally executed. Thanks to everyone who sent
* me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else.
* Much bad coding was cleaned up including throwing exceptions where necessary
* instead of returning null values or something similar. Here are some changes
* that may affect you:
* <ul>
* <li><em>Does not break lines, by default.</em> This is to keep in compliance with
* <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li>
* <li><em>Throws exceptions instead of returning null values.</em> Because some operations
* (especially those that may permit the GZIP option) use IO streams, there
* is a possiblity of an java.io.IOException being thrown. After some discussion and
* thought, I've changed the behavior of the methods to throw java.io.IOExceptions
* rather than return null if ever there's an error. I think this is more
* appropriate, though it will require some changes to your code. Sorry,
* it should have been done this way to begin with.</li>
* <li><em>Removed all references to System.out, System.err, and the like.</em>
* Shame on me. All I can say is sorry they were ever there.</li>
* <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed
* such as when passed arrays are null or offsets are invalid.</li>
* <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings.
* This was especially annoying before for people who were thorough in their
* own projects and then had gobs of javadoc warnings on this file.</li>
* </ul>
* <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug
* when using very small files (~< 40 bytes).</li>
* <li>v2.2 - Added some helper methods for encoding/decoding directly from
* one file to the next. Also added a main() method to support command line
* encoding/decoding from one file to the next. Also added these Base64 dialects:
* <ol>
* <li>The default is RFC3548 format.</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
* URL and file name friendly format as described in Section 4 of RFC3548.
* http://www.faqs.org/rfcs/rfc3548.html</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
* URL and file name friendly format that preserves lexical ordering as described
* in http://www.faqs.org/qa/rfcc-1940.html</li>
* </ol>
* Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
* for contributing the new Base64 dialects.
* </li>
*
* <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
* some convenience methods for reading and writing to and from files.</li>
* <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
* with other encodings (like EBCDIC).</li>
* <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
* encoded data was a single byte.</li>
* <li>v2.0 - I got rid of methods that used booleans to set options.
* Now everything is more consolidated and cleaner. The code now detects
* when data that's being decoded is gzip-compressed and will decompress it
* automatically. Generally things are cleaner. You'll probably have to
* change some method calls that you were making to support the new
* options format (<tt>int</tt>s that you "OR" together).</li>
* <li>v1.5.1 - Fixed bug when decompressing and decoding to a
* byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
* Added the ability to "suspend" encoding in the Output Stream so
* you can turn on and off the encoding if you need to embed base64
* data in an otherwise "normal" stream (like an XML file).</li>
* <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
* This helps when using GZIP streams.
* Added the ability to GZip-compress objects before encoding them.</li>
* <li>v1.4 - Added helper methods to read/write files.</li>
* <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
* <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
* where last buffer being read, if not completely full, was not returned.</li>
* <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
* <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
* </ul>
*
* <p>
* I am placing this code in the Public Domain. Do with it as you will.
* This software comes with no guarantees or warranties but with
* plenty of well-wishing instead!
* Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
* periodically to check for updates or to contribute improvements.
* </p>
*
* @author Robert Harder
* @author [email protected]
* @version 2.3.7
*/
public class Base64
{
/* ******** P U B L I C F I E L D S ******** */
/** No options specified. Value is zero. */
public final static int NO_OPTIONS = 0;
/** Specify encoding in first bit. Value is one. */
public final static int ENCODE = 1;
/** Specify decoding in first bit. Value is zero. */
public final static int DECODE = 0;
/** Specify that data should be gzip-compressed in second bit. Value is two. */
public final static int GZIP = 2;
/** Specify that gzipped data should <em>not</em> be automatically gunzipped. */
public final static int DONT_GUNZIP = 4;
/** Do break lines when encoding. Value is 8. */
public final static int DO_BREAK_LINES = 8;
/**
* Encode using Base64-like encoding that is URL- and Filename-safe as described
* in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* It is important to note that data encoded this way is <em>not</em> officially valid Base64,
* or at the very least should not be called Base64 without also specifying that is
* was encoded using the URL- and Filename-safe dialect.
*/
public final static int URL_SAFE = 16;
/**
* Encode using the special "ordered" dialect of Base64 described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
public final static int ORDERED = 32;
/* ******** P R I V A T E F I E L D S ******** */
/** Maximum line length (76) of Base64 output. */
private final static int MAX_LINE_LENGTH = 76;
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte)'=';
/** The new line character (\n) as a byte. */
private final static byte NEW_LINE = (byte)'\n';
/** Preferred encoding. */
private final static String PREFERRED_ENCODING = "US-ASCII";
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
/** The 64 valid Base64 values. */
/* Host platform me be something funny like EBCDIC, so we hardcode these values. */
private final static byte[] _STANDARD_ALPHABET = {
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
};
/**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
**/
private final static byte[] _STANDARD_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9,-9,-9, // Decimal 44 - 46
63, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9,-9,-9, // Decimal 91 - 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9,-9 // Decimal 123 - 127
,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
};
/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
/**
* Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
*/
private final static byte[] _URL_SAFE_ALPHABET = {
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_'
};
/**
* Used in decoding URL- and Filename-safe dialects of Base64.
*/
private final static byte[] _URL_SAFE_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
62, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9, // Decimal 91 - 94
63, // Underscore at decimal 95
-9, // Decimal 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9,-9 // Decimal 123 - 127
,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
};
/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
/**
* I don't get the point of this technique, but someone requested it,
* and it is described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
private final static byte[] _ORDERED_ALPHABET = {
(byte)'-',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',
(byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'_',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z'
};
/**
* Used in decoding the "ordered" dialect of Base64.
*/
private final static byte[] _ORDERED_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
0, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M'
24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z'
-9,-9,-9,-9, // Decimal 91 - 94
37, // Underscore at decimal 95
-9, // Decimal 96
38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm'
51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z'
-9,-9,-9,-9,-9 // Decimal 123 - 127
,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
};
/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
/**
* Returns one of the _SOMETHING_ALPHABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getAlphabet( int options ) {
if ((options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_ALPHABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_ALPHABET;
} else {
return _STANDARD_ALPHABET;
}
} // end getAlphabet
/**
* Returns one of the _SOMETHING_DECODABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED and URL_SAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getDecodabet( int options ) {
if( (options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_DECODABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_DECODABET;
} else {
return _STANDARD_DECODABET;
}
} // end getAlphabet
/** Defeats instantiation. */
private Base64(){}
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* Encodes up to the first three bytes of array <var>threeBytes</var>
* and returns a four-byte array in Base64 notation.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.
* The array <var>threeBytes</var> needs only be as big as
* <var>numSigBytes</var>.
* Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
*
* @param b4 A reusable byte array to reduce array instantiation
* @param threeBytes the array to convert
* @param numSigBytes the number of significant bytes in your array
* @return four byte array in Base64 notation.
* @since 1.5.1
*/
private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) {
encode3to4( threeBytes, 0, numSigBytes, b4, 0, options );
return b4;
} // end encode3to4
/**
* <p>Encodes up to three bytes of the array <var>source</var>
* and writes the resulting four Base64 bytes to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 3 for
* the <var>source</var> array or <var>destOffset</var> + 4 for
* the <var>destination</var> array.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.</p>
* <p>This is the lowest level of the encoding methods with
* all possible parameters.</p>
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param numSigBytes the number of significant bytes in your array
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(
byte[] source, int srcOffset, int numSigBytes,
byte[] destination, int destOffset, int options ) {
byte[] ALPHABET = getAlphabet( options );
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
| ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
| ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
switch( numSigBytes )
{
case 3:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
return destination;
case 2:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
case 1:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = EQUALS_SIGN;
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
} // end encode3to4
/**
* Performs Base64 encoding on the <code>raw</code> ByteBuffer,
* writing it to the <code>encoded</code> ByteBuffer.
* This is an experimental feature. Currently it does not
* pass along any options (such as {@link #DO_BREAK_LINES}
* or {@link #GZIP}.
*
* @param raw input buffer
* @param encoded output buffer
* @since 2.3
*/
public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){
byte[] raw3 = new byte[3];
byte[] enc4 = new byte[4];
while( raw.hasRemaining() ){
int rem = Math.min(3,raw.remaining());
raw.get(raw3,0,rem);
Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
encoded.put(enc4);
} // end input remaining
}
/**
* Performs Base64 encoding on the <code>raw</code> ByteBuffer,
* writing it to the <code>encoded</code> CharBuffer.
* This is an experimental feature. Currently it does not
* pass along any options (such as {@link #DO_BREAK_LINES}
* or {@link #GZIP}.
*
* @param raw input buffer
* @param encoded output buffer
* @since 2.3
*/
public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){
byte[] raw3 = new byte[3];
byte[] enc4 = new byte[4];
while( raw.hasRemaining() ){
int rem = Math.min(3,raw.remaining());
raw.get(raw3,0,rem);
Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
for( int i = 0; i < 4; i++ ){
encoded.put( (char)(enc4[i] & 0xFF) );
}
} // end input remaining
}
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object.
*
* <p>As of v 2.3, if the object
* cannot be serialized or there is another error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* The object is not GZip-compressed before being encoded.
*
* @param serializableObject The object to encode
* @return The Base64-encoded object
* @throws java.io.IOException if there is an error
* @throws NullPointerException if serializedObject is null
* @since 1.4
*/
public static String encodeObject( java.io.Serializable serializableObject )
throws java.io.IOException {
return encodeObject( serializableObject, NO_OPTIONS );
} // end encodeObject
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object.
*
* <p>As of v 2.3, if the object
* cannot be serialized or there is another error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* The object is not GZip-compressed before being encoded.
* <p>
* Example options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* </pre>
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
* @param serializableObject The object to encode
* @param options Specified options
* @return The Base64-encoded object
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @since 2.0
*/
public static String encodeObject( java.io.Serializable serializableObject, int options )
throws java.io.IOException {
if( serializableObject == null ){
throw new NullPointerException( "Cannot serialize a null object." );
} // end if: null
// Streams
java.io.ByteArrayOutputStream baos = null;
java.io.OutputStream b64os = null;
java.util.zip.GZIPOutputStream gzos = null;
java.io.ObjectOutputStream oos = null;
try {
// ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | options );
if( (options & GZIP) != 0 ){
// Gzip
gzos = new java.util.zip.GZIPOutputStream(b64os);
oos = new java.io.ObjectOutputStream( gzos );
} else {
// Not gzipped
oos = new java.io.ObjectOutputStream( b64os );
}
oos.writeObject( serializableObject );
} // end try
catch( java.io.IOException e ) {
// Catch it and then throw it immediately so that
// the finally{} block is called for cleanup.
throw e;
} // end catch
finally {
try{ oos.close(); } catch( Exception e ){}
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
// Return value according to relevant encoding.
try {
return new String( baos.toByteArray(), PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue){
// Fall back to some Java default
return new String( baos.toByteArray() );
} // end catch
} // end encode
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* @param source The data to convert
* @return The data in Base64-encoded form
* @throws NullPointerException if source array is null
* @since 1.4
*/
public static String encodeBytes( byte[] source ) {
// Since we're not going to have the GZIP encoding turned on,
// we're not going to have an java.io.IOException thrown, so
// we should not force the user to have to catch it.
String encoded = null;
try {
encoded = encodeBytes(source, 0, source.length, NO_OPTIONS);
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
} // end catch
assert encoded != null;
return encoded;
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Example options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
*
* <p>As of v 2.3, if there is an error with the GZIP stream,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
*
* @param source The data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @since 2.0
*/
public static String encodeBytes( byte[] source, int options ) throws java.io.IOException {
return encodeBytes( source, 0, source.length, options );
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* <p>As of v 2.3, if there is an error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @return The Base64-encoded data as a String
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 1.4
*/
public static String encodeBytes( byte[] source, int off, int len ) {
// Since we're not going to have the GZIP encoding turned on,
// we're not going to have an java.io.IOException thrown, so
// we should not force the user to have to catch it.
String encoded = null;
try {
encoded = encodeBytes( source, off, len, NO_OPTIONS );
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
} // end catch
assert encoded != null;
return encoded;
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Example options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
*
* <p>As of v 2.3, if there is an error with the GZIP stream,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 2.0
*/
public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
byte[] encoded = encodeBytesToBytes( source, off, len, options );
// Return value according to relevant encoding.
try {
return new String( encoded, PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue) {
return new String( encoded );
} // end catch
} // end encodeBytes
/**
* Similar to {@link #encodeBytes(byte[])} but returns
* a byte array instead of instantiating a String. This is more efficient
* if you're working with I/O streams and have large data sets to encode.
*
*
* @param source The data to convert
* @return The Base64-encoded data as a byte[] (of ASCII characters)
* @throws NullPointerException if source array is null
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes( byte[] source ) {
byte[] encoded = null;
try {
encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS );
} catch( java.io.IOException ex ) {
assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
}
return encoded;
}
/**
* Similar to {@link #encodeBytes(byte[], int, int, int)} but returns
* a byte array instead of instantiating a String. This is more efficient
* if you're working with I/O streams and have large data sets to encode.
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
if( source == null ){
throw new NullPointerException( "Cannot serialize a null array." );
} // end if: null
if( off < 0 ){
throw new IllegalArgumentException( "Cannot have negative offset: " + off );
} // end if: off < 0
if( len < 0 ){
throw new IllegalArgumentException( "Cannot have length offset: " + len );
} // end if: len < 0
if( off + len > source.length ){
throw new IllegalArgumentException(
String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length));
} // end if: off < 0
// Compress?
if( (options & GZIP) != 0 ) {
java.io.ByteArrayOutputStream baos = null;
java.util.zip.GZIPOutputStream gzos = null;
Base64.OutputStream b64os = null;
try {
// GZip -> Base64 -> ByteArray
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | options );
gzos = new java.util.zip.GZIPOutputStream( b64os );
gzos.write( source, off, len );
gzos.close();
} // end try
catch( java.io.IOException e ) {
// Catch it and then throw it immediately so that
// the finally{} block is called for cleanup.
throw e;
} // end catch
finally {
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
return baos.toByteArray();
} // end if: compress
// Else, don't compress. Better not to use streams at all then.
else {
boolean breakLines = (options & DO_BREAK_LINES) != 0;
//int len43 = len * 4 / 3;
//byte[] outBuff = new byte[ ( len43 ) // Main 4:3
// + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
// + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
// Try to determine more precisely how big the array needs to be.
// If we get it right, we don't have to do an array copy, and
// we save a bunch of memory.
int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding
if( breakLines ){
encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters
}
byte[] outBuff = new byte[ encLen ];
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for( ; d < len2; d+=3, e+=4 ) {
encode3to4( source, d+off, 3, outBuff, e, options );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH )
{
outBuff[e+4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if( d < len ) {
encode3to4( source, d+off, len - d, outBuff, e, options );
e += 4;
} // end if: some padding needed
// Only resize array if we didn't guess it right.
if( e <= outBuff.length - 1 ){
// If breaking lines and the last byte falls right at
// the line length (76 bytes per line), there will be
// one extra byte, and the array will need to be resized.
// Not too bad of an estimate on array size, I'd say.
byte[] finalOut = new byte[e];
System.arraycopy(outBuff,0, finalOut,0,e);
//System.err.println("Having to resize array from " + outBuff.length + " to " + e );
return finalOut;
} else {
//System.err.println("No need to resize array.");
return outBuff;
}
} // end else: don't compress
} // end encodeBytesToBytes
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* Decodes four bytes from array <var>source</var>
* and writes the resulting bytes (up to three of them)
* to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 4 for
* the <var>source</var> array or <var>destOffset</var> + 3 for
* the <var>destination</var> array.
* This method returns the actual number of bytes that
* were converted from the Base64 encoding.
* <p>This is the lowest level of the decoding methods with
* all possible parameters.</p>
*
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @param options alphabet type is pulled from this (standard, url-safe, ordered)
* @return the number of decoded bytes converted
* @throws NullPointerException if source or destination arrays are null
* @throws IllegalArgumentException if srcOffset or destOffset are invalid
* or there is not enough room in the array.
* @since 1.3
*/
private static int decode4to3(
byte[] source, int srcOffset,
byte[] destination, int destOffset, int options ) {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Source array was null." );
} // end if
if( destination == null ){
throw new NullPointerException( "Destination array was null." );
} // end if
if( srcOffset < 0 || srcOffset + 3 >= source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) );
} // end if
if( destOffset < 0 || destOffset +2 >= destination.length ){
throw new IllegalArgumentException( String.format(
"Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) );
} // end if
byte[] DECODABET = getDecodabet( options );
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}
} // end decodeToBytes
/**
* Low-level access to decoding ASCII characters in
* the form of a byte array. <strong>Ignores GUNZIP option, if
* it's set.</strong> This is not generally a recommended method,
* although it is used internally as part of the decoding process.
* Special case: if len = 0, an empty array is returned. Still,
* if you need more speed and reduced memory footprint (and aren't
* gzipping), consider this method.
*
* @param source The Base64 encoded data
* @return decoded data
* @since 2.3.1
*/
public static byte[] decode( byte[] source )
throws java.io.IOException {
byte[] decoded = null;
// try {
decoded = decode( source, 0, source.length, Base64.NO_OPTIONS );
// } catch( java.io.IOException ex ) {
// assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
// }
return decoded;
}
/**
* Low-level access to decoding ASCII characters in
* the form of a byte array. <strong>Ignores GUNZIP option, if
* it's set.</strong> This is not generally a recommended method,
* although it is used internally as part of the decoding process.
* Special case: if len = 0, an empty array is returned. Still,
* if you need more speed and reduced memory footprint (and aren't
* gzipping), consider this method.
*
* @param source The Base64 encoded data
* @param off The offset of where to begin decoding
* @param len The length of characters to decode
* @param options Can specify options such as alphabet type to use
* @return decoded data
* @throws java.io.IOException If bogus characters exist in source data
* @since 1.3
*/
public static byte[] decode( byte[] source, int off, int len, int options )
throws java.io.IOException {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Cannot decode null source array." );
} // end if
if( off < 0 || off + len > source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) );
} // end if
if( len == 0 ){
return new byte[0];
}else if( len < 4 ){
throw new IllegalArgumentException(
"Base64-encoded string must have at least four characters, but length specified was " + len );
} // end if
byte[] DECODABET = getDecodabet( options );
int len34 = len * 3 / 4; // Estimate on array size
byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
int outBuffPosn = 0; // Keep track of where we're writing
byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space
int b4Posn = 0; // Keep track of four byte input buffer
int i = 0; // Source array counter
byte sbiDecode = 0; // Special value from DECODABET
for( i = off; i < off+len; i++ ) { // Loop through source
sbiDecode = DECODABET[ source[i]&0xFF ];
// White space, Equals sign, or legit Base64 character
// Note the values such as -5 and -9 in the
// DECODABETs at the top of the file.
if( sbiDecode >= WHITE_SPACE_ENC ) {
if( sbiDecode >= EQUALS_SIGN_ENC ) {
b4[ b4Posn++ ] = source[i]; // Save non-whitespace
if( b4Posn > 3 ) { // Time to decode?
outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if( source[i] == EQUALS_SIGN ) {
break;
} // end if: equals sign
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else {
// There's a bad input character in the Base64 stream.
throw new java.io.IOException( String.format(
"Bad Base64 input character decimal %d in array position %d", ((int)source[i])&0xFF, i ) );
} // end else:
} // each input character
byte[] out = new byte[ outBuffPosn ];
System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
return out;
} // end decode
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @return the decoded data
* @throws java.io.IOException If there is a problem
* @since 1.4
*/
public static byte[] decode( String s ) throws java.io.IOException {
return decode( s, NO_OPTIONS );
}
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @param options encode options such as URL_SAFE
* @return the decoded data
* @throws java.io.IOException if there is an error
* @throws NullPointerException if <tt>s</tt> is null
* @since 1.4
*/
public static byte[] decode( String s, int options ) throws java.io.IOException {
if( s == null ){
throw new NullPointerException( "Input string was null." );
} // end if
byte[] bytes;
try {
bytes = s.getBytes( PREFERRED_ENCODING );
} // end try
catch( java.io.UnsupportedEncodingException uee ) {
bytes = s.getBytes();
} // end catch
//</change>
// Decode
bytes = decode( bytes, 0, bytes.length, options );
// Check to see if it's gzip-compressed
// GZIP Magic Two-Byte Number: 0x8b1f (35615)
boolean dontGunzip = (options & DONT_GUNZIP) != 0;
if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) {
int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) {
java.io.ByteArrayInputStream bais = null;
java.util.zip.GZIPInputStream gzis = null;
java.io.ByteArrayOutputStream baos = null;
byte[] buffer = new byte[2048];
int length = 0;
try {
baos = new java.io.ByteArrayOutputStream();
bais = new java.io.ByteArrayInputStream( bytes );
gzis = new java.util.zip.GZIPInputStream( bais );
while( ( length = gzis.read( buffer ) ) >= 0 ) {
baos.write(buffer,0,length);
} // end while: reading input
// No error? Get new bytes.
bytes = baos.toByteArray();
} // end try
catch( java.io.IOException e ) {
e.printStackTrace();
// Just return originally-decoded bytes
} // end catch
finally {
try{ baos.close(); } catch( Exception e ){}
try{ gzis.close(); } catch( Exception e ){}
try{ bais.close(); } catch( Exception e ){}
} // end finally
} // end if: gzipped
} // end if: bytes.length >= 2
return bytes;
} // end decode
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <tt>null</tt> if there was an error.
*
* @param encodedObject The Base64 data to decode
* @return The decoded and deserialized object
* @throws NullPointerException if encodedObject is null
* @throws java.io.IOException if there is a general error
* @throws ClassNotFoundException if the decoded object is of a
* class that cannot be found by the JVM
* @since 1.5
*/
public static Object decodeToObject( String encodedObject )
throws java.io.IOException, java.lang.ClassNotFoundException {
return decodeToObject(encodedObject,NO_OPTIONS,null);
}
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <tt>null</tt> if there was an error.
* If <tt>loader</tt> is not null, it will be the class loader
* used when deserializing.
*
* @param encodedObject The Base64 data to decode
* @param options Various parameters related to decoding
* @param loader Optional class loader to use in deserializing classes.
* @return The decoded and deserialized object
* @throws NullPointerException if encodedObject is null
* @throws java.io.IOException if there is a general error
* @throws ClassNotFoundException if the decoded object is of a
* class that cannot be found by the JVM
* @since 2.3.4
*/
@SuppressWarnings("all")
public static Object decodeToObject(
String encodedObject, int options, final ClassLoader loader )
throws java.io.IOException, java.lang.ClassNotFoundException {
// Decode and gunzip if necessary
byte[] objBytes = decode( encodedObject, options );
java.io.ByteArrayInputStream bais = null;
java.io.ObjectInputStream ois = null;
Object obj = null;
try {
bais = new java.io.ByteArrayInputStream( objBytes );
// If no custom class loader is provided, use Java's builtin OIS.
if( loader == null ){
ois = new java.io.ObjectInputStream( bais );
} // end if: no loader provided
// Else make a customized object input stream that uses
// the provided class loader.
else {
ois = new java.io.ObjectInputStream(bais){
@Override
public Class<?> resolveClass(java.io.ObjectStreamClass streamClass)
throws java.io.IOException, ClassNotFoundException {
Class c = Class.forName(streamClass.getName(), false, loader);
if( c == null ){
return super.resolveClass(streamClass);
} else {
return c; // Class loader knows of this class.
} // end else: not null
} // end resolveClass
}; // end ois
} // end else: no custom class loader
obj = ois.readObject();
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
catch( java.lang.ClassNotFoundException e ) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
finally {
try{ bais.close(); } catch( Exception e ){}
try{ ois.close(); } catch( Exception e ){}
} // end finally
return obj;
} // end decodeObject
/**
* Convenience method for encoding data to a file.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param dataToEncode byte array of data to encode in base64 form
* @param filename Filename for saving encoded data
* @throws java.io.IOException if there is an error
* @throws NullPointerException if dataToEncode is null
* @since 2.1
*/
public static void encodeToFile( byte[] dataToEncode, String filename )
throws java.io.IOException {
if( dataToEncode == null ){
throw new NullPointerException( "Data to encode was null." );
} // end iff
Base64.OutputStream bos = null;
try {
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.ENCODE );
bos.write( dataToEncode );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw to execute finally{} block
} // end catch: java.io.IOException
finally {
try{ bos.close(); } catch( Exception e ){}
} // end finally
} // end encodeToFile
/**
* Convenience method for decoding data to a file.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param dataToDecode Base64-encoded data as a string
* @param filename Filename for saving decoded data
* @throws java.io.IOException if there is an error
* @since 2.1
*/
public static void decodeToFile( String dataToDecode, String filename )
throws java.io.IOException {
Base64.OutputStream bos = null;
try{
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.DECODE );
bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw to execute finally{} block
} // end catch: java.io.IOException
finally {
try{ bos.close(); } catch( Exception e ){}
} // end finally
} // end decodeToFile
/**
* Convenience method for reading a base64-encoded
* file and decoding it.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param filename Filename for reading encoded data
* @return decoded byte array
* @throws java.io.IOException if there is an error
* @since 2.1
*/
public static byte[] decodeFromFile( String filename )
throws java.io.IOException {
byte[] decodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = null;
int length = 0;
int numBytes = 0;
// Check for size of file
if( file.length() > Integer.MAX_VALUE )
{
throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." );
} // end if: file too big for int index
buffer = new byte[ (int)file.length() ];
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.DECODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
length += numBytes;
} // end while
// Save in a variable to return
decodedData = new byte[ length ];
System.arraycopy( buffer, 0, decodedData, 0, length );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try{ bis.close(); } catch( Exception e) {}
} // end finally
return decodedData;
} // end decodeFromFile
/**
* Convenience method for reading a binary file
* and base64-encoding it.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param filename Filename for reading binary data
* @return base64-encoded string
* @throws java.io.IOException if there is an error
* @since 2.1
*/
public static String encodeFromFile( String filename )
throws java.io.IOException {
String encodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4+1),40) ]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5)
int length = 0;
int numBytes = 0;
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.ENCODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
length += numBytes;
} // end while
// Save in a variable to return
encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try{ bis.close(); } catch( Exception e) {}
} // end finally
return encodedData;
} // end encodeFromFile
/**
* Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
*
* @param infile Input file
* @param outfile Output file
* @throws java.io.IOException if there is an error
* @since 2.2
*/
public static void encodeFileToFile( String infile, String outfile )
throws java.io.IOException {
String encoded = Base64.encodeFromFile( infile );
java.io.OutputStream out = null;
try{
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream( outfile ) );
out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output.
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try { out.close(); }
catch( Exception ex ){}
} // end finally
} // end encodeFileToFile
/**
* Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
*
* @param infile Input file
* @param outfile Output file
* @throws java.io.IOException if there is an error
* @since 2.2
*/
public static void decodeFileToFile( String infile, String outfile )
throws java.io.IOException {
byte[] decoded = Base64.decodeFromFile( infile );
java.io.OutputStream out = null;
try{
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream( outfile ) );
out.write( decoded );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try { out.close(); }
catch( Exception ex ){}
} // end finally
} // end decodeFileToFile
/* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
/**
* A {@link Base64.InputStream} will read data from another
* <tt>java.io.InputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class InputStream extends java.io.FilterInputStream {
private boolean encode; // Encoding or decoding
private int position; // Current position in the buffer
private byte[] buffer; // Small buffer holding converted data
private int bufferLength; // Length of buffer (3 or 4)
private int numSigBytes; // Number of meaningful bytes in the buffer
private int lineLength;
private boolean breakLines; // Break lines at less than 80 characters
private int options; // Record options used to create the stream.
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.InputStream} in DECODE mode.
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @since 1.3
*/
public InputStream( java.io.InputStream in ) {
this( in, DECODE );
} // end constructor
/**
* Constructs a {@link Base64.InputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DO_BREAK_LINES: break lines at 76 characters
* (only meaningful when encoding)</i>
* </pre>
* <p>
* Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
*
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @param options Specified options
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DO_BREAK_LINES
* @since 2.0
*/
public InputStream( java.io.InputStream in, int options ) {
super( in );
this.options = options; // Record for later
this.breakLines = (options & DO_BREAK_LINES) > 0;
this.encode = (options & ENCODE) > 0;
this.bufferLength = encode ? 4 : 3;
this.buffer = new byte[ bufferLength ];
this.position = -1;
this.lineLength = 0;
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Reads enough of the input stream to convert
* to/from Base64 and returns the next byte.
*
* @return next byte
* @since 1.3
*/
@Override
public int read() throws java.io.IOException {
// Do we need to get data?
if( position < 0 ) {
if( encode ) {
byte[] b3 = new byte[3];
int numBinaryBytes = 0;
for( int i = 0; i < 3; i++ ) {
int b = in.read();
// If end of stream, b is -1.
if( b >= 0 ) {
b3[i] = (byte)b;
numBinaryBytes++;
} else {
break; // out of for loop
} // end else: end of stream
} // end for: each needed input byte
if( numBinaryBytes > 0 ) {
encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
position = 0;
numSigBytes = 4;
} // end if: got data
else {
return -1; // Must be end of stream
} // end else
} // end if: encoding
// Else decoding
else {
byte[] b4 = new byte[4];
int i = 0;
for( i = 0; i < 4; i++ ) {
// Read four "meaningful" bytes:
int b = 0;
do{ b = in.read(); }
while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
if( b < 0 ) {
break; // Reads a -1 if end of stream
} // end if: end of stream
b4[i] = (byte)b;
} // end for: each needed input byte
if( i == 4 ) {
numSigBytes = decode4to3( b4, 0, buffer, 0, options );
position = 0;
} // end if: got four characters
else if( i == 0 ){
return -1;
} // end else if: also padded correctly
else {
// Must have broken out from above.
throw new java.io.IOException( "Improperly padded Base64 input." );
} // end
} // end else: decode
} // end else: get data
// Got data?
if( position >= 0 ) {
// End of relevant data?
if( /*!encode &&*/ position >= numSigBytes ){
return -1;
} // end if: got data
if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) {
lineLength = 0;
return '\n';
} // end if
else {
lineLength++; // This isn't important when decoding
// but throwing an extra "if" seems
// just as wasteful.
int b = buffer[ position++ ];
if( position >= bufferLength ) {
position = -1;
} // end if: end
return b & 0xFF; // This is how you "cast" a byte that's
// intended to be unsigned.
} // end else
} // end if: position >= 0
// Else error
else {
throw new java.io.IOException( "Error in Base64 code reading stream." );
} // end else
} // end read
/**
* Calls {@link #read()} repeatedly until the end of stream
* is reached or <var>len</var> bytes are read.
* Returns number of bytes read into array or -1 if
* end of stream is encountered.
*
* @param dest array to hold values
* @param off offset for array
* @param len max number of bytes to read into array
* @return bytes read into array or -1 if end of stream is encountered.
* @since 1.3
*/
@Override
public int read( byte[] dest, int off, int len )
throws java.io.IOException {
int i;
int b;
for( i = 0; i < len; i++ ) {
b = read();
if( b >= 0 ) {
dest[off + i] = (byte) b;
}
else if( i == 0 ) {
return -1;
}
else {
break; // Out of 'for' loop
} // Out of 'for' loop
} // end for: each byte read
return i;
} // end read
} // end inner class InputStream
/* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
/**
* A {@link Base64.OutputStream} will write data to another
* <tt>java.io.OutputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class OutputStream extends java.io.FilterOutputStream {
private boolean encode;
private int position;
private byte[] buffer;
private int bufferLength;
private int lineLength;
private boolean breakLines;
private byte[] b4; // Scratch used in a few places
private boolean suspendEncoding;
private int options; // Record for later
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.OutputStream} in ENCODE mode.
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @since 1.3
*/
public OutputStream( java.io.OutputStream out ) {
this( out, ENCODE );
} // end constructor
/**
* Constructs a {@link Base64.OutputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DO_BREAK_LINES: don't break lines at 76 characters
* (only meaningful when encoding)</i>
* </pre>
* <p>
* Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @param options Specified options.
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DO_BREAK_LINES
* @since 1.3
*/
public OutputStream( java.io.OutputStream out, int options ) {
super( out );
this.breakLines = (options & DO_BREAK_LINES) != 0;
this.encode = (options & ENCODE) != 0;
this.bufferLength = encode ? 3 : 4;
this.buffer = new byte[ bufferLength ];
this.position = 0;
this.lineLength = 0;
this.suspendEncoding = false;
this.b4 = new byte[4];
this.options = options;
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Writes the byte to the output stream after
* converting to/from Base64 notation.
* When encoding, bytes are buffered three
* at a time before the output stream actually
* gets a write() call.
* When decoding, bytes are buffered four
* at a time.
*
* @param theByte the byte to write
* @since 1.3
*/
@Override
public void write(int theByte)
throws java.io.IOException {
// Encoding suspended?
if( suspendEncoding ) {
this.out.write( theByte );
return;
} // end if: supsended
// Encode?
if( encode ) {
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) { // Enough to encode.
this.out.write( encode3to4( b4, buffer, bufferLength, options ) );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH ) {
this.out.write( NEW_LINE );
lineLength = 0;
} // end if: end of line
position = 0;
} // end if: enough to output
} // end if: encoding
// Else, Decoding
else {
// Meaningful Base64 character?
if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) {
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) { // Enough to output.
int len = Base64.decode4to3( buffer, 0, b4, 0, options );
out.write( b4, 0, len );
position = 0;
} // end if: enough to output
} // end if: meaningful base64 character
else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) {
throw new java.io.IOException( "Invalid character in Base64 data." );
} // end else: not white space either
} // end else: decoding
} // end write
/**
* Calls {@link #write(int)} repeatedly until <var>len</var>
* bytes are written.
*
* @param theBytes array from which to read bytes
* @param off offset for array
* @param len max number of bytes to read into array
* @since 1.3
*/
@Override
public void write( byte[] theBytes, int off, int len )
throws java.io.IOException {
// Encoding suspended?
if( suspendEncoding ) {
this.out.write( theBytes, off, len );
return;
} // end if: supsended
for( int i = 0; i < len; i++ ) {
write( theBytes[ off + i ] );
} // end for: each byte written
} // end write
/**
* Method added by PHIL. [Thanks, PHIL. -Rob]
* This pads the buffer without closing the stream.
* @throws java.io.IOException if there's an error.
*/
public void flushBase64() throws java.io.IOException {
if( position > 0 ) {
if( encode ) {
out.write( encode3to4( b4, buffer, position, options ) );
position = 0;
} // end if: encoding
else {
throw new java.io.IOException( "Base64 input not properly padded." );
} // end else: decoding
} // end if: buffer partially full
} // end flush
/**
* Flushes and closes (I think, in the superclass) the stream.
*
* @since 1.3
*/
@Override
public void close() throws java.io.IOException {
// 1. Ensure that pending characters are written
flushBase64();
// 2. Actually close the stream
// Base class both flushes and closes.
super.close();
buffer = null;
out = null;
} // end close
/**
* Suspends encoding of the stream.
* May be helpful if you need to embed a piece of
* base64-encoded data in a stream.
*
* @throws java.io.IOException if there's an error flushing
* @since 1.5.1
*/
public void suspendEncoding() throws java.io.IOException {
flushBase64();
this.suspendEncoding = true;
} // end suspendEncoding
/**
* Resumes encoding of the stream.
* May be helpful if you need to embed a piece of
* base64-encoded data in a stream.
*
* @since 1.5.1
*/
public void resumeEncoding() {
this.suspendEncoding = false;
} // end resumeEncoding
} // end inner class OutputStream
} // end class Base64
| 86,946 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Logger.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Logger.java | /*
* see license.txt
*/
package seventh.shared;
/**
* @author Tony
*
*/
public interface Logger {
/**
* @param msg
*/
public void print(Object msg);
/**
* @param msg
*/
public void println(Object msg);
/**
* @param msg
* @param args
*/
public void printf(Object msg, Object ...args );
}
| 371 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Arrays.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/Arrays.java | /*
* see license.txt
*/
package seventh.shared;
import java.util.Comparator;
/**
* Simple array utilities
*
* @author Tony
*
*/
public class Arrays {
/**
* Counts the amount of used elements in the array
*
* @param array
* @return the sum of used elements in the array
*/
public static <T> int usedLength(T[] array) {
int sum = 0;
if (array != null) {
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
sum++;
}
}
}
return sum;
}
/**
* Clears out the array, null'ing out all elements
*
* @param array
*/
public static <T> void clear(T[] array) {
if (array != null) {
for (int i = 0; i < array.length; i++) {
array[i] = null;
}
}
}
/**
* Sorts the supplied array by the {@link Comparator}
*
* @param array
* @param comp
* @return the supplied array
*/
public static <T> T[] sort(T[] array, Comparator<T> comp) {
if (array == null || array.length == 0) {
return array;
}
quicksort(array, comp, 0, array.length - 1);
return array;
}
private static <T> void quicksort(T[] array, Comparator<T> comp, int low, int high) {
int i = low;
int j = high;
T pivot = array[low + (high - low) / 2];
while (i <= j) {
while (comp.compare(array[i], pivot) < 0) {
i++;
}
while (comp.compare(array[j], pivot) > 0) {
j--;
}
if (i <= j) {
swap(array, i, j);
i++;
j--;
}
}
if (low < j) {
quicksort(array, comp, low, j);
}
if (i < high) {
quicksort(array, comp, i, high);
}
}
private static <T> void swap(T[] array, int i, int j) {
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
| 2,115 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
EaseInInterpolation.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/EaseInInterpolation.java | /*
* see license.txt
*/
package seventh.shared;
/**
* @author Tony
*
*/
public class EaseInInterpolation implements Updatable {
private float value;
private float target;
private float speed, acceleration;
private long totalTime;
private long remainingTime;
public EaseInInterpolation() {
}
/**
* @param from
* @param to
* @param time
*/
public EaseInInterpolation(float from, float to, long time) {
reset(from, to, time);
}
/**
* Resets this interpolation
*
* @param from
* @param to
* @param time
*/
public void reset(float from, float to, long time) {
if(time > 0) {
this.value = from;
this.target = to;
this.speed = 0f;
float timeSq = (time/1000.0f) * (time/1000.0f);
this.acceleration = (to-from) / (timeSq/4);
this.remainingTime = this.totalTime = time;
}
}
/* (non-Javadoc)
* @see seventh.shared.Updatable#update(seventh.shared.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
this.remainingTime -= timeStep.getDeltaTime();
if(this.remainingTime > 0) {
if(this.remainingTime < this.totalTime/2) {
this.speed -= this.acceleration * timeStep.asFraction();
}
else {
this.speed += this.acceleration * timeStep.asFraction();
}
this.value += this.speed * timeStep.asFraction();
}
}
/**
* @return if there is any time remaining
*/
public boolean isExpired() {
return this.remainingTime <= 0;
}
/**
* @return the remainingTime
*/
public long getRemainingTime() {
return remainingTime;
}
/**
* @return the value
*/
public float getValue() {
return value;
}
/**
* @return the target
*/
public float getTarget() {
return target;
}
}
| 2,116 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ServerInfo.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/ServerInfo.java | /*
* see license.txt
*/
package seventh.shared;
import java.util.ArrayList;
import java.util.List;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoUserFunction;
import seventh.game.Player;
import seventh.game.Team;
import seventh.game.game_types.GameType;
import seventh.server.GameSession;
import seventh.server.ServerContext;
import seventh.server.ServerSeventhConfig;
/**
* Server information for finding a game
*
* @author Tony
*
*/
public class ServerInfo {
private String address;
private int port;
private String serverName;
private String gameType;
private String mapName;
private List<String> axis, allies;
/**
* @param obj
*/
public ServerInfo(LeoObject obj) {
this.axis = new ArrayList<>();
this.allies = new ArrayList<>();
parseEntry(obj);
}
/**
* @param context
*/
public ServerInfo(ServerContext context) {
/*
* TODO - Move this code out to a Util class
* inside the server code, eventually we should
* make three projects: shared, client, server
*/
this.axis = new ArrayList<>();
this.allies = new ArrayList<>();
ServerSeventhConfig config = context.getConfig();
this.address = config.getAddress();
this.port = context.getPort();
this.serverName = config.getServerName();
if(context.hasGameSession()) {
GameSession session = context.getGameSession();
GameType gameType = session.getGameType();
this.gameType = gameType.getType().name();
this.mapName = session.getMap().getMapFileName();
Team alliedTeam = gameType.getAlliedTeam();
for(Player player : alliedTeam.getPlayers()) {
this.allies.add(player.getName());
}
Team axisTeam = gameType.getAxisTeam();
for(Player player : axisTeam.getPlayers()) {
this.axis.add(player.getName());
}
}
}
/**
* @return the address
*/
public String getAddress() {
return address;
}
/**
* @return the port
*/
public int getPort() {
return port;
}
/**
* @return the serverName
*/
public String getServerName() {
return serverName;
}
/**
* @return the gameType
*/
public String getGameType() {
return gameType;
}
/**
* @return the allies
*/
public List<String> getAllies() {
return allies;
}
/**
* @return the axis
*/
public List<String> getAxis() {
return axis;
}
/**
* @return the mapName
*/
public String getMapName() {
return mapName;
}
private void parseEntry(LeoObject object) {
try {
this.address = object.getObject("address").toString();
this.port = Integer.parseInt(object.getObject("port").toString());
this.serverName = object.getObject("server_name").toString();
this.gameType = object.getObject("game_type").toString();
this.mapName = object.getObject("map").toString();
if(this.mapName != null) {
int slashIndex = this.mapName.lastIndexOf("/");
int extIndex = this.mapName.lastIndexOf(".");
if(slashIndex>-1 && extIndex>-1) {
this.mapName = this.mapName.substring(slashIndex+1, extIndex);
}
}
LeoArray leoAxis = object.getObject("axis").as();
leoAxis.foreach(new LeoUserFunction() {
@Override
public LeoObject xcall(LeoObject arg1) throws LeolaRuntimeException {
axis.add(arg1.toString());
return LeoObject.FALSE;
}
});
LeoArray leoAllies = object.getObject("allies").as();
leoAllies.foreach(new LeoUserFunction() {
@Override
public LeoObject xcall(LeoObject arg1) throws LeolaRuntimeException {
allies.add(arg1.toString());
return LeoObject.FALSE;
}
});
}
catch(Exception e) {
Cons.println("*** ERROR: Parsing the ServerInfo: " + e);
}
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
LeoMap map = new LeoMap();
map.putByString("address", LeoObject.valueOf(getAddress()));
map.putByString("port", LeoObject.valueOf(getPort()));
map.putByString("server_name", LeoObject.valueOf(getServerName()));
map.putByString("game_type", LeoObject.valueOf(getGameType()));
map.putByString("map", LeoObject.valueOf(getMapName()));
LeoArray leoAxis = new LeoArray();
for(String player : this.axis) {
leoAxis.add(LeoObject.valueOf(player));
}
map.putByString("axis", leoAxis);
LeoArray leoAllies = new LeoArray();
for(String player : this.allies) {
leoAllies.add(LeoObject.valueOf(player));
}
map.putByString("allies", leoAllies);
return map.toString();
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + port;
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ServerInfo other = (ServerInfo) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (port != other.port)
return false;
return true;
}
}
| 6,602 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SoundType.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/SoundType.java | /*
* see license.txt
*/
package seventh.shared;
/**
* All available sounds in the game
*
* @author Tony
*
*/
public enum SoundType {
SURFACE_NORMAL,
SURFACE_DIRT,
SURFACE_SAND,
SURFACE_WATER,
SURFACE_GRASS,
SURFACE_METAL,
SURFACE_WOOD,
EMPTY_FIRE,
// Alies Weapon Sounds
M1_GARAND_FIRE,
M1_GARAND_LAST_FIRE(SoundSourceType.REFERENCED_ATTACHED),
M1_GARAND_RELOAD(SoundSourceType.REFERENCED_ATTACHED),
THOMPSON_FIRE,
THOMPSON_RELOAD(SoundSourceType.REFERENCED_ATTACHED),
SPRINGFIELD_FIRE,
SPRINGFIELD_RECHAMBER(SoundSourceType.REFERENCED_ATTACHED),
SPRINGFIELD_RELOAD(SoundSourceType.REFERENCED_ATTACHED),
KAR98_FIRE,
KAR98_RECHAMBER(SoundSourceType.REFERENCED_ATTACHED),
KAR98_RELOAD(SoundSourceType.REFERENCED_ATTACHED),
MP44_FIRE,
MP44_RELOAD(SoundSourceType.REFERENCED_ATTACHED),
MP40_FIRE,
MP40_RELOAD(SoundSourceType.REFERENCED_ATTACHED),
SHOTGUN_FIRE,
SHOTGUN_RELOAD(SoundSourceType.REFERENCED_ATTACHED),
SHOTGUN_PUMP(SoundSourceType.REFERENCED_ATTACHED),
PISTOL_FIRE,
PISTOL_RELOAD(SoundSourceType.REFERENCED_ATTACHED),
RISKER_FIRE,
RISKER_RECHAMBER(SoundSourceType.REFERENCED_ATTACHED),
RISKER_RELOAD(SoundSourceType.REFERENCED_ATTACHED),
RPG_FIRE,
FLAMETHROWER_SHOOT(SoundSourceType.REFERENCED_ATTACHED),
GRENADE_PINPULLED,
GRENADE_THROW,
SMOKE_GRENADE,
MELEE_SWING,
MELEE_HIT,
HAMMER_SWING,
BREATH_LITE(SoundSourceType.REFERENCED_ATTACHED),
BREATH_HEAVY(SoundSourceType.REFERENCED_ATTACHED),
FIRE(SoundSourceType.REFERENCED_ATTACHED),
EXPLOSION(SoundSourceType.POSITIONAL),
WEAPON_SWITCH(SoundSourceType.REFERENCED_ATTACHED),
WEAPON_PICKUP(SoundSourceType.POSITIONAL),
WEAPON_DROPPED,
AMMO_PICKUP(SoundSourceType.POSITIONAL),
HEALTH_PACK_PICKUP,
RUFFLE(SoundSourceType.REFERENCED_ATTACHED),
BULLET_SHELL,
SHOTGUN_SHELL,
BOMB_TICK(SoundSourceType.GLOBAL),
BOMB_PLANT,
BOMB_DISARM,
UI_ELEMENT_HOVER(SoundSourceType.GLOBAL),
UI_ELEMENT_SELECT(SoundSourceType.GLOBAL),
UI_NAVIGATE(SoundSourceType.GLOBAL),
UI_KEY_TYPE(SoundSourceType.GLOBAL),
IMPACT_METAL(SoundSourceType.POSITIONAL),
IMPACT_WOOD(SoundSourceType.POSITIONAL),
IMPACT_FOLIAGE(SoundSourceType.POSITIONAL),
IMPACT_GLASS(SoundSourceType.POSITIONAL),
IMPACT_DEFAULT(SoundSourceType.POSITIONAL),
IMPACT_FLESH(SoundSourceType.POSITIONAL),
HIT_INDICATOR(SoundSourceType.GLOBAL),
HEADSHOT(SoundSourceType.GLOBAL),
TANK_REV_DOWN(SoundSourceType.REFERENCED_ATTACHED),
TANK_REV_UP(SoundSourceType.REFERENCED_ATTACHED),
TANK_ON(SoundSourceType.REFERENCED_ATTACHED),
TANK_OFF(SoundSourceType.REFERENCED_ATTACHED),
TANK_IDLE(SoundSourceType.REFERENCED_ATTACHED),
TANK_SHIFT(SoundSourceType.REFERENCED_ATTACHED),
TANK_TURRET_MOVE(SoundSourceType.REFERENCED_ATTACHED),
TANK_MOVE(SoundSourceType.REFERENCED_ATTACHED),
TANK_FIRE(SoundSourceType.REFERENCED_ATTACHED),
FLAG_CAPTURED(SoundSourceType.GLOBAL),
FLAG_STOLEN(SoundSourceType.GLOBAL),
FLAG_RETURNED(SoundSourceType.GLOBAL),
ENEMY_FLAG_CAPTURED(SoundSourceType.GLOBAL),
ENEMY_FLAG_STOLEN(SoundSourceType.GLOBAL),
MG42_FIRE,
RADIO_STATIC(SoundSourceType.REFERENCED),
ALLIED_VICTORY(SoundSourceType.GLOBAL),
AXIS_VICTORY(SoundSourceType.GLOBAL),
DOOR_OPEN(SoundSourceType.POSITIONAL),
DOOR_CLOSE(SoundSourceType.POSITIONAL),
DOOR_CLOSE_BLOCKED(SoundSourceType.POSITIONAL),
DOOR_OPEN_BLOCKED(SoundSourceType.POSITIONAL),
MUTE,
;
public static enum SoundSourceType {
/**
* Played at an X,Y coordinate
*/
POSITIONAL,
/**
* Played at the position of the referenced ID
* of an Entity
*/
REFERENCED,
/**
* Attached to an entity by reference ID
* (i.e., when the entity moves, so does the
* sound)
*/
REFERENCED_ATTACHED,
/**
* Plays in a global channel, that is right
* at the camera location so it is always heard
*/
GLOBAL,
}
private SoundSourceType sourceType;
private SoundType() {
this(SoundSourceType.REFERENCED);
}
/**
* @param sourceType
*/
private SoundType(SoundSourceType sourceType) {
this.sourceType = sourceType;
}
private static final SoundType[] values = values();
public byte netValue() {
return (byte)this.ordinal();
}
/**
* @return the sourceType
*/
public SoundSourceType getSourceType() {
return sourceType;
}
public static SoundType fromNet(byte value) {
if(value >= values.length) {
return MUTE;
}
if(value < 0) {
return MUTE;
}
return values[value];
}
}
| 5,158 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
NetworkProtocol.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/NetworkProtocol.java | /*
* see license.txt
*/
package seventh.shared;
import harenet.api.Connection;
import harenet.api.ConnectionListener;
import harenet.api.Endpoint;
import harenet.messages.NetMessage;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* @author Tony
*
*/
public abstract class NetworkProtocol implements ConnectionListener {
public static enum MessageType {
ALL_CLIENTS,
ALL_EXCEPT,
ONE,
}
private class InboundMessage {
Connection conn;
NetMessage msg;
/**
* @param conn
* @param msg
*/
public InboundMessage(Connection conn, NetMessage msg) {
this.conn = conn;
this.msg = msg;
}
}
private Queue<InboundMessage> messageQ;
private Endpoint endpoint;
/**
*
*/
public NetworkProtocol(Endpoint endpoint) {
this.endpoint = endpoint;
this.messageQ = new ConcurrentLinkedQueue<InboundMessage>();
}
/*
* (non-Javadoc)
* @see net.ConnectionListener#onReceived(net.Connection, java.lang.Object)
*/
@Override
public void onReceived(Connection conn, Object message) {
if(message instanceof NetMessage) {
queueInboundMessage(conn, (NetMessage)message);
}
else {
//Cons.println("Received a non Message object type: " + message.getClass());
}
}
protected void queueInboundMessage(Connection conn, NetMessage msg) {
this.messageQ.add(new InboundMessage(conn, msg));
}
/**
* Close out the connection
*/
public void close() {
try { this.endpoint.stop(); } catch(Exception e) {}
try { this.endpoint.close(); } catch(Exception e) {}
}
/**
* Post any Queued up messages
*/
public abstract void postQueuedMessages();
/**
* Process game specific messages
*
* @param conn
* @param message
*/
protected abstract void processMessage(Connection conn, NetMessage message) throws IOException;
/**
* Reads/writes to the network buffers
* @param timeStep
*/
public void updateNetwork(TimeStep timeStep) {
int maxMessage = 100;
while(!this.messageQ.isEmpty() && maxMessage > 0) {
maxMessage--;
InboundMessage p = this.messageQ.poll();
try {
processMessage(p.conn, p.msg);
} catch (IOException e) {
Cons.println("Failed to send message: " + e);
}
}
}
}
| 2,699 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
CommonCommands.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/CommonCommands.java | /*
* see license.txt
*/
package seventh.shared;
/**
* @author Tony
*
*/
public class CommonCommands {
public static void addCommonCommands(Console console) {
console.addCommand(new ExecCommand());
}
}
| 225 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
DefaultConsole.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/shared/DefaultConsole.java | /*
* see license.txt
*/
package seventh.shared;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* @author Tony
*
*/
public class DefaultConsole implements Console {
static class QueuedExecution {
String command;
String[] args;
public QueuedExecution(String command, String[] args) {
this.command = command;
this.args = args;
}
}
private Map<String, Command> commands;
private List<Logger> loggers;
private Queue<QueuedExecution> queuedCommands;
private long sleepTime;
/**
* @param logger
*/
public DefaultConsole(Logger logger) {
this.commands = new ConcurrentHashMap<String, Command>();
this.loggers = new ArrayList<Logger>();
this.loggers.add(logger);
this.queuedCommands = new ConcurrentLinkedQueue<>();
addCommand(new Command("cmdlist") {
@Override
public void execute(Console console, String... args) {
console.println("\n");
for(String commandName : commands.keySet()) {
console.println(commandName);
}
}
});
addCommand(new Command("sleep") {
@Override
public void execute(Console console, String... args) {
try {
if(args.length != 1) {
console.println("<usage> sleep [msec]");
}
else {
sleepTime = Long.parseLong(args[0]);
}
}
catch(Exception e) {
console.println("*** Must be a valid long value");
}
}
});
}
/**
*/
public DefaultConsole() {
this(new SysOutLogger());
}
/* (non-Javadoc)
* @see seventh.shared.Console#update(seventh.shared.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
if(sleepTime > 0) {
sleepTime -= timeStep.getDeltaTime();
}
else {
while(!this.queuedCommands.isEmpty()) {
QueuedExecution exe = this.queuedCommands.poll();
executeCommand(exe);
/* if we encountered a sleep command,
* break out
*/
if(sleepTime > 0) {
break;
}
}
}
}
/* (non-Javadoc)
* @see shared.Console#addCommand(shared.Command)
*/
public void addCommand(Command command) {
if(command==null) {
throw new IllegalArgumentException("The command can not be null!");
}
addCommand(command.getName(), command);
}
/* (non-Javadoc)
* @see shared.Console#addCommand(java.lang.String, shared.Command)
*/
public void addCommand(String alias, Command command) {
if(alias == null) {
throw new IllegalArgumentException("The command alias can not be null!");
}
if(command==null) {
throw new IllegalArgumentException("The command can not be null!");
}
this.commands.put(alias.toLowerCase(), command);
}
/* (non-Javadoc)
* @see shared.Console#removeCommand(java.lang.String)
*/
public void removeCommand(String commandName) {
this.commands.remove(commandName.toLowerCase());
}
/* (non-Javadoc)
* @see shared.Console#removeCommand(shared.Command)
*/
public void removeCommand(Command command) {
if(command!=null) {
removeCommand(command.getName());
}
}
/*
* (non-Javadoc)
* @see shared.Console#getCommand(java.lang.String)
*/
public Command getCommand(String commandName) {
return this.commands.get(commandName.toLowerCase());
}
/* (non-Javadoc)
* @see shared.Console#find(java.lang.String)
*/
public List<String> find(String partialName) {
List<String> matches = new ArrayList<String>();
if(partialName != null) {
String partialNameLower = partialName.toLowerCase();
Set<String> names = this.commands.keySet();
for(String cmdName : names) {
if(cmdName.startsWith(partialNameLower)) {
matches.add(cmdName);
}
}
}
return matches;
}
/* (non-Javadoc)
* @see shared.Console#addLogger(shared.Logger)
*/
public void addLogger(Logger logger) {
this.loggers.add(logger);
}
/* (non-Javadoc)
* @see seventh.shared.Console#removeLogger(seventh.shared.Logger)
*/
@Override
public void removeLogger(Logger logger) {
this.loggers.remove(logger);
}
/* (non-Javadoc)
* @see shared.Console#setLogger(shared.Logger)
*/
public void setLogger(Logger logger) {
this.loggers.clear();
addLogger(logger);
}
/* (non-Javadoc)
* @see shared.Logger#print(java.lang.Object)
*/
public synchronized void print(Object msg) {
int size = loggers.size();
for(int i = 0; i < size; i++) {
loggers.get(i).print(msg);
}
}
/* (non-Javadoc)
* @see shared.Logger#printf(java.lang.Object, java.lang.Object[])
*/
public synchronized void printf(Object msg, Object... args) {
int size = loggers.size();
for(int i = 0; i < size; i++) {
loggers.get(i).printf(msg, args);
}
}
/* (non-Javadoc)
* @see shared.Logger#println(java.lang.Object)
*/
public synchronized void println(Object msg) {
int size = loggers.size();
for(int i = 0; i < size; i++) {
loggers.get(i).println(msg);
}
}
private void executeCommand(QueuedExecution exe) {
String commandName = exe.command;
String[] args = exe.args;
Command cmd = getCommand(commandName);
if(cmd != null) {
try {
cmd.execute(this, args);
}
catch(Exception e) {
println("*** Error executing command: " + e);
}
}
else {
println("*** Command not found: " + commandName);
}
}
/* (non-Javadoc)
* @see shared.Console#execute(java.lang.String, java.lang.String[])
*/
public void execute(String commandName, String... args) {
this.queuedCommands.add(new QueuedExecution(commandName, args));
}
/* (non-Javadoc)
* @see palisma.shared.Console#execute(java.lang.String)
*/
@Override
public void execute(String commandLine) {
String cmd = null;
String[] args = commandLine.split(" ");
switch(args.length) {
case 0: return;
case 1: cmd = args[0];
args= new String[0];
break;
default: {
cmd = args[0];
String[] args2 = new String[args.length-1];
for(int i = 0; i < args2.length; i++) {
args2[i] = args[i+1];
}
args = args2;
}
}
execute(cmd, args);
}
}
| 7,711 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
DepthFirstGraphSearch.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/graph/DepthFirstGraphSearch.java | /*
*
* see license.txt
*/
package seventh.graph;
import java.util.HashSet;
import java.util.Set;
/**
* Performs a Depth-First search on the given graph.
*
* @author Tony
*
*/
public class DepthFirstGraphSearch<E,T> implements GraphSearch<E,T> {
/*
* (non-Javadoc)
* @see leola.live.game.graph.GraphSearch#search(leola.live.game.graph.GraphNode, leola.live.game.graph.GraphSearch.SearchCondition)
*/
public GraphNode<E,T> search(GraphNode<E,T> graph, SearchCondition<E,T> condition) {
return search(graph, condition, new HashSet<GraphNode<E,T>>());
}
/**
* Does a depth first search for the root node.
*
* @param node
* @param visited
* @return
*/
private GraphNode<E,T> search(GraphNode<E,T> node, SearchCondition<E,T> condition, Set<GraphNode<E,T>> visited ) {
if ( !visited.contains(node)) {
visited.add(node);
/* If we reached the node of interest, return it */
if ( condition.foundItem(node) ) {
return node;
}
/* Search each neighbor for the root */
Edges<E, T> edges = node.edges();
for(int i = 0; i < edges.size(); i++) {
Edge<E,T> edge = edges.get(i);
if(edge == null) {
continue;
}
/* Search the neighbor node */
GraphNode<E,T> rightNode = edge.getRight();
if ( rightNode !=null && !visited.contains(rightNode) ) {
return search(rightNode, condition, visited);
}
}
}
return null; /* Not found */
}
}
| 1,770 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AStarGraphSearch.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/graph/AStarGraphSearch.java | /*
* see license.txt
*/
package seventh.graph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import seventh.graph.Edges.Directions;
import seventh.shared.ArrayMap;
/**
* Uses the A* (A-Star) optimal-path searching algorithm.
*
* @author Tony
*
*/
public class AStarGraphSearch<E, T> implements GraphSearchPath<E, T> {
private Map<GraphNode<E,T>, Integer> gScores /* Distance from start to optimal path */
, hScores /* Heuristic scores */
, fScores; /* Sum of heuristic from node to goal */
private Map<GraphNode<E,T>, GraphNode<E,T>> cameFrom; /* Nodes visited to reach goal node */
private Set<GraphNode<E,T>> closedSet /* List of nodes we do not care about anymore */
, openSet; /* Working set of nodes to be tested */
/**
*
*/
public AStarGraphSearch() {
boolean jdk = false;
// TODO - Continue testing working on ArrayMap
// removing GC from HashMap Entries
if(jdk) {
gScores = new HashMap<GraphNode<E,T>, Integer>();
hScores = new HashMap<GraphNode<E,T>, Integer>();
fScores = new HashMap<GraphNode<E,T>, Integer>();
cameFrom = new HashMap<GraphNode<E,T>, GraphNode<E,T>>();
}
else {
gScores = new ArrayMap<>();
hScores = new ArrayMap<GraphNode<E,T>, Integer>();
fScores = new ArrayMap<>();
cameFrom = new ArrayMap<GraphNode<E,T>, GraphNode<E,T>>();
}
closedSet = new HashSet<GraphNode<E,T>>();
openSet = new HashSet<GraphNode<E,T>>();
}
/*
* (non-Javadoc)
* @see leola.live.game.graph.GraphSearchPath#search(leola.live.game.graph.GraphNode, leola.live.game.graph.GraphNode)
*/
public List<GraphNode<E,T>> search(GraphNode<E, T> start, GraphNode<E, T> goal) {
if(start == null || goal == null) {
return null;
}
return aStar(start, goal);
}
/**
* Calculate the heuristic distance between the currentNode and the goal node.
*
* @param currentNode
* @param goal
* @return
*/
protected int heuristicEstimateDistance(GraphNode<E, T> startNode, GraphNode<E, T> currentNode, GraphNode<E, T> goal) {
return 0; /* Make the H value 0, this essentially makes the A* algorithm Dijkstra's algorithm */
}
/**
* If this node should be ignored
*
* @param node
* @return true if this node should be ignored
*/
protected boolean shouldIgnore(GraphNode<E, T> node) {
return false;
}
/**
* Retrieves the lowest score (Heuristic 'H') in the supplied set from the map of total scores ('F').
*
* <p>
* To optimize performance, convert the openSet (set) into a PriorityQueue so this method call
* turns into a O(1) versus a O(n) call.
*
* @param set - set to retrieve the lowest scored node
* @param fScores - map containing the heuristic scores
* @return the lowest heuristic {@link GraphNode} in the supplied set.
*/
private GraphNode<E,T> getLowestScore(Set<GraphNode<E,T>> set, Map<GraphNode<E,T>, Integer> fScores) {
GraphNode<E,T> lowerScore = null;
/*
* Search for the lowest H score.
*/
for(GraphNode<E,T> node : set) {
/* Set the first node to the lowest */
if ( lowerScore == null ) {
lowerScore = node;
continue;
}
int score = fScores.get(node);
/* Check to see if this node has a lower H score */
if ( score < fScores.get(lowerScore)) {
lowerScore = node;
}
}
return lowerScore;
}
/**
* Reconstructs the path from the start to finish nodes.
*
* @param <E>
* @param <T>
* @param cameFrom - path traversed
* @param currentNode - current node
* @param result - list of {@link GraphNode}s needed to reach the goal
* @return the result list - for convience
*/
private List<GraphNode<E,T>> reconstructPath(Map<GraphNode<E,T>, GraphNode<E,T>> cameFrom, GraphNode<E,T> currentNode, List<GraphNode<E,T>> result) {
/* If we visited this node, add it to the result set */
if ( cameFrom.containsKey(currentNode) ) {
/* Find the rest of the path */
reconstructPath(cameFrom, cameFrom.get(currentNode), result);
result.add(currentNode); /* Notice this is after the recursive call - we want the results to be in descending order */
return result;
}
return result;
}
/**
* Find the most optimal path to the goal node. The best (or most optimal) path is calculated by the A* (A-Star) algorithm.
*
* @param start - starting node
* @param goal - ending node
* @return the optimal node traversal from start to goal nodes. null if no path found.
*/
private List<GraphNode<E,T>> aStar(GraphNode<E,T> start, GraphNode<E,T> goal) {
gScores.clear();
hScores.clear();
fScores.clear();
cameFrom.clear();
closedSet.clear();
openSet.clear();
/* Push the start node so we have a starting point */
openSet.add(start);
gScores.put(start, 0); /* No other possibility, thus 0 to denote optimal path */
hScores.put(start, heuristicEstimateDistance(start, start, goal)); /* Guess the cost from start to goal nodes */
fScores.put(start, hScores.get(start)); /* Store the sum of the cost 0 + X = X */
/*
* Until we run out of nodes of interest, lets compile our path. If there
* are no more nodes of interest, and we have not found our goal node, this means
* there is no path.
*/
while( ! openSet.isEmpty() ) {
/* Get the most optimal node to work from */
GraphNode<E, T> x = getLowestScore(openSet, fScores);
/* If this node is the goal, we are done */
if ( x == goal ) {
/* optimal path from start to finish */
return reconstructPath(cameFrom, goal, new ArrayList<GraphNode<E, T>>());
}
/* Remove this node so we don't visit it again */
openSet.remove(x);
closedSet.add(x);
/*
* For each neighbor (the nodes edges contain the neighbors)
*/
Edges<E, T> edges = x.edges();
int skipMask = 0;
for(int i = 0; i < edges.size(); i++) {
Edge<E,T> edge = edges.get(i);
if(edge == null) {
continue;
}
GraphNode<E, T> y = edge.getRight();
/* If this node has been visited before, ignore it and move on */
if ( y == null || closedSet.contains(y)) {
continue;
}
Directions dir = Directions.fromIndex(i);
if(shouldIgnore(y)) {
if(Directions.isCardinal(i)) {
switch(dir) {
case N:
skipMask |= Directions.NE.getMask();
skipMask |= Directions.NW.getMask();
break;
case E:
skipMask |= Directions.NE.getMask();
skipMask |= Directions.SE.getMask();
break;
case S:
skipMask |= Directions.SE.getMask();
skipMask |= Directions.SW.getMask();
break;
case W:
skipMask |= Directions.NW.getMask();
skipMask |= Directions.SW.getMask();
break;
default:
}
}
continue;
}
if((dir.getMask() & skipMask) != 0) {
continue;
}
/* Compile the shortest distance traveled between x and y plus the sum scores*/
int tentativeGscore = gScores.get(x) + edge.getWeight();
boolean tentativeIsBetter = false;
/* If this neighbor has not been tested, lets go ahead and add it */
if ( ! openSet.contains(y)) {
openSet.add(y);
/* Calculate the heuristic to determine if this direction is the most optimal */
hScores.put(y, heuristicEstimateDistance(start, y, goal));
tentativeIsBetter = true;
}
/* The neighbor is waiting to be tested (in the openSet) so test to see if the distance
* from x to y is better than y to goal. If this neighbor is being visited from another
* parent, it might be a more optimal path so test for that.
*/
else if ( gScores.containsKey(y) && tentativeGscore < gScores.get(y)) {
tentativeIsBetter = true;
}
/*
* If traveling to this neighbor is cheaper than from another node, override
* the path to this one. If this is the first time this neighbor is to be
* visited, place it in our path.
*/
if ( tentativeIsBetter ) {
cameFrom.put(y, x); /* remember our path */
gScores.put(y, tentativeGscore); /* Remember our score */
fScores.put(y, tentativeGscore + hScores.get(y)); /* remember the total score */
}
}
}
return null; /* No path found */
}
}
| 10,979 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Edge.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/graph/Edge.java | /*
* see license.txt
*/
package seventh.graph;
/**
* An {@link Edge} denotes the 'link' between two {@link GraphNode}s. An {@link Edge} can have an associated cost and data.
*
* @author Tony
*
*/
public class Edge<E, T> {
private GraphNode<E, T> left;
private GraphNode<E, T> right;
private int weight;
private T value;
/**
* Constructs a new {@link Edge} which links the left and right {@link GraphNode}s.
*
* <p>
* Defaults the weight to 0 if weight is not important.
*
* @param left - the left {@link GraphNode}
* @param right - the right {@link GraphNode}
* @param value - the data stored in this edge.
*/
public Edge(GraphNode<E, T> left, GraphNode<E, T> right, T value) {
this(left, right, value, 0);
}
/**
* Constructs a new {@link Edge} which links the left and right {@link GraphNode}s.
*
* @param left - the left {@link GraphNode}
* @param right - the right {@link GraphNode}
* @param value - the data stored in this edge.
* @param weight - the cost of this edge (used for searching).
*/
public Edge(GraphNode<E, T> left, GraphNode<E, T> right, T value, int weight) {
this.left = left;
this.right = right;
this.value = value;
this.weight = weight;
}
/**
* @return the left
*/
public GraphNode<E, T> getLeft() {
return this.left;
}
/**
* @param left the left to set
*/
public void setLeft(GraphNode<E, T> left) {
this.left = left;
}
/**
* @return the right
*/
public GraphNode<E, T> getRight() {
return this.right;
}
/**
* @param right the right to set
*/
public void setRight(GraphNode<E, T> right) {
this.right = right;
}
/**
* @return the weight
*/
public int getWeight() {
return this.weight;
}
/**
* @param weight the weight to set
*/
public void setWeight(int weight) {
this.weight = weight;
}
/**
* @return the value
*/
public T getValue() {
return this.value;
}
/**
* @param value the value to set
*/
public void setValue(T value) {
this.value = value;
}
public void removeEdge() {
if(this.left!=null) {
this.left.removeEdge(this);
}
if(this.right!=null) {
this.right.removeEdge(this);
}
}
}
| 2,517 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Edges.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/graph/Edges.java | /*
* see license.txt
*/
package seventh.graph;
/**
* List of edges for a {@link GraphNode}
*
* @author Tony
*
*/
public class Edges<E, T> {
public static enum Directions {
N(1<<0),
E(1<<1),
S(1<<2),
W(1<<3),
NE(1<<4),
SE(1<<5),
SW(1<<6),
NW(1<<7),
;
private static final Directions[] values = values();
private int mask;
Directions(int m) {
this.mask = m;
}
/**
* @return the mask
*/
public int getMask() {
return mask;
}
public Directions invertedDirection() {
switch(this) {
case E:
return W;
case N:
return S;
case NE:
return SW;
case NW:
return SE;
case S:
return N;
case SE:
return NW;
case SW:
return NE;
case W:
return E;
default:
return N;
}
}
public static Directions fromIndex(int index) {
return values[index];
}
public static boolean isCardinal(int index) {
return index>=0 && index < NE.ordinal();
}
public static boolean isInterCardinal(int index) {
return index < 8 && index > W.ordinal();
}
}
private Edge<E, T>[] edges;
@SuppressWarnings("unchecked")
public Edges() {
this.edges = new Edge[8];
}
public int size() {
return this.edges.length;
}
public void addEdge(Directions dir, Edge<E, T> edge) {
this.edges[dir.ordinal()] = edge;
}
public void removeEdge(Directions dir) {
this.edges[dir.ordinal()] = null;
}
public void removeEdge(Edge<E, T> edge) {
for(int i = 0; i < this.edges.length; i++) {
if(this.edges[i] == edge) {
this.edges[i] = null;
break;
}
}
}
public Edge<E,T> get(int index) {
return this.edges[index];
}
public Edge<E,T> get(Directions dir) {
return this.edges[dir.ordinal()];
}
public void removeEdges() {
for(int i = 0; i < this.edges.length; i++) {
Edge<E,T> edge = this.edges[i];
if(edge!=null) {
edge.removeEdge();
}
}
}
}
| 2,670 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
GraphException.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/graph/GraphException.java | /*
* see license.txt
*/
package seventh.graph;
/**
* Base Exception.
*
* @author Tony
*
*/
public class GraphException extends Exception {
/**
* UID
*/
private static final long serialVersionUID = 1560018059471863025L;
/**
*
*/
public GraphException() {
}
/**
* @param message
*/
public GraphException(String message) {
super(message);
}
/**
* @param cause
*/
public GraphException(Throwable cause) {
super(cause);
}
/**
* @param message
* @param cause
*/
public GraphException(String message, Throwable cause) {
super(message, cause);
}
}
| 691 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
GraphSearch.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/graph/GraphSearch.java | /*
* see license.txt
*/
package seventh.graph;
/**
* This interface allows for different search algorithms for graphs to implement.
*
* @author Tony
*
*/
public interface GraphSearch<E,T> {
/**
* A {@link SearchCondition} allows an implementer to listen to each node while
* it is being traversed by the {@link GraphSearch}. Upon a condition specified by the
* implementer, a node can be found.
*
* @author Tonys
*
* @param <E>
* @param <T>
*/
public interface SearchCondition<E,T> {
/**
* Determine if the item has been found in the node.
*
* @param node - current node being searched.
* @return if this node contains the search criteria.
*/
public boolean foundItem(GraphNode<E,T> node);
}
/**
* Performs a search on the given graph.
*
* @param graph - graph to search
* @param condition - condition
* @return node that was searched for, null if not found.
*/
public GraphNode<E, T> search(GraphNode<E, T> graph, SearchCondition<E, T> condition);
}
| 1,140 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
TestPathing.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/graph/TestPathing.java | /*
* see license.txt
*/
package seventh.graph;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import seventh.graph.Edges.Directions;
import seventh.graph.GraphSearch.SearchCondition;
/**
* @author Tony
*
*/
public class TestPathing {
static class NodeData {
int x, y;
NodeData(int x, int y) {
this.x = x; this.y = y;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "[ " + x + "," + y + " ]";
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NodeData other = (NodeData) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
static class EdgeData {
}
static final int[][] MAP =
{
//0 1 2 3 4 5 6 7 8
{ 0, 0, 0, 0, 0, 0, 0, 0, 0},//0
{ 0, 0, 0, 1, 1, 0, 0, 0, 0},//1
{ 0, 0, 0, 0, 1, 0, 0, 0, 0},//2
{ 0, 0, 0, 0, 1, 0, 0, 0, 0},//3
{ 0, 0, 0, 0, 0, 0, 0, 0, 0},//4
{ 0, 0, 0, 0, 0, 0, 0, 0, 0},//5
};
/**
* @param args
*/
public static void main(String[] args) throws Exception {
TestPathing path = new TestPathing();
final NodeData start = new NodeData(8,3);
final NodeData findMe = new NodeData(1,2);
Map<NodeData, GraphNode<NodeData, EdgeData>> graph = path.constructGraph(MAP);
GraphNode<NodeData, EdgeData> node = graph.get(start);
GraphSearch<NodeData, EdgeData> search = new DepthFirstGraphSearch<NodeData, EdgeData>();
final int[] iterations = {0};
GraphNode<NodeData, EdgeData> result = search.search(node, new SearchCondition<TestPathing.NodeData, TestPathing.EdgeData>() {
@Override
public boolean foundItem(GraphNode<NodeData, EdgeData> node) {
//System.out.println("Checking: " + node.getValue());
iterations[0]++;
return findMe.equals(node.getValue());
}
});
if(result != null ) {
System.out.println("Found: " + result.getValue() + " in " + iterations[0] + " iterations.");
}
else {
System.out.println("No result found.");
}
GraphSearchPath<NodeData, EdgeData> searchPath = new AStarGraphSearch<TestPathing.NodeData, TestPathing.EdgeData>(){
/* (non-Javadoc)
* @see graph.AStarGraphSearch#heuristicEstimateDistance(graph.GraphNode, graph.GraphNode)
*/
@Override
protected int heuristicEstimateDistance(
GraphNode<NodeData, EdgeData> startNode,
GraphNode<NodeData, EdgeData> currentNode,
GraphNode<NodeData, EdgeData> goal) {
int distance = ((currentNode.getValue().x - goal.getValue().x) *
(currentNode.getValue().x - goal.getValue().x)) +
((currentNode.getValue().y - goal.getValue().y) *
(currentNode.getValue().y - goal.getValue().y));
return distance;
}
};
List<GraphNode<NodeData, EdgeData>> resultPath = searchPath.search(node, result);
if(resultPath==null || resultPath.isEmpty()) {
System.out.println("No path found");
}
else {
for(GraphNode<NodeData, EdgeData> n:resultPath) {
System.out.println("Visit node: " + n.getValue());
}
for(int y = 0; y < MAP.length; y++) {
System.out.println("+-+-+-+-+-+-+-+-+-+");
for(int x = 0; x < MAP[y].length; x++ ) {
boolean isPath = false;
for(GraphNode<NodeData, EdgeData> n:resultPath) {
isPath = n.getValue().equals(new NodeData(x,y));
if(isPath)break;
}
if(MAP[y][x] > 0) {
System.out.print(isPath ? "|E" : "|#");
}
else {
System.out.print(isPath ? "|*" : "| ");
}
}
System.out.println("|");
}
System.out.println("+-+-+-+-+-+-+-+-+-+");
}
}
public Map<NodeData, GraphNode<NodeData, EdgeData>> constructGraph(int[][] map) throws Exception {
Map<NodeData, GraphNode<NodeData, EdgeData>> nodes = new HashMap<TestPathing.NodeData, GraphNode<NodeData,EdgeData>>();
// first build all graph nodes.
for(int y = 0; y < map.length; y++) {
for(int x = 0; x < map[y].length; x++ ) {
if (map[y][x]==0)
{
NodeData data = new NodeData(x,y);
GraphNode<NodeData, EdgeData> node = new GraphNode<NodeData, EdgeData>(data);
nodes.put(data, node);
}
}
}
// now let's build the edge nodes
for(GraphNode<NodeData, EdgeData> node : nodes.values()) {
NodeData data = node.getValue();
GraphNode<NodeData, EdgeData> nw = nodes.get(new NodeData(data.x - 1, data.y - 1));
GraphNode<NodeData, EdgeData> n = nodes.get(new NodeData(data.x, data.y - 1));
GraphNode<NodeData, EdgeData> ne = nodes.get(new NodeData(data.x + 1, data.y - 1));
GraphNode<NodeData, EdgeData> e = nodes.get(new NodeData(data.x + 1, data.y));
GraphNode<NodeData, EdgeData> se = nodes.get(new NodeData(data.x + 1, data.y + 1));
GraphNode<NodeData, EdgeData> s = nodes.get(new NodeData(data.x, data.y + 1));
GraphNode<NodeData, EdgeData> sw = nodes.get(new NodeData(data.x - 1, data.y + 1));
GraphNode<NodeData, EdgeData> w = nodes.get(new NodeData(data.x - 1, data.y));
if (nw != null) {
node.addEdge(Directions.NW, new Edge<TestPathing.NodeData, TestPathing.EdgeData>(node, nw, new EdgeData()));
}
if (n != null) {
node.addEdge(Directions.N, new Edge<TestPathing.NodeData, TestPathing.EdgeData>(node, n, new EdgeData()));
}
if (ne != null) {
node.addEdge(Directions.NE, new Edge<TestPathing.NodeData, TestPathing.EdgeData>(node, ne, new EdgeData()));
}
if (e != null) {
node.addEdge(Directions.E, new Edge<TestPathing.NodeData, TestPathing.EdgeData>(node, e, new EdgeData()));
}
if (se != null) {
node.addEdge(Directions.SE, new Edge<TestPathing.NodeData, TestPathing.EdgeData>(node, se, new EdgeData()));
}
if (s != null) {
node.addEdge(Directions.S, new Edge<TestPathing.NodeData, TestPathing.EdgeData>(node, s, new EdgeData()));
}
if (sw != null) {
node.addEdge(Directions.SW, new Edge<TestPathing.NodeData, TestPathing.EdgeData>(node, sw, new EdgeData()));
}
if (w != null) {
node.addEdge(Directions.W, new Edge<TestPathing.NodeData, TestPathing.EdgeData>(node, w, new EdgeData()));
}
}
return nodes;
}
}
| 8,336 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
GraphNode.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/graph/GraphNode.java | /*
* see license.txt
*/
package seventh.graph;
import seventh.graph.Edges.Directions;
/**
* A node in a graph linked by {@link Edge}s.
*
* @author Tony
*
*/
public class GraphNode<E, T> {
private Edges<E, T> edges;
private E value;
/**
* Constructs a {@link GraphNode}.
*
* @param value
*/
public GraphNode(E value) {
this.edges = new Edges<E, T>();
this.value = value;
}
/**
* Constructs a {@link GraphNode}.
*/
public GraphNode() {
this(null);
}
/**
* Adds an {@link Edge}.
*
* @param edge
*/
public void addEdge(Directions dir, Edge<E,T> edge) {
this.edges.addEdge(dir, edge);
}
public void removeEdge(Directions dir) {
this.edges.removeEdge(dir);
}
public void removeEdge(Edge<E,T> edge) {
this.edges.removeEdge(edge);
}
/**
* @return the value
*/
public E getValue() {
return this.value;
}
/**
* @param value the value to set
*/
public void setValue(E value) {
this.value = value;
}
/**
* Get the graphs {@link Edge}s.
*
* @return
*/
public Edges<E, T> edges() {
return this.edges;
}
/**
* Finds the {@link Edge} that links this node with the
* rightNode.
*
* <p>
* Note: The Edge is found by testing pointer equality not Object equality (i.e., '==' and not .equals()).
*
* @param rightNode - other node that is linked with this node
* @return the edge that links the two nodes, null if no such nodes exists.
*/
public Edge<E,T> getEdge(GraphNode<E,T> rightNode) {
Edge<E,T> result = null;
/* Search for the matching Edge (the one that links the right and left) */
Edges<E, T> edges = edges();
for(int i = 0; i < edges.size(); i++) {
Edge<E,T> edge = edges.get(i);
if(edge == null) {
continue;
}
/* Notice we check if the REFERENCE equals the right node */
if (edge.getRight() == rightNode) {
result = edge;
break;
}
}
return (result);
}
}
| 2,318 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
GraphSearchPath.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/graph/GraphSearchPath.java | /*
* see license.txt
*/
package seventh.graph;
import java.util.List;
/**
* Searches for the path from a given start node to an end node.
*
* @author Tony
*
*/
public interface GraphSearchPath<E,T> {
/**
* Finds the path from the start node to the end goal node.
*
* @param start - starting point
* @param goal - ending point
* @return a list of nodes that link the start and end node, null if no path exists.
*/
public List<GraphNode<E,T>> search(GraphNode<E,T> start, GraphNode<E,T> goal);
}
| 544 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Triangle.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/math/Triangle.java | /*
* leola-live
* see license.txt
*/
package seventh.math;
/**
* A triangle defined by 3 vectors of each corner. The vectors are connected by:
* <pre>
* b
* / \
* a---c
* </pre>
*
* @author Tony
*
*/
public class Triangle {
public Vector2f a;
public Vector2f b;
public Vector2f c;
/**
* @param a
* @param b
* @param c
*/
public Triangle(Vector2f a, Vector2f b, Vector2f c) {
this.a = a; this.b = b; this.c = c;
}
/**
* Translates the {@link Triangle} to a new location.
*
* @param a
*/
public void translate(Vector2f a) {
Vector2f.Vector2fAdd(this.a, a, this.a);
Vector2f.Vector2fAdd(this.b, a, this.b);
Vector2f.Vector2fAdd(this.c, a, this.c);
}
/**
* Translates the {@link Triangle} to a new location.
*
* @param a
*/
public void translate(float a) {
Vector2f.Vector2fAdd(this.a, a, this.a);
Vector2f.Vector2fAdd(this.b, a, this.b);
Vector2f.Vector2fAdd(this.c, a, this.c);
}
/**
* Translates the {@link Triangle} to a new location.
*
* @param triangle
* @param a
* @param dest
*/
public static void TriangleTranslate(Triangle triangle, Vector2f a, Triangle dest) {
Vector2f.Vector2fAdd(triangle.a, a, dest.a);
Vector2f.Vector2fAdd(triangle.b, a, dest.b);
Vector2f.Vector2fAdd(triangle.c, a, dest.c);
}
/**
* Translates the {@link Triangle} to a new location.
*
* @param triangle
* @param a
* @param dest
*/
public static void TriangleTranslate(Triangle triangle, float a, Triangle dest) {
Vector2f.Vector2fAdd(triangle.a, a, dest.a);
Vector2f.Vector2fAdd(triangle.b, a, dest.b);
Vector2f.Vector2fAdd(triangle.c, a, dest.c);
}
/**
* Determine if the supplied point is within (contains or intersects) the supplied {@link Triangle}.
*
* @param a
* @param triangle
* @return true if the point is in the {@link Triangle}
*/
public static boolean pointIntersectsTriangle(Vector2f a, Triangle triangle) {
float x0 = triangle.a.x;
float y0 = triangle.a.y;
float x1 = triangle.b.x;
float y1 = triangle.b.y;
float x2 = triangle.c.x;
float y2 = triangle.c.y;
return pointIntersectsTriangle(a.x, a.y, x0, y0, x1, y1, x2, y2);
}
/**
* Determine if the supplied point is within (contains or intersects) the supplied {@link Triangle}.
*
* @param px
* @param py
* @param x0
* @param y0
* @param x1
* @param y1
* @param x2
* @param y2
* @return true if the point is in the {@link Triangle}
*/
public static boolean pointIntersectsTriangle(float px, float py, float x0, float y0, float x1, float y1, float x2, float y2) {
float v0x = x2 - x0;
float v0y = y2 - y0;
float v1x = x1 - x0;
float v1y = y1 - y0;
float v2x = px - x0;
float v2y = py - y0;
// dot(v1.x * v2.x + v1.y * v2.y)
// dot(v0,v0)
float dot00 = v0x * v0x + v0y * v0y;
// dot(v0,v1)
float dot01 = v0x * v1x + v0y * v1y;
// dot(v0,v2)
float dot02 = v0x * v2x + v0y * v2y;
// dot(v1, v1)
float dot11 = v1x * v1x + v1y * v1y;
// dot(v1, v2)
float dot12 = v1x * v2x + v1y * v2y;
float det = dot00 * dot11 - dot01 * dot01;
if(det == 0) {
return false;
}
float invDet = 1f / det;
float u = (dot11 * dot02 - dot01 * dot12) * invDet;
float v = (dot00 * dot12 - dot01 * dot02) * invDet;
return (u >= 0) && (v >= 0) && (u + v < 1f);
}
/**
* Determine if the supplied {@link Line} intersects with the supplied {@link Triangle}.
*
* @param L
* @param triangle
* @return
*/
public static boolean lineIntersectsTriangle(Line L, Triangle triangle) {
return Line.lineIntersectLine(L.a, L.b, triangle.a, triangle.b) ||
Line.lineIntersectLine(L.a, L.b, triangle.b, triangle.c) ||
Line.lineIntersectLine(L.a, L.b, triangle.c, triangle.a);
}
/**
* Determine if the supplied {@link Line} intersects with the supplied {@link Triangle}.
*
* @param a
* @param b
* @param triangle
* @return
*/
public static boolean lineIntersectsTriangle(Vector2f a, Vector2f b, Triangle triangle) {
return Line.lineIntersectLine(a, b, triangle.a, triangle.b) ||
Line.lineIntersectLine(a, b, triangle.b, triangle.c) ||
Line.lineIntersectLine(a, b, triangle.c, triangle.a);
}
/**
* Determine if the supplied {@link Rectangle} and {@link Triangle} intersect.
*
* <p>
* The algorithm used is from <a>http://www.sebleedelisle.com/2009/05/super-fast-trianglerectangle-intersection-test/</a>
*
* @param rectangle
* @param t
* @return true if the rectangle intersects the triangle
*/
public static boolean rectangleIntersectsTriangle(Rectangle rectangle, Triangle triangle) {
float x0 = triangle.a.x;
float y0 = triangle.a.y;
float x1 = triangle.b.x;
float y1 = triangle.b.y;
float x2 = triangle.c.x;
float y2 = triangle.c.y;
return rectangleIntersectsTriangle(rectangle, x0, y0, x1, y1, x2, y2);
}
/**
* Determine if the supplied {@link Rectangle} and {@link Triangle} intersect.
*
* <p>
* The algorithm used is from <a>http://www.sebleedelisle.com/2009/05/super-fast-trianglerectangle-intersection-test/</a>
*
* @param rectangle
* @param x0
* @param y0
* @param x1
* @param y1
* @param x2
* @param y2
* @return true if the rectangle intersects the triangle
*/
public static boolean rectangleIntersectsTriangle(Rectangle rectangle, float x0, float y0, float x1, float y1, float x2, float y2) {
int l = rectangle.x;
int r = rectangle.x + rectangle.width;
int t = rectangle.y;
int b = rectangle.y + rectangle.height;
int b0 = 0;
if ( x0 > l ) b0 = 1;
if ( y0 > t ) b0 |= (b0 << 1);
if ( x0 > r ) b0 |= (b0 << 2);
if ( y0 > b ) b0 |= (b0 << 3);
if ( b0 == 3 ) return true;
int b1 = 0;
if ( x1 > l ) b1 = 1;
if ( y1 > t ) b1 |= (b1 << 1);
if ( x1 > r ) b1 |= (b1 << 2);
if ( y1 > b ) b1 |= (b1 << 3);
if ( b1 == 3 ) return true;
int b2 = 0;
if ( x2 > l ) b2 = 1;
if ( y2 > t ) b2 |= (b2 << 1);
if ( x2 > r ) b2 |= (b2 << 2);
if ( y2 > b ) b2 |= (b2 << 3);
if ( b2 == 3 ) return true;
int i0 = b0 ^ b1;
if (i0 != 0)
{
float m = (y1 - y0) / (x1 - x0);
float c = y0 -(m * x0);
if ( (i0 & 1) > 0 ) { float s = m * l + c; if ( s > t && s < b) return true; }
if ( (i0 & 2) > 0 ) { float s = (t - c) / m; if ( s > l && s < r) return true; }
if ( (i0 & 4) > 0 ) { float s = m * r + c; if ( s > t && s < b) return true; }
if ( (i0 & 8) > 0 ) { float s = (b - c) / m; if ( s > l && s < r) return true; }
}
int i1 = b1 ^ b2;
if (i1 != 0)
{
float m = (y2 - y1) / (x2 - x1);
float c = y1 -(m * x1);
if ( (i1 & 1) > 0 ) { float s = m * l + c; if ( s > t && s < b) return true; }
if ( (i1 & 2) > 0 ) { float s = (t - c) / m; if ( s > l && s < r) return true; }
if ( (i1 & 4) > 0 ) { float s = m * r + c; if ( s > t && s < b) return true; }
if ( (i1 & 8) > 0 ) { float s = (b - c) / m; if ( s > l && s < r) return true; }
}
int i2 = b0 ^ b2;
if (i2 != 0)
{
float m = (y2 - y0) / (x2 - x0);
float c = y0 - (m * x0);
if ( (i2 & 1) > 0 ) { float s = m * l + c; if ( s > t && s < b) return true; }
if ( (i2 & 2) > 0 ) { float s = (t - c) / m; if ( s > l && s < r) return true; }
if ( (i2 & 4) > 0 ) { float s = m * r + c; if ( s > t && s < b) return true; }
if ( (i2 & 8) > 0 ) { float s = (b - c) / m; if ( s > l && s < r) return true; }
}
return false;
}
}
| 8,709 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Line.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/math/Line.java | /*
* leola-live
* see license.txt
*/
package seventh.math;
import java.awt.geom.Line2D;
/**
* @author Tony
*
*/
public class Line {
public Vector2f a;
public Vector2f b;
/**
* Constructs a new Line.
*
* @param a
* @param b
*/
public Line(Vector2f a, Vector2f b) {
this.a = a;
this.b = b;
}
/**
* Determine if a line intersects with another line.
*
* @param l1
* @param l2
* @return
*/
public static boolean lineIntersectLine( Line l1, Line l2 ) {
return lineIntersectLine(l1.a, l1.b, l2.a, l2.b);
}
/**
* Determine if a line intersects with another line
*
* @param v1
* @param v2
* @param v3
* @param v4
* @return
*/
public static boolean lineIntersectLine( Vector2f v1, Vector2f v2, Vector2f v3, Vector2f v4 )
{
return Line2D.linesIntersect(v1.x, v1.y, v2.x, v2.y, v3.x, v3.y, v4.x, v4.y);
// float denom = ((v4.y - v3.y) * (v2.x - v1.x)) - ((v4.x - v3.x) * (v2.y - v1.y));
// float numerator = ((v4.x - v3.x) * (v1.y - v3.y)) - ((v4.y - v3.y) * (v1.x - v3.x));
//
// float numerator2 = ((v2.x - v1.x) * (v1.y - v3.y)) - ((v2.y - v1.y) * (v1.x - v3.x));
//
// if ( denom == 0.0f ) return false;
//
// float ua = numerator / denom;
// float ub = numerator2/ denom;
//
// return (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f);
}
/**
* Line Line intersection. You've crossed the line, line! (maybe, we'll see).
*
* @param v1x
* @param v1y
* @param v2x
* @param v2y
* @param v3x
* @param v3y
* @param v4x
* @param v4y
* @return true if the lines cross
*/
public static boolean lineIntersectLine( float v1x, float v1y, float v2x, float v2y, float v3x, float v3y, float v4x, float v4y ) {
return Line2D.linesIntersect(v1x, v1y, v2x, v2y, v3x, v3y, v4x, v4y);
}
// public static boolean lineIntersectsRect(float x0, float y0, float x1, float y1, Rectangle rect) {
//
// float l = rect.x;
//
// float d = x1 - x0;
// if(d==0) return false;
//
// float m = (y1 - y0) / (x1 - x0);
// float c = y0 - (m*x0);
//
// float topIntersection = 0f;
// float bottomIntersection = 0f;
//
// if(m>0) {
// topIntersection = (m*rect.x + c);
// }
// return false;
// }
/**
* Determine if a line intersects with a {@link Rectangle}.
*
* @param rect
* @return
*/
public static boolean lineIntersectsRectangle(Line l, Rectangle rect) {
return lineIntersectsRectangle(l.a, l.b, rect);
}
/**
* Determine if a line intersects with a {@link Rectangle}.
*
* @param rect
* @return
*/
public static boolean lineIntersectsRectangle(Vector2f v1, Vector2f v2, Rectangle rect) {
//Line2D line = new Line2D.Float(v1.x, v1.y, v2.x, v2.y);
//return line.intersects(new java.awt.Rectangle(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()));
return intersectsLine(rect, v1.x, v1.y, v2.x, v2.y);
//
// int x = rect.getX();
// int y = rect.getY();
// int width = rect.getWidth();
// int height = rect.getHeight();
//
// Vector2f lowerLeft = new Vector2f( x, y+height );
// Vector2f upperRight = new Vector2f( x+width, y );
// Vector2f upperLeft = new Vector2f( x, y );
// Vector2f lowerRight = new Vector2f( x+width, y+height);
//
// // check if it is inside
// if (v1.x > lowerLeft.x && v1.x < upperRight.x && v1.y < lowerLeft.y && v1.y > upperRight.y &&
// v2.x > lowerLeft.x && v2.x < upperRight.x && v2.y < lowerLeft.y && v2.y > upperRight.y ) {
// return true;
// }
//
// // check each line for intersection
// if (lineIntersectLine(v1,v2, upperLeft, lowerLeft ) ) return true;
// if (lineIntersectLine(v1,v2, lowerLeft, lowerRight) ) return true;
// if (lineIntersectLine(v1,v2, upperLeft, upperRight) ) return true;
// if (lineIntersectLine(v1,v2, upperRight, lowerRight) ) return true;
//
// // no collision
// return false;
}
/**
* The bitmask that indicates that a point lies to the left of
* this <code>Rectangle2D</code>.
* @since 1.2
*/
private static final int OUT_LEFT = 1;
/**
* The bitmask that indicates that a point lies above
* this <code>Rectangle2D</code>.
* @since 1.2
*/
private static final int OUT_TOP = 2;
/**
* The bitmask that indicates that a point lies to the right of
* this <code>Rectangle2D</code>.
* @since 1.2
*/
private static final int OUT_RIGHT = 4;
/**
* The bitmask that indicates that a point lies below
* this <code>Rectangle2D</code>.
* @since 1.2
*/
private static final int OUT_BOTTOM = 8;
/**
* {@inheritDoc}
* @since 1.2
*/
private static int outcode(Rectangle r, float x, float y) {
/*
* Note on casts to double below. If the arithmetic of
* x+w or y+h is done in int, then we may get integer
* overflow. By converting to double before the addition
* we force the addition to be carried out in double to
* avoid overflow in the comparison.
*
* See bug 4320890 for problems that this can cause.
*/
int out = 0;
if (r.width <= 0) {
out |= OUT_LEFT | OUT_RIGHT;
} else if (x < r.x) {
out |= OUT_LEFT;
} else if (x > r.x + (float)r.width) {
out |= OUT_RIGHT;
}
if (r.height <= 0) {
out |= OUT_TOP | OUT_BOTTOM;
} else if (y < r.y) {
out |= OUT_TOP;
} else if (y > r.y + (float)r.height) {
out |= OUT_BOTTOM;
}
return out;
}
/**
* Tests if the specified line segment intersects the interior of this
* <code>Rectangle2D</code>.
*
* @param x1 the X coordinate of the start point of the specified
* line segment
* @param y1 the Y coordinate of the start point of the specified
* line segment
* @param x2 the X coordinate of the end point of the specified
* line segment
* @param y2 the Y coordinate of the end point of the specified
* line segment
* @return <code>true</code> if the specified line segment intersects
* the interior of this <code>Rectangle2D</code>; <code>false</code>
* otherwise.
* @since 1.2
*/
private static boolean intersectsLine(Rectangle r, float x1, float y1, float x2, float y2) {
int out1, out2;
if ((out2 = outcode(r, x2, y2)) == 0) {
return true;
}
while ((out1 = outcode(r, x1, y1)) != 0) {
if ((out1 & out2) != 0) {
return false;
}
if ((out1 & (OUT_LEFT | OUT_RIGHT)) != 0) {
float x = (float)r.x;
if ((out1 & OUT_RIGHT) != 0) {
x += r.width;
}
y1 = y1 + (x - x1) * (y2 - y1) / (x2 - x1);
x1 = x;
} else {
float y = (float)r.y;
if ((out1 & OUT_BOTTOM) != 0) {
y += r.height;
}
x1 = x1 + (y - y1) * (x2 - x1) / (y2 - y1);
y1 = y;
}
}
return true;
}
/**
* Returns true if the line intersects the rectangle, and stores the clipping points in the near and far vectors.
*
* @param line
* @param rect
* @param near - the near collision
* @param far - the far collision
* @return if a collision occurred
*/
public static boolean lineIntersectsRectangle(Line line, Rectangle rect, Vector2f near, Vector2f far) {
return lineIntersectsRectangle(line.a, line.b, rect, near, far);
}
/**
* Returns true if the line intersects the rectangle, and stores the clipping points in the near and far vectors.
*
* @param v1
* @param v2
* @param rect
* @param near - the near collision
* @param far - the far collision
* @return if a collision occurred
*/
public static boolean lineIntersectsRectangle(Vector2f v1, Vector2f v2, Rectangle rect, Vector2f near, Vector2f far) {
Vector2f O = v1;
Vector2f D = new Vector2f();
Vector2f.Vector2fNormalize(v2, D);
Vector2f E = new Vector2f();
E.x = rect.getWidth() / 2;
E.y = rect.getHeight() / 2;
Vector2f C = new Vector2f();
C.x = rect.getX() + E.x;
C.y = rect.getY() + E.y;
float t[] = {0, 0}; /* parametric values corresponding to the points where the line intersects the AABB. */
boolean result = intersectLineAABB(O, D, C, E, t, FloatUtil.epsilon);
Vector2f tmp = new Vector2f();
// near = O + t0 * D
Vector2f.Vector2fMult(D, t[0], tmp);
Vector2f.Vector2fAdd(O, tmp, near);
// far = O + t1 * D
Vector2f.Vector2fMult(D, t[1], tmp);
Vector2f.Vector2fAdd(O, tmp, far);
return result && (rect.contains(far)
|| rect.contains(near));
}
/**
* Calculates the far collision point of the {@link Line} through the {@link Rectangle}.
*
* <p>
* It is recommended that the {@link Line} is guaranteed to intersect the supplied {@link Rectangle}.
*
* @param L
* @param rect
* @return
*/
public static Vector2f farCollisionPoint(Line L, Rectangle rect) {
Vector2f near = new Vector2f();
Vector2f far = new Vector2f();
Line.lineIntersectsRectangle(L, rect, near, far);
return far;
}
/**
* Calculates the near collision point of the {@link Line} through the {@link Rectangle}.
*
* <p>
* It is recommended that the {@link Line} is guaranteed to intersect the supplied {@link Rectangle}.
*
* @param L
* @param rect
* @return
*/
public static Vector2f nearCollisionPoint(Line L, Rectangle rect) {
Vector2f near = new Vector2f();
Vector2f far = new Vector2f();
Line.lineIntersectsRectangle(L, rect, near, far);
return near;
}
/**
* Great thanks to jvk on this article:
* http://www.gamedev.net/community/forums/topic.asp?topic_id=433699
*
* @param O
* @param D
* @param C
* @param e
* @param t
* @param epsilon
* @return
*/
private static boolean intersectLineAABB(
Vector2f O, // Line origin
Vector2f D, // Line direction (unit length)
Vector2f C, // AABB center
Vector2f e, // AABB extents
float t[], // Parametric points of intersection on output
float epsilon) // Threshold for epsilon test
{
int parallel = 0;
boolean found = false;
Vector2f d = new Vector2f();
Vector2f.Vector2fSubtract(C, O, d);
for (int i = 0; i < 2; ++i)
{
if (Math.abs(D.get(i)) < epsilon)
parallel |= 1 << i;
else
{
float es = (D.get(i) > 0.0f) ? e.get(i) : -e.get(i);
float invDi = 1.0f / D.get(i);
if (!found)
{
t[0] = (d.get(i) - es) * invDi;
t[1] = (d.get(i) + es) * invDi;
found = true;
}
else
{
float s = (d.get(i) - es) * invDi;
if (s > t[0])
t[0] = s;
s = (d.get(i) + es) * invDi;
if (s < t[1])
t[1] = s;
if (t[0] > t[1])
return false;
}
}
}
if (parallel != 0) {
for (int i = 0; i < 2; ++i) {
if ((parallel & (1 << i)) != 0 ) {
if (Math.abs(d.get(i) - t[0] * D.get(i)) > e.get(i) || Math.abs(d.get(i) - t[1] * D.get(i)) > e.get(i)) {
return false;
}
}
}
}
return true;
}
public static void main(String [] args) {
Line l = new Line(new Vector2f(-1, -1), new Vector2f(1, 1));
// Vector2f Pnear = new Vector2f();
// Vector2f Pfar = new Vector2f();
Vector2f C = new Vector2f(2, 2);
Vector2f E = new Vector2f(2, 2);
// Vector2f [] D = new Vector2f[2];
// //for(int i = 0 ; i < 2; i++) {
// D[0] = new Vector2f(0,0);
// D[1] = new Vector2f(0,0);
// //}
// l.SegmentIntersectBox(l, C, R, D, Pnear, Pfar);
float [] t = {0, 0};
intersectLineAABB(l.a, l.b, C, E, t, FloatUtil.epsilon);
Vector2f tmp = new Vector2f();
Vector2f near = new Vector2f();
Vector2f far = new Vector2f();
Vector2f.Vector2fMult(l.b, t[0], tmp);
Vector2f.Vector2fAdd(l.a, tmp, near);
Vector2f.Vector2fMult(l.b, t[1], tmp);
Vector2f.Vector2fAdd(l.a, tmp, far);
System.out.println();
}
}
| 13,869 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Vector4f.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/math/Vector4f.java | /*
* leola-live
* see license.txt
*/
package seventh.math;
/**
* @author Tony
*
*/
public class Vector4f {
/**
* X Component
*/
public float x;
/**
* Y Component
*/
public float y;
/**
* Z Component
*/
public float z;
/**
* W Component
*/
public float w;
/**
* @param x
* @param y
* @param z
* @param w
*/
public Vector4f(float x, float y, float z, float w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/**
*/
public Vector4f() {
this(0,0,0,0);
}
/**
* Sets all components.
*
* @param x
* @param y
* @param z
* @param w
*/
public void set(float x, float y, float z, float w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/**
* @return the x
*/
public float getX() {
return this.x;
}
/**
* @param x the x to set
*/
public void setX(float x) {
this.x = x;
}
/**
* @return the y
*/
public float getY() {
return this.y;
}
/**
* @param y the y to set
*/
public void setY(float y) {
this.y = y;
}
/**
* @return the z
*/
public float getZ() {
return this.z;
}
/**
* @param z the z to set
*/
public void setZ(float z) {
this.z = z;
}
/**
* @return the w
*/
public float getW() {
return this.w;
}
/**
* @param w the w to set
*/
public void setW(float w) {
this.w = w;
}
}
| 1,719 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
FastMath.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/math/FastMath.java | /*
* leola-live
* see license.txt
*/
package seventh.math;
import java.lang.reflect.Method;
/**
* Utility and fast math functions.
*
* Thanks to:<br>
* Riven on JavaGaming.org for sin/cos/atan2 tables.<br>
* Roquen on JavaGaming.org for random numbers.<br>
* pjt33 on JavaGaming.org for fixed point.<br>
* Jim Shima for atan2_fast.<br>
*
* <p>
* Taken from JavaGaming.org from <b>Nate</b>
*
* @author Nate
*/
public class FastMath {
static public final float PI = 3.1415926535897932384626433832795028841971f;
static public final float fullCircle = PI * 2;
static private final int SIN_BITS = 12; // Adjust for accuracy.
static private final int SIN_MASK = ~(-1 << SIN_BITS);
static private final int SIN_COUNT = SIN_MASK + 1;
static private final float radFull = PI * 2;
static private final float degFull = 360;
static private final float radToIndex = SIN_COUNT / radFull;
static private final float degToIndex = SIN_COUNT / degFull;
static public final float [] sin = new float[SIN_COUNT];
static public final float [] cos = new float[SIN_COUNT];
static {
for (int i = 0; i < SIN_COUNT; i++) {
float a = (i + 0.5f) / SIN_COUNT * radFull;
sin[i] = (float)Math.sin(a);
cos[i] = (float)Math.cos(a);
}
}
static public final float sin(float rad) {
return sin[(int)(rad * radToIndex) & SIN_MASK];
}
static public final float cos(float rad) {
return cos[(int)(rad * radToIndex) & SIN_MASK];
}
static public final float sin(int deg) {
return sin[(int)(deg * degToIndex) & SIN_MASK];
}
static public final float cos(int deg) {
return cos[(int)(deg * degToIndex) & SIN_MASK];
}
private static final int ATAN2_BITS = 7; // Adjust for accuracy.
private static final int ATAN2_BITS2 = ATAN2_BITS << 1;
private static final int ATAN2_MASK = ~(-1 << ATAN2_BITS2);
private static final int ATAN2_COUNT = ATAN2_MASK + 1;
private static final int ATAN2_DIM = (int)Math.sqrt(ATAN2_COUNT);
private static final float INV_ATAN2_DIM_MINUS_1 = 1.0f / (ATAN2_DIM - 1);
private static final float [] atan2 = new float[ATAN2_COUNT];
static {
for (int i = 0; i < ATAN2_DIM; i++) {
for (int j = 0; j < ATAN2_DIM; j++) {
float x0 = (float)i / ATAN2_DIM;
float y0 = (float)j / ATAN2_DIM;
atan2[j * ATAN2_DIM + i] = (float) Math.atan2(y0, x0);
}
}
}
public static final float atan2(float y, float x) {
float add, mul;
if ( x < 0 ) {
if ( y < 0 ) {
y = -y;
mul = 1;
}
else
mul = -1;
x = -x;
add = -3.141592653f;
}
else {
if ( y < 0 ) {
y = -y;
mul = -1;
}
else
mul = 1;
add = 0;
}
float invDiv = 1 / (((x < y) ? y : x) * INV_ATAN2_DIM_MINUS_1);
int xi = (int) (x * invDiv);
int yi = (int) (y * invDiv);
return (atan2[yi * ATAN2_DIM + xi] + add) * mul;
}
/**
* This is a very fast atan2, but not very accurate.
*/
static public float atan2_fast(float y, float x) {
// From: http://dspguru.com/comp.dsp/tricks/alg/fxdatan2.htm
float abs_y = y < 0 ? -y : y;
float angle;
if ( x >= 0 )
angle = 0.7853981633974483f - 0.7853981633974483f * (x - abs_y) / (x + abs_y);
else
angle = 2.356194490192345f - 0.7853981633974483f * (x + abs_y) / (abs_y - x);
return y < 0 ? -angle : angle;
}
static private Method sqrtMethod;
static {
try {
sqrtMethod = Class.forName("android.util.FloatMath").getMethod("sqrt", new Class[] {
float.class
});
}
catch (Exception ex) {
try {
sqrtMethod = Class.forName("java.lang.Math").getMethod("sqrt", new Class[] {
double.class
});
}
catch (Exception ignored) {
}
}
}
static public final float sqrt(float value) {
try {
return ((Number) sqrtMethod.invoke(null, value)).floatValue();
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Inverse square root approximation
*
* @param x
* @return
*/
public static float a_isqrt(float x) {
float hx = x * 0.5f;
int ix;
float r;
// make initial guess
ix = Float.floatToRawIntBits(x);
ix = 0x5f3759df - (ix >> 1);
r = Float.intBitsToFloat(ix);
// do some number of newton-ralphson steps,
// each doubles the number of accurate
// binary digits.
r = r * (1.5f - hx * r * r);
// r = r*(1.5f-hx*r*r);
// r = r*(1.5f-hx*r*r);
// r = r*(1.5f-hx*r*r);
return r; // 1/sqrt(x)
// return r*x; // sqrt(x)
}
/**
* square root approximation
*
* @param x
* @return
*/
public static float a_sqrt(float x) {
float hx = x * 0.5f;
int ix;
float r;
// make initial guess
ix = Float.floatToRawIntBits(x);
ix = 0x5f3759df - (ix >> 1);
r = Float.intBitsToFloat(ix);
// do some number of newton-ralphson steps,
// each doubles the number of accurate
// binary digits.
r = r * (1.5f - hx * r * r);
// r = r*(1.5f-hx*r*r);
// r = r*(1.5f-hx*r*r);
// r = r*(1.5f-hx*r*r);
return r * x; // sqrt(x)
}
/**
* Fixed point multiply.
*/
static public int multiply(int x, int y) {
return (int)((long) x * (long) y >> 16);
}
/**
* Fixed point divide.
*/
static public int divide(int x, int y) {
return (int)((((long) x) << 16) / y);
}
static private int randomSeed = (int)System.currentTimeMillis();
/**
* Returns a random number between 0 (inclusive) and the specified value
* (inclusive).
*
* @param range
* Must be >= 0.
*/
static public final int random(int range) {
int seed = randomSeed * 1103515245 + 12345;
randomSeed = seed;
return ((seed >>> 15) * (range + 1)) >>> 17;
}
static public final int random(int start, int end) {
int seed = randomSeed * 1103515245 + 12345;
randomSeed = seed;
return (((seed >>> 15) * ((end - start) + 1)) >>> 17) + start;
}
static public final boolean randomBoolean() {
int seed = randomSeed * 1103515245 + 12345;
randomSeed = seed;
return seed > 0;
}
static public final float random() {
int seed = randomSeed * 1103515245 + 12345;
randomSeed = seed;
return (seed >>> 8) * (1f / (1 << 24));
}
static public int nextPowerOfTwo(int value) {
return 1 << (32 - Integer.numberOfLeadingZeros(value - 1));
}
/**
* Takes the minimum value.
*
* @param a
* @param b
* @return
*/
public static float min(float a, float b) {
return (a <= b) ? a : b;
}
/**
* Takes the minimum value.
*
* @param a
* @param b
* @return
*/
public static double min(double a, double b) {
return (a <= b) ? a : b;
}
/**
* Takes the minimum value.
*
* @param a
* @param b
* @return
*/
public static int min(int a, int b) {
return (a <= b) ? a : b;
}
/**
* Takes the minimum value.
*
* @param a
* @param b
* @return
*/
public static long min(long a, long b) {
return (a <= b) ? a : b;
}
// /---
/**
* Takes the maximum value.
*
* @param a
* @param b
* @return
*/
public static float max(float a, float b) {
return (a >= b) ? a : b;
}
/**
* Takes the maximum value.
*
* @param a
* @param b
* @return
*/
public static double max(double a, double b) {
return (a >= b) ? a : b;
}
/**
* Takes the maximum value.
*
* @param a
* @param b
* @return
*/
public static int max(int a, int b) {
return (a >= b) ? a : b;
}
/**
* Takes the maximum value.
*
* @param a
* @param b
* @return
*/
public static long max(long a, long b) {
return (a >= b) ? a : b;
}
} | 8,747 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Vector2f.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/math/Vector2f.java | /*
* leola-live
* see license.txt
*/
package seventh.math;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
/**
* 2 component vector.
*
* @author Tony
*
*/
public /*strictfp*/ final class Vector2f {
/**
* The zero vector
*/
public static final Vector2f ZERO_VECTOR = new Vector2f(0, 0);
/**
* The Right vector
*/
public static final Vector2f RIGHT_VECTOR = new Vector2f(1, 0);
/**
* X and Y components.
*/
public float x, y;
/**
* Constructs a new Vector2f
*/
public Vector2f() {
this.x = this.y = 0;
}
/**
* Constructs a new Vector2f
*
* @param x
* @param y
*/
public Vector2f(float x, float y) {
this.x = x; this.y = y;
}
/**
* Constructs a new Vector2f
*
* @param v
*/
public Vector2f(float []v) {
this.x = v[0]; this.y = v[1];
}
/**
* @param v
*/
public Vector2f(Vector2f v) {
this.x = v.x; this.y = v.y;
}
/**
* Get a component of the vector.
*
* @param i
* @return
*/
public float get(int i) {
return (i == 0) ? this.x : this.y;
}
/**
* Set this vector.
*
* @param x
* @param y
*/
public void set(float x, float y) {
this.x = x; this.y = y;
}
/**
* Set this vector
*
* @param v
*/
public void set(Vector2f v) {
this.x = v.x; this.y = v.y;
}
/**
* Set this vector.
* @param v
*/
public void set(float[] v) {
this.x = v[0]; this.y = v[1];
}
/**
* Zero out the {@link Vector2f}
*/
public void zeroOut() {
this.x=0;
this.y=0;
}
/**
* Is this the Zero Vector?
* @return
*/
public boolean isZero() {
return this.x == 0 && this.y == 0;
}
/**
* Round to the nearest integer.
*/
public void round() {
this.x = Math.round(this.x);
this.y = Math.round(this.y);
}
/**
* Subtract a {@link Vector2f} from this one.
*
* @param v
* @return
*/
public Vector2f subtract(Vector2f v) {
Vector2f dest = new Vector2f();
Vector2fSubtract(this, v, dest);
return dest;
}
/**
* Add a {@link Vector2f} to this one.
*
* @param v
* @return
*/
public Vector2f addition(Vector2f v) {
Vector2f dest = new Vector2f();
Vector2fAdd(this, v, dest);
return dest;
}
/**
* Multiply this by a {@link Vector2f}.
*
* @param v
* @return
*/
public Vector2f mult(Vector2f v) {
return new Vector2f( this.x * v.x, this.y * v.y );
}
/**
* Multiply this by a scalar value.
*
* @param scalar
* @return
*/
public Vector2f mult(float scalar) {
return new Vector2f(this.x * scalar, this.y * scalar );
}
/**
* Multiply this by a {@link Vector2f}.
*
* @param v
* @return
*/
public Vector2f div(Vector2f v) {
return new Vector2f( this.x / v.x, this.y / v.y );
}
/**
* Divide this by a scalar value.
*
* @param scalar
* @return
*/
public Vector2f div(float scalar) {
return new Vector2f(this.x / scalar, this.y / scalar );
}
/**
* Normalize this vector
*/
public void normalize() {
float flLen = (float)Math.sqrt( (this.x * this.x + this.y * this.y) );
if ( flLen == 0 ) return;
flLen = 1.0f / flLen;
this.x = this.x * flLen;
this.y = this.y * flLen;
}
/**
* The length of this vector squared.
*
* @return
*/
public float lengthSquared() {
return this.x * this.x + this.y * this.y;
}
/**
* The length of this vector squared.
*
* @return
*/
public float length() {
return (float)Math.sqrt( (this.x * this.x + this.y * this.y) );
}
/**
* Rotate the {@link Vector2f}.
*
* @param radians
*/
public Vector2f rotate(double radians) {
// T : V->W
// W = | cos(r) -sin(r) |
// | sin(r) cos(r) |
//
// V = | x |
// | y |
//
// T = | (xcos(r) - ysin(r)) |
// | (xsin(r) + ycos(r)) |
double x1 = this.x * cos(radians) - this.y * sin(radians);
double y1 = this.x * sin(radians) + this.y * cos(radians);
return new Vector2f((float)x1, (float)y1);
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object o) {
if ( o instanceof Vector2f ) {
Vector2f v = (Vector2f)o;
return v.x == this.x && this.y == v.y;
}
return false;
}
public int hashCode() {
return ((Float)x).hashCode() + ((Float)y).hashCode();
}
@Override
public String toString() {
return "{ \"x\": " + this.x + ", \"y\": " + this.y + "}";
}
/* (non-Javadoc)
* @see org.myriad.shared.Clonable#createClone()
*/
public Vector2f createClone() {
return new Vector2f(this.x, this.y);
}
/**
* Converts the vector to an array.
*
* @return
*/
public float[] toArray() {
return new float[]{this.x, this.y};
}
/*
=======================================================================================
Free functions
=======================================================================================
*/
/**
* @param v1
* @param v2
* @return
*/
public static /*strictfp*/ float Vector2fCrossProduct(Vector2f v1, Vector2f v2) {
return v1.x * v2.y - v1.y * v2.x;
}
/**
* @param v1
* @param v2
* @return
*/
public static /*strictfp*/ float Vector2fDotProduct(Vector2f v1, Vector2f v2) {
return v1.x * v2.x + v1.y * v2.y;
}
/**
* The determinant.
*
* @param v1
* @param v2
* @return
*/
public static /*strictfp*/ float Vector2fDet(Vector2f v1, Vector2f v2) {
return v1.x * v2.y - v2.x * v1.y;
}
/**
* Addition
*
* @param a
* @param b
* @param dest
*/
public static /*strictfp*/ void Vector2fAdd(Vector2f a, Vector2f b, Vector2f dest) {
dest.x = a.x + b.x;
dest.y = a.y + b.y;
}
/**
* Addition
*
* @param a
* @param scalar
* @param dest
*/
public static /*strictfp*/ void Vector2fAdd(Vector2f a, float scalar, Vector2f dest) {
dest.x = a.x + scalar;
dest.y = a.y + scalar;
}
/**
* Subtraction
*
* @param a
* @param b
* @param dest
*/
public static /*strictfp*/ void Vector2fSubtract(Vector2f a, Vector2f b, Vector2f dest) {
dest.x = a.x - b.x;
dest.y = a.y - b.y;
}
/**
* Subtraction
*
* @param a
* @param scalar
* @param dest
*/
public static /*strictfp*/ void Vector2fSubtract(Vector2f a, float scalar, Vector2f dest) {
dest.x = a.x - scalar;
dest.y = a.y - scalar;
}
/**
* Multiplication.
*
* @param a
* @param b
* @param dest
*/
public static /*strictfp*/ void Vector2fMult(Vector2f a, Vector2f b, Vector2f dest) {
dest.x = a.x * b.x;
dest.y = a.y * b.y;
}
/**
* Multiplication.
*
* @param a
* @param scalar
* @param dest
*/
public static /*strictfp*/ void Vector2fMult(Vector2f a, float scalar, Vector2f dest) {
dest.x = a.x * scalar;
dest.y = a.y * scalar;
}
/**
* Division.
*
* @param a
* @param b
* @param dest
*/
public static /*strictfp*/ void Vector2fDiv(Vector2f a, Vector2f b, Vector2f dest) {
dest.x = a.x / b.x;
dest.y = a.y / b.y;
}
/**
* Division.
*
* @param a
* @param scalar
* @param dest
*/
public static /*strictfp*/ void Vector2fDiv(Vector2f a, float scalar, Vector2f dest) {
dest.x = a.x / scalar;
dest.y = a.y / scalar;
}
/**
* Rotate about the vector a.
*
* @param a
* @param scalar
* @param dest
*/
public static /*strictfp*/ void Vector2fRotate(Vector2f a, double radians, Vector2f dest) {
float x = (float)(a.x * cos(radians) - a.y * sin(radians));
float y = (float)(a.x * sin(radians) + a.y * cos(radians));
dest.x = x;
dest.y = y;
}
/**
* Takes in two NORMALIZED vectors and calculates the angle between
* them.
* @param a
* @param b
* @return the angle between the two vectors in radians.
*/
public static /*strictfp*/ double Vector2fAngle(Vector2f a, Vector2f b) {
double angle = atan2(b.y, b.x) - atan2(a.y, a.x);
return angle;
}
/**
* Does a vector scale and addition:
*
* <p>
* dest = a + b*scalar;
*
* @param a
* @param b
* @param scalar
* @param dest
*/
public static /*strictfp*/ void Vector2fMA(Vector2f a, Vector2f b, float scalar, Vector2f dest) {
dest.x = a.x + b.x * scalar;
dest.y = a.y + b.y * scalar;
}
/**
* Does a vector scale and subtraction:
*
* <p>
* dest = a - b*scalar;
*
* @param a
* @param b
* @param scalar
* @param dest
*/
public static /*strictfp*/ void Vector2fMS(Vector2f a, Vector2f b, float scalar, Vector2f dest) {
dest.x = a.x - b.x * scalar;
dest.y = a.y - b.y * scalar;
}
/**
* Copies a into dest
* @param a
* @param dest
*/
public static /*strictfp*/ void Vector2fCopy(Vector2f a, Vector2f dest) {
dest.x = a.x;
dest.y = a.y;
}
/**
* Test for equality.
*
* @param a
* @param b
* @return
*/
public static /*strictfp*/ boolean Vector2fEquals(Vector2f a, Vector2f b) {
return a.x == b.x && a.y == b.y;
}
/**
* Accounts for float inaccuracy.
*
* @param a
* @param b
* @return
*/
public static /*strictfp*/ boolean Vector2fApproxEquals(Vector2f a, Vector2f b) {
return FloatUtil.eq(a.x, b.x) && FloatUtil.eq(a.y, b.y);
}
/**
* Accounts for float inaccuracy.
*
* @param a
* @param b
* @param epsilon
* @return
*/
public static /*strictfp*/ boolean Vector2fApproxEquals(Vector2f a, Vector2f b, float epsilon) {
float tmp = FloatUtil.epsilon;
FloatUtil.epsilon = epsilon;
boolean result = FloatUtil.eq(a.x, b.x) && FloatUtil.eq(a.y, b.y);
FloatUtil.epsilon = tmp;
return result;
}
/**
* Unit length of the vector.
*
* @param a
* @return
*/
public static /*strictfp*/ float Vector2fLength(Vector2f a) {
return (float)Math.sqrt( (a.x * a.x + a.y * a.y) );
}
/**
* The length squared.
*
* @param a
* @return
*/
public static /*strictfp*/ float Vector2fLengthSq(Vector2f a) {
return (a.x * a.x + a.y * a.y);
}
/**
* The distance between two vectors
*
* @param a
* @return
*/
public static /*strictfp*/ float Vector2fDistanceSq(Vector2f a, Vector2f b) {
return (b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y);
}
/**
* The distance between two vectors
*
* @param a
* @return
*/
public static /*strictfp*/ float Vector2fDistance(Vector2f a, Vector2f b) {
return (float)Math.sqrt((b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y));
}
/**
* Normalizes the vector.
*
* @param a
* @param dest
*/
public static /*strictfp*/ void Vector2fNormalize(Vector2f a, Vector2f dest) {
float fLen = (float)Math.sqrt( (a.x * a.x + a.y * a.y) );
if ( fLen == 0 ) return;
//fLen = 1.0f / fLen;
dest.x = a.x / fLen;
dest.y = a.y / fLen;
}
/**
* Perpendicular {@link Vector2f} of 'a'
*
* @param a
* @param dest
*/
public static /*strictfp*/ void Vector2fPerpendicular(Vector2f a, Vector2f dest) {
float x = a.y;
float y = -a.x;
dest.x = x;
dest.y = y;
}
/**
* Zero outs the components.
*
* @param a
*/
public static /*strictfp*/ void Vector2fZeroOut(Vector2f a) {
a.x = a.y = 0;
}
/**
* Tests if this is the zero vector.
*
* @param a
* @return
*/
public static /*strictfp*/ boolean Vector2fIsZero(Vector2f a) {
return a.x == 0 && a.y == 0;
}
/**
* Calculates the length squared for each vector and determines if
* a is greater or equal in length.
*
* @param a
* @param b
* @return
*/
public static /*strictfp*/ boolean Vector2fGreaterOrEq(Vector2f a, Vector2f b) {
float aLength = (a.x * a.x + a.y * a.y);
float bLength = (b.x * b.x + b.y * b.y);
return FloatUtil.gte(aLength, bLength);
}
/**
* Rounds the components to the nearest whole number.
*
* @param a
* @param dest
*/
public static /*strictfp*/ void Vector2fRound(Vector2f a, Vector2f dest) {
dest.x = Math.round(a.x);
dest.y = Math.round(a.y);
}
/**
* Snaps the components to the nearest whole number.
*
* @param a
* @param dest
*/
public static /*strictfp*/ void Vector2fSnap(Vector2f a, Vector2f dest) {
dest.x = (int)a.x;
dest.y = (int)a.y;
}
/**
* Sets the components.
*
* @param a
* @param x
* @param y
*/
public static /*strictfp*/ void Vector2fSet(Vector2f a, float x, float y) {
a.x = x;
a.y = y;
}
/**
* Negate the vector
*
* @param a
* @param x
* @param y
*/
public static /*strictfp*/ void Vector2fNegate(Vector2f a, Vector2f dest) {
dest.x = -a.x;
dest.y = -a.y;
}
/**
* Anything but zero will be rounded to the next whole number, if negative it
* will round to the lower whole number.
*
* @param a
* @param x
* @param y
*/
public static /*strictfp*/ void Vector2fWholeNumber(Vector2f a, Vector2f dest) {
int t = (int)a.x;
float delta = a.x - (float)t;
if ( !FloatUtil.eq(delta, 0) ) {
dest.x = (a.x < 0) ? t - 1 : t + 1;
}
t = (int)a.y;
delta = a.y - (float)t;
if ( !FloatUtil.eq(delta, 0) ) {
dest.y = (a.y < 0 ) ? t - 1 : t + 1;
}
Vector2fSnap(dest, dest);
}
/**
* Interpolate between a and b vectors.
*
* @param a
* @param b
* @param alpha
* @param dest
*/
public static /*strictfp*/ void Vector2fInterpolate(Vector2f a, Vector2f b, float alpha, Vector2f dest ) {
//dest.x = b.x * alpha + a.x * (1.0f - alpha);
//dest.y = b.y * alpha + a.y * (1.0f - alpha);
dest.x = a.x + ((b.x - a.x) * alpha);
dest.y = a.y + ((b.y - a.y) * alpha);
}
/**
* Linear interpolates between a and b vectors
*
* @param a
* @param b
* @param alpha
* @param dest
*/
public static /*strictfp*/ void Vector2fLerp(Vector2f a, Vector2f b, float alpha, Vector2f dest ) {
final float invAlpha = 1.0f - alpha;
dest.x = (a.x * invAlpha) + (b.x * alpha);
dest.y = (a.y * invAlpha) + (b.y * alpha);
}
}
| 15,865 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Pair.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/math/Pair.java | /*
* leola-live
* see license.txt
*/
package seventh.math;
/**
* @author Tony
*
*/
public class Pair<X, Y> {
/**
* Get the first item
*/
private X first;
/**
* Get the second item
*/
private Y second;
/**
*
* @param first
* @param second
*/
public Pair(X first, Y second) {
this.first = first;
this.second = second;
}
/**
*/
public Pair() {
}
/**
* @param first the first to set
*/
public void setFirst(X first) {
this.first = first;
}
/**
* @return the first
*/
public X getFirst() {
return first;
}
/**
* @param second the second to set
*/
public void setSecond(Y second) {
this.second = second;
}
/**
* @return the second
*/
public Y getSecond() {
return second;
}
}
| 932 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Projection.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/math/Projection.java | /*
* see license.txt
*/
package seventh.math;
/**
* @author Tony
*
*/
public class Projection {
private double min;
private double max;
/**
* @param min
* @param max
*/
public Projection(double min, double max) {
this.min = min;
this.max = max;
}
/**
* Determines if the other {@link Projection} overlaps with this one
* @param other
* @return true if they overlap
*/
public boolean overlaps(Projection other) {
if(other.min > this.max || this.min > other.max) {
return false;
}
return true;
}
}
| 643 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Matrix2f.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/math/Matrix2f.java | /*
* leola-live
* see license.txt
*/
package seventh.math;
/**
* A 2x2 matrix
*
* @author Tony
*
*/
public class Matrix2f {
/**
* Column 1 of the matrix
*/
public final Vector2f col1;
/**
* Column 2 of the matrix
*/
public final Vector2f col2;
/**
* Identity matrix
*/
public static final Matrix2f IDENTITY = new Matrix2f(1, 0, 0, 1);
/**
* @param m
*/
public Matrix2f(Matrix2f m) {
this.col1 = new Vector2f(m.col1);
this.col2 = new Vector2f(m.col2);
}
/**
*/
public Matrix2f() {
this.col1 = new Vector2f();
this.col2 = new Vector2f();
}
/**
* @param c1
* @param c2
*/
public Matrix2f(Vector2f c1, Vector2f c2) {
this.col1 = c1;
this.col2 = c2;
}
/**
* @param m
*/
public Matrix2f(float[][] m) {
this.col1 = new Vector2f(m[0][0], m[1][0]);
this.col2 = new Vector2f(m[0][1], m[1][1]);
}
/**
* @param c00
* @param c01
* @param c10
* @param c11
*/
public Matrix2f(float c00, float c01
,float c10, float c11) {
this.col1 = new Vector2f();
this.col2 = new Vector2f();
this.col1.x = c00; this.col2.x = c01;
this.col1.y = c10; this.col2.y = c11;
}
/**
* To Identity matrix
*/
public void toIdentity() {
this.col1.x = 1; this.col2.x = 0;
this.col1.y = 0; this.col2.y = 1;
}
/**
* To Zero Matrix
*/
public void zeroOut() {
this.col1.x = 0; this.col2.x = 0;
this.col1.y = 0; this.col2.y = 0;
}
/**
* Does a matrix multiplication against the supplied vector.
*
* @param a
* @param b
* @param dest
* @return the dest vector for convenience
*/
public static Vector2f Matrix2fMult(Matrix2f a, Vector2f b, Vector2f dest) {
float x = a.col1.x * b.x + a.col2.x * b.y;
float y = a.col1.y * b.x + a.col2.y * b.y;
dest.x = x;
dest.y = y;
return dest;
}
}
| 2,186 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Circle.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/math/Circle.java | /*
* leola-live
* see license.txt
*/
package seventh.math;
import static seventh.math.Vector2f.Vector2fDet;
import static seventh.math.Vector2f.Vector2fLengthSq;
import static seventh.math.Vector2f.Vector2fSubtract;
/**
* @author Tony
*
*/
public class Circle {
public float radius;
public Vector2f origin;
/**
* Constructs a new {@link Circle}.
*
* @param origin
* @param radius
*/
public Circle(Vector2f origin, float radius) {
this.origin = origin;
this.radius = radius;
}
public static boolean circleContainsPoint(Circle circle, Vector2f a) {
return circleContainsPoint(circle.origin.x, circle.origin.y, circle.radius, a.x, a.y);
}
/**
* Determines if the point is in the circle
*
* @param cx
* @param cy
* @param radius
* @param x
* @param y
* @return
*/
public static boolean circleContainsPoint(float cx, float cy, float radius, float x, float y) {
float distSq = (cx - x) * 2 + (cy - y) * 2;
return distSq <= radius * radius;
}
/**
* Check and see if the circle is contained within the supplied rectangle.
*
* @param circle
* @param rect
* @return
*/
public static boolean circleContainsRect(Circle circle, Rectangle rect) {
return circleContainsRect(circle.origin.x, circle.origin.y, circle.radius, rect);
}
/**
* Check and see if the circle is contained within the supplied rectangle.
*
* @param circle
* @param rect
* @return
*/
public static boolean circleContainsRect(float cx, float cy, float radius, Rectangle rect) {
int x = rect.getX();
int y = rect.getY();
int width = rect.getWidth();
int height = rect.getHeight();
// check if it is inside
return (cx > x && cx < x + width &&
cy < y + height && cy > y );
}
/**
* Determine if the supplied {@link Circle} intersects the {@link Rectangle}.
*
* @param circle
* @param rect
* @return
*/
public static boolean circleIntersectsRect(Circle circle, Rectangle rect) {
return circleIntersectsRect(circle.origin.x, circle.origin.y, circle.radius, rect);
}
/**
* Determine if the supplied {@link Circle} intersects the {@link Rectangle}.
*
* @param circle
* @param rect
* @return
*/
public static boolean circleIntersectsRect(float cx, float cy, float radius, Rectangle rect) {
float circleDistanceX = Math.abs(cx - rect.x);
float circleDistanceY = Math.abs(cy - rect.y);
if (circleDistanceX > (rect.width / 2 + radius)) { return false; }
if (circleDistanceY > (rect.height / 2 + radius)) { return false; }
if (circleDistanceX <= (rect.width / 2)) { return true; }
if (circleDistanceY <= (rect.height / 2)) { return true; }
float cornerDistanceSq = (circleDistanceX - rect.width / 2) * (circleDistanceX - rect.width / 2) +
(circleDistanceY - rect.height / 2) * (circleDistanceY - rect.height / 2);
return (cornerDistanceSq <= (radius * radius));
}
/**
* Determine if the Circle intersects the {@link Line}.
*
* @param circle
* @param line
* @return
*/
public static boolean circleIntersectsLine(Circle circle, Line line) {
return circleIntersectsLine(circle, line.a, line.b);
}
/**
* Determine if the Circle intersects the line segment.
*
* @param circle
* @param line
* @return
*/
public static boolean circleIntersectsLine(Circle circle, Vector2f a, Vector2f b) {
Vector2f ca = new Vector2f();
Vector2f cb = new Vector2f();
// translate to origin
Vector2fSubtract(a, circle.origin, ca);
Vector2fSubtract(b, circle.origin, cb);
Vector2f d = new Vector2f();
Vector2fSubtract(cb, ca, d);
float dr = Vector2fLengthSq(d);
float det = Vector2fDet(ca, cb);
// only the discriminant matters:
float delta = circle.radius * circle.radius * dr - (det * det);
/*
* Delta<0 no intersection
* Delta=0 tangent
* Delta>0 intersection
*
*/
return delta >= 0;
}
}
| 4,417 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
OBB.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/math/OBB.java | /*
* see license.txt
*/
package seventh.math;
/**
* Oriented Bounding Box. Used for rotating objects. In general, the collision checks are rather expensive (relative to
* normal {@link Rectangle} collision checks).
*
* @author Tony
*
*/
public class OBB {
public float width;
public float height;
public float orientation;
public Vector2f center;
public Vector2f topLeft, topRight, bottomLeft, bottomRight;
/**
* Defaults to nothing
*/
public OBB() {
this(0, new Vector2f(), 0, 0);
}
/**
* Based off of the supplied {@link Rectangle}
*
* @param r
*/
public OBB(Rectangle r) {
this(0, new Vector2f(r.x + r.width / 2, r.y + r.height / 2), r.width, r.height);
}
/**
* Based off of the supplied {@link Rectangle} and orientation
*
* @param orientation
* @param r
*/
public OBB(float orientation, Rectangle r) {
this(orientation, new Vector2f(r.x + r.width / 2, r.y + r.height / 2), r.width, r.height);
}
/**
* Based off of the supplied {@link OBB}
*
* @param obb
*/
public OBB(OBB obb) {
this(obb.orientation, new Vector2f(obb.center), obb.width, obb.height);
}
/**
* @param orientation
* @param cx
* @param cy
* @param width
* @param height
*/
public OBB(float orientation, float cx, float cy, float width, float height) {
this(orientation, new Vector2f(cx, cy), width, height);
}
/**
* @param orientation
* @param center
* @param width
* @param height
*/
public OBB(float orientation, Vector2f center, float width, float height) {
this.orientation = orientation;
this.center = center;
this.width = width;
this.height = height;
this.topLeft = new Vector2f();
this.topRight = new Vector2f();
this.bottomLeft = new Vector2f();
this.bottomRight = new Vector2f();
setLocation(center);
}
/**
* Updates the {@link OBB}
*
* @param newOrientation
* @param center
*/
public void update(float newOrientation, Vector2f center) {
update(newOrientation, center.x, center.y);
}
/**
* Updates the OOB internal state
*
* @param newOrientation
* @param px
* @param py
*/
public void update(float newOrientation, float px, float py) {
// first translate to center coordinate space
this.center.set(0, 0);
this.topLeft.set(center.x - width / 2f, center.y + height / 2f);
this.topRight.set(center.x + width / 2f, center.y + height / 2f);
this.bottomLeft.set(center.x - width / 2f, center.y - height / 2f);
this.bottomRight.set(center.x + width / 2f, center.y - height / 2f);
// rotate the rectangle
this.orientation = newOrientation;
Vector2f.Vector2fRotate(topLeft, orientation, topLeft);
Vector2f.Vector2fRotate(topRight, orientation, topRight);
Vector2f.Vector2fRotate(bottomLeft, orientation, bottomLeft);
Vector2f.Vector2fRotate(bottomRight, orientation, bottomRight);
// translate the rotated rectangle back to the supplied
// center position
this.center.set(px, py);
Vector2f.Vector2fAdd(topLeft, center, topLeft);
Vector2f.Vector2fAdd(topRight, center, topRight);
Vector2f.Vector2fAdd(bottomLeft, center, bottomLeft);
Vector2f.Vector2fAdd(bottomRight, center, bottomRight);
}
public void rotateAround(Vector2f pos, float newOrientation) {
// first translate to center coordinate space
Vector2f.Vector2fSubtract(center, pos, center);
Vector2f.Vector2fSubtract(topLeft, pos, topLeft);
Vector2f.Vector2fSubtract(topRight, pos, topRight);
Vector2f.Vector2fSubtract(bottomLeft, pos, bottomLeft);
Vector2f.Vector2fSubtract(bottomRight, pos, bottomRight);
// rotate the rectangle
this.orientation = newOrientation;
Vector2f.Vector2fRotate(center, orientation, center);
Vector2f.Vector2fRotate(topLeft, orientation, topLeft);
Vector2f.Vector2fRotate(topRight, orientation, topRight);
Vector2f.Vector2fRotate(bottomLeft, orientation, bottomLeft);
Vector2f.Vector2fRotate(bottomRight, orientation, bottomRight);
// translate the rotated rectangle back to the supplied
// center position
Vector2f.Vector2fAdd(center, pos, center);
Vector2f.Vector2fAdd(topLeft, pos, topLeft);
Vector2f.Vector2fAdd(topRight, pos, topRight);
Vector2f.Vector2fAdd(bottomLeft, pos, bottomLeft);
Vector2f.Vector2fAdd(bottomRight, pos, bottomRight);
}
/**
* set the rotation to the supplied orientation
*
* @param newOrientation
*/
public void rotateTo(float newOrientation) {
// update(orientation, center.x, center.y);
update(newOrientation, center.x, center.y); // I changed this, because the param was invalid.
}
/**
* Rotate relative to the current orientation
*
* @param adjustBy
*/
public void rotate(float adjustBy) {
rotateTo(orientation + adjustBy);
}
/**
* Move relative to the current center position
*
* @param p
*/
public void translate(Vector2f p) {
translate(p.x, p.y);
}
/**
* Move relative to the current center position
*
* @param px
* @param py
*/
public void translate(float px, float py) {
setLocation(center.x + px, center.y + py);
}
/**
* Move the center position to the supplied position
*
* @param px
* @param py
*/
public void setLocation(float px, float py) {
update(orientation, px, py);
}
/**
* Move the center position to the supplied position
*
* @param pos
*/
public void setLocation(Vector2f pos) {
setLocation(pos.x, pos.y);
}
/**
* Re-adjust the width/height properties
*
* @param width
* @param height
*/
public void setBounds(float width, float height) {
this.width = width;
this.height = height;
setLocation(center);
}
/**
* @return the center
*/
public Vector2f getCenter() {
return center;
}
/**
* @return the orientation
*/
public float getOrientation() {
return orientation;
}
/**
* @return the width
*/
public float getWidth() {
return width;
}
/**
* @return the height
*/
public float getHeight() {
return height;
}
/**
* Longest length from corner to corner
* @return Longest length from corner to corner
*/
public float length() {
float distance = Vector2f.Vector2fDistance(this.topLeft, this.bottomRight);
return distance;
}
/**
* Determines if the supplied point is inside the {@link OBB}
*
* @param p
* @return true if the point is inside the OOB
*/
public boolean contains(Vector2f p) {
return contains(p.x, p.y);
}
private float sign(float px, float py, Vector2f a, Vector2f b) {
return (px - b.x) * (a.y - b.y) - (a.x - b.x) * (py - b.y);
}
private boolean pointInTriangle(float px, float py, Vector2f a, Vector2f b, Vector2f c) {
boolean b1 = sign(px, py, a, b) < 0f;
boolean b2 = sign(px, py, b, c) < 0f;
boolean b3 = sign(px, py, c, a) < 0f;
return ((b1 == b2) && (b2 == b3));
}
/**
* Determines if the supplied point is inside the {@link OBB}
*
* @param px
* @param py
* @return true if the point is inside the {@link OBB}
*/
public boolean contains(float px, float py) {
// just do simple contains if there is no rotation
// if(orientation == 0) {
// return Math.abs(center.x-px) < width/2 && Math.abs(center.y-py) < height/2;
// }
//
// double tx = Math.cos(orientation)*px - Math.sin(orientation)*py;
// double ty = Math.cos(orientation)*py + Math.sin(orientation)*px;
//
// double cx = Math.cos(orientation)*center.x - Math.sin(orientation)*center.y;
// double cy = Math.cos(orientation)*center.y + Math.sin(orientation)*center.x;
//
// return Math.abs(cx-tx) < width/2 && Math.abs(cy-ty) < height/2;
// double newy = Math.sin(orientation) * (py-center.y) + Math.cos(orientation) * (px - center.x);
// double newx = Math.cos(orientation) * (px-center.x) - Math.sin(orientation) * (py - center.y);
// return (newy > center.y - height/2f) && (newy < center.y + height/2f) &&
// (newx > center.x - width/2f) && (newx < center.x + width/2f);
// float yy = py - center.y;
// float xx = px - center.x;
//
// float hh = height/2f;
// float hw = width/2f;
//
// double newx = (xx*Math.cos(orientation)) - (yy*Math.sin(orientation));
// double newy = (xx*Math.sin(orientation)) + (yy*Math.cos(orientation));
// return (newy > center.y - hh) && (newy < center.y + hh) &&
// (newx > center.x - hw) && (newx < center.x + hw);
return pointInTriangle(px, py, topLeft, topRight, bottomLeft) ||
pointInTriangle(px, py, topLeft, topRight, bottomRight);
}
/**
* Determines if the {@link Rectangle} interests with this {@link OBB}
* @param b
* @return true if the {@link Rectangle} intersects with this {@link OBB}
*/
public boolean intersects(Rectangle b) {
return // check to see if the OOB corners are within the rectangle
b.contains(topLeft) ||
b.contains(topRight) ||
b.contains(bottomLeft) ||
b.contains(bottomRight) ||
// now check the lines
checkLineAgainstOOB(topLeft, topRight, b) ||
checkLineAgainstOOB(topRight, bottomRight, b) ||
checkLineAgainstOOB(bottomRight, bottomLeft, b) ||
checkLineAgainstOOB(bottomLeft, topLeft, b);// ||
// now check if the Rectangle is in this OOB
//contains(b.x , b.y) ||
//contains(b.x+b.width, b.y) ||
//contains(b.x+b.width, b.y+b.height) ||
//contains(b.x , b.y+b.height);
}
public boolean expensiveIntersects(Rectangle b) {
return // check to see if the OBB corners are within the rectangle
b.contains(topLeft) ||
b.contains(topRight) ||
b.contains(bottomLeft) ||
b.contains(bottomRight) ||
// now check the lines
checkLineAgainstOOB(topLeft, topRight, b) ||
checkLineAgainstOOB(topRight, bottomRight, b) ||
checkLineAgainstOOB(bottomRight, bottomLeft, b) ||
checkLineAgainstOOB(bottomLeft, topLeft, b) ||
// now check if the Rectangle is in this OOB
contains(b.x , b.y) ||
contains(b.x+b.width, b.y) ||
contains(b.x+b.width, b.y+b.height) ||
contains(b.x , b.y+b.height);
}
/**
* Determines if the supplied {@link OBB} intersects this {@link OBB}
*
* @param other
* @return true if the two {@link OBB}'s overlap
*/
public boolean intersects(OBB other) {
return // check the for line intersections
checkLineAgainstOOB(topLeft, topRight, other) ||
checkLineAgainstOOB(topRight, bottomRight, other) ||
checkLineAgainstOOB(bottomRight, bottomLeft, other) ||
checkLineAgainstOOB(bottomLeft, topLeft, other) ||
// now check to see if they are inside eachother
hasCornersInside(other) ||
other.hasCornersInside(this);
}
/**
* Probably a more efficient way of doing this, but in general the algorithm
* determines if any of the four corners of either {@link OBB} is contained in the
* other {@link OBB} (and checks the reverse)
*
* @param other
* @return true if any of the supplied {@link OBB} corners are contained in this {@link OBB}
*/
private boolean hasCornersInside(OBB other) {
return contains(other.topLeft) ||
contains(other.topRight) ||
contains(other.bottomLeft) ||
contains(other.bottomRight);
}
/**
* Not very efficient means of testing, but tests the supplied line with all of the other lines
* that make up the other {@link OBB}
*
* @param a
* @param b
* @param other
* @return true if the supplied line intersects with one of the lines that make up the {@link OBB}
*/
private boolean checkLineAgainstOOB(Vector2f a, Vector2f b, OBB other) {
return Line.lineIntersectLine(a, b, other.topLeft, other.topRight) ||
Line.lineIntersectLine(a, b, other.topRight, other.bottomRight) ||
Line.lineIntersectLine(a, b, other.bottomRight, other.bottomLeft) ||
Line.lineIntersectLine(a, b, other.bottomLeft, other.topLeft);
}
private boolean checkLineAgainstOOB(Vector2f a, Vector2f b, Rectangle other) {
return Line.lineIntersectLine(a.x, a.y, b.x, b.y, other.x , other.y , other.x + other.width, other.y) ||
Line.lineIntersectLine(a.x, a.y, b.x, b.y, other.x+other.width, other.y , other.x + other.width, other.y + other.height) ||
Line.lineIntersectLine(a.x, a.y, b.x, b.y, other.x+other.width, other.y + other.height, other.x , other.y + other.height) ||
Line.lineIntersectLine(a.x, a.y, b.x, b.y, other.x , other.y + other.height, other.x , other.y);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{ \n width: ").append(width)
.append(", \n height: ").append(height)
.append(", \n orientation: ").append(orientation)
.append(", \n center: ").append(center)
.append(", \n topLeft: ").append(topLeft)
.append(", \n topRight: ").append(topRight)
.append(", \n bottomLeft: ").append(bottomLeft)
.append(", \n bottomRight: ").append(bottomRight)
.append(" \n}");
return builder.toString();
}
public static void main(String[] args) {
OBB a = new OBB( (float)Math.PI / 4f, new Vector2f(0, 0), 50, 50);
System.out.println(a.contains(1, 1));
System.out.println(a.contains(-1, -1));
System.out.println(a.contains(0, 25));
System.out.println(a.contains(0, -25));
System.out.println(a.contains(25, 0));
System.out.println(a.contains(-25, 0));
float d = 36;
System.out.println(a.contains(0, d));
System.out.println(a.contains(0, -d));
System.out.println(a.contains(d, 0));
System.out.println(a.contains(-d, 0));
Vector2f v = new Vector2f(25, 0);
Vector2f.Vector2fRotate(v, 3 * Math.PI / 4, v);
System.out.println("Point is in a: " + a.contains(v));
// a.setLocation(76, 76);
printOOB(a);
OBB b = new OBB( a.orientation, new Vector2f(35.355f, 35.355f), 50, 50 );
b.translate(1, 1);
b.translate(-1, -1);
printOOB(b);
System.out.println("A intersects B: " + a.intersects(b));
OBB tank = new OBB(0, new Vector2f(767.5f, 782.5f), 225, 145);
Rectangle me = new Rectangle(24, 24);
me.setLocation(763, 829);
System.out.println("Tank intersects: " + tank.expensiveIntersects(me));
// {
// width: 225.0,
// height: 145.0,
// orientation: 0.0,
// center: { "x": 767.5, "y": 782.5},
// topLeft: { "x": 655.0, "y": 855.0},
// topRight: { "x": 880.0, "y": 855.0},
// bottomLeft: { "x": 655.0, "y": 710.0},
// bottomRight: { "x": 880.0, "y": 710.0}
// }
// { "x": 763.0, "y": 829.0}:{ "x" : 763, "y" : 829, "width" : 24, "height" : 24 }
}
private static void printOOB(OBB a) {
System.out.printf("C : (%3.1f, %3.1f) D: %3.1f \n", a.center.x, a.center.y, Vector2f.Vector2fDistance(Vector2f.ZERO_VECTOR, a.center));
System.out.printf("TL: (%3.1f, %3.1f) D: %3.1f \n", a.topLeft.x, a.topLeft.y, Vector2f.Vector2fDistance(Vector2f.ZERO_VECTOR, a.topLeft));
System.out.printf("TR: (%3.1f, %3.1f) D: %3.1f \n", a.topRight.x, a.topRight.y, Vector2f.Vector2fDistance(Vector2f.ZERO_VECTOR, a.topRight));
System.out.printf("BL: (%3.1f, %3.1f) D: %3.1f \n", a.bottomLeft.x, a.bottomLeft.y, Vector2f.Vector2fDistance(Vector2f.ZERO_VECTOR, a.bottomLeft));
System.out.printf("BR: (%3.1f, %3.1f) D: %3.1f \n", a.bottomRight.x, a.bottomRight.y, Vector2f.Vector2fDistance(Vector2f.ZERO_VECTOR, a.bottomRight));
}
}
| 17,795 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Rectangle.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/math/Rectangle.java | /*
* leola-live
* see license.txt
*/
package seventh.math;
/**
* A {@link Rectangle} which is very similar to Java's and LWJGL's implementation, however with Android
* development a developer may not want to include LWJGL on their classpath.
*
* <p>
* Most of the code is taken from the LWJGL Rectangle implementation.
*
* @author Tony
*
*/
public class Rectangle {
/**
* X Component
*/
public int x;
/**
* Y Component
*/
public int y;
/**
* Width
*/
public int width;
/**
* Height
*/
public int height;
/**
* @param b
* @param width
* @param height
*/
public Rectangle(Vector2f b, int width, int height) {
this.x = (int)b.x;
this.y = (int)b.y;
this.width = width;
this.height = height;
}
/**
* @param x
* @param y
* @param width
* @param height
*/
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/**
* @param width
* @param height
*/
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
/**
* @param rect
*/
public Rectangle(Rectangle rect) {
this(rect.x, rect.y, rect.width, rect.height);
}
/**
*/
public Rectangle() {
this(0, 0, 0, 0);
}
/**
* @return the x
*/
public int getX() {
return this.x;
}
/**
* @param x the x to set
*/
public void setX(int x) {
this.x = x;
}
/**
* @return the y
*/
public int getY() {
return this.y;
}
/**
* @param y the y to set
*/
public void setY(int y) {
this.y = y;
}
/**
* @return the width
*/
public int getWidth() {
return this.width;
}
/**
* @param width the width to set
*/
public void setWidth(int width) {
this.width = width;
}
/**
* @return the height
*/
public int getHeight() {
return this.height;
}
/**
* @param height the height to set
*/
public void setHeight(int height) {
this.height = height;
}
/**
* Sets the components. Equivalent to setBounds
*
* @param x
* @param y
* @param width
* @param height
*/
public void set(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/**
* Sets the components. Equivalent to set
*
* @param x
* @param y
* @param width
* @param height
*/
public void setBounds(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/**
* Sets the components. Equivalent to setBounds
*
* @param b
* @param width
* @param height
*/
public void set(Vector2f b, int width, int height) {
this.x = (int)b.x;
this.y = (int)b.y;
this.width = width;
this.height = height;
}
/**
* Sets the components. Equivalent to set
*
* @param b
* @param width
* @param height
*/
public void setBounds(Vector2f b, int width, int height) {
this.x = (int)b.x;
this.y = (int)b.y;
this.width = width;
this.height = height;
}
/**
* Sets the components, same as set
*
* @param b
*/
public void setBounds(Rectangle b) {
this.x = b.x;
this.y = b.y;
this.width = b.width;
this.height = b.height;
}
/**
* Sets the components
*
* @param b
*/
public void set(Rectangle b) {
this.x = b.x;
this.y = b.y;
this.width = b.width;
this.height = b.height;
}
/**
* Zero outs all components.
*/
public void zeroOut() {
this.x = this.y = this.width = this.height = 0;
}
/**
* Sets the x and y components
* @param x
* @param y
*/
public void setLocation(int x, int y) {
this.x = x;
this.y = y;
}
/**
* Sets the x and y components
* @param v
*/
public void setLocation(Vector2f v) {
this.x = (int)v.x;
this.y = (int)v.y;
}
/**
* Sets the x and y to match the supplied rectangle.
* @param r
*/
public void setLocation(Rectangle r) {
this.x = r.x;
this.y = r.y;
}
/**
* Sets the width and height
* @param w
* @param h
*/
public void setSize(int w, int h) {
this.width = w;
this.height = h;
}
/**
* Sets the width and height to match the supplied rectangle.
* @param r
*/
public void setSize(Rectangle r) {
this.width = r.width;
this.height = r.height;
}
/**
* Centers around the position
* @param pos
*/
public void centerAround(Vector2f pos) {
this.x = (int)pos.x - (this.width / 2);
this.y = (int)pos.y - (this.height / 2);
}
/**
* Centers around the position
* @param x
* @param y
*/
public void centerAround(int x, int y) {
this.x = x - (this.width / 2);
this.y = y - (this.height / 2);
}
/**
* @see Rectangle#RectangleIntersection(Rectangle, Rectangle, Rectangle)
*
* @param b
* @return the intersection rectangle
*/
public Rectangle intersection(Rectangle b) {
Rectangle dest = new Rectangle();
RectangleIntersection(this, b, dest);
return dest;
}
/**
* Tests for intersection
*
* @param b
* @return true if this rectangle intersects b
*/
public boolean intersects(Rectangle b) {
return RectangleIntersects(this, b);
}
/**
* Tests to see if this contains b
* @param b
* @return true if this contains b
*/
public boolean contains(Rectangle b) {
return RectangleContains(this, b);
}
/**
* Tests to see if this contains b
* @param b
* @return true if this contains b
*/
public boolean contains(Vector2f b) {
return RectangleContains(this, b);
}
/**
* Tests to see if this contains b
* @param x
* @param y
* @return true if this contains the x & y
*/
public boolean contains(int x, int y) {
return RectangleContains(this, x, y);
}
/**
* If this {@link Rectangle} contains the {@link OBB}
* @param oob
* @return true if it contains it
*/
public boolean contains(OBB oob) {
return RectangleContains(this, oob.topLeft) &&
RectangleContains(this, oob.topRight) &&
RectangleContains(this, oob.bottomRight) &&
RectangleContains(this, oob.bottomLeft);
}
public void addSize(int w, int h) {
this.width += w;
this.height += h;
}
/**
* Adds b to this.
* @param b
*/
public void add(Vector2f b) {
RectangleAdd(this, b, this);
}
/**
* Adds x and y to this
* @param x
* @param y
*/
public void add(int x, int y) {
RectangleAdd(this, x, y, this);
}
/**
* Adds the x and y components to this rectangle
*
* <pre>
* RectangleAdd(this, b, this);
* </pre>
*
* @see Rectangle#RectangleAdd(Rectangle, Rectangle, Rectangle)
*
* @param b
*/
public void add(Rectangle b) {
RectangleAdd(this, b, this);
}
/*
* The below is from the LWJGL implementation.
*/
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Checks whether two rectangles are equal.
* <p>
* The result is <code>true</code> if and only if the argument is not
* <code>null</code> and is a <code>Rectangle</code> object that has the
* same top-left corner, width, and height as this <code>Rectangle</code>.
* @param obj the <code>Object</code> to compare with
* this <code>Rectangle</code>
* @return <code>true</code> if the objects are equal;
* <code>false</code> otherwise.
*/
public boolean equals(Object obj) {
if (obj instanceof Rectangle) {
Rectangle r = (Rectangle) obj;
return ((x == r.x) && (y == r.y) && (width == r.width) && (height == r.height));
}
return super.equals(obj);
}
/**
* Debugging
* @return a String
*/
public String toString() {
return "{ \"x\" : " + x + ", \"y\" : " + y + ", \"width\" : " + width + ", \"height\" : " + height + " }";
}
/**
* Computes the intersection of this <code>Rectangle</code> with the
* specified <code>Rectangle</code>. Returns a new <code>Rectangle</code>
* that represents the intersection of the two rectangles.
* If the two rectangles do not intersect, the result will be
* an empty rectangle.
*
* @param r the specified <code>Rectangle</code>
* @param dest the largest <code>Rectangle</code> contained in both the
* specified <code>Rectangle</code> and in
* this <code>Rectangle</code>; or if the rectangles
* do not intersect, an empty rectangle.
*/
public static void RectangleIntersection(Rectangle a, Rectangle b, Rectangle dest) {
int tx1 = a.x;
int ty1 = a.y;
int rx1 = b.x;
int ry1 = b.y;
long tx2 = tx1;
tx2 += a.width;
long ty2 = ty1;
ty2 += a.height;
long rx2 = rx1;
rx2 += b.width;
long ry2 = ry1;
ry2 += b.height;
if (tx1 < rx1)
tx1 = rx1;
if (ty1 < ry1)
ty1 = ry1;
if (tx2 > rx2)
tx2 = rx2;
if (ty2 > ry2)
ty2 = ry2;
tx2 -= tx1;
ty2 -= ty1;
// tx2,ty2 will never overflow (they will never be
// larger than the smallest of the two source w,h)
// they might underflow, though...
if (tx2 < Integer.MIN_VALUE)
tx2 = Integer.MIN_VALUE;
if (ty2 < Integer.MIN_VALUE)
ty2 = Integer.MIN_VALUE;
dest.set(tx1, ty1, (int)tx2, (int)ty2);
}
/**
* Determines if two {@link Rectangle} intersect.
* @param a
* @param b
* @return true if a intersects b
*/
public static boolean RectangleIntersects(Rectangle a, Rectangle b) {
int tw = a.width;
int th = a.height;
int rw = b.width;
int rh = b.height;
if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
return false;
}
int tx = a.x;
int ty = a.y;
int rx = b.x;
int ry = b.y;
rw += rx;
rh += ry;
tw += tx;
th += ty;
// overflow || intersect
return ((rw < rx || rw > tx) && (rh < ry || rh > ty) && (tw < tx || tw > rx) && (th < ty || th > ry));
}
/**
* Determines if a contains b
*
* @param a
* @param b
* @return true if a contains b
*/
public static boolean RectangleContains(Rectangle a, Rectangle b) {
int X = b.x;
int Y = b.y;
int W = b.width;
int H = b.height;
int w = a.width;
int h = a.height;
if ((w | h | W | H) < 0) {
// At least one of the dimensions is negative...
return false;
}
// Note: if any dimension is zero, tests below must return false...
int x = a.x;
int y = a.y;
if (b.x < x || b.y < y) {
return false;
}
w += x;
W += X;
if (W <= X) {
// X+W overflowed or W was zero, return false if...
// either original w or W was zero or
// x+w did not overflow or
// the overflowed x+w is smaller than the overflowed X+W
if (w >= x || W > w)
return false;
} else {
// X+W did not overflow and W was not zero, return false if...
// original w was zero or
// x+w did not overflow and x+w is smaller than X+W
if (w >= x && W > w)
return false;
}
h += y;
H += Y;
if (H <= Y) {
if (h >= y || H > h)
return false;
} else {
if (h >= y && H > h)
return false;
}
return true;
}
/**
* If the supplied rectangle contains a point
* @param a
* @param b
* @return
*/
public static boolean RectangleContains(Rectangle a, int bx, int by) {
int w = a.width;
int h = a.height;
if ((w | h) < 0) {
// At least one of the dimensions is negative...
return false;
}
// Note: if either dimension is zero, tests below must return false...
int x = a.x;
int y = a.y;
if (bx < x || by < y) {
return false;
}
w += x;
h += y;
// overflow || intersect
return ((w < x || w > bx) && (h < y || h > by));
}
/**
* If the supplied rectangle contains a point
* @param a
* @param b
* @return
*/
public static boolean RectangleContains(Rectangle a, Vector2f b) {
int w = a.width;
int h = a.height;
if ((w | h) < 0) {
// At least one of the dimensions is negative...
return false;
}
// Note: if either dimension is zero, tests below must return false...
int x = a.x;
int y = a.y;
if (b.x < x || b.y < y) {
return false;
}
w += x;
h += y;
// overflow || intersect
return ((w < x || w > b.x) && (h < y || h > b.y));
}
/**
* Adds to the Rectangle
*
* @param a
* @param b
* @param dest - result
*/
public static void RectangleAdd(Rectangle a, Vector2f b, Rectangle dest) {
dest.x = a.x + (int)b.x;
dest.y = a.y + (int)b.y;
}
/**
* Adds to the rectangle
* @param a
* @param x
* @param y
* @param dest - result
*/
public static void RectangleAdd(Rectangle a, int x, int y, Rectangle dest) {
dest.x = a.x + x;
dest.y = a.y + y;
}
/**
* Adds the x & y component of Rectangle b to Rectangle a and stores it in dest.
* @param a
* @param b
* @param dest - the result
*/
public static void RectangleAdd(Rectangle a, Rectangle b, Rectangle dest) {
dest.x = a.x + b.x;
dest.y = a.y + b.y;
}
}
| 16,869 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Tri.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/math/Tri.java | /*
* leola-live
* see license.txt
*/
package seventh.math;
/**
* @author Tony
*
*/
public class Tri<X, Y, Z> extends Pair<X, Y> {
/**
* Thrid Var
*/
private Z third;
/**
* @param first
* @param second
*/
public Tri(X first, Y second, Z third) {
super(first, second);
this.third = third;
}
/**
* @param third the third to set
*/
public void setThird(Z third) {
this.third = third;
}
/**
* @return the third
*/
public Z getThird() {
return third;
}
}
| 591 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.