repo_name
stringclasses 5
values | pr_number
int64 1.52k
15.5k
| pr_title
stringlengths 8
143
| pr_description
stringlengths 0
10.2k
| author
stringlengths 3
18
| date_created
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 11
10.2k
| filepath
stringlengths 6
220
| before_content
stringlengths 0
597M
| after_content
stringlengths 0
597M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglAWTInput.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.lwjgl;
import java.awt.AWTException;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.OverlayLayout;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import com.badlogic.gdx.AbstractInput;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.utils.IntSet;
import com.badlogic.gdx.utils.Pool;
public class LwjglAWTInput extends AbstractInput implements MouseMotionListener, MouseListener, MouseWheelListener, KeyListener {
class KeyEvent {
static final int KEY_DOWN = 0;
static final int KEY_UP = 1;
static final int KEY_TYPED = 2;
long timeStamp;
int type;
int keyCode;
char keyChar;
}
class TouchEvent {
static final int TOUCH_DOWN = 0;
static final int TOUCH_UP = 1;
static final int TOUCH_DRAGGED = 2;
static final int TOUCH_MOVED = 3;
static final int TOUCH_SCROLLED = 4;
long timeStamp;
int type;
int x;
int y;
int pointer;
int button;
int scrollAmount;
}
Pool<KeyEvent> usedKeyEvents = new Pool<KeyEvent>(16, 1000) {
protected KeyEvent newObject () {
return new KeyEvent();
}
};
Pool<TouchEvent> usedTouchEvents = new Pool<TouchEvent>(16, 1000) {
protected TouchEvent newObject () {
return new TouchEvent();
}
};
private final LwjglAWTCanvas lwjglAwtCanvas;
List<KeyEvent> keyEvents = new ArrayList<KeyEvent>();
List<TouchEvent> touchEvents = new ArrayList<TouchEvent>();
int touchX = 0;
int touchY = 0;
int deltaX = 0;
int deltaY = 0;
boolean touchDown = false;
boolean justTouched = false;
boolean[] justPressedButtons = new boolean[5];
IntSet pressedButtons = new IntSet();
InputProcessor processor;
Canvas canvas;
boolean catched = false;
Robot robot = null;
long currentEventTimeStamp;
public LwjglAWTInput (LwjglAWTCanvas lwjglAwtCanvas) {
this.lwjglAwtCanvas = lwjglAwtCanvas;
setListeners(lwjglAwtCanvas.getCanvas());
try {
robot = new Robot(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice());
} catch (HeadlessException e) {
} catch (AWTException e) {
}
}
public void setListeners (Canvas canvas) {
if (this.canvas != null) {
canvas.removeMouseListener(this);
canvas.removeMouseMotionListener(this);
canvas.removeMouseWheelListener(this);
canvas.removeKeyListener(this);
}
canvas.addMouseListener(this);
canvas.addMouseMotionListener(this);
canvas.addMouseWheelListener(this);
canvas.addKeyListener(this);
canvas.setFocusTraversalKeysEnabled(false);
this.canvas = canvas;
}
@Override
public float getAccelerometerX () {
return 0;
}
@Override
public float getAccelerometerY () {
return 0;
}
@Override
public float getAccelerometerZ () {
return 0;
}
@Override
public void getTextInput (TextInputListener listener, String title, String text, String hint) {
getTextInput(listener, title, text, hint, OnscreenKeyboardType.Default);
}
@Override
public void getTextInput (final TextInputListener listener, final String title, final String text, final String hint,
OnscreenKeyboardType type) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run () {
JPanel panel = new JPanel(new FlowLayout());
JPanel textPanel = new JPanel() {
public boolean isOptimizedDrawingEnabled () {
return false;
};
};
textPanel.setLayout(new OverlayLayout(textPanel));
panel.add(textPanel);
final JTextField textField = new JTextField(20);
textField.setText(text);
textField.setAlignmentX(0.0f);
textPanel.add(textField);
final JLabel placeholderLabel = new JLabel(hint);
placeholderLabel.setForeground(Color.GRAY);
placeholderLabel.setAlignmentX(0.0f);
textPanel.add(placeholderLabel, 0);
textField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate (DocumentEvent arg0) {
this.updated();
}
@Override
public void insertUpdate (DocumentEvent arg0) {
this.updated();
}
@Override
public void changedUpdate (DocumentEvent arg0) {
this.updated();
}
private void updated () {
if (textField.getText().length() == 0)
placeholderLabel.setVisible(true);
else
placeholderLabel.setVisible(false);
}
});
JOptionPane pane = new JOptionPane(panel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, null,
null);
pane.setInitialValue(null);
pane.setComponentOrientation(JOptionPane.getRootFrame().getComponentOrientation());
Border border = textField.getBorder();
placeholderLabel.setBorder(new EmptyBorder(border.getBorderInsets(textField)));
JDialog dialog = pane.createDialog(null, title);
pane.selectInitialValue();
dialog.addWindowFocusListener(new WindowFocusListener() {
@Override
public void windowLostFocus (WindowEvent arg0) {
}
@Override
public void windowGainedFocus (WindowEvent arg0) {
textField.requestFocusInWindow();
}
});
dialog.setVisible(true);
dialog.dispose();
Object selectedValue = pane.getValue();
if (selectedValue != null && (selectedValue instanceof Integer)
&& ((Integer)selectedValue).intValue() == JOptionPane.OK_OPTION) {
listener.input(textField.getText());
} else {
listener.canceled();
}
}
});
}
@Override
public int getMaxPointers () {
return 1;
}
@Override
public int getX () {
return touchX;
}
@Override
public int getX (int pointer) {
if (pointer == 0)
return touchX;
else
return 0;
}
@Override
public int getY () {
return touchY;
}
@Override
public int getY (int pointer) {
if (pointer == 0)
return touchY;
else
return 0;
}
@Override
public synchronized boolean isKeyPressed (int key) {
if (key == Input.Keys.ANY_KEY) {
return pressedKeyCount > 0;
}
if (key < 0 || key > 255) {
return false;
}
return pressedKeys[key];
}
@Override
public synchronized boolean isKeyJustPressed (int key) {
if (key == Input.Keys.ANY_KEY) {
return keyJustPressed;
}
if (key < 0 || key > 255) {
return false;
}
return justPressedKeys[key];
}
@Override
public boolean isTouched () {
return touchDown;
}
@Override
public boolean isTouched (int pointer) {
if (pointer == 0)
return touchDown;
else
return false;
}
@Override
public float getPressure () {
return getPressure(0);
}
@Override
public float getPressure (int pointer) {
return isTouched(pointer) ? 1 : 0;
}
void processEvents () {
synchronized (this) {
if (justTouched) {
justTouched = false;
for (int i = 0; i < justPressedButtons.length; i++) {
justPressedButtons[i] = false;
}
}
if (keyJustPressed) {
keyJustPressed = false;
for (int i = 0; i < justPressedKeys.length; i++) {
justPressedKeys[i] = false;
}
}
if (processor != null) {
InputProcessor processor = this.processor;
int len = keyEvents.size();
for (int i = 0; i < len; i++) {
KeyEvent e = keyEvents.get(i);
currentEventTimeStamp = e.timeStamp;
switch (e.type) {
case KeyEvent.KEY_DOWN:
processor.keyDown(e.keyCode);
keyJustPressed = true;
justPressedKeys[e.keyCode] = true;
break;
case KeyEvent.KEY_UP:
processor.keyUp(e.keyCode);
break;
case KeyEvent.KEY_TYPED:
processor.keyTyped(e.keyChar);
}
usedKeyEvents.free(e);
}
len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent e = touchEvents.get(i);
currentEventTimeStamp = e.timeStamp;
switch (e.type) {
case TouchEvent.TOUCH_DOWN:
processor.touchDown(e.x, e.y, e.pointer, e.button);
justTouched = true;
justPressedButtons[e.button] = true;
break;
case TouchEvent.TOUCH_UP:
processor.touchUp(e.x, e.y, e.pointer, e.button);
break;
case TouchEvent.TOUCH_DRAGGED:
processor.touchDragged(e.x, e.y, e.pointer);
break;
case TouchEvent.TOUCH_MOVED:
processor.mouseMoved(e.x, e.y);
break;
case TouchEvent.TOUCH_SCROLLED:
processor.scrolled(0, e.scrollAmount);
break;
}
usedTouchEvents.free(e);
}
} else {
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if (event.type == TouchEvent.TOUCH_DOWN) justTouched = true;
usedTouchEvents.free(event);
}
len = keyEvents.size();
for (int i = 0; i < len; i++) {
usedKeyEvents.free(keyEvents.get(i));
}
}
if (touchEvents.isEmpty()) {
deltaX = 0;
deltaY = 0;
}
keyEvents.clear();
touchEvents.clear();
}
}
@Override
public void setOnscreenKeyboardVisible (boolean visible) {
}
@Override
public void setOnscreenKeyboardVisible (boolean visible, OnscreenKeyboardType type) {
}
@Override
public void mouseDragged (MouseEvent e) {
synchronized (this) {
TouchEvent event = usedTouchEvents.obtain();
event.pointer = 0;
event.x = e.getX();
event.y = e.getY();
event.type = TouchEvent.TOUCH_DRAGGED;
event.timeStamp = System.nanoTime();
touchEvents.add(event);
deltaX = event.x - touchX;
deltaY = event.y - touchY;
touchX = event.x;
touchY = event.y;
checkCatched(e);
lwjglAwtCanvas.graphics.requestRendering();
}
}
@Override
public void mouseMoved (MouseEvent e) {
synchronized (this) {
TouchEvent event = usedTouchEvents.obtain();
event.pointer = 0;
event.x = e.getX();
event.y = e.getY();
event.type = TouchEvent.TOUCH_MOVED;
event.timeStamp = System.nanoTime();
touchEvents.add(event);
deltaX = event.x - touchX;
deltaY = event.y - touchY;
touchX = event.x;
touchY = event.y;
checkCatched(e);
lwjglAwtCanvas.graphics.requestRendering();
}
}
@Override
public void mouseClicked (MouseEvent arg0) {
}
@Override
public void mouseEntered (MouseEvent e) {
touchX = e.getX();
touchY = e.getY();
checkCatched(e);
lwjglAwtCanvas.graphics.requestRendering();
}
@Override
public void mouseExited (MouseEvent e) {
checkCatched(e);
lwjglAwtCanvas.graphics.requestRendering();
}
private void checkCatched (MouseEvent e) {
if (catched && robot != null && canvas.isShowing()) {
int x = Math.max(0, Math.min(e.getX(), canvas.getWidth()) - 1) + canvas.getLocationOnScreen().x;
int y = Math.max(0, Math.min(e.getY(), canvas.getHeight()) - 1) + canvas.getLocationOnScreen().y;
if (e.getX() < 0 || e.getX() >= canvas.getWidth() || e.getY() < 0 || e.getY() >= canvas.getHeight()) {
robot.mouseMove(x, y);
}
}
}
private int toGdxButton (int swingButton) {
if (swingButton == MouseEvent.BUTTON1) return Buttons.LEFT;
if (swingButton == MouseEvent.BUTTON2) return Buttons.MIDDLE;
if (swingButton == MouseEvent.BUTTON3) return Buttons.RIGHT;
return Buttons.LEFT;
}
@Override
public void mousePressed (MouseEvent e) {
synchronized (this) {
TouchEvent event = usedTouchEvents.obtain();
event.pointer = 0;
event.x = e.getX();
event.y = e.getY();
event.type = TouchEvent.TOUCH_DOWN;
event.button = toGdxButton(e.getButton());
event.timeStamp = System.nanoTime();
touchEvents.add(event);
deltaX = event.x - touchX;
deltaY = event.y - touchY;
touchX = event.x;
touchY = event.y;
touchDown = true;
pressedButtons.add(event.button);
lwjglAwtCanvas.graphics.requestRendering();
}
}
@Override
public void mouseReleased (MouseEvent e) {
synchronized (this) {
TouchEvent event = usedTouchEvents.obtain();
event.pointer = 0;
event.x = e.getX();
event.y = e.getY();
event.button = toGdxButton(e.getButton());
event.type = TouchEvent.TOUCH_UP;
event.timeStamp = System.nanoTime();
touchEvents.add(event);
deltaX = event.x - touchX;
deltaY = event.y - touchY;
touchX = event.x;
touchY = event.y;
pressedButtons.remove(event.button);
if (pressedButtons.size == 0) touchDown = false;
lwjglAwtCanvas.graphics.requestRendering();
}
}
@Override
public void mouseWheelMoved (MouseWheelEvent e) {
synchronized (this) {
TouchEvent event = usedTouchEvents.obtain();
event.pointer = 0;
event.type = TouchEvent.TOUCH_SCROLLED;
event.scrollAmount = e.getWheelRotation();
event.timeStamp = System.nanoTime();
touchEvents.add(event);
lwjglAwtCanvas.graphics.requestRendering();
}
}
@Override
public void keyPressed (java.awt.event.KeyEvent e) {
synchronized (this) {
KeyEvent event = usedKeyEvents.obtain();
event.keyChar = 0;
event.keyCode = translateKeyCode(e.getKeyCode());
event.type = KeyEvent.KEY_DOWN;
event.timeStamp = System.nanoTime();
keyEvents.add(event);
if (!pressedKeys[event.keyCode]) {
pressedKeyCount++;
pressedKeys[event.keyCode] = true;
}
lwjglAwtCanvas.graphics.requestRendering();
}
}
@Override
public void keyReleased (java.awt.event.KeyEvent e) {
synchronized (this) {
KeyEvent event = usedKeyEvents.obtain();
event.keyChar = 0;
event.keyCode = translateKeyCode(e.getKeyCode());
event.type = KeyEvent.KEY_UP;
event.timeStamp = System.nanoTime();
keyEvents.add(event);
if (pressedKeys[event.keyCode]) {
pressedKeyCount--;
pressedKeys[event.keyCode] = false;
}
lwjglAwtCanvas.graphics.requestRendering();
}
}
@Override
public void keyTyped (java.awt.event.KeyEvent e) {
synchronized (this) {
KeyEvent event = usedKeyEvents.obtain();
event.keyChar = e.getKeyChar();
event.keyCode = 0;
event.type = KeyEvent.KEY_TYPED;
event.timeStamp = System.nanoTime();
keyEvents.add(event);
lwjglAwtCanvas.graphics.requestRendering();
}
}
protected int translateKeyCode (int keyCode) {
switch (keyCode) {
case java.awt.event.KeyEvent.VK_0:
return Input.Keys.NUM_0;
case java.awt.event.KeyEvent.VK_1:
return Input.Keys.NUM_1;
case java.awt.event.KeyEvent.VK_2:
return Input.Keys.NUM_2;
case java.awt.event.KeyEvent.VK_3:
return Input.Keys.NUM_3;
case java.awt.event.KeyEvent.VK_4:
return Input.Keys.NUM_4;
case java.awt.event.KeyEvent.VK_5:
return Input.Keys.NUM_5;
case java.awt.event.KeyEvent.VK_6:
return Input.Keys.NUM_6;
case java.awt.event.KeyEvent.VK_7:
return Input.Keys.NUM_7;
case java.awt.event.KeyEvent.VK_8:
return Input.Keys.NUM_8;
case java.awt.event.KeyEvent.VK_9:
return Input.Keys.NUM_9;
case java.awt.event.KeyEvent.VK_A:
return Input.Keys.A;
case java.awt.event.KeyEvent.VK_B:
return Input.Keys.B;
case java.awt.event.KeyEvent.VK_C:
return Input.Keys.C;
case java.awt.event.KeyEvent.VK_D:
return Input.Keys.D;
case java.awt.event.KeyEvent.VK_E:
return Input.Keys.E;
case java.awt.event.KeyEvent.VK_F:
return Input.Keys.F;
case java.awt.event.KeyEvent.VK_G:
return Input.Keys.G;
case java.awt.event.KeyEvent.VK_H:
return Input.Keys.H;
case java.awt.event.KeyEvent.VK_I:
return Input.Keys.I;
case java.awt.event.KeyEvent.VK_J:
return Input.Keys.J;
case java.awt.event.KeyEvent.VK_K:
return Input.Keys.K;
case java.awt.event.KeyEvent.VK_L:
return Input.Keys.L;
case java.awt.event.KeyEvent.VK_M:
return Input.Keys.M;
case java.awt.event.KeyEvent.VK_N:
return Input.Keys.N;
case java.awt.event.KeyEvent.VK_O:
return Input.Keys.O;
case java.awt.event.KeyEvent.VK_P:
return Input.Keys.P;
case java.awt.event.KeyEvent.VK_Q:
return Input.Keys.Q;
case java.awt.event.KeyEvent.VK_R:
return Input.Keys.R;
case java.awt.event.KeyEvent.VK_S:
return Input.Keys.S;
case java.awt.event.KeyEvent.VK_T:
return Input.Keys.T;
case java.awt.event.KeyEvent.VK_U:
return Input.Keys.U;
case java.awt.event.KeyEvent.VK_V:
return Input.Keys.V;
case java.awt.event.KeyEvent.VK_W:
return Input.Keys.W;
case java.awt.event.KeyEvent.VK_X:
return Input.Keys.X;
case java.awt.event.KeyEvent.VK_Y:
return Input.Keys.Y;
case java.awt.event.KeyEvent.VK_Z:
return Input.Keys.Z;
case java.awt.event.KeyEvent.VK_ALT:
return Input.Keys.ALT_LEFT;
case java.awt.event.KeyEvent.VK_ALT_GRAPH:
return Input.Keys.ALT_RIGHT;
case java.awt.event.KeyEvent.VK_BACK_SLASH:
return Input.Keys.BACKSLASH;
case java.awt.event.KeyEvent.VK_COMMA:
return Input.Keys.COMMA;
case java.awt.event.KeyEvent.VK_DELETE:
return Input.Keys.FORWARD_DEL;
case java.awt.event.KeyEvent.VK_LEFT:
return Input.Keys.DPAD_LEFT;
case java.awt.event.KeyEvent.VK_RIGHT:
return Input.Keys.DPAD_RIGHT;
case java.awt.event.KeyEvent.VK_UP:
return Input.Keys.DPAD_UP;
case java.awt.event.KeyEvent.VK_DOWN:
return Input.Keys.DPAD_DOWN;
case java.awt.event.KeyEvent.VK_ENTER:
return Input.Keys.ENTER;
case java.awt.event.KeyEvent.VK_HOME:
return Input.Keys.HOME;
case java.awt.event.KeyEvent.VK_MINUS:
return Input.Keys.MINUS;
case java.awt.event.KeyEvent.VK_SUBTRACT:
return Keys.NUMPAD_SUBTRACT;
case java.awt.event.KeyEvent.VK_PERIOD:
return Input.Keys.PERIOD;
case java.awt.event.KeyEvent.VK_PLUS:
return Input.Keys.PLUS;
case java.awt.event.KeyEvent.VK_ADD:
return Keys.NUMPAD_ADD;
case java.awt.event.KeyEvent.VK_SEMICOLON:
return Input.Keys.SEMICOLON;
case java.awt.event.KeyEvent.VK_SHIFT:
return Input.Keys.SHIFT_LEFT;
case java.awt.event.KeyEvent.VK_SLASH:
return Input.Keys.SLASH;
case java.awt.event.KeyEvent.VK_SPACE:
return Input.Keys.SPACE;
case java.awt.event.KeyEvent.VK_TAB:
return Input.Keys.TAB;
case java.awt.event.KeyEvent.VK_BACK_SPACE:
return Input.Keys.DEL;
case java.awt.event.KeyEvent.VK_QUOTE:
return Input.Keys.APOSTROPHE;
case java.awt.event.KeyEvent.VK_ASTERISK:
return Input.Keys.STAR;
case java.awt.event.KeyEvent.VK_MULTIPLY:
return Keys.NUMPAD_MULTIPLY;
case java.awt.event.KeyEvent.VK_CONTROL:
return Input.Keys.CONTROL_LEFT;
case java.awt.event.KeyEvent.VK_ESCAPE:
return Input.Keys.ESCAPE;
case java.awt.event.KeyEvent.VK_END:
return Input.Keys.END;
case java.awt.event.KeyEvent.VK_INSERT:
return Input.Keys.INSERT;
case java.awt.event.KeyEvent.VK_PAGE_UP:
return Input.Keys.PAGE_UP;
case java.awt.event.KeyEvent.VK_PAGE_DOWN:
return Input.Keys.PAGE_DOWN;
case java.awt.event.KeyEvent.VK_F1:
return Input.Keys.F1;
case java.awt.event.KeyEvent.VK_F2:
return Input.Keys.F2;
case java.awt.event.KeyEvent.VK_F3:
return Input.Keys.F3;
case java.awt.event.KeyEvent.VK_F4:
return Input.Keys.F4;
case java.awt.event.KeyEvent.VK_F5:
return Input.Keys.F5;
case java.awt.event.KeyEvent.VK_F6:
return Input.Keys.F6;
case java.awt.event.KeyEvent.VK_F7:
return Input.Keys.F7;
case java.awt.event.KeyEvent.VK_F8:
return Input.Keys.F8;
case java.awt.event.KeyEvent.VK_F9:
return Input.Keys.F9;
case java.awt.event.KeyEvent.VK_F10:
return Input.Keys.F10;
case java.awt.event.KeyEvent.VK_F11:
return Input.Keys.F11;
case java.awt.event.KeyEvent.VK_F12:
return Input.Keys.F12;
case java.awt.event.KeyEvent.VK_F13:
return Input.Keys.F13;
case java.awt.event.KeyEvent.VK_F14:
return Input.Keys.F14;
case java.awt.event.KeyEvent.VK_F15:
return Input.Keys.F15;
case java.awt.event.KeyEvent.VK_F16:
return Input.Keys.F16;
case java.awt.event.KeyEvent.VK_F17:
return Input.Keys.F17;
case java.awt.event.KeyEvent.VK_F18:
return Input.Keys.F18;
case java.awt.event.KeyEvent.VK_F19:
return Input.Keys.F19;
case java.awt.event.KeyEvent.VK_F20:
return Input.Keys.F20;
case java.awt.event.KeyEvent.VK_F21:
return Input.Keys.F21;
case java.awt.event.KeyEvent.VK_F22:
return Input.Keys.F22;
case java.awt.event.KeyEvent.VK_F23:
return Input.Keys.F23;
case java.awt.event.KeyEvent.VK_F24:
return Input.Keys.F24;
case java.awt.event.KeyEvent.VK_COLON:
return Input.Keys.COLON;
case java.awt.event.KeyEvent.VK_NUMPAD0:
return Keys.NUMPAD_0;
case java.awt.event.KeyEvent.VK_NUMPAD1:
return Keys.NUMPAD_1;
case java.awt.event.KeyEvent.VK_NUMPAD2:
return Keys.NUMPAD_2;
case java.awt.event.KeyEvent.VK_NUMPAD3:
return Keys.NUMPAD_3;
case java.awt.event.KeyEvent.VK_NUMPAD4:
return Keys.NUMPAD_4;
case java.awt.event.KeyEvent.VK_NUMPAD5:
return Keys.NUMPAD_5;
case java.awt.event.KeyEvent.VK_NUMPAD6:
return Keys.NUMPAD_6;
case java.awt.event.KeyEvent.VK_NUMPAD7:
return Keys.NUMPAD_7;
case java.awt.event.KeyEvent.VK_NUMPAD8:
return Keys.NUMPAD_8;
case java.awt.event.KeyEvent.VK_NUMPAD9:
return Keys.NUMPAD_9;
case java.awt.event.KeyEvent.VK_SEPARATOR:
return Keys.NUMPAD_COMMA;
case java.awt.event.KeyEvent.VK_DECIMAL:
return Keys.NUMPAD_DOT;
case java.awt.event.KeyEvent.VK_DIVIDE:
return Keys.NUMPAD_DIVIDE;
case java.awt.event.KeyEvent.VK_NUM_LOCK:
return Keys.NUM_LOCK;
case java.awt.event.KeyEvent.VK_SCROLL_LOCK:
return Keys.SCROLL_LOCK;
case java.awt.event.KeyEvent.VK_PRINTSCREEN:
return Keys.PRINT_SCREEN;
case java.awt.event.KeyEvent.VK_PAUSE:
return Keys.PAUSE;
case java.awt.event.KeyEvent.VK_CAPS_LOCK:
return Keys.CAPS_LOCK;
}
return Input.Keys.UNKNOWN;
}
@Override
public void setInputProcessor (InputProcessor processor) {
synchronized (this) {
this.processor = processor;
}
}
@Override
public InputProcessor getInputProcessor () {
return this.processor;
}
@Override
public void vibrate (int milliseconds) {
}
@Override
public void vibrate (int milliseconds, boolean fallback) {
}
@Override
public void vibrate (int milliseconds, int amplitude, boolean fallback) {
}
@Override
public void vibrate (VibrationType vibrationType) {
}
@Override
public boolean justTouched () {
return justTouched;
}
@Override
public boolean isButtonPressed (int button) {
return pressedButtons.contains(button);
}
@Override
public boolean isButtonJustPressed (int button) {
if (button < 0 || button >= justPressedButtons.length) return false;
return justPressedButtons[button];
}
@Override
public float getAzimuth () {
return 0;
}
@Override
public float getPitch () {
return 0;
}
@Override
public float getRoll () {
return 0;
}
@Override
public boolean isPeripheralAvailable (Peripheral peripheral) {
if (peripheral == Peripheral.HardwareKeyboard) return true;
return false;
}
@Override
public int getRotation () {
return 0;
}
@Override
public Orientation getNativeOrientation () {
return Orientation.Landscape;
}
@Override
public void setCursorCatched (boolean catched) {
this.catched = catched;
showCursor(!catched);
}
private void showCursor (boolean visible) {
if (!visible) {
Toolkit t = Toolkit.getDefaultToolkit();
Image i = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Cursor noCursor = t.createCustomCursor(i, new Point(0, 0), "none");
JFrame frame = findJFrame(canvas);
frame.setCursor(noCursor);
} else {
JFrame frame = findJFrame(canvas);
frame.setCursor(Cursor.getDefaultCursor());
}
}
protected static JFrame findJFrame (Component component) {
Container parent = component.getParent();
while (parent != null) {
if (parent instanceof JFrame) {
return (JFrame)parent;
}
parent = parent.getParent();
}
return null;
}
@Override
public boolean isCursorCatched () {
return catched;
}
@Override
public int getDeltaX () {
return deltaX;
}
@Override
public int getDeltaX (int pointer) {
if (pointer == 0) return deltaX;
return 0;
}
@Override
public int getDeltaY () {
return deltaY;
}
@Override
public int getDeltaY (int pointer) {
if (pointer == 0) return deltaY;
return 0;
}
@Override
public void setCursorPosition (int x, int y) {
if (robot != null) {
robot.mouseMove(canvas.getLocationOnScreen().x + x, canvas.getLocationOnScreen().y + y);
}
}
@Override
public long getCurrentEventTime () {
return currentEventTimeStamp;
}
@Override
public void getRotationMatrix (float[] matrix) {
}
@Override
public float getGyroscopeX () {
return 0;
}
@Override
public float getGyroscopeY () {
return 0;
}
@Override
public float getGyroscopeZ () {
return 0;
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.lwjgl;
import java.awt.AWTException;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.OverlayLayout;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import com.badlogic.gdx.AbstractInput;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.utils.IntSet;
import com.badlogic.gdx.utils.Pool;
public class LwjglAWTInput extends AbstractInput implements MouseMotionListener, MouseListener, MouseWheelListener, KeyListener {
class KeyEvent {
static final int KEY_DOWN = 0;
static final int KEY_UP = 1;
static final int KEY_TYPED = 2;
long timeStamp;
int type;
int keyCode;
char keyChar;
}
class TouchEvent {
static final int TOUCH_DOWN = 0;
static final int TOUCH_UP = 1;
static final int TOUCH_DRAGGED = 2;
static final int TOUCH_MOVED = 3;
static final int TOUCH_SCROLLED = 4;
long timeStamp;
int type;
int x;
int y;
int pointer;
int button;
int scrollAmount;
}
Pool<KeyEvent> usedKeyEvents = new Pool<KeyEvent>(16, 1000) {
protected KeyEvent newObject () {
return new KeyEvent();
}
};
Pool<TouchEvent> usedTouchEvents = new Pool<TouchEvent>(16, 1000) {
protected TouchEvent newObject () {
return new TouchEvent();
}
};
private final LwjglAWTCanvas lwjglAwtCanvas;
List<KeyEvent> keyEvents = new ArrayList<KeyEvent>();
List<TouchEvent> touchEvents = new ArrayList<TouchEvent>();
int touchX = 0;
int touchY = 0;
int deltaX = 0;
int deltaY = 0;
boolean touchDown = false;
boolean justTouched = false;
boolean[] justPressedButtons = new boolean[5];
IntSet pressedButtons = new IntSet();
InputProcessor processor;
Canvas canvas;
boolean catched = false;
Robot robot = null;
long currentEventTimeStamp;
public LwjglAWTInput (LwjglAWTCanvas lwjglAwtCanvas) {
this.lwjglAwtCanvas = lwjglAwtCanvas;
setListeners(lwjglAwtCanvas.getCanvas());
try {
robot = new Robot(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice());
} catch (HeadlessException e) {
} catch (AWTException e) {
}
}
public void setListeners (Canvas canvas) {
if (this.canvas != null) {
canvas.removeMouseListener(this);
canvas.removeMouseMotionListener(this);
canvas.removeMouseWheelListener(this);
canvas.removeKeyListener(this);
}
canvas.addMouseListener(this);
canvas.addMouseMotionListener(this);
canvas.addMouseWheelListener(this);
canvas.addKeyListener(this);
canvas.setFocusTraversalKeysEnabled(false);
this.canvas = canvas;
}
@Override
public float getAccelerometerX () {
return 0;
}
@Override
public float getAccelerometerY () {
return 0;
}
@Override
public float getAccelerometerZ () {
return 0;
}
@Override
public void getTextInput (TextInputListener listener, String title, String text, String hint) {
getTextInput(listener, title, text, hint, OnscreenKeyboardType.Default);
}
@Override
public void getTextInput (final TextInputListener listener, final String title, final String text, final String hint,
OnscreenKeyboardType type) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run () {
JPanel panel = new JPanel(new FlowLayout());
JPanel textPanel = new JPanel() {
public boolean isOptimizedDrawingEnabled () {
return false;
};
};
textPanel.setLayout(new OverlayLayout(textPanel));
panel.add(textPanel);
final JTextField textField = new JTextField(20);
textField.setText(text);
textField.setAlignmentX(0.0f);
textPanel.add(textField);
final JLabel placeholderLabel = new JLabel(hint);
placeholderLabel.setForeground(Color.GRAY);
placeholderLabel.setAlignmentX(0.0f);
textPanel.add(placeholderLabel, 0);
textField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate (DocumentEvent arg0) {
this.updated();
}
@Override
public void insertUpdate (DocumentEvent arg0) {
this.updated();
}
@Override
public void changedUpdate (DocumentEvent arg0) {
this.updated();
}
private void updated () {
if (textField.getText().length() == 0)
placeholderLabel.setVisible(true);
else
placeholderLabel.setVisible(false);
}
});
JOptionPane pane = new JOptionPane(panel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, null,
null);
pane.setInitialValue(null);
pane.setComponentOrientation(JOptionPane.getRootFrame().getComponentOrientation());
Border border = textField.getBorder();
placeholderLabel.setBorder(new EmptyBorder(border.getBorderInsets(textField)));
JDialog dialog = pane.createDialog(null, title);
pane.selectInitialValue();
dialog.addWindowFocusListener(new WindowFocusListener() {
@Override
public void windowLostFocus (WindowEvent arg0) {
}
@Override
public void windowGainedFocus (WindowEvent arg0) {
textField.requestFocusInWindow();
}
});
dialog.setVisible(true);
dialog.dispose();
Object selectedValue = pane.getValue();
if (selectedValue != null && (selectedValue instanceof Integer)
&& ((Integer)selectedValue).intValue() == JOptionPane.OK_OPTION) {
listener.input(textField.getText());
} else {
listener.canceled();
}
}
});
}
@Override
public int getMaxPointers () {
return 1;
}
@Override
public int getX () {
return touchX;
}
@Override
public int getX (int pointer) {
if (pointer == 0)
return touchX;
else
return 0;
}
@Override
public int getY () {
return touchY;
}
@Override
public int getY (int pointer) {
if (pointer == 0)
return touchY;
else
return 0;
}
@Override
public synchronized boolean isKeyPressed (int key) {
if (key == Input.Keys.ANY_KEY) {
return pressedKeyCount > 0;
}
if (key < 0 || key > 255) {
return false;
}
return pressedKeys[key];
}
@Override
public synchronized boolean isKeyJustPressed (int key) {
if (key == Input.Keys.ANY_KEY) {
return keyJustPressed;
}
if (key < 0 || key > 255) {
return false;
}
return justPressedKeys[key];
}
@Override
public boolean isTouched () {
return touchDown;
}
@Override
public boolean isTouched (int pointer) {
if (pointer == 0)
return touchDown;
else
return false;
}
@Override
public float getPressure () {
return getPressure(0);
}
@Override
public float getPressure (int pointer) {
return isTouched(pointer) ? 1 : 0;
}
void processEvents () {
synchronized (this) {
if (justTouched) {
justTouched = false;
for (int i = 0; i < justPressedButtons.length; i++) {
justPressedButtons[i] = false;
}
}
if (keyJustPressed) {
keyJustPressed = false;
for (int i = 0; i < justPressedKeys.length; i++) {
justPressedKeys[i] = false;
}
}
if (processor != null) {
InputProcessor processor = this.processor;
int len = keyEvents.size();
for (int i = 0; i < len; i++) {
KeyEvent e = keyEvents.get(i);
currentEventTimeStamp = e.timeStamp;
switch (e.type) {
case KeyEvent.KEY_DOWN:
processor.keyDown(e.keyCode);
keyJustPressed = true;
justPressedKeys[e.keyCode] = true;
break;
case KeyEvent.KEY_UP:
processor.keyUp(e.keyCode);
break;
case KeyEvent.KEY_TYPED:
processor.keyTyped(e.keyChar);
}
usedKeyEvents.free(e);
}
len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent e = touchEvents.get(i);
currentEventTimeStamp = e.timeStamp;
switch (e.type) {
case TouchEvent.TOUCH_DOWN:
processor.touchDown(e.x, e.y, e.pointer, e.button);
justTouched = true;
justPressedButtons[e.button] = true;
break;
case TouchEvent.TOUCH_UP:
processor.touchUp(e.x, e.y, e.pointer, e.button);
break;
case TouchEvent.TOUCH_DRAGGED:
processor.touchDragged(e.x, e.y, e.pointer);
break;
case TouchEvent.TOUCH_MOVED:
processor.mouseMoved(e.x, e.y);
break;
case TouchEvent.TOUCH_SCROLLED:
processor.scrolled(0, e.scrollAmount);
break;
}
usedTouchEvents.free(e);
}
} else {
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if (event.type == TouchEvent.TOUCH_DOWN) justTouched = true;
usedTouchEvents.free(event);
}
len = keyEvents.size();
for (int i = 0; i < len; i++) {
usedKeyEvents.free(keyEvents.get(i));
}
}
if (touchEvents.isEmpty()) {
deltaX = 0;
deltaY = 0;
}
keyEvents.clear();
touchEvents.clear();
}
}
@Override
public void setOnscreenKeyboardVisible (boolean visible) {
}
@Override
public void setOnscreenKeyboardVisible (boolean visible, OnscreenKeyboardType type) {
}
@Override
public void mouseDragged (MouseEvent e) {
synchronized (this) {
TouchEvent event = usedTouchEvents.obtain();
event.pointer = 0;
event.x = e.getX();
event.y = e.getY();
event.type = TouchEvent.TOUCH_DRAGGED;
event.timeStamp = System.nanoTime();
touchEvents.add(event);
deltaX = event.x - touchX;
deltaY = event.y - touchY;
touchX = event.x;
touchY = event.y;
checkCatched(e);
lwjglAwtCanvas.graphics.requestRendering();
}
}
@Override
public void mouseMoved (MouseEvent e) {
synchronized (this) {
TouchEvent event = usedTouchEvents.obtain();
event.pointer = 0;
event.x = e.getX();
event.y = e.getY();
event.type = TouchEvent.TOUCH_MOVED;
event.timeStamp = System.nanoTime();
touchEvents.add(event);
deltaX = event.x - touchX;
deltaY = event.y - touchY;
touchX = event.x;
touchY = event.y;
checkCatched(e);
lwjglAwtCanvas.graphics.requestRendering();
}
}
@Override
public void mouseClicked (MouseEvent arg0) {
}
@Override
public void mouseEntered (MouseEvent e) {
touchX = e.getX();
touchY = e.getY();
checkCatched(e);
lwjglAwtCanvas.graphics.requestRendering();
}
@Override
public void mouseExited (MouseEvent e) {
checkCatched(e);
lwjglAwtCanvas.graphics.requestRendering();
}
private void checkCatched (MouseEvent e) {
if (catched && robot != null && canvas.isShowing()) {
int x = Math.max(0, Math.min(e.getX(), canvas.getWidth()) - 1) + canvas.getLocationOnScreen().x;
int y = Math.max(0, Math.min(e.getY(), canvas.getHeight()) - 1) + canvas.getLocationOnScreen().y;
if (e.getX() < 0 || e.getX() >= canvas.getWidth() || e.getY() < 0 || e.getY() >= canvas.getHeight()) {
robot.mouseMove(x, y);
}
}
}
private int toGdxButton (int swingButton) {
if (swingButton == MouseEvent.BUTTON1) return Buttons.LEFT;
if (swingButton == MouseEvent.BUTTON2) return Buttons.MIDDLE;
if (swingButton == MouseEvent.BUTTON3) return Buttons.RIGHT;
return Buttons.LEFT;
}
@Override
public void mousePressed (MouseEvent e) {
synchronized (this) {
TouchEvent event = usedTouchEvents.obtain();
event.pointer = 0;
event.x = e.getX();
event.y = e.getY();
event.type = TouchEvent.TOUCH_DOWN;
event.button = toGdxButton(e.getButton());
event.timeStamp = System.nanoTime();
touchEvents.add(event);
deltaX = event.x - touchX;
deltaY = event.y - touchY;
touchX = event.x;
touchY = event.y;
touchDown = true;
pressedButtons.add(event.button);
lwjglAwtCanvas.graphics.requestRendering();
}
}
@Override
public void mouseReleased (MouseEvent e) {
synchronized (this) {
TouchEvent event = usedTouchEvents.obtain();
event.pointer = 0;
event.x = e.getX();
event.y = e.getY();
event.button = toGdxButton(e.getButton());
event.type = TouchEvent.TOUCH_UP;
event.timeStamp = System.nanoTime();
touchEvents.add(event);
deltaX = event.x - touchX;
deltaY = event.y - touchY;
touchX = event.x;
touchY = event.y;
pressedButtons.remove(event.button);
if (pressedButtons.size == 0) touchDown = false;
lwjglAwtCanvas.graphics.requestRendering();
}
}
@Override
public void mouseWheelMoved (MouseWheelEvent e) {
synchronized (this) {
TouchEvent event = usedTouchEvents.obtain();
event.pointer = 0;
event.type = TouchEvent.TOUCH_SCROLLED;
event.scrollAmount = e.getWheelRotation();
event.timeStamp = System.nanoTime();
touchEvents.add(event);
lwjglAwtCanvas.graphics.requestRendering();
}
}
@Override
public void keyPressed (java.awt.event.KeyEvent e) {
synchronized (this) {
KeyEvent event = usedKeyEvents.obtain();
event.keyChar = 0;
event.keyCode = translateKeyCode(e.getKeyCode());
event.type = KeyEvent.KEY_DOWN;
event.timeStamp = System.nanoTime();
keyEvents.add(event);
if (!pressedKeys[event.keyCode]) {
pressedKeyCount++;
pressedKeys[event.keyCode] = true;
}
lwjglAwtCanvas.graphics.requestRendering();
}
}
@Override
public void keyReleased (java.awt.event.KeyEvent e) {
synchronized (this) {
KeyEvent event = usedKeyEvents.obtain();
event.keyChar = 0;
event.keyCode = translateKeyCode(e.getKeyCode());
event.type = KeyEvent.KEY_UP;
event.timeStamp = System.nanoTime();
keyEvents.add(event);
if (pressedKeys[event.keyCode]) {
pressedKeyCount--;
pressedKeys[event.keyCode] = false;
}
lwjglAwtCanvas.graphics.requestRendering();
}
}
@Override
public void keyTyped (java.awt.event.KeyEvent e) {
synchronized (this) {
KeyEvent event = usedKeyEvents.obtain();
event.keyChar = e.getKeyChar();
event.keyCode = 0;
event.type = KeyEvent.KEY_TYPED;
event.timeStamp = System.nanoTime();
keyEvents.add(event);
lwjglAwtCanvas.graphics.requestRendering();
}
}
protected int translateKeyCode (int keyCode) {
switch (keyCode) {
case java.awt.event.KeyEvent.VK_0:
return Input.Keys.NUM_0;
case java.awt.event.KeyEvent.VK_1:
return Input.Keys.NUM_1;
case java.awt.event.KeyEvent.VK_2:
return Input.Keys.NUM_2;
case java.awt.event.KeyEvent.VK_3:
return Input.Keys.NUM_3;
case java.awt.event.KeyEvent.VK_4:
return Input.Keys.NUM_4;
case java.awt.event.KeyEvent.VK_5:
return Input.Keys.NUM_5;
case java.awt.event.KeyEvent.VK_6:
return Input.Keys.NUM_6;
case java.awt.event.KeyEvent.VK_7:
return Input.Keys.NUM_7;
case java.awt.event.KeyEvent.VK_8:
return Input.Keys.NUM_8;
case java.awt.event.KeyEvent.VK_9:
return Input.Keys.NUM_9;
case java.awt.event.KeyEvent.VK_A:
return Input.Keys.A;
case java.awt.event.KeyEvent.VK_B:
return Input.Keys.B;
case java.awt.event.KeyEvent.VK_C:
return Input.Keys.C;
case java.awt.event.KeyEvent.VK_D:
return Input.Keys.D;
case java.awt.event.KeyEvent.VK_E:
return Input.Keys.E;
case java.awt.event.KeyEvent.VK_F:
return Input.Keys.F;
case java.awt.event.KeyEvent.VK_G:
return Input.Keys.G;
case java.awt.event.KeyEvent.VK_H:
return Input.Keys.H;
case java.awt.event.KeyEvent.VK_I:
return Input.Keys.I;
case java.awt.event.KeyEvent.VK_J:
return Input.Keys.J;
case java.awt.event.KeyEvent.VK_K:
return Input.Keys.K;
case java.awt.event.KeyEvent.VK_L:
return Input.Keys.L;
case java.awt.event.KeyEvent.VK_M:
return Input.Keys.M;
case java.awt.event.KeyEvent.VK_N:
return Input.Keys.N;
case java.awt.event.KeyEvent.VK_O:
return Input.Keys.O;
case java.awt.event.KeyEvent.VK_P:
return Input.Keys.P;
case java.awt.event.KeyEvent.VK_Q:
return Input.Keys.Q;
case java.awt.event.KeyEvent.VK_R:
return Input.Keys.R;
case java.awt.event.KeyEvent.VK_S:
return Input.Keys.S;
case java.awt.event.KeyEvent.VK_T:
return Input.Keys.T;
case java.awt.event.KeyEvent.VK_U:
return Input.Keys.U;
case java.awt.event.KeyEvent.VK_V:
return Input.Keys.V;
case java.awt.event.KeyEvent.VK_W:
return Input.Keys.W;
case java.awt.event.KeyEvent.VK_X:
return Input.Keys.X;
case java.awt.event.KeyEvent.VK_Y:
return Input.Keys.Y;
case java.awt.event.KeyEvent.VK_Z:
return Input.Keys.Z;
case java.awt.event.KeyEvent.VK_ALT:
return Input.Keys.ALT_LEFT;
case java.awt.event.KeyEvent.VK_ALT_GRAPH:
return Input.Keys.ALT_RIGHT;
case java.awt.event.KeyEvent.VK_BACK_SLASH:
return Input.Keys.BACKSLASH;
case java.awt.event.KeyEvent.VK_COMMA:
return Input.Keys.COMMA;
case java.awt.event.KeyEvent.VK_DELETE:
return Input.Keys.FORWARD_DEL;
case java.awt.event.KeyEvent.VK_LEFT:
return Input.Keys.DPAD_LEFT;
case java.awt.event.KeyEvent.VK_RIGHT:
return Input.Keys.DPAD_RIGHT;
case java.awt.event.KeyEvent.VK_UP:
return Input.Keys.DPAD_UP;
case java.awt.event.KeyEvent.VK_DOWN:
return Input.Keys.DPAD_DOWN;
case java.awt.event.KeyEvent.VK_ENTER:
return Input.Keys.ENTER;
case java.awt.event.KeyEvent.VK_HOME:
return Input.Keys.HOME;
case java.awt.event.KeyEvent.VK_MINUS:
return Input.Keys.MINUS;
case java.awt.event.KeyEvent.VK_SUBTRACT:
return Keys.NUMPAD_SUBTRACT;
case java.awt.event.KeyEvent.VK_PERIOD:
return Input.Keys.PERIOD;
case java.awt.event.KeyEvent.VK_PLUS:
return Input.Keys.PLUS;
case java.awt.event.KeyEvent.VK_ADD:
return Keys.NUMPAD_ADD;
case java.awt.event.KeyEvent.VK_SEMICOLON:
return Input.Keys.SEMICOLON;
case java.awt.event.KeyEvent.VK_SHIFT:
return Input.Keys.SHIFT_LEFT;
case java.awt.event.KeyEvent.VK_SLASH:
return Input.Keys.SLASH;
case java.awt.event.KeyEvent.VK_SPACE:
return Input.Keys.SPACE;
case java.awt.event.KeyEvent.VK_TAB:
return Input.Keys.TAB;
case java.awt.event.KeyEvent.VK_BACK_SPACE:
return Input.Keys.DEL;
case java.awt.event.KeyEvent.VK_QUOTE:
return Input.Keys.APOSTROPHE;
case java.awt.event.KeyEvent.VK_ASTERISK:
return Input.Keys.STAR;
case java.awt.event.KeyEvent.VK_MULTIPLY:
return Keys.NUMPAD_MULTIPLY;
case java.awt.event.KeyEvent.VK_CONTROL:
return Input.Keys.CONTROL_LEFT;
case java.awt.event.KeyEvent.VK_ESCAPE:
return Input.Keys.ESCAPE;
case java.awt.event.KeyEvent.VK_END:
return Input.Keys.END;
case java.awt.event.KeyEvent.VK_INSERT:
return Input.Keys.INSERT;
case java.awt.event.KeyEvent.VK_PAGE_UP:
return Input.Keys.PAGE_UP;
case java.awt.event.KeyEvent.VK_PAGE_DOWN:
return Input.Keys.PAGE_DOWN;
case java.awt.event.KeyEvent.VK_F1:
return Input.Keys.F1;
case java.awt.event.KeyEvent.VK_F2:
return Input.Keys.F2;
case java.awt.event.KeyEvent.VK_F3:
return Input.Keys.F3;
case java.awt.event.KeyEvent.VK_F4:
return Input.Keys.F4;
case java.awt.event.KeyEvent.VK_F5:
return Input.Keys.F5;
case java.awt.event.KeyEvent.VK_F6:
return Input.Keys.F6;
case java.awt.event.KeyEvent.VK_F7:
return Input.Keys.F7;
case java.awt.event.KeyEvent.VK_F8:
return Input.Keys.F8;
case java.awt.event.KeyEvent.VK_F9:
return Input.Keys.F9;
case java.awt.event.KeyEvent.VK_F10:
return Input.Keys.F10;
case java.awt.event.KeyEvent.VK_F11:
return Input.Keys.F11;
case java.awt.event.KeyEvent.VK_F12:
return Input.Keys.F12;
case java.awt.event.KeyEvent.VK_F13:
return Input.Keys.F13;
case java.awt.event.KeyEvent.VK_F14:
return Input.Keys.F14;
case java.awt.event.KeyEvent.VK_F15:
return Input.Keys.F15;
case java.awt.event.KeyEvent.VK_F16:
return Input.Keys.F16;
case java.awt.event.KeyEvent.VK_F17:
return Input.Keys.F17;
case java.awt.event.KeyEvent.VK_F18:
return Input.Keys.F18;
case java.awt.event.KeyEvent.VK_F19:
return Input.Keys.F19;
case java.awt.event.KeyEvent.VK_F20:
return Input.Keys.F20;
case java.awt.event.KeyEvent.VK_F21:
return Input.Keys.F21;
case java.awt.event.KeyEvent.VK_F22:
return Input.Keys.F22;
case java.awt.event.KeyEvent.VK_F23:
return Input.Keys.F23;
case java.awt.event.KeyEvent.VK_F24:
return Input.Keys.F24;
case java.awt.event.KeyEvent.VK_COLON:
return Input.Keys.COLON;
case java.awt.event.KeyEvent.VK_NUMPAD0:
return Keys.NUMPAD_0;
case java.awt.event.KeyEvent.VK_NUMPAD1:
return Keys.NUMPAD_1;
case java.awt.event.KeyEvent.VK_NUMPAD2:
return Keys.NUMPAD_2;
case java.awt.event.KeyEvent.VK_NUMPAD3:
return Keys.NUMPAD_3;
case java.awt.event.KeyEvent.VK_NUMPAD4:
return Keys.NUMPAD_4;
case java.awt.event.KeyEvent.VK_NUMPAD5:
return Keys.NUMPAD_5;
case java.awt.event.KeyEvent.VK_NUMPAD6:
return Keys.NUMPAD_6;
case java.awt.event.KeyEvent.VK_NUMPAD7:
return Keys.NUMPAD_7;
case java.awt.event.KeyEvent.VK_NUMPAD8:
return Keys.NUMPAD_8;
case java.awt.event.KeyEvent.VK_NUMPAD9:
return Keys.NUMPAD_9;
case java.awt.event.KeyEvent.VK_SEPARATOR:
return Keys.NUMPAD_COMMA;
case java.awt.event.KeyEvent.VK_DECIMAL:
return Keys.NUMPAD_DOT;
case java.awt.event.KeyEvent.VK_DIVIDE:
return Keys.NUMPAD_DIVIDE;
case java.awt.event.KeyEvent.VK_NUM_LOCK:
return Keys.NUM_LOCK;
case java.awt.event.KeyEvent.VK_SCROLL_LOCK:
return Keys.SCROLL_LOCK;
case java.awt.event.KeyEvent.VK_PRINTSCREEN:
return Keys.PRINT_SCREEN;
case java.awt.event.KeyEvent.VK_PAUSE:
return Keys.PAUSE;
case java.awt.event.KeyEvent.VK_CAPS_LOCK:
return Keys.CAPS_LOCK;
}
return Input.Keys.UNKNOWN;
}
@Override
public void setInputProcessor (InputProcessor processor) {
synchronized (this) {
this.processor = processor;
}
}
@Override
public InputProcessor getInputProcessor () {
return this.processor;
}
@Override
public void vibrate (int milliseconds) {
}
@Override
public void vibrate (int milliseconds, boolean fallback) {
}
@Override
public void vibrate (int milliseconds, int amplitude, boolean fallback) {
}
@Override
public void vibrate (VibrationType vibrationType) {
}
@Override
public boolean justTouched () {
return justTouched;
}
@Override
public boolean isButtonPressed (int button) {
return pressedButtons.contains(button);
}
@Override
public boolean isButtonJustPressed (int button) {
if (button < 0 || button >= justPressedButtons.length) return false;
return justPressedButtons[button];
}
@Override
public float getAzimuth () {
return 0;
}
@Override
public float getPitch () {
return 0;
}
@Override
public float getRoll () {
return 0;
}
@Override
public boolean isPeripheralAvailable (Peripheral peripheral) {
if (peripheral == Peripheral.HardwareKeyboard) return true;
return false;
}
@Override
public int getRotation () {
return 0;
}
@Override
public Orientation getNativeOrientation () {
return Orientation.Landscape;
}
@Override
public void setCursorCatched (boolean catched) {
this.catched = catched;
showCursor(!catched);
}
private void showCursor (boolean visible) {
if (!visible) {
Toolkit t = Toolkit.getDefaultToolkit();
Image i = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Cursor noCursor = t.createCustomCursor(i, new Point(0, 0), "none");
JFrame frame = findJFrame(canvas);
frame.setCursor(noCursor);
} else {
JFrame frame = findJFrame(canvas);
frame.setCursor(Cursor.getDefaultCursor());
}
}
protected static JFrame findJFrame (Component component) {
Container parent = component.getParent();
while (parent != null) {
if (parent instanceof JFrame) {
return (JFrame)parent;
}
parent = parent.getParent();
}
return null;
}
@Override
public boolean isCursorCatched () {
return catched;
}
@Override
public int getDeltaX () {
return deltaX;
}
@Override
public int getDeltaX (int pointer) {
if (pointer == 0) return deltaX;
return 0;
}
@Override
public int getDeltaY () {
return deltaY;
}
@Override
public int getDeltaY (int pointer) {
if (pointer == 0) return deltaY;
return 0;
}
@Override
public void setCursorPosition (int x, int y) {
if (robot != null) {
robot.mouseMove(canvas.getLocationOnScreen().x + x, canvas.getLocationOnScreen().y + y);
}
}
@Override
public long getCurrentEventTime () {
return currentEventTimeStamp;
}
@Override
public void getRotationMatrix (float[] matrix) {
}
@Override
public float getGyroscopeX () {
return 0;
}
@Override
public float getGyroscopeY () {
return 0;
}
@Override
public float getGyroscopeZ () {
return 0;
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglAWTCanvas.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.lwjgl;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.PaintEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.SwingUtilities;
import com.badlogic.gdx.ApplicationLogger;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.AWTGLCanvas;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.PixelFormat;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.LifecycleListener;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.backends.lwjgl.audio.OpenALLwjglAudio;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Clipboard;
/** An OpenGL surface on an AWT Canvas, allowing OpenGL to be embedded in a Swing application. This uses {@link AWTGLCanvas},
* which allows multiple LwjglAWTCanvas to be used in a single application. All OpenGL calls are done on the EDT. Note that you
* may need to call {@link #stop()} or a Swing application may deadlock on System.exit due to how LWJGL and/or Swing deal with
* shutdown hooks.
* @author Nathan Sweet */
public class LwjglAWTCanvas implements Application {
static int instanceCount;
LwjglGraphics graphics;
OpenALLwjglAudio audio;
LwjglFiles files;
LwjglAWTInput input;
LwjglNet net;
final ApplicationListener listener;
AWTGLCanvas canvas;
final Array<Runnable> runnables = new Array();
final Array<Runnable> executedRunnables = new Array();
final Array<LifecycleListener> lifecycleListeners = new Array<LifecycleListener>();
boolean running = true;
int lastWidth;
int lastHeight;
int logLevel = LOG_INFO;
ApplicationLogger applicationLogger;
final String logTag = "LwjglAWTCanvas";
Cursor cursor;
public LwjglAWTCanvas (ApplicationListener listener) {
this(listener, null, null);
}
public LwjglAWTCanvas (ApplicationListener listener, LwjglAWTCanvas sharedContextCanvas) {
this(listener, null, sharedContextCanvas);
}
public LwjglAWTCanvas (ApplicationListener listener, LwjglApplicationConfiguration config) {
this(listener, config, null);
}
public LwjglAWTCanvas (ApplicationListener listener, LwjglApplicationConfiguration config,
LwjglAWTCanvas sharedContextCanvas) {
this.listener = listener;
if (config == null) config = new LwjglApplicationConfiguration();
LwjglNativesLoader.load();
setApplicationLogger(new LwjglApplicationLogger());
instanceCount++;
AWTGLCanvas sharedDrawable = sharedContextCanvas != null ? sharedContextCanvas.canvas : null;
try {
canvas = new AWTGLCanvas(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(), new PixelFormat(),
sharedDrawable) {
private final Dimension minSize = new Dimension(0, 0);
private final NonSystemPaint nonSystemPaint = new NonSystemPaint(this);
@Override
public Dimension getMinimumSize () {
return minSize;
}
@Override
public void initGL () {
create();
}
@Override
public void paintGL () {
try {
boolean systemPaint = !(EventQueue.getCurrentEvent() instanceof NonSystemPaint);
render(systemPaint);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(nonSystemPaint);
} catch (Throwable ex) {
exception(ex);
}
}
};
} catch (Throwable ex) {
exception(ex);
return;
}
canvas.setBackground(new Color(config.initialBackgroundColor.r, config.initialBackgroundColor.g,
config.initialBackgroundColor.b, config.initialBackgroundColor.a));
graphics = new LwjglGraphics(canvas, config) {
@Override
public void setTitle (String title) {
super.setTitle(title);
LwjglAWTCanvas.this.setTitle(title);
}
@Override
public boolean setWindowedMode (int width, int height) {
if (!super.setWindowedMode(width, height)) return false;
LwjglAWTCanvas.this.setDisplayMode(width, height);
return true;
}
@Override
public boolean setFullscreenMode (DisplayMode displayMode) {
if (!super.setFullscreenMode(displayMode)) return false;
LwjglAWTCanvas.this.setDisplayMode(displayMode.width, displayMode.height);
return true;
}
public boolean shouldRender () {
synchronized (this) {
boolean rq = requestRendering;
requestRendering = false;
return rq || isContinuous;
}
}
};
if (!LwjglApplicationConfiguration.disableAudio && Gdx.audio == null) audio = new OpenALLwjglAudio();
if (Gdx.files == null) files = new LwjglFiles();
if (Gdx.net == null) net = new LwjglNet(config);
input = new LwjglAWTInput(this);
setGlobals();
}
protected void setDisplayMode (int width, int height) {
}
protected void setTitle (String title) {
}
@Override
public ApplicationListener getApplicationListener () {
return listener;
}
public Canvas getCanvas () {
return canvas;
}
@Override
public Audio getAudio () {
return Gdx.audio;
}
@Override
public Files getFiles () {
return files;
}
@Override
public Graphics getGraphics () {
return graphics;
}
@Override
public Input getInput () {
return input;
}
@Override
public Net getNet () {
return net;
}
@Override
public ApplicationType getType () {
return ApplicationType.Desktop;
}
@Override
public int getVersion () {
return 0;
}
void setGlobals () {
Gdx.app = this;
if (audio != null) Gdx.audio = audio;
if (files != null) Gdx.files = files;
if (net != null) Gdx.net = net;
Gdx.graphics = graphics;
Gdx.input = input;
}
void create () {
try {
setGlobals();
graphics.initiateGL();
canvas.setVSyncEnabled(graphics.config.vSyncEnabled);
listener.create();
lastWidth = Math.max(1, graphics.getWidth());
lastHeight = Math.max(1, graphics.getHeight());
listener.resize(lastWidth, lastHeight);
start();
} catch (Throwable ex) {
stopped();
exception(ex);
}
}
void render (boolean shouldRender) throws LWJGLException {
if (!running) return;
setGlobals();
canvas.setCursor(cursor);
int width = Math.max(1, graphics.getWidth());
int height = Math.max(1, graphics.getHeight());
if (lastWidth != width || lastHeight != height) {
lastWidth = width;
lastHeight = height;
Gdx.gl.glViewport(0, 0, lastWidth, lastHeight);
resize(width, height);
listener.resize(width, height);
shouldRender = true;
}
if (executeRunnables()) shouldRender = true;
// If one of the runnables set running to false, for example after an exit().
if (!running) return;
shouldRender |= graphics.shouldRender();
input.processEvents();
if (audio != null) audio.update();
if (shouldRender) {
graphics.updateTime();
graphics.frameId++;
listener.render();
canvas.swapBuffers();
}
Display.sync(getFrameRate() * instanceCount);
}
public boolean executeRunnables () {
synchronized (runnables) {
for (int i = runnables.size - 1; i >= 0; i--)
executedRunnables.addAll(runnables.get(i));
runnables.clear();
}
if (executedRunnables.size == 0) return false;
do
executedRunnables.pop().run();
while (executedRunnables.size > 0);
return true;
}
protected int getFrameRate () {
int frameRate = isActive() ? graphics.config.foregroundFPS : graphics.config.backgroundFPS;
if (frameRate == -1) frameRate = 10;
if (frameRate == 0) frameRate = graphics.config.backgroundFPS;
if (frameRate == 0) frameRate = 30;
return frameRate;
}
/** Returns true when the frame containing the canvas is the foreground window. */
public boolean isActive () {
Component root = SwingUtilities.getRoot(canvas);
return root instanceof Frame ? ((Frame)root).isActive() : true;
}
/** Called after {@link ApplicationListener} create and resize, but before the game loop iteration. */
protected void start () {
}
/** Called when the canvas size changes. */
protected void resize (int width, int height) {
}
/** Called when the game loop has stopped. */
protected void stopped () {
}
public void stop () {
if (!running) return;
running = false;
setGlobals();
Array<LifecycleListener> listeners = lifecycleListeners;
// To allow destroying of OpenGL textures during disposal.
if (canvas.isDisplayable()) {
makeCurrent();
} else {
error(logTag, "OpenGL context destroyed before application listener has had a chance to dispose of textures.");
}
synchronized (listeners) {
for (LifecycleListener listener : listeners) {
listener.pause();
listener.dispose();
}
}
listener.pause();
listener.dispose();
Gdx.app = null;
Gdx.graphics = null;
if (audio != null) {
audio.dispose();
Gdx.audio = null;
}
if (files != null) Gdx.files = null;
if (net != null) Gdx.net = null;
instanceCount--;
stopped();
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return getJavaHeap();
}
Map<String, Preferences> preferences = new HashMap<String, Preferences>();
@Override
public Preferences getPreferences (String name) {
if (preferences.containsKey(name)) {
return preferences.get(name);
} else {
Preferences prefs = new LwjglPreferences(name, ".prefs/");
preferences.put(name, prefs);
return prefs;
}
}
@Override
public Clipboard getClipboard () {
return new LwjglClipboard();
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
}
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message);
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message, exception);
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message);
}
@Override
public void log (String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
@Override
public int getLogLevel () {
return logLevel;
}
@Override
public void setApplicationLogger (ApplicationLogger applicationLogger) {
this.applicationLogger = applicationLogger;
}
@Override
public ApplicationLogger getApplicationLogger () {
return applicationLogger;
}
@Override
public void exit () {
postRunnable(new Runnable() {
@Override
public void run () {
stop();
System.exit(-1);
}
});
}
/** Make the canvas' context current. It is highly recommended that the context is only made current inside the AWT thread (for
* example in an overridden paintGL()). */
public void makeCurrent () {
try {
canvas.makeCurrent();
setGlobals();
} catch (Throwable ex) {
exception(ex);
}
}
/** Test whether the canvas' context is current. */
public boolean isCurrent () {
try {
return canvas.isCurrent();
} catch (Throwable ex) {
exception(ex);
return false;
}
}
/** @param cursor May be null. */
public void setCursor (Cursor cursor) {
this.cursor = cursor;
}
@Override
public void addLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
protected void exception (Throwable ex) {
ex.printStackTrace();
stop();
}
static public class NonSystemPaint extends PaintEvent {
public NonSystemPaint (AWTGLCanvas canvas) {
super(canvas, UPDATE, new Rectangle(0, 0, 99999, 99999));
}
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.lwjgl;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.PaintEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.SwingUtilities;
import com.badlogic.gdx.ApplicationLogger;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.AWTGLCanvas;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.PixelFormat;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.LifecycleListener;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.backends.lwjgl.audio.OpenALLwjglAudio;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Clipboard;
/** An OpenGL surface on an AWT Canvas, allowing OpenGL to be embedded in a Swing application. This uses {@link AWTGLCanvas},
* which allows multiple LwjglAWTCanvas to be used in a single application. All OpenGL calls are done on the EDT. Note that you
* may need to call {@link #stop()} or a Swing application may deadlock on System.exit due to how LWJGL and/or Swing deal with
* shutdown hooks.
* @author Nathan Sweet */
public class LwjglAWTCanvas implements Application {
static int instanceCount;
LwjglGraphics graphics;
OpenALLwjglAudio audio;
LwjglFiles files;
LwjglAWTInput input;
LwjglNet net;
final ApplicationListener listener;
AWTGLCanvas canvas;
final Array<Runnable> runnables = new Array();
final Array<Runnable> executedRunnables = new Array();
final Array<LifecycleListener> lifecycleListeners = new Array<LifecycleListener>();
boolean running = true;
int lastWidth;
int lastHeight;
int logLevel = LOG_INFO;
ApplicationLogger applicationLogger;
final String logTag = "LwjglAWTCanvas";
Cursor cursor;
public LwjglAWTCanvas (ApplicationListener listener) {
this(listener, null, null);
}
public LwjglAWTCanvas (ApplicationListener listener, LwjglAWTCanvas sharedContextCanvas) {
this(listener, null, sharedContextCanvas);
}
public LwjglAWTCanvas (ApplicationListener listener, LwjglApplicationConfiguration config) {
this(listener, config, null);
}
public LwjglAWTCanvas (ApplicationListener listener, LwjglApplicationConfiguration config,
LwjglAWTCanvas sharedContextCanvas) {
this.listener = listener;
if (config == null) config = new LwjglApplicationConfiguration();
LwjglNativesLoader.load();
setApplicationLogger(new LwjglApplicationLogger());
instanceCount++;
AWTGLCanvas sharedDrawable = sharedContextCanvas != null ? sharedContextCanvas.canvas : null;
try {
canvas = new AWTGLCanvas(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(), new PixelFormat(),
sharedDrawable) {
private final Dimension minSize = new Dimension(0, 0);
private final NonSystemPaint nonSystemPaint = new NonSystemPaint(this);
@Override
public Dimension getMinimumSize () {
return minSize;
}
@Override
public void initGL () {
create();
}
@Override
public void paintGL () {
try {
boolean systemPaint = !(EventQueue.getCurrentEvent() instanceof NonSystemPaint);
render(systemPaint);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(nonSystemPaint);
} catch (Throwable ex) {
exception(ex);
}
}
};
} catch (Throwable ex) {
exception(ex);
return;
}
canvas.setBackground(new Color(config.initialBackgroundColor.r, config.initialBackgroundColor.g,
config.initialBackgroundColor.b, config.initialBackgroundColor.a));
graphics = new LwjglGraphics(canvas, config) {
@Override
public void setTitle (String title) {
super.setTitle(title);
LwjglAWTCanvas.this.setTitle(title);
}
@Override
public boolean setWindowedMode (int width, int height) {
if (!super.setWindowedMode(width, height)) return false;
LwjglAWTCanvas.this.setDisplayMode(width, height);
return true;
}
@Override
public boolean setFullscreenMode (DisplayMode displayMode) {
if (!super.setFullscreenMode(displayMode)) return false;
LwjglAWTCanvas.this.setDisplayMode(displayMode.width, displayMode.height);
return true;
}
public boolean shouldRender () {
synchronized (this) {
boolean rq = requestRendering;
requestRendering = false;
return rq || isContinuous;
}
}
};
if (!LwjglApplicationConfiguration.disableAudio && Gdx.audio == null) audio = new OpenALLwjglAudio();
if (Gdx.files == null) files = new LwjglFiles();
if (Gdx.net == null) net = new LwjglNet(config);
input = new LwjglAWTInput(this);
setGlobals();
}
protected void setDisplayMode (int width, int height) {
}
protected void setTitle (String title) {
}
@Override
public ApplicationListener getApplicationListener () {
return listener;
}
public Canvas getCanvas () {
return canvas;
}
@Override
public Audio getAudio () {
return Gdx.audio;
}
@Override
public Files getFiles () {
return files;
}
@Override
public Graphics getGraphics () {
return graphics;
}
@Override
public Input getInput () {
return input;
}
@Override
public Net getNet () {
return net;
}
@Override
public ApplicationType getType () {
return ApplicationType.Desktop;
}
@Override
public int getVersion () {
return 0;
}
void setGlobals () {
Gdx.app = this;
if (audio != null) Gdx.audio = audio;
if (files != null) Gdx.files = files;
if (net != null) Gdx.net = net;
Gdx.graphics = graphics;
Gdx.input = input;
}
void create () {
try {
setGlobals();
graphics.initiateGL();
canvas.setVSyncEnabled(graphics.config.vSyncEnabled);
listener.create();
lastWidth = Math.max(1, graphics.getWidth());
lastHeight = Math.max(1, graphics.getHeight());
listener.resize(lastWidth, lastHeight);
start();
} catch (Throwable ex) {
stopped();
exception(ex);
}
}
void render (boolean shouldRender) throws LWJGLException {
if (!running) return;
setGlobals();
canvas.setCursor(cursor);
int width = Math.max(1, graphics.getWidth());
int height = Math.max(1, graphics.getHeight());
if (lastWidth != width || lastHeight != height) {
lastWidth = width;
lastHeight = height;
Gdx.gl.glViewport(0, 0, lastWidth, lastHeight);
resize(width, height);
listener.resize(width, height);
shouldRender = true;
}
if (executeRunnables()) shouldRender = true;
// If one of the runnables set running to false, for example after an exit().
if (!running) return;
shouldRender |= graphics.shouldRender();
input.processEvents();
if (audio != null) audio.update();
if (shouldRender) {
graphics.updateTime();
graphics.frameId++;
listener.render();
canvas.swapBuffers();
}
Display.sync(getFrameRate() * instanceCount);
}
public boolean executeRunnables () {
synchronized (runnables) {
for (int i = runnables.size - 1; i >= 0; i--)
executedRunnables.addAll(runnables.get(i));
runnables.clear();
}
if (executedRunnables.size == 0) return false;
do
executedRunnables.pop().run();
while (executedRunnables.size > 0);
return true;
}
protected int getFrameRate () {
int frameRate = isActive() ? graphics.config.foregroundFPS : graphics.config.backgroundFPS;
if (frameRate == -1) frameRate = 10;
if (frameRate == 0) frameRate = graphics.config.backgroundFPS;
if (frameRate == 0) frameRate = 30;
return frameRate;
}
/** Returns true when the frame containing the canvas is the foreground window. */
public boolean isActive () {
Component root = SwingUtilities.getRoot(canvas);
return root instanceof Frame ? ((Frame)root).isActive() : true;
}
/** Called after {@link ApplicationListener} create and resize, but before the game loop iteration. */
protected void start () {
}
/** Called when the canvas size changes. */
protected void resize (int width, int height) {
}
/** Called when the game loop has stopped. */
protected void stopped () {
}
public void stop () {
if (!running) return;
running = false;
setGlobals();
Array<LifecycleListener> listeners = lifecycleListeners;
// To allow destroying of OpenGL textures during disposal.
if (canvas.isDisplayable()) {
makeCurrent();
} else {
error(logTag, "OpenGL context destroyed before application listener has had a chance to dispose of textures.");
}
synchronized (listeners) {
for (LifecycleListener listener : listeners) {
listener.pause();
listener.dispose();
}
}
listener.pause();
listener.dispose();
Gdx.app = null;
Gdx.graphics = null;
if (audio != null) {
audio.dispose();
Gdx.audio = null;
}
if (files != null) Gdx.files = null;
if (net != null) Gdx.net = null;
instanceCount--;
stopped();
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return getJavaHeap();
}
Map<String, Preferences> preferences = new HashMap<String, Preferences>();
@Override
public Preferences getPreferences (String name) {
if (preferences.containsKey(name)) {
return preferences.get(name);
} else {
Preferences prefs = new LwjglPreferences(name, ".prefs/");
preferences.put(name, prefs);
return prefs;
}
}
@Override
public Clipboard getClipboard () {
return new LwjglClipboard();
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
}
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message);
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message, exception);
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message);
}
@Override
public void log (String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
@Override
public int getLogLevel () {
return logLevel;
}
@Override
public void setApplicationLogger (ApplicationLogger applicationLogger) {
this.applicationLogger = applicationLogger;
}
@Override
public ApplicationLogger getApplicationLogger () {
return applicationLogger;
}
@Override
public void exit () {
postRunnable(new Runnable() {
@Override
public void run () {
stop();
System.exit(-1);
}
});
}
/** Make the canvas' context current. It is highly recommended that the context is only made current inside the AWT thread (for
* example in an overridden paintGL()). */
public void makeCurrent () {
try {
canvas.makeCurrent();
setGlobals();
} catch (Throwable ex) {
exception(ex);
}
}
/** Test whether the canvas' context is current. */
public boolean isCurrent () {
try {
return canvas.isCurrent();
} catch (Throwable ex) {
exception(ex);
return false;
}
}
/** @param cursor May be null. */
public void setCursor (Cursor cursor) {
this.cursor = cursor;
}
@Override
public void addLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
protected void exception (Throwable ex) {
ex.printStackTrace();
stop();
}
static public class NonSystemPaint extends PaintEvent {
public NonSystemPaint (AWTGLCanvas canvas) {
super(canvas, UPDATE, new Rectangle(0, 0, 99999, 99999));
}
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/org/jbox2d/dynamics/contacts/Position.java | /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* 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.
*
* 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 HOLDER 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.
******************************************************************************/
package org.jbox2d.dynamics.contacts;
import org.jbox2d.common.Vec2;
public class Position {
public final Vec2 c = new Vec2();
public float a;
}
| /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* 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.
*
* 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 HOLDER 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.
******************************************************************************/
package org.jbox2d.dynamics.contacts;
import org.jbox2d.common.Vec2;
public class Position {
public final Vec2 c = new Vec2();
public float a;
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./tests/gdx-tests/src/com/badlogic/gdx/tests/bench/TiledMapBench.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tests.bench;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapLayers;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.maps.tiled.tiles.StaticTiledMapTile;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.tests.utils.OrthoCamController;
import com.badlogic.gdx.utils.ScreenUtils;
public class TiledMapBench extends GdxTest {
private TiledMap map;
private TiledMapRenderer renderer;
private OrthographicCamera camera;
private OrthoCamController cameraController;
private AssetManager assetManager;
private Texture tiles;
private Texture texture;
private BitmapFont font;
private SpriteBatch batch;
@Override
public void create () {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera();
camera.setToOrtho(false, (w / h) * 320, 320);
camera.update();
cameraController = new OrthoCamController(camera);
Gdx.input.setInputProcessor(cameraController);
font = new BitmapFont();
batch = new SpriteBatch();
{
tiles = new Texture(Gdx.files.internal("data/maps/tiled/tiles.png"));
TextureRegion[][] splitTiles = TextureRegion.split(tiles, 32, 32);
map = new TiledMap();
MapLayers layers = map.getLayers();
for (int l = 0; l < 20; l++) {
TiledMapTileLayer layer = new TiledMapTileLayer(150, 100, 32, 32);
for (int x = 0; x < 150; x++) {
for (int y = 0; y < 100; y++) {
int ty = (int)(Math.random() * splitTiles.length);
int tx = (int)(Math.random() * splitTiles[ty].length);
Cell cell = new Cell();
cell.setTile(new StaticTiledMapTile(splitTiles[ty][tx]));
layer.setCell(x, y, cell);
}
}
layers.add(layer);
}
}
renderer = new OrthogonalTiledMapRenderer(map);
}
@Override
public void render () {
ScreenUtils.clear(100f / 255f, 100f / 255f, 250f / 255f, 1f);
camera.update();
renderer.setView(camera);
renderer.render();
batch.begin();
font.draw(batch, "FPS: " + Gdx.graphics.getFramesPerSecond(), 10, 20);
batch.end();
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tests.bench;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapLayers;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.maps.tiled.tiles.StaticTiledMapTile;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.tests.utils.OrthoCamController;
import com.badlogic.gdx.utils.ScreenUtils;
public class TiledMapBench extends GdxTest {
private TiledMap map;
private TiledMapRenderer renderer;
private OrthographicCamera camera;
private OrthoCamController cameraController;
private AssetManager assetManager;
private Texture tiles;
private Texture texture;
private BitmapFont font;
private SpriteBatch batch;
@Override
public void create () {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera();
camera.setToOrtho(false, (w / h) * 320, 320);
camera.update();
cameraController = new OrthoCamController(camera);
Gdx.input.setInputProcessor(cameraController);
font = new BitmapFont();
batch = new SpriteBatch();
{
tiles = new Texture(Gdx.files.internal("data/maps/tiled/tiles.png"));
TextureRegion[][] splitTiles = TextureRegion.split(tiles, 32, 32);
map = new TiledMap();
MapLayers layers = map.getLayers();
for (int l = 0; l < 20; l++) {
TiledMapTileLayer layer = new TiledMapTileLayer(150, 100, 32, 32);
for (int x = 0; x < 150; x++) {
for (int y = 0; y < 100; y++) {
int ty = (int)(Math.random() * splitTiles.length);
int tx = (int)(Math.random() * splitTiles[ty].length);
Cell cell = new Cell();
cell.setTile(new StaticTiledMapTile(splitTiles[ty][tx]));
layer.setCell(x, y, cell);
}
}
layers.add(layer);
}
}
renderer = new OrthogonalTiledMapRenderer(map);
}
@Override
public void render () {
ScreenUtils.clear(100f / 255f, 100f / 255f, 250f / 255f, 1f);
camera.update();
renderer.setView(camera);
renderer.render();
batch.begin();
font.draw(batch, "FPS: " + Gdx.graphics.getFramesPerSecond(), 10, 20);
batch.end();
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./gdx/src/com/badlogic/gdx/graphics/g3d/attributes/DirectionalLightsAttribute.java |
package com.badlogic.gdx.graphics.g3d.attributes;
import com.badlogic.gdx.graphics.g3d.Attribute;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.utils.Array;
/** An {@link Attribute} which can be used to send an {@link Array} of {@link DirectionalLight} instances to the {@link Shader}.
* The lights are stored by reference, the {@link #copy()} or {@link #DirectionalLightsAttribute(DirectionalLightsAttribute)}
* method will not create new lights.
* @author Xoppa */
public class DirectionalLightsAttribute extends Attribute {
public final static String Alias = "directionalLights";
public final static long Type = register(Alias);
public final static boolean is (final long mask) {
return (mask & Type) == mask;
}
public final Array<DirectionalLight> lights;
public DirectionalLightsAttribute () {
super(Type);
lights = new Array<DirectionalLight>(1);
}
public DirectionalLightsAttribute (final DirectionalLightsAttribute copyFrom) {
this();
lights.addAll(copyFrom.lights);
}
@Override
public DirectionalLightsAttribute copy () {
return new DirectionalLightsAttribute(this);
}
@Override
public int hashCode () {
int result = super.hashCode();
for (DirectionalLight light : lights)
result = 1229 * result + (light == null ? 0 : light.hashCode());
return result;
}
@Override
public int compareTo (Attribute o) {
if (type != o.type) return type < o.type ? -1 : 1;
return 0; // FIXME implement comparing
}
}
|
package com.badlogic.gdx.graphics.g3d.attributes;
import com.badlogic.gdx.graphics.g3d.Attribute;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.utils.Array;
/** An {@link Attribute} which can be used to send an {@link Array} of {@link DirectionalLight} instances to the {@link Shader}.
* The lights are stored by reference, the {@link #copy()} or {@link #DirectionalLightsAttribute(DirectionalLightsAttribute)}
* method will not create new lights.
* @author Xoppa */
public class DirectionalLightsAttribute extends Attribute {
public final static String Alias = "directionalLights";
public final static long Type = register(Alias);
public final static boolean is (final long mask) {
return (mask & Type) == mask;
}
public final Array<DirectionalLight> lights;
public DirectionalLightsAttribute () {
super(Type);
lights = new Array<DirectionalLight>(1);
}
public DirectionalLightsAttribute (final DirectionalLightsAttribute copyFrom) {
this();
lights.addAll(copyFrom.lights);
}
@Override
public DirectionalLightsAttribute copy () {
return new DirectionalLightsAttribute(this);
}
@Override
public int hashCode () {
int result = super.hashCode();
for (DirectionalLight light : lights)
result = 1229 * result + (light == null ? 0 : light.hashCode());
return result;
}
@Override
public int compareTo (Attribute o) {
if (type != o.type) return type < o.type ? -1 : 1;
return 0; // FIXME implement comparing
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/CustomCollisionDispatcher.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class CustomCollisionDispatcher extends btCollisionDispatcher {
private long swigCPtr;
protected CustomCollisionDispatcher (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.CustomCollisionDispatcher_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new CustomCollisionDispatcher, normally you should not need this constructor it's intended for low-level
* usage. */
public CustomCollisionDispatcher (long cPtr, boolean cMemoryOwn) {
this("CustomCollisionDispatcher", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.CustomCollisionDispatcher_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (CustomCollisionDispatcher obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_CustomCollisionDispatcher(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
protected void swigDirectorDisconnect () {
swigCMemOwn = false;
delete();
}
public void swigReleaseOwnership () {
swigCMemOwn = false;
CollisionJNI.CustomCollisionDispatcher_change_ownership(this, swigCPtr, false);
}
public void swigTakeOwnership () {
swigCMemOwn = true;
CollisionJNI.CustomCollisionDispatcher_change_ownership(this, swigCPtr, true);
}
public CustomCollisionDispatcher (btCollisionConfiguration collisionConfiguration) {
this(CollisionJNI.new_CustomCollisionDispatcher(btCollisionConfiguration.getCPtr(collisionConfiguration),
collisionConfiguration), true);
CollisionJNI.CustomCollisionDispatcher_director_connect(this, swigCPtr, swigCMemOwn, true);
}
public boolean needsCollision (btCollisionObject body0, btCollisionObject body1) {
return (getClass() == CustomCollisionDispatcher.class)
? CollisionJNI.CustomCollisionDispatcher_needsCollision(swigCPtr, this, btCollisionObject.getCPtr(body0), body0,
btCollisionObject.getCPtr(body1), body1)
: CollisionJNI.CustomCollisionDispatcher_needsCollisionSwigExplicitCustomCollisionDispatcher(swigCPtr, this,
btCollisionObject.getCPtr(body0), body0, btCollisionObject.getCPtr(body1), body1);
}
public boolean needsResponse (btCollisionObject body0, btCollisionObject body1) {
return (getClass() == CustomCollisionDispatcher.class)
? CollisionJNI.CustomCollisionDispatcher_needsResponse(swigCPtr, this, btCollisionObject.getCPtr(body0), body0,
btCollisionObject.getCPtr(body1), body1)
: CollisionJNI.CustomCollisionDispatcher_needsResponseSwigExplicitCustomCollisionDispatcher(swigCPtr, this,
btCollisionObject.getCPtr(body0), body0, btCollisionObject.getCPtr(body1), body1);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class CustomCollisionDispatcher extends btCollisionDispatcher {
private long swigCPtr;
protected CustomCollisionDispatcher (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.CustomCollisionDispatcher_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new CustomCollisionDispatcher, normally you should not need this constructor it's intended for low-level
* usage. */
public CustomCollisionDispatcher (long cPtr, boolean cMemoryOwn) {
this("CustomCollisionDispatcher", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.CustomCollisionDispatcher_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (CustomCollisionDispatcher obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_CustomCollisionDispatcher(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
protected void swigDirectorDisconnect () {
swigCMemOwn = false;
delete();
}
public void swigReleaseOwnership () {
swigCMemOwn = false;
CollisionJNI.CustomCollisionDispatcher_change_ownership(this, swigCPtr, false);
}
public void swigTakeOwnership () {
swigCMemOwn = true;
CollisionJNI.CustomCollisionDispatcher_change_ownership(this, swigCPtr, true);
}
public CustomCollisionDispatcher (btCollisionConfiguration collisionConfiguration) {
this(CollisionJNI.new_CustomCollisionDispatcher(btCollisionConfiguration.getCPtr(collisionConfiguration),
collisionConfiguration), true);
CollisionJNI.CustomCollisionDispatcher_director_connect(this, swigCPtr, swigCMemOwn, true);
}
public boolean needsCollision (btCollisionObject body0, btCollisionObject body1) {
return (getClass() == CustomCollisionDispatcher.class)
? CollisionJNI.CustomCollisionDispatcher_needsCollision(swigCPtr, this, btCollisionObject.getCPtr(body0), body0,
btCollisionObject.getCPtr(body1), body1)
: CollisionJNI.CustomCollisionDispatcher_needsCollisionSwigExplicitCustomCollisionDispatcher(swigCPtr, this,
btCollisionObject.getCPtr(body0), body0, btCollisionObject.getCPtr(body1), body1);
}
public boolean needsResponse (btCollisionObject body0, btCollisionObject body1) {
return (getClass() == CustomCollisionDispatcher.class)
? CollisionJNI.CustomCollisionDispatcher_needsResponse(swigCPtr, this, btCollisionObject.getCPtr(body0), body0,
btCollisionObject.getCPtr(body1), body1)
: CollisionJNI.CustomCollisionDispatcher_needsResponseSwigExplicitCustomCollisionDispatcher(swigCPtr, this,
btCollisionObject.getCPtr(body0), body0, btCollisionObject.getCPtr(body1), body1);
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./tests/gdx-tests/src/com/badlogic/gdx/tests/TextAreaTest.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextArea;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.ScreenUtils;
public class TextAreaTest extends GdxTest {
private Stage stage;
private Skin skin;
@Override
public void create () {
stage = new Stage();
Gdx.input.setInputProcessor(stage);
skin = new Skin(Gdx.files.internal("data/uiskin.json"));
TextArea textArea = new TextArea("Text Area\nEssentially, a text field\nwith\nmultiple\nlines.\n"
+ "It can even handle very loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong lines.",
skin);
textArea.setX(10);
textArea.setY(10);
textArea.setWidth(200);
textArea.setHeight(200);
TextField textField = new TextField("Text field", skin);
textField.setX(10);
textField.setY(220);
textField.setWidth(200);
textField.setHeight(30);
stage.addActor(textArea);
stage.addActor(textField);
Gdx.input.setCatchKey(Input.Keys.TAB, true);
}
@Override
public void render () {
ScreenUtils.clear(0.2f, 0.2f, 0.2f, 1);
stage.draw();
Gdx.app.log("X", "FPS: " + Gdx.graphics.getFramesPerSecond());
SpriteBatch spriteBatch = (SpriteBatch)stage.getBatch();
Gdx.app.log("X", "render calls: " + spriteBatch.totalRenderCalls);
spriteBatch.totalRenderCalls = 0;
}
@Override
public void resize (int width, int height) {
stage.getViewport().update(width, height, true);
}
@Override
public void dispose () {
stage.dispose();
skin.dispose();
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextArea;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.ScreenUtils;
public class TextAreaTest extends GdxTest {
private Stage stage;
private Skin skin;
@Override
public void create () {
stage = new Stage();
Gdx.input.setInputProcessor(stage);
skin = new Skin(Gdx.files.internal("data/uiskin.json"));
TextArea textArea = new TextArea("Text Area\nEssentially, a text field\nwith\nmultiple\nlines.\n"
+ "It can even handle very loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong lines.",
skin);
textArea.setX(10);
textArea.setY(10);
textArea.setWidth(200);
textArea.setHeight(200);
TextField textField = new TextField("Text field", skin);
textField.setX(10);
textField.setY(220);
textField.setWidth(200);
textField.setHeight(30);
stage.addActor(textArea);
stage.addActor(textField);
Gdx.input.setCatchKey(Input.Keys.TAB, true);
}
@Override
public void render () {
ScreenUtils.clear(0.2f, 0.2f, 0.2f, 1);
stage.draw();
Gdx.app.log("X", "FPS: " + Gdx.graphics.getFramesPerSecond());
SpriteBatch spriteBatch = (SpriteBatch)stage.getBatch();
Gdx.app.log("X", "render calls: " + spriteBatch.totalRenderCalls);
spriteBatch.totalRenderCalls = 0;
}
@Override
public void resize (int width, int height) {
stage.getViewport().update(width, height, true);
}
@Override
public void dispose () {
stage.dispose();
skin.dispose();
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/webaudio/AudioControlGraphPool.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.gwt.webaudio;
import com.badlogic.gdx.utils.Pool;
import com.google.gwt.core.client.JavaScriptObject;
public class AudioControlGraphPool extends Pool<AudioControlGraph> {
public JavaScriptObject audioContext;
public JavaScriptObject destinationNode;
public AudioControlGraphPool (JavaScriptObject audioContext, JavaScriptObject destinationNode) {
this.audioContext = audioContext;
this.destinationNode = destinationNode;
}
@Override
protected AudioControlGraph newObject () {
return new AudioControlGraph(audioContext, destinationNode);
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.gwt.webaudio;
import com.badlogic.gdx.utils.Pool;
import com.google.gwt.core.client.JavaScriptObject;
public class AudioControlGraphPool extends Pool<AudioControlGraph> {
public JavaScriptObject audioContext;
public JavaScriptObject destinationNode;
public AudioControlGraphPool (JavaScriptObject audioContext, JavaScriptObject destinationNode) {
this.audioContext = audioContext;
this.destinationNode = destinationNode;
}
@Override
protected AudioControlGraph newObject () {
return new AudioControlGraph(audioContext, destinationNode);
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./gdx/src/com/badlogic/gdx/graphics/Texture.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics;
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetLoaderParameters.LoadedCallback;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.AssetLoader;
import com.badlogic.gdx.assets.loaders.TextureLoader.TextureParameter;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.glutils.FileTextureData;
import com.badlogic.gdx.graphics.glutils.PixmapTextureData;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
/** A Texture wraps a standard OpenGL ES texture.
* <p>
* A Texture can be managed. If the OpenGL context is lost all managed textures get invalidated. This happens when a user switches
* to another application or receives an incoming call. Managed textures get reloaded automatically.
* <p>
* A Texture has to be bound via the {@link Texture#bind()} method in order for it to be applied to geometry. The texture will be
* bound to the currently active texture unit specified via {@link GL20#glActiveTexture(int)}.
* <p>
* You can draw {@link Pixmap}s to a texture at any time. The changes will be automatically uploaded to texture memory. This is of
* course not extremely fast so use it with care. It also only works with unmanaged textures.
* <p>
* A Texture must be disposed when it is no longer used
* @author [email protected] */
public class Texture extends GLTexture {
private static AssetManager assetManager;
final static Map<Application, Array<Texture>> managedTextures = new HashMap<Application, Array<Texture>>();
public enum TextureFilter {
/** Fetch the nearest texel that best maps to the pixel on screen. */
Nearest(GL20.GL_NEAREST),
/** Fetch four nearest texels that best maps to the pixel on screen. */
Linear(GL20.GL_LINEAR),
/** @see TextureFilter#MipMapLinearLinear */
MipMap(GL20.GL_LINEAR_MIPMAP_LINEAR),
/** Fetch the best fitting image from the mip map chain based on the pixel/texel ratio and then sample the texels with a
* nearest filter. */
MipMapNearestNearest(GL20.GL_NEAREST_MIPMAP_NEAREST),
/** Fetch the best fitting image from the mip map chain based on the pixel/texel ratio and then sample the texels with a
* linear filter. */
MipMapLinearNearest(GL20.GL_LINEAR_MIPMAP_NEAREST),
/** Fetch the two best fitting images from the mip map chain and then sample the nearest texel from each of the two images,
* combining them to the final output pixel. */
MipMapNearestLinear(GL20.GL_NEAREST_MIPMAP_LINEAR),
/** Fetch the two best fitting images from the mip map chain and then sample the four nearest texels from each of the two
* images, combining them to the final output pixel. */
MipMapLinearLinear(GL20.GL_LINEAR_MIPMAP_LINEAR);
final int glEnum;
TextureFilter (int glEnum) {
this.glEnum = glEnum;
}
public boolean isMipMap () {
return glEnum != GL20.GL_NEAREST && glEnum != GL20.GL_LINEAR;
}
public int getGLEnum () {
return glEnum;
}
}
public enum TextureWrap {
MirroredRepeat(GL20.GL_MIRRORED_REPEAT), ClampToEdge(GL20.GL_CLAMP_TO_EDGE), Repeat(GL20.GL_REPEAT);
final int glEnum;
TextureWrap (int glEnum) {
this.glEnum = glEnum;
}
public int getGLEnum () {
return glEnum;
}
}
TextureData data;
public Texture (String internalPath) {
this(Gdx.files.internal(internalPath));
}
public Texture (FileHandle file) {
this(file, null, false);
}
public Texture (FileHandle file, boolean useMipMaps) {
this(file, null, useMipMaps);
}
public Texture (FileHandle file, Format format, boolean useMipMaps) {
this(TextureData.Factory.loadFromFile(file, format, useMipMaps));
}
public Texture (Pixmap pixmap) {
this(new PixmapTextureData(pixmap, null, false, false));
}
public Texture (Pixmap pixmap, boolean useMipMaps) {
this(new PixmapTextureData(pixmap, null, useMipMaps, false));
}
public Texture (Pixmap pixmap, Format format, boolean useMipMaps) {
this(new PixmapTextureData(pixmap, format, useMipMaps, false));
}
public Texture (int width, int height, Format format) {
this(new PixmapTextureData(new Pixmap(width, height, format), null, false, true));
}
public Texture (TextureData data) {
this(GL20.GL_TEXTURE_2D, Gdx.gl.glGenTexture(), data);
}
protected Texture (int glTarget, int glHandle, TextureData data) {
super(glTarget, glHandle);
load(data);
if (data.isManaged()) addManagedTexture(Gdx.app, this);
}
public void load (TextureData data) {
if (this.data != null && data.isManaged() != this.data.isManaged())
throw new GdxRuntimeException("New data must have the same managed status as the old data");
this.data = data;
if (!data.isPrepared()) data.prepare();
bind();
uploadImageData(GL20.GL_TEXTURE_2D, data);
unsafeSetFilter(minFilter, magFilter, true);
unsafeSetWrap(uWrap, vWrap, true);
unsafeSetAnisotropicFilter(anisotropicFilterLevel, true);
Gdx.gl.glBindTexture(glTarget, 0);
}
/** Used internally to reload after context loss. Creates a new GL handle then calls {@link #load(TextureData)}. Use this only
* if you know what you do! */
@Override
protected void reload () {
if (!isManaged()) throw new GdxRuntimeException("Tried to reload unmanaged Texture");
glHandle = Gdx.gl.glGenTexture();
load(data);
}
/** Draws the given {@link Pixmap} to the texture at position x, y. No clipping is performed so you have to make sure that you
* draw only inside the texture region. Note that this will only draw to mipmap level 0!
*
* @param pixmap The Pixmap
* @param x The x coordinate in pixels
* @param y The y coordinate in pixels */
public void draw (Pixmap pixmap, int x, int y) {
if (data.isManaged()) throw new GdxRuntimeException("can't draw to a managed texture");
bind();
Gdx.gl.glTexSubImage2D(glTarget, 0, x, y, pixmap.getWidth(), pixmap.getHeight(), pixmap.getGLFormat(), pixmap.getGLType(),
pixmap.getPixels());
}
@Override
public int getWidth () {
return data.getWidth();
}
@Override
public int getHeight () {
return data.getHeight();
}
@Override
public int getDepth () {
return 0;
}
public TextureData getTextureData () {
return data;
}
/** @return whether this texture is managed or not. */
public boolean isManaged () {
return data.isManaged();
}
/** Disposes all resources associated with the texture */
public void dispose () {
// this is a hack. reason: we have to set the glHandle to 0 for textures that are
// reloaded through the asset manager as we first remove (and thus dispose) the texture
// and then reload it. the glHandle is set to 0 in invalidateAllTextures prior to
// removal from the asset manager.
if (glHandle == 0) return;
delete();
if (data.isManaged()) if (managedTextures.get(Gdx.app) != null) managedTextures.get(Gdx.app).removeValue(this, true);
}
public String toString () {
if (data instanceof FileTextureData) return data.toString();
return super.toString();
}
private static void addManagedTexture (Application app, Texture texture) {
Array<Texture> managedTextureArray = managedTextures.get(app);
if (managedTextureArray == null) managedTextureArray = new Array<Texture>();
managedTextureArray.add(texture);
managedTextures.put(app, managedTextureArray);
}
/** Clears all managed textures. This is an internal method. Do not use it! */
public static void clearAllTextures (Application app) {
managedTextures.remove(app);
}
/** Invalidate all managed textures. This is an internal method. Do not use it! */
public static void invalidateAllTextures (Application app) {
Array<Texture> managedTextureArray = managedTextures.get(app);
if (managedTextureArray == null) return;
if (assetManager == null) {
for (int i = 0; i < managedTextureArray.size; i++) {
Texture texture = managedTextureArray.get(i);
texture.reload();
}
} else {
// first we have to make sure the AssetManager isn't loading anything anymore,
// otherwise the ref counting trick below wouldn't work (when a texture is
// currently on the task stack of the manager.)
assetManager.finishLoading();
// next we go through each texture and reload either directly or via the
// asset manager.
Array<Texture> textures = new Array<Texture>(managedTextureArray);
for (Texture texture : textures) {
String fileName = assetManager.getAssetFileName(texture);
if (fileName == null) {
texture.reload();
} else {
// get the ref count of the texture, then set it to 0 so we
// can actually remove it from the assetmanager. Also set the
// handle to zero, otherwise we might accidentially dispose
// already reloaded textures.
final int refCount = assetManager.getReferenceCount(fileName);
assetManager.setReferenceCount(fileName, 0);
texture.glHandle = 0;
// create the parameters, passing the reference to the texture as
// well as a callback that sets the ref count.
TextureParameter params = new TextureParameter();
params.textureData = texture.getTextureData();
params.minFilter = texture.getMinFilter();
params.magFilter = texture.getMagFilter();
params.wrapU = texture.getUWrap();
params.wrapV = texture.getVWrap();
params.genMipMaps = texture.data.useMipMaps(); // not sure about this?
params.texture = texture; // special parameter which will ensure that the references stay the same.
params.loadedCallback = new LoadedCallback() {
@Override
public void finishedLoading (AssetManager assetManager, String fileName, Class type) {
assetManager.setReferenceCount(fileName, refCount);
}
};
// unload the texture, create a new gl handle then reload it.
assetManager.unload(fileName);
texture.glHandle = Gdx.gl.glGenTexture();
assetManager.load(fileName, Texture.class, params);
}
}
managedTextureArray.clear();
managedTextureArray.addAll(textures);
}
}
/** Sets the {@link AssetManager}. When the context is lost, textures managed by the asset manager are reloaded by the manager
* on a separate thread (provided that a suitable {@link AssetLoader} is registered with the manager). Textures not managed by
* the AssetManager are reloaded via the usual means on the rendering thread.
* @param manager the asset manager. */
public static void setAssetManager (AssetManager manager) {
Texture.assetManager = manager;
}
public static String getManagedStatus () {
StringBuilder builder = new StringBuilder();
builder.append("Managed textures/app: { ");
for (Application app : managedTextures.keySet()) {
builder.append(managedTextures.get(app).size);
builder.append(" ");
}
builder.append("}");
return builder.toString();
}
/** @return the number of managed textures currently loaded */
public static int getNumManagedTextures () {
return managedTextures.get(Gdx.app).size;
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics;
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetLoaderParameters.LoadedCallback;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.AssetLoader;
import com.badlogic.gdx.assets.loaders.TextureLoader.TextureParameter;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.glutils.FileTextureData;
import com.badlogic.gdx.graphics.glutils.PixmapTextureData;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
/** A Texture wraps a standard OpenGL ES texture.
* <p>
* A Texture can be managed. If the OpenGL context is lost all managed textures get invalidated. This happens when a user switches
* to another application or receives an incoming call. Managed textures get reloaded automatically.
* <p>
* A Texture has to be bound via the {@link Texture#bind()} method in order for it to be applied to geometry. The texture will be
* bound to the currently active texture unit specified via {@link GL20#glActiveTexture(int)}.
* <p>
* You can draw {@link Pixmap}s to a texture at any time. The changes will be automatically uploaded to texture memory. This is of
* course not extremely fast so use it with care. It also only works with unmanaged textures.
* <p>
* A Texture must be disposed when it is no longer used
* @author [email protected] */
public class Texture extends GLTexture {
private static AssetManager assetManager;
final static Map<Application, Array<Texture>> managedTextures = new HashMap<Application, Array<Texture>>();
public enum TextureFilter {
/** Fetch the nearest texel that best maps to the pixel on screen. */
Nearest(GL20.GL_NEAREST),
/** Fetch four nearest texels that best maps to the pixel on screen. */
Linear(GL20.GL_LINEAR),
/** @see TextureFilter#MipMapLinearLinear */
MipMap(GL20.GL_LINEAR_MIPMAP_LINEAR),
/** Fetch the best fitting image from the mip map chain based on the pixel/texel ratio and then sample the texels with a
* nearest filter. */
MipMapNearestNearest(GL20.GL_NEAREST_MIPMAP_NEAREST),
/** Fetch the best fitting image from the mip map chain based on the pixel/texel ratio and then sample the texels with a
* linear filter. */
MipMapLinearNearest(GL20.GL_LINEAR_MIPMAP_NEAREST),
/** Fetch the two best fitting images from the mip map chain and then sample the nearest texel from each of the two images,
* combining them to the final output pixel. */
MipMapNearestLinear(GL20.GL_NEAREST_MIPMAP_LINEAR),
/** Fetch the two best fitting images from the mip map chain and then sample the four nearest texels from each of the two
* images, combining them to the final output pixel. */
MipMapLinearLinear(GL20.GL_LINEAR_MIPMAP_LINEAR);
final int glEnum;
TextureFilter (int glEnum) {
this.glEnum = glEnum;
}
public boolean isMipMap () {
return glEnum != GL20.GL_NEAREST && glEnum != GL20.GL_LINEAR;
}
public int getGLEnum () {
return glEnum;
}
}
public enum TextureWrap {
MirroredRepeat(GL20.GL_MIRRORED_REPEAT), ClampToEdge(GL20.GL_CLAMP_TO_EDGE), Repeat(GL20.GL_REPEAT);
final int glEnum;
TextureWrap (int glEnum) {
this.glEnum = glEnum;
}
public int getGLEnum () {
return glEnum;
}
}
TextureData data;
public Texture (String internalPath) {
this(Gdx.files.internal(internalPath));
}
public Texture (FileHandle file) {
this(file, null, false);
}
public Texture (FileHandle file, boolean useMipMaps) {
this(file, null, useMipMaps);
}
public Texture (FileHandle file, Format format, boolean useMipMaps) {
this(TextureData.Factory.loadFromFile(file, format, useMipMaps));
}
public Texture (Pixmap pixmap) {
this(new PixmapTextureData(pixmap, null, false, false));
}
public Texture (Pixmap pixmap, boolean useMipMaps) {
this(new PixmapTextureData(pixmap, null, useMipMaps, false));
}
public Texture (Pixmap pixmap, Format format, boolean useMipMaps) {
this(new PixmapTextureData(pixmap, format, useMipMaps, false));
}
public Texture (int width, int height, Format format) {
this(new PixmapTextureData(new Pixmap(width, height, format), null, false, true));
}
public Texture (TextureData data) {
this(GL20.GL_TEXTURE_2D, Gdx.gl.glGenTexture(), data);
}
protected Texture (int glTarget, int glHandle, TextureData data) {
super(glTarget, glHandle);
load(data);
if (data.isManaged()) addManagedTexture(Gdx.app, this);
}
public void load (TextureData data) {
if (this.data != null && data.isManaged() != this.data.isManaged())
throw new GdxRuntimeException("New data must have the same managed status as the old data");
this.data = data;
if (!data.isPrepared()) data.prepare();
bind();
uploadImageData(GL20.GL_TEXTURE_2D, data);
unsafeSetFilter(minFilter, magFilter, true);
unsafeSetWrap(uWrap, vWrap, true);
unsafeSetAnisotropicFilter(anisotropicFilterLevel, true);
Gdx.gl.glBindTexture(glTarget, 0);
}
/** Used internally to reload after context loss. Creates a new GL handle then calls {@link #load(TextureData)}. Use this only
* if you know what you do! */
@Override
protected void reload () {
if (!isManaged()) throw new GdxRuntimeException("Tried to reload unmanaged Texture");
glHandle = Gdx.gl.glGenTexture();
load(data);
}
/** Draws the given {@link Pixmap} to the texture at position x, y. No clipping is performed so you have to make sure that you
* draw only inside the texture region. Note that this will only draw to mipmap level 0!
*
* @param pixmap The Pixmap
* @param x The x coordinate in pixels
* @param y The y coordinate in pixels */
public void draw (Pixmap pixmap, int x, int y) {
if (data.isManaged()) throw new GdxRuntimeException("can't draw to a managed texture");
bind();
Gdx.gl.glTexSubImage2D(glTarget, 0, x, y, pixmap.getWidth(), pixmap.getHeight(), pixmap.getGLFormat(), pixmap.getGLType(),
pixmap.getPixels());
}
@Override
public int getWidth () {
return data.getWidth();
}
@Override
public int getHeight () {
return data.getHeight();
}
@Override
public int getDepth () {
return 0;
}
public TextureData getTextureData () {
return data;
}
/** @return whether this texture is managed or not. */
public boolean isManaged () {
return data.isManaged();
}
/** Disposes all resources associated with the texture */
public void dispose () {
// this is a hack. reason: we have to set the glHandle to 0 for textures that are
// reloaded through the asset manager as we first remove (and thus dispose) the texture
// and then reload it. the glHandle is set to 0 in invalidateAllTextures prior to
// removal from the asset manager.
if (glHandle == 0) return;
delete();
if (data.isManaged()) if (managedTextures.get(Gdx.app) != null) managedTextures.get(Gdx.app).removeValue(this, true);
}
public String toString () {
if (data instanceof FileTextureData) return data.toString();
return super.toString();
}
private static void addManagedTexture (Application app, Texture texture) {
Array<Texture> managedTextureArray = managedTextures.get(app);
if (managedTextureArray == null) managedTextureArray = new Array<Texture>();
managedTextureArray.add(texture);
managedTextures.put(app, managedTextureArray);
}
/** Clears all managed textures. This is an internal method. Do not use it! */
public static void clearAllTextures (Application app) {
managedTextures.remove(app);
}
/** Invalidate all managed textures. This is an internal method. Do not use it! */
public static void invalidateAllTextures (Application app) {
Array<Texture> managedTextureArray = managedTextures.get(app);
if (managedTextureArray == null) return;
if (assetManager == null) {
for (int i = 0; i < managedTextureArray.size; i++) {
Texture texture = managedTextureArray.get(i);
texture.reload();
}
} else {
// first we have to make sure the AssetManager isn't loading anything anymore,
// otherwise the ref counting trick below wouldn't work (when a texture is
// currently on the task stack of the manager.)
assetManager.finishLoading();
// next we go through each texture and reload either directly or via the
// asset manager.
Array<Texture> textures = new Array<Texture>(managedTextureArray);
for (Texture texture : textures) {
String fileName = assetManager.getAssetFileName(texture);
if (fileName == null) {
texture.reload();
} else {
// get the ref count of the texture, then set it to 0 so we
// can actually remove it from the assetmanager. Also set the
// handle to zero, otherwise we might accidentially dispose
// already reloaded textures.
final int refCount = assetManager.getReferenceCount(fileName);
assetManager.setReferenceCount(fileName, 0);
texture.glHandle = 0;
// create the parameters, passing the reference to the texture as
// well as a callback that sets the ref count.
TextureParameter params = new TextureParameter();
params.textureData = texture.getTextureData();
params.minFilter = texture.getMinFilter();
params.magFilter = texture.getMagFilter();
params.wrapU = texture.getUWrap();
params.wrapV = texture.getVWrap();
params.genMipMaps = texture.data.useMipMaps(); // not sure about this?
params.texture = texture; // special parameter which will ensure that the references stay the same.
params.loadedCallback = new LoadedCallback() {
@Override
public void finishedLoading (AssetManager assetManager, String fileName, Class type) {
assetManager.setReferenceCount(fileName, refCount);
}
};
// unload the texture, create a new gl handle then reload it.
assetManager.unload(fileName);
texture.glHandle = Gdx.gl.glGenTexture();
assetManager.load(fileName, Texture.class, params);
}
}
managedTextureArray.clear();
managedTextureArray.addAll(textures);
}
}
/** Sets the {@link AssetManager}. When the context is lost, textures managed by the asset manager are reloaded by the manager
* on a separate thread (provided that a suitable {@link AssetLoader} is registered with the manager). Textures not managed by
* the AssetManager are reloaded via the usual means on the rendering thread.
* @param manager the asset manager. */
public static void setAssetManager (AssetManager manager) {
Texture.assetManager = manager;
}
public static String getManagedStatus () {
StringBuilder builder = new StringBuilder();
builder.append("Managed textures/app: { ");
for (Application app : managedTextures.keySet()) {
builder.append(managedTextures.get(app).size);
builder.append(" ");
}
builder.append("}");
return builder.toString();
}
/** @return the number of managed textures currently loaded */
public static int getNumManagedTextures () {
return managedTextures.get(Gdx.app).size;
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./extensions/gdx-bullet/jni/swig-src/dynamics/com/badlogic/gdx/physics/bullet/dynamics/btDantzigSolver.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.dynamics;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
public class btDantzigSolver extends btMLCPSolverInterface {
private long swigCPtr;
protected btDantzigSolver (final String className, long cPtr, boolean cMemoryOwn) {
super(className, DynamicsJNI.btDantzigSolver_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btDantzigSolver, normally you should not need this constructor it's intended for low-level usage. */
public btDantzigSolver (long cPtr, boolean cMemoryOwn) {
this("btDantzigSolver", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(DynamicsJNI.btDantzigSolver_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btDantzigSolver obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
DynamicsJNI.delete_btDantzigSolver(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public btDantzigSolver () {
this(DynamicsJNI.new_btDantzigSolver(), true);
}
public boolean solveMLCP (SWIGTYPE_p_btMatrixXT_float_t A, SWIGTYPE_p_btVectorXT_float_t b, SWIGTYPE_p_btVectorXT_float_t x,
SWIGTYPE_p_btVectorXT_float_t lo, SWIGTYPE_p_btVectorXT_float_t hi, SWIGTYPE_p_btAlignedObjectArrayT_int_t limitDependency,
int numIterations, boolean useSparsity) {
return DynamicsJNI.btDantzigSolver_solveMLCP__SWIG_0(swigCPtr, this, SWIGTYPE_p_btMatrixXT_float_t.getCPtr(A),
SWIGTYPE_p_btVectorXT_float_t.getCPtr(b), SWIGTYPE_p_btVectorXT_float_t.getCPtr(x),
SWIGTYPE_p_btVectorXT_float_t.getCPtr(lo), SWIGTYPE_p_btVectorXT_float_t.getCPtr(hi),
SWIGTYPE_p_btAlignedObjectArrayT_int_t.getCPtr(limitDependency), numIterations, useSparsity);
}
public boolean solveMLCP (SWIGTYPE_p_btMatrixXT_float_t A, SWIGTYPE_p_btVectorXT_float_t b, SWIGTYPE_p_btVectorXT_float_t x,
SWIGTYPE_p_btVectorXT_float_t lo, SWIGTYPE_p_btVectorXT_float_t hi, SWIGTYPE_p_btAlignedObjectArrayT_int_t limitDependency,
int numIterations) {
return DynamicsJNI.btDantzigSolver_solveMLCP__SWIG_1(swigCPtr, this, SWIGTYPE_p_btMatrixXT_float_t.getCPtr(A),
SWIGTYPE_p_btVectorXT_float_t.getCPtr(b), SWIGTYPE_p_btVectorXT_float_t.getCPtr(x),
SWIGTYPE_p_btVectorXT_float_t.getCPtr(lo), SWIGTYPE_p_btVectorXT_float_t.getCPtr(hi),
SWIGTYPE_p_btAlignedObjectArrayT_int_t.getCPtr(limitDependency), numIterations);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.dynamics;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
public class btDantzigSolver extends btMLCPSolverInterface {
private long swigCPtr;
protected btDantzigSolver (final String className, long cPtr, boolean cMemoryOwn) {
super(className, DynamicsJNI.btDantzigSolver_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btDantzigSolver, normally you should not need this constructor it's intended for low-level usage. */
public btDantzigSolver (long cPtr, boolean cMemoryOwn) {
this("btDantzigSolver", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(DynamicsJNI.btDantzigSolver_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btDantzigSolver obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
DynamicsJNI.delete_btDantzigSolver(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public btDantzigSolver () {
this(DynamicsJNI.new_btDantzigSolver(), true);
}
public boolean solveMLCP (SWIGTYPE_p_btMatrixXT_float_t A, SWIGTYPE_p_btVectorXT_float_t b, SWIGTYPE_p_btVectorXT_float_t x,
SWIGTYPE_p_btVectorXT_float_t lo, SWIGTYPE_p_btVectorXT_float_t hi, SWIGTYPE_p_btAlignedObjectArrayT_int_t limitDependency,
int numIterations, boolean useSparsity) {
return DynamicsJNI.btDantzigSolver_solveMLCP__SWIG_0(swigCPtr, this, SWIGTYPE_p_btMatrixXT_float_t.getCPtr(A),
SWIGTYPE_p_btVectorXT_float_t.getCPtr(b), SWIGTYPE_p_btVectorXT_float_t.getCPtr(x),
SWIGTYPE_p_btVectorXT_float_t.getCPtr(lo), SWIGTYPE_p_btVectorXT_float_t.getCPtr(hi),
SWIGTYPE_p_btAlignedObjectArrayT_int_t.getCPtr(limitDependency), numIterations, useSparsity);
}
public boolean solveMLCP (SWIGTYPE_p_btMatrixXT_float_t A, SWIGTYPE_p_btVectorXT_float_t b, SWIGTYPE_p_btVectorXT_float_t x,
SWIGTYPE_p_btVectorXT_float_t lo, SWIGTYPE_p_btVectorXT_float_t hi, SWIGTYPE_p_btAlignedObjectArrayT_int_t limitDependency,
int numIterations) {
return DynamicsJNI.btDantzigSolver_solveMLCP__SWIG_1(swigCPtr, this, SWIGTYPE_p_btMatrixXT_float_t.getCPtr(A),
SWIGTYPE_p_btVectorXT_float_t.getCPtr(b), SWIGTYPE_p_btVectorXT_float_t.getCPtr(x),
SWIGTYPE_p_btVectorXT_float_t.getCPtr(lo), SWIGTYPE_p_btVectorXT_float_t.getCPtr(hi),
SWIGTYPE_p_btAlignedObjectArrayT_int_t.getCPtr(limitDependency), numIterations);
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./gdx/src/com/badlogic/gdx/graphics/g3d/utils/AnimationController.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics.g3d.utils;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.model.Animation;
import com.badlogic.gdx.graphics.g3d.model.Node;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.Pool;
/** Class to control one or more {@link Animation}s on a {@link ModelInstance}. Use the
* {@link #setAnimation(String, int, float, AnimationListener)} method to change the current animation. Use the
* {@link #animate(String, int, float, AnimationListener, float)} method to start an animation, optionally blending onto the
* current animation. Use the {@link #queue(String, int, float, AnimationListener, float)} method to queue an animation to be
* played when the current animation is finished. Use the {@link #action(String, int, float, AnimationListener, float)} method to
* play a (short) animation on top of the current animation.
*
* You can use multiple AnimationControllers on the same ModelInstance, as long as they don't interfere with each other (don't
* affect the same {@link Node}s).
*
* @author Xoppa */
public class AnimationController extends BaseAnimationController {
/** Listener that will be informed when an animation is looped or completed.
* @author Xoppa */
public interface AnimationListener {
/** Gets called when an animation is completed.
* @param animation The animation which just completed. */
void onEnd (final AnimationDesc animation);
/** Gets called when an animation is looped. The {@link AnimationDesc#loopCount} is updated prior to this call and can be
* read or written to alter the number of remaining loops.
* @param animation The animation which just looped. */
void onLoop (final AnimationDesc animation);
}
/** Class describing how to play and {@link Animation}. You can read the values within this class to get the progress of the
* animation. Do not change the values. Only valid when the animation is currently played.
* @author Xoppa */
public static class AnimationDesc {
/** Listener which will be informed when the animation is looped or ended. */
public AnimationListener listener;
/** The animation to be applied. */
public Animation animation;
/** The speed at which to play the animation (can be negative), 1.0 for normal speed. */
public float speed;
/** The current animation time. */
public float time;
/** The offset within the animation (animation time = offsetTime + time) */
public float offset;
/** The duration of the animation */
public float duration;
/** The number of remaining loops, negative for continuous, zero if stopped. */
public int loopCount;
protected AnimationDesc () {
}
/** @param delta delta time, must be positive.
* @return the remaining time or -1 if still animating. */
protected float update (float delta) {
if (loopCount != 0 && animation != null) {
int loops;
final float diff = speed * delta;
if (!MathUtils.isZero(duration)) {
time += diff;
if (speed < 0) {
float invTime = duration - time;
loops = (int)Math.abs(invTime / duration);
invTime = Math.abs(invTime % duration);
time = duration - invTime;
} else {
loops = (int)Math.abs(time / duration);
time = Math.abs(time % duration);
}
} else
loops = 1;
for (int i = 0; i < loops; i++) {
if (loopCount > 0) loopCount--;
if (loopCount != 0 && listener != null) listener.onLoop(this);
if (loopCount == 0) {
final float result = ((loops - 1) - i) * duration + (diff < 0f ? duration - time : time);
time = (diff < 0f) ? 0f : duration;
if (listener != null) listener.onEnd(this);
return result;
}
}
return -1;
} else
return delta;
}
}
protected final Pool<AnimationDesc> animationPool = new Pool<AnimationDesc>() {
@Override
protected AnimationDesc newObject () {
return new AnimationDesc();
}
};
/** The animation currently playing. Do not alter this value. */
public AnimationDesc current;
/** The animation queued to be played when the {@link #current} animation is completed. Do not alter this value. */
public AnimationDesc queued;
/** The transition time which should be applied to the queued animation. Do not alter this value. */
public float queuedTransitionTime;
/** The animation which previously played. Do not alter this value. */
public AnimationDesc previous;
/** The current transition time. Do not alter this value. */
public float transitionCurrentTime;
/** The target transition time. Do not alter this value. */
public float transitionTargetTime;
/** Whether an action is being performed. Do not alter this value. */
public boolean inAction;
/** When true a call to {@link #update(float)} will not be processed. */
public boolean paused;
/** Whether to allow the same animation to be played while playing that animation. */
public boolean allowSameAnimation;
private boolean justChangedAnimation = false;
/** Construct a new AnimationController.
* @param target The {@link ModelInstance} on which the animations will be performed. */
public AnimationController (final ModelInstance target) {
super(target);
}
private AnimationDesc obtain (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
if (anim == null) return null;
final AnimationDesc result = animationPool.obtain();
result.animation = anim;
result.listener = listener;
result.loopCount = loopCount;
result.speed = speed;
result.offset = offset;
result.duration = duration < 0 ? (anim.duration - offset) : duration;
result.time = speed < 0 ? result.duration : 0.f;
return result;
}
private AnimationDesc obtain (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
if (id == null) return null;
final Animation anim = target.getAnimation(id);
if (anim == null) throw new GdxRuntimeException("Unknown animation: " + id);
return obtain(anim, offset, duration, loopCount, speed, listener);
}
private AnimationDesc obtain (final AnimationDesc anim) {
return obtain(anim.animation, anim.offset, anim.duration, anim.loopCount, anim.speed, anim.listener);
}
/** Update any animations currently being played.
* @param delta The time elapsed since last update, change this to alter the overall speed (can be negative). */
public void update (float delta) {
if (paused) return;
if (previous != null && ((transitionCurrentTime += delta) >= transitionTargetTime)) {
removeAnimation(previous.animation);
justChangedAnimation = true;
animationPool.free(previous);
previous = null;
}
if (justChangedAnimation) {
target.calculateTransforms();
justChangedAnimation = false;
}
if (current == null || current.loopCount == 0 || current.animation == null) return;
final float remain = current.update(delta);
if (remain >= 0f && queued != null) {
inAction = false;
animate(queued, queuedTransitionTime);
queued = null;
if (remain > 0f) update(remain);
return;
}
if (previous != null)
applyAnimations(previous.animation, previous.offset + previous.time, current.animation, current.offset + current.time,
transitionCurrentTime / transitionTargetTime);
else
applyAnimation(current.animation, current.offset + current.time);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id) {
return setAnimation(id, 1, 1.0f, null);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to loop the animation, zero to play the animation only once, negative to continuously
* loop the animation.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, int loopCount) {
return setAnimation(id, loopCount, 1.0f, null);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, final AnimationListener listener) {
return setAnimation(id, 1, 1.0f, listener);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, int loopCount, final AnimationListener listener) {
return setAnimation(id, loopCount, 1.0f, listener);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, int loopCount, float speed, final AnimationListener listener) {
return setAnimation(id, 0f, -1f, loopCount, speed, listener);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
return setAnimation(obtain(id, offset, duration, loopCount, speed, listener));
}
/** Set the active animation, replacing any current animation. */
protected AnimationDesc setAnimation (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
return setAnimation(obtain(anim, offset, duration, loopCount, speed, listener));
}
/** Set the active animation, replacing any current animation. */
protected AnimationDesc setAnimation (final AnimationDesc anim) {
if (current == null)
current = anim;
else {
if (!allowSameAnimation && anim != null && current.animation == anim.animation)
anim.time = current.time;
else
removeAnimation(current.animation);
animationPool.free(current);
current = anim;
}
justChangedAnimation = true;
return anim;
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, float transitionTime) {
return animate(id, 1, 1.0f, null, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, final AnimationListener listener, float transitionTime) {
return animate(id, 1, 1.0f, listener, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to loop the animation, zero to play the animation only once, negative to continuously
* loop the animation.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, int loopCount, final AnimationListener listener, float transitionTime) {
return animate(id, loopCount, 1.0f, listener, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, int loopCount, float speed, final AnimationListener listener,
float transitionTime) {
return animate(id, 0f, -1f, loopCount, speed, listener, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return animate(obtain(id, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time. */
protected AnimationDesc animate (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return animate(obtain(anim, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time. */
protected AnimationDesc animate (final AnimationDesc anim, float transitionTime) {
if (current == null || current.loopCount == 0)
current = anim;
else if (inAction)
queue(anim, transitionTime);
else if (!allowSameAnimation && anim != null && current.animation == anim.animation) {
anim.time = current.time;
animationPool.free(current);
current = anim;
} else {
if (previous != null) {
removeAnimation(previous.animation);
animationPool.free(previous);
}
previous = current;
current = anim;
transitionCurrentTime = 0f;
transitionTargetTime = transitionTime;
}
return anim;
}
/** Queue an animation to be applied when the {@link #current} animation is finished. If the current animation is continuously
* looping it will be synchronized on next loop.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc queue (final String id, int loopCount, float speed, final AnimationListener listener,
float transitionTime) {
return queue(id, 0f, -1f, loopCount, speed, listener, transitionTime);
}
/** Queue an animation to be applied when the {@link #current} animation is finished. If the current animation is continuously
* looping it will be synchronized on next loop.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc queue (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return queue(obtain(id, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Queue an animation to be applied when the current is finished. If current is continuous it will be synced on next loop. */
protected AnimationDesc queue (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return queue(obtain(anim, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Queue an animation to be applied when the current is finished. If current is continuous it will be synced on next loop. */
protected AnimationDesc queue (final AnimationDesc anim, float transitionTime) {
if (current == null || current.loopCount == 0)
animate(anim, transitionTime);
else {
if (queued != null) animationPool.free(queued);
queued = anim;
queuedTransitionTime = transitionTime;
if (current.loopCount < 0) current.loopCount = 1;
}
return anim;
}
/** Apply an action animation on top of the current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc action (final String id, int loopCount, float speed, final AnimationListener listener,
float transitionTime) {
return action(id, 0, -1f, loopCount, speed, listener, transitionTime);
}
/** Apply an action animation on top of the current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc action (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return action(obtain(id, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Apply an action animation on top of the current animation. */
protected AnimationDesc action (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return action(obtain(anim, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Apply an action animation on top of the current animation. */
protected AnimationDesc action (final AnimationDesc anim, float transitionTime) {
if (anim.loopCount < 0) throw new GdxRuntimeException("An action cannot be continuous");
if (current == null || current.loopCount == 0)
animate(anim, transitionTime);
else {
AnimationDesc toQueue = inAction ? null : obtain(current);
inAction = false;
animate(anim, transitionTime);
inAction = true;
if (toQueue != null) queue(toQueue, transitionTime);
}
return anim;
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics.g3d.utils;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.model.Animation;
import com.badlogic.gdx.graphics.g3d.model.Node;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.Pool;
/** Class to control one or more {@link Animation}s on a {@link ModelInstance}. Use the
* {@link #setAnimation(String, int, float, AnimationListener)} method to change the current animation. Use the
* {@link #animate(String, int, float, AnimationListener, float)} method to start an animation, optionally blending onto the
* current animation. Use the {@link #queue(String, int, float, AnimationListener, float)} method to queue an animation to be
* played when the current animation is finished. Use the {@link #action(String, int, float, AnimationListener, float)} method to
* play a (short) animation on top of the current animation.
*
* You can use multiple AnimationControllers on the same ModelInstance, as long as they don't interfere with each other (don't
* affect the same {@link Node}s).
*
* @author Xoppa */
public class AnimationController extends BaseAnimationController {
/** Listener that will be informed when an animation is looped or completed.
* @author Xoppa */
public interface AnimationListener {
/** Gets called when an animation is completed.
* @param animation The animation which just completed. */
void onEnd (final AnimationDesc animation);
/** Gets called when an animation is looped. The {@link AnimationDesc#loopCount} is updated prior to this call and can be
* read or written to alter the number of remaining loops.
* @param animation The animation which just looped. */
void onLoop (final AnimationDesc animation);
}
/** Class describing how to play and {@link Animation}. You can read the values within this class to get the progress of the
* animation. Do not change the values. Only valid when the animation is currently played.
* @author Xoppa */
public static class AnimationDesc {
/** Listener which will be informed when the animation is looped or ended. */
public AnimationListener listener;
/** The animation to be applied. */
public Animation animation;
/** The speed at which to play the animation (can be negative), 1.0 for normal speed. */
public float speed;
/** The current animation time. */
public float time;
/** The offset within the animation (animation time = offsetTime + time) */
public float offset;
/** The duration of the animation */
public float duration;
/** The number of remaining loops, negative for continuous, zero if stopped. */
public int loopCount;
protected AnimationDesc () {
}
/** @param delta delta time, must be positive.
* @return the remaining time or -1 if still animating. */
protected float update (float delta) {
if (loopCount != 0 && animation != null) {
int loops;
final float diff = speed * delta;
if (!MathUtils.isZero(duration)) {
time += diff;
if (speed < 0) {
float invTime = duration - time;
loops = (int)Math.abs(invTime / duration);
invTime = Math.abs(invTime % duration);
time = duration - invTime;
} else {
loops = (int)Math.abs(time / duration);
time = Math.abs(time % duration);
}
} else
loops = 1;
for (int i = 0; i < loops; i++) {
if (loopCount > 0) loopCount--;
if (loopCount != 0 && listener != null) listener.onLoop(this);
if (loopCount == 0) {
final float result = ((loops - 1) - i) * duration + (diff < 0f ? duration - time : time);
time = (diff < 0f) ? 0f : duration;
if (listener != null) listener.onEnd(this);
return result;
}
}
return -1;
} else
return delta;
}
}
protected final Pool<AnimationDesc> animationPool = new Pool<AnimationDesc>() {
@Override
protected AnimationDesc newObject () {
return new AnimationDesc();
}
};
/** The animation currently playing. Do not alter this value. */
public AnimationDesc current;
/** The animation queued to be played when the {@link #current} animation is completed. Do not alter this value. */
public AnimationDesc queued;
/** The transition time which should be applied to the queued animation. Do not alter this value. */
public float queuedTransitionTime;
/** The animation which previously played. Do not alter this value. */
public AnimationDesc previous;
/** The current transition time. Do not alter this value. */
public float transitionCurrentTime;
/** The target transition time. Do not alter this value. */
public float transitionTargetTime;
/** Whether an action is being performed. Do not alter this value. */
public boolean inAction;
/** When true a call to {@link #update(float)} will not be processed. */
public boolean paused;
/** Whether to allow the same animation to be played while playing that animation. */
public boolean allowSameAnimation;
private boolean justChangedAnimation = false;
/** Construct a new AnimationController.
* @param target The {@link ModelInstance} on which the animations will be performed. */
public AnimationController (final ModelInstance target) {
super(target);
}
private AnimationDesc obtain (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
if (anim == null) return null;
final AnimationDesc result = animationPool.obtain();
result.animation = anim;
result.listener = listener;
result.loopCount = loopCount;
result.speed = speed;
result.offset = offset;
result.duration = duration < 0 ? (anim.duration - offset) : duration;
result.time = speed < 0 ? result.duration : 0.f;
return result;
}
private AnimationDesc obtain (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
if (id == null) return null;
final Animation anim = target.getAnimation(id);
if (anim == null) throw new GdxRuntimeException("Unknown animation: " + id);
return obtain(anim, offset, duration, loopCount, speed, listener);
}
private AnimationDesc obtain (final AnimationDesc anim) {
return obtain(anim.animation, anim.offset, anim.duration, anim.loopCount, anim.speed, anim.listener);
}
/** Update any animations currently being played.
* @param delta The time elapsed since last update, change this to alter the overall speed (can be negative). */
public void update (float delta) {
if (paused) return;
if (previous != null && ((transitionCurrentTime += delta) >= transitionTargetTime)) {
removeAnimation(previous.animation);
justChangedAnimation = true;
animationPool.free(previous);
previous = null;
}
if (justChangedAnimation) {
target.calculateTransforms();
justChangedAnimation = false;
}
if (current == null || current.loopCount == 0 || current.animation == null) return;
final float remain = current.update(delta);
if (remain >= 0f && queued != null) {
inAction = false;
animate(queued, queuedTransitionTime);
queued = null;
if (remain > 0f) update(remain);
return;
}
if (previous != null)
applyAnimations(previous.animation, previous.offset + previous.time, current.animation, current.offset + current.time,
transitionCurrentTime / transitionTargetTime);
else
applyAnimation(current.animation, current.offset + current.time);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id) {
return setAnimation(id, 1, 1.0f, null);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to loop the animation, zero to play the animation only once, negative to continuously
* loop the animation.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, int loopCount) {
return setAnimation(id, loopCount, 1.0f, null);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, final AnimationListener listener) {
return setAnimation(id, 1, 1.0f, listener);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, int loopCount, final AnimationListener listener) {
return setAnimation(id, loopCount, 1.0f, listener);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, int loopCount, float speed, final AnimationListener listener) {
return setAnimation(id, 0f, -1f, loopCount, speed, listener);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
return setAnimation(obtain(id, offset, duration, loopCount, speed, listener));
}
/** Set the active animation, replacing any current animation. */
protected AnimationDesc setAnimation (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
return setAnimation(obtain(anim, offset, duration, loopCount, speed, listener));
}
/** Set the active animation, replacing any current animation. */
protected AnimationDesc setAnimation (final AnimationDesc anim) {
if (current == null)
current = anim;
else {
if (!allowSameAnimation && anim != null && current.animation == anim.animation)
anim.time = current.time;
else
removeAnimation(current.animation);
animationPool.free(current);
current = anim;
}
justChangedAnimation = true;
return anim;
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, float transitionTime) {
return animate(id, 1, 1.0f, null, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, final AnimationListener listener, float transitionTime) {
return animate(id, 1, 1.0f, listener, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to loop the animation, zero to play the animation only once, negative to continuously
* loop the animation.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, int loopCount, final AnimationListener listener, float transitionTime) {
return animate(id, loopCount, 1.0f, listener, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, int loopCount, float speed, final AnimationListener listener,
float transitionTime) {
return animate(id, 0f, -1f, loopCount, speed, listener, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return animate(obtain(id, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time. */
protected AnimationDesc animate (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return animate(obtain(anim, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time. */
protected AnimationDesc animate (final AnimationDesc anim, float transitionTime) {
if (current == null || current.loopCount == 0)
current = anim;
else if (inAction)
queue(anim, transitionTime);
else if (!allowSameAnimation && anim != null && current.animation == anim.animation) {
anim.time = current.time;
animationPool.free(current);
current = anim;
} else {
if (previous != null) {
removeAnimation(previous.animation);
animationPool.free(previous);
}
previous = current;
current = anim;
transitionCurrentTime = 0f;
transitionTargetTime = transitionTime;
}
return anim;
}
/** Queue an animation to be applied when the {@link #current} animation is finished. If the current animation is continuously
* looping it will be synchronized on next loop.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc queue (final String id, int loopCount, float speed, final AnimationListener listener,
float transitionTime) {
return queue(id, 0f, -1f, loopCount, speed, listener, transitionTime);
}
/** Queue an animation to be applied when the {@link #current} animation is finished. If the current animation is continuously
* looping it will be synchronized on next loop.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc queue (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return queue(obtain(id, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Queue an animation to be applied when the current is finished. If current is continuous it will be synced on next loop. */
protected AnimationDesc queue (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return queue(obtain(anim, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Queue an animation to be applied when the current is finished. If current is continuous it will be synced on next loop. */
protected AnimationDesc queue (final AnimationDesc anim, float transitionTime) {
if (current == null || current.loopCount == 0)
animate(anim, transitionTime);
else {
if (queued != null) animationPool.free(queued);
queued = anim;
queuedTransitionTime = transitionTime;
if (current.loopCount < 0) current.loopCount = 1;
}
return anim;
}
/** Apply an action animation on top of the current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc action (final String id, int loopCount, float speed, final AnimationListener listener,
float transitionTime) {
return action(id, 0, -1f, loopCount, speed, listener, transitionTime);
}
/** Apply an action animation on top of the current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc action (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return action(obtain(id, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Apply an action animation on top of the current animation. */
protected AnimationDesc action (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return action(obtain(anim, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Apply an action animation on top of the current animation. */
protected AnimationDesc action (final AnimationDesc anim, float transitionTime) {
if (anim.loopCount < 0) throw new GdxRuntimeException("An action cannot be continuous");
if (current == null || current.loopCount == 0)
animate(anim, transitionTime);
else {
AnimationDesc toQueue = inAction ? null : obtain(current);
inAction = false;
animate(anim, transitionTime);
inAction = true;
if (toQueue != null) queue(toQueue, transitionTime);
}
return anim;
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/files/FileHandle.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.files;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import com.badlogic.gdx.Files.FileType;
import com.badlogic.gdx.utils.GdxRuntimeException;
public class FileHandle {
protected File file;
protected FileType type;
protected FileHandle () {
}
public FileHandle (String fileName) {
}
public FileHandle (File file) {
}
protected FileHandle (String fileName, FileType type) {
}
protected FileHandle (File file, FileType type) {
}
public String path () {
throw new GdxRuntimeException("Stub");
}
public String name () {
throw new GdxRuntimeException("Stub");
}
public String extension () {
throw new GdxRuntimeException("Stub");
}
public String nameWithoutExtension () {
throw new GdxRuntimeException("Stub");
}
/** @return the path and filename without the extension, e.g. dir/dir2/file.png -> dir/dir2/file */
public String pathWithoutExtension () {
throw new GdxRuntimeException("Stub");
}
public FileType type () {
throw new GdxRuntimeException("Stub");
}
/** Returns a stream for reading this file as bytes.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public InputStream read () {
throw new GdxRuntimeException("Stub");
}
/** Returns a buffered stream for reading this file as bytes.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public BufferedInputStream read (int bufferSize) {
throw new GdxRuntimeException("Stub");
}
/** Returns a reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public Reader reader () {
throw new GdxRuntimeException("Stub");
}
/** Returns a reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public Reader reader (String charset) {
throw new GdxRuntimeException("Stub");
}
/** Returns a buffered reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public BufferedReader reader (int bufferSize) {
throw new GdxRuntimeException("Stub");
}
/** Returns a buffered reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public BufferedReader reader (int bufferSize, String charset) {
throw new GdxRuntimeException("Stub");
}
/** Reads the entire file into a string using the platform's default charset.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public String readString () {
throw new GdxRuntimeException("Stub");
}
/** Reads the entire file into a string using the specified charset.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public String readString (String charset) {
throw new GdxRuntimeException("Stub");
}
/** Reads the entire file into a byte array.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public byte[] readBytes () {
throw new GdxRuntimeException("Stub");
}
/** Reads the entire file into the byte array. The byte array must be big enough to hold the file's data.
* @param bytes the array to load the file into
* @param offset the offset to start writing bytes
* @param size the number of bytes to read, see {@link #length()}
* @return the number of read bytes */
public int readBytes (byte[] bytes, int offset, int size) {
throw new GdxRuntimeException("Stub");
}
/** Attempts to memory map this file in READ_ONLY mode. Android files must not be compressed.
* @throws GdxRuntimeException if this file handle represents a directory, doesn't exist, or could not be read, or memory
* mapping fails, or is a {@link FileType#Classpath} file. */
public ByteBuffer map () {
throw new GdxRuntimeException("Stub");
}
/** Attempts to memory map this file. Android files must not be compressed.
* @throws GdxRuntimeException if this file handle represents a directory, doesn't exist, or could not be read, or memory
* mapping fails, or is a {@link FileType#Classpath} file. */
public ByteBuffer map (FileChannel.MapMode mode) {
throw new GdxRuntimeException("Stub");
}
/** Returns a stream for writing to this file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public OutputStream write (boolean append) {
throw new GdxRuntimeException("Stub");
}
/** Returns a buffered stream for writing to this file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @param bufferSize The size of the buffer.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public OutputStream write (boolean append, int bufferSize) {
throw new GdxRuntimeException("Stub");
}
/** Reads the remaining bytes from the specified stream and writes them to this file. The stream is closed. Parent directories
* will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void write (InputStream input, boolean append) {
throw new GdxRuntimeException("Stub");
}
/** Returns a writer for writing to this file using the default charset. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public Writer writer (boolean append) {
throw new GdxRuntimeException("Stub");
}
/** Returns a writer for writing to this file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @param charset May be null to use the default charset.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public Writer writer (boolean append, String charset) {
throw new GdxRuntimeException("Stub");
}
/** Writes the specified string to the file using the default charset. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeString (String string, boolean append) {
throw new GdxRuntimeException("Stub");
}
/** Writes the specified string to the file as UTF-8. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @param charset May be null to use the default charset.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeString (String string, boolean append, String charset) {
throw new GdxRuntimeException("Stub");
}
/** Writes the specified bytes to the file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeBytes (byte[] bytes, boolean append) {
throw new GdxRuntimeException("Stub");
}
/** Writes the specified bytes to the file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeBytes (byte[] bytes, int offset, int length, boolean append) {
throw new GdxRuntimeException("Stub");
}
/** Returns the paths to the children of this directory that satisfy the specified filter. Returns an empty list if this file
* handle represents a file and not a directory. On the desktop, an {@link FileType#Internal} handle to a directory on the
* classpath will return a zero length array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list (FileFilter filter) {
throw new GdxRuntimeException("Stub");
}
/** Returns the paths to the children of this directory that satisfy the specified filter. Returns an empty list if this file
* handle represents a file and not a directory. On the desktop, an {@link FileType#Internal} handle to a directory on the
* classpath will return a zero length array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list (FilenameFilter filter) {
throw new GdxRuntimeException("Stub");
}
/** Returns the paths to the children of this directory. Returns an empty list if this file handle represents a file and not a
* directory. On the desktop, an {@link FileType#Internal} handle to a directory on the classpath will return a zero length
* array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list () {
throw new GdxRuntimeException("Stub");
}
/** Returns the paths to the children of this directory with the specified suffix. Returns an empty list if this file handle
* represents a file and not a directory. On the desktop, an {@link FileType#Internal} handle to a directory on the classpath
* will return a zero length array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list (String suffix) {
throw new GdxRuntimeException("Stub");
}
/** Returns true if this file is a directory. Always returns false for classpath files. On Android, an
* {@link FileType#Internal} handle to an empty directory will return false. On the desktop, an {@link FileType#Internal}
* handle to a directory on the classpath will return false. */
public boolean isDirectory () {
throw new GdxRuntimeException("Stub");
}
/** Returns a handle to the child with the specified name.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} and the child
* doesn't exist. */
public FileHandle child (String name) {
throw new GdxRuntimeException("Stub");
}
public FileHandle parent () {
throw new GdxRuntimeException("Stub");
}
/** Returns a handle to the sibling with the specified name.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} and the sibling
* doesn't exist, or this file is the root. */
public FileHandle sibling (String name) {
throw new GdxRuntimeException("Stub");
}
/** @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public void mkdirs () {
throw new GdxRuntimeException("Stub");
}
/** Returns true if the file exists. On Android, a {@link FileType#Classpath} or {@link FileType#Internal} handle to a
* directory will always return false. */
public boolean exists () {
throw new GdxRuntimeException("Stub");
}
/** Deletes this file or empty directory and returns success. Will not delete a directory that has children.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public boolean delete () {
throw new GdxRuntimeException("Stub");
}
/** Deletes this file or directory and all children, recursively.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public boolean deleteDirectory () {
throw new GdxRuntimeException("Stub");
}
/** Deletes all children of this directory, recursively.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public void emptyDirectory () {
throw new GdxRuntimeException("Not available on GWT");
}
/** Deletes all children of this directory, recursively. Optionally preserving the folder structure.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public void emptyDirectory (boolean preserveTree) {
throw new GdxRuntimeException("Not available on GWT");
}
/** Copies this file or directory to the specified file or directory. If this handle is a file, then 1) if the destination is a
* file, it is overwritten, or 2) if the destination is a directory, this file is copied into it, or 3) if the destination
* doesn't exist, {@link #mkdirs()} is called on the destination's parent and this file is copied into it with a new name. If
* this handle is a directory, then 1) if the destination is a file, GdxRuntimeException is thrown, or 2) if the destination is
* a directory, this directory is copied into it recursively, overwriting existing files, or 3) if the destination doesn't
* exist, {@link #mkdirs()} is called on the destination and this directory is copied into it recursively.
* @throws GdxRuntimeException if the destination file handle is a {@link FileType#Classpath} or {@link FileType#Internal}
* file, or copying failed. */
public void copyTo (FileHandle dest) {
throw new GdxRuntimeException("Stub");
}
/** Moves this file to the specified file, overwriting the file if it already exists.
* @throws GdxRuntimeException if the source or destination file handle is a {@link FileType#Classpath} or
* {@link FileType#Internal} file. */
public void moveTo (FileHandle dest) {
throw new GdxRuntimeException("Stub");
}
/** Returns the length in bytes of this file, or 0 if this file is a directory, does not exist, or the size cannot otherwise be
* determined. */
public long length () {
throw new GdxRuntimeException("Stub");
}
/** Returns the last modified time in milliseconds for this file. Zero is returned if the file doesn't exist. Zero is returned
* for {@link FileType#Classpath} files. On Android, zero is returned for {@link FileType#Internal} files. On the desktop, zero
* is returned for {@link FileType#Internal} files on the classpath. */
public long lastModified () {
throw new GdxRuntimeException("Stub");
}
public String toString () {
throw new GdxRuntimeException("Stub");
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.files;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import com.badlogic.gdx.Files.FileType;
import com.badlogic.gdx.utils.GdxRuntimeException;
public class FileHandle {
protected File file;
protected FileType type;
protected FileHandle () {
}
public FileHandle (String fileName) {
}
public FileHandle (File file) {
}
protected FileHandle (String fileName, FileType type) {
}
protected FileHandle (File file, FileType type) {
}
public String path () {
throw new GdxRuntimeException("Stub");
}
public String name () {
throw new GdxRuntimeException("Stub");
}
public String extension () {
throw new GdxRuntimeException("Stub");
}
public String nameWithoutExtension () {
throw new GdxRuntimeException("Stub");
}
/** @return the path and filename without the extension, e.g. dir/dir2/file.png -> dir/dir2/file */
public String pathWithoutExtension () {
throw new GdxRuntimeException("Stub");
}
public FileType type () {
throw new GdxRuntimeException("Stub");
}
/** Returns a stream for reading this file as bytes.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public InputStream read () {
throw new GdxRuntimeException("Stub");
}
/** Returns a buffered stream for reading this file as bytes.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public BufferedInputStream read (int bufferSize) {
throw new GdxRuntimeException("Stub");
}
/** Returns a reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public Reader reader () {
throw new GdxRuntimeException("Stub");
}
/** Returns a reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public Reader reader (String charset) {
throw new GdxRuntimeException("Stub");
}
/** Returns a buffered reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public BufferedReader reader (int bufferSize) {
throw new GdxRuntimeException("Stub");
}
/** Returns a buffered reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public BufferedReader reader (int bufferSize, String charset) {
throw new GdxRuntimeException("Stub");
}
/** Reads the entire file into a string using the platform's default charset.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public String readString () {
throw new GdxRuntimeException("Stub");
}
/** Reads the entire file into a string using the specified charset.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public String readString (String charset) {
throw new GdxRuntimeException("Stub");
}
/** Reads the entire file into a byte array.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public byte[] readBytes () {
throw new GdxRuntimeException("Stub");
}
/** Reads the entire file into the byte array. The byte array must be big enough to hold the file's data.
* @param bytes the array to load the file into
* @param offset the offset to start writing bytes
* @param size the number of bytes to read, see {@link #length()}
* @return the number of read bytes */
public int readBytes (byte[] bytes, int offset, int size) {
throw new GdxRuntimeException("Stub");
}
/** Attempts to memory map this file in READ_ONLY mode. Android files must not be compressed.
* @throws GdxRuntimeException if this file handle represents a directory, doesn't exist, or could not be read, or memory
* mapping fails, or is a {@link FileType#Classpath} file. */
public ByteBuffer map () {
throw new GdxRuntimeException("Stub");
}
/** Attempts to memory map this file. Android files must not be compressed.
* @throws GdxRuntimeException if this file handle represents a directory, doesn't exist, or could not be read, or memory
* mapping fails, or is a {@link FileType#Classpath} file. */
public ByteBuffer map (FileChannel.MapMode mode) {
throw new GdxRuntimeException("Stub");
}
/** Returns a stream for writing to this file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public OutputStream write (boolean append) {
throw new GdxRuntimeException("Stub");
}
/** Returns a buffered stream for writing to this file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @param bufferSize The size of the buffer.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public OutputStream write (boolean append, int bufferSize) {
throw new GdxRuntimeException("Stub");
}
/** Reads the remaining bytes from the specified stream and writes them to this file. The stream is closed. Parent directories
* will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void write (InputStream input, boolean append) {
throw new GdxRuntimeException("Stub");
}
/** Returns a writer for writing to this file using the default charset. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public Writer writer (boolean append) {
throw new GdxRuntimeException("Stub");
}
/** Returns a writer for writing to this file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @param charset May be null to use the default charset.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public Writer writer (boolean append, String charset) {
throw new GdxRuntimeException("Stub");
}
/** Writes the specified string to the file using the default charset. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeString (String string, boolean append) {
throw new GdxRuntimeException("Stub");
}
/** Writes the specified string to the file as UTF-8. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @param charset May be null to use the default charset.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeString (String string, boolean append, String charset) {
throw new GdxRuntimeException("Stub");
}
/** Writes the specified bytes to the file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeBytes (byte[] bytes, boolean append) {
throw new GdxRuntimeException("Stub");
}
/** Writes the specified bytes to the file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeBytes (byte[] bytes, int offset, int length, boolean append) {
throw new GdxRuntimeException("Stub");
}
/** Returns the paths to the children of this directory that satisfy the specified filter. Returns an empty list if this file
* handle represents a file and not a directory. On the desktop, an {@link FileType#Internal} handle to a directory on the
* classpath will return a zero length array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list (FileFilter filter) {
throw new GdxRuntimeException("Stub");
}
/** Returns the paths to the children of this directory that satisfy the specified filter. Returns an empty list if this file
* handle represents a file and not a directory. On the desktop, an {@link FileType#Internal} handle to a directory on the
* classpath will return a zero length array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list (FilenameFilter filter) {
throw new GdxRuntimeException("Stub");
}
/** Returns the paths to the children of this directory. Returns an empty list if this file handle represents a file and not a
* directory. On the desktop, an {@link FileType#Internal} handle to a directory on the classpath will return a zero length
* array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list () {
throw new GdxRuntimeException("Stub");
}
/** Returns the paths to the children of this directory with the specified suffix. Returns an empty list if this file handle
* represents a file and not a directory. On the desktop, an {@link FileType#Internal} handle to a directory on the classpath
* will return a zero length array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list (String suffix) {
throw new GdxRuntimeException("Stub");
}
/** Returns true if this file is a directory. Always returns false for classpath files. On Android, an
* {@link FileType#Internal} handle to an empty directory will return false. On the desktop, an {@link FileType#Internal}
* handle to a directory on the classpath will return false. */
public boolean isDirectory () {
throw new GdxRuntimeException("Stub");
}
/** Returns a handle to the child with the specified name.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} and the child
* doesn't exist. */
public FileHandle child (String name) {
throw new GdxRuntimeException("Stub");
}
public FileHandle parent () {
throw new GdxRuntimeException("Stub");
}
/** Returns a handle to the sibling with the specified name.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} and the sibling
* doesn't exist, or this file is the root. */
public FileHandle sibling (String name) {
throw new GdxRuntimeException("Stub");
}
/** @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public void mkdirs () {
throw new GdxRuntimeException("Stub");
}
/** Returns true if the file exists. On Android, a {@link FileType#Classpath} or {@link FileType#Internal} handle to a
* directory will always return false. */
public boolean exists () {
throw new GdxRuntimeException("Stub");
}
/** Deletes this file or empty directory and returns success. Will not delete a directory that has children.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public boolean delete () {
throw new GdxRuntimeException("Stub");
}
/** Deletes this file or directory and all children, recursively.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public boolean deleteDirectory () {
throw new GdxRuntimeException("Stub");
}
/** Deletes all children of this directory, recursively.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public void emptyDirectory () {
throw new GdxRuntimeException("Not available on GWT");
}
/** Deletes all children of this directory, recursively. Optionally preserving the folder structure.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public void emptyDirectory (boolean preserveTree) {
throw new GdxRuntimeException("Not available on GWT");
}
/** Copies this file or directory to the specified file or directory. If this handle is a file, then 1) if the destination is a
* file, it is overwritten, or 2) if the destination is a directory, this file is copied into it, or 3) if the destination
* doesn't exist, {@link #mkdirs()} is called on the destination's parent and this file is copied into it with a new name. If
* this handle is a directory, then 1) if the destination is a file, GdxRuntimeException is thrown, or 2) if the destination is
* a directory, this directory is copied into it recursively, overwriting existing files, or 3) if the destination doesn't
* exist, {@link #mkdirs()} is called on the destination and this directory is copied into it recursively.
* @throws GdxRuntimeException if the destination file handle is a {@link FileType#Classpath} or {@link FileType#Internal}
* file, or copying failed. */
public void copyTo (FileHandle dest) {
throw new GdxRuntimeException("Stub");
}
/** Moves this file to the specified file, overwriting the file if it already exists.
* @throws GdxRuntimeException if the source or destination file handle is a {@link FileType#Classpath} or
* {@link FileType#Internal} file. */
public void moveTo (FileHandle dest) {
throw new GdxRuntimeException("Stub");
}
/** Returns the length in bytes of this file, or 0 if this file is a directory, does not exist, or the size cannot otherwise be
* determined. */
public long length () {
throw new GdxRuntimeException("Stub");
}
/** Returns the last modified time in milliseconds for this file. Zero is returned if the file doesn't exist. Zero is returned
* for {@link FileType#Classpath} files. On Android, zero is returned for {@link FileType#Internal} files. On the desktop, zero
* is returned for {@link FileType#Internal} files on the classpath. */
public long lastModified () {
throw new GdxRuntimeException("Stub");
}
public String toString () {
throw new GdxRuntimeException("Stub");
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./extensions/gdx-tools/src/com/badlogic/gdx/tools/flame/FlameMain.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tools.flame;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.FileDialog;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.Writer;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.CompoundBorder;
import javax.swing.plaf.basic.BasicSplitPaneUI;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetErrorListener;
import com.badlogic.gdx.assets.AssetLoaderParameters;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.AssetLoader;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.assets.loaders.resolvers.AbsoluteFileHandleResolver;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.backends.lwjgl.LwjglCanvas;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.particles.ParticleController;
import com.badlogic.gdx.graphics.g3d.particles.ParticleEffect;
import com.badlogic.gdx.graphics.g3d.particles.ParticleEffectLoader;
import com.badlogic.gdx.graphics.g3d.particles.ParticleEffectLoader.ParticleEffectSaveParameter;
import com.badlogic.gdx.graphics.g3d.particles.ParticleSystem;
import com.badlogic.gdx.graphics.g3d.particles.batches.BillboardParticleBatch;
import com.badlogic.gdx.graphics.g3d.particles.batches.ModelInstanceParticleBatch;
import com.badlogic.gdx.graphics.g3d.particles.batches.ParticleBatch;
import com.badlogic.gdx.graphics.g3d.particles.batches.PointSpriteParticleBatch;
import com.badlogic.gdx.graphics.g3d.particles.emitters.Emitter;
import com.badlogic.gdx.graphics.g3d.particles.emitters.RegularEmitter;
import com.badlogic.gdx.graphics.g3d.particles.influencers.ColorInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.Influencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.ModelInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.ParticleControllerFinalizerInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.ParticleControllerInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.RegionInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.ScaleInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.SpawnInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.renderers.BillboardRenderer;
import com.badlogic.gdx.graphics.g3d.particles.renderers.ModelInstanceRenderer;
import com.badlogic.gdx.graphics.g3d.particles.renderers.ParticleControllerControllerRenderer;
import com.badlogic.gdx.graphics.g3d.particles.renderers.PointSpriteRenderer;
import com.badlogic.gdx.graphics.g3d.particles.values.GradientColorValue;
import com.badlogic.gdx.graphics.g3d.particles.values.NumericValue;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.RandomXS128;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.JsonWriter;
import com.badlogic.gdx.utils.StreamUtils;
import com.badlogic.gdx.utils.StringBuilder;
/** @author Inferno */
public class FlameMain extends JFrame implements AssetErrorListener {
public static final String DEFAULT_FONT = "default.fnt", DEFAULT_BILLBOARD_PARTICLE = "pre_particle.png",
DEFAULT_MODEL_PARTICLE = "monkey.g3db",
// DEFAULT_PFX = "default.pfx",
DEFAULT_TEMPLATE_PFX = "defaultTemplate.pfx", DEFAULT_SKIN = "uiskin.json";
public static final int EVT_ASSET_RELOADED = 0;
static class ControllerData {
public boolean enabled = true;
public ParticleController controller;
public ControllerData (ParticleController emitter) {
controller = emitter;
}
}
private static class InfluencerWrapper<T> {
String string;
Class<Influencer> type;
public InfluencerWrapper (String string, Class<Influencer> type) {
this.string = string;
this.type = type;
}
@Override
public String toString () {
return string;
}
}
public enum ControllerType {
Billboard("Billboard", new InfluencerWrapper[] {new InfluencerWrapper("Single Color", ColorInfluencer.Single.class),
new InfluencerWrapper("Random Color", ColorInfluencer.Random.class),
new InfluencerWrapper("Single Region", RegionInfluencer.Single.class),
new InfluencerWrapper("Random Region", RegionInfluencer.Random.class),
new InfluencerWrapper("Animated Region", RegionInfluencer.Animated.class),
new InfluencerWrapper("Scale", ScaleInfluencer.class), new InfluencerWrapper("Spawn", SpawnInfluencer.class),
new InfluencerWrapper("Dynamics", DynamicsInfluencer.class)}), PointSprite(
"Point Sprite",
new InfluencerWrapper[] {new InfluencerWrapper("Single Color", ColorInfluencer.Single.class),
new InfluencerWrapper("Random Color", ColorInfluencer.Random.class),
new InfluencerWrapper("Single Region", RegionInfluencer.Single.class),
new InfluencerWrapper("Random Region", RegionInfluencer.Random.class),
new InfluencerWrapper("Animated Region", RegionInfluencer.Animated.class),
new InfluencerWrapper("Scale", ScaleInfluencer.class), new InfluencerWrapper("Spawn", SpawnInfluencer.class),
new InfluencerWrapper("Dynamics", DynamicsInfluencer.class)}), ModelInstance(
"Model Instance",
new InfluencerWrapper[] {new InfluencerWrapper("Single Color", ColorInfluencer.Single.class),
new InfluencerWrapper("Random Color", ColorInfluencer.Random.class),
new InfluencerWrapper("Single Model", ModelInfluencer.Single.class),
new InfluencerWrapper("Random Model", ModelInfluencer.Random.class),
new InfluencerWrapper("Scale", ScaleInfluencer.class), new InfluencerWrapper("Spawn", SpawnInfluencer.class),
new InfluencerWrapper("Dynamics", DynamicsInfluencer.class)}), ParticleController(
"Particle Controller",
new InfluencerWrapper[] {
new InfluencerWrapper("Single Particle Controller", ParticleControllerInfluencer.Single.class),
new InfluencerWrapper("Random Particle Controller", ParticleControllerInfluencer.Random.class),
new InfluencerWrapper("Scale", ScaleInfluencer.class),
new InfluencerWrapper("Spawn", SpawnInfluencer.class),
new InfluencerWrapper("Dynamics", DynamicsInfluencer.class)});
public String desc;
public InfluencerWrapper[] wrappers;
private ControllerType (String desc, InfluencerWrapper[] wrappers) {
this.desc = desc;
this.wrappers = wrappers;
}
}
LwjglCanvas lwjglCanvas;
JPanel controllerPropertiesPanel;
JPanel editorPropertiesPanel;
EffectPanel effectPanel;
JSplitPane splitPane;
NumericValue fovValue;
NumericValue deltaMultiplier;
GradientColorValue backgroundColor;
AppRenderer renderer;
AssetManager assetManager;
JComboBox influencerBox;
TextureAtlas textureAtlas;
JsonWriter.OutputType jsonOutputType = JsonWriter.OutputType.minimal;
boolean jsonPrettyPrint = false;
private ParticleEffect effect;
/** READ only */
public Array<ControllerData> controllersData;
ParticleSystem particleSystem;
public FlameMain () {
super("Flame");
MathUtils.random = new RandomXS128();
particleSystem = ParticleSystem.get();
effect = new ParticleEffect();
particleSystem.add(effect);
assetManager = new AssetManager();
assetManager.setErrorListener(this);
assetManager.setLoader(ParticleEffect.class, new ParticleEffectLoader(new InternalFileHandleResolver()));
controllersData = new Array<ControllerData>();
lwjglCanvas = new LwjglCanvas(renderer = new AppRenderer());
addWindowListener(new WindowAdapter() {
public void windowClosed (WindowEvent event) {
// System.exit(0);
Gdx.app.exit();
}
});
initializeComponents();
setSize(1280, 950);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}
public ControllerType getControllerType () {
ParticleController controller = getEmitter();
ControllerType type = null;
if (controller.renderer instanceof BillboardRenderer)
type = ControllerType.Billboard;
else if (controller.renderer instanceof PointSpriteRenderer)
type = ControllerType.PointSprite;
else if (controller.renderer instanceof ModelInstanceRenderer)
type = ControllerType.ModelInstance;
else if (controller.renderer instanceof ParticleControllerControllerRenderer) type = ControllerType.ParticleController;
return type;
}
void reloadRows () {
EventQueue.invokeLater(new Runnable() {
public void run () {
// Ensure no listener is left watching for events
EventManager.get().clear();
// Clear
editorPropertiesPanel.removeAll();
influencerBox.removeAllItems();
controllerPropertiesPanel.removeAll();
// Editor props
addRow(editorPropertiesPanel, new NumericPanel(FlameMain.this, fovValue, "Field of View", ""));
addRow(editorPropertiesPanel, new NumericPanel(FlameMain.this, deltaMultiplier, "Delta multiplier", ""));
addRow(editorPropertiesPanel, new GradientPanel(FlameMain.this, backgroundColor, "Background color", "", true));
addRow(editorPropertiesPanel, new DrawPanel(FlameMain.this, "Draw", ""));
addRow(editorPropertiesPanel, new TextureLoaderPanel(FlameMain.this, "Texture", ""));
addRow(editorPropertiesPanel, new BillboardBatchPanel(FlameMain.this, renderer.billboardBatch), 1, 1);
addRow(editorPropertiesPanel, new PointSpriteBatchPanel(FlameMain.this, renderer.pointSpriteBatch), 1, 1);
addRow(editorPropertiesPanel, new SavePanel(FlameMain.this, "Save", ""));
editorPropertiesPanel.repaint();
// Controller props
ParticleController controller = getEmitter();
if (controller != null) {
// Reload available influencers
DefaultComboBoxModel model = (DefaultComboBoxModel)influencerBox.getModel();
ControllerType type = getControllerType();
if (type != null) {
for (Object value : type.wrappers)
model.addElement(value);
}
JPanel panel = null;
addRow(controllerPropertiesPanel, getPanel(controller.emitter));
for (int i = 0, c = controller.influencers.size; i < c; ++i) {
Influencer influencer = (Influencer)controller.influencers.get(i);
panel = getPanel(influencer);
if (panel != null) addRow(controllerPropertiesPanel, panel, 1, i == c - 1 ? 1 : 0);
}
for (Component component : controllerPropertiesPanel.getComponents())
if (component instanceof EditorPanel) ((EditorPanel)component).update(FlameMain.this);
}
controllerPropertiesPanel.repaint();
}
});
}
protected JPanel getPanel (Emitter emitter) {
if (emitter instanceof RegularEmitter) {
return new RegularEmitterPanel(this, (RegularEmitter)emitter);
}
return null;
}
protected JPanel getPanel (Influencer influencer) {
if (influencer instanceof ColorInfluencer.Single) {
return new ColorInfluencerPanel(this, (ColorInfluencer.Single)influencer);
}
if (influencer instanceof ColorInfluencer.Random) {
return new InfluencerPanel<ColorInfluencer.Random>(this, (ColorInfluencer.Random)influencer, "Random Color Influencer",
"Assign a random color to the particles") {};
} else if (influencer instanceof ScaleInfluencer) {
return new ScaleInfluencerPanel(this, (ScaleInfluencer)influencer);
} else if (influencer instanceof SpawnInfluencer) {
return new SpawnInfluencerPanel(this, (SpawnInfluencer)influencer);
} else if (influencer instanceof DynamicsInfluencer) {
return new DynamicsInfluencerPanel(this, (DynamicsInfluencer)influencer);
} else if (influencer instanceof ModelInfluencer) {
boolean single = influencer instanceof ModelInfluencer.Single;
String name = single ? "Model Single Influencer" : "Model Random Influencer";
return new ModelInfluencerPanel(this, (ModelInfluencer)influencer, single, name,
"Defines what model will be used for the particles");
} else if (influencer instanceof ParticleControllerInfluencer) {
boolean single = influencer instanceof ParticleControllerInfluencer.Single;
String name = single ? "Particle Controller Single Influencer" : "Particle Controller Random Influencer";
return new ParticleControllerInfluencerPanel(this, (ParticleControllerInfluencer)influencer, single, name,
"Defines what controller will be used for the particles");
} else if (influencer instanceof RegionInfluencer.Single) {
return new RegionInfluencerPanel(this, "Billboard Single Region Influencer", "Assign the chosen region to the particles",
(RegionInfluencer.Single)influencer);
} else if (influencer instanceof RegionInfluencer.Animated) {
return new RegionInfluencerPanel(this, "Billboard Animated Region Influencer", "Animates the region of the particles",
(RegionInfluencer.Animated)influencer);
} else if (influencer instanceof RegionInfluencer.Random) {
return new RegionInfluencerPanel(this, "Billboard Random Region Influencer",
"Assigns a randomly picked (among those selected) region to the particles", (RegionInfluencer.Random)influencer);
} else if (influencer instanceof ParticleControllerFinalizerInfluencer) {
return new InfluencerPanel<ParticleControllerFinalizerInfluencer>(this,
(ParticleControllerFinalizerInfluencer)influencer, "ParticleControllerFinalizer Influencer",
"This is required when dealing with a controller of controllers, it will update the controller assigned to each particle, it MUST be the last influencer always.",
true, false) {};
}
return null;
}
protected JPanel getPanel (ParticleBatch renderer) {
if (renderer instanceof PointSpriteParticleBatch) {
return new PointSpriteBatchPanel(this, (PointSpriteParticleBatch)renderer);
}
if (renderer instanceof BillboardParticleBatch) {
return new BillboardBatchPanel(this, (BillboardParticleBatch)renderer);
} else if (renderer instanceof ModelInstanceParticleBatch) {
return new EmptyPanel(this, "Model Instance Batch", "It renders particles as model instances.");
}
return null;
}
void addRow (JPanel panel, JPanel row) {
addRow(panel, row, 1, 0);
}
void addRow (JPanel panel, JPanel row, float wx, float wy) {
row.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, java.awt.Color.black));
panel.add(row, new GridBagConstraints(0, -1, 1, 1, wx, wy, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 0, 0), 0, 0));
}
public void setVisible (String name, boolean visible) {
for (Component component : controllerPropertiesPanel.getComponents())
if (component instanceof EditorPanel && ((EditorPanel)component).getName().equals(name)) component.setVisible(visible);
}
private void rebuildActiveControllers () {
// rebuild list
Array<ParticleController> effectControllers = effect.getControllers();
effectControllers.clear();
for (ControllerData controllerData : controllersData) {
if (controllerData.enabled) effectControllers.add(controllerData.controller);
}
// System.out.println("rebuilding active controllers");
effect.init();
effect.start();
}
public ParticleController getEmitter () {
return effectPanel.editIndex >= 0 ? controllersData.get(effectPanel.editIndex).controller : null;
}
public void addEmitter (ParticleController emitter) {
controllersData.add(new ControllerData(emitter));
rebuildActiveControllers();
}
public void removeEmitter (int row) {
controllersData.removeIndex(row).controller.dispose();
rebuildActiveControllers();
}
public void setEnabled (int emitterIndex, boolean enabled) {
ControllerData data = controllersData.get(emitterIndex);
data.enabled = enabled;
rebuildActiveControllers();
}
public boolean isEnabled (int emitterIndex) {
return controllersData.get(emitterIndex).enabled;
}
private void initializeComponents () {
splitPane = new JSplitPane();
splitPane.setUI(new BasicSplitPaneUI() {
public void paint (Graphics g, JComponent jc) {
}
});
splitPane.setDividerSize(4);
getContentPane().add(splitPane, BorderLayout.CENTER);
{
JSplitPane rightSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
rightSplit.setUI(new BasicSplitPaneUI() {
public void paint (Graphics g, JComponent jc) {
}
});
rightSplit.setDividerSize(4);
splitPane.add(rightSplit, JSplitPane.RIGHT);
{
JPanel propertiesPanel = new JPanel(new GridBagLayout());
rightSplit.add(propertiesPanel, JSplitPane.TOP);
propertiesPanel.setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(3, 0, 6, 6),
BorderFactory.createTitledBorder("Editor Properties")));
{
JScrollPane scroll = new JScrollPane();
propertiesPanel.add(scroll, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTH,
GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
scroll.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
{
editorPropertiesPanel = new JPanel(new GridBagLayout());
scroll.setViewportView(editorPropertiesPanel);
scroll.getVerticalScrollBar().setUnitIncrement(70);
}
}
}
{
JSplitPane rightSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
rightSplitPane.setUI(new BasicSplitPaneUI() {
public void paint (Graphics g, JComponent jc) {
}
});
rightSplitPane.setDividerSize(4);
rightSplitPane.setDividerLocation(100);
rightSplit.add(rightSplitPane, JSplitPane.BOTTOM);
JPanel propertiesPanel = new JPanel(new GridBagLayout());
rightSplitPane.add(propertiesPanel, JSplitPane.TOP);
propertiesPanel.setBorder(
new CompoundBorder(BorderFactory.createEmptyBorder(3, 0, 6, 6), BorderFactory.createTitledBorder("Influencers")));
{
JScrollPane scroll = new JScrollPane();
propertiesPanel.add(scroll, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTH,
GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
scroll.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
{
JPanel influencersPanel = new JPanel(new GridBagLayout());
influencerBox = new JComboBox(new DefaultComboBoxModel());
JButton addInfluencerButton = new JButton("Add");
addInfluencerButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed (ActionEvent e) {
InfluencerWrapper wrapper = (InfluencerWrapper)influencerBox.getSelectedItem();
ParticleController controller = getEmitter();
if (controller != null) addInfluencer(wrapper.type, controller);
}
});
influencersPanel.add(influencerBox, new GridBagConstraints(0, 0, 1, 1, 0, 1, GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
influencersPanel.add(addInfluencerButton, new GridBagConstraints(1, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
scroll.setViewportView(influencersPanel);
scroll.getVerticalScrollBar().setUnitIncrement(70);
}
}
propertiesPanel = new JPanel(new GridBagLayout());
rightSplitPane.add(propertiesPanel, JSplitPane.BOTTOM);
propertiesPanel.setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(3, 0, 6, 6),
BorderFactory.createTitledBorder("Particle Controller Components")));
{
JScrollPane scroll = new JScrollPane();
propertiesPanel.add(scroll, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTH,
GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
scroll.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
{
controllerPropertiesPanel = new JPanel(new GridBagLayout());
scroll.setViewportView(controllerPropertiesPanel);
scroll.getVerticalScrollBar().setUnitIncrement(70);
}
}
}
rightSplit.setDividerLocation(250);
}
{
JSplitPane leftSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
leftSplit.setUI(new BasicSplitPaneUI() {
public void paint (Graphics g, JComponent jc) {
}
});
leftSplit.setDividerSize(4);
splitPane.add(leftSplit, JSplitPane.LEFT);
{
JPanel spacer = new JPanel(new BorderLayout());
leftSplit.add(spacer, JSplitPane.TOP);
spacer.add(lwjglCanvas.getCanvas());
spacer.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 4));
}
{
JPanel emittersPanel = new JPanel(new BorderLayout());
leftSplit.add(emittersPanel, JSplitPane.BOTTOM);
emittersPanel.setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(0, 6, 6, 0),
BorderFactory.createTitledBorder("Particle Controllers")));
{
effectPanel = new EffectPanel(this);
emittersPanel.add(effectPanel);
}
}
leftSplit.setDividerLocation(625);
}
splitPane.setDividerLocation(500);
}
protected void addInfluencer (Class<Influencer> type, ParticleController controller) {
if (controller.findInfluencer(type) != null) return;
try {
controller.end();
Influencer newInfluencer = type.newInstance();
boolean replaced = false;
if (ColorInfluencer.class.isAssignableFrom(type)) {
replaced = controller.replaceInfluencer(ColorInfluencer.class, (ColorInfluencer)newInfluencer);
} else if (RegionInfluencer.class.isAssignableFrom(type)) {
replaced = controller.replaceInfluencer(RegionInfluencer.class, (RegionInfluencer)newInfluencer);
} else if (ModelInfluencer.class.isAssignableFrom(type)) {
ModelInfluencer newModelInfluencer = (ModelInfluencer)newInfluencer;
ModelInfluencer currentInfluencer = (ModelInfluencer)controller.findInfluencer(ModelInfluencer.class);
if (currentInfluencer != null) {
newModelInfluencer.models.add(currentInfluencer.models.first());
}
replaced = controller.replaceInfluencer(ModelInfluencer.class, (ModelInfluencer)newInfluencer);
} else if (ParticleControllerInfluencer.class.isAssignableFrom(type)) {
ParticleControllerInfluencer newModelInfluencer = (ParticleControllerInfluencer)newInfluencer;
ParticleControllerInfluencer currentInfluencer = (ParticleControllerInfluencer)controller
.findInfluencer(ParticleControllerInfluencer.class);
if (currentInfluencer != null) {
newModelInfluencer.templates.add(currentInfluencer.templates.first());
}
replaced = controller.replaceInfluencer(ParticleControllerInfluencer.class,
(ParticleControllerInfluencer)newInfluencer);
}
if (!replaced) {
if (getControllerType() != ControllerType.ParticleController)
controller.influencers.add(newInfluencer);
else {
Influencer finalizer = controller.influencers.pop();
controller.influencers.add(newInfluencer);
controller.influencers.add(finalizer);
}
}
controller.init();
effect.start();
reloadRows();
} catch (Exception e1) {
e1.printStackTrace();
}
}
protected boolean canAddInfluencer (Class influencerType, ParticleController controller) {
boolean hasSameInfluencer = controller.findInfluencer(influencerType) != null;
if (!hasSameInfluencer) {
if ((ColorInfluencer.Single.class.isAssignableFrom(influencerType)
&& controller.findInfluencer(ColorInfluencer.Random.class) != null)
|| (ColorInfluencer.Random.class.isAssignableFrom(influencerType)
&& controller.findInfluencer(ColorInfluencer.Single.class) != null)) {
return false;
}
if (RegionInfluencer.class.isAssignableFrom(influencerType)) {
return controller.findInfluencer(RegionInfluencer.class) == null;
} else if (ModelInfluencer.class.isAssignableFrom(influencerType)) {
return controller.findInfluencer(ModelInfluencer.class) == null;
} else if (ParticleControllerInfluencer.class.isAssignableFrom(influencerType)) {
return controller.findInfluencer(ParticleControllerInfluencer.class) == null;
}
}
return !hasSameInfluencer;
}
class AppRenderer implements ApplicationListener {
// Stats
private float maxActiveTimer;
private int maxActive, lastMaxActive;
boolean isUpdate = true;
// Controls
private CameraInputController cameraInputController;
// UI
private Stage ui;
TextButton playPauseButton;
private Label fpsLabel, pointCountLabel, billboardCountLabel, modelInstanceCountLabel, maxLabel;
StringBuilder stringBuilder;
// Render
public PerspectiveCamera worldCamera;
private boolean isDrawXYZ, isDrawXZPlane, isDrawXYPlane;
private Array<Model> models;
private ModelInstance xyzInstance, xzPlaneInstance, xyPlaneInstance;
private Environment environment;
private ModelBatch modelBatch;
PointSpriteParticleBatch pointSpriteBatch;
BillboardParticleBatch billboardBatch;
ModelInstanceParticleBatch modelInstanceParticleBatch;
public void create () {
if (ui != null) return;
int w = Gdx.graphics.getWidth(), h = Gdx.graphics.getHeight();
modelBatch = new ModelBatch();
environment = new Environment();
environment.add(new DirectionalLight().set(Color.WHITE, 0, 0, -1));
worldCamera = new PerspectiveCamera(67, w, h);
worldCamera.position.set(10, 10, 10);
worldCamera.lookAt(0, 0, 0);
worldCamera.near = 0.1f;
worldCamera.far = 300f;
worldCamera.update();
cameraInputController = new CameraInputController(worldCamera);
// Batches
pointSpriteBatch = new PointSpriteParticleBatch();
pointSpriteBatch.setCamera(worldCamera);
billboardBatch = new BillboardParticleBatch();
billboardBatch.setCamera(worldCamera);
modelInstanceParticleBatch = new ModelInstanceParticleBatch();
particleSystem.add(billboardBatch);
particleSystem.add(pointSpriteBatch);
particleSystem.add(modelInstanceParticleBatch);
fovValue = new NumericValue();
fovValue.setValue(67);
fovValue.setActive(true);
deltaMultiplier = new NumericValue();
deltaMultiplier.setValue(1.0f);
deltaMultiplier.setActive(true);
backgroundColor = new GradientColorValue();
Color color = Color.valueOf("878787");
backgroundColor.setColors(new float[] {color.r, color.g, color.b});
models = new Array<Model>();
ModelBuilder builder = new ModelBuilder();
Model xyzModel = builder.createXYZCoordinates(10, new Material(), Usage.Position | Usage.ColorPacked),
planeModel = builder.createLineGrid(10, 10, 1, 1, new Material(ColorAttribute.createDiffuse(Color.WHITE)),
Usage.Position);
models.add(xyzModel);
models.add(planeModel);
xyzInstance = new ModelInstance(xyzModel);
xzPlaneInstance = new ModelInstance(planeModel);
xyPlaneInstance = new ModelInstance(planeModel);
xyPlaneInstance.transform.rotate(1f, 0f, 0f, 90f);
setDrawXYZ(true);
setDrawXZPlane(true);
// Load default resources
ParticleEffectLoader.ParticleEffectLoadParameter params = new ParticleEffectLoader.ParticleEffectLoadParameter(
particleSystem.getBatches());
assetManager.load(DEFAULT_BILLBOARD_PARTICLE, Texture.class);
assetManager.load(DEFAULT_MODEL_PARTICLE, Model.class);
assetManager.load(DEFAULT_SKIN, Skin.class);
assetManager.load(DEFAULT_TEMPLATE_PFX, ParticleEffect.class, params);
assetManager.finishLoading();
assetManager.setLoader(ParticleEffect.class, new ParticleEffectLoader(new AbsoluteFileHandleResolver()));
assetManager.get(DEFAULT_MODEL_PARTICLE, Model.class).materials.get(0)
.set(new BlendingAttribute(GL20.GL_ONE, GL20.GL_ONE_MINUS_SRC_ALPHA, 1));
// Ui
stringBuilder = new StringBuilder();
Skin skin = assetManager.get(DEFAULT_SKIN, Skin.class);
ui = new Stage();
fpsLabel = new Label("", skin);
pointCountLabel = new Label("", skin);
billboardCountLabel = new Label("", skin);
modelInstanceCountLabel = new Label("", skin);
maxLabel = new Label("", skin);
playPauseButton = new TextButton("Pause", skin);
playPauseButton.addListener(new ClickListener() {
@Override
public void clicked (InputEvent event, float x, float y) {
isUpdate = !isUpdate;
playPauseButton.setText(isUpdate ? "Pause" : "Play");
}
});
Table table = new Table(skin);
table.setFillParent(true);
table.pad(5);
table.add(fpsLabel).expandX().left().row();
table.add(pointCountLabel).expandX().left().row();
table.add(billboardCountLabel).expandX().left().row();
table.add(modelInstanceCountLabel).expandX().left().row();
table.add(maxLabel).expandX().left().row();
table.add(playPauseButton).expand().bottom().left().row();
ui.addActor(table);
setTexture((Texture)assetManager.get(DEFAULT_BILLBOARD_PARTICLE));
effectPanel.createDefaultEmitter(ControllerType.Billboard, true, true);
}
@Override
public void resize (int width, int height) {
Gdx.input.setInputProcessor(new InputMultiplexer(ui, cameraInputController));
Gdx.gl.glViewport(0, 0, width, height);
worldCamera.viewportWidth = width;
worldCamera.viewportHeight = height;
worldCamera.update();
ui.getViewport().setWorldSize(width, height);
ui.getViewport().update(width, height, true);
}
public void render () {
float delta = Math.max(0, Gdx.graphics.getDeltaTime() * deltaMultiplier.getValue());
update(delta);
renderWorld();
}
private void update (float delta) {
worldCamera.fieldOfView = fovValue.getValue();
worldCamera.update();
cameraInputController.update();
if (isUpdate) {
particleSystem.update(delta);
// Update ui
stringBuilder.delete(0, stringBuilder.length);
stringBuilder.append("Point Sprites : ").append(pointSpriteBatch.getBufferedCount());
pointCountLabel.setText(stringBuilder);
stringBuilder.delete(0, stringBuilder.length);
stringBuilder.append("Billboards : ").append(billboardBatch.getBufferedCount());
billboardCountLabel.setText(stringBuilder);
stringBuilder.delete(0, stringBuilder.length);
stringBuilder.append("Model Instances : ").append(modelInstanceParticleBatch.getBufferedCount());
modelInstanceCountLabel.setText(stringBuilder);
}
stringBuilder.delete(0, stringBuilder.length);
stringBuilder.append("FPS : ").append(Gdx.graphics.getFramesPerSecond());
fpsLabel.setText(stringBuilder);
ui.act(Gdx.graphics.getDeltaTime());
}
private void renderWorld () {
float[] colors = backgroundColor.getColors();
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
Gdx.gl.glClearColor(colors[0], colors[1], colors[2], 0);
modelBatch.begin(worldCamera);
if (isDrawXYZ) modelBatch.render(xyzInstance);
if (isDrawXZPlane) modelBatch.render(xzPlaneInstance);
if (isDrawXYPlane) modelBatch.render(xyPlaneInstance);
particleSystem.begin();
particleSystem.draw();
particleSystem.end();
// Draw
modelBatch.render(particleSystem, environment);
modelBatch.end();
ui.draw();
}
@Override
public void dispose () {
}
@Override
public void pause () {
}
@Override
public void resume () {
}
public void setDrawXYZ (boolean isDraw) {
isDrawXYZ = isDraw;
}
public boolean IsDrawXYZ () {
return isDrawXYZ;
}
public void setDrawXZPlane (boolean isDraw) {
isDrawXZPlane = isDraw;
}
public boolean IsDrawXZPlane () {
return isDrawXZPlane;
}
public void setDrawXYPlane (boolean isDraw) {
isDrawXYPlane = isDraw;
}
public boolean IsDrawXYPlane () {
return isDrawXYPlane;
}
}
public static void main (String[] args) {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
try {
UIManager.setLookAndFeel(info.getClassName());
} catch (Throwable ignored) {
}
break;
}
}
EventQueue.invokeLater(new Runnable() {
public void run () {
new FlameMain();
}
});
}
public AppRenderer getRenderer () {
return renderer;
}
String lastDir;
public File showFileLoadDialog () {
return showFileDialog("Open", FileDialog.LOAD);
}
public File showFileSaveDialog () {
return showFileDialog("Save", FileDialog.SAVE);
}
private File showFileDialog (String title, int mode) {
FileDialog dialog = new FileDialog(this, title, mode);
if (lastDir != null) dialog.setDirectory(lastDir);
dialog.setVisible(true);
final String file = dialog.getFile();
final String dir = dialog.getDirectory();
if (dir == null || file == null || file.trim().length() == 0) return null;
lastDir = dir;
return new File(dir, file);
}
@Override
public void error (AssetDescriptor asset, Throwable throwable) {
throwable.printStackTrace();
}
public PointSpriteParticleBatch getPointSpriteBatch () {
return renderer.pointSpriteBatch;
}
public BillboardParticleBatch getBillboardBatch () {
return renderer.billboardBatch;
}
public ModelInstanceParticleBatch getModelInstanceParticleBatch () {
return renderer.modelInstanceParticleBatch;
}
public void setAtlas (TextureAtlas atlas) {
this.textureAtlas = atlas;
setTexture(atlas.getTextures().first());
}
public void setTexture (Texture texture) {
renderer.billboardBatch.setTexture(texture);
renderer.pointSpriteBatch.setTexture(texture);
}
public Texture getTexture () {
return renderer.billboardBatch.getTexture();
}
public TextureAtlas getAtlas (Texture texture) {
Array<TextureAtlas> atlases = assetManager.getAll(TextureAtlas.class, new Array<TextureAtlas>());
for (TextureAtlas atlas : atlases) {
if (atlas.getTextures().contains(texture)) return atlas;
}
return null;
}
public TextureAtlas getAtlas () {
return getAtlas(renderer.billboardBatch.getTexture());
}
public String getAtlasFilename () {
if (textureAtlas == null) {
return null;
}
return assetManager.getAssetFileName(textureAtlas);
}
public boolean isUsingDefaultTexture () {
return renderer.billboardBatch.getTexture() == assetManager.get(DEFAULT_BILLBOARD_PARTICLE, Texture.class);
}
public Array<ParticleEffect> getParticleEffects (Array<ParticleController> controllers, Array<ParticleEffect> out) {
out.clear();
assetManager.getAll(ParticleEffect.class, out);
for (int i = 0; i < out.size;) {
ParticleEffect effect = out.get(i);
Array<ParticleController> effectControllers = effect.getControllers();
boolean remove = true;
for (ParticleController controller : controllers) {
if (effectControllers.contains(controller, true)) {
remove = false;
break;
}
}
if (remove) {
out.removeIndex(i);
continue;
}
++i;
}
return out;
}
public void saveEffect (File file) {
Writer fileWriter = null;
try {
ParticleEffectLoader loader = (ParticleEffectLoader)assetManager.getLoader(ParticleEffect.class);
loader.save(effect, new ParticleEffectSaveParameter(new FileHandle(file.getAbsolutePath()), assetManager,
particleSystem.getBatches(), jsonOutputType, jsonPrettyPrint));
} catch (Exception ex) {
System.out.println("Error saving effect: " + file.getAbsolutePath());
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error saving effect.");
} finally {
StreamUtils.closeQuietly(fileWriter);
}
}
public ParticleEffect openEffect (File file, boolean replaceCurrentWorkspace) {
try {
ParticleEffect loadedEffect = load(file.getAbsolutePath(), ParticleEffect.class, null,
new ParticleEffectLoader.ParticleEffectLoadParameter(particleSystem.getBatches()));
loadedEffect = loadedEffect.copy();
loadedEffect.init();
if (replaceCurrentWorkspace) {
effect = loadedEffect;
controllersData.clear();
particleSystem.removeAll();
particleSystem.add(effect);
for (ParticleController controller : effect.getControllers())
controllersData.add(new ControllerData(controller));
rebuildActiveControllers();
}
reloadRows();
return loadedEffect;
} catch (Exception ex) {
System.out.println("Error loading effect: " + file.getAbsolutePath());
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error opening effect.");
}
return null;
}
public <T> T load (String resource, Class<T> type, AssetLoader loader, AssetLoaderParameters<T> params) {
String resolvedPath = resource.replaceAll("\\\\", "/");
boolean exist = assetManager.isLoaded(resolvedPath, type);
T oldAsset = null;
if (exist) {
oldAsset = assetManager.get(resolvedPath, type);
for (int i = assetManager.getReferenceCount(resolvedPath); i > 0; --i)
assetManager.unload(resolvedPath);
}
AssetLoader<T, AssetLoaderParameters<T>> currentLoader = assetManager.getLoader(type);
if (loader != null) assetManager.setLoader(type, loader);
assetManager.setLoader(ParticleEffect.class, new ParticleEffectLoader(new FileHandleResolver() {
@Override
public FileHandle resolve (String fileName) {
FileHandle attempt = Gdx.files.absolute(fileName);
if (attempt.exists()) return attempt;
if (DEFAULT_BILLBOARD_PARTICLE.equals(attempt.name())) return Gdx.files.internal(DEFAULT_BILLBOARD_PARTICLE);
if (DEFAULT_MODEL_PARTICLE.equals(attempt.name())) return Gdx.files.internal(DEFAULT_MODEL_PARTICLE);
if (DEFAULT_TEMPLATE_PFX.equals(attempt.name())) return Gdx.files.internal(DEFAULT_TEMPLATE_PFX);
return attempt;
}
}));
assetManager.load(resolvedPath, type, params);
assetManager.finishLoading();
T res = assetManager.get(resolvedPath);
if (currentLoader != null) assetManager.setLoader(type, currentLoader);
if (exist) EventManager.get().fire(EVT_ASSET_RELOADED, new Object[] {oldAsset, res});
return res;
}
public void restart () {
effect.init();
effect.start();
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tools.flame;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.FileDialog;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.Writer;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.CompoundBorder;
import javax.swing.plaf.basic.BasicSplitPaneUI;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetErrorListener;
import com.badlogic.gdx.assets.AssetLoaderParameters;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.AssetLoader;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.assets.loaders.resolvers.AbsoluteFileHandleResolver;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.backends.lwjgl.LwjglCanvas;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.particles.ParticleController;
import com.badlogic.gdx.graphics.g3d.particles.ParticleEffect;
import com.badlogic.gdx.graphics.g3d.particles.ParticleEffectLoader;
import com.badlogic.gdx.graphics.g3d.particles.ParticleEffectLoader.ParticleEffectSaveParameter;
import com.badlogic.gdx.graphics.g3d.particles.ParticleSystem;
import com.badlogic.gdx.graphics.g3d.particles.batches.BillboardParticleBatch;
import com.badlogic.gdx.graphics.g3d.particles.batches.ModelInstanceParticleBatch;
import com.badlogic.gdx.graphics.g3d.particles.batches.ParticleBatch;
import com.badlogic.gdx.graphics.g3d.particles.batches.PointSpriteParticleBatch;
import com.badlogic.gdx.graphics.g3d.particles.emitters.Emitter;
import com.badlogic.gdx.graphics.g3d.particles.emitters.RegularEmitter;
import com.badlogic.gdx.graphics.g3d.particles.influencers.ColorInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.Influencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.ModelInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.ParticleControllerFinalizerInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.ParticleControllerInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.RegionInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.ScaleInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.influencers.SpawnInfluencer;
import com.badlogic.gdx.graphics.g3d.particles.renderers.BillboardRenderer;
import com.badlogic.gdx.graphics.g3d.particles.renderers.ModelInstanceRenderer;
import com.badlogic.gdx.graphics.g3d.particles.renderers.ParticleControllerControllerRenderer;
import com.badlogic.gdx.graphics.g3d.particles.renderers.PointSpriteRenderer;
import com.badlogic.gdx.graphics.g3d.particles.values.GradientColorValue;
import com.badlogic.gdx.graphics.g3d.particles.values.NumericValue;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.RandomXS128;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.JsonWriter;
import com.badlogic.gdx.utils.StreamUtils;
import com.badlogic.gdx.utils.StringBuilder;
/** @author Inferno */
public class FlameMain extends JFrame implements AssetErrorListener {
public static final String DEFAULT_FONT = "default.fnt", DEFAULT_BILLBOARD_PARTICLE = "pre_particle.png",
DEFAULT_MODEL_PARTICLE = "monkey.g3db",
// DEFAULT_PFX = "default.pfx",
DEFAULT_TEMPLATE_PFX = "defaultTemplate.pfx", DEFAULT_SKIN = "uiskin.json";
public static final int EVT_ASSET_RELOADED = 0;
static class ControllerData {
public boolean enabled = true;
public ParticleController controller;
public ControllerData (ParticleController emitter) {
controller = emitter;
}
}
private static class InfluencerWrapper<T> {
String string;
Class<Influencer> type;
public InfluencerWrapper (String string, Class<Influencer> type) {
this.string = string;
this.type = type;
}
@Override
public String toString () {
return string;
}
}
public enum ControllerType {
Billboard("Billboard", new InfluencerWrapper[] {new InfluencerWrapper("Single Color", ColorInfluencer.Single.class),
new InfluencerWrapper("Random Color", ColorInfluencer.Random.class),
new InfluencerWrapper("Single Region", RegionInfluencer.Single.class),
new InfluencerWrapper("Random Region", RegionInfluencer.Random.class),
new InfluencerWrapper("Animated Region", RegionInfluencer.Animated.class),
new InfluencerWrapper("Scale", ScaleInfluencer.class), new InfluencerWrapper("Spawn", SpawnInfluencer.class),
new InfluencerWrapper("Dynamics", DynamicsInfluencer.class)}), PointSprite(
"Point Sprite",
new InfluencerWrapper[] {new InfluencerWrapper("Single Color", ColorInfluencer.Single.class),
new InfluencerWrapper("Random Color", ColorInfluencer.Random.class),
new InfluencerWrapper("Single Region", RegionInfluencer.Single.class),
new InfluencerWrapper("Random Region", RegionInfluencer.Random.class),
new InfluencerWrapper("Animated Region", RegionInfluencer.Animated.class),
new InfluencerWrapper("Scale", ScaleInfluencer.class), new InfluencerWrapper("Spawn", SpawnInfluencer.class),
new InfluencerWrapper("Dynamics", DynamicsInfluencer.class)}), ModelInstance(
"Model Instance",
new InfluencerWrapper[] {new InfluencerWrapper("Single Color", ColorInfluencer.Single.class),
new InfluencerWrapper("Random Color", ColorInfluencer.Random.class),
new InfluencerWrapper("Single Model", ModelInfluencer.Single.class),
new InfluencerWrapper("Random Model", ModelInfluencer.Random.class),
new InfluencerWrapper("Scale", ScaleInfluencer.class), new InfluencerWrapper("Spawn", SpawnInfluencer.class),
new InfluencerWrapper("Dynamics", DynamicsInfluencer.class)}), ParticleController(
"Particle Controller",
new InfluencerWrapper[] {
new InfluencerWrapper("Single Particle Controller", ParticleControllerInfluencer.Single.class),
new InfluencerWrapper("Random Particle Controller", ParticleControllerInfluencer.Random.class),
new InfluencerWrapper("Scale", ScaleInfluencer.class),
new InfluencerWrapper("Spawn", SpawnInfluencer.class),
new InfluencerWrapper("Dynamics", DynamicsInfluencer.class)});
public String desc;
public InfluencerWrapper[] wrappers;
private ControllerType (String desc, InfluencerWrapper[] wrappers) {
this.desc = desc;
this.wrappers = wrappers;
}
}
LwjglCanvas lwjglCanvas;
JPanel controllerPropertiesPanel;
JPanel editorPropertiesPanel;
EffectPanel effectPanel;
JSplitPane splitPane;
NumericValue fovValue;
NumericValue deltaMultiplier;
GradientColorValue backgroundColor;
AppRenderer renderer;
AssetManager assetManager;
JComboBox influencerBox;
TextureAtlas textureAtlas;
JsonWriter.OutputType jsonOutputType = JsonWriter.OutputType.minimal;
boolean jsonPrettyPrint = false;
private ParticleEffect effect;
/** READ only */
public Array<ControllerData> controllersData;
ParticleSystem particleSystem;
public FlameMain () {
super("Flame");
MathUtils.random = new RandomXS128();
particleSystem = ParticleSystem.get();
effect = new ParticleEffect();
particleSystem.add(effect);
assetManager = new AssetManager();
assetManager.setErrorListener(this);
assetManager.setLoader(ParticleEffect.class, new ParticleEffectLoader(new InternalFileHandleResolver()));
controllersData = new Array<ControllerData>();
lwjglCanvas = new LwjglCanvas(renderer = new AppRenderer());
addWindowListener(new WindowAdapter() {
public void windowClosed (WindowEvent event) {
// System.exit(0);
Gdx.app.exit();
}
});
initializeComponents();
setSize(1280, 950);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}
public ControllerType getControllerType () {
ParticleController controller = getEmitter();
ControllerType type = null;
if (controller.renderer instanceof BillboardRenderer)
type = ControllerType.Billboard;
else if (controller.renderer instanceof PointSpriteRenderer)
type = ControllerType.PointSprite;
else if (controller.renderer instanceof ModelInstanceRenderer)
type = ControllerType.ModelInstance;
else if (controller.renderer instanceof ParticleControllerControllerRenderer) type = ControllerType.ParticleController;
return type;
}
void reloadRows () {
EventQueue.invokeLater(new Runnable() {
public void run () {
// Ensure no listener is left watching for events
EventManager.get().clear();
// Clear
editorPropertiesPanel.removeAll();
influencerBox.removeAllItems();
controllerPropertiesPanel.removeAll();
// Editor props
addRow(editorPropertiesPanel, new NumericPanel(FlameMain.this, fovValue, "Field of View", ""));
addRow(editorPropertiesPanel, new NumericPanel(FlameMain.this, deltaMultiplier, "Delta multiplier", ""));
addRow(editorPropertiesPanel, new GradientPanel(FlameMain.this, backgroundColor, "Background color", "", true));
addRow(editorPropertiesPanel, new DrawPanel(FlameMain.this, "Draw", ""));
addRow(editorPropertiesPanel, new TextureLoaderPanel(FlameMain.this, "Texture", ""));
addRow(editorPropertiesPanel, new BillboardBatchPanel(FlameMain.this, renderer.billboardBatch), 1, 1);
addRow(editorPropertiesPanel, new PointSpriteBatchPanel(FlameMain.this, renderer.pointSpriteBatch), 1, 1);
addRow(editorPropertiesPanel, new SavePanel(FlameMain.this, "Save", ""));
editorPropertiesPanel.repaint();
// Controller props
ParticleController controller = getEmitter();
if (controller != null) {
// Reload available influencers
DefaultComboBoxModel model = (DefaultComboBoxModel)influencerBox.getModel();
ControllerType type = getControllerType();
if (type != null) {
for (Object value : type.wrappers)
model.addElement(value);
}
JPanel panel = null;
addRow(controllerPropertiesPanel, getPanel(controller.emitter));
for (int i = 0, c = controller.influencers.size; i < c; ++i) {
Influencer influencer = (Influencer)controller.influencers.get(i);
panel = getPanel(influencer);
if (panel != null) addRow(controllerPropertiesPanel, panel, 1, i == c - 1 ? 1 : 0);
}
for (Component component : controllerPropertiesPanel.getComponents())
if (component instanceof EditorPanel) ((EditorPanel)component).update(FlameMain.this);
}
controllerPropertiesPanel.repaint();
}
});
}
protected JPanel getPanel (Emitter emitter) {
if (emitter instanceof RegularEmitter) {
return new RegularEmitterPanel(this, (RegularEmitter)emitter);
}
return null;
}
protected JPanel getPanel (Influencer influencer) {
if (influencer instanceof ColorInfluencer.Single) {
return new ColorInfluencerPanel(this, (ColorInfluencer.Single)influencer);
}
if (influencer instanceof ColorInfluencer.Random) {
return new InfluencerPanel<ColorInfluencer.Random>(this, (ColorInfluencer.Random)influencer, "Random Color Influencer",
"Assign a random color to the particles") {};
} else if (influencer instanceof ScaleInfluencer) {
return new ScaleInfluencerPanel(this, (ScaleInfluencer)influencer);
} else if (influencer instanceof SpawnInfluencer) {
return new SpawnInfluencerPanel(this, (SpawnInfluencer)influencer);
} else if (influencer instanceof DynamicsInfluencer) {
return new DynamicsInfluencerPanel(this, (DynamicsInfluencer)influencer);
} else if (influencer instanceof ModelInfluencer) {
boolean single = influencer instanceof ModelInfluencer.Single;
String name = single ? "Model Single Influencer" : "Model Random Influencer";
return new ModelInfluencerPanel(this, (ModelInfluencer)influencer, single, name,
"Defines what model will be used for the particles");
} else if (influencer instanceof ParticleControllerInfluencer) {
boolean single = influencer instanceof ParticleControllerInfluencer.Single;
String name = single ? "Particle Controller Single Influencer" : "Particle Controller Random Influencer";
return new ParticleControllerInfluencerPanel(this, (ParticleControllerInfluencer)influencer, single, name,
"Defines what controller will be used for the particles");
} else if (influencer instanceof RegionInfluencer.Single) {
return new RegionInfluencerPanel(this, "Billboard Single Region Influencer", "Assign the chosen region to the particles",
(RegionInfluencer.Single)influencer);
} else if (influencer instanceof RegionInfluencer.Animated) {
return new RegionInfluencerPanel(this, "Billboard Animated Region Influencer", "Animates the region of the particles",
(RegionInfluencer.Animated)influencer);
} else if (influencer instanceof RegionInfluencer.Random) {
return new RegionInfluencerPanel(this, "Billboard Random Region Influencer",
"Assigns a randomly picked (among those selected) region to the particles", (RegionInfluencer.Random)influencer);
} else if (influencer instanceof ParticleControllerFinalizerInfluencer) {
return new InfluencerPanel<ParticleControllerFinalizerInfluencer>(this,
(ParticleControllerFinalizerInfluencer)influencer, "ParticleControllerFinalizer Influencer",
"This is required when dealing with a controller of controllers, it will update the controller assigned to each particle, it MUST be the last influencer always.",
true, false) {};
}
return null;
}
protected JPanel getPanel (ParticleBatch renderer) {
if (renderer instanceof PointSpriteParticleBatch) {
return new PointSpriteBatchPanel(this, (PointSpriteParticleBatch)renderer);
}
if (renderer instanceof BillboardParticleBatch) {
return new BillboardBatchPanel(this, (BillboardParticleBatch)renderer);
} else if (renderer instanceof ModelInstanceParticleBatch) {
return new EmptyPanel(this, "Model Instance Batch", "It renders particles as model instances.");
}
return null;
}
void addRow (JPanel panel, JPanel row) {
addRow(panel, row, 1, 0);
}
void addRow (JPanel panel, JPanel row, float wx, float wy) {
row.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, java.awt.Color.black));
panel.add(row, new GridBagConstraints(0, -1, 1, 1, wx, wy, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 0, 0), 0, 0));
}
public void setVisible (String name, boolean visible) {
for (Component component : controllerPropertiesPanel.getComponents())
if (component instanceof EditorPanel && ((EditorPanel)component).getName().equals(name)) component.setVisible(visible);
}
private void rebuildActiveControllers () {
// rebuild list
Array<ParticleController> effectControllers = effect.getControllers();
effectControllers.clear();
for (ControllerData controllerData : controllersData) {
if (controllerData.enabled) effectControllers.add(controllerData.controller);
}
// System.out.println("rebuilding active controllers");
effect.init();
effect.start();
}
public ParticleController getEmitter () {
return effectPanel.editIndex >= 0 ? controllersData.get(effectPanel.editIndex).controller : null;
}
public void addEmitter (ParticleController emitter) {
controllersData.add(new ControllerData(emitter));
rebuildActiveControllers();
}
public void removeEmitter (int row) {
controllersData.removeIndex(row).controller.dispose();
rebuildActiveControllers();
}
public void setEnabled (int emitterIndex, boolean enabled) {
ControllerData data = controllersData.get(emitterIndex);
data.enabled = enabled;
rebuildActiveControllers();
}
public boolean isEnabled (int emitterIndex) {
return controllersData.get(emitterIndex).enabled;
}
private void initializeComponents () {
splitPane = new JSplitPane();
splitPane.setUI(new BasicSplitPaneUI() {
public void paint (Graphics g, JComponent jc) {
}
});
splitPane.setDividerSize(4);
getContentPane().add(splitPane, BorderLayout.CENTER);
{
JSplitPane rightSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
rightSplit.setUI(new BasicSplitPaneUI() {
public void paint (Graphics g, JComponent jc) {
}
});
rightSplit.setDividerSize(4);
splitPane.add(rightSplit, JSplitPane.RIGHT);
{
JPanel propertiesPanel = new JPanel(new GridBagLayout());
rightSplit.add(propertiesPanel, JSplitPane.TOP);
propertiesPanel.setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(3, 0, 6, 6),
BorderFactory.createTitledBorder("Editor Properties")));
{
JScrollPane scroll = new JScrollPane();
propertiesPanel.add(scroll, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTH,
GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
scroll.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
{
editorPropertiesPanel = new JPanel(new GridBagLayout());
scroll.setViewportView(editorPropertiesPanel);
scroll.getVerticalScrollBar().setUnitIncrement(70);
}
}
}
{
JSplitPane rightSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
rightSplitPane.setUI(new BasicSplitPaneUI() {
public void paint (Graphics g, JComponent jc) {
}
});
rightSplitPane.setDividerSize(4);
rightSplitPane.setDividerLocation(100);
rightSplit.add(rightSplitPane, JSplitPane.BOTTOM);
JPanel propertiesPanel = new JPanel(new GridBagLayout());
rightSplitPane.add(propertiesPanel, JSplitPane.TOP);
propertiesPanel.setBorder(
new CompoundBorder(BorderFactory.createEmptyBorder(3, 0, 6, 6), BorderFactory.createTitledBorder("Influencers")));
{
JScrollPane scroll = new JScrollPane();
propertiesPanel.add(scroll, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTH,
GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
scroll.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
{
JPanel influencersPanel = new JPanel(new GridBagLayout());
influencerBox = new JComboBox(new DefaultComboBoxModel());
JButton addInfluencerButton = new JButton("Add");
addInfluencerButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed (ActionEvent e) {
InfluencerWrapper wrapper = (InfluencerWrapper)influencerBox.getSelectedItem();
ParticleController controller = getEmitter();
if (controller != null) addInfluencer(wrapper.type, controller);
}
});
influencersPanel.add(influencerBox, new GridBagConstraints(0, 0, 1, 1, 0, 1, GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
influencersPanel.add(addInfluencerButton, new GridBagConstraints(1, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
scroll.setViewportView(influencersPanel);
scroll.getVerticalScrollBar().setUnitIncrement(70);
}
}
propertiesPanel = new JPanel(new GridBagLayout());
rightSplitPane.add(propertiesPanel, JSplitPane.BOTTOM);
propertiesPanel.setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(3, 0, 6, 6),
BorderFactory.createTitledBorder("Particle Controller Components")));
{
JScrollPane scroll = new JScrollPane();
propertiesPanel.add(scroll, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTH,
GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
scroll.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
{
controllerPropertiesPanel = new JPanel(new GridBagLayout());
scroll.setViewportView(controllerPropertiesPanel);
scroll.getVerticalScrollBar().setUnitIncrement(70);
}
}
}
rightSplit.setDividerLocation(250);
}
{
JSplitPane leftSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
leftSplit.setUI(new BasicSplitPaneUI() {
public void paint (Graphics g, JComponent jc) {
}
});
leftSplit.setDividerSize(4);
splitPane.add(leftSplit, JSplitPane.LEFT);
{
JPanel spacer = new JPanel(new BorderLayout());
leftSplit.add(spacer, JSplitPane.TOP);
spacer.add(lwjglCanvas.getCanvas());
spacer.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 4));
}
{
JPanel emittersPanel = new JPanel(new BorderLayout());
leftSplit.add(emittersPanel, JSplitPane.BOTTOM);
emittersPanel.setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(0, 6, 6, 0),
BorderFactory.createTitledBorder("Particle Controllers")));
{
effectPanel = new EffectPanel(this);
emittersPanel.add(effectPanel);
}
}
leftSplit.setDividerLocation(625);
}
splitPane.setDividerLocation(500);
}
protected void addInfluencer (Class<Influencer> type, ParticleController controller) {
if (controller.findInfluencer(type) != null) return;
try {
controller.end();
Influencer newInfluencer = type.newInstance();
boolean replaced = false;
if (ColorInfluencer.class.isAssignableFrom(type)) {
replaced = controller.replaceInfluencer(ColorInfluencer.class, (ColorInfluencer)newInfluencer);
} else if (RegionInfluencer.class.isAssignableFrom(type)) {
replaced = controller.replaceInfluencer(RegionInfluencer.class, (RegionInfluencer)newInfluencer);
} else if (ModelInfluencer.class.isAssignableFrom(type)) {
ModelInfluencer newModelInfluencer = (ModelInfluencer)newInfluencer;
ModelInfluencer currentInfluencer = (ModelInfluencer)controller.findInfluencer(ModelInfluencer.class);
if (currentInfluencer != null) {
newModelInfluencer.models.add(currentInfluencer.models.first());
}
replaced = controller.replaceInfluencer(ModelInfluencer.class, (ModelInfluencer)newInfluencer);
} else if (ParticleControllerInfluencer.class.isAssignableFrom(type)) {
ParticleControllerInfluencer newModelInfluencer = (ParticleControllerInfluencer)newInfluencer;
ParticleControllerInfluencer currentInfluencer = (ParticleControllerInfluencer)controller
.findInfluencer(ParticleControllerInfluencer.class);
if (currentInfluencer != null) {
newModelInfluencer.templates.add(currentInfluencer.templates.first());
}
replaced = controller.replaceInfluencer(ParticleControllerInfluencer.class,
(ParticleControllerInfluencer)newInfluencer);
}
if (!replaced) {
if (getControllerType() != ControllerType.ParticleController)
controller.influencers.add(newInfluencer);
else {
Influencer finalizer = controller.influencers.pop();
controller.influencers.add(newInfluencer);
controller.influencers.add(finalizer);
}
}
controller.init();
effect.start();
reloadRows();
} catch (Exception e1) {
e1.printStackTrace();
}
}
protected boolean canAddInfluencer (Class influencerType, ParticleController controller) {
boolean hasSameInfluencer = controller.findInfluencer(influencerType) != null;
if (!hasSameInfluencer) {
if ((ColorInfluencer.Single.class.isAssignableFrom(influencerType)
&& controller.findInfluencer(ColorInfluencer.Random.class) != null)
|| (ColorInfluencer.Random.class.isAssignableFrom(influencerType)
&& controller.findInfluencer(ColorInfluencer.Single.class) != null)) {
return false;
}
if (RegionInfluencer.class.isAssignableFrom(influencerType)) {
return controller.findInfluencer(RegionInfluencer.class) == null;
} else if (ModelInfluencer.class.isAssignableFrom(influencerType)) {
return controller.findInfluencer(ModelInfluencer.class) == null;
} else if (ParticleControllerInfluencer.class.isAssignableFrom(influencerType)) {
return controller.findInfluencer(ParticleControllerInfluencer.class) == null;
}
}
return !hasSameInfluencer;
}
class AppRenderer implements ApplicationListener {
// Stats
private float maxActiveTimer;
private int maxActive, lastMaxActive;
boolean isUpdate = true;
// Controls
private CameraInputController cameraInputController;
// UI
private Stage ui;
TextButton playPauseButton;
private Label fpsLabel, pointCountLabel, billboardCountLabel, modelInstanceCountLabel, maxLabel;
StringBuilder stringBuilder;
// Render
public PerspectiveCamera worldCamera;
private boolean isDrawXYZ, isDrawXZPlane, isDrawXYPlane;
private Array<Model> models;
private ModelInstance xyzInstance, xzPlaneInstance, xyPlaneInstance;
private Environment environment;
private ModelBatch modelBatch;
PointSpriteParticleBatch pointSpriteBatch;
BillboardParticleBatch billboardBatch;
ModelInstanceParticleBatch modelInstanceParticleBatch;
public void create () {
if (ui != null) return;
int w = Gdx.graphics.getWidth(), h = Gdx.graphics.getHeight();
modelBatch = new ModelBatch();
environment = new Environment();
environment.add(new DirectionalLight().set(Color.WHITE, 0, 0, -1));
worldCamera = new PerspectiveCamera(67, w, h);
worldCamera.position.set(10, 10, 10);
worldCamera.lookAt(0, 0, 0);
worldCamera.near = 0.1f;
worldCamera.far = 300f;
worldCamera.update();
cameraInputController = new CameraInputController(worldCamera);
// Batches
pointSpriteBatch = new PointSpriteParticleBatch();
pointSpriteBatch.setCamera(worldCamera);
billboardBatch = new BillboardParticleBatch();
billboardBatch.setCamera(worldCamera);
modelInstanceParticleBatch = new ModelInstanceParticleBatch();
particleSystem.add(billboardBatch);
particleSystem.add(pointSpriteBatch);
particleSystem.add(modelInstanceParticleBatch);
fovValue = new NumericValue();
fovValue.setValue(67);
fovValue.setActive(true);
deltaMultiplier = new NumericValue();
deltaMultiplier.setValue(1.0f);
deltaMultiplier.setActive(true);
backgroundColor = new GradientColorValue();
Color color = Color.valueOf("878787");
backgroundColor.setColors(new float[] {color.r, color.g, color.b});
models = new Array<Model>();
ModelBuilder builder = new ModelBuilder();
Model xyzModel = builder.createXYZCoordinates(10, new Material(), Usage.Position | Usage.ColorPacked),
planeModel = builder.createLineGrid(10, 10, 1, 1, new Material(ColorAttribute.createDiffuse(Color.WHITE)),
Usage.Position);
models.add(xyzModel);
models.add(planeModel);
xyzInstance = new ModelInstance(xyzModel);
xzPlaneInstance = new ModelInstance(planeModel);
xyPlaneInstance = new ModelInstance(planeModel);
xyPlaneInstance.transform.rotate(1f, 0f, 0f, 90f);
setDrawXYZ(true);
setDrawXZPlane(true);
// Load default resources
ParticleEffectLoader.ParticleEffectLoadParameter params = new ParticleEffectLoader.ParticleEffectLoadParameter(
particleSystem.getBatches());
assetManager.load(DEFAULT_BILLBOARD_PARTICLE, Texture.class);
assetManager.load(DEFAULT_MODEL_PARTICLE, Model.class);
assetManager.load(DEFAULT_SKIN, Skin.class);
assetManager.load(DEFAULT_TEMPLATE_PFX, ParticleEffect.class, params);
assetManager.finishLoading();
assetManager.setLoader(ParticleEffect.class, new ParticleEffectLoader(new AbsoluteFileHandleResolver()));
assetManager.get(DEFAULT_MODEL_PARTICLE, Model.class).materials.get(0)
.set(new BlendingAttribute(GL20.GL_ONE, GL20.GL_ONE_MINUS_SRC_ALPHA, 1));
// Ui
stringBuilder = new StringBuilder();
Skin skin = assetManager.get(DEFAULT_SKIN, Skin.class);
ui = new Stage();
fpsLabel = new Label("", skin);
pointCountLabel = new Label("", skin);
billboardCountLabel = new Label("", skin);
modelInstanceCountLabel = new Label("", skin);
maxLabel = new Label("", skin);
playPauseButton = new TextButton("Pause", skin);
playPauseButton.addListener(new ClickListener() {
@Override
public void clicked (InputEvent event, float x, float y) {
isUpdate = !isUpdate;
playPauseButton.setText(isUpdate ? "Pause" : "Play");
}
});
Table table = new Table(skin);
table.setFillParent(true);
table.pad(5);
table.add(fpsLabel).expandX().left().row();
table.add(pointCountLabel).expandX().left().row();
table.add(billboardCountLabel).expandX().left().row();
table.add(modelInstanceCountLabel).expandX().left().row();
table.add(maxLabel).expandX().left().row();
table.add(playPauseButton).expand().bottom().left().row();
ui.addActor(table);
setTexture((Texture)assetManager.get(DEFAULT_BILLBOARD_PARTICLE));
effectPanel.createDefaultEmitter(ControllerType.Billboard, true, true);
}
@Override
public void resize (int width, int height) {
Gdx.input.setInputProcessor(new InputMultiplexer(ui, cameraInputController));
Gdx.gl.glViewport(0, 0, width, height);
worldCamera.viewportWidth = width;
worldCamera.viewportHeight = height;
worldCamera.update();
ui.getViewport().setWorldSize(width, height);
ui.getViewport().update(width, height, true);
}
public void render () {
float delta = Math.max(0, Gdx.graphics.getDeltaTime() * deltaMultiplier.getValue());
update(delta);
renderWorld();
}
private void update (float delta) {
worldCamera.fieldOfView = fovValue.getValue();
worldCamera.update();
cameraInputController.update();
if (isUpdate) {
particleSystem.update(delta);
// Update ui
stringBuilder.delete(0, stringBuilder.length);
stringBuilder.append("Point Sprites : ").append(pointSpriteBatch.getBufferedCount());
pointCountLabel.setText(stringBuilder);
stringBuilder.delete(0, stringBuilder.length);
stringBuilder.append("Billboards : ").append(billboardBatch.getBufferedCount());
billboardCountLabel.setText(stringBuilder);
stringBuilder.delete(0, stringBuilder.length);
stringBuilder.append("Model Instances : ").append(modelInstanceParticleBatch.getBufferedCount());
modelInstanceCountLabel.setText(stringBuilder);
}
stringBuilder.delete(0, stringBuilder.length);
stringBuilder.append("FPS : ").append(Gdx.graphics.getFramesPerSecond());
fpsLabel.setText(stringBuilder);
ui.act(Gdx.graphics.getDeltaTime());
}
private void renderWorld () {
float[] colors = backgroundColor.getColors();
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
Gdx.gl.glClearColor(colors[0], colors[1], colors[2], 0);
modelBatch.begin(worldCamera);
if (isDrawXYZ) modelBatch.render(xyzInstance);
if (isDrawXZPlane) modelBatch.render(xzPlaneInstance);
if (isDrawXYPlane) modelBatch.render(xyPlaneInstance);
particleSystem.begin();
particleSystem.draw();
particleSystem.end();
// Draw
modelBatch.render(particleSystem, environment);
modelBatch.end();
ui.draw();
}
@Override
public void dispose () {
}
@Override
public void pause () {
}
@Override
public void resume () {
}
public void setDrawXYZ (boolean isDraw) {
isDrawXYZ = isDraw;
}
public boolean IsDrawXYZ () {
return isDrawXYZ;
}
public void setDrawXZPlane (boolean isDraw) {
isDrawXZPlane = isDraw;
}
public boolean IsDrawXZPlane () {
return isDrawXZPlane;
}
public void setDrawXYPlane (boolean isDraw) {
isDrawXYPlane = isDraw;
}
public boolean IsDrawXYPlane () {
return isDrawXYPlane;
}
}
public static void main (String[] args) {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
try {
UIManager.setLookAndFeel(info.getClassName());
} catch (Throwable ignored) {
}
break;
}
}
EventQueue.invokeLater(new Runnable() {
public void run () {
new FlameMain();
}
});
}
public AppRenderer getRenderer () {
return renderer;
}
String lastDir;
public File showFileLoadDialog () {
return showFileDialog("Open", FileDialog.LOAD);
}
public File showFileSaveDialog () {
return showFileDialog("Save", FileDialog.SAVE);
}
private File showFileDialog (String title, int mode) {
FileDialog dialog = new FileDialog(this, title, mode);
if (lastDir != null) dialog.setDirectory(lastDir);
dialog.setVisible(true);
final String file = dialog.getFile();
final String dir = dialog.getDirectory();
if (dir == null || file == null || file.trim().length() == 0) return null;
lastDir = dir;
return new File(dir, file);
}
@Override
public void error (AssetDescriptor asset, Throwable throwable) {
throwable.printStackTrace();
}
public PointSpriteParticleBatch getPointSpriteBatch () {
return renderer.pointSpriteBatch;
}
public BillboardParticleBatch getBillboardBatch () {
return renderer.billboardBatch;
}
public ModelInstanceParticleBatch getModelInstanceParticleBatch () {
return renderer.modelInstanceParticleBatch;
}
public void setAtlas (TextureAtlas atlas) {
this.textureAtlas = atlas;
setTexture(atlas.getTextures().first());
}
public void setTexture (Texture texture) {
renderer.billboardBatch.setTexture(texture);
renderer.pointSpriteBatch.setTexture(texture);
}
public Texture getTexture () {
return renderer.billboardBatch.getTexture();
}
public TextureAtlas getAtlas (Texture texture) {
Array<TextureAtlas> atlases = assetManager.getAll(TextureAtlas.class, new Array<TextureAtlas>());
for (TextureAtlas atlas : atlases) {
if (atlas.getTextures().contains(texture)) return atlas;
}
return null;
}
public TextureAtlas getAtlas () {
return getAtlas(renderer.billboardBatch.getTexture());
}
public String getAtlasFilename () {
if (textureAtlas == null) {
return null;
}
return assetManager.getAssetFileName(textureAtlas);
}
public boolean isUsingDefaultTexture () {
return renderer.billboardBatch.getTexture() == assetManager.get(DEFAULT_BILLBOARD_PARTICLE, Texture.class);
}
public Array<ParticleEffect> getParticleEffects (Array<ParticleController> controllers, Array<ParticleEffect> out) {
out.clear();
assetManager.getAll(ParticleEffect.class, out);
for (int i = 0; i < out.size;) {
ParticleEffect effect = out.get(i);
Array<ParticleController> effectControllers = effect.getControllers();
boolean remove = true;
for (ParticleController controller : controllers) {
if (effectControllers.contains(controller, true)) {
remove = false;
break;
}
}
if (remove) {
out.removeIndex(i);
continue;
}
++i;
}
return out;
}
public void saveEffect (File file) {
Writer fileWriter = null;
try {
ParticleEffectLoader loader = (ParticleEffectLoader)assetManager.getLoader(ParticleEffect.class);
loader.save(effect, new ParticleEffectSaveParameter(new FileHandle(file.getAbsolutePath()), assetManager,
particleSystem.getBatches(), jsonOutputType, jsonPrettyPrint));
} catch (Exception ex) {
System.out.println("Error saving effect: " + file.getAbsolutePath());
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error saving effect.");
} finally {
StreamUtils.closeQuietly(fileWriter);
}
}
public ParticleEffect openEffect (File file, boolean replaceCurrentWorkspace) {
try {
ParticleEffect loadedEffect = load(file.getAbsolutePath(), ParticleEffect.class, null,
new ParticleEffectLoader.ParticleEffectLoadParameter(particleSystem.getBatches()));
loadedEffect = loadedEffect.copy();
loadedEffect.init();
if (replaceCurrentWorkspace) {
effect = loadedEffect;
controllersData.clear();
particleSystem.removeAll();
particleSystem.add(effect);
for (ParticleController controller : effect.getControllers())
controllersData.add(new ControllerData(controller));
rebuildActiveControllers();
}
reloadRows();
return loadedEffect;
} catch (Exception ex) {
System.out.println("Error loading effect: " + file.getAbsolutePath());
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error opening effect.");
}
return null;
}
public <T> T load (String resource, Class<T> type, AssetLoader loader, AssetLoaderParameters<T> params) {
String resolvedPath = resource.replaceAll("\\\\", "/");
boolean exist = assetManager.isLoaded(resolvedPath, type);
T oldAsset = null;
if (exist) {
oldAsset = assetManager.get(resolvedPath, type);
for (int i = assetManager.getReferenceCount(resolvedPath); i > 0; --i)
assetManager.unload(resolvedPath);
}
AssetLoader<T, AssetLoaderParameters<T>> currentLoader = assetManager.getLoader(type);
if (loader != null) assetManager.setLoader(type, loader);
assetManager.setLoader(ParticleEffect.class, new ParticleEffectLoader(new FileHandleResolver() {
@Override
public FileHandle resolve (String fileName) {
FileHandle attempt = Gdx.files.absolute(fileName);
if (attempt.exists()) return attempt;
if (DEFAULT_BILLBOARD_PARTICLE.equals(attempt.name())) return Gdx.files.internal(DEFAULT_BILLBOARD_PARTICLE);
if (DEFAULT_MODEL_PARTICLE.equals(attempt.name())) return Gdx.files.internal(DEFAULT_MODEL_PARTICLE);
if (DEFAULT_TEMPLATE_PFX.equals(attempt.name())) return Gdx.files.internal(DEFAULT_TEMPLATE_PFX);
return attempt;
}
}));
assetManager.load(resolvedPath, type, params);
assetManager.finishLoading();
T res = assetManager.get(resolvedPath);
if (currentLoader != null) assetManager.setLoader(type, currentLoader);
if (exist) EventManager.get().fire(EVT_ASSET_RELOADED, new Object[] {oldAsset, res});
return res;
}
public void restart () {
effect.init();
effect.start();
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./gdx/src/com/badlogic/gdx/graphics/g3d/particles/batches/ModelInstanceParticleBatch.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics.g3d.particles.batches;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.particles.ResourceData;
import com.badlogic.gdx.graphics.g3d.particles.renderers.ModelInstanceControllerRenderData;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Pool;
/*** This class is used to render particles having a model instance channel.
* @author Inferno */
public class ModelInstanceParticleBatch implements ParticleBatch<ModelInstanceControllerRenderData> {
Array<ModelInstanceControllerRenderData> controllersRenderData;
int bufferedParticlesCount;
public ModelInstanceParticleBatch () {
controllersRenderData = new Array<ModelInstanceControllerRenderData>(false, 5);
}
@Override
public void getRenderables (Array<Renderable> renderables, Pool<Renderable> pool) {
for (ModelInstanceControllerRenderData data : controllersRenderData) {
for (int i = 0, count = data.controller.particles.size; i < count; ++i) {
data.modelInstanceChannel.data[i].getRenderables(renderables, pool);
}
}
}
public int getBufferedCount () {
return bufferedParticlesCount;
}
@Override
public void begin () {
controllersRenderData.clear();
bufferedParticlesCount = 0;
}
@Override
public void end () {
}
@Override
public void draw (ModelInstanceControllerRenderData data) {
controllersRenderData.add(data);
bufferedParticlesCount += data.controller.particles.size;
}
@Override
public void save (AssetManager manager, ResourceData assetDependencyData) {
}
@Override
public void load (AssetManager manager, ResourceData assetDependencyData) {
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics.g3d.particles.batches;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.particles.ResourceData;
import com.badlogic.gdx.graphics.g3d.particles.renderers.ModelInstanceControllerRenderData;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Pool;
/*** This class is used to render particles having a model instance channel.
* @author Inferno */
public class ModelInstanceParticleBatch implements ParticleBatch<ModelInstanceControllerRenderData> {
Array<ModelInstanceControllerRenderData> controllersRenderData;
int bufferedParticlesCount;
public ModelInstanceParticleBatch () {
controllersRenderData = new Array<ModelInstanceControllerRenderData>(false, 5);
}
@Override
public void getRenderables (Array<Renderable> renderables, Pool<Renderable> pool) {
for (ModelInstanceControllerRenderData data : controllersRenderData) {
for (int i = 0, count = data.controller.particles.size; i < count; ++i) {
data.modelInstanceChannel.data[i].getRenderables(renderables, pool);
}
}
}
public int getBufferedCount () {
return bufferedParticlesCount;
}
@Override
public void begin () {
controllersRenderData.clear();
bufferedParticlesCount = 0;
}
@Override
public void end () {
}
@Override
public void draw (ModelInstanceControllerRenderData data) {
controllersRenderData.add(data);
bufferedParticlesCount += data.controller.particles.size;
}
@Override
public void save (AssetManager manager, ResourceData assetDependencyData) {
}
@Override
public void load (AssetManager manager, ResourceData assetDependencyData) {
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./tests/gdx-tests/src/com/badlogic/gdx/tests/gles3/PixelBufferObjectTest.java |
package com.badlogic.gdx.tests.gles3;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.tests.utils.GdxTestConfig;
import com.badlogic.gdx.utils.BufferUtils;
@GdxTestConfig(requireGL30 = true)
public class PixelBufferObjectTest extends GdxTest {
static class PBOUpload {
private Texture texture;
protected Lock lock;
protected Pixmap pixmap;
protected int pixmapSizeBytes;
protected boolean pixmapReady;
protected boolean textureReady;
protected boolean pboTransferComplete;
protected Buffer mappedBuffer;
protected int pboHandle;
private final boolean useSubImage;
public PBOUpload (boolean useSubImage) {
super();
this.useSubImage = useSubImage;
}
public void start () {
lock = new ReentrantLock();
lock.lock();
new Thread(new Runnable() {
@Override
public void run () {
// load the pixmap in order to get header information
pixmap = new Pixmap(Gdx.files.internal("data/badlogic.jpg"));
pixmapSizeBytes = pixmap.getWidth() * pixmap.getHeight() * 3;
pixmapReady = true;
// wait for PBO initialization (need to be done in GLThread)
lock.lock();
// Transfer data from pixmap to PBO
ByteBuffer data = pixmap.getPixels();
data.rewind();
BufferUtils.copy(data, mappedBuffer, pixmapSizeBytes);
pboTransferComplete = true;
}
}).start();
}
public void update () {
// first step: once we get pixmap size, we can create both texture and PBO
if (pixmapReady && texture == null) {
texture = new Texture(pixmap.getWidth(), pixmap.getHeight(), pixmap.getFormat());
pboHandle = Gdx.gl.glGenBuffer();
Gdx.gl.glBindBuffer(GL30.GL_PIXEL_UNPACK_BUFFER, pboHandle);
Gdx.gl.glBufferData(GL30.GL_PIXEL_UNPACK_BUFFER, pixmapSizeBytes, null, GL30.GL_STREAM_DRAW);
mappedBuffer = Gdx.gl30.glMapBufferRange(GL30.GL_PIXEL_UNPACK_BUFFER, 0, pixmapSizeBytes,
GL30.GL_MAP_WRITE_BIT | GL30.GL_MAP_UNSYNCHRONIZED_BIT);
Gdx.gl.glBindBuffer(GL30.GL_PIXEL_UNPACK_BUFFER, 0);
lock.unlock();
}
// second step: once async transfer is complete, we can transfer to the texture and cleanup
if (!textureReady && pboTransferComplete) {
// transfer data to texture (GL Thread)
Gdx.gl.glBindBuffer(GL30.GL_PIXEL_UNPACK_BUFFER, pboHandle);
Gdx.gl30.glUnmapBuffer(GL30.GL_PIXEL_UNPACK_BUFFER);
Gdx.gl.glBindTexture(GL20.GL_TEXTURE_2D, texture.getTextureObjectHandle());
// for testing purpose: use glTexSubImage2D or glTexImage2D
if (useSubImage) {
Gdx.gl30.glTexSubImage2D(GL20.GL_TEXTURE_2D, 0, 0, 0, pixmap.getWidth(), pixmap.getHeight(), pixmap.getGLFormat(),
pixmap.getGLType(), 0);
} else {
Gdx.gl30.glTexImage2D(GL20.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(),
0, pixmap.getGLFormat(), pixmap.getGLType(), 0);
}
Gdx.gl.glBindTexture(GL20.GL_TEXTURE_2D, 0);
Gdx.gl.glBindBuffer(GL30.GL_PIXEL_UNPACK_BUFFER, 0);
// cleanup
mappedBuffer = null;
Gdx.gl.glDeleteBuffer(pboHandle);
pboHandle = 0;
pixmap.dispose();
pixmap = null;
textureReady = true;
}
}
public boolean isTextureReady () {
return textureReady;
}
public Texture getTexture () {
return texture;
}
}
private SpriteBatch batch;
private PBOUpload demo1, demo2;
@Override
public void create () {
batch = new SpriteBatch();
demo1 = new PBOUpload(false);
demo1.start();
demo2 = new PBOUpload(true);
demo2.start();
}
@Override
public void render () {
demo1.update();
demo2.update();
batch.begin();
if (demo1.isTextureReady()) {
batch.draw(demo1.getTexture(), 0, 0, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);
}
if (demo2.isTextureReady()) {
batch.draw(demo2.getTexture(), Gdx.graphics.getWidth() / 2, 0, Gdx.graphics.getWidth() / 2,
Gdx.graphics.getHeight() / 2);
}
batch.end();
}
}
|
package com.badlogic.gdx.tests.gles3;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.tests.utils.GdxTestConfig;
import com.badlogic.gdx.utils.BufferUtils;
@GdxTestConfig(requireGL30 = true)
public class PixelBufferObjectTest extends GdxTest {
static class PBOUpload {
private Texture texture;
protected Lock lock;
protected Pixmap pixmap;
protected int pixmapSizeBytes;
protected boolean pixmapReady;
protected boolean textureReady;
protected boolean pboTransferComplete;
protected Buffer mappedBuffer;
protected int pboHandle;
private final boolean useSubImage;
public PBOUpload (boolean useSubImage) {
super();
this.useSubImage = useSubImage;
}
public void start () {
lock = new ReentrantLock();
lock.lock();
new Thread(new Runnable() {
@Override
public void run () {
// load the pixmap in order to get header information
pixmap = new Pixmap(Gdx.files.internal("data/badlogic.jpg"));
pixmapSizeBytes = pixmap.getWidth() * pixmap.getHeight() * 3;
pixmapReady = true;
// wait for PBO initialization (need to be done in GLThread)
lock.lock();
// Transfer data from pixmap to PBO
ByteBuffer data = pixmap.getPixels();
data.rewind();
BufferUtils.copy(data, mappedBuffer, pixmapSizeBytes);
pboTransferComplete = true;
}
}).start();
}
public void update () {
// first step: once we get pixmap size, we can create both texture and PBO
if (pixmapReady && texture == null) {
texture = new Texture(pixmap.getWidth(), pixmap.getHeight(), pixmap.getFormat());
pboHandle = Gdx.gl.glGenBuffer();
Gdx.gl.glBindBuffer(GL30.GL_PIXEL_UNPACK_BUFFER, pboHandle);
Gdx.gl.glBufferData(GL30.GL_PIXEL_UNPACK_BUFFER, pixmapSizeBytes, null, GL30.GL_STREAM_DRAW);
mappedBuffer = Gdx.gl30.glMapBufferRange(GL30.GL_PIXEL_UNPACK_BUFFER, 0, pixmapSizeBytes,
GL30.GL_MAP_WRITE_BIT | GL30.GL_MAP_UNSYNCHRONIZED_BIT);
Gdx.gl.glBindBuffer(GL30.GL_PIXEL_UNPACK_BUFFER, 0);
lock.unlock();
}
// second step: once async transfer is complete, we can transfer to the texture and cleanup
if (!textureReady && pboTransferComplete) {
// transfer data to texture (GL Thread)
Gdx.gl.glBindBuffer(GL30.GL_PIXEL_UNPACK_BUFFER, pboHandle);
Gdx.gl30.glUnmapBuffer(GL30.GL_PIXEL_UNPACK_BUFFER);
Gdx.gl.glBindTexture(GL20.GL_TEXTURE_2D, texture.getTextureObjectHandle());
// for testing purpose: use glTexSubImage2D or glTexImage2D
if (useSubImage) {
Gdx.gl30.glTexSubImage2D(GL20.GL_TEXTURE_2D, 0, 0, 0, pixmap.getWidth(), pixmap.getHeight(), pixmap.getGLFormat(),
pixmap.getGLType(), 0);
} else {
Gdx.gl30.glTexImage2D(GL20.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(),
0, pixmap.getGLFormat(), pixmap.getGLType(), 0);
}
Gdx.gl.glBindTexture(GL20.GL_TEXTURE_2D, 0);
Gdx.gl.glBindBuffer(GL30.GL_PIXEL_UNPACK_BUFFER, 0);
// cleanup
mappedBuffer = null;
Gdx.gl.glDeleteBuffer(pboHandle);
pboHandle = 0;
pixmap.dispose();
pixmap = null;
textureReady = true;
}
}
public boolean isTextureReady () {
return textureReady;
}
public Texture getTexture () {
return texture;
}
}
private SpriteBatch batch;
private PBOUpload demo1, demo2;
@Override
public void create () {
batch = new SpriteBatch();
demo1 = new PBOUpload(false);
demo1.start();
demo2 = new PBOUpload(true);
demo2.start();
}
@Override
public void render () {
demo1.update();
demo2.update();
batch.begin();
if (demo1.isTextureReady()) {
batch.draw(demo1.getTexture(), 0, 0, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);
}
if (demo2.isTextureReady()) {
batch.draw(demo2.getTexture(), Gdx.graphics.getWidth() / 2, 0, Gdx.graphics.getWidth() / 2,
Gdx.graphics.getHeight() / 2);
}
batch.end();
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./backends/gdx-backends-gwt/src/com/badlogic/gwtref/client/Field.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gwtref.client;
import java.lang.annotation.Annotation;
import java.util.Arrays;
public class Field {
final String name;
final CachedTypeLookup enclosingType;
final CachedTypeLookup type;
final boolean isFinal;
final boolean isDefaultAccess;
final boolean isPrivate;
final boolean isProtected;
final boolean isPublic;
final boolean isStatic;
final boolean isTransient;
final boolean isVolatile;
final int getter;
final int setter;
final CachedTypeLookup[] elementTypes;
final Annotation[] annotations;
Field (String name, Class enclosingType, Class type, boolean isFinal, boolean isDefaultAccess, boolean isPrivate,
boolean isProtected, boolean isPublic, boolean isStatic, boolean isTransient, boolean isVolatile, int getter, int setter,
Class[] elementTypes, Annotation[] annotations) {
this.name = name;
this.enclosingType = new CachedTypeLookup(enclosingType);
this.type = new CachedTypeLookup(type);
this.isFinal = isFinal;
this.isDefaultAccess = isDefaultAccess;
this.isPrivate = isPrivate;
this.isProtected = isProtected;
this.isPublic = isPublic;
this.isStatic = isStatic;
this.isTransient = isTransient;
this.isVolatile = isVolatile;
this.getter = getter;
this.setter = setter;
CachedTypeLookup[] tmp = null;
if (elementTypes != null) {
tmp = new CachedTypeLookup[elementTypes.length];
for (int i = 0; i < tmp.length; i++) {
tmp[i] = new CachedTypeLookup(elementTypes[i]);
}
}
this.elementTypes = tmp;
this.annotations = annotations != null ? annotations : new Annotation[] {};
}
public Object get (Object obj) throws IllegalAccessException {
return ReflectionCache.getFieldValue(this, obj);
}
public void set (Object obj, Object value) throws IllegalAccessException {
ReflectionCache.setFieldValue(this, obj, value);
}
public Type getElementType (int index) {
if (elementTypes != null && index >= 0 && index < elementTypes.length) return elementTypes[index].getType();
return null;
}
public String getName () {
return name;
}
public Type getEnclosingType () {
return enclosingType.getType();
}
public Type getType () {
return type.getType();
}
public boolean isSynthetic () {
return false;
}
public boolean isFinal () {
return isFinal;
}
public boolean isDefaultAccess () {
return isDefaultAccess;
}
public boolean isPrivate () {
return isPrivate;
}
public boolean isProtected () {
return isProtected;
}
public boolean isPublic () {
return isPublic;
}
public boolean isStatic () {
return isStatic;
}
public boolean isTransient () {
return isTransient;
}
public boolean isVolatile () {
return isVolatile;
}
public Annotation[] getDeclaredAnnotations () {
return annotations;
}
@Override
public String toString () {
return "Field [name=" + name + ", enclosingType=" + enclosingType + ", type=" + type + ", isFinal=" + isFinal
+ ", isDefaultAccess=" + isDefaultAccess + ", isPrivate=" + isPrivate + ", isProtected=" + isProtected + ", isPublic="
+ isPublic + ", isStatic=" + isStatic + ", isTransient=" + isTransient + ", isVolatile=" + isVolatile + ", getter="
+ getter + ", setter=" + setter + ", elementTypes=" + Arrays.toString(elementTypes) + ", annotations="
+ Arrays.toString(annotations) + "]";
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gwtref.client;
import java.lang.annotation.Annotation;
import java.util.Arrays;
public class Field {
final String name;
final CachedTypeLookup enclosingType;
final CachedTypeLookup type;
final boolean isFinal;
final boolean isDefaultAccess;
final boolean isPrivate;
final boolean isProtected;
final boolean isPublic;
final boolean isStatic;
final boolean isTransient;
final boolean isVolatile;
final int getter;
final int setter;
final CachedTypeLookup[] elementTypes;
final Annotation[] annotations;
Field (String name, Class enclosingType, Class type, boolean isFinal, boolean isDefaultAccess, boolean isPrivate,
boolean isProtected, boolean isPublic, boolean isStatic, boolean isTransient, boolean isVolatile, int getter, int setter,
Class[] elementTypes, Annotation[] annotations) {
this.name = name;
this.enclosingType = new CachedTypeLookup(enclosingType);
this.type = new CachedTypeLookup(type);
this.isFinal = isFinal;
this.isDefaultAccess = isDefaultAccess;
this.isPrivate = isPrivate;
this.isProtected = isProtected;
this.isPublic = isPublic;
this.isStatic = isStatic;
this.isTransient = isTransient;
this.isVolatile = isVolatile;
this.getter = getter;
this.setter = setter;
CachedTypeLookup[] tmp = null;
if (elementTypes != null) {
tmp = new CachedTypeLookup[elementTypes.length];
for (int i = 0; i < tmp.length; i++) {
tmp[i] = new CachedTypeLookup(elementTypes[i]);
}
}
this.elementTypes = tmp;
this.annotations = annotations != null ? annotations : new Annotation[] {};
}
public Object get (Object obj) throws IllegalAccessException {
return ReflectionCache.getFieldValue(this, obj);
}
public void set (Object obj, Object value) throws IllegalAccessException {
ReflectionCache.setFieldValue(this, obj, value);
}
public Type getElementType (int index) {
if (elementTypes != null && index >= 0 && index < elementTypes.length) return elementTypes[index].getType();
return null;
}
public String getName () {
return name;
}
public Type getEnclosingType () {
return enclosingType.getType();
}
public Type getType () {
return type.getType();
}
public boolean isSynthetic () {
return false;
}
public boolean isFinal () {
return isFinal;
}
public boolean isDefaultAccess () {
return isDefaultAccess;
}
public boolean isPrivate () {
return isPrivate;
}
public boolean isProtected () {
return isProtected;
}
public boolean isPublic () {
return isPublic;
}
public boolean isStatic () {
return isStatic;
}
public boolean isTransient () {
return isTransient;
}
public boolean isVolatile () {
return isVolatile;
}
public Annotation[] getDeclaredAnnotations () {
return annotations;
}
@Override
public String toString () {
return "Field [name=" + name + ", enclosingType=" + enclosingType + ", type=" + type + ", isFinal=" + isFinal
+ ", isDefaultAccess=" + isDefaultAccess + ", isPrivate=" + isPrivate + ", isProtected=" + isProtected + ", isPublic="
+ isPublic + ", isStatic=" + isStatic + ", isTransient=" + isTransient + ", isVolatile=" + isVolatile + ", getter="
+ getter + ", setter=" + setter + ", elementTypes=" + Arrays.toString(elementTypes) + ", annotations="
+ Arrays.toString(annotations) + "]";
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btSortedOverlappingPairCache.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btSortedOverlappingPairCache extends btOverlappingPairCache {
private long swigCPtr;
protected btSortedOverlappingPairCache (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btSortedOverlappingPairCache_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btSortedOverlappingPairCache, normally you should not need this constructor it's intended for low-level
* usage. */
public btSortedOverlappingPairCache (long cPtr, boolean cMemoryOwn) {
this("btSortedOverlappingPairCache", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btSortedOverlappingPairCache_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btSortedOverlappingPairCache obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btSortedOverlappingPairCache(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public btSortedOverlappingPairCache () {
this(CollisionJNI.new_btSortedOverlappingPairCache(), true);
}
public boolean needsBroadphaseCollision (btBroadphaseProxy proxy0, btBroadphaseProxy proxy1) {
return CollisionJNI.btSortedOverlappingPairCache_needsBroadphaseCollision(swigCPtr, this, btBroadphaseProxy.getCPtr(proxy0),
proxy0, btBroadphaseProxy.getCPtr(proxy1), proxy1);
}
public btBroadphasePairArray getOverlappingPairArrayConst () {
return new btBroadphasePairArray(CollisionJNI.btSortedOverlappingPairCache_getOverlappingPairArrayConst(swigCPtr, this),
false);
}
public btOverlapFilterCallback getOverlapFilterCallback () {
long cPtr = CollisionJNI.btSortedOverlappingPairCache_getOverlapFilterCallback(swigCPtr, this);
return (cPtr == 0) ? null : new btOverlapFilterCallback(cPtr, false);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btSortedOverlappingPairCache extends btOverlappingPairCache {
private long swigCPtr;
protected btSortedOverlappingPairCache (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btSortedOverlappingPairCache_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btSortedOverlappingPairCache, normally you should not need this constructor it's intended for low-level
* usage. */
public btSortedOverlappingPairCache (long cPtr, boolean cMemoryOwn) {
this("btSortedOverlappingPairCache", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btSortedOverlappingPairCache_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btSortedOverlappingPairCache obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btSortedOverlappingPairCache(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public btSortedOverlappingPairCache () {
this(CollisionJNI.new_btSortedOverlappingPairCache(), true);
}
public boolean needsBroadphaseCollision (btBroadphaseProxy proxy0, btBroadphaseProxy proxy1) {
return CollisionJNI.btSortedOverlappingPairCache_needsBroadphaseCollision(swigCPtr, this, btBroadphaseProxy.getCPtr(proxy0),
proxy0, btBroadphaseProxy.getCPtr(proxy1), proxy1);
}
public btBroadphasePairArray getOverlappingPairArrayConst () {
return new btBroadphasePairArray(CollisionJNI.btSortedOverlappingPairCache_getOverlappingPairArrayConst(swigCPtr, this),
false);
}
public btOverlapFilterCallback getOverlapFilterCallback () {
long cPtr = CollisionJNI.btSortedOverlappingPairCache_getOverlapFilterCallback(swigCPtr, this);
return (cPtr == 0) ? null : new btOverlapFilterCallback(cPtr, false);
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./extensions/gdx-bullet/jni/src/bullet/BulletCollision/NarrowPhaseCollision/btRaycastCallback.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
//#include <stdio.h>
#include "BulletCollision/CollisionShapes/btConvexShape.h"
#include "BulletCollision/CollisionShapes/btTriangleShape.h"
#include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h"
#include "BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"
#include "btRaycastCallback.h"
btTriangleRaycastCallback::btTriangleRaycastCallback(const btVector3& from,const btVector3& to, unsigned int flags)
:
m_from(from),
m_to(to),
//@BP Mod
m_flags(flags),
m_hitFraction(btScalar(1.))
{
}
void btTriangleRaycastCallback::processTriangle(btVector3* triangle,int partId, int triangleIndex)
{
const btVector3 &vert0=triangle[0];
const btVector3 &vert1=triangle[1];
const btVector3 &vert2=triangle[2];
btVector3 v10; v10 = vert1 - vert0 ;
btVector3 v20; v20 = vert2 - vert0 ;
btVector3 triangleNormal; triangleNormal = v10.cross( v20 );
const btScalar dist = vert0.dot(triangleNormal);
btScalar dist_a = triangleNormal.dot(m_from) ;
dist_a-= dist;
btScalar dist_b = triangleNormal.dot(m_to);
dist_b -= dist;
if ( dist_a * dist_b >= btScalar(0.0) )
{
return ; // same sign
}
if (((m_flags & kF_FilterBackfaces) != 0) && (dist_a <= btScalar(0.0)))
{
// Backface, skip check
return;
}
const btScalar proj_length=dist_a-dist_b;
const btScalar distance = (dist_a)/(proj_length);
// Now we have the intersection point on the plane, we'll see if it's inside the triangle
// Add an epsilon as a tolerance for the raycast,
// in case the ray hits exacly on the edge of the triangle.
// It must be scaled for the triangle size.
if(distance < m_hitFraction)
{
btScalar edge_tolerance =triangleNormal.length2();
edge_tolerance *= btScalar(-0.0001);
btVector3 point; point.setInterpolate3( m_from, m_to, distance);
{
btVector3 v0p; v0p = vert0 - point;
btVector3 v1p; v1p = vert1 - point;
btVector3 cp0; cp0 = v0p.cross( v1p );
if ( (btScalar)(cp0.dot(triangleNormal)) >=edge_tolerance)
{
btVector3 v2p; v2p = vert2 - point;
btVector3 cp1;
cp1 = v1p.cross( v2p);
if ( (btScalar)(cp1.dot(triangleNormal)) >=edge_tolerance)
{
btVector3 cp2;
cp2 = v2p.cross(v0p);
if ( (btScalar)(cp2.dot(triangleNormal)) >=edge_tolerance)
{
//@BP Mod
// Triangle normal isn't normalized
triangleNormal.normalize();
//@BP Mod - Allow for unflipped normal when raycasting against backfaces
if (((m_flags & kF_KeepUnflippedNormal) == 0) && (dist_a <= btScalar(0.0)))
{
m_hitFraction = reportHit(-triangleNormal,distance,partId,triangleIndex);
}
else
{
m_hitFraction = reportHit(triangleNormal,distance,partId,triangleIndex);
}
}
}
}
}
}
}
btTriangleConvexcastCallback::btTriangleConvexcastCallback (const btConvexShape* convexShape, const btTransform& convexShapeFrom, const btTransform& convexShapeTo, const btTransform& triangleToWorld, const btScalar triangleCollisionMargin)
{
m_convexShape = convexShape;
m_convexShapeFrom = convexShapeFrom;
m_convexShapeTo = convexShapeTo;
m_triangleToWorld = triangleToWorld;
m_hitFraction = 1.0f;
m_triangleCollisionMargin = triangleCollisionMargin;
m_allowedPenetration = 0.f;
}
void
btTriangleConvexcastCallback::processTriangle (btVector3* triangle, int partId, int triangleIndex)
{
btTriangleShape triangleShape (triangle[0], triangle[1], triangle[2]);
triangleShape.setMargin(m_triangleCollisionMargin);
btVoronoiSimplexSolver simplexSolver;
btGjkEpaPenetrationDepthSolver gjkEpaPenetrationSolver;
//#define USE_SUBSIMPLEX_CONVEX_CAST 1
//if you reenable USE_SUBSIMPLEX_CONVEX_CAST see commented out code below
#ifdef USE_SUBSIMPLEX_CONVEX_CAST
btSubsimplexConvexCast convexCaster(m_convexShape, &triangleShape, &simplexSolver);
#else
//btGjkConvexCast convexCaster(m_convexShape,&triangleShape,&simplexSolver);
btContinuousConvexCollision convexCaster(m_convexShape,&triangleShape,&simplexSolver,&gjkEpaPenetrationSolver);
#endif //#USE_SUBSIMPLEX_CONVEX_CAST
btConvexCast::CastResult castResult;
castResult.m_fraction = btScalar(1.);
castResult.m_allowedPenetration = m_allowedPenetration;
if (convexCaster.calcTimeOfImpact(m_convexShapeFrom,m_convexShapeTo,m_triangleToWorld, m_triangleToWorld, castResult))
{
//add hit
if (castResult.m_normal.length2() > btScalar(0.0001))
{
if (castResult.m_fraction < m_hitFraction)
{
/* btContinuousConvexCast's normal is already in world space */
/*
#ifdef USE_SUBSIMPLEX_CONVEX_CAST
//rotate normal into worldspace
castResult.m_normal = m_convexShapeFrom.getBasis() * castResult.m_normal;
#endif //USE_SUBSIMPLEX_CONVEX_CAST
*/
castResult.m_normal.normalize();
reportHit (castResult.m_normal,
castResult.m_hitPoint,
castResult.m_fraction,
partId,
triangleIndex);
}
}
}
}
| /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
//#include <stdio.h>
#include "BulletCollision/CollisionShapes/btConvexShape.h"
#include "BulletCollision/CollisionShapes/btTriangleShape.h"
#include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h"
#include "BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"
#include "btRaycastCallback.h"
btTriangleRaycastCallback::btTriangleRaycastCallback(const btVector3& from,const btVector3& to, unsigned int flags)
:
m_from(from),
m_to(to),
//@BP Mod
m_flags(flags),
m_hitFraction(btScalar(1.))
{
}
void btTriangleRaycastCallback::processTriangle(btVector3* triangle,int partId, int triangleIndex)
{
const btVector3 &vert0=triangle[0];
const btVector3 &vert1=triangle[1];
const btVector3 &vert2=triangle[2];
btVector3 v10; v10 = vert1 - vert0 ;
btVector3 v20; v20 = vert2 - vert0 ;
btVector3 triangleNormal; triangleNormal = v10.cross( v20 );
const btScalar dist = vert0.dot(triangleNormal);
btScalar dist_a = triangleNormal.dot(m_from) ;
dist_a-= dist;
btScalar dist_b = triangleNormal.dot(m_to);
dist_b -= dist;
if ( dist_a * dist_b >= btScalar(0.0) )
{
return ; // same sign
}
if (((m_flags & kF_FilterBackfaces) != 0) && (dist_a <= btScalar(0.0)))
{
// Backface, skip check
return;
}
const btScalar proj_length=dist_a-dist_b;
const btScalar distance = (dist_a)/(proj_length);
// Now we have the intersection point on the plane, we'll see if it's inside the triangle
// Add an epsilon as a tolerance for the raycast,
// in case the ray hits exacly on the edge of the triangle.
// It must be scaled for the triangle size.
if(distance < m_hitFraction)
{
btScalar edge_tolerance =triangleNormal.length2();
edge_tolerance *= btScalar(-0.0001);
btVector3 point; point.setInterpolate3( m_from, m_to, distance);
{
btVector3 v0p; v0p = vert0 - point;
btVector3 v1p; v1p = vert1 - point;
btVector3 cp0; cp0 = v0p.cross( v1p );
if ( (btScalar)(cp0.dot(triangleNormal)) >=edge_tolerance)
{
btVector3 v2p; v2p = vert2 - point;
btVector3 cp1;
cp1 = v1p.cross( v2p);
if ( (btScalar)(cp1.dot(triangleNormal)) >=edge_tolerance)
{
btVector3 cp2;
cp2 = v2p.cross(v0p);
if ( (btScalar)(cp2.dot(triangleNormal)) >=edge_tolerance)
{
//@BP Mod
// Triangle normal isn't normalized
triangleNormal.normalize();
//@BP Mod - Allow for unflipped normal when raycasting against backfaces
if (((m_flags & kF_KeepUnflippedNormal) == 0) && (dist_a <= btScalar(0.0)))
{
m_hitFraction = reportHit(-triangleNormal,distance,partId,triangleIndex);
}
else
{
m_hitFraction = reportHit(triangleNormal,distance,partId,triangleIndex);
}
}
}
}
}
}
}
btTriangleConvexcastCallback::btTriangleConvexcastCallback (const btConvexShape* convexShape, const btTransform& convexShapeFrom, const btTransform& convexShapeTo, const btTransform& triangleToWorld, const btScalar triangleCollisionMargin)
{
m_convexShape = convexShape;
m_convexShapeFrom = convexShapeFrom;
m_convexShapeTo = convexShapeTo;
m_triangleToWorld = triangleToWorld;
m_hitFraction = 1.0f;
m_triangleCollisionMargin = triangleCollisionMargin;
m_allowedPenetration = 0.f;
}
void
btTriangleConvexcastCallback::processTriangle (btVector3* triangle, int partId, int triangleIndex)
{
btTriangleShape triangleShape (triangle[0], triangle[1], triangle[2]);
triangleShape.setMargin(m_triangleCollisionMargin);
btVoronoiSimplexSolver simplexSolver;
btGjkEpaPenetrationDepthSolver gjkEpaPenetrationSolver;
//#define USE_SUBSIMPLEX_CONVEX_CAST 1
//if you reenable USE_SUBSIMPLEX_CONVEX_CAST see commented out code below
#ifdef USE_SUBSIMPLEX_CONVEX_CAST
btSubsimplexConvexCast convexCaster(m_convexShape, &triangleShape, &simplexSolver);
#else
//btGjkConvexCast convexCaster(m_convexShape,&triangleShape,&simplexSolver);
btContinuousConvexCollision convexCaster(m_convexShape,&triangleShape,&simplexSolver,&gjkEpaPenetrationSolver);
#endif //#USE_SUBSIMPLEX_CONVEX_CAST
btConvexCast::CastResult castResult;
castResult.m_fraction = btScalar(1.);
castResult.m_allowedPenetration = m_allowedPenetration;
if (convexCaster.calcTimeOfImpact(m_convexShapeFrom,m_convexShapeTo,m_triangleToWorld, m_triangleToWorld, castResult))
{
//add hit
if (castResult.m_normal.length2() > btScalar(0.0001))
{
if (castResult.m_fraction < m_hitFraction)
{
/* btContinuousConvexCast's normal is already in world space */
/*
#ifdef USE_SUBSIMPLEX_CONVEX_CAST
//rotate normal into worldspace
castResult.m_normal = m_convexShapeFrom.getBasis() * castResult.m_normal;
#endif //USE_SUBSIMPLEX_CONVEX_CAST
*/
castResult.m_normal.normalize();
reportHit (castResult.m_normal,
castResult.m_hitPoint,
castResult.m_fraction,
partId,
triangleIndex);
}
}
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./extensions/gdx-box2d/gdx-box2d/src/com/badlogic/gdx/physics/box2d/joints/PrismaticJointDef.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.physics.box2d.joints;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.JointDef;
/** Prismatic joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses
* local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint
* translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when
* saving and loading a game.
* @warning at least one body should by dynamic with a non-fixed rotation. */
public class PrismaticJointDef extends JointDef {
public PrismaticJointDef () {
type = JointType.PrismaticJoint;
}
/** Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. */
public void initialize (Body bodyA, Body bodyB, Vector2 anchor, Vector2 axis) {
this.bodyA = bodyA;
this.bodyB = bodyB;
localAnchorA.set(bodyA.getLocalPoint(anchor));
localAnchorB.set(bodyB.getLocalPoint(anchor));
localAxisA.set(bodyA.getLocalVector(axis));
referenceAngle = bodyB.getAngle() - bodyA.getAngle();
}
/** The local anchor point relative to body1's origin. */
public final Vector2 localAnchorA = new Vector2();
/** The local anchor point relative to body2's origin. */
public final Vector2 localAnchorB = new Vector2();
/** The local translation axis in body1. */
public final Vector2 localAxisA = new Vector2(1, 0);
/** The constrained angle between the bodies: body2_angle - body1_angle. */
public float referenceAngle = 0;
/** Enable/disable the joint limit. */
public boolean enableLimit = false;
/** The lower translation limit, usually in meters. */
public float lowerTranslation = 0;
/** The upper translation limit, usually in meters. */
public float upperTranslation = 0;
/** Enable/disable the joint motor. */
public boolean enableMotor = false;
/** The maximum motor torque, usually in N-m. */
public float maxMotorForce = 0;
/** The desired motor speed in radians per second. */
public float motorSpeed = 0;
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.physics.box2d.joints;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.JointDef;
/** Prismatic joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses
* local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint
* translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when
* saving and loading a game.
* @warning at least one body should by dynamic with a non-fixed rotation. */
public class PrismaticJointDef extends JointDef {
public PrismaticJointDef () {
type = JointType.PrismaticJoint;
}
/** Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. */
public void initialize (Body bodyA, Body bodyB, Vector2 anchor, Vector2 axis) {
this.bodyA = bodyA;
this.bodyB = bodyB;
localAnchorA.set(bodyA.getLocalPoint(anchor));
localAnchorB.set(bodyB.getLocalPoint(anchor));
localAxisA.set(bodyA.getLocalVector(axis));
referenceAngle = bodyB.getAngle() - bodyA.getAngle();
}
/** The local anchor point relative to body1's origin. */
public final Vector2 localAnchorA = new Vector2();
/** The local anchor point relative to body2's origin. */
public final Vector2 localAnchorB = new Vector2();
/** The local translation axis in body1. */
public final Vector2 localAxisA = new Vector2(1, 0);
/** The constrained angle between the bodies: body2_angle - body1_angle. */
public float referenceAngle = 0;
/** Enable/disable the joint limit. */
public boolean enableLimit = false;
/** The lower translation limit, usually in meters. */
public float lowerTranslation = 0;
/** The upper translation limit, usually in meters. */
public float upperTranslation = 0;
/** Enable/disable the joint motor. */
public boolean enableMotor = false;
/** The maximum motor torque, usually in N-m. */
public float maxMotorForce = 0;
/** The desired motor speed in radians per second. */
public float motorSpeed = 0;
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./extensions/gdx-box2d/gdx-box2d/jni/Box2D/Dynamics/Contacts/b2PolygonContact.cpp | /*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Dynamics/Contacts/b2PolygonContact.h>
#include <Box2D/Common/b2BlockAllocator.h>
#include <Box2D/Collision/b2TimeOfImpact.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2Fixture.h>
#include <Box2D/Dynamics/b2WorldCallbacks.h>
#include <new>
using namespace std;
b2Contact* b2PolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator)
{
void* mem = allocator->Allocate(sizeof(b2PolygonContact));
return new (mem) b2PolygonContact(fixtureA, fixtureB);
}
void b2PolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator)
{
((b2PolygonContact*)contact)->~b2PolygonContact();
allocator->Free(contact, sizeof(b2PolygonContact));
}
b2PolygonContact::b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB)
: b2Contact(fixtureA, 0, fixtureB, 0)
{
b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon);
b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon);
}
void b2PolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB)
{
b2CollidePolygons( manifold,
(b2PolygonShape*)m_fixtureA->GetShape(), xfA,
(b2PolygonShape*)m_fixtureB->GetShape(), xfB);
}
| /*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Dynamics/Contacts/b2PolygonContact.h>
#include <Box2D/Common/b2BlockAllocator.h>
#include <Box2D/Collision/b2TimeOfImpact.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2Fixture.h>
#include <Box2D/Dynamics/b2WorldCallbacks.h>
#include <new>
using namespace std;
b2Contact* b2PolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator)
{
void* mem = allocator->Allocate(sizeof(b2PolygonContact));
return new (mem) b2PolygonContact(fixtureA, fixtureB);
}
void b2PolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator)
{
((b2PolygonContact*)contact)->~b2PolygonContact();
allocator->Free(contact, sizeof(b2PolygonContact));
}
b2PolygonContact::b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB)
: b2Contact(fixtureA, 0, fixtureB, 0)
{
b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon);
b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon);
}
void b2PolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB)
{
b2CollidePolygons( manifold,
(b2PolygonShape*)m_fixtureA->GetShape(), xfA,
(b2PolygonShape*)m_fixtureB->GetShape(), xfB);
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./extensions/gdx-box2d/gdx-box2d/src/com/badlogic/gdx/physics/box2d/ContactImpulse.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.physics.box2d;
/** Contact impulses for reporting. Impulses are used instead of forces because sub-step forces may approach infinity for rigid
* body collisions. These match up one-to-one with the contact points in b2Manifold.
* @author mzechner */
public class ContactImpulse {
// @off
/*JNI
#include <Box2D/Box2D.h>
*/
final World world;
long addr;
float[] tmp = new float[2];
final float[] normalImpulses = new float[2];
final float[] tangentImpulses = new float[2];
protected ContactImpulse (World world, long addr) {
this.world = world;
this.addr = addr;
}
public float[] getNormalImpulses () {
jniGetNormalImpulses(addr, normalImpulses);
return normalImpulses;
}
private native void jniGetNormalImpulses (long addr, float[] values); /*
b2ContactImpulse* contactImpulse = (b2ContactImpulse*)addr;
values[0] = contactImpulse->normalImpulses[0];
values[1] = contactImpulse->normalImpulses[1];
*/
public float[] getTangentImpulses () {
jniGetTangentImpulses(addr, tangentImpulses);
return tangentImpulses;
}
private native void jniGetTangentImpulses (long addr, float[] values); /*
b2ContactImpulse* contactImpulse = (b2ContactImpulse*)addr;
values[0] = contactImpulse->tangentImpulses[0];
values[1] = contactImpulse->tangentImpulses[1];
*/
public int getCount () {
return jniGetCount(addr);
}
private native int jniGetCount (long addr); /*
b2ContactImpulse* contactImpulse = (b2ContactImpulse*)addr;
return contactImpulse->count;
*/
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.physics.box2d;
/** Contact impulses for reporting. Impulses are used instead of forces because sub-step forces may approach infinity for rigid
* body collisions. These match up one-to-one with the contact points in b2Manifold.
* @author mzechner */
public class ContactImpulse {
// @off
/*JNI
#include <Box2D/Box2D.h>
*/
final World world;
long addr;
float[] tmp = new float[2];
final float[] normalImpulses = new float[2];
final float[] tangentImpulses = new float[2];
protected ContactImpulse (World world, long addr) {
this.world = world;
this.addr = addr;
}
public float[] getNormalImpulses () {
jniGetNormalImpulses(addr, normalImpulses);
return normalImpulses;
}
private native void jniGetNormalImpulses (long addr, float[] values); /*
b2ContactImpulse* contactImpulse = (b2ContactImpulse*)addr;
values[0] = contactImpulse->normalImpulses[0];
values[1] = contactImpulse->normalImpulses[1];
*/
public float[] getTangentImpulses () {
jniGetTangentImpulses(addr, tangentImpulses);
return tangentImpulses;
}
private native void jniGetTangentImpulses (long addr, float[] values); /*
b2ContactImpulse* contactImpulse = (b2ContactImpulse*)addr;
values[0] = contactImpulse->tangentImpulses[0];
values[1] = contactImpulse->tangentImpulses[1];
*/
public int getCount () {
return jniGetCount(addr);
}
private native int jniGetCount (long addr); /*
b2ContactImpulse* contactImpulse = (b2ContactImpulse*)addr;
return contactImpulse->count;
*/
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./backends/gdx-backend-robovm/src/com/badlogic/gdx/backends/iosrobovm/custom/UIAccelerometerDelegate.java | /*
* Copyright (C) 2014 Trillian Mobile AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.badlogic.gdx.backends.iosrobovm.custom;
/*<imports>*/
import org.robovm.objc.annotation.*;
import org.robovm.apple.foundation.*;
/*</imports>*/
/*<javadoc>*/
/*</javadoc>*/
/*<annotations>*//*</annotations>*/
/*<visibility>*/public/* </visibility> */ interface /* <name> */ UIAccelerometerDelegate/* </name> */
/* <implements> */extends NSObjectProtocol/* </implements> */ {
/* <ptr> */
/* </ptr> */
/* <bind> */
/* </bind> */
/* <constants> *//* </constants> */
/* <properties> */
/* </properties> */
/* <methods> */
/** @since Available in iOS 2.0 and later.
* @deprecated Deprecated in iOS 5.0. */
@Deprecated
@Method(selector = "accelerometer:didAccelerate:")
void didAccelerate (UIAccelerometer accelerometer, UIAcceleration acceleration);
/* </methods> */
/* <adapter> */
/* </adapter> */
}
| /*
* Copyright (C) 2014 Trillian Mobile AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.badlogic.gdx.backends.iosrobovm.custom;
/*<imports>*/
import org.robovm.objc.annotation.*;
import org.robovm.apple.foundation.*;
/*</imports>*/
/*<javadoc>*/
/*</javadoc>*/
/*<annotations>*//*</annotations>*/
/*<visibility>*/public/* </visibility> */ interface /* <name> */ UIAccelerometerDelegate/* </name> */
/* <implements> */extends NSObjectProtocol/* </implements> */ {
/* <ptr> */
/* </ptr> */
/* <bind> */
/* </bind> */
/* <constants> *//* </constants> */
/* <properties> */
/* </properties> */
/* <methods> */
/** @since Available in iOS 2.0 and later.
* @deprecated Deprecated in iOS 5.0. */
@Deprecated
@Method(selector = "accelerometer:didAccelerate:")
void didAccelerate (UIAccelerometer accelerometer, UIAcceleration acceleration);
/* </methods> */
/* <adapter> */
/* </adapter> */
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/utils/reflect/ClassReflection.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.utils.reflect;
import java.lang.annotation.Inherited;
import com.badlogic.gwtref.client.ReflectionCache;
import com.badlogic.gwtref.client.Type;
/** Utilities for Class reflection.
* @author nexsoftware */
public final class ClassReflection {
/** Returns the Class object associated with the class or interface with the supplied string name. */
static public Class forName (String name) throws ReflectionException {
try {
return ReflectionCache.forName(name).getClassOfType();
} catch (ClassNotFoundException e) {
throw new ReflectionException("Class not found: " + name, e);
}
}
/** Returns the simple name of the underlying class as supplied in the source code. */
static public String getSimpleName (Class c) {
return c.getSimpleName();
}
/** Determines if the supplied Object is assignment-compatible with the object represented by supplied Class. */
static public boolean isInstance (Class c, Object obj) {
return obj != null && isAssignableFrom(c, obj.getClass());
}
/** Determines if the class or interface represented by first Class parameter is either the same as, or is a superclass or
* superinterface of, the class or interface represented by the second Class parameter. */
static public boolean isAssignableFrom (Class c1, Class c2) {
Type c1Type = ReflectionCache.getType(c1);
Type c2Type = ReflectionCache.getType(c2);
return c1Type.isAssignableFrom(c2Type);
}
/** Returns true if the class or interface represented by the supplied Class is a member class. */
static public boolean isMemberClass (Class c) {
return ReflectionCache.getType(c).isMemberClass();
}
/** Returns true if the class or interface represented by the supplied Class is a static class. */
static public boolean isStaticClass (Class c) {
return ReflectionCache.getType(c).isStatic();
}
/** Determines if the supplied Class object represents an array class. */
static public boolean isArray (Class c) {
return ReflectionCache.getType(c).isArray();
}
/** Determines if the supplied Class object represents a primitive type. */
static public boolean isPrimitive (Class c) {
return ReflectionCache.getType(c).isPrimitive();
}
/** Determines if the supplied Class object represents an enum type. */
static public boolean isEnum (Class c) {
return ReflectionCache.getType(c).isEnum();
}
/** Determines if the supplied Class object represents an annotation type. */
static public boolean isAnnotation (Class c) {
return ReflectionCache.getType(c).isAnnotation();
}
/** Determines if the supplied Class object represents an interface type. */
static public boolean isInterface (Class c) {
return ReflectionCache.getType(c).isInterface();
}
/** Determines if the supplied Class object represents an abstract type. */
static public boolean isAbstract (Class c) {
return ReflectionCache.getType(c).isAbstract();
}
/** Creates a new instance of the class represented by the supplied Class. */
static public <T> T newInstance (Class<T> c) throws ReflectionException {
try {
return (T)ReflectionCache.getType(c).newInstance();
} catch (NoSuchMethodException e) {
throw new ReflectionException("Could not use default constructor of " + c.getName(), e);
}
}
/** Returns the Class representing the component type of an array. If this class does not represent an array class this method
* returns null. */
static public Class getComponentType (Class c) {
return ReflectionCache.getType(c).getComponentType();
}
/** Returns an array of {@link Constructor} containing the public constructors of the class represented by the supplied
* Class. */
static public Constructor[] getConstructors (Class c) {
com.badlogic.gwtref.client.Constructor[] constructors = ReflectionCache.getType(c).getConstructors();
Constructor[] result = new Constructor[constructors.length];
for (int i = 0, j = constructors.length; i < j; i++) {
result[i] = new Constructor(constructors[i]);
}
return result;
}
/** Returns a {@link Constructor} that represents the public constructor for the supplied class which takes the supplied
* parameter types. */
static public Constructor getConstructor (Class c, Class... parameterTypes) throws ReflectionException {
try {
return new Constructor(ReflectionCache.getType(c).getConstructor(parameterTypes));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting constructor for class: " + c.getName(), e);
} catch (NoSuchMethodException e) {
throw new ReflectionException("Constructor not found for class: " + c.getName(), e);
}
}
/** Returns a {@link Constructor} that represents the constructor for the supplied class which takes the supplied parameter
* types. */
static public Constructor getDeclaredConstructor (Class c, Class... parameterTypes) throws ReflectionException {
try {
return new Constructor(ReflectionCache.getType(c).getDeclaredConstructor(parameterTypes));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting constructor for class: " + c.getName(), e);
} catch (NoSuchMethodException e) {
throw new ReflectionException("Constructor not found for class: " + c.getName(), e);
}
}
/** Returns the elements of this enum class or null if this Class object does not represent an enum type. */
static public Object[] getEnumConstants (Class c) {
return ReflectionCache.getType(c).getEnumConstants();
}
/** Returns an array of {@link Method} containing the public member methods of the class represented by the supplied Class. */
static public Method[] getMethods (Class c) {
com.badlogic.gwtref.client.Method[] methods = ReflectionCache.getType(c).getMethods();
Method[] result = new Method[methods.length];
for (int i = 0, j = methods.length; i < j; i++) {
result[i] = new Method(methods[i]);
}
return result;
}
/** Returns a {@link Method} that represents the public member method for the supplied class which takes the supplied parameter
* types. */
static public Method getMethod (Class c, String name, Class... parameterTypes) throws ReflectionException {
try {
return new Method(ReflectionCache.getType(c).getMethod(name, parameterTypes));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting method: " + name + ", for class: " + c.getName(), e);
} catch (NoSuchMethodException e) {
throw new ReflectionException("Method not found: " + name + ", for class: " + c.getName(), e);
}
}
/** Returns an array of {@link Method} containing the methods declared by the class represented by the supplied Class. */
static public Method[] getDeclaredMethods (Class c) {
com.badlogic.gwtref.client.Method[] methods = ReflectionCache.getType(c).getDeclaredMethods();
Method[] result = new Method[methods.length];
for (int i = 0, j = methods.length; i < j; i++) {
result[i] = new Method(methods[i]);
}
return result;
}
/** Returns a {@link Method} that represents the method declared by the supplied class which takes the supplied parameter
* types. */
static public Method getDeclaredMethod (Class c, String name, Class... parameterTypes) throws ReflectionException {
try {
return new Method(ReflectionCache.getType(c).getDeclaredMethod(name, parameterTypes));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting method: " + name + ", for class: " + c.getName(), e);
} catch (NoSuchMethodException e) {
throw new ReflectionException("Method not found: " + name + ", for class: " + c.getName(), e);
}
}
/** Returns an array of {@link Field} containing the public fields of the class represented by the supplied Class. */
static public Field[] getFields (Class c) {
com.badlogic.gwtref.client.Field[] fields = ReflectionCache.getType(c).getFields();
Field[] result = new Field[fields.length];
for (int i = 0, j = fields.length; i < j; i++) {
result[i] = new Field(fields[i]);
}
return result;
}
/** Returns a {@link Field} that represents the specified public member field for the supplied class. */
static public Field getField (Class c, String name) throws ReflectionException {
try {
return new Field(ReflectionCache.getType(c).getField(name));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting field: " + name + ", for class: " + c.getName(), e);
} catch (NoSuchFieldException e) {
throw new ReflectionException("Field not found: " + name + ", for class: " + c.getName(), e);
}
}
/** Returns an array of {@link Field} objects reflecting all the fields declared by the supplied class. */
static public Field[] getDeclaredFields (Class c) {
com.badlogic.gwtref.client.Field[] fields = ReflectionCache.getType(c).getDeclaredFields();
Field[] result = new Field[fields.length];
for (int i = 0, j = fields.length; i < j; i++) {
result[i] = new Field(fields[i]);
}
return result;
}
/** Returns a {@link Field} that represents the specified declared field for the supplied class. */
static public Field getDeclaredField (Class c, String name) throws ReflectionException {
try {
return new Field(ReflectionCache.getType(c).getDeclaredField(name));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting field: " + name + ", for class: " + c.getName(), e);
} catch (NoSuchFieldException e) {
throw new ReflectionException("Field not found: " + name + ", for class: " + c.getName(), e);
}
}
/** Returns true if the supplied class has an annotation of the given type. */
static public boolean isAnnotationPresent (Class c, Class<? extends java.lang.annotation.Annotation> annotationType) {
Annotation[] annotations = getAnnotations(c);
for (Annotation annotation : annotations) {
if (annotation.getAnnotationType().equals(annotationType)) return true;
}
return false;
}
/** Returns an array of {@link Annotation} objects reflecting all annotations declared by the supplied class, and inherited
* from its superclass. Returns an empty array if there are none. */
static public Annotation[] getAnnotations (Class c) {
Type declType = ReflectionCache.getType(c);
java.lang.annotation.Annotation[] annotations = declType.getDeclaredAnnotations();
// annotations of supplied class
Annotation[] result = new Annotation[annotations.length];
for (int i = 0; i < annotations.length; i++) {
result[i] = new Annotation(annotations[i]);
}
// search super classes, until Object.class is reached
Type superType = declType.getSuperclass();
java.lang.annotation.Annotation[] superAnnotations;
while (!superType.getClassOfType().equals(Object.class)) {
superAnnotations = superType.getDeclaredAnnotations();
for (int i = 0; i < superAnnotations.length; i++) {
// check for annotation types marked as Inherited
Type annotationType = ReflectionCache.getType(superAnnotations[i].annotationType());
if (annotationType.getDeclaredAnnotation(Inherited.class) != null) {
// ignore duplicates
boolean duplicate = false;
for (Annotation annotation : result) {
if (annotation.getAnnotationType().equals(annotationType)) {
duplicate = true;
break;
}
}
// append to result set
if (!duplicate) {
Annotation[] copy = new Annotation[result.length + 1];
for (int j = 0; j < result.length; j++) {
copy[j] = result[j];
}
copy[result.length] = new Annotation(superAnnotations[i]);
result = copy;
}
}
}
superType = superType.getSuperclass();
}
return result;
}
/** Returns an {@link Annotation} object reflecting the annotation provided, or null of this class doesn't have, or doesn't
* inherit, such an annotation. This is a convenience function if the caller knows already which annotation type he's looking
* for. */
static public Annotation getAnnotation (Class c, Class<? extends java.lang.annotation.Annotation> annotationType) {
Annotation[] annotations = getAnnotations(c);
for (Annotation annotation : annotations) {
if (annotation.getAnnotationType().equals(annotationType)) return annotation;
}
return null;
}
/** Returns an array of {@link Annotation} objects reflecting all annotations declared by the supplied class, or an empty array
* if there are none. Does not include inherited annotations. */
static public Annotation[] getDeclaredAnnotations (Class c) {
java.lang.annotation.Annotation[] annotations = ReflectionCache.getType(c).getDeclaredAnnotations();
Annotation[] result = new Annotation[annotations.length];
for (int i = 0; i < annotations.length; i++) {
result[i] = new Annotation(annotations[i]);
}
return result;
}
/** Returns an {@link Annotation} object reflecting the annotation provided, or null of this class doesn't have such an
* annotation. This is a convenience function if the caller knows already which annotation type he's looking for. */
static public Annotation getDeclaredAnnotation (Class c, Class<? extends java.lang.annotation.Annotation> annotationType) {
java.lang.annotation.Annotation annotation = ReflectionCache.getType(c).getDeclaredAnnotation(annotationType);
if (annotation != null) return new Annotation(annotation);
return null;
}
static public Class[] getInterfaces (Class c) {
return ReflectionCache.getType(c).getInterfaces();
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.utils.reflect;
import java.lang.annotation.Inherited;
import com.badlogic.gwtref.client.ReflectionCache;
import com.badlogic.gwtref.client.Type;
/** Utilities for Class reflection.
* @author nexsoftware */
public final class ClassReflection {
/** Returns the Class object associated with the class or interface with the supplied string name. */
static public Class forName (String name) throws ReflectionException {
try {
return ReflectionCache.forName(name).getClassOfType();
} catch (ClassNotFoundException e) {
throw new ReflectionException("Class not found: " + name, e);
}
}
/** Returns the simple name of the underlying class as supplied in the source code. */
static public String getSimpleName (Class c) {
return c.getSimpleName();
}
/** Determines if the supplied Object is assignment-compatible with the object represented by supplied Class. */
static public boolean isInstance (Class c, Object obj) {
return obj != null && isAssignableFrom(c, obj.getClass());
}
/** Determines if the class or interface represented by first Class parameter is either the same as, or is a superclass or
* superinterface of, the class or interface represented by the second Class parameter. */
static public boolean isAssignableFrom (Class c1, Class c2) {
Type c1Type = ReflectionCache.getType(c1);
Type c2Type = ReflectionCache.getType(c2);
return c1Type.isAssignableFrom(c2Type);
}
/** Returns true if the class or interface represented by the supplied Class is a member class. */
static public boolean isMemberClass (Class c) {
return ReflectionCache.getType(c).isMemberClass();
}
/** Returns true if the class or interface represented by the supplied Class is a static class. */
static public boolean isStaticClass (Class c) {
return ReflectionCache.getType(c).isStatic();
}
/** Determines if the supplied Class object represents an array class. */
static public boolean isArray (Class c) {
return ReflectionCache.getType(c).isArray();
}
/** Determines if the supplied Class object represents a primitive type. */
static public boolean isPrimitive (Class c) {
return ReflectionCache.getType(c).isPrimitive();
}
/** Determines if the supplied Class object represents an enum type. */
static public boolean isEnum (Class c) {
return ReflectionCache.getType(c).isEnum();
}
/** Determines if the supplied Class object represents an annotation type. */
static public boolean isAnnotation (Class c) {
return ReflectionCache.getType(c).isAnnotation();
}
/** Determines if the supplied Class object represents an interface type. */
static public boolean isInterface (Class c) {
return ReflectionCache.getType(c).isInterface();
}
/** Determines if the supplied Class object represents an abstract type. */
static public boolean isAbstract (Class c) {
return ReflectionCache.getType(c).isAbstract();
}
/** Creates a new instance of the class represented by the supplied Class. */
static public <T> T newInstance (Class<T> c) throws ReflectionException {
try {
return (T)ReflectionCache.getType(c).newInstance();
} catch (NoSuchMethodException e) {
throw new ReflectionException("Could not use default constructor of " + c.getName(), e);
}
}
/** Returns the Class representing the component type of an array. If this class does not represent an array class this method
* returns null. */
static public Class getComponentType (Class c) {
return ReflectionCache.getType(c).getComponentType();
}
/** Returns an array of {@link Constructor} containing the public constructors of the class represented by the supplied
* Class. */
static public Constructor[] getConstructors (Class c) {
com.badlogic.gwtref.client.Constructor[] constructors = ReflectionCache.getType(c).getConstructors();
Constructor[] result = new Constructor[constructors.length];
for (int i = 0, j = constructors.length; i < j; i++) {
result[i] = new Constructor(constructors[i]);
}
return result;
}
/** Returns a {@link Constructor} that represents the public constructor for the supplied class which takes the supplied
* parameter types. */
static public Constructor getConstructor (Class c, Class... parameterTypes) throws ReflectionException {
try {
return new Constructor(ReflectionCache.getType(c).getConstructor(parameterTypes));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting constructor for class: " + c.getName(), e);
} catch (NoSuchMethodException e) {
throw new ReflectionException("Constructor not found for class: " + c.getName(), e);
}
}
/** Returns a {@link Constructor} that represents the constructor for the supplied class which takes the supplied parameter
* types. */
static public Constructor getDeclaredConstructor (Class c, Class... parameterTypes) throws ReflectionException {
try {
return new Constructor(ReflectionCache.getType(c).getDeclaredConstructor(parameterTypes));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting constructor for class: " + c.getName(), e);
} catch (NoSuchMethodException e) {
throw new ReflectionException("Constructor not found for class: " + c.getName(), e);
}
}
/** Returns the elements of this enum class or null if this Class object does not represent an enum type. */
static public Object[] getEnumConstants (Class c) {
return ReflectionCache.getType(c).getEnumConstants();
}
/** Returns an array of {@link Method} containing the public member methods of the class represented by the supplied Class. */
static public Method[] getMethods (Class c) {
com.badlogic.gwtref.client.Method[] methods = ReflectionCache.getType(c).getMethods();
Method[] result = new Method[methods.length];
for (int i = 0, j = methods.length; i < j; i++) {
result[i] = new Method(methods[i]);
}
return result;
}
/** Returns a {@link Method} that represents the public member method for the supplied class which takes the supplied parameter
* types. */
static public Method getMethod (Class c, String name, Class... parameterTypes) throws ReflectionException {
try {
return new Method(ReflectionCache.getType(c).getMethod(name, parameterTypes));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting method: " + name + ", for class: " + c.getName(), e);
} catch (NoSuchMethodException e) {
throw new ReflectionException("Method not found: " + name + ", for class: " + c.getName(), e);
}
}
/** Returns an array of {@link Method} containing the methods declared by the class represented by the supplied Class. */
static public Method[] getDeclaredMethods (Class c) {
com.badlogic.gwtref.client.Method[] methods = ReflectionCache.getType(c).getDeclaredMethods();
Method[] result = new Method[methods.length];
for (int i = 0, j = methods.length; i < j; i++) {
result[i] = new Method(methods[i]);
}
return result;
}
/** Returns a {@link Method} that represents the method declared by the supplied class which takes the supplied parameter
* types. */
static public Method getDeclaredMethod (Class c, String name, Class... parameterTypes) throws ReflectionException {
try {
return new Method(ReflectionCache.getType(c).getDeclaredMethod(name, parameterTypes));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting method: " + name + ", for class: " + c.getName(), e);
} catch (NoSuchMethodException e) {
throw new ReflectionException("Method not found: " + name + ", for class: " + c.getName(), e);
}
}
/** Returns an array of {@link Field} containing the public fields of the class represented by the supplied Class. */
static public Field[] getFields (Class c) {
com.badlogic.gwtref.client.Field[] fields = ReflectionCache.getType(c).getFields();
Field[] result = new Field[fields.length];
for (int i = 0, j = fields.length; i < j; i++) {
result[i] = new Field(fields[i]);
}
return result;
}
/** Returns a {@link Field} that represents the specified public member field for the supplied class. */
static public Field getField (Class c, String name) throws ReflectionException {
try {
return new Field(ReflectionCache.getType(c).getField(name));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting field: " + name + ", for class: " + c.getName(), e);
} catch (NoSuchFieldException e) {
throw new ReflectionException("Field not found: " + name + ", for class: " + c.getName(), e);
}
}
/** Returns an array of {@link Field} objects reflecting all the fields declared by the supplied class. */
static public Field[] getDeclaredFields (Class c) {
com.badlogic.gwtref.client.Field[] fields = ReflectionCache.getType(c).getDeclaredFields();
Field[] result = new Field[fields.length];
for (int i = 0, j = fields.length; i < j; i++) {
result[i] = new Field(fields[i]);
}
return result;
}
/** Returns a {@link Field} that represents the specified declared field for the supplied class. */
static public Field getDeclaredField (Class c, String name) throws ReflectionException {
try {
return new Field(ReflectionCache.getType(c).getDeclaredField(name));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting field: " + name + ", for class: " + c.getName(), e);
} catch (NoSuchFieldException e) {
throw new ReflectionException("Field not found: " + name + ", for class: " + c.getName(), e);
}
}
/** Returns true if the supplied class has an annotation of the given type. */
static public boolean isAnnotationPresent (Class c, Class<? extends java.lang.annotation.Annotation> annotationType) {
Annotation[] annotations = getAnnotations(c);
for (Annotation annotation : annotations) {
if (annotation.getAnnotationType().equals(annotationType)) return true;
}
return false;
}
/** Returns an array of {@link Annotation} objects reflecting all annotations declared by the supplied class, and inherited
* from its superclass. Returns an empty array if there are none. */
static public Annotation[] getAnnotations (Class c) {
Type declType = ReflectionCache.getType(c);
java.lang.annotation.Annotation[] annotations = declType.getDeclaredAnnotations();
// annotations of supplied class
Annotation[] result = new Annotation[annotations.length];
for (int i = 0; i < annotations.length; i++) {
result[i] = new Annotation(annotations[i]);
}
// search super classes, until Object.class is reached
Type superType = declType.getSuperclass();
java.lang.annotation.Annotation[] superAnnotations;
while (!superType.getClassOfType().equals(Object.class)) {
superAnnotations = superType.getDeclaredAnnotations();
for (int i = 0; i < superAnnotations.length; i++) {
// check for annotation types marked as Inherited
Type annotationType = ReflectionCache.getType(superAnnotations[i].annotationType());
if (annotationType.getDeclaredAnnotation(Inherited.class) != null) {
// ignore duplicates
boolean duplicate = false;
for (Annotation annotation : result) {
if (annotation.getAnnotationType().equals(annotationType)) {
duplicate = true;
break;
}
}
// append to result set
if (!duplicate) {
Annotation[] copy = new Annotation[result.length + 1];
for (int j = 0; j < result.length; j++) {
copy[j] = result[j];
}
copy[result.length] = new Annotation(superAnnotations[i]);
result = copy;
}
}
}
superType = superType.getSuperclass();
}
return result;
}
/** Returns an {@link Annotation} object reflecting the annotation provided, or null of this class doesn't have, or doesn't
* inherit, such an annotation. This is a convenience function if the caller knows already which annotation type he's looking
* for. */
static public Annotation getAnnotation (Class c, Class<? extends java.lang.annotation.Annotation> annotationType) {
Annotation[] annotations = getAnnotations(c);
for (Annotation annotation : annotations) {
if (annotation.getAnnotationType().equals(annotationType)) return annotation;
}
return null;
}
/** Returns an array of {@link Annotation} objects reflecting all annotations declared by the supplied class, or an empty array
* if there are none. Does not include inherited annotations. */
static public Annotation[] getDeclaredAnnotations (Class c) {
java.lang.annotation.Annotation[] annotations = ReflectionCache.getType(c).getDeclaredAnnotations();
Annotation[] result = new Annotation[annotations.length];
for (int i = 0; i < annotations.length; i++) {
result[i] = new Annotation(annotations[i]);
}
return result;
}
/** Returns an {@link Annotation} object reflecting the annotation provided, or null of this class doesn't have such an
* annotation. This is a convenience function if the caller knows already which annotation type he's looking for. */
static public Annotation getDeclaredAnnotation (Class c, Class<? extends java.lang.annotation.Annotation> annotationType) {
java.lang.annotation.Annotation annotation = ReflectionCache.getType(c).getDeclaredAnnotation(annotationType);
if (annotation != null) return new Annotation(annotation);
return null;
}
static public Class[] getInterfaces (Class c) {
return ReflectionCache.getType(c).getInterfaces();
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./gdx/src/com/badlogic/gdx/utils/Collections.java |
package com.badlogic.gdx.utils;
public class Collections {
/** When true, {@link Iterable#iterator()} for {@link Array}, {@link ObjectMap}, and other collections will allocate a new
* iterator for each invocation. When false, the iterator is reused and nested use will throw an exception. Default is
* false. */
public static boolean allocateIterators;
}
|
package com.badlogic.gdx.utils;
public class Collections {
/** When true, {@link Iterable#iterator()} for {@link Array}, {@link ObjectMap}, and other collections will allocate a new
* iterator for each invocation. When false, the iterator is reused and nested use will throw an exception. Default is
* false. */
public static boolean allocateIterators;
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./gdx/src/com/badlogic/gdx/math/Rectangle.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
******************************************************************************/
package com.badlogic.gdx.math;
import java.io.Serializable;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.NumberUtils;
import com.badlogic.gdx.utils.Scaling;
/** Encapsulates a 2D rectangle defined by its corner point in the bottom left and its extents in x (width) and y (height).
* @author [email protected] */
public class Rectangle implements Serializable, Shape2D {
/** Static temporary rectangle. Use with care! Use only when sure other code will not also use this. */
static public final Rectangle tmp = new Rectangle();
/** Static temporary rectangle. Use with care! Use only when sure other code will not also use this. */
static public final Rectangle tmp2 = new Rectangle();
private static final long serialVersionUID = 5733252015138115702L;
public float x, y;
public float width, height;
/** Constructs a new rectangle with all values set to zero */
public Rectangle () {
}
/** Constructs a new rectangle with the given corner point in the bottom left and dimensions.
* @param x The corner point x-coordinate
* @param y The corner point y-coordinate
* @param width The width
* @param height The height */
public Rectangle (float x, float y, float width, float height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/** Constructs a rectangle based on the given rectangle
* @param rect The rectangle */
public Rectangle (Rectangle rect) {
x = rect.x;
y = rect.y;
width = rect.width;
height = rect.height;
}
/** @param x bottom-left x coordinate
* @param y bottom-left y coordinate
* @param width width
* @param height height
* @return this rectangle for chaining */
public Rectangle set (float x, float y, float width, float height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
return this;
}
/** @return the x-coordinate of the bottom left corner */
public float getX () {
return x;
}
/** Sets the x-coordinate of the bottom left corner
* @param x The x-coordinate
* @return this rectangle for chaining */
public Rectangle setX (float x) {
this.x = x;
return this;
}
/** @return the y-coordinate of the bottom left corner */
public float getY () {
return y;
}
/** Sets the y-coordinate of the bottom left corner
* @param y The y-coordinate
* @return this rectangle for chaining */
public Rectangle setY (float y) {
this.y = y;
return this;
}
/** @return the width */
public float getWidth () {
return width;
}
/** Sets the width of this rectangle
* @param width The width
* @return this rectangle for chaining */
public Rectangle setWidth (float width) {
this.width = width;
return this;
}
/** @return the height */
public float getHeight () {
return height;
}
/** Sets the height of this rectangle
* @param height The height
* @return this rectangle for chaining */
public Rectangle setHeight (float height) {
this.height = height;
return this;
}
/** return the Vector2 with coordinates of this rectangle
* @param position The Vector2 */
public Vector2 getPosition (Vector2 position) {
return position.set(x, y);
}
/** Sets the x and y-coordinates of the bottom left corner from vector
* @param position The position vector
* @return this rectangle for chaining */
public Rectangle setPosition (Vector2 position) {
this.x = position.x;
this.y = position.y;
return this;
}
/** Sets the x and y-coordinates of the bottom left corner
* @param x The x-coordinate
* @param y The y-coordinate
* @return this rectangle for chaining */
public Rectangle setPosition (float x, float y) {
this.x = x;
this.y = y;
return this;
}
/** Sets the width and height of this rectangle
* @param width The width
* @param height The height
* @return this rectangle for chaining */
public Rectangle setSize (float width, float height) {
this.width = width;
this.height = height;
return this;
}
/** Sets the squared size of this rectangle
* @param sizeXY The size
* @return this rectangle for chaining */
public Rectangle setSize (float sizeXY) {
this.width = sizeXY;
this.height = sizeXY;
return this;
}
/** @return the Vector2 with size of this rectangle
* @param size The Vector2 */
public Vector2 getSize (Vector2 size) {
return size.set(width, height);
}
/** @param x point x coordinate
* @param y point y coordinate
* @return whether the point is contained in the rectangle */
public boolean contains (float x, float y) {
return this.x <= x && this.x + this.width >= x && this.y <= y && this.y + this.height >= y;
}
/** @param point The coordinates vector
* @return whether the point is contained in the rectangle */
public boolean contains (Vector2 point) {
return contains(point.x, point.y);
}
/** @param circle the circle
* @return whether the circle is contained in the rectangle */
public boolean contains (Circle circle) {
return (circle.x - circle.radius >= x) && (circle.x + circle.radius <= x + width) && (circle.y - circle.radius >= y)
&& (circle.y + circle.radius <= y + height);
}
/** @param rectangle the other {@link Rectangle}.
* @return whether the other rectangle is contained in this rectangle. */
public boolean contains (Rectangle rectangle) {
float xmin = rectangle.x;
float xmax = xmin + rectangle.width;
float ymin = rectangle.y;
float ymax = ymin + rectangle.height;
return ((xmin > x && xmin < x + width) && (xmax > x && xmax < x + width))
&& ((ymin > y && ymin < y + height) && (ymax > y && ymax < y + height));
}
/** @param r the other {@link Rectangle}
* @return whether this rectangle overlaps the other rectangle. */
public boolean overlaps (Rectangle r) {
return x < r.x + r.width && x + width > r.x && y < r.y + r.height && y + height > r.y;
}
/** Sets the values of the given rectangle to this rectangle.
* @param rect the other rectangle
* @return this rectangle for chaining */
public Rectangle set (Rectangle rect) {
this.x = rect.x;
this.y = rect.y;
this.width = rect.width;
this.height = rect.height;
return this;
}
/** Merges this rectangle with the other rectangle. The rectangle should not have negative width or negative height.
* @param rect the other rectangle
* @return this rectangle for chaining */
public Rectangle merge (Rectangle rect) {
float minX = Math.min(x, rect.x);
float maxX = Math.max(x + width, rect.x + rect.width);
x = minX;
width = maxX - minX;
float minY = Math.min(y, rect.y);
float maxY = Math.max(y + height, rect.y + rect.height);
y = minY;
height = maxY - minY;
return this;
}
/** Merges this rectangle with a point. The rectangle should not have negative width or negative height.
* @param x the x coordinate of the point
* @param y the y coordinate of the point
* @return this rectangle for chaining */
public Rectangle merge (float x, float y) {
float minX = Math.min(this.x, x);
float maxX = Math.max(this.x + width, x);
this.x = minX;
this.width = maxX - minX;
float minY = Math.min(this.y, y);
float maxY = Math.max(this.y + height, y);
this.y = minY;
this.height = maxY - minY;
return this;
}
/** Merges this rectangle with a point. The rectangle should not have negative width or negative height.
* @param vec the vector describing the point
* @return this rectangle for chaining */
public Rectangle merge (Vector2 vec) {
return merge(vec.x, vec.y);
}
/** Merges this rectangle with a list of points. The rectangle should not have negative width or negative height.
* @param vecs the vectors describing the points
* @return this rectangle for chaining */
public Rectangle merge (Vector2[] vecs) {
float minX = x;
float maxX = x + width;
float minY = y;
float maxY = y + height;
for (int i = 0; i < vecs.length; ++i) {
Vector2 v = vecs[i];
minX = Math.min(minX, v.x);
maxX = Math.max(maxX, v.x);
minY = Math.min(minY, v.y);
maxY = Math.max(maxY, v.y);
}
x = minX;
width = maxX - minX;
y = minY;
height = maxY - minY;
return this;
}
/** Calculates the aspect ratio ( width / height ) of this rectangle
* @return the aspect ratio of this rectangle. Returns Float.NaN if height is 0 to avoid ArithmeticException */
public float getAspectRatio () {
return (height == 0) ? Float.NaN : width / height;
}
/** Calculates the center of the rectangle. Results are located in the given Vector2
* @param vector the Vector2 to use
* @return the given vector with results stored inside */
public Vector2 getCenter (Vector2 vector) {
vector.x = x + width / 2;
vector.y = y + height / 2;
return vector;
}
/** Moves this rectangle so that its center point is located at a given position
* @param x the position's x
* @param y the position's y
* @return this for chaining */
public Rectangle setCenter (float x, float y) {
setPosition(x - width / 2, y - height / 2);
return this;
}
/** Moves this rectangle so that its center point is located at a given position
* @param position the position
* @return this for chaining */
public Rectangle setCenter (Vector2 position) {
setPosition(position.x - width / 2, position.y - height / 2);
return this;
}
/** Fits this rectangle around another rectangle while maintaining aspect ratio. This scales and centers the rectangle to the
* other rectangle (e.g. Having a camera translate and scale to show a given area)
* @param rect the other rectangle to fit this rectangle around
* @return this rectangle for chaining
* @see Scaling */
public Rectangle fitOutside (Rectangle rect) {
float ratio = getAspectRatio();
if (ratio > rect.getAspectRatio()) {
// Wider than tall
setSize(rect.height * ratio, rect.height);
} else {
// Taller than wide
setSize(rect.width, rect.width / ratio);
}
setPosition((rect.x + rect.width / 2) - width / 2, (rect.y + rect.height / 2) - height / 2);
return this;
}
/** Fits this rectangle into another rectangle while maintaining aspect ratio. This scales and centers the rectangle to the
* other rectangle (e.g. Scaling a texture within a arbitrary cell without squeezing)
* @param rect the other rectangle to fit this rectangle inside
* @return this rectangle for chaining
* @see Scaling */
public Rectangle fitInside (Rectangle rect) {
float ratio = getAspectRatio();
if (ratio < rect.getAspectRatio()) {
// Taller than wide
setSize(rect.height * ratio, rect.height);
} else {
// Wider than tall
setSize(rect.width, rect.width / ratio);
}
setPosition((rect.x + rect.width / 2) - width / 2, (rect.y + rect.height / 2) - height / 2);
return this;
}
/** Converts this {@code Rectangle} to a string in the format {@code [x,y,width,height]}.
* @return a string representation of this object. */
public String toString () {
return "[" + x + "," + y + "," + width + "," + height + "]";
}
/** Sets this {@code Rectangle} to the value represented by the specified string according to the format of
* {@link #toString()}.
* @param v the string.
* @return this rectangle for chaining */
public Rectangle fromString (String v) {
int s0 = v.indexOf(',', 1);
int s1 = v.indexOf(',', s0 + 1);
int s2 = v.indexOf(',', s1 + 1);
if (s0 != -1 && s1 != -1 && s2 != -1 && v.charAt(0) == '[' && v.charAt(v.length() - 1) == ']') {
try {
float x = Float.parseFloat(v.substring(1, s0));
float y = Float.parseFloat(v.substring(s0 + 1, s1));
float width = Float.parseFloat(v.substring(s1 + 1, s2));
float height = Float.parseFloat(v.substring(s2 + 1, v.length() - 1));
return this.set(x, y, width, height);
} catch (NumberFormatException ex) {
// Throw a GdxRuntimeException
}
}
throw new GdxRuntimeException("Malformed Rectangle: " + v);
}
public float area () {
return this.width * this.height;
}
public float perimeter () {
return 2 * (this.width + this.height);
}
public int hashCode () {
final int prime = 31;
int result = 1;
result = prime * result + NumberUtils.floatToRawIntBits(height);
result = prime * result + NumberUtils.floatToRawIntBits(width);
result = prime * result + NumberUtils.floatToRawIntBits(x);
result = prime * result + NumberUtils.floatToRawIntBits(y);
return result;
}
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Rectangle other = (Rectangle)obj;
if (NumberUtils.floatToRawIntBits(height) != NumberUtils.floatToRawIntBits(other.height)) return false;
if (NumberUtils.floatToRawIntBits(width) != NumberUtils.floatToRawIntBits(other.width)) return false;
if (NumberUtils.floatToRawIntBits(x) != NumberUtils.floatToRawIntBits(other.x)) return false;
if (NumberUtils.floatToRawIntBits(y) != NumberUtils.floatToRawIntBits(other.y)) return false;
return true;
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
******************************************************************************/
package com.badlogic.gdx.math;
import java.io.Serializable;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.NumberUtils;
import com.badlogic.gdx.utils.Scaling;
/** Encapsulates a 2D rectangle defined by its corner point in the bottom left and its extents in x (width) and y (height).
* @author [email protected] */
public class Rectangle implements Serializable, Shape2D {
/** Static temporary rectangle. Use with care! Use only when sure other code will not also use this. */
static public final Rectangle tmp = new Rectangle();
/** Static temporary rectangle. Use with care! Use only when sure other code will not also use this. */
static public final Rectangle tmp2 = new Rectangle();
private static final long serialVersionUID = 5733252015138115702L;
public float x, y;
public float width, height;
/** Constructs a new rectangle with all values set to zero */
public Rectangle () {
}
/** Constructs a new rectangle with the given corner point in the bottom left and dimensions.
* @param x The corner point x-coordinate
* @param y The corner point y-coordinate
* @param width The width
* @param height The height */
public Rectangle (float x, float y, float width, float height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/** Constructs a rectangle based on the given rectangle
* @param rect The rectangle */
public Rectangle (Rectangle rect) {
x = rect.x;
y = rect.y;
width = rect.width;
height = rect.height;
}
/** @param x bottom-left x coordinate
* @param y bottom-left y coordinate
* @param width width
* @param height height
* @return this rectangle for chaining */
public Rectangle set (float x, float y, float width, float height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
return this;
}
/** @return the x-coordinate of the bottom left corner */
public float getX () {
return x;
}
/** Sets the x-coordinate of the bottom left corner
* @param x The x-coordinate
* @return this rectangle for chaining */
public Rectangle setX (float x) {
this.x = x;
return this;
}
/** @return the y-coordinate of the bottom left corner */
public float getY () {
return y;
}
/** Sets the y-coordinate of the bottom left corner
* @param y The y-coordinate
* @return this rectangle for chaining */
public Rectangle setY (float y) {
this.y = y;
return this;
}
/** @return the width */
public float getWidth () {
return width;
}
/** Sets the width of this rectangle
* @param width The width
* @return this rectangle for chaining */
public Rectangle setWidth (float width) {
this.width = width;
return this;
}
/** @return the height */
public float getHeight () {
return height;
}
/** Sets the height of this rectangle
* @param height The height
* @return this rectangle for chaining */
public Rectangle setHeight (float height) {
this.height = height;
return this;
}
/** return the Vector2 with coordinates of this rectangle
* @param position The Vector2 */
public Vector2 getPosition (Vector2 position) {
return position.set(x, y);
}
/** Sets the x and y-coordinates of the bottom left corner from vector
* @param position The position vector
* @return this rectangle for chaining */
public Rectangle setPosition (Vector2 position) {
this.x = position.x;
this.y = position.y;
return this;
}
/** Sets the x and y-coordinates of the bottom left corner
* @param x The x-coordinate
* @param y The y-coordinate
* @return this rectangle for chaining */
public Rectangle setPosition (float x, float y) {
this.x = x;
this.y = y;
return this;
}
/** Sets the width and height of this rectangle
* @param width The width
* @param height The height
* @return this rectangle for chaining */
public Rectangle setSize (float width, float height) {
this.width = width;
this.height = height;
return this;
}
/** Sets the squared size of this rectangle
* @param sizeXY The size
* @return this rectangle for chaining */
public Rectangle setSize (float sizeXY) {
this.width = sizeXY;
this.height = sizeXY;
return this;
}
/** @return the Vector2 with size of this rectangle
* @param size The Vector2 */
public Vector2 getSize (Vector2 size) {
return size.set(width, height);
}
/** @param x point x coordinate
* @param y point y coordinate
* @return whether the point is contained in the rectangle */
public boolean contains (float x, float y) {
return this.x <= x && this.x + this.width >= x && this.y <= y && this.y + this.height >= y;
}
/** @param point The coordinates vector
* @return whether the point is contained in the rectangle */
public boolean contains (Vector2 point) {
return contains(point.x, point.y);
}
/** @param circle the circle
* @return whether the circle is contained in the rectangle */
public boolean contains (Circle circle) {
return (circle.x - circle.radius >= x) && (circle.x + circle.radius <= x + width) && (circle.y - circle.radius >= y)
&& (circle.y + circle.radius <= y + height);
}
/** @param rectangle the other {@link Rectangle}.
* @return whether the other rectangle is contained in this rectangle. */
public boolean contains (Rectangle rectangle) {
float xmin = rectangle.x;
float xmax = xmin + rectangle.width;
float ymin = rectangle.y;
float ymax = ymin + rectangle.height;
return ((xmin > x && xmin < x + width) && (xmax > x && xmax < x + width))
&& ((ymin > y && ymin < y + height) && (ymax > y && ymax < y + height));
}
/** @param r the other {@link Rectangle}
* @return whether this rectangle overlaps the other rectangle. */
public boolean overlaps (Rectangle r) {
return x < r.x + r.width && x + width > r.x && y < r.y + r.height && y + height > r.y;
}
/** Sets the values of the given rectangle to this rectangle.
* @param rect the other rectangle
* @return this rectangle for chaining */
public Rectangle set (Rectangle rect) {
this.x = rect.x;
this.y = rect.y;
this.width = rect.width;
this.height = rect.height;
return this;
}
/** Merges this rectangle with the other rectangle. The rectangle should not have negative width or negative height.
* @param rect the other rectangle
* @return this rectangle for chaining */
public Rectangle merge (Rectangle rect) {
float minX = Math.min(x, rect.x);
float maxX = Math.max(x + width, rect.x + rect.width);
x = minX;
width = maxX - minX;
float minY = Math.min(y, rect.y);
float maxY = Math.max(y + height, rect.y + rect.height);
y = minY;
height = maxY - minY;
return this;
}
/** Merges this rectangle with a point. The rectangle should not have negative width or negative height.
* @param x the x coordinate of the point
* @param y the y coordinate of the point
* @return this rectangle for chaining */
public Rectangle merge (float x, float y) {
float minX = Math.min(this.x, x);
float maxX = Math.max(this.x + width, x);
this.x = minX;
this.width = maxX - minX;
float minY = Math.min(this.y, y);
float maxY = Math.max(this.y + height, y);
this.y = minY;
this.height = maxY - minY;
return this;
}
/** Merges this rectangle with a point. The rectangle should not have negative width or negative height.
* @param vec the vector describing the point
* @return this rectangle for chaining */
public Rectangle merge (Vector2 vec) {
return merge(vec.x, vec.y);
}
/** Merges this rectangle with a list of points. The rectangle should not have negative width or negative height.
* @param vecs the vectors describing the points
* @return this rectangle for chaining */
public Rectangle merge (Vector2[] vecs) {
float minX = x;
float maxX = x + width;
float minY = y;
float maxY = y + height;
for (int i = 0; i < vecs.length; ++i) {
Vector2 v = vecs[i];
minX = Math.min(minX, v.x);
maxX = Math.max(maxX, v.x);
minY = Math.min(minY, v.y);
maxY = Math.max(maxY, v.y);
}
x = minX;
width = maxX - minX;
y = minY;
height = maxY - minY;
return this;
}
/** Calculates the aspect ratio ( width / height ) of this rectangle
* @return the aspect ratio of this rectangle. Returns Float.NaN if height is 0 to avoid ArithmeticException */
public float getAspectRatio () {
return (height == 0) ? Float.NaN : width / height;
}
/** Calculates the center of the rectangle. Results are located in the given Vector2
* @param vector the Vector2 to use
* @return the given vector with results stored inside */
public Vector2 getCenter (Vector2 vector) {
vector.x = x + width / 2;
vector.y = y + height / 2;
return vector;
}
/** Moves this rectangle so that its center point is located at a given position
* @param x the position's x
* @param y the position's y
* @return this for chaining */
public Rectangle setCenter (float x, float y) {
setPosition(x - width / 2, y - height / 2);
return this;
}
/** Moves this rectangle so that its center point is located at a given position
* @param position the position
* @return this for chaining */
public Rectangle setCenter (Vector2 position) {
setPosition(position.x - width / 2, position.y - height / 2);
return this;
}
/** Fits this rectangle around another rectangle while maintaining aspect ratio. This scales and centers the rectangle to the
* other rectangle (e.g. Having a camera translate and scale to show a given area)
* @param rect the other rectangle to fit this rectangle around
* @return this rectangle for chaining
* @see Scaling */
public Rectangle fitOutside (Rectangle rect) {
float ratio = getAspectRatio();
if (ratio > rect.getAspectRatio()) {
// Wider than tall
setSize(rect.height * ratio, rect.height);
} else {
// Taller than wide
setSize(rect.width, rect.width / ratio);
}
setPosition((rect.x + rect.width / 2) - width / 2, (rect.y + rect.height / 2) - height / 2);
return this;
}
/** Fits this rectangle into another rectangle while maintaining aspect ratio. This scales and centers the rectangle to the
* other rectangle (e.g. Scaling a texture within a arbitrary cell without squeezing)
* @param rect the other rectangle to fit this rectangle inside
* @return this rectangle for chaining
* @see Scaling */
public Rectangle fitInside (Rectangle rect) {
float ratio = getAspectRatio();
if (ratio < rect.getAspectRatio()) {
// Taller than wide
setSize(rect.height * ratio, rect.height);
} else {
// Wider than tall
setSize(rect.width, rect.width / ratio);
}
setPosition((rect.x + rect.width / 2) - width / 2, (rect.y + rect.height / 2) - height / 2);
return this;
}
/** Converts this {@code Rectangle} to a string in the format {@code [x,y,width,height]}.
* @return a string representation of this object. */
public String toString () {
return "[" + x + "," + y + "," + width + "," + height + "]";
}
/** Sets this {@code Rectangle} to the value represented by the specified string according to the format of
* {@link #toString()}.
* @param v the string.
* @return this rectangle for chaining */
public Rectangle fromString (String v) {
int s0 = v.indexOf(',', 1);
int s1 = v.indexOf(',', s0 + 1);
int s2 = v.indexOf(',', s1 + 1);
if (s0 != -1 && s1 != -1 && s2 != -1 && v.charAt(0) == '[' && v.charAt(v.length() - 1) == ']') {
try {
float x = Float.parseFloat(v.substring(1, s0));
float y = Float.parseFloat(v.substring(s0 + 1, s1));
float width = Float.parseFloat(v.substring(s1 + 1, s2));
float height = Float.parseFloat(v.substring(s2 + 1, v.length() - 1));
return this.set(x, y, width, height);
} catch (NumberFormatException ex) {
// Throw a GdxRuntimeException
}
}
throw new GdxRuntimeException("Malformed Rectangle: " + v);
}
public float area () {
return this.width * this.height;
}
public float perimeter () {
return 2 * (this.width + this.height);
}
public int hashCode () {
final int prime = 31;
int result = 1;
result = prime * result + NumberUtils.floatToRawIntBits(height);
result = prime * result + NumberUtils.floatToRawIntBits(width);
result = prime * result + NumberUtils.floatToRawIntBits(x);
result = prime * result + NumberUtils.floatToRawIntBits(y);
return result;
}
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Rectangle other = (Rectangle)obj;
if (NumberUtils.floatToRawIntBits(height) != NumberUtils.floatToRawIntBits(other.height)) return false;
if (NumberUtils.floatToRawIntBits(width) != NumberUtils.floatToRawIntBits(other.width)) return false;
if (NumberUtils.floatToRawIntBits(x) != NumberUtils.floatToRawIntBits(other.x)) return false;
if (NumberUtils.floatToRawIntBits(y) != NumberUtils.floatToRawIntBits(other.y)) return false;
return true;
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./extensions/gdx-setup/res/com/badlogic/gdx/setup/resources/html/GdxDefinitionSuperdev | <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit trunk//EN" "http://www.gwtproject.org/doctype/2.8.0/gwt-module.dtd">
<module rename-to="html">
%GWT_INHERITS%
<inherits name='%PACKAGE%.GdxDefinition' />
<collapse-all-properties />
<add-linker name="xsiframe"/>
<set-configuration-property name="devModeRedirectEnabled" value="true"/>
<set-configuration-property name='xsiframe.failIfScriptTag' value='FALSE'/>
</module>
| <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit trunk//EN" "http://www.gwtproject.org/doctype/2.8.0/gwt-module.dtd">
<module rename-to="html">
%GWT_INHERITS%
<inherits name='%PACKAGE%.GdxDefinition' />
<collapse-all-properties />
<add-linker name="xsiframe"/>
<set-configuration-property name="devModeRedirectEnabled" value="true"/>
<set-configuration-property name='xsiframe.failIfScriptTag' value='FALSE'/>
</module>
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./extensions/gdx-bullet/jni/swig-src/softbody/com/badlogic/gdx/physics/bullet/softbody/btSparseSdf3.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.softbody;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
import com.badlogic.gdx.physics.bullet.dynamics.*;
import com.badlogic.gdx.math.Vector3;
public class btSparseSdf3 extends BulletBase {
private long swigCPtr;
protected btSparseSdf3 (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btSparseSdf3, normally you should not need this constructor it's intended for low-level usage. */
public btSparseSdf3 (long cPtr, boolean cMemoryOwn) {
this("btSparseSdf3", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btSparseSdf3 obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
SoftbodyJNI.delete_btSparseSdf3(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
static public class IntFrac extends BulletBase {
private long swigCPtr;
protected IntFrac (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new IntFrac, normally you should not need this constructor it's intended for low-level usage. */
public IntFrac (long cPtr, boolean cMemoryOwn) {
this("IntFrac", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (IntFrac obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
SoftbodyJNI.delete_btSparseSdf3_IntFrac(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setB (int value) {
SoftbodyJNI.btSparseSdf3_IntFrac_b_set(swigCPtr, this, value);
}
public int getB () {
return SoftbodyJNI.btSparseSdf3_IntFrac_b_get(swigCPtr, this);
}
public void setI (int value) {
SoftbodyJNI.btSparseSdf3_IntFrac_i_set(swigCPtr, this, value);
}
public int getI () {
return SoftbodyJNI.btSparseSdf3_IntFrac_i_get(swigCPtr, this);
}
public void setF (float value) {
SoftbodyJNI.btSparseSdf3_IntFrac_f_set(swigCPtr, this, value);
}
public float getF () {
return SoftbodyJNI.btSparseSdf3_IntFrac_f_get(swigCPtr, this);
}
public IntFrac () {
this(SoftbodyJNI.new_btSparseSdf3_IntFrac(), true);
}
}
static public class Cell extends BulletBase {
private long swigCPtr;
protected Cell (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new Cell, normally you should not need this constructor it's intended for low-level usage. */
public Cell (long cPtr, boolean cMemoryOwn) {
this("Cell", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (Cell obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
SoftbodyJNI.delete_btSparseSdf3_Cell(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setD (SWIGTYPE_p_a_3_1__a_3_1__float value) {
SoftbodyJNI.btSparseSdf3_Cell_d_set(swigCPtr, this, SWIGTYPE_p_a_3_1__a_3_1__float.getCPtr(value));
}
public SWIGTYPE_p_a_3_1__a_3_1__float getD () {
long cPtr = SoftbodyJNI.btSparseSdf3_Cell_d_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_a_3_1__a_3_1__float(cPtr, false);
}
public void setC (int[] value) {
SoftbodyJNI.btSparseSdf3_Cell_c_set(swigCPtr, this, value);
}
public int[] getC () {
return SoftbodyJNI.btSparseSdf3_Cell_c_get(swigCPtr, this);
}
public void setPuid (int value) {
SoftbodyJNI.btSparseSdf3_Cell_puid_set(swigCPtr, this, value);
}
public int getPuid () {
return SoftbodyJNI.btSparseSdf3_Cell_puid_get(swigCPtr, this);
}
public void setHash (long value) {
SoftbodyJNI.btSparseSdf3_Cell_hash_set(swigCPtr, this, value);
}
public long getHash () {
return SoftbodyJNI.btSparseSdf3_Cell_hash_get(swigCPtr, this);
}
public void setPclient (btCollisionShape value) {
SoftbodyJNI.btSparseSdf3_Cell_pclient_set(swigCPtr, this, btCollisionShape.getCPtr(value), value);
}
public btCollisionShape getPclient () {
long cPtr = SoftbodyJNI.btSparseSdf3_Cell_pclient_get(swigCPtr, this);
return (cPtr == 0) ? null : btCollisionShape.newDerivedObject(cPtr, false);
}
public void setNext (btSparseSdf3.Cell value) {
SoftbodyJNI.btSparseSdf3_Cell_next_set(swigCPtr, this, btSparseSdf3.Cell.getCPtr(value), value);
}
public btSparseSdf3.Cell getNext () {
long cPtr = SoftbodyJNI.btSparseSdf3_Cell_next_get(swigCPtr, this);
return (cPtr == 0) ? null : new btSparseSdf3.Cell(cPtr, false);
}
public Cell () {
this(SoftbodyJNI.new_btSparseSdf3_Cell(), true);
}
}
public void setCells (SWIGTYPE_p_btAlignedObjectArrayT_btSparseSdfT_3_t__Cell_p_t value) {
SoftbodyJNI.btSparseSdf3_cells_set(swigCPtr, this,
SWIGTYPE_p_btAlignedObjectArrayT_btSparseSdfT_3_t__Cell_p_t.getCPtr(value));
}
public SWIGTYPE_p_btAlignedObjectArrayT_btSparseSdfT_3_t__Cell_p_t getCells () {
long cPtr = SoftbodyJNI.btSparseSdf3_cells_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_btAlignedObjectArrayT_btSparseSdfT_3_t__Cell_p_t(cPtr, false);
}
public void setVoxelsz (float value) {
SoftbodyJNI.btSparseSdf3_voxelsz_set(swigCPtr, this, value);
}
public float getVoxelsz () {
return SoftbodyJNI.btSparseSdf3_voxelsz_get(swigCPtr, this);
}
public void setPuid (int value) {
SoftbodyJNI.btSparseSdf3_puid_set(swigCPtr, this, value);
}
public int getPuid () {
return SoftbodyJNI.btSparseSdf3_puid_get(swigCPtr, this);
}
public void setNcells (int value) {
SoftbodyJNI.btSparseSdf3_ncells_set(swigCPtr, this, value);
}
public int getNcells () {
return SoftbodyJNI.btSparseSdf3_ncells_get(swigCPtr, this);
}
public void setClampCells (int value) {
SoftbodyJNI.btSparseSdf3_clampCells_set(swigCPtr, this, value);
}
public int getClampCells () {
return SoftbodyJNI.btSparseSdf3_clampCells_get(swigCPtr, this);
}
public void setNprobes (int value) {
SoftbodyJNI.btSparseSdf3_nprobes_set(swigCPtr, this, value);
}
public int getNprobes () {
return SoftbodyJNI.btSparseSdf3_nprobes_get(swigCPtr, this);
}
public void setNqueries (int value) {
SoftbodyJNI.btSparseSdf3_nqueries_set(swigCPtr, this, value);
}
public int getNqueries () {
return SoftbodyJNI.btSparseSdf3_nqueries_get(swigCPtr, this);
}
public void Initialize (int hashsize, int clampCells) {
SoftbodyJNI.btSparseSdf3_Initialize__SWIG_0(swigCPtr, this, hashsize, clampCells);
}
public void Initialize (int hashsize) {
SoftbodyJNI.btSparseSdf3_Initialize__SWIG_1(swigCPtr, this, hashsize);
}
public void Initialize () {
SoftbodyJNI.btSparseSdf3_Initialize__SWIG_2(swigCPtr, this);
}
public void Reset () {
SoftbodyJNI.btSparseSdf3_Reset(swigCPtr, this);
}
public void GarbageCollect (int lifetime) {
SoftbodyJNI.btSparseSdf3_GarbageCollect__SWIG_0(swigCPtr, this, lifetime);
}
public void GarbageCollect () {
SoftbodyJNI.btSparseSdf3_GarbageCollect__SWIG_1(swigCPtr, this);
}
public int RemoveReferences (btCollisionShape pcs) {
return SoftbodyJNI.btSparseSdf3_RemoveReferences(swigCPtr, this, btCollisionShape.getCPtr(pcs), pcs);
}
public float Evaluate (Vector3 x, btCollisionShape shape, Vector3 normal, float margin) {
return SoftbodyJNI.btSparseSdf3_Evaluate(swigCPtr, this, x, btCollisionShape.getCPtr(shape), shape, normal, margin);
}
public void BuildCell (btSparseSdf3.Cell c) {
SoftbodyJNI.btSparseSdf3_BuildCell(swigCPtr, this, btSparseSdf3.Cell.getCPtr(c), c);
}
public static float DistanceToShape (Vector3 x, btCollisionShape shape) {
return SoftbodyJNI.btSparseSdf3_DistanceToShape(x, btCollisionShape.getCPtr(shape), shape);
}
public static btSparseSdf3.IntFrac Decompose (float x) {
return new btSparseSdf3.IntFrac(SoftbodyJNI.btSparseSdf3_Decompose(x), true);
}
public static float Lerp (float a, float b, float t) {
return SoftbodyJNI.btSparseSdf3_Lerp(a, b, t);
}
public static long Hash (int x, int y, int z, btCollisionShape shape) {
return SoftbodyJNI.btSparseSdf3_Hash(x, y, z, btCollisionShape.getCPtr(shape), shape);
}
public btSparseSdf3 () {
this(SoftbodyJNI.new_btSparseSdf3(), true);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.softbody;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
import com.badlogic.gdx.physics.bullet.dynamics.*;
import com.badlogic.gdx.math.Vector3;
public class btSparseSdf3 extends BulletBase {
private long swigCPtr;
protected btSparseSdf3 (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btSparseSdf3, normally you should not need this constructor it's intended for low-level usage. */
public btSparseSdf3 (long cPtr, boolean cMemoryOwn) {
this("btSparseSdf3", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btSparseSdf3 obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
SoftbodyJNI.delete_btSparseSdf3(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
static public class IntFrac extends BulletBase {
private long swigCPtr;
protected IntFrac (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new IntFrac, normally you should not need this constructor it's intended for low-level usage. */
public IntFrac (long cPtr, boolean cMemoryOwn) {
this("IntFrac", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (IntFrac obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
SoftbodyJNI.delete_btSparseSdf3_IntFrac(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setB (int value) {
SoftbodyJNI.btSparseSdf3_IntFrac_b_set(swigCPtr, this, value);
}
public int getB () {
return SoftbodyJNI.btSparseSdf3_IntFrac_b_get(swigCPtr, this);
}
public void setI (int value) {
SoftbodyJNI.btSparseSdf3_IntFrac_i_set(swigCPtr, this, value);
}
public int getI () {
return SoftbodyJNI.btSparseSdf3_IntFrac_i_get(swigCPtr, this);
}
public void setF (float value) {
SoftbodyJNI.btSparseSdf3_IntFrac_f_set(swigCPtr, this, value);
}
public float getF () {
return SoftbodyJNI.btSparseSdf3_IntFrac_f_get(swigCPtr, this);
}
public IntFrac () {
this(SoftbodyJNI.new_btSparseSdf3_IntFrac(), true);
}
}
static public class Cell extends BulletBase {
private long swigCPtr;
protected Cell (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new Cell, normally you should not need this constructor it's intended for low-level usage. */
public Cell (long cPtr, boolean cMemoryOwn) {
this("Cell", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (Cell obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
SoftbodyJNI.delete_btSparseSdf3_Cell(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setD (SWIGTYPE_p_a_3_1__a_3_1__float value) {
SoftbodyJNI.btSparseSdf3_Cell_d_set(swigCPtr, this, SWIGTYPE_p_a_3_1__a_3_1__float.getCPtr(value));
}
public SWIGTYPE_p_a_3_1__a_3_1__float getD () {
long cPtr = SoftbodyJNI.btSparseSdf3_Cell_d_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_a_3_1__a_3_1__float(cPtr, false);
}
public void setC (int[] value) {
SoftbodyJNI.btSparseSdf3_Cell_c_set(swigCPtr, this, value);
}
public int[] getC () {
return SoftbodyJNI.btSparseSdf3_Cell_c_get(swigCPtr, this);
}
public void setPuid (int value) {
SoftbodyJNI.btSparseSdf3_Cell_puid_set(swigCPtr, this, value);
}
public int getPuid () {
return SoftbodyJNI.btSparseSdf3_Cell_puid_get(swigCPtr, this);
}
public void setHash (long value) {
SoftbodyJNI.btSparseSdf3_Cell_hash_set(swigCPtr, this, value);
}
public long getHash () {
return SoftbodyJNI.btSparseSdf3_Cell_hash_get(swigCPtr, this);
}
public void setPclient (btCollisionShape value) {
SoftbodyJNI.btSparseSdf3_Cell_pclient_set(swigCPtr, this, btCollisionShape.getCPtr(value), value);
}
public btCollisionShape getPclient () {
long cPtr = SoftbodyJNI.btSparseSdf3_Cell_pclient_get(swigCPtr, this);
return (cPtr == 0) ? null : btCollisionShape.newDerivedObject(cPtr, false);
}
public void setNext (btSparseSdf3.Cell value) {
SoftbodyJNI.btSparseSdf3_Cell_next_set(swigCPtr, this, btSparseSdf3.Cell.getCPtr(value), value);
}
public btSparseSdf3.Cell getNext () {
long cPtr = SoftbodyJNI.btSparseSdf3_Cell_next_get(swigCPtr, this);
return (cPtr == 0) ? null : new btSparseSdf3.Cell(cPtr, false);
}
public Cell () {
this(SoftbodyJNI.new_btSparseSdf3_Cell(), true);
}
}
public void setCells (SWIGTYPE_p_btAlignedObjectArrayT_btSparseSdfT_3_t__Cell_p_t value) {
SoftbodyJNI.btSparseSdf3_cells_set(swigCPtr, this,
SWIGTYPE_p_btAlignedObjectArrayT_btSparseSdfT_3_t__Cell_p_t.getCPtr(value));
}
public SWIGTYPE_p_btAlignedObjectArrayT_btSparseSdfT_3_t__Cell_p_t getCells () {
long cPtr = SoftbodyJNI.btSparseSdf3_cells_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_btAlignedObjectArrayT_btSparseSdfT_3_t__Cell_p_t(cPtr, false);
}
public void setVoxelsz (float value) {
SoftbodyJNI.btSparseSdf3_voxelsz_set(swigCPtr, this, value);
}
public float getVoxelsz () {
return SoftbodyJNI.btSparseSdf3_voxelsz_get(swigCPtr, this);
}
public void setPuid (int value) {
SoftbodyJNI.btSparseSdf3_puid_set(swigCPtr, this, value);
}
public int getPuid () {
return SoftbodyJNI.btSparseSdf3_puid_get(swigCPtr, this);
}
public void setNcells (int value) {
SoftbodyJNI.btSparseSdf3_ncells_set(swigCPtr, this, value);
}
public int getNcells () {
return SoftbodyJNI.btSparseSdf3_ncells_get(swigCPtr, this);
}
public void setClampCells (int value) {
SoftbodyJNI.btSparseSdf3_clampCells_set(swigCPtr, this, value);
}
public int getClampCells () {
return SoftbodyJNI.btSparseSdf3_clampCells_get(swigCPtr, this);
}
public void setNprobes (int value) {
SoftbodyJNI.btSparseSdf3_nprobes_set(swigCPtr, this, value);
}
public int getNprobes () {
return SoftbodyJNI.btSparseSdf3_nprobes_get(swigCPtr, this);
}
public void setNqueries (int value) {
SoftbodyJNI.btSparseSdf3_nqueries_set(swigCPtr, this, value);
}
public int getNqueries () {
return SoftbodyJNI.btSparseSdf3_nqueries_get(swigCPtr, this);
}
public void Initialize (int hashsize, int clampCells) {
SoftbodyJNI.btSparseSdf3_Initialize__SWIG_0(swigCPtr, this, hashsize, clampCells);
}
public void Initialize (int hashsize) {
SoftbodyJNI.btSparseSdf3_Initialize__SWIG_1(swigCPtr, this, hashsize);
}
public void Initialize () {
SoftbodyJNI.btSparseSdf3_Initialize__SWIG_2(swigCPtr, this);
}
public void Reset () {
SoftbodyJNI.btSparseSdf3_Reset(swigCPtr, this);
}
public void GarbageCollect (int lifetime) {
SoftbodyJNI.btSparseSdf3_GarbageCollect__SWIG_0(swigCPtr, this, lifetime);
}
public void GarbageCollect () {
SoftbodyJNI.btSparseSdf3_GarbageCollect__SWIG_1(swigCPtr, this);
}
public int RemoveReferences (btCollisionShape pcs) {
return SoftbodyJNI.btSparseSdf3_RemoveReferences(swigCPtr, this, btCollisionShape.getCPtr(pcs), pcs);
}
public float Evaluate (Vector3 x, btCollisionShape shape, Vector3 normal, float margin) {
return SoftbodyJNI.btSparseSdf3_Evaluate(swigCPtr, this, x, btCollisionShape.getCPtr(shape), shape, normal, margin);
}
public void BuildCell (btSparseSdf3.Cell c) {
SoftbodyJNI.btSparseSdf3_BuildCell(swigCPtr, this, btSparseSdf3.Cell.getCPtr(c), c);
}
public static float DistanceToShape (Vector3 x, btCollisionShape shape) {
return SoftbodyJNI.btSparseSdf3_DistanceToShape(x, btCollisionShape.getCPtr(shape), shape);
}
public static btSparseSdf3.IntFrac Decompose (float x) {
return new btSparseSdf3.IntFrac(SoftbodyJNI.btSparseSdf3_Decompose(x), true);
}
public static float Lerp (float a, float b, float t) {
return SoftbodyJNI.btSparseSdf3_Lerp(a, b, t);
}
public static long Hash (int x, int y, int z, btCollisionShape shape) {
return SoftbodyJNI.btSparseSdf3_Hash(x, y, z, btCollisionShape.getCPtr(shape), shape);
}
public btSparseSdf3 () {
this(SoftbodyJNI.new_btSparseSdf3(), true);
}
}
| -1 |
|
libgdx/libgdx | 7,215 | Revert #6821 | obigu | 2023-08-22T10:02:37Z | 2023-08-25T03:27:36Z | c9ed23f0371f1ece2942ccff2086893f2c08e1c9 | ed811688c42a3eeb32427e56b47988e7ac4a6539 | Revert #6821. | ./extensions/gdx-bullet/jni/swig-src/dynamics/com/badlogic/gdx/physics/bullet/dynamics/btRotationalLimitMotor2.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.dynamics;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
public class btRotationalLimitMotor2 extends BulletBase {
private long swigCPtr;
protected btRotationalLimitMotor2 (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btRotationalLimitMotor2, normally you should not need this constructor it's intended for low-level
* usage. */
public btRotationalLimitMotor2 (long cPtr, boolean cMemoryOwn) {
this("btRotationalLimitMotor2", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btRotationalLimitMotor2 obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
DynamicsJNI.delete_btRotationalLimitMotor2(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setLoLimit (float value) {
DynamicsJNI.btRotationalLimitMotor2_loLimit_set(swigCPtr, this, value);
}
public float getLoLimit () {
return DynamicsJNI.btRotationalLimitMotor2_loLimit_get(swigCPtr, this);
}
public void setHiLimit (float value) {
DynamicsJNI.btRotationalLimitMotor2_hiLimit_set(swigCPtr, this, value);
}
public float getHiLimit () {
return DynamicsJNI.btRotationalLimitMotor2_hiLimit_get(swigCPtr, this);
}
public void setBounce (float value) {
DynamicsJNI.btRotationalLimitMotor2_bounce_set(swigCPtr, this, value);
}
public float getBounce () {
return DynamicsJNI.btRotationalLimitMotor2_bounce_get(swigCPtr, this);
}
public void setStopERP (float value) {
DynamicsJNI.btRotationalLimitMotor2_stopERP_set(swigCPtr, this, value);
}
public float getStopERP () {
return DynamicsJNI.btRotationalLimitMotor2_stopERP_get(swigCPtr, this);
}
public void setStopCFM (float value) {
DynamicsJNI.btRotationalLimitMotor2_stopCFM_set(swigCPtr, this, value);
}
public float getStopCFM () {
return DynamicsJNI.btRotationalLimitMotor2_stopCFM_get(swigCPtr, this);
}
public void setMotorERP (float value) {
DynamicsJNI.btRotationalLimitMotor2_motorERP_set(swigCPtr, this, value);
}
public float getMotorERP () {
return DynamicsJNI.btRotationalLimitMotor2_motorERP_get(swigCPtr, this);
}
public void setMotorCFM (float value) {
DynamicsJNI.btRotationalLimitMotor2_motorCFM_set(swigCPtr, this, value);
}
public float getMotorCFM () {
return DynamicsJNI.btRotationalLimitMotor2_motorCFM_get(swigCPtr, this);
}
public void setEnableMotor (boolean value) {
DynamicsJNI.btRotationalLimitMotor2_enableMotor_set(swigCPtr, this, value);
}
public boolean getEnableMotor () {
return DynamicsJNI.btRotationalLimitMotor2_enableMotor_get(swigCPtr, this);
}
public void setTargetVelocity (float value) {
DynamicsJNI.btRotationalLimitMotor2_targetVelocity_set(swigCPtr, this, value);
}
public float getTargetVelocity () {
return DynamicsJNI.btRotationalLimitMotor2_targetVelocity_get(swigCPtr, this);
}
public void setMaxMotorForce (float value) {
DynamicsJNI.btRotationalLimitMotor2_maxMotorForce_set(swigCPtr, this, value);
}
public float getMaxMotorForce () {
return DynamicsJNI.btRotationalLimitMotor2_maxMotorForce_get(swigCPtr, this);
}
public void setServoMotor (boolean value) {
DynamicsJNI.btRotationalLimitMotor2_servoMotor_set(swigCPtr, this, value);
}
public boolean getServoMotor () {
return DynamicsJNI.btRotationalLimitMotor2_servoMotor_get(swigCPtr, this);
}
public void setServoTarget (float value) {
DynamicsJNI.btRotationalLimitMotor2_servoTarget_set(swigCPtr, this, value);
}
public float getServoTarget () {
return DynamicsJNI.btRotationalLimitMotor2_servoTarget_get(swigCPtr, this);
}
public void setEnableSpring (boolean value) {
DynamicsJNI.btRotationalLimitMotor2_enableSpring_set(swigCPtr, this, value);
}
public boolean getEnableSpring () {
return DynamicsJNI.btRotationalLimitMotor2_enableSpring_get(swigCPtr, this);
}
public void setSpringStiffness (float value) {
DynamicsJNI.btRotationalLimitMotor2_springStiffness_set(swigCPtr, this, value);
}
public float getSpringStiffness () {
return DynamicsJNI.btRotationalLimitMotor2_springStiffness_get(swigCPtr, this);
}
public void setSpringStiffnessLimited (boolean value) {
DynamicsJNI.btRotationalLimitMotor2_springStiffnessLimited_set(swigCPtr, this, value);
}
public boolean getSpringStiffnessLimited () {
return DynamicsJNI.btRotationalLimitMotor2_springStiffnessLimited_get(swigCPtr, this);
}
public void setSpringDamping (float value) {
DynamicsJNI.btRotationalLimitMotor2_springDamping_set(swigCPtr, this, value);
}
public float getSpringDamping () {
return DynamicsJNI.btRotationalLimitMotor2_springDamping_get(swigCPtr, this);
}
public void setSpringDampingLimited (boolean value) {
DynamicsJNI.btRotationalLimitMotor2_springDampingLimited_set(swigCPtr, this, value);
}
public boolean getSpringDampingLimited () {
return DynamicsJNI.btRotationalLimitMotor2_springDampingLimited_get(swigCPtr, this);
}
public void setEquilibriumPoint (float value) {
DynamicsJNI.btRotationalLimitMotor2_equilibriumPoint_set(swigCPtr, this, value);
}
public float getEquilibriumPoint () {
return DynamicsJNI.btRotationalLimitMotor2_equilibriumPoint_get(swigCPtr, this);
}
public void setCurrentLimitError (float value) {
DynamicsJNI.btRotationalLimitMotor2_currentLimitError_set(swigCPtr, this, value);
}
public float getCurrentLimitError () {
return DynamicsJNI.btRotationalLimitMotor2_currentLimitError_get(swigCPtr, this);
}
public void setCurrentLimitErrorHi (float value) {
DynamicsJNI.btRotationalLimitMotor2_currentLimitErrorHi_set(swigCPtr, this, value);
}
public float getCurrentLimitErrorHi () {
return DynamicsJNI.btRotationalLimitMotor2_currentLimitErrorHi_get(swigCPtr, this);
}
public void setCurrentPosition (float value) {
DynamicsJNI.btRotationalLimitMotor2_currentPosition_set(swigCPtr, this, value);
}
public float getCurrentPosition () {
return DynamicsJNI.btRotationalLimitMotor2_currentPosition_get(swigCPtr, this);
}
public void setCurrentLimit (int value) {
DynamicsJNI.btRotationalLimitMotor2_currentLimit_set(swigCPtr, this, value);
}
public int getCurrentLimit () {
return DynamicsJNI.btRotationalLimitMotor2_currentLimit_get(swigCPtr, this);
}
public btRotationalLimitMotor2 () {
this(DynamicsJNI.new_btRotationalLimitMotor2__SWIG_0(), true);
}
public btRotationalLimitMotor2 (btRotationalLimitMotor2 limot) {
this(DynamicsJNI.new_btRotationalLimitMotor2__SWIG_1(btRotationalLimitMotor2.getCPtr(limot), limot), true);
}
public boolean isLimited () {
return DynamicsJNI.btRotationalLimitMotor2_isLimited(swigCPtr, this);
}
public void testLimitValue (float test_value) {
DynamicsJNI.btRotationalLimitMotor2_testLimitValue(swigCPtr, this, test_value);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.dynamics;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
public class btRotationalLimitMotor2 extends BulletBase {
private long swigCPtr;
protected btRotationalLimitMotor2 (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btRotationalLimitMotor2, normally you should not need this constructor it's intended for low-level
* usage. */
public btRotationalLimitMotor2 (long cPtr, boolean cMemoryOwn) {
this("btRotationalLimitMotor2", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btRotationalLimitMotor2 obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
DynamicsJNI.delete_btRotationalLimitMotor2(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setLoLimit (float value) {
DynamicsJNI.btRotationalLimitMotor2_loLimit_set(swigCPtr, this, value);
}
public float getLoLimit () {
return DynamicsJNI.btRotationalLimitMotor2_loLimit_get(swigCPtr, this);
}
public void setHiLimit (float value) {
DynamicsJNI.btRotationalLimitMotor2_hiLimit_set(swigCPtr, this, value);
}
public float getHiLimit () {
return DynamicsJNI.btRotationalLimitMotor2_hiLimit_get(swigCPtr, this);
}
public void setBounce (float value) {
DynamicsJNI.btRotationalLimitMotor2_bounce_set(swigCPtr, this, value);
}
public float getBounce () {
return DynamicsJNI.btRotationalLimitMotor2_bounce_get(swigCPtr, this);
}
public void setStopERP (float value) {
DynamicsJNI.btRotationalLimitMotor2_stopERP_set(swigCPtr, this, value);
}
public float getStopERP () {
return DynamicsJNI.btRotationalLimitMotor2_stopERP_get(swigCPtr, this);
}
public void setStopCFM (float value) {
DynamicsJNI.btRotationalLimitMotor2_stopCFM_set(swigCPtr, this, value);
}
public float getStopCFM () {
return DynamicsJNI.btRotationalLimitMotor2_stopCFM_get(swigCPtr, this);
}
public void setMotorERP (float value) {
DynamicsJNI.btRotationalLimitMotor2_motorERP_set(swigCPtr, this, value);
}
public float getMotorERP () {
return DynamicsJNI.btRotationalLimitMotor2_motorERP_get(swigCPtr, this);
}
public void setMotorCFM (float value) {
DynamicsJNI.btRotationalLimitMotor2_motorCFM_set(swigCPtr, this, value);
}
public float getMotorCFM () {
return DynamicsJNI.btRotationalLimitMotor2_motorCFM_get(swigCPtr, this);
}
public void setEnableMotor (boolean value) {
DynamicsJNI.btRotationalLimitMotor2_enableMotor_set(swigCPtr, this, value);
}
public boolean getEnableMotor () {
return DynamicsJNI.btRotationalLimitMotor2_enableMotor_get(swigCPtr, this);
}
public void setTargetVelocity (float value) {
DynamicsJNI.btRotationalLimitMotor2_targetVelocity_set(swigCPtr, this, value);
}
public float getTargetVelocity () {
return DynamicsJNI.btRotationalLimitMotor2_targetVelocity_get(swigCPtr, this);
}
public void setMaxMotorForce (float value) {
DynamicsJNI.btRotationalLimitMotor2_maxMotorForce_set(swigCPtr, this, value);
}
public float getMaxMotorForce () {
return DynamicsJNI.btRotationalLimitMotor2_maxMotorForce_get(swigCPtr, this);
}
public void setServoMotor (boolean value) {
DynamicsJNI.btRotationalLimitMotor2_servoMotor_set(swigCPtr, this, value);
}
public boolean getServoMotor () {
return DynamicsJNI.btRotationalLimitMotor2_servoMotor_get(swigCPtr, this);
}
public void setServoTarget (float value) {
DynamicsJNI.btRotationalLimitMotor2_servoTarget_set(swigCPtr, this, value);
}
public float getServoTarget () {
return DynamicsJNI.btRotationalLimitMotor2_servoTarget_get(swigCPtr, this);
}
public void setEnableSpring (boolean value) {
DynamicsJNI.btRotationalLimitMotor2_enableSpring_set(swigCPtr, this, value);
}
public boolean getEnableSpring () {
return DynamicsJNI.btRotationalLimitMotor2_enableSpring_get(swigCPtr, this);
}
public void setSpringStiffness (float value) {
DynamicsJNI.btRotationalLimitMotor2_springStiffness_set(swigCPtr, this, value);
}
public float getSpringStiffness () {
return DynamicsJNI.btRotationalLimitMotor2_springStiffness_get(swigCPtr, this);
}
public void setSpringStiffnessLimited (boolean value) {
DynamicsJNI.btRotationalLimitMotor2_springStiffnessLimited_set(swigCPtr, this, value);
}
public boolean getSpringStiffnessLimited () {
return DynamicsJNI.btRotationalLimitMotor2_springStiffnessLimited_get(swigCPtr, this);
}
public void setSpringDamping (float value) {
DynamicsJNI.btRotationalLimitMotor2_springDamping_set(swigCPtr, this, value);
}
public float getSpringDamping () {
return DynamicsJNI.btRotationalLimitMotor2_springDamping_get(swigCPtr, this);
}
public void setSpringDampingLimited (boolean value) {
DynamicsJNI.btRotationalLimitMotor2_springDampingLimited_set(swigCPtr, this, value);
}
public boolean getSpringDampingLimited () {
return DynamicsJNI.btRotationalLimitMotor2_springDampingLimited_get(swigCPtr, this);
}
public void setEquilibriumPoint (float value) {
DynamicsJNI.btRotationalLimitMotor2_equilibriumPoint_set(swigCPtr, this, value);
}
public float getEquilibriumPoint () {
return DynamicsJNI.btRotationalLimitMotor2_equilibriumPoint_get(swigCPtr, this);
}
public void setCurrentLimitError (float value) {
DynamicsJNI.btRotationalLimitMotor2_currentLimitError_set(swigCPtr, this, value);
}
public float getCurrentLimitError () {
return DynamicsJNI.btRotationalLimitMotor2_currentLimitError_get(swigCPtr, this);
}
public void setCurrentLimitErrorHi (float value) {
DynamicsJNI.btRotationalLimitMotor2_currentLimitErrorHi_set(swigCPtr, this, value);
}
public float getCurrentLimitErrorHi () {
return DynamicsJNI.btRotationalLimitMotor2_currentLimitErrorHi_get(swigCPtr, this);
}
public void setCurrentPosition (float value) {
DynamicsJNI.btRotationalLimitMotor2_currentPosition_set(swigCPtr, this, value);
}
public float getCurrentPosition () {
return DynamicsJNI.btRotationalLimitMotor2_currentPosition_get(swigCPtr, this);
}
public void setCurrentLimit (int value) {
DynamicsJNI.btRotationalLimitMotor2_currentLimit_set(swigCPtr, this, value);
}
public int getCurrentLimit () {
return DynamicsJNI.btRotationalLimitMotor2_currentLimit_get(swigCPtr, this);
}
public btRotationalLimitMotor2 () {
this(DynamicsJNI.new_btRotationalLimitMotor2__SWIG_0(), true);
}
public btRotationalLimitMotor2 (btRotationalLimitMotor2 limot) {
this(DynamicsJNI.new_btRotationalLimitMotor2__SWIG_1(btRotationalLimitMotor2.getCPtr(limot), limot), true);
}
public boolean isLimited () {
return DynamicsJNI.btRotationalLimitMotor2_isLimited(swigCPtr, this);
}
public void testLimitValue (float test_value) {
DynamicsJNI.btRotationalLimitMotor2_testLimitValue(swigCPtr, this, test_value);
}
}
| -1 |
|
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-tools/src/com/badlogic/gdx/tools/flame/NumericPanel.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tools.flame;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.badlogic.gdx.graphics.g3d.particles.values.NumericValue;
/** @author Inferno */
class NumericPanel extends ParticleValuePanel<NumericValue> {
JSpinner valueSpinner;
public NumericPanel (FlameMain editor, NumericValue value, String name, String description) {
super(editor, name, description);
setValue(value);
}
@Override
public void setValue (NumericValue value) {
super.setValue(value);
if (value == null) return;
setValue(valueSpinner, value.getValue());
}
protected void initializeComponents () {
super.initializeComponents();
JPanel contentPanel = getContentPanel();
{
JLabel label = new JLabel("Value:");
contentPanel.add(label, new GridBagConstraints(0, 1, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 6), 0, 0));
}
{
valueSpinner = new JSpinner(new SpinnerNumberModel(0, -99999, 99999, 0.1f));
contentPanel.add(valueSpinner, new GridBagConstraints(1, 1, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
}
valueSpinner.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
NumericPanel.this.value.setValue((Float)valueSpinner.getValue());
}
});
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tools.flame;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.badlogic.gdx.graphics.g3d.particles.values.NumericValue;
/** @author Inferno */
class NumericPanel extends ParticleValuePanel<NumericValue> {
JSpinner valueSpinner;
public NumericPanel (FlameMain editor, NumericValue value, String name, String description) {
super(editor, name, description);
setValue(value);
}
@Override
public void setValue (NumericValue value) {
super.setValue(value);
if (value == null) return;
setValue(valueSpinner, value.getValue());
}
protected void initializeComponents () {
super.initializeComponents();
JPanel contentPanel = getContentPanel();
{
JLabel label = new JLabel("Value:");
contentPanel.add(label, new GridBagConstraints(0, 1, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 6), 0, 0));
}
{
valueSpinner = new JSpinner(new SpinnerNumberModel(0, -99999, 99999, 0.1f));
contentPanel.add(valueSpinner, new GridBagConstraints(1, 1, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
}
valueSpinner.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
NumericPanel.this.value.setValue(((Number)valueSpinner.getValue()).floatValue());
}
});
}
}
| 1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-tools/src/com/badlogic/gdx/tools/flame/Slider.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tools.flame;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeListener;
/** @author Inferno */
public class Slider extends JPanel {
public JSpinner spinner;
public Slider (float initialValue, final float min, final float max, float stepSize) {
spinner = new JSpinner(new SpinnerNumberModel(initialValue, min, max, stepSize));
setLayout(new BorderLayout());
add(spinner);
}
public void setValue (float value) {
spinner.setValue((double)value);
}
public float getValue () {
return ((Double)spinner.getValue()).floatValue();
}
public void addChangeListener (ChangeListener listener) {
spinner.addChangeListener(listener);
}
public Dimension getPreferredSize () {
Dimension size = super.getPreferredSize();
size.width = 75;
size.height = 26;
return size;
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tools.flame;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeListener;
/** @author Inferno */
public class Slider extends JPanel {
public JSpinner spinner;
public Slider (float initialValue, final float min, final float max, float stepSize) {
spinner = new JSpinner(new SpinnerNumberModel(initialValue, min, max, stepSize));
setLayout(new BorderLayout());
add(spinner);
}
public void setValue (float value) {
spinner.setValue((double)value);
}
public float getValue () {
return ((Number)spinner.getValue()).floatValue();
}
public void addChangeListener (ChangeListener listener) {
spinner.addChangeListener(listener);
}
public Dimension getPreferredSize () {
Dimension size = super.getPreferredSize();
size.width = 75;
size.height = 26;
return size;
}
}
| 1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-tools/src/com/badlogic/gdx/tools/particleeditor/NumericPanel.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tools.particleeditor;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.badlogic.gdx.graphics.g2d.ParticleEmitter.NumericValue;
class NumericPanel extends EditorPanel {
private final NumericValue value;
JSpinner valueSpinner;
public NumericPanel (final NumericValue value, String name, String description) {
super(value, name, description);
this.value = value;
initializeComponents();
valueSpinner.setValue(value.getValue());
valueSpinner.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
value.setValue((Float)valueSpinner.getValue());
}
});
}
private void initializeComponents () {
JPanel contentPanel = getContentPanel();
{
JLabel label = new JLabel("Value:");
contentPanel.add(label, new GridBagConstraints(0, 1, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 6), 0, 0));
}
{
valueSpinner = new JSpinner(new SpinnerNumberModel(0, -99999, 99999, 0.1f));
contentPanel.add(valueSpinner, new GridBagConstraints(1, 1, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
}
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tools.particleeditor;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.badlogic.gdx.graphics.g2d.ParticleEmitter.NumericValue;
class NumericPanel extends EditorPanel {
private final NumericValue value;
JSpinner valueSpinner;
public NumericPanel (final NumericValue value, String name, String description) {
super(value, name, description);
this.value = value;
initializeComponents();
valueSpinner.setValue(value.getValue());
valueSpinner.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
value.setValue(((Number)valueSpinner.getValue()).floatValue());
}
});
}
private void initializeComponents () {
JPanel contentPanel = getContentPanel();
{
JLabel label = new JLabel("Value:");
contentPanel.add(label, new GridBagConstraints(0, 1, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 6), 0, 0));
}
{
valueSpinner = new JSpinner(new SpinnerNumberModel(0, -99999, 99999, 0.1f));
contentPanel.add(valueSpinner, new GridBagConstraints(1, 1, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
}
}
}
| 1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-tools/src/com/badlogic/gdx/tools/particleeditor/Slider.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tools.particleeditor;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeListener;
// BOZO - Slider is a placeholder that uses a spinner until the slider (in NewSlider) is complete.
class Slider extends JPanel {
private JSpinner spinner;
public Slider (float initialValue, final float min, final float max, float stepSize, final float sliderMin,
final float sliderMax) {
spinner = new JSpinner(new SpinnerNumberModel(initialValue, min, max, stepSize));
setLayout(new BorderLayout());
add(spinner);
}
public void setValue (float value) {
spinner.setValue((double)value);
}
public float getValue () {
return ((Double)spinner.getValue()).floatValue();
}
public void addChangeListener (ChangeListener listener) {
spinner.addChangeListener(listener);
}
public Dimension getPreferredSize () {
Dimension size = super.getPreferredSize();
size.width = 75;
size.height = 26;
return size;
}
public static void main (String[] args) throws Exception {
EventQueue.invokeLater(new Runnable() {
public void run () {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(480, 320);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
frame.getContentPane().add(panel);
panel.add(new Slider(200, 100, 500, 0.1f, 150, 300));
frame.setVisible(true);
}
});
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tools.particleeditor;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeListener;
// BOZO - Slider is a placeholder that uses a spinner until the slider (in NewSlider) is complete.
class Slider extends JPanel {
private JSpinner spinner;
public Slider (float initialValue, final float min, final float max, float stepSize, final float sliderMin,
final float sliderMax) {
spinner = new JSpinner(new SpinnerNumberModel(initialValue, min, max, stepSize));
setLayout(new BorderLayout());
add(spinner);
}
public void setValue (float value) {
spinner.setValue((double)value);
}
public float getValue () {
return ((Number)spinner.getValue()).floatValue();
}
public void addChangeListener (ChangeListener listener) {
spinner.addChangeListener(listener);
}
public Dimension getPreferredSize () {
Dimension size = super.getPreferredSize();
size.width = 75;
size.height = 26;
return size;
}
public static void main (String[] args) throws Exception {
EventQueue.invokeLater(new Runnable() {
public void run () {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(480, 320);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
frame.getContentPane().add(panel);
panel.add(new Slider(200, 100, 500, 0.1f, 150, 300));
frame.setVisible(true);
}
});
}
}
| 1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./gdx/src/com/badlogic/gdx/files/package-info.java | /** Platform independent wrappers for file handles and file streaming.
*
* Use {@link com.badlogic.gdx.Gdx#files} to get a reference to the {@link com.badlogic.gdx.Files} implementation to create and
* look up files. */
package com.badlogic.gdx.files;
// This is a doc-only file and has no actual content.
| /** Platform independent wrappers for file handles and file streaming.
*
* Use {@link com.badlogic.gdx.Gdx#files} to get a reference to the {@link com.badlogic.gdx.Files} implementation to create and
* look up files. */
package com.badlogic.gdx.files;
// This is a doc-only file and has no actual content.
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btGimBvhDataArray.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btGimBvhDataArray extends BulletBase {
private long swigCPtr;
protected btGimBvhDataArray (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btGimBvhDataArray, normally you should not need this constructor it's intended for low-level usage. */
public btGimBvhDataArray (long cPtr, boolean cMemoryOwn) {
this("btGimBvhDataArray", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btGimBvhDataArray obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btGimBvhDataArray(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public btGimBvhDataArray operatorAssignment (btGimBvhDataArray other) {
return new btGimBvhDataArray(
CollisionJNI.btGimBvhDataArray_operatorAssignment(swigCPtr, this, btGimBvhDataArray.getCPtr(other), other), false);
}
public btGimBvhDataArray () {
this(CollisionJNI.new_btGimBvhDataArray__SWIG_0(), true);
}
public btGimBvhDataArray (btGimBvhDataArray otherArray) {
this(CollisionJNI.new_btGimBvhDataArray__SWIG_1(btGimBvhDataArray.getCPtr(otherArray), otherArray), true);
}
public int size () {
return CollisionJNI.btGimBvhDataArray_size(swigCPtr, this);
}
public GIM_BVH_DATA atConst (int n) {
return new GIM_BVH_DATA(CollisionJNI.btGimBvhDataArray_atConst(swigCPtr, this, n), false);
}
public GIM_BVH_DATA at (int n) {
return new GIM_BVH_DATA(CollisionJNI.btGimBvhDataArray_at(swigCPtr, this, n), false);
}
public GIM_BVH_DATA operatorSubscriptConst (int n) {
return new GIM_BVH_DATA(CollisionJNI.btGimBvhDataArray_operatorSubscriptConst(swigCPtr, this, n), false);
}
public GIM_BVH_DATA operatorSubscript (int n) {
return new GIM_BVH_DATA(CollisionJNI.btGimBvhDataArray_operatorSubscript(swigCPtr, this, n), false);
}
public void clear () {
CollisionJNI.btGimBvhDataArray_clear(swigCPtr, this);
}
public void pop_back () {
CollisionJNI.btGimBvhDataArray_pop_back(swigCPtr, this);
}
public void resizeNoInitialize (int newsize) {
CollisionJNI.btGimBvhDataArray_resizeNoInitialize(swigCPtr, this, newsize);
}
public void resize (int newsize, GIM_BVH_DATA fillData) {
CollisionJNI.btGimBvhDataArray_resize__SWIG_0(swigCPtr, this, newsize, GIM_BVH_DATA.getCPtr(fillData), fillData);
}
public void resize (int newsize) {
CollisionJNI.btGimBvhDataArray_resize__SWIG_1(swigCPtr, this, newsize);
}
public GIM_BVH_DATA expandNonInitializing () {
return new GIM_BVH_DATA(CollisionJNI.btGimBvhDataArray_expandNonInitializing(swigCPtr, this), false);
}
public GIM_BVH_DATA expand (GIM_BVH_DATA fillValue) {
return new GIM_BVH_DATA(
CollisionJNI.btGimBvhDataArray_expand__SWIG_0(swigCPtr, this, GIM_BVH_DATA.getCPtr(fillValue), fillValue), false);
}
public GIM_BVH_DATA expand () {
return new GIM_BVH_DATA(CollisionJNI.btGimBvhDataArray_expand__SWIG_1(swigCPtr, this), false);
}
public void push_back (GIM_BVH_DATA _Val) {
CollisionJNI.btGimBvhDataArray_push_back(swigCPtr, this, GIM_BVH_DATA.getCPtr(_Val), _Val);
}
public int capacity () {
return CollisionJNI.btGimBvhDataArray_capacity(swigCPtr, this);
}
public void reserve (int _Count) {
CollisionJNI.btGimBvhDataArray_reserve(swigCPtr, this, _Count);
}
static public class less extends BulletBase {
private long swigCPtr;
protected less (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new less, normally you should not need this constructor it's intended for low-level usage. */
public less (long cPtr, boolean cMemoryOwn) {
this("less", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (less obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btGimBvhDataArray_less(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public less () {
this(CollisionJNI.new_btGimBvhDataArray_less(), true);
}
}
public void swap (int index0, int index1) {
CollisionJNI.btGimBvhDataArray_swap(swigCPtr, this, index0, index1);
}
public void removeAtIndex (int index) {
CollisionJNI.btGimBvhDataArray_removeAtIndex(swigCPtr, this, index);
}
public void initializeFromBuffer (long buffer, int size, int capacity) {
CollisionJNI.btGimBvhDataArray_initializeFromBuffer(swigCPtr, this, buffer, size, capacity);
}
public void copyFromArray (btGimBvhDataArray otherArray) {
CollisionJNI.btGimBvhDataArray_copyFromArray(swigCPtr, this, btGimBvhDataArray.getCPtr(otherArray), otherArray);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btGimBvhDataArray extends BulletBase {
private long swigCPtr;
protected btGimBvhDataArray (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btGimBvhDataArray, normally you should not need this constructor it's intended for low-level usage. */
public btGimBvhDataArray (long cPtr, boolean cMemoryOwn) {
this("btGimBvhDataArray", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btGimBvhDataArray obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btGimBvhDataArray(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public btGimBvhDataArray operatorAssignment (btGimBvhDataArray other) {
return new btGimBvhDataArray(
CollisionJNI.btGimBvhDataArray_operatorAssignment(swigCPtr, this, btGimBvhDataArray.getCPtr(other), other), false);
}
public btGimBvhDataArray () {
this(CollisionJNI.new_btGimBvhDataArray__SWIG_0(), true);
}
public btGimBvhDataArray (btGimBvhDataArray otherArray) {
this(CollisionJNI.new_btGimBvhDataArray__SWIG_1(btGimBvhDataArray.getCPtr(otherArray), otherArray), true);
}
public int size () {
return CollisionJNI.btGimBvhDataArray_size(swigCPtr, this);
}
public GIM_BVH_DATA atConst (int n) {
return new GIM_BVH_DATA(CollisionJNI.btGimBvhDataArray_atConst(swigCPtr, this, n), false);
}
public GIM_BVH_DATA at (int n) {
return new GIM_BVH_DATA(CollisionJNI.btGimBvhDataArray_at(swigCPtr, this, n), false);
}
public GIM_BVH_DATA operatorSubscriptConst (int n) {
return new GIM_BVH_DATA(CollisionJNI.btGimBvhDataArray_operatorSubscriptConst(swigCPtr, this, n), false);
}
public GIM_BVH_DATA operatorSubscript (int n) {
return new GIM_BVH_DATA(CollisionJNI.btGimBvhDataArray_operatorSubscript(swigCPtr, this, n), false);
}
public void clear () {
CollisionJNI.btGimBvhDataArray_clear(swigCPtr, this);
}
public void pop_back () {
CollisionJNI.btGimBvhDataArray_pop_back(swigCPtr, this);
}
public void resizeNoInitialize (int newsize) {
CollisionJNI.btGimBvhDataArray_resizeNoInitialize(swigCPtr, this, newsize);
}
public void resize (int newsize, GIM_BVH_DATA fillData) {
CollisionJNI.btGimBvhDataArray_resize__SWIG_0(swigCPtr, this, newsize, GIM_BVH_DATA.getCPtr(fillData), fillData);
}
public void resize (int newsize) {
CollisionJNI.btGimBvhDataArray_resize__SWIG_1(swigCPtr, this, newsize);
}
public GIM_BVH_DATA expandNonInitializing () {
return new GIM_BVH_DATA(CollisionJNI.btGimBvhDataArray_expandNonInitializing(swigCPtr, this), false);
}
public GIM_BVH_DATA expand (GIM_BVH_DATA fillValue) {
return new GIM_BVH_DATA(
CollisionJNI.btGimBvhDataArray_expand__SWIG_0(swigCPtr, this, GIM_BVH_DATA.getCPtr(fillValue), fillValue), false);
}
public GIM_BVH_DATA expand () {
return new GIM_BVH_DATA(CollisionJNI.btGimBvhDataArray_expand__SWIG_1(swigCPtr, this), false);
}
public void push_back (GIM_BVH_DATA _Val) {
CollisionJNI.btGimBvhDataArray_push_back(swigCPtr, this, GIM_BVH_DATA.getCPtr(_Val), _Val);
}
public int capacity () {
return CollisionJNI.btGimBvhDataArray_capacity(swigCPtr, this);
}
public void reserve (int _Count) {
CollisionJNI.btGimBvhDataArray_reserve(swigCPtr, this, _Count);
}
static public class less extends BulletBase {
private long swigCPtr;
protected less (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new less, normally you should not need this constructor it's intended for low-level usage. */
public less (long cPtr, boolean cMemoryOwn) {
this("less", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (less obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btGimBvhDataArray_less(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public less () {
this(CollisionJNI.new_btGimBvhDataArray_less(), true);
}
}
public void swap (int index0, int index1) {
CollisionJNI.btGimBvhDataArray_swap(swigCPtr, this, index0, index1);
}
public void removeAtIndex (int index) {
CollisionJNI.btGimBvhDataArray_removeAtIndex(swigCPtr, this, index);
}
public void initializeFromBuffer (long buffer, int size, int capacity) {
CollisionJNI.btGimBvhDataArray_initializeFromBuffer(swigCPtr, this, buffer, size, capacity);
}
public void copyFromArray (btGimBvhDataArray otherArray) {
CollisionJNI.btGimBvhDataArray_copyFromArray(swigCPtr, this, btGimBvhDataArray.getCPtr(otherArray), otherArray);
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./backends/gdx-backend-robovm/src/com/badlogic/gdx/backends/iosrobovm/IOSPreferences.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.iosrobovm;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.robovm.apple.foundation.NSAutoreleasePool;
import org.robovm.apple.foundation.NSMutableDictionary;
import org.robovm.apple.foundation.NSNumber;
import org.robovm.apple.foundation.NSObject;
import org.robovm.apple.foundation.NSString;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
public class IOSPreferences implements Preferences {
NSMutableDictionary<NSString, NSObject> nsDictionary;
File file;
public IOSPreferences (NSMutableDictionary<NSString, NSObject> nsDictionary, String filePath) {
this.nsDictionary = nsDictionary;
this.file = new File(filePath);
}
@Override
public Preferences putBoolean (String key, boolean val) {
nsDictionary.put(convertKey(key), NSNumber.valueOf(val));
return this;
}
@Override
public Preferences putInteger (String key, int val) {
nsDictionary.put(convertKey(key), NSNumber.valueOf(val));
return this;
}
@Override
public Preferences putLong (String key, long val) {
nsDictionary.put(convertKey(key), NSNumber.valueOf(val));
return this;
}
@Override
public Preferences putFloat (String key, float val) {
nsDictionary.put(convertKey(key), NSNumber.valueOf(val));
return this;
}
@Override
public Preferences putString (String key, String val) {
nsDictionary.put(convertKey(key), new NSString(val));
return this;
}
@Override
public Preferences put (Map<String, ?> vals) {
Set<String> keySet = vals.keySet();
for (String key : keySet) {
Object value = vals.get(key);
if (value instanceof String) {
putString(key, (String)value);
} else if (value instanceof Boolean) {
putBoolean(key, (Boolean)value);
} else if (value instanceof Integer) {
putInteger(key, (Integer)value);
} else if (value instanceof Long) {
putLong(key, (Long)value);
} else if (value instanceof Float) {
putFloat(key, (Float)value);
}
}
return this;
}
@Override
public boolean getBoolean (String key) {
NSNumber value = (NSNumber)nsDictionary.get(convertKey(key));
if (value == null) return false;
return value.booleanValue();
}
@Override
public int getInteger (String key) {
NSNumber value = (NSNumber)nsDictionary.get(convertKey(key));
if (value == null) return 0;
return value.intValue();
}
@Override
public long getLong (String key) {
NSNumber value = (NSNumber)nsDictionary.get(convertKey(key));
if (value == null) return 0L;
return value.longValue();
}
@Override
public float getFloat (String key) {
NSNumber value = (NSNumber)nsDictionary.get(convertKey(key));
if (value == null) return 0f;
return value.floatValue();
}
@Override
public String getString (String key) {
NSString value = (NSString)nsDictionary.get(convertKey(key));
if (value == null) return "";
return value.toString();
}
@Override
public boolean getBoolean (String key, boolean defValue) {
if (!contains(key)) return defValue;
return getBoolean(key);
}
@Override
public int getInteger (String key, int defValue) {
if (!contains(key)) return defValue;
return getInteger(key);
}
@Override
public long getLong (String key, long defValue) {
if (!contains(key)) return defValue;
return getLong(key);
}
@Override
public float getFloat (String key, float defValue) {
if (!contains(key)) return defValue;
return getFloat(key);
}
@Override
public String getString (String key, String defValue) {
if (!contains(key)) return defValue;
return getString(key);
}
@Override
public Map<String, ?> get () {
Map<String, Object> map = new HashMap<String, Object>();
for (NSString key : nsDictionary.keySet()) {
NSObject value = nsDictionary.get(key);
map.put(key.toString(), value.toString());
}
return map;
}
@Override
public boolean contains (String key) {
return nsDictionary.containsKey(convertKey(key));
}
@Override
public void clear () {
nsDictionary.clear();
}
@Override
public void remove (String key) {
nsDictionary.remove(convertKey(key));
}
private NSString convertKey (String key) {
return new NSString(key);
}
@Override
public void flush () {
NSAutoreleasePool pool = new NSAutoreleasePool();
if (!nsDictionary.write(file, false)) {
Gdx.app.debug("IOSPreferences", "Failed to write NSDictionary to file " + file);
}
pool.close();
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.iosrobovm;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.robovm.apple.foundation.NSAutoreleasePool;
import org.robovm.apple.foundation.NSMutableDictionary;
import org.robovm.apple.foundation.NSNumber;
import org.robovm.apple.foundation.NSObject;
import org.robovm.apple.foundation.NSString;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
public class IOSPreferences implements Preferences {
NSMutableDictionary<NSString, NSObject> nsDictionary;
File file;
public IOSPreferences (NSMutableDictionary<NSString, NSObject> nsDictionary, String filePath) {
this.nsDictionary = nsDictionary;
this.file = new File(filePath);
}
@Override
public Preferences putBoolean (String key, boolean val) {
nsDictionary.put(convertKey(key), NSNumber.valueOf(val));
return this;
}
@Override
public Preferences putInteger (String key, int val) {
nsDictionary.put(convertKey(key), NSNumber.valueOf(val));
return this;
}
@Override
public Preferences putLong (String key, long val) {
nsDictionary.put(convertKey(key), NSNumber.valueOf(val));
return this;
}
@Override
public Preferences putFloat (String key, float val) {
nsDictionary.put(convertKey(key), NSNumber.valueOf(val));
return this;
}
@Override
public Preferences putString (String key, String val) {
nsDictionary.put(convertKey(key), new NSString(val));
return this;
}
@Override
public Preferences put (Map<String, ?> vals) {
Set<String> keySet = vals.keySet();
for (String key : keySet) {
Object value = vals.get(key);
if (value instanceof String) {
putString(key, (String)value);
} else if (value instanceof Boolean) {
putBoolean(key, (Boolean)value);
} else if (value instanceof Integer) {
putInteger(key, (Integer)value);
} else if (value instanceof Long) {
putLong(key, (Long)value);
} else if (value instanceof Float) {
putFloat(key, (Float)value);
}
}
return this;
}
@Override
public boolean getBoolean (String key) {
NSNumber value = (NSNumber)nsDictionary.get(convertKey(key));
if (value == null) return false;
return value.booleanValue();
}
@Override
public int getInteger (String key) {
NSNumber value = (NSNumber)nsDictionary.get(convertKey(key));
if (value == null) return 0;
return value.intValue();
}
@Override
public long getLong (String key) {
NSNumber value = (NSNumber)nsDictionary.get(convertKey(key));
if (value == null) return 0L;
return value.longValue();
}
@Override
public float getFloat (String key) {
NSNumber value = (NSNumber)nsDictionary.get(convertKey(key));
if (value == null) return 0f;
return value.floatValue();
}
@Override
public String getString (String key) {
NSString value = (NSString)nsDictionary.get(convertKey(key));
if (value == null) return "";
return value.toString();
}
@Override
public boolean getBoolean (String key, boolean defValue) {
if (!contains(key)) return defValue;
return getBoolean(key);
}
@Override
public int getInteger (String key, int defValue) {
if (!contains(key)) return defValue;
return getInteger(key);
}
@Override
public long getLong (String key, long defValue) {
if (!contains(key)) return defValue;
return getLong(key);
}
@Override
public float getFloat (String key, float defValue) {
if (!contains(key)) return defValue;
return getFloat(key);
}
@Override
public String getString (String key, String defValue) {
if (!contains(key)) return defValue;
return getString(key);
}
@Override
public Map<String, ?> get () {
Map<String, Object> map = new HashMap<String, Object>();
for (NSString key : nsDictionary.keySet()) {
NSObject value = nsDictionary.get(key);
map.put(key.toString(), value.toString());
}
return map;
}
@Override
public boolean contains (String key) {
return nsDictionary.containsKey(convertKey(key));
}
@Override
public void clear () {
nsDictionary.clear();
}
@Override
public void remove (String key) {
nsDictionary.remove(convertKey(key));
}
private NSString convertKey (String key) {
return new NSString(key);
}
@Override
public void flush () {
NSAutoreleasePool pool = new NSAutoreleasePool();
if (!nsDictionary.write(file, false)) {
Gdx.app.debug("IOSPreferences", "Failed to write NSDictionary to file " + file);
}
pool.close();
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Value.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.scenes.scene2d.ui;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.Layout;
import com.badlogic.gdx.utils.Null;
/** Value placeholder, allowing the value to be computed on request. Values can be provided an actor for context to reduce the
* number of value instances that need to be created and reduce verbosity in code that specifies values.
* @author Nathan Sweet */
abstract public class Value {
/** Calls {@link #get(Actor)} with null. */
public float get () {
return get(null);
}
/** @param context May be null. */
abstract public float get (@Null Actor context);
/** A value that is always zero. */
static public final Fixed zero = new Fixed(0);
/** A fixed value that is not computed each time it is used.
* @author Nathan Sweet */
static public class Fixed extends Value {
static final Fixed[] cache = new Fixed[111];
private final float value;
public Fixed (float value) {
this.value = value;
}
public float get (@Null Actor context) {
return value;
}
public String toString () {
return Float.toString(value);
}
static public Fixed valueOf (float value) {
if (value == 0) return zero;
if (value >= -10 && value <= 100 && value == (int)value) {
Fixed fixed = cache[(int)value + 10];
if (fixed == null) cache[(int)value + 10] = fixed = new Fixed(value);
return fixed;
}
return new Fixed(value);
}
}
/** Value that is the minWidth of the actor in the cell. */
static public Value minWidth = new Value() {
public float get (@Null Actor context) {
if (context instanceof Layout) return ((Layout)context).getMinWidth();
return context == null ? 0 : context.getWidth();
}
};
/** Value that is the minHeight of the actor in the cell. */
static public Value minHeight = new Value() {
public float get (@Null Actor context) {
if (context instanceof Layout) return ((Layout)context).getMinHeight();
return context == null ? 0 : context.getHeight();
}
};
/** Value that is the prefWidth of the actor in the cell. */
static public Value prefWidth = new Value() {
public float get (@Null Actor context) {
if (context instanceof Layout) return ((Layout)context).getPrefWidth();
return context == null ? 0 : context.getWidth();
}
};
/** Value that is the prefHeight of the actor in the cell. */
static public Value prefHeight = new Value() {
public float get (@Null Actor context) {
if (context instanceof Layout) return ((Layout)context).getPrefHeight();
return context == null ? 0 : context.getHeight();
}
};
/** Value that is the maxWidth of the actor in the cell. */
static public Value maxWidth = new Value() {
public float get (@Null Actor context) {
if (context instanceof Layout) return ((Layout)context).getMaxWidth();
return context == null ? 0 : context.getWidth();
}
};
/** Value that is the maxHeight of the actor in the cell. */
static public Value maxHeight = new Value() {
public float get (@Null Actor context) {
if (context instanceof Layout) return ((Layout)context).getMaxHeight();
return context == null ? 0 : context.getHeight();
}
};
/** Returns a value that is a percentage of the actor's width. */
static public Value percentWidth (final float percent) {
return new Value() {
public float get (@Null Actor actor) {
return actor.getWidth() * percent;
}
};
}
/** Returns a value that is a percentage of the actor's height. */
static public Value percentHeight (final float percent) {
return new Value() {
public float get (@Null Actor actor) {
return actor.getHeight() * percent;
}
};
}
/** Returns a value that is a percentage of the specified actor's width. The context actor is ignored. */
static public Value percentWidth (final float percent, final Actor actor) {
if (actor == null) throw new IllegalArgumentException("actor cannot be null.");
return new Value() {
public float get (@Null Actor context) {
return actor.getWidth() * percent;
}
};
}
/** Returns a value that is a percentage of the specified actor's height. The context actor is ignored. */
static public Value percentHeight (final float percent, final Actor actor) {
if (actor == null) throw new IllegalArgumentException("actor cannot be null.");
return new Value() {
public float get (@Null Actor context) {
return actor.getHeight() * percent;
}
};
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.scenes.scene2d.ui;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.Layout;
import com.badlogic.gdx.utils.Null;
/** Value placeholder, allowing the value to be computed on request. Values can be provided an actor for context to reduce the
* number of value instances that need to be created and reduce verbosity in code that specifies values.
* @author Nathan Sweet */
abstract public class Value {
/** Calls {@link #get(Actor)} with null. */
public float get () {
return get(null);
}
/** @param context May be null. */
abstract public float get (@Null Actor context);
/** A value that is always zero. */
static public final Fixed zero = new Fixed(0);
/** A fixed value that is not computed each time it is used.
* @author Nathan Sweet */
static public class Fixed extends Value {
static final Fixed[] cache = new Fixed[111];
private final float value;
public Fixed (float value) {
this.value = value;
}
public float get (@Null Actor context) {
return value;
}
public String toString () {
return Float.toString(value);
}
static public Fixed valueOf (float value) {
if (value == 0) return zero;
if (value >= -10 && value <= 100 && value == (int)value) {
Fixed fixed = cache[(int)value + 10];
if (fixed == null) cache[(int)value + 10] = fixed = new Fixed(value);
return fixed;
}
return new Fixed(value);
}
}
/** Value that is the minWidth of the actor in the cell. */
static public Value minWidth = new Value() {
public float get (@Null Actor context) {
if (context instanceof Layout) return ((Layout)context).getMinWidth();
return context == null ? 0 : context.getWidth();
}
};
/** Value that is the minHeight of the actor in the cell. */
static public Value minHeight = new Value() {
public float get (@Null Actor context) {
if (context instanceof Layout) return ((Layout)context).getMinHeight();
return context == null ? 0 : context.getHeight();
}
};
/** Value that is the prefWidth of the actor in the cell. */
static public Value prefWidth = new Value() {
public float get (@Null Actor context) {
if (context instanceof Layout) return ((Layout)context).getPrefWidth();
return context == null ? 0 : context.getWidth();
}
};
/** Value that is the prefHeight of the actor in the cell. */
static public Value prefHeight = new Value() {
public float get (@Null Actor context) {
if (context instanceof Layout) return ((Layout)context).getPrefHeight();
return context == null ? 0 : context.getHeight();
}
};
/** Value that is the maxWidth of the actor in the cell. */
static public Value maxWidth = new Value() {
public float get (@Null Actor context) {
if (context instanceof Layout) return ((Layout)context).getMaxWidth();
return context == null ? 0 : context.getWidth();
}
};
/** Value that is the maxHeight of the actor in the cell. */
static public Value maxHeight = new Value() {
public float get (@Null Actor context) {
if (context instanceof Layout) return ((Layout)context).getMaxHeight();
return context == null ? 0 : context.getHeight();
}
};
/** Returns a value that is a percentage of the actor's width. */
static public Value percentWidth (final float percent) {
return new Value() {
public float get (@Null Actor actor) {
return actor.getWidth() * percent;
}
};
}
/** Returns a value that is a percentage of the actor's height. */
static public Value percentHeight (final float percent) {
return new Value() {
public float get (@Null Actor actor) {
return actor.getHeight() * percent;
}
};
}
/** Returns a value that is a percentage of the specified actor's width. The context actor is ignored. */
static public Value percentWidth (final float percent, final Actor actor) {
if (actor == null) throw new IllegalArgumentException("actor cannot be null.");
return new Value() {
public float get (@Null Actor context) {
return actor.getWidth() * percent;
}
};
}
/** Returns a value that is a percentage of the specified actor's height. The context actor is ignored. */
static public Value percentHeight (final float percent, final Actor actor) {
if (actor == null) throw new IllegalArgumentException("actor cannot be null.");
return new Value() {
public float get (@Null Actor context) {
return actor.getHeight() * percent;
}
};
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btConvexShape.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.Matrix4;
public class btConvexShape extends btCollisionShape {
private long swigCPtr;
protected btConvexShape (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btConvexShape_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btConvexShape, normally you should not need this constructor it's intended for low-level usage. */
public btConvexShape (long cPtr, boolean cMemoryOwn) {
this("btConvexShape", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btConvexShape_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btConvexShape obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btConvexShape(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public long operatorNew (long sizeInBytes) {
return CollisionJNI.btConvexShape_operatorNew__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDelete (long ptr) {
CollisionJNI.btConvexShape_operatorDelete__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNew (long arg0, long ptr) {
return CollisionJNI.btConvexShape_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDelete (long arg0, long arg1) {
CollisionJNI.btConvexShape_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1);
}
public long operatorNewArray (long sizeInBytes) {
return CollisionJNI.btConvexShape_operatorNewArray__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDeleteArray (long ptr) {
CollisionJNI.btConvexShape_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNewArray (long arg0, long ptr) {
return CollisionJNI.btConvexShape_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDeleteArray (long arg0, long arg1) {
CollisionJNI.btConvexShape_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1);
}
public Vector3 localGetSupportingVertex (Vector3 vec) {
return CollisionJNI.btConvexShape_localGetSupportingVertex(swigCPtr, this, vec);
}
public Vector3 localGetSupportingVertexWithoutMargin (Vector3 vec) {
return CollisionJNI.btConvexShape_localGetSupportingVertexWithoutMargin(swigCPtr, this, vec);
}
public Vector3 localGetSupportVertexWithoutMarginNonVirtual (Vector3 vec) {
return CollisionJNI.btConvexShape_localGetSupportVertexWithoutMarginNonVirtual(swigCPtr, this, vec);
}
public Vector3 localGetSupportVertexNonVirtual (Vector3 vec) {
return CollisionJNI.btConvexShape_localGetSupportVertexNonVirtual(swigCPtr, this, vec);
}
public float getMarginNonVirtual () {
return CollisionJNI.btConvexShape_getMarginNonVirtual(swigCPtr, this);
}
public void getAabbNonVirtual (Matrix4 t, Vector3 aabbMin, Vector3 aabbMax) {
CollisionJNI.btConvexShape_getAabbNonVirtual(swigCPtr, this, t, aabbMin, aabbMax);
}
public void project (Matrix4 trans, Vector3 dir, SWIGTYPE_p_float minProj, SWIGTYPE_p_float maxProj, Vector3 witnesPtMin,
Vector3 witnesPtMax) {
CollisionJNI.btConvexShape_project(swigCPtr, this, trans, dir, SWIGTYPE_p_float.getCPtr(minProj),
SWIGTYPE_p_float.getCPtr(maxProj), witnesPtMin, witnesPtMax);
}
public void batchedUnitVectorGetSupportingVertexWithoutMargin (btVector3 vectors, btVector3 supportVerticesOut,
int numVectors) {
CollisionJNI.btConvexShape_batchedUnitVectorGetSupportingVertexWithoutMargin(swigCPtr, this, btVector3.getCPtr(vectors),
vectors, btVector3.getCPtr(supportVerticesOut), supportVerticesOut, numVectors);
}
public void getAabbSlow (Matrix4 t, Vector3 aabbMin, Vector3 aabbMax) {
CollisionJNI.btConvexShape_getAabbSlow(swigCPtr, this, t, aabbMin, aabbMax);
}
public int getNumPreferredPenetrationDirections () {
return CollisionJNI.btConvexShape_getNumPreferredPenetrationDirections(swigCPtr, this);
}
public void getPreferredPenetrationDirection (int index, Vector3 penetrationVector) {
CollisionJNI.btConvexShape_getPreferredPenetrationDirection(swigCPtr, this, index, penetrationVector);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.Matrix4;
public class btConvexShape extends btCollisionShape {
private long swigCPtr;
protected btConvexShape (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btConvexShape_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btConvexShape, normally you should not need this constructor it's intended for low-level usage. */
public btConvexShape (long cPtr, boolean cMemoryOwn) {
this("btConvexShape", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btConvexShape_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btConvexShape obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btConvexShape(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public long operatorNew (long sizeInBytes) {
return CollisionJNI.btConvexShape_operatorNew__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDelete (long ptr) {
CollisionJNI.btConvexShape_operatorDelete__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNew (long arg0, long ptr) {
return CollisionJNI.btConvexShape_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDelete (long arg0, long arg1) {
CollisionJNI.btConvexShape_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1);
}
public long operatorNewArray (long sizeInBytes) {
return CollisionJNI.btConvexShape_operatorNewArray__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDeleteArray (long ptr) {
CollisionJNI.btConvexShape_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNewArray (long arg0, long ptr) {
return CollisionJNI.btConvexShape_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDeleteArray (long arg0, long arg1) {
CollisionJNI.btConvexShape_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1);
}
public Vector3 localGetSupportingVertex (Vector3 vec) {
return CollisionJNI.btConvexShape_localGetSupportingVertex(swigCPtr, this, vec);
}
public Vector3 localGetSupportingVertexWithoutMargin (Vector3 vec) {
return CollisionJNI.btConvexShape_localGetSupportingVertexWithoutMargin(swigCPtr, this, vec);
}
public Vector3 localGetSupportVertexWithoutMarginNonVirtual (Vector3 vec) {
return CollisionJNI.btConvexShape_localGetSupportVertexWithoutMarginNonVirtual(swigCPtr, this, vec);
}
public Vector3 localGetSupportVertexNonVirtual (Vector3 vec) {
return CollisionJNI.btConvexShape_localGetSupportVertexNonVirtual(swigCPtr, this, vec);
}
public float getMarginNonVirtual () {
return CollisionJNI.btConvexShape_getMarginNonVirtual(swigCPtr, this);
}
public void getAabbNonVirtual (Matrix4 t, Vector3 aabbMin, Vector3 aabbMax) {
CollisionJNI.btConvexShape_getAabbNonVirtual(swigCPtr, this, t, aabbMin, aabbMax);
}
public void project (Matrix4 trans, Vector3 dir, SWIGTYPE_p_float minProj, SWIGTYPE_p_float maxProj, Vector3 witnesPtMin,
Vector3 witnesPtMax) {
CollisionJNI.btConvexShape_project(swigCPtr, this, trans, dir, SWIGTYPE_p_float.getCPtr(minProj),
SWIGTYPE_p_float.getCPtr(maxProj), witnesPtMin, witnesPtMax);
}
public void batchedUnitVectorGetSupportingVertexWithoutMargin (btVector3 vectors, btVector3 supportVerticesOut,
int numVectors) {
CollisionJNI.btConvexShape_batchedUnitVectorGetSupportingVertexWithoutMargin(swigCPtr, this, btVector3.getCPtr(vectors),
vectors, btVector3.getCPtr(supportVerticesOut), supportVerticesOut, numVectors);
}
public void getAabbSlow (Matrix4 t, Vector3 aabbMin, Vector3 aabbMax) {
CollisionJNI.btConvexShape_getAabbSlow(swigCPtr, this, t, aabbMin, aabbMax);
}
public int getNumPreferredPenetrationDirections () {
return CollisionJNI.btConvexShape_getNumPreferredPenetrationDirections(swigCPtr, this);
}
public void getPreferredPenetrationDirection (int index, Vector3 penetrationVector) {
CollisionJNI.btConvexShape_getPreferredPenetrationDirection(swigCPtr, this, index, penetrationVector);
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./tests/gdx-tests/src/com/badlogic/gdx/tests/bullet/CollisionDispatcherTest.java |
package com.badlogic.gdx.tests.bullet;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.physics.bullet.collision.CustomCollisionDispatcher;
import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration;
import com.badlogic.gdx.physics.bullet.collision.btCollisionObject;
import com.badlogic.gdx.physics.bullet.collision.btDbvtBroadphase;
import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration;
import com.badlogic.gdx.physics.bullet.dynamics.btDiscreteDynamicsWorld;
import com.badlogic.gdx.physics.bullet.dynamics.btSequentialImpulseConstraintSolver;
public class CollisionDispatcherTest extends BaseBulletTest {
public static class MyCollisionDispatcher extends CustomCollisionDispatcher {
public MyCollisionDispatcher (btCollisionConfiguration collisionConfiguration) {
super(collisionConfiguration);
}
@Override
public boolean needsCollision (btCollisionObject body0, btCollisionObject body1) {
if (body0.getUserValue() % 2 == 0 || body1.getUserValue() % 2 == 0) return super.needsCollision(body0, body1);
return false;
}
@Override
public boolean needsResponse (btCollisionObject body0, btCollisionObject body1) {
if (body0.getUserValue() % 2 == 0 || body1.getUserValue() % 2 == 0) return super.needsCollision(body0, body1);
return false;
}
}
@Override
public BulletWorld createWorld () {
btDefaultCollisionConfiguration collisionConfiguration = new btDefaultCollisionConfiguration();
MyCollisionDispatcher dispatcher = new MyCollisionDispatcher(collisionConfiguration);
btDbvtBroadphase broadphase = new btDbvtBroadphase();
btSequentialImpulseConstraintSolver solver = new btSequentialImpulseConstraintSolver();
btDiscreteDynamicsWorld collisionWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver,
collisionConfiguration);
return new BulletWorld(collisionConfiguration, dispatcher, broadphase, solver, collisionWorld);
}
@Override
public void create () {
super.create();
// Create the entities
world.add("ground", 0f, 0f, 0f).setColor(0.25f + 0.5f * (float)Math.random(), 0.25f + 0.5f * (float)Math.random(),
0.25f + 0.5f * (float)Math.random(), 1f);
for (float x = -5f; x <= 5f; x += 2f) {
for (float y = 5f; y <= 15f; y += 2f) {
world.add("box", x + 0.1f * MathUtils.random(), y + 0.1f * MathUtils.random(), 0.1f * MathUtils.random()).body
.setUserValue((int)((x + 5f) / 2f + .5f));
}
}
}
@Override
public boolean tap (float x, float y, int count, int button) {
shoot(x, y);
return true;
}
}
|
package com.badlogic.gdx.tests.bullet;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.physics.bullet.collision.CustomCollisionDispatcher;
import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration;
import com.badlogic.gdx.physics.bullet.collision.btCollisionObject;
import com.badlogic.gdx.physics.bullet.collision.btDbvtBroadphase;
import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration;
import com.badlogic.gdx.physics.bullet.dynamics.btDiscreteDynamicsWorld;
import com.badlogic.gdx.physics.bullet.dynamics.btSequentialImpulseConstraintSolver;
public class CollisionDispatcherTest extends BaseBulletTest {
public static class MyCollisionDispatcher extends CustomCollisionDispatcher {
public MyCollisionDispatcher (btCollisionConfiguration collisionConfiguration) {
super(collisionConfiguration);
}
@Override
public boolean needsCollision (btCollisionObject body0, btCollisionObject body1) {
if (body0.getUserValue() % 2 == 0 || body1.getUserValue() % 2 == 0) return super.needsCollision(body0, body1);
return false;
}
@Override
public boolean needsResponse (btCollisionObject body0, btCollisionObject body1) {
if (body0.getUserValue() % 2 == 0 || body1.getUserValue() % 2 == 0) return super.needsCollision(body0, body1);
return false;
}
}
@Override
public BulletWorld createWorld () {
btDefaultCollisionConfiguration collisionConfiguration = new btDefaultCollisionConfiguration();
MyCollisionDispatcher dispatcher = new MyCollisionDispatcher(collisionConfiguration);
btDbvtBroadphase broadphase = new btDbvtBroadphase();
btSequentialImpulseConstraintSolver solver = new btSequentialImpulseConstraintSolver();
btDiscreteDynamicsWorld collisionWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver,
collisionConfiguration);
return new BulletWorld(collisionConfiguration, dispatcher, broadphase, solver, collisionWorld);
}
@Override
public void create () {
super.create();
// Create the entities
world.add("ground", 0f, 0f, 0f).setColor(0.25f + 0.5f * (float)Math.random(), 0.25f + 0.5f * (float)Math.random(),
0.25f + 0.5f * (float)Math.random(), 1f);
for (float x = -5f; x <= 5f; x += 2f) {
for (float y = 5f; y <= 15f; y += 2f) {
world.add("box", x + 0.1f * MathUtils.random(), y + 0.1f * MathUtils.random(), 0.1f * MathUtils.random()).body
.setUserValue((int)((x + 5f) / 2f + .5f));
}
}
}
@Override
public boolean tap (float x, float y, int count, int button) {
shoot(x, y);
return true;
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/io/DataOutput.java | /*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package java.io;
public interface DataOutput {
public void write (byte[] data) throws IOException;
public void write (byte[] data, int ofs, int len) throws IOException;
public void write (int v) throws IOException;
public void writeBoolean (boolean v) throws IOException;
public void writeByte (int v) throws IOException;
public void writeBytes (String s) throws IOException;
public void writeChar (int v) throws IOException;
public void writeChars (String s) throws IOException;
public void writeDouble (double v) throws IOException;
public void writeFloat (float v) throws IOException;
public void writeInt (int v) throws IOException;
public void writeLong (long v) throws IOException;
public void writeShort (int v) throws IOException;
public void writeUTF (String s) throws IOException;
}
| /*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package java.io;
public interface DataOutput {
public void write (byte[] data) throws IOException;
public void write (byte[] data, int ofs, int len) throws IOException;
public void write (int v) throws IOException;
public void writeBoolean (boolean v) throws IOException;
public void writeByte (int v) throws IOException;
public void writeBytes (String s) throws IOException;
public void writeChar (int v) throws IOException;
public void writeChars (String s) throws IOException;
public void writeDouble (double v) throws IOException;
public void writeFloat (float v) throws IOException;
public void writeInt (int v) throws IOException;
public void writeLong (long v) throws IOException;
public void writeShort (int v) throws IOException;
public void writeUTF (String s) throws IOException;
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./gdx/src/com/badlogic/gdx/utils/LongArray.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.utils;
import java.util.Arrays;
import com.badlogic.gdx.math.MathUtils;
/** A resizable, ordered or unordered long array. Avoids the boxing that occurs with ArrayList<Long>. If unordered, this class
* avoids a memory copy when removing elements (the last element is moved to the removed element's position).
* @author Nathan Sweet */
public class LongArray {
public long[] items;
public int size;
public boolean ordered;
/** Creates an ordered array with a capacity of 16. */
public LongArray () {
this(true, 16);
}
/** Creates an ordered array with the specified capacity. */
public LongArray (int capacity) {
this(true, capacity);
}
/** @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a
* memory copy.
* @param capacity Any elements added beyond this will cause the backing array to be grown. */
public LongArray (boolean ordered, int capacity) {
this.ordered = ordered;
items = new long[capacity];
}
/** Creates a new array containing the elements in the specific array. The new array will be ordered if the specific array is
* ordered. The capacity is set to the number of elements, so any subsequent elements added will cause the backing array to be
* grown. */
public LongArray (LongArray array) {
this.ordered = array.ordered;
size = array.size;
items = new long[size];
System.arraycopy(array.items, 0, items, 0, size);
}
/** Creates a new ordered array containing the elements in the specified array. The capacity is set to the number of elements,
* so any subsequent elements added will cause the backing array to be grown. */
public LongArray (long[] array) {
this(true, array, 0, array.length);
}
/** Creates a new array containing the elements in the specified array. The capacity is set to the number of elements, so any
* subsequent elements added will cause the backing array to be grown.
* @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a
* memory copy. */
public LongArray (boolean ordered, long[] array, int startIndex, int count) {
this(ordered, count);
size = count;
System.arraycopy(array, startIndex, items, 0, count);
}
public void add (long value) {
long[] items = this.items;
if (size == items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
items[size++] = value;
}
public void add (long value1, long value2) {
long[] items = this.items;
if (size + 1 >= items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
items[size] = value1;
items[size + 1] = value2;
size += 2;
}
public void add (long value1, long value2, long value3) {
long[] items = this.items;
if (size + 2 >= items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
items[size] = value1;
items[size + 1] = value2;
items[size + 2] = value3;
size += 3;
}
public void add (long value1, long value2, long value3, long value4) {
long[] items = this.items;
if (size + 3 >= items.length) items = resize(Math.max(8, (int)(size * 1.8f))); // 1.75 isn't enough when size=5.
items[size] = value1;
items[size + 1] = value2;
items[size + 2] = value3;
items[size + 3] = value4;
size += 4;
}
public void addAll (LongArray array) {
addAll(array.items, 0, array.size);
}
public void addAll (LongArray array, int offset, int length) {
if (offset + length > array.size)
throw new IllegalArgumentException("offset + length must be <= size: " + offset + " + " + length + " <= " + array.size);
addAll(array.items, offset, length);
}
public void addAll (long... array) {
addAll(array, 0, array.length);
}
public void addAll (long[] array, int offset, int length) {
long[] items = this.items;
int sizeNeeded = size + length;
if (sizeNeeded > items.length) items = resize(Math.max(Math.max(8, sizeNeeded), (int)(size * 1.75f)));
System.arraycopy(array, offset, items, size, length);
size += length;
}
public long get (int index) {
if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
return items[index];
}
public void set (int index, long value) {
if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
items[index] = value;
}
public void incr (int index, long value) {
if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
items[index] += value;
}
public void incr (long value) {
long[] items = this.items;
for (int i = 0, n = size; i < n; i++)
items[i] += value;
}
public void mul (int index, long value) {
if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
items[index] *= value;
}
public void mul (long value) {
long[] items = this.items;
for (int i = 0, n = size; i < n; i++)
items[i] *= value;
}
public void insert (int index, long value) {
if (index > size) throw new IndexOutOfBoundsException("index can't be > size: " + index + " > " + size);
long[] items = this.items;
if (size == items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
if (ordered)
System.arraycopy(items, index, items, index + 1, size - index);
else
items[size] = items[index];
size++;
items[index] = value;
}
/** Inserts the specified number of items at the specified index. The new items will have values equal to the values at those
* indices before the insertion. */
public void insertRange (int index, int count) {
if (index > size) throw new IndexOutOfBoundsException("index can't be > size: " + index + " > " + size);
int sizeNeeded = size + count;
if (sizeNeeded > items.length) items = resize(Math.max(Math.max(8, sizeNeeded), (int)(size * 1.75f)));
System.arraycopy(items, index, items, index + count, size - index);
size = sizeNeeded;
}
public void swap (int first, int second) {
if (first >= size) throw new IndexOutOfBoundsException("first can't be >= size: " + first + " >= " + size);
if (second >= size) throw new IndexOutOfBoundsException("second can't be >= size: " + second + " >= " + size);
long[] items = this.items;
long firstValue = items[first];
items[first] = items[second];
items[second] = firstValue;
}
public boolean contains (long value) {
int i = size - 1;
long[] items = this.items;
while (i >= 0)
if (items[i--] == value) return true;
return false;
}
public int indexOf (long value) {
long[] items = this.items;
for (int i = 0, n = size; i < n; i++)
if (items[i] == value) return i;
return -1;
}
public int lastIndexOf (char value) {
long[] items = this.items;
for (int i = size - 1; i >= 0; i--)
if (items[i] == value) return i;
return -1;
}
public boolean removeValue (long value) {
long[] items = this.items;
for (int i = 0, n = size; i < n; i++) {
if (items[i] == value) {
removeIndex(i);
return true;
}
}
return false;
}
/** Removes and returns the item at the specified index. */
public long removeIndex (int index) {
if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
long[] items = this.items;
long value = items[index];
size--;
if (ordered)
System.arraycopy(items, index + 1, items, index, size - index);
else
items[index] = items[size];
return value;
}
/** Removes the items between the specified indices, inclusive. */
public void removeRange (int start, int end) {
int n = size;
if (end >= n) throw new IndexOutOfBoundsException("end can't be >= size: " + end + " >= " + size);
if (start > end) throw new IndexOutOfBoundsException("start can't be > end: " + start + " > " + end);
int count = end - start + 1, lastIndex = n - count;
if (ordered)
System.arraycopy(items, start + count, items, start, n - (start + count));
else {
int i = Math.max(lastIndex, end + 1);
System.arraycopy(items, i, items, start, n - i);
}
size = n - count;
}
/** Removes from this array all of elements contained in the specified array.
* @return true if this array was modified. */
public boolean removeAll (LongArray array) {
int size = this.size;
int startSize = size;
long[] items = this.items;
for (int i = 0, n = array.size; i < n; i++) {
long item = array.get(i);
for (int ii = 0; ii < size; ii++) {
if (item == items[ii]) {
removeIndex(ii);
size--;
break;
}
}
}
return size != startSize;
}
/** Removes and returns the last item. */
public long pop () {
return items[--size];
}
/** Returns the last item. */
public long peek () {
return items[size - 1];
}
/** Returns the first item. */
public long first () {
if (size == 0) throw new IllegalStateException("Array is empty.");
return items[0];
}
/** Returns true if the array has one or more items. */
public boolean notEmpty () {
return size > 0;
}
/** Returns true if the array is empty. */
public boolean isEmpty () {
return size == 0;
}
public void clear () {
size = 0;
}
/** Reduces the size of the backing array to the size of the actual items. This is useful to release memory when many items
* have been removed, or if it is known that more items will not be added.
* @return {@link #items} */
public long[] shrink () {
if (items.length != size) resize(size);
return items;
}
/** Increases the size of the backing array to accommodate the specified number of additional items. Useful before adding many
* items to avoid multiple backing array resizes.
* @return {@link #items} */
public long[] ensureCapacity (int additionalCapacity) {
if (additionalCapacity < 0) throw new IllegalArgumentException("additionalCapacity must be >= 0: " + additionalCapacity);
int sizeNeeded = size + additionalCapacity;
if (sizeNeeded > items.length) resize(Math.max(Math.max(8, sizeNeeded), (int)(size * 1.75f)));
return items;
}
/** Sets the array size, leaving any values beyond the current size undefined.
* @return {@link #items} */
public long[] setSize (int newSize) {
if (newSize < 0) throw new IllegalArgumentException("newSize must be >= 0: " + newSize);
if (newSize > items.length) resize(Math.max(8, newSize));
size = newSize;
return items;
}
protected long[] resize (int newSize) {
long[] newItems = new long[newSize];
long[] items = this.items;
System.arraycopy(items, 0, newItems, 0, Math.min(size, newItems.length));
this.items = newItems;
return newItems;
}
public void sort () {
Arrays.sort(items, 0, size);
}
public void reverse () {
long[] items = this.items;
for (int i = 0, lastIndex = size - 1, n = size / 2; i < n; i++) {
int ii = lastIndex - i;
long temp = items[i];
items[i] = items[ii];
items[ii] = temp;
}
}
public void shuffle () {
long[] items = this.items;
for (int i = size - 1; i >= 0; i--) {
int ii = MathUtils.random(i);
long temp = items[i];
items[i] = items[ii];
items[ii] = temp;
}
}
/** Reduces the size of the array to the specified size. If the array is already smaller than the specified size, no action is
* taken. */
public void truncate (int newSize) {
if (size > newSize) size = newSize;
}
/** Returns a random item from the array, or zero if the array is empty. */
public long random () {
if (size == 0) return 0;
return items[MathUtils.random(0, size - 1)];
}
public long[] toArray () {
long[] array = new long[size];
System.arraycopy(items, 0, array, 0, size);
return array;
}
public int hashCode () {
if (!ordered) return super.hashCode();
long[] items = this.items;
int h = 1;
for (int i = 0, n = size; i < n; i++) {
long item = items[i];
h = h * 31 + (int)(item ^ (item >>> 32));
}
return h;
}
public boolean equals (Object object) {
if (object == this) return true;
if (!ordered) return false;
if (!(object instanceof LongArray)) return false;
LongArray array = (LongArray)object;
if (!array.ordered) return false;
int n = size;
if (n != array.size) return false;
long[] items1 = this.items, items2 = array.items;
for (int i = 0; i < n; i++)
if (items1[i] != items2[i]) return false;
return true;
}
public String toString () {
if (size == 0) return "[]";
long[] items = this.items;
StringBuilder buffer = new StringBuilder(32);
buffer.append('[');
buffer.append(items[0]);
for (int i = 1; i < size; i++) {
buffer.append(", ");
buffer.append(items[i]);
}
buffer.append(']');
return buffer.toString();
}
public String toString (String separator) {
if (size == 0) return "";
long[] items = this.items;
StringBuilder buffer = new StringBuilder(32);
buffer.append(items[0]);
for (int i = 1; i < size; i++) {
buffer.append(separator);
buffer.append(items[i]);
}
return buffer.toString();
}
/** @see #LongArray(long[]) */
static public LongArray with (long... array) {
return new LongArray(array);
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.utils;
import java.util.Arrays;
import com.badlogic.gdx.math.MathUtils;
/** A resizable, ordered or unordered long array. Avoids the boxing that occurs with ArrayList<Long>. If unordered, this class
* avoids a memory copy when removing elements (the last element is moved to the removed element's position).
* @author Nathan Sweet */
public class LongArray {
public long[] items;
public int size;
public boolean ordered;
/** Creates an ordered array with a capacity of 16. */
public LongArray () {
this(true, 16);
}
/** Creates an ordered array with the specified capacity. */
public LongArray (int capacity) {
this(true, capacity);
}
/** @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a
* memory copy.
* @param capacity Any elements added beyond this will cause the backing array to be grown. */
public LongArray (boolean ordered, int capacity) {
this.ordered = ordered;
items = new long[capacity];
}
/** Creates a new array containing the elements in the specific array. The new array will be ordered if the specific array is
* ordered. The capacity is set to the number of elements, so any subsequent elements added will cause the backing array to be
* grown. */
public LongArray (LongArray array) {
this.ordered = array.ordered;
size = array.size;
items = new long[size];
System.arraycopy(array.items, 0, items, 0, size);
}
/** Creates a new ordered array containing the elements in the specified array. The capacity is set to the number of elements,
* so any subsequent elements added will cause the backing array to be grown. */
public LongArray (long[] array) {
this(true, array, 0, array.length);
}
/** Creates a new array containing the elements in the specified array. The capacity is set to the number of elements, so any
* subsequent elements added will cause the backing array to be grown.
* @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a
* memory copy. */
public LongArray (boolean ordered, long[] array, int startIndex, int count) {
this(ordered, count);
size = count;
System.arraycopy(array, startIndex, items, 0, count);
}
public void add (long value) {
long[] items = this.items;
if (size == items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
items[size++] = value;
}
public void add (long value1, long value2) {
long[] items = this.items;
if (size + 1 >= items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
items[size] = value1;
items[size + 1] = value2;
size += 2;
}
public void add (long value1, long value2, long value3) {
long[] items = this.items;
if (size + 2 >= items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
items[size] = value1;
items[size + 1] = value2;
items[size + 2] = value3;
size += 3;
}
public void add (long value1, long value2, long value3, long value4) {
long[] items = this.items;
if (size + 3 >= items.length) items = resize(Math.max(8, (int)(size * 1.8f))); // 1.75 isn't enough when size=5.
items[size] = value1;
items[size + 1] = value2;
items[size + 2] = value3;
items[size + 3] = value4;
size += 4;
}
public void addAll (LongArray array) {
addAll(array.items, 0, array.size);
}
public void addAll (LongArray array, int offset, int length) {
if (offset + length > array.size)
throw new IllegalArgumentException("offset + length must be <= size: " + offset + " + " + length + " <= " + array.size);
addAll(array.items, offset, length);
}
public void addAll (long... array) {
addAll(array, 0, array.length);
}
public void addAll (long[] array, int offset, int length) {
long[] items = this.items;
int sizeNeeded = size + length;
if (sizeNeeded > items.length) items = resize(Math.max(Math.max(8, sizeNeeded), (int)(size * 1.75f)));
System.arraycopy(array, offset, items, size, length);
size += length;
}
public long get (int index) {
if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
return items[index];
}
public void set (int index, long value) {
if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
items[index] = value;
}
public void incr (int index, long value) {
if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
items[index] += value;
}
public void incr (long value) {
long[] items = this.items;
for (int i = 0, n = size; i < n; i++)
items[i] += value;
}
public void mul (int index, long value) {
if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
items[index] *= value;
}
public void mul (long value) {
long[] items = this.items;
for (int i = 0, n = size; i < n; i++)
items[i] *= value;
}
public void insert (int index, long value) {
if (index > size) throw new IndexOutOfBoundsException("index can't be > size: " + index + " > " + size);
long[] items = this.items;
if (size == items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
if (ordered)
System.arraycopy(items, index, items, index + 1, size - index);
else
items[size] = items[index];
size++;
items[index] = value;
}
/** Inserts the specified number of items at the specified index. The new items will have values equal to the values at those
* indices before the insertion. */
public void insertRange (int index, int count) {
if (index > size) throw new IndexOutOfBoundsException("index can't be > size: " + index + " > " + size);
int sizeNeeded = size + count;
if (sizeNeeded > items.length) items = resize(Math.max(Math.max(8, sizeNeeded), (int)(size * 1.75f)));
System.arraycopy(items, index, items, index + count, size - index);
size = sizeNeeded;
}
public void swap (int first, int second) {
if (first >= size) throw new IndexOutOfBoundsException("first can't be >= size: " + first + " >= " + size);
if (second >= size) throw new IndexOutOfBoundsException("second can't be >= size: " + second + " >= " + size);
long[] items = this.items;
long firstValue = items[first];
items[first] = items[second];
items[second] = firstValue;
}
public boolean contains (long value) {
int i = size - 1;
long[] items = this.items;
while (i >= 0)
if (items[i--] == value) return true;
return false;
}
public int indexOf (long value) {
long[] items = this.items;
for (int i = 0, n = size; i < n; i++)
if (items[i] == value) return i;
return -1;
}
public int lastIndexOf (char value) {
long[] items = this.items;
for (int i = size - 1; i >= 0; i--)
if (items[i] == value) return i;
return -1;
}
public boolean removeValue (long value) {
long[] items = this.items;
for (int i = 0, n = size; i < n; i++) {
if (items[i] == value) {
removeIndex(i);
return true;
}
}
return false;
}
/** Removes and returns the item at the specified index. */
public long removeIndex (int index) {
if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
long[] items = this.items;
long value = items[index];
size--;
if (ordered)
System.arraycopy(items, index + 1, items, index, size - index);
else
items[index] = items[size];
return value;
}
/** Removes the items between the specified indices, inclusive. */
public void removeRange (int start, int end) {
int n = size;
if (end >= n) throw new IndexOutOfBoundsException("end can't be >= size: " + end + " >= " + size);
if (start > end) throw new IndexOutOfBoundsException("start can't be > end: " + start + " > " + end);
int count = end - start + 1, lastIndex = n - count;
if (ordered)
System.arraycopy(items, start + count, items, start, n - (start + count));
else {
int i = Math.max(lastIndex, end + 1);
System.arraycopy(items, i, items, start, n - i);
}
size = n - count;
}
/** Removes from this array all of elements contained in the specified array.
* @return true if this array was modified. */
public boolean removeAll (LongArray array) {
int size = this.size;
int startSize = size;
long[] items = this.items;
for (int i = 0, n = array.size; i < n; i++) {
long item = array.get(i);
for (int ii = 0; ii < size; ii++) {
if (item == items[ii]) {
removeIndex(ii);
size--;
break;
}
}
}
return size != startSize;
}
/** Removes and returns the last item. */
public long pop () {
return items[--size];
}
/** Returns the last item. */
public long peek () {
return items[size - 1];
}
/** Returns the first item. */
public long first () {
if (size == 0) throw new IllegalStateException("Array is empty.");
return items[0];
}
/** Returns true if the array has one or more items. */
public boolean notEmpty () {
return size > 0;
}
/** Returns true if the array is empty. */
public boolean isEmpty () {
return size == 0;
}
public void clear () {
size = 0;
}
/** Reduces the size of the backing array to the size of the actual items. This is useful to release memory when many items
* have been removed, or if it is known that more items will not be added.
* @return {@link #items} */
public long[] shrink () {
if (items.length != size) resize(size);
return items;
}
/** Increases the size of the backing array to accommodate the specified number of additional items. Useful before adding many
* items to avoid multiple backing array resizes.
* @return {@link #items} */
public long[] ensureCapacity (int additionalCapacity) {
if (additionalCapacity < 0) throw new IllegalArgumentException("additionalCapacity must be >= 0: " + additionalCapacity);
int sizeNeeded = size + additionalCapacity;
if (sizeNeeded > items.length) resize(Math.max(Math.max(8, sizeNeeded), (int)(size * 1.75f)));
return items;
}
/** Sets the array size, leaving any values beyond the current size undefined.
* @return {@link #items} */
public long[] setSize (int newSize) {
if (newSize < 0) throw new IllegalArgumentException("newSize must be >= 0: " + newSize);
if (newSize > items.length) resize(Math.max(8, newSize));
size = newSize;
return items;
}
protected long[] resize (int newSize) {
long[] newItems = new long[newSize];
long[] items = this.items;
System.arraycopy(items, 0, newItems, 0, Math.min(size, newItems.length));
this.items = newItems;
return newItems;
}
public void sort () {
Arrays.sort(items, 0, size);
}
public void reverse () {
long[] items = this.items;
for (int i = 0, lastIndex = size - 1, n = size / 2; i < n; i++) {
int ii = lastIndex - i;
long temp = items[i];
items[i] = items[ii];
items[ii] = temp;
}
}
public void shuffle () {
long[] items = this.items;
for (int i = size - 1; i >= 0; i--) {
int ii = MathUtils.random(i);
long temp = items[i];
items[i] = items[ii];
items[ii] = temp;
}
}
/** Reduces the size of the array to the specified size. If the array is already smaller than the specified size, no action is
* taken. */
public void truncate (int newSize) {
if (size > newSize) size = newSize;
}
/** Returns a random item from the array, or zero if the array is empty. */
public long random () {
if (size == 0) return 0;
return items[MathUtils.random(0, size - 1)];
}
public long[] toArray () {
long[] array = new long[size];
System.arraycopy(items, 0, array, 0, size);
return array;
}
public int hashCode () {
if (!ordered) return super.hashCode();
long[] items = this.items;
int h = 1;
for (int i = 0, n = size; i < n; i++) {
long item = items[i];
h = h * 31 + (int)(item ^ (item >>> 32));
}
return h;
}
public boolean equals (Object object) {
if (object == this) return true;
if (!ordered) return false;
if (!(object instanceof LongArray)) return false;
LongArray array = (LongArray)object;
if (!array.ordered) return false;
int n = size;
if (n != array.size) return false;
long[] items1 = this.items, items2 = array.items;
for (int i = 0; i < n; i++)
if (items1[i] != items2[i]) return false;
return true;
}
public String toString () {
if (size == 0) return "[]";
long[] items = this.items;
StringBuilder buffer = new StringBuilder(32);
buffer.append('[');
buffer.append(items[0]);
for (int i = 1; i < size; i++) {
buffer.append(", ");
buffer.append(items[i]);
}
buffer.append(']');
return buffer.toString();
}
public String toString (String separator) {
if (size == 0) return "";
long[] items = this.items;
StringBuilder buffer = new StringBuilder(32);
buffer.append(items[0]);
for (int i = 1; i < size; i++) {
buffer.append(separator);
buffer.append(items[i]);
}
return buffer.toString();
}
/** @see #LongArray(long[]) */
static public LongArray with (long... array) {
return new LongArray(array);
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./tests/gdx-tests/src/com/badlogic/gdx/tests/utils/CommandLineOptions.java |
package com.badlogic.gdx.tests.utils;
import java.util.ArrayList;
import java.util.List;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
/** Shared class for desktop launchers.
*
* options: --gl30, --gl31, --gl32 enable GLES 3.x (default is GLES 2.0) --glErrors enable GLProfiler and log any GL errors.
* (default is disabled) */
public class CommandLineOptions {
public String startupTestName = null;
public boolean gl30 = false;
public boolean gl31 = false;
public boolean gl32 = false;
public boolean angle = false;
public boolean logGLErrors = false;
public CommandLineOptions (String[] argv) {
Array<String> args = new Array<String>(argv);
for (String arg : args) {
if (arg.startsWith("-")) {
if (arg.equals("--gl30"))
gl30 = true;
else if (arg.equals("--gl31"))
gl31 = true;
else if (arg.equals("--gl32"))
gl32 = true;
else if (arg.equals("--glErrors"))
logGLErrors = true;
else if (arg.equals("--angle"))
angle = true;
else
System.err.println("skip unrecognized option " + arg);
} else {
startupTestName = arg;
}
}
if ((gl30 || gl31 || gl32) && angle) {
throw new GdxRuntimeException("Both --gl3[0|1|2] and --angle set. Can not be combined.");
}
}
public boolean isTestCompatible (String testName) {
final Class<? extends GdxTest> clazz = GdxTests.forName(testName);
GdxTestConfig config = clazz.getAnnotation(GdxTestConfig.class);
if (config != null) {
if (config.requireGL32() && !gl32) return false;
if (config.requireGL31() && !(gl31 || gl32)) return false;
if (config.requireGL30() && !(gl30 || gl31 || gl32)) return false;
if (config.OnlyGL20() && (gl30 || gl31 || gl32)) return false;
}
return true;
}
public Object[] getCompatibleTests () {
List<String> names = new ArrayList<>();
for (String name : GdxTests.getNames()) {
if (isTestCompatible(name)) names.add(name);
}
return names.toArray();
}
}
|
package com.badlogic.gdx.tests.utils;
import java.util.ArrayList;
import java.util.List;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
/** Shared class for desktop launchers.
*
* options: --gl30, --gl31, --gl32 enable GLES 3.x (default is GLES 2.0) --glErrors enable GLProfiler and log any GL errors.
* (default is disabled) */
public class CommandLineOptions {
public String startupTestName = null;
public boolean gl30 = false;
public boolean gl31 = false;
public boolean gl32 = false;
public boolean angle = false;
public boolean logGLErrors = false;
public CommandLineOptions (String[] argv) {
Array<String> args = new Array<String>(argv);
for (String arg : args) {
if (arg.startsWith("-")) {
if (arg.equals("--gl30"))
gl30 = true;
else if (arg.equals("--gl31"))
gl31 = true;
else if (arg.equals("--gl32"))
gl32 = true;
else if (arg.equals("--glErrors"))
logGLErrors = true;
else if (arg.equals("--angle"))
angle = true;
else
System.err.println("skip unrecognized option " + arg);
} else {
startupTestName = arg;
}
}
if ((gl30 || gl31 || gl32) && angle) {
throw new GdxRuntimeException("Both --gl3[0|1|2] and --angle set. Can not be combined.");
}
}
public boolean isTestCompatible (String testName) {
final Class<? extends GdxTest> clazz = GdxTests.forName(testName);
GdxTestConfig config = clazz.getAnnotation(GdxTestConfig.class);
if (config != null) {
if (config.requireGL32() && !gl32) return false;
if (config.requireGL31() && !(gl31 || gl32)) return false;
if (config.requireGL30() && !(gl30 || gl31 || gl32)) return false;
if (config.OnlyGL20() && (gl30 || gl31 || gl32)) return false;
}
return true;
}
public Object[] getCompatibleTests () {
List<String> names = new ArrayList<>();
for (String name : GdxTests.getNames()) {
if (isTestCompatible(name)) names.add(name);
}
return names.toArray();
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btSphereShape.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btSphereShape extends btConvexInternalShape {
private long swigCPtr;
protected btSphereShape (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btSphereShape_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btSphereShape, normally you should not need this constructor it's intended for low-level usage. */
public btSphereShape (long cPtr, boolean cMemoryOwn) {
this("btSphereShape", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btSphereShape_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btSphereShape obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btSphereShape(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public long operatorNew (long sizeInBytes) {
return CollisionJNI.btSphereShape_operatorNew__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDelete (long ptr) {
CollisionJNI.btSphereShape_operatorDelete__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNew (long arg0, long ptr) {
return CollisionJNI.btSphereShape_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDelete (long arg0, long arg1) {
CollisionJNI.btSphereShape_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1);
}
public long operatorNewArray (long sizeInBytes) {
return CollisionJNI.btSphereShape_operatorNewArray__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDeleteArray (long ptr) {
CollisionJNI.btSphereShape_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNewArray (long arg0, long ptr) {
return CollisionJNI.btSphereShape_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDeleteArray (long arg0, long arg1) {
CollisionJNI.btSphereShape_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1);
}
public btSphereShape (float radius) {
this(CollisionJNI.new_btSphereShape(radius), true);
}
public float getRadius () {
return CollisionJNI.btSphereShape_getRadius(swigCPtr, this);
}
public void setUnscaledRadius (float radius) {
CollisionJNI.btSphereShape_setUnscaledRadius(swigCPtr, this, radius);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btSphereShape extends btConvexInternalShape {
private long swigCPtr;
protected btSphereShape (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btSphereShape_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btSphereShape, normally you should not need this constructor it's intended for low-level usage. */
public btSphereShape (long cPtr, boolean cMemoryOwn) {
this("btSphereShape", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btSphereShape_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btSphereShape obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btSphereShape(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public long operatorNew (long sizeInBytes) {
return CollisionJNI.btSphereShape_operatorNew__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDelete (long ptr) {
CollisionJNI.btSphereShape_operatorDelete__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNew (long arg0, long ptr) {
return CollisionJNI.btSphereShape_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDelete (long arg0, long arg1) {
CollisionJNI.btSphereShape_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1);
}
public long operatorNewArray (long sizeInBytes) {
return CollisionJNI.btSphereShape_operatorNewArray__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDeleteArray (long ptr) {
CollisionJNI.btSphereShape_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNewArray (long arg0, long ptr) {
return CollisionJNI.btSphereShape_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDeleteArray (long arg0, long arg1) {
CollisionJNI.btSphereShape_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1);
}
public btSphereShape (float radius) {
this(CollisionJNI.new_btSphereShape(radius), true);
}
public float getRadius () {
return CollisionJNI.btSphereShape_getRadius(swigCPtr, this);
}
public void setUnscaledRadius (float radius) {
CollisionJNI.btSphereShape_setUnscaledRadius(swigCPtr, this, radius);
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./gdx/test/com/badlogic/gdx/math/IntersectorTest.java |
package com.badlogic.gdx.math;
import com.badlogic.gdx.math.Intersector.SplitTriangle;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class IntersectorTest {
/** Compares two triangles for equality. Triangles must have the same winding, but may begin with different vertex. Values are
* epsilon compared, with default tolerance. Triangles are assumed to be valid triangles - no duplicate vertices. */
private static boolean triangleEquals (float[] base, int baseOffset, int stride, float[] comp) {
assertTrue(stride >= 3);
assertTrue(base.length - baseOffset >= 9);
assertTrue(comp.length == 9);
int offset = -1;
// Find first comp vertex in base triangle
for (int i = 0; i < 3; i++) {
int b = baseOffset + i * stride;
if (MathUtils.isEqual(base[b], comp[0]) && MathUtils.isEqual(base[b + 1], comp[1])
&& MathUtils.isEqual(base[b + 2], comp[2])) {
offset = i;
break;
}
}
assertTrue("Triangles do not have common first vertex.", offset != -1);
// Compare vertices
for (int i = 0; i < 3; i++) {
int b = baseOffset + ((offset + i) * stride) % (3 * stride);
int c = i * stride;
if (!MathUtils.isEqual(base[b], comp[c]) || !MathUtils.isEqual(base[b + 1], comp[c + 1])
|| !MathUtils.isEqual(base[b + 2], comp[c + 2])) {
return false;
}
}
return true;
}
@Test
public void testSplitTriangle () {
Plane plane = new Plane(new Vector3(1, 0, 0), 0);
SplitTriangle split = new SplitTriangle(3);
{// All back
float[] fTriangle = {-10, 0, 10, -1, 0, 0, -12, 0, 10}; // Whole triangle on the back side
Intersector.splitTriangle(fTriangle, plane, split);
assertTrue(split.numBack == 1);
assertTrue(split.numFront == 0);
assertTrue(split.total == 1);
assertTrue(triangleEquals(split.back, 0, 3, fTriangle));
fTriangle[4] = 5f;
assertFalse("Test is broken", triangleEquals(split.back, 0, 3, fTriangle));
}
{// All front
float[] fTriangle = {10, 0, 10, 1, 0, 0, 12, 0, 10}; // Whole triangle on the front side
Intersector.splitTriangle(fTriangle, plane, split);
assertTrue(split.numBack == 0);
assertTrue(split.numFront == 1);
assertTrue(split.total == 1);
assertTrue(triangleEquals(split.front, 0, 3, fTriangle));
}
{// Two back, one front
float[] triangle = {-10, 0, 10, 10, 0, 0, -10, 0, -10}; // ABC One vertex in front, two in back
Intersector.splitTriangle(triangle, plane, split); // Split points are D (0,0,5) and E (0,0,-5)
assertTrue(split.numBack == 2);
assertTrue(split.numFront == 1);
assertTrue(split.total == 3);
// There is only one way to triangulate front
assertTrue(triangleEquals(split.front, 0, 3, new float[] {0, 0, 5, 10, 0, 0, 0, 0, -5}));
// There are two ways to triangulate back
float[][] firstWay = {{-10, 0, 10, 0, 0, 5, 0, 0, -5}, {-10, 0, 10, 0, 0, -5, -10, 0, -10}};// ADE AEC
float[][] secondWay = {{-10, 0, 10, 0, 0, 5, -10, 0, -10}, {0, 0, 5, 0, 0, -5, -10, 0, -10}};// ADC DEC
float[] base = split.back;
boolean first = (triangleEquals(base, 0, 3, firstWay[0]) && triangleEquals(base, 9, 3, firstWay[1]))
|| (triangleEquals(base, 0, 3, firstWay[1]) && triangleEquals(base, 9, 3, firstWay[0]));
boolean second = (triangleEquals(base, 0, 3, secondWay[0]) && triangleEquals(base, 9, 3, secondWay[1]))
|| (triangleEquals(base, 0, 3, secondWay[1]) && triangleEquals(base, 9, 3, secondWay[0]));
assertTrue("Either first or second way must be right (first: " + first + ", second: " + second + ")", first ^ second);
}
{// Two front, one back
float[] triangle = {10, 0, 10, -10, 0, 0, 10, 0, -10}; // ABC One vertex in back, two in front
Intersector.splitTriangle(triangle, plane, split); // Split points are D (0,0,5) and E (0,0,-5)
assertTrue(split.numBack == 1);
assertTrue(split.numFront == 2);
assertTrue(split.total == 3);
// There is only one way to triangulate back
assertTrue(triangleEquals(split.back, 0, 3, new float[] {0, 0, 5, -10, 0, 0, 0, 0, -5}));
// There are two ways to triangulate front
float[][] firstWay = {{10, 0, 10, 0, 0, 5, 0, 0, -5}, {10, 0, 10, 0, 0, -5, 10, 0, -10}};// ADE AEC
float[][] secondWay = {{10, 0, 10, 0, 0, 5, 10, 0, -10}, {0, 0, 5, 0, 0, -5, 10, 0, -10}};// ADC DEC
float[] base = split.front;
boolean first = (triangleEquals(base, 0, 3, firstWay[0]) && triangleEquals(base, 9, 3, firstWay[1]))
|| (triangleEquals(base, 0, 3, firstWay[1]) && triangleEquals(base, 9, 3, firstWay[0]));
boolean second = (triangleEquals(base, 0, 3, secondWay[0]) && triangleEquals(base, 9, 3, secondWay[1]))
|| (triangleEquals(base, 0, 3, secondWay[1]) && triangleEquals(base, 9, 3, secondWay[0]));
assertTrue("Either first or second way must be right (first: " + first + ", second: " + second + ")", first ^ second);
}
}
@Test
public void intersectSegmentCircle () {
Circle circle = new Circle(5f, 5f, 4f);
// Segment intersects, both segment points outside circle
boolean intersects = Intersector.intersectSegmentCircle(new Vector2(0, 1f), new Vector2(12f, 3f), circle, null);
assertTrue(intersects);
// Segment intersects, only one of the points inside circle (and is aligned with center)
intersects = Intersector.intersectSegmentCircle(new Vector2(0, 5f), new Vector2(2f, 5f), circle, null);
assertTrue(intersects);
// Segment intersects, no points outside circle
intersects = Intersector.intersectSegmentCircle(new Vector2(5.5f, 6f), new Vector2(7f, 5.5f), circle, null);
assertTrue(intersects);
// Segment doesn't intersect
intersects = Intersector.intersectSegmentCircle(new Vector2(0f, 6f), new Vector2(0.5f, 2f), circle, null);
assertFalse(intersects);
// Segment is parallel to Y axis left of circle's center
Intersector.MinimumTranslationVector mtv = new Intersector.MinimumTranslationVector();
intersects = Intersector.intersectSegmentCircle(new Vector2(1.5f, 6f), new Vector2(1.5f, 3f), circle, mtv);
assertTrue(intersects);
assertTrue(mtv.normal.equals(new Vector2(-1f, 0)));
assertTrue(mtv.depth == 0.5f);
// Segment contains circle center point
intersects = Intersector.intersectSegmentCircle(new Vector2(4f, 5f), new Vector2(6f, 5f), circle, mtv);
assertTrue(intersects);
assertTrue(mtv.normal.equals(new Vector2(0, 1f)) || mtv.normal.equals(new Vector2(0f, -1f)));
assertTrue(mtv.depth == 4f);
// Segment contains circle center point which is the same as the end point
intersects = Intersector.intersectSegmentCircle(new Vector2(4f, 5f), new Vector2(5f, 5f), circle, mtv);
assertTrue(intersects);
assertTrue(mtv.normal.equals(new Vector2(0, 1f)) || mtv.normal.equals(new Vector2(0f, -1f)));
assertTrue(mtv.depth == 4f);
}
@Test
public void testIntersectPlanes () {
final int NEAR = 0;
final int FAR = 1;
final int LEFT = 2;
final int RIGHT = 3;
final int TOP = 4;
final int BOTTOM = 5;
/*
* camera = new PerspectiveCamera(60, 1280, 720); camera.direction.set(0, 0, 1); camera.near = 0.1f; camera.far = 100f;
* camera.update(); Plane[] planes = camera.frustum.planes;
*/
Plane[] planes = new Plane[6];
planes[NEAR] = new Plane(new Vector3(0.0f, 0.0f, 1.0f), -0.1f);
planes[FAR] = new Plane(new Vector3(0.0f, -0.0f, -1.0f), 99.99771f);
planes[LEFT] = new Plane(new Vector3(-0.69783056f, 0.0f, 0.71626294f), -9.3877316E-7f);
planes[RIGHT] = new Plane(new Vector3(0.6978352f, 0.0f, 0.71625835f), -0.0f);
planes[TOP] = new Plane(new Vector3(0.0f, -0.86602545f, 0.5f), -0.0f);
planes[BOTTOM] = new Plane(new Vector3(-0.0f, 0.86602545f, 0.5f), -0.0f);
Vector3 intersection = new Vector3();
Intersector.intersectPlanes(planes[TOP], planes[FAR], planes[LEFT], intersection);
assertEquals(102.63903f, intersection.x, 0.1f);
assertEquals(57.7337f, intersection.y, 0.1f);
assertEquals(100, intersection.z, 0.1f);
Intersector.intersectPlanes(planes[TOP], planes[FAR], planes[RIGHT], intersection);
assertEquals(-102.63903f, intersection.x, 0.1f);
assertEquals(57.7337f, intersection.y, 0.1f);
assertEquals(100, intersection.z, 0.1f);
Intersector.intersectPlanes(planes[BOTTOM], planes[FAR], planes[LEFT], intersection);
assertEquals(102.63903f, intersection.x, 0.1f);
assertEquals(-57.7337f, intersection.y, 0.1f);
assertEquals(100, intersection.z, 0.1f);
Intersector.intersectPlanes(planes[BOTTOM], planes[FAR], planes[RIGHT], intersection);
assertEquals(-102.63903f, intersection.x, 0.1f);
assertEquals(-57.7337f, intersection.y, 0.1f);
assertEquals(100, intersection.z, 0.1f);
}
@Test
public void testIsPointInTriangle2D () {
assertFalse(Intersector.isPointInTriangle(new Vector2(0.1f, 0), new Vector2(0, 0), new Vector2(1, 1), new Vector2(-1, -1)));
assertTrue(Intersector.isPointInTriangle(new Vector2(0, 0.1f), new Vector2(-1, 1), new Vector2(1, 1), new Vector2(-1, -2)));
}
@Test
public void testIsPointInTriangle3D () {
// 2D ---
assertFalse(Intersector.isPointInTriangle(new Vector3(0.1f, 0, 0), new Vector3(0, 0, 0), new Vector3(1, 1, 0),
new Vector3(-1, -1, 0)));
assertTrue(Intersector.isPointInTriangle(new Vector3(0, 0.1f, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0),
new Vector3(-1, -2, 0)));
// 3D ---
assertTrue(Intersector.isPointInTriangle(new Vector3(0.2f, 0, 1.25f), new Vector3(-1, 1, 0), new Vector3(1.4f, 0.99f, 2.5f),
new Vector3(-1, -2, 0)));
// 1.2f away.
assertFalse(Intersector.isPointInTriangle(new Vector3(2.6f, 0, 3.75f), new Vector3(-1, 1, 0),
new Vector3(1.4f, 0.99f, 2.5f), new Vector3(-1, -2, 0)));
// In an edge.
assertTrue(Intersector.isPointInTriangle(new Vector3(0, -0.5f, 0.5f), new Vector3(-1, 1, 0), new Vector3(1, 1, 1),
new Vector3(-1, -2, 0)));
// Really close to the edge.
float epsilon = 0.0000001f; // One more 0 will fail.
float almost1 = 1 - epsilon;
assertFalse(Intersector.isPointInTriangle(new Vector3(0, -0.5f, 0.5f), new Vector3(-1, 1, 0), new Vector3(almost1, 1, 1),
new Vector3(-1, -2, 0)));
// A really long distance away.
assertFalse(Intersector.isPointInTriangle(new Vector3(199f, 1f, 500f), new Vector3(-1, 1, 0), new Vector3(1, 1, 5f),
new Vector3(-1, -2, 0)));
assertFalse(Intersector.isPointInTriangle(new Vector3(-5120.8345f, 8946.126f, -3270.5813f),
new Vector3(50.008057f, 22.20586f, 124.62208f), new Vector3(62.282288f, 22.205864f, 109.665924f),
new Vector3(70.92052f, 7.205861f, 115.437805f)));
}
}
|
package com.badlogic.gdx.math;
import com.badlogic.gdx.math.Intersector.SplitTriangle;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class IntersectorTest {
/** Compares two triangles for equality. Triangles must have the same winding, but may begin with different vertex. Values are
* epsilon compared, with default tolerance. Triangles are assumed to be valid triangles - no duplicate vertices. */
private static boolean triangleEquals (float[] base, int baseOffset, int stride, float[] comp) {
assertTrue(stride >= 3);
assertTrue(base.length - baseOffset >= 9);
assertTrue(comp.length == 9);
int offset = -1;
// Find first comp vertex in base triangle
for (int i = 0; i < 3; i++) {
int b = baseOffset + i * stride;
if (MathUtils.isEqual(base[b], comp[0]) && MathUtils.isEqual(base[b + 1], comp[1])
&& MathUtils.isEqual(base[b + 2], comp[2])) {
offset = i;
break;
}
}
assertTrue("Triangles do not have common first vertex.", offset != -1);
// Compare vertices
for (int i = 0; i < 3; i++) {
int b = baseOffset + ((offset + i) * stride) % (3 * stride);
int c = i * stride;
if (!MathUtils.isEqual(base[b], comp[c]) || !MathUtils.isEqual(base[b + 1], comp[c + 1])
|| !MathUtils.isEqual(base[b + 2], comp[c + 2])) {
return false;
}
}
return true;
}
@Test
public void testSplitTriangle () {
Plane plane = new Plane(new Vector3(1, 0, 0), 0);
SplitTriangle split = new SplitTriangle(3);
{// All back
float[] fTriangle = {-10, 0, 10, -1, 0, 0, -12, 0, 10}; // Whole triangle on the back side
Intersector.splitTriangle(fTriangle, plane, split);
assertTrue(split.numBack == 1);
assertTrue(split.numFront == 0);
assertTrue(split.total == 1);
assertTrue(triangleEquals(split.back, 0, 3, fTriangle));
fTriangle[4] = 5f;
assertFalse("Test is broken", triangleEquals(split.back, 0, 3, fTriangle));
}
{// All front
float[] fTriangle = {10, 0, 10, 1, 0, 0, 12, 0, 10}; // Whole triangle on the front side
Intersector.splitTriangle(fTriangle, plane, split);
assertTrue(split.numBack == 0);
assertTrue(split.numFront == 1);
assertTrue(split.total == 1);
assertTrue(triangleEquals(split.front, 0, 3, fTriangle));
}
{// Two back, one front
float[] triangle = {-10, 0, 10, 10, 0, 0, -10, 0, -10}; // ABC One vertex in front, two in back
Intersector.splitTriangle(triangle, plane, split); // Split points are D (0,0,5) and E (0,0,-5)
assertTrue(split.numBack == 2);
assertTrue(split.numFront == 1);
assertTrue(split.total == 3);
// There is only one way to triangulate front
assertTrue(triangleEquals(split.front, 0, 3, new float[] {0, 0, 5, 10, 0, 0, 0, 0, -5}));
// There are two ways to triangulate back
float[][] firstWay = {{-10, 0, 10, 0, 0, 5, 0, 0, -5}, {-10, 0, 10, 0, 0, -5, -10, 0, -10}};// ADE AEC
float[][] secondWay = {{-10, 0, 10, 0, 0, 5, -10, 0, -10}, {0, 0, 5, 0, 0, -5, -10, 0, -10}};// ADC DEC
float[] base = split.back;
boolean first = (triangleEquals(base, 0, 3, firstWay[0]) && triangleEquals(base, 9, 3, firstWay[1]))
|| (triangleEquals(base, 0, 3, firstWay[1]) && triangleEquals(base, 9, 3, firstWay[0]));
boolean second = (triangleEquals(base, 0, 3, secondWay[0]) && triangleEquals(base, 9, 3, secondWay[1]))
|| (triangleEquals(base, 0, 3, secondWay[1]) && triangleEquals(base, 9, 3, secondWay[0]));
assertTrue("Either first or second way must be right (first: " + first + ", second: " + second + ")", first ^ second);
}
{// Two front, one back
float[] triangle = {10, 0, 10, -10, 0, 0, 10, 0, -10}; // ABC One vertex in back, two in front
Intersector.splitTriangle(triangle, plane, split); // Split points are D (0,0,5) and E (0,0,-5)
assertTrue(split.numBack == 1);
assertTrue(split.numFront == 2);
assertTrue(split.total == 3);
// There is only one way to triangulate back
assertTrue(triangleEquals(split.back, 0, 3, new float[] {0, 0, 5, -10, 0, 0, 0, 0, -5}));
// There are two ways to triangulate front
float[][] firstWay = {{10, 0, 10, 0, 0, 5, 0, 0, -5}, {10, 0, 10, 0, 0, -5, 10, 0, -10}};// ADE AEC
float[][] secondWay = {{10, 0, 10, 0, 0, 5, 10, 0, -10}, {0, 0, 5, 0, 0, -5, 10, 0, -10}};// ADC DEC
float[] base = split.front;
boolean first = (triangleEquals(base, 0, 3, firstWay[0]) && triangleEquals(base, 9, 3, firstWay[1]))
|| (triangleEquals(base, 0, 3, firstWay[1]) && triangleEquals(base, 9, 3, firstWay[0]));
boolean second = (triangleEquals(base, 0, 3, secondWay[0]) && triangleEquals(base, 9, 3, secondWay[1]))
|| (triangleEquals(base, 0, 3, secondWay[1]) && triangleEquals(base, 9, 3, secondWay[0]));
assertTrue("Either first or second way must be right (first: " + first + ", second: " + second + ")", first ^ second);
}
}
@Test
public void intersectSegmentCircle () {
Circle circle = new Circle(5f, 5f, 4f);
// Segment intersects, both segment points outside circle
boolean intersects = Intersector.intersectSegmentCircle(new Vector2(0, 1f), new Vector2(12f, 3f), circle, null);
assertTrue(intersects);
// Segment intersects, only one of the points inside circle (and is aligned with center)
intersects = Intersector.intersectSegmentCircle(new Vector2(0, 5f), new Vector2(2f, 5f), circle, null);
assertTrue(intersects);
// Segment intersects, no points outside circle
intersects = Intersector.intersectSegmentCircle(new Vector2(5.5f, 6f), new Vector2(7f, 5.5f), circle, null);
assertTrue(intersects);
// Segment doesn't intersect
intersects = Intersector.intersectSegmentCircle(new Vector2(0f, 6f), new Vector2(0.5f, 2f), circle, null);
assertFalse(intersects);
// Segment is parallel to Y axis left of circle's center
Intersector.MinimumTranslationVector mtv = new Intersector.MinimumTranslationVector();
intersects = Intersector.intersectSegmentCircle(new Vector2(1.5f, 6f), new Vector2(1.5f, 3f), circle, mtv);
assertTrue(intersects);
assertTrue(mtv.normal.equals(new Vector2(-1f, 0)));
assertTrue(mtv.depth == 0.5f);
// Segment contains circle center point
intersects = Intersector.intersectSegmentCircle(new Vector2(4f, 5f), new Vector2(6f, 5f), circle, mtv);
assertTrue(intersects);
assertTrue(mtv.normal.equals(new Vector2(0, 1f)) || mtv.normal.equals(new Vector2(0f, -1f)));
assertTrue(mtv.depth == 4f);
// Segment contains circle center point which is the same as the end point
intersects = Intersector.intersectSegmentCircle(new Vector2(4f, 5f), new Vector2(5f, 5f), circle, mtv);
assertTrue(intersects);
assertTrue(mtv.normal.equals(new Vector2(0, 1f)) || mtv.normal.equals(new Vector2(0f, -1f)));
assertTrue(mtv.depth == 4f);
}
@Test
public void testIntersectPlanes () {
final int NEAR = 0;
final int FAR = 1;
final int LEFT = 2;
final int RIGHT = 3;
final int TOP = 4;
final int BOTTOM = 5;
/*
* camera = new PerspectiveCamera(60, 1280, 720); camera.direction.set(0, 0, 1); camera.near = 0.1f; camera.far = 100f;
* camera.update(); Plane[] planes = camera.frustum.planes;
*/
Plane[] planes = new Plane[6];
planes[NEAR] = new Plane(new Vector3(0.0f, 0.0f, 1.0f), -0.1f);
planes[FAR] = new Plane(new Vector3(0.0f, -0.0f, -1.0f), 99.99771f);
planes[LEFT] = new Plane(new Vector3(-0.69783056f, 0.0f, 0.71626294f), -9.3877316E-7f);
planes[RIGHT] = new Plane(new Vector3(0.6978352f, 0.0f, 0.71625835f), -0.0f);
planes[TOP] = new Plane(new Vector3(0.0f, -0.86602545f, 0.5f), -0.0f);
planes[BOTTOM] = new Plane(new Vector3(-0.0f, 0.86602545f, 0.5f), -0.0f);
Vector3 intersection = new Vector3();
Intersector.intersectPlanes(planes[TOP], planes[FAR], planes[LEFT], intersection);
assertEquals(102.63903f, intersection.x, 0.1f);
assertEquals(57.7337f, intersection.y, 0.1f);
assertEquals(100, intersection.z, 0.1f);
Intersector.intersectPlanes(planes[TOP], planes[FAR], planes[RIGHT], intersection);
assertEquals(-102.63903f, intersection.x, 0.1f);
assertEquals(57.7337f, intersection.y, 0.1f);
assertEquals(100, intersection.z, 0.1f);
Intersector.intersectPlanes(planes[BOTTOM], planes[FAR], planes[LEFT], intersection);
assertEquals(102.63903f, intersection.x, 0.1f);
assertEquals(-57.7337f, intersection.y, 0.1f);
assertEquals(100, intersection.z, 0.1f);
Intersector.intersectPlanes(planes[BOTTOM], planes[FAR], planes[RIGHT], intersection);
assertEquals(-102.63903f, intersection.x, 0.1f);
assertEquals(-57.7337f, intersection.y, 0.1f);
assertEquals(100, intersection.z, 0.1f);
}
@Test
public void testIsPointInTriangle2D () {
assertFalse(Intersector.isPointInTriangle(new Vector2(0.1f, 0), new Vector2(0, 0), new Vector2(1, 1), new Vector2(-1, -1)));
assertTrue(Intersector.isPointInTriangle(new Vector2(0, 0.1f), new Vector2(-1, 1), new Vector2(1, 1), new Vector2(-1, -2)));
}
@Test
public void testIsPointInTriangle3D () {
// 2D ---
assertFalse(Intersector.isPointInTriangle(new Vector3(0.1f, 0, 0), new Vector3(0, 0, 0), new Vector3(1, 1, 0),
new Vector3(-1, -1, 0)));
assertTrue(Intersector.isPointInTriangle(new Vector3(0, 0.1f, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0),
new Vector3(-1, -2, 0)));
// 3D ---
assertTrue(Intersector.isPointInTriangle(new Vector3(0.2f, 0, 1.25f), new Vector3(-1, 1, 0), new Vector3(1.4f, 0.99f, 2.5f),
new Vector3(-1, -2, 0)));
// 1.2f away.
assertFalse(Intersector.isPointInTriangle(new Vector3(2.6f, 0, 3.75f), new Vector3(-1, 1, 0),
new Vector3(1.4f, 0.99f, 2.5f), new Vector3(-1, -2, 0)));
// In an edge.
assertTrue(Intersector.isPointInTriangle(new Vector3(0, -0.5f, 0.5f), new Vector3(-1, 1, 0), new Vector3(1, 1, 1),
new Vector3(-1, -2, 0)));
// Really close to the edge.
float epsilon = 0.0000001f; // One more 0 will fail.
float almost1 = 1 - epsilon;
assertFalse(Intersector.isPointInTriangle(new Vector3(0, -0.5f, 0.5f), new Vector3(-1, 1, 0), new Vector3(almost1, 1, 1),
new Vector3(-1, -2, 0)));
// A really long distance away.
assertFalse(Intersector.isPointInTriangle(new Vector3(199f, 1f, 500f), new Vector3(-1, 1, 0), new Vector3(1, 1, 5f),
new Vector3(-1, -2, 0)));
assertFalse(Intersector.isPointInTriangle(new Vector3(-5120.8345f, 8946.126f, -3270.5813f),
new Vector3(50.008057f, 22.20586f, 124.62208f), new Vector3(62.282288f, 22.205864f, 109.665924f),
new Vector3(70.92052f, 7.205861f, 115.437805f)));
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./gdx/src/com/badlogic/gdx/scenes/scene2d/actions/LayoutAction.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.scenes.scene2d.actions;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.Layout;
import com.badlogic.gdx.utils.GdxRuntimeException;
/** Sets an actor's {@link Layout#setLayoutEnabled(boolean) layout} to enabled or disabled. The actor must implements
* {@link Layout}.
* @author Nathan Sweet */
public class LayoutAction extends Action {
private boolean enabled;
public void setTarget (Actor actor) {
if (actor != null && !(actor instanceof Layout)) throw new GdxRuntimeException("Actor must implement layout: " + actor);
super.setTarget(actor);
}
public boolean act (float delta) {
((Layout)target).setLayoutEnabled(enabled);
return true;
}
public boolean isEnabled () {
return enabled;
}
public void setLayoutEnabled (boolean enabled) {
this.enabled = enabled;
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.scenes.scene2d.actions;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.Layout;
import com.badlogic.gdx.utils.GdxRuntimeException;
/** Sets an actor's {@link Layout#setLayoutEnabled(boolean) layout} to enabled or disabled. The actor must implements
* {@link Layout}.
* @author Nathan Sweet */
public class LayoutAction extends Action {
private boolean enabled;
public void setTarget (Actor actor) {
if (actor != null && !(actor instanceof Layout)) throw new GdxRuntimeException("Actor must implement layout: " + actor);
super.setTarget(actor);
}
public boolean act (float delta) {
((Layout)target).setLayoutEnabled(enabled);
return true;
}
public boolean isEnabled () {
return enabled;
}
public void setLayoutEnabled (boolean enabled) {
this.enabled = enabled;
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteHeapByteBuffer.java | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.nio;
import com.google.gwt.corp.compatibility.Numbers;
/** HeapByteBuffer, ReadWriteHeapByteBuffer and ReadOnlyHeapByteBuffer compose the implementation of array based byte buffers.
* <p>
* ReadWriteHeapByteBuffer extends HeapByteBuffer with all the write methods.
* </p>
* <p>
* This class is marked final for runtime performance.
* </p>
*/
final class ReadWriteHeapByteBuffer extends HeapByteBuffer {
static ReadWriteHeapByteBuffer copy (HeapByteBuffer other, int markOfOther) {
ReadWriteHeapByteBuffer buf = new ReadWriteHeapByteBuffer(other.backingArray, other.capacity(), other.offset);
buf.limit = other.limit();
buf.position = other.position();
buf.mark = markOfOther;
buf.order(other.order());
return buf;
}
ReadWriteHeapByteBuffer (byte[] backingArray) {
super(backingArray);
}
ReadWriteHeapByteBuffer (int capacity) {
super(capacity);
}
ReadWriteHeapByteBuffer (byte[] backingArray, int capacity, int arrayOffset) {
super(backingArray, capacity, arrayOffset);
}
public ByteBuffer asReadOnlyBuffer () {
return ReadOnlyHeapByteBuffer.copy(this, mark);
}
public ByteBuffer compact () {
System.arraycopy(backingArray, position + offset, backingArray, offset, remaining());
position = limit - position;
limit = capacity;
mark = UNSET_MARK;
return this;
}
public ByteBuffer duplicate () {
return copy(this, mark);
}
public boolean isReadOnly () {
return false;
}
protected byte[] protectedArray () {
return backingArray;
}
protected int protectedArrayOffset () {
return offset;
}
protected boolean protectedHasArray () {
return true;
}
public ByteBuffer put (byte b) {
if (position == limit) {
throw new BufferOverflowException();
}
backingArray[offset + position++] = b;
return this;
}
public ByteBuffer put (int index, byte b) {
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
backingArray[offset + index] = b;
return this;
}
/*
* Override ByteBuffer.put(byte[], int, int) to improve performance.
*
* (non-Javadoc)
*
* @see java.nio.ByteBuffer#put(byte[], int, int)
*/
public ByteBuffer put (byte[] src, int off, int len) {
if (off < 0 || len < 0 || (long)off + (long)len > src.length) {
throw new IndexOutOfBoundsException();
}
if (len > remaining()) {
throw new BufferOverflowException();
}
if (isReadOnly()) {
throw new ReadOnlyBufferException();
}
System.arraycopy(src, off, backingArray, offset + position, len);
position += len;
return this;
}
public ByteBuffer putDouble (double value) {
return putLong(Numbers.doubleToRawLongBits(value));
}
public ByteBuffer putDouble (int index, double value) {
return putLong(index, Numbers.doubleToRawLongBits(value));
}
public ByteBuffer putFloat (float value) {
return putInt(Numbers.floatToIntBits(value));
}
public ByteBuffer putFloat (int index, float value) {
return putInt(index, Numbers.floatToIntBits(value));
}
public ByteBuffer putInt (int value) {
int newPosition = position + 4;
if (newPosition > limit) {
throw new BufferOverflowException();
}
store(position, value);
position = newPosition;
return this;
}
public ByteBuffer putInt (int index, int value) {
if (index < 0 || (long)index + 4 > limit) {
throw new IndexOutOfBoundsException();
}
store(index, value);
return this;
}
public ByteBuffer putLong (int index, long value) {
if (index < 0 || (long)index + 8 > limit) {
throw new IndexOutOfBoundsException();
}
store(index, value);
return this;
}
public ByteBuffer putLong (long value) {
int newPosition = position + 8;
if (newPosition > limit) {
throw new BufferOverflowException();
}
store(position, value);
position = newPosition;
return this;
}
public ByteBuffer putShort (int index, short value) {
if (index < 0 || (long)index + 2 > limit) {
throw new IndexOutOfBoundsException();
}
store(index, value);
return this;
}
public ByteBuffer putShort (short value) {
int newPosition = position + 2;
if (newPosition > limit) {
throw new BufferOverflowException();
}
store(position, value);
position = newPosition;
return this;
}
public ByteBuffer slice () {
ReadWriteHeapByteBuffer slice = new ReadWriteHeapByteBuffer(backingArray, remaining(), offset + position);
slice.order = order;
return slice;
}
}
| /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.nio;
import com.google.gwt.corp.compatibility.Numbers;
/** HeapByteBuffer, ReadWriteHeapByteBuffer and ReadOnlyHeapByteBuffer compose the implementation of array based byte buffers.
* <p>
* ReadWriteHeapByteBuffer extends HeapByteBuffer with all the write methods.
* </p>
* <p>
* This class is marked final for runtime performance.
* </p>
*/
final class ReadWriteHeapByteBuffer extends HeapByteBuffer {
static ReadWriteHeapByteBuffer copy (HeapByteBuffer other, int markOfOther) {
ReadWriteHeapByteBuffer buf = new ReadWriteHeapByteBuffer(other.backingArray, other.capacity(), other.offset);
buf.limit = other.limit();
buf.position = other.position();
buf.mark = markOfOther;
buf.order(other.order());
return buf;
}
ReadWriteHeapByteBuffer (byte[] backingArray) {
super(backingArray);
}
ReadWriteHeapByteBuffer (int capacity) {
super(capacity);
}
ReadWriteHeapByteBuffer (byte[] backingArray, int capacity, int arrayOffset) {
super(backingArray, capacity, arrayOffset);
}
public ByteBuffer asReadOnlyBuffer () {
return ReadOnlyHeapByteBuffer.copy(this, mark);
}
public ByteBuffer compact () {
System.arraycopy(backingArray, position + offset, backingArray, offset, remaining());
position = limit - position;
limit = capacity;
mark = UNSET_MARK;
return this;
}
public ByteBuffer duplicate () {
return copy(this, mark);
}
public boolean isReadOnly () {
return false;
}
protected byte[] protectedArray () {
return backingArray;
}
protected int protectedArrayOffset () {
return offset;
}
protected boolean protectedHasArray () {
return true;
}
public ByteBuffer put (byte b) {
if (position == limit) {
throw new BufferOverflowException();
}
backingArray[offset + position++] = b;
return this;
}
public ByteBuffer put (int index, byte b) {
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
backingArray[offset + index] = b;
return this;
}
/*
* Override ByteBuffer.put(byte[], int, int) to improve performance.
*
* (non-Javadoc)
*
* @see java.nio.ByteBuffer#put(byte[], int, int)
*/
public ByteBuffer put (byte[] src, int off, int len) {
if (off < 0 || len < 0 || (long)off + (long)len > src.length) {
throw new IndexOutOfBoundsException();
}
if (len > remaining()) {
throw new BufferOverflowException();
}
if (isReadOnly()) {
throw new ReadOnlyBufferException();
}
System.arraycopy(src, off, backingArray, offset + position, len);
position += len;
return this;
}
public ByteBuffer putDouble (double value) {
return putLong(Numbers.doubleToRawLongBits(value));
}
public ByteBuffer putDouble (int index, double value) {
return putLong(index, Numbers.doubleToRawLongBits(value));
}
public ByteBuffer putFloat (float value) {
return putInt(Numbers.floatToIntBits(value));
}
public ByteBuffer putFloat (int index, float value) {
return putInt(index, Numbers.floatToIntBits(value));
}
public ByteBuffer putInt (int value) {
int newPosition = position + 4;
if (newPosition > limit) {
throw new BufferOverflowException();
}
store(position, value);
position = newPosition;
return this;
}
public ByteBuffer putInt (int index, int value) {
if (index < 0 || (long)index + 4 > limit) {
throw new IndexOutOfBoundsException();
}
store(index, value);
return this;
}
public ByteBuffer putLong (int index, long value) {
if (index < 0 || (long)index + 8 > limit) {
throw new IndexOutOfBoundsException();
}
store(index, value);
return this;
}
public ByteBuffer putLong (long value) {
int newPosition = position + 8;
if (newPosition > limit) {
throw new BufferOverflowException();
}
store(position, value);
position = newPosition;
return this;
}
public ByteBuffer putShort (int index, short value) {
if (index < 0 || (long)index + 2 > limit) {
throw new IndexOutOfBoundsException();
}
store(index, value);
return this;
}
public ByteBuffer putShort (short value) {
int newPosition = position + 2;
if (newPosition > limit) {
throw new BufferOverflowException();
}
store(position, value);
position = newPosition;
return this;
}
public ByteBuffer slice () {
ReadWriteHeapByteBuffer slice = new ReadWriteHeapByteBuffer(backingArray, remaining(), offset + position);
slice.order = order;
return slice;
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./gdx/src/com/badlogic/gdx/scenes/scene2d/actions/EventAction.java |
package com.badlogic.gdx.scenes.scene2d.actions;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Event;
import com.badlogic.gdx.scenes.scene2d.EventListener;
import com.badlogic.gdx.utils.reflect.ClassReflection;
/** Adds a listener to the actor for a specific event type and does not complete until {@link #handle(Event)} returns true.
* @author JavadocMD
* @author Nathan Sweet */
abstract public class EventAction<T extends Event> extends Action {
final Class<? extends T> eventClass;
boolean result, active;
private final EventListener listener = new EventListener() {
public boolean handle (Event event) {
if (!active || !ClassReflection.isInstance(eventClass, event)) return false;
result = EventAction.this.handle((T)event);
return result;
}
};
public EventAction (Class<? extends T> eventClass) {
this.eventClass = eventClass;
}
public void restart () {
result = false;
active = false;
}
public void setTarget (Actor newTarget) {
if (target != null) target.removeListener(listener);
super.setTarget(newTarget);
if (newTarget != null) newTarget.addListener(listener);
}
/** Called when the specific type of event occurs on the actor.
* @return true if the event should be considered {@link Event#handle() handled} and this EventAction considered complete. */
abstract public boolean handle (T event);
public boolean act (float delta) {
active = true;
return result;
}
public boolean isActive () {
return active;
}
public void setActive (boolean active) {
this.active = active;
}
}
|
package com.badlogic.gdx.scenes.scene2d.actions;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Event;
import com.badlogic.gdx.scenes.scene2d.EventListener;
import com.badlogic.gdx.utils.reflect.ClassReflection;
/** Adds a listener to the actor for a specific event type and does not complete until {@link #handle(Event)} returns true.
* @author JavadocMD
* @author Nathan Sweet */
abstract public class EventAction<T extends Event> extends Action {
final Class<? extends T> eventClass;
boolean result, active;
private final EventListener listener = new EventListener() {
public boolean handle (Event event) {
if (!active || !ClassReflection.isInstance(eventClass, event)) return false;
result = EventAction.this.handle((T)event);
return result;
}
};
public EventAction (Class<? extends T> eventClass) {
this.eventClass = eventClass;
}
public void restart () {
result = false;
active = false;
}
public void setTarget (Actor newTarget) {
if (target != null) target.removeListener(listener);
super.setTarget(newTarget);
if (newTarget != null) newTarget.addListener(listener);
}
/** Called when the specific type of event occurs on the actor.
* @return true if the event should be considered {@link Event#handle() handled} and this EventAction considered complete. */
abstract public boolean handle (T event);
public boolean act (float delta) {
active = true;
return result;
}
public boolean isActive () {
return active;
}
public void setActive (boolean active) {
this.active = active;
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./tests/gdx-tests/src/com/badlogic/gdx/tests/g3d/shadows/system/realistic/MainShader.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tests.g3d.shadows.system.realistic;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.g3d.Attributes;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.attributes.DirectionalLightsAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.SpotLightsAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.environment.SpotLight;
import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.tests.g3d.shadows.system.BaseShadowSystem.LightProperties;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap;
/** This shader is used by the realistic shadow system. This shader supports normal mapping and specular mapping
* @author realitix */
public class MainShader extends DefaultShader {
public static class Config extends DefaultShader.Config {
public RealisticShadowSystem shadowSystem;
public Config (RealisticShadowSystem shadowSystem) {
super();
numBones = 12;
numPointLights = 2;
numSpotLights = 5;
numDirectionalLights = 2;
this.shadowSystem = shadowSystem;
}
}
/** **** Directional shadow **** */
protected final int u_dirShadows0uvTransform = register(new Uniform("u_dirShadows[0].uvTransform"));
protected final int u_dirShadows1uvTransform = register(new Uniform("u_dirShadows[1].uvTransform"));
protected int dirShadowsLoc;
protected int dirShadowsUvTransformOffset;
protected int dirShadowsSize;
// Shadow projViewTrans
protected int u_dirShadowMapProjViewTrans0 = register(new Uniform("u_dirShadowMapProjViewTrans[0]"));
protected int u_dirShadowMapProjViewTrans1 = register(new Uniform("u_dirShadowMapProjViewTrans[1]"));
protected int dirShadowMapProjViewTransLoc;
protected int dirShadowMapProjViewTransSize;
// Shadow UVTransform
protected int u_dirShadowMapUVTransform0 = register(new Uniform("u_dirShadowMapUVTransform[0]"));
protected int u_dirShadowMapUVTransform1 = register(new Uniform("u_dirShadowMapUVTransform[1]"));
protected int dirShadowMapUVTransformLoc;
protected int dirShadowMapUVTransformSize;
/** **** Spot shadow **** */
protected final int u_spotShadows0uvTransform = register(new Uniform("u_spotShadows[0].uvTransform"));
protected final int u_spotShadows1uvTransform = register(new Uniform("u_spotShadows[1].uvTransform"));
protected int spotShadowsLoc;
protected int spotShadowsUvTransformOffset;
protected int spotShadowsSize;
// Shadow projViewTrans
protected int u_spotShadowMapProjViewTrans0 = register(new Uniform("u_spotShadowMapProjViewTrans[0]"));
protected int u_spotShadowMapProjViewTrans1 = register(new Uniform("u_spotShadowMapProjViewTrans[1]"));
protected int spotShadowMapProjViewTransLoc;
protected int spotShadowMapProjViewTransSize;
// Shadow UVTransform
protected int u_spotShadowMapUVTransform0 = register(new Uniform("u_spotShadowMapUVTransform[0]"));
protected int u_spotShadowMapUVTransform1 = register(new Uniform("u_spotShadowMapUVTransform[1]"));
protected int spotShadowMapUVTransformLoc;
protected int spotShadowMapUVTransformSize;
protected RealisticShadowSystem shadowSystem;
private static String defaultVertexShader = null;
public static String getDefaultVertexShader () {
if (defaultVertexShader == null) defaultVertexShader = Gdx.files
.classpath("com/badlogic/gdx/tests/g3d/shadows/system/realistic/main.vertex.glsl").readString();
return defaultVertexShader;
}
private static String defaultFragmentShader = null;
public static String getDefaultFragmentShader () {
if (defaultFragmentShader == null) defaultFragmentShader = Gdx.files
.classpath("com/badlogic/gdx/tests/g3d/shadows/system/realistic/main.fragment.glsl").readString();
return defaultFragmentShader;
}
public static String createPrefix (final Renderable renderable, final Config config) {
return DefaultShader.createPrefix(renderable, config);
}
public MainShader (final Renderable renderable, final Config config) {
this(renderable, config, createPrefix(renderable, config));
}
public MainShader (final Renderable renderable, final Config config, final String prefix) {
this(renderable, config, prefix, getDefaultVertexShader(), getDefaultFragmentShader());
}
public MainShader (final Renderable renderable, final Config config, final String prefix, final String vertexShader,
final String fragmentShader) {
this(renderable, config, new ShaderProgram(prefix + vertexShader, prefix + fragmentShader));
}
public MainShader (final Renderable renderable, final Config config, final ShaderProgram shaderProgram) {
super(renderable, config, shaderProgram);
this.shadowSystem = config.shadowSystem;
}
@Override
public void init () {
super.init();
// Directional Shadow
dirShadowsLoc = loc(u_dirShadows0uvTransform);
dirShadowsUvTransformOffset = loc(u_dirShadows0uvTransform) - dirShadowsLoc;
dirShadowsSize = loc(u_dirShadows1uvTransform) - dirShadowsLoc;
if (dirShadowsSize < 0) dirShadowsSize = 0;
dirShadowMapProjViewTransLoc = loc(u_dirShadowMapProjViewTrans0);
dirShadowMapProjViewTransSize = loc(u_dirShadowMapProjViewTrans1) - dirShadowMapProjViewTransLoc;
dirShadowMapUVTransformLoc = loc(u_dirShadowMapUVTransform0);
dirShadowMapUVTransformSize = loc(u_dirShadowMapUVTransform1) - dirShadowMapUVTransformLoc;
// Spot Shadow
spotShadowsLoc = loc(u_spotShadows0uvTransform);
spotShadowsUvTransformOffset = loc(u_spotShadows0uvTransform) - spotShadowsLoc;
spotShadowsSize = loc(u_spotShadows1uvTransform) - spotShadowsLoc;
if (spotShadowsSize < 0) spotShadowsSize = 0;
spotShadowMapProjViewTransLoc = loc(u_spotShadowMapProjViewTrans0);
spotShadowMapProjViewTransSize = loc(u_spotShadowMapProjViewTrans1) - spotShadowMapProjViewTransLoc;
spotShadowMapUVTransformLoc = loc(u_spotShadowMapUVTransform0);
spotShadowMapUVTransformSize = loc(u_spotShadowMapUVTransform1) - spotShadowMapUVTransformLoc;
}
@Override
protected void bindLights (final Renderable renderable, final Attributes attributes) {
super.bindLights(renderable, attributes);
final Environment environment = renderable.environment;
bindDirectionalShadows(attributes);
bindSpotShadows(attributes);
if (shadowSystem.getTexture() != null) {
set(u_shadowTexture, shadowSystem.getTexture());
}
}
public void bindDirectionalShadows (final Attributes attributes) {
final DirectionalLightsAttribute dla = attributes.get(DirectionalLightsAttribute.class, DirectionalLightsAttribute.Type);
final Array<DirectionalLight> dirs = dla == null ? null : dla.lights;
if (dirLightsLoc >= 0) {
for (int i = 0; i < directionalLights.length; i++) {
if (dirs == null || dirs.size <= i) {
continue;
}
int idx = dirShadowsLoc + i * dirShadowsSize;
// Shadow
ObjectMap<DirectionalLight, LightProperties> dirCameras = shadowSystem.getDirectionalCameras();
DirectionalLight dl = dirs.get(i);
if (shadowSystem.hasLight(dl)) {
// UVTransform
final TextureRegion tr = dirCameras.get(dl).region;
Camera cam = dirCameras.get(dl).camera;
if (cam != null) {
program.setUniformf(idx + dirShadowsUvTransformOffset, tr.getU(), tr.getV(), tr.getU2() - tr.getU(),
tr.getV2() - tr.getV());
// ProjViewTrans
idx = dirShadowMapProjViewTransLoc + i * dirShadowMapProjViewTransSize;
program.setUniformMatrix(idx, dirCameras.get(dl).camera.combined);
}
}
if (dirLightsSize <= 0) break;
}
}
}
public void bindSpotShadows (final Attributes attributes) {
final SpotLightsAttribute sla = attributes.get(SpotLightsAttribute.class, SpotLightsAttribute.Type);
final Array<SpotLight> spots = sla == null ? null : sla.lights;
if (spotLightsLoc >= 0) {
for (int i = 0; i < spotLights.length; i++) {
if (spots == null || spots.size <= i) {
continue;
}
int idx = spotShadowsLoc + i * spotShadowsSize;
// Shadow
ObjectMap<SpotLight, LightProperties> spotCameras = shadowSystem.getSpotCameras();
SpotLight sl = spots.get(i);
if (shadowSystem.hasLight(sl)) {
// UVTransform
final TextureRegion tr = spotCameras.get(sl).region;
Camera cam = spotCameras.get(sl).camera;
if (cam != null) {
program.setUniformf(idx + spotShadowsUvTransformOffset, tr.getU(), tr.getV(), tr.getU2() - tr.getU(),
tr.getV2() - tr.getV());
// ProjViewTrans
idx = spotShadowMapProjViewTransLoc + i * spotShadowMapProjViewTransSize;
program.setUniformMatrix(idx, spotCameras.get(sl).camera.combined);
}
}
if (spotLightsSize <= 0) break;
}
}
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tests.g3d.shadows.system.realistic;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.g3d.Attributes;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.attributes.DirectionalLightsAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.SpotLightsAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.environment.SpotLight;
import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.tests.g3d.shadows.system.BaseShadowSystem.LightProperties;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap;
/** This shader is used by the realistic shadow system. This shader supports normal mapping and specular mapping
* @author realitix */
public class MainShader extends DefaultShader {
public static class Config extends DefaultShader.Config {
public RealisticShadowSystem shadowSystem;
public Config (RealisticShadowSystem shadowSystem) {
super();
numBones = 12;
numPointLights = 2;
numSpotLights = 5;
numDirectionalLights = 2;
this.shadowSystem = shadowSystem;
}
}
/** **** Directional shadow **** */
protected final int u_dirShadows0uvTransform = register(new Uniform("u_dirShadows[0].uvTransform"));
protected final int u_dirShadows1uvTransform = register(new Uniform("u_dirShadows[1].uvTransform"));
protected int dirShadowsLoc;
protected int dirShadowsUvTransformOffset;
protected int dirShadowsSize;
// Shadow projViewTrans
protected int u_dirShadowMapProjViewTrans0 = register(new Uniform("u_dirShadowMapProjViewTrans[0]"));
protected int u_dirShadowMapProjViewTrans1 = register(new Uniform("u_dirShadowMapProjViewTrans[1]"));
protected int dirShadowMapProjViewTransLoc;
protected int dirShadowMapProjViewTransSize;
// Shadow UVTransform
protected int u_dirShadowMapUVTransform0 = register(new Uniform("u_dirShadowMapUVTransform[0]"));
protected int u_dirShadowMapUVTransform1 = register(new Uniform("u_dirShadowMapUVTransform[1]"));
protected int dirShadowMapUVTransformLoc;
protected int dirShadowMapUVTransformSize;
/** **** Spot shadow **** */
protected final int u_spotShadows0uvTransform = register(new Uniform("u_spotShadows[0].uvTransform"));
protected final int u_spotShadows1uvTransform = register(new Uniform("u_spotShadows[1].uvTransform"));
protected int spotShadowsLoc;
protected int spotShadowsUvTransformOffset;
protected int spotShadowsSize;
// Shadow projViewTrans
protected int u_spotShadowMapProjViewTrans0 = register(new Uniform("u_spotShadowMapProjViewTrans[0]"));
protected int u_spotShadowMapProjViewTrans1 = register(new Uniform("u_spotShadowMapProjViewTrans[1]"));
protected int spotShadowMapProjViewTransLoc;
protected int spotShadowMapProjViewTransSize;
// Shadow UVTransform
protected int u_spotShadowMapUVTransform0 = register(new Uniform("u_spotShadowMapUVTransform[0]"));
protected int u_spotShadowMapUVTransform1 = register(new Uniform("u_spotShadowMapUVTransform[1]"));
protected int spotShadowMapUVTransformLoc;
protected int spotShadowMapUVTransformSize;
protected RealisticShadowSystem shadowSystem;
private static String defaultVertexShader = null;
public static String getDefaultVertexShader () {
if (defaultVertexShader == null) defaultVertexShader = Gdx.files
.classpath("com/badlogic/gdx/tests/g3d/shadows/system/realistic/main.vertex.glsl").readString();
return defaultVertexShader;
}
private static String defaultFragmentShader = null;
public static String getDefaultFragmentShader () {
if (defaultFragmentShader == null) defaultFragmentShader = Gdx.files
.classpath("com/badlogic/gdx/tests/g3d/shadows/system/realistic/main.fragment.glsl").readString();
return defaultFragmentShader;
}
public static String createPrefix (final Renderable renderable, final Config config) {
return DefaultShader.createPrefix(renderable, config);
}
public MainShader (final Renderable renderable, final Config config) {
this(renderable, config, createPrefix(renderable, config));
}
public MainShader (final Renderable renderable, final Config config, final String prefix) {
this(renderable, config, prefix, getDefaultVertexShader(), getDefaultFragmentShader());
}
public MainShader (final Renderable renderable, final Config config, final String prefix, final String vertexShader,
final String fragmentShader) {
this(renderable, config, new ShaderProgram(prefix + vertexShader, prefix + fragmentShader));
}
public MainShader (final Renderable renderable, final Config config, final ShaderProgram shaderProgram) {
super(renderable, config, shaderProgram);
this.shadowSystem = config.shadowSystem;
}
@Override
public void init () {
super.init();
// Directional Shadow
dirShadowsLoc = loc(u_dirShadows0uvTransform);
dirShadowsUvTransformOffset = loc(u_dirShadows0uvTransform) - dirShadowsLoc;
dirShadowsSize = loc(u_dirShadows1uvTransform) - dirShadowsLoc;
if (dirShadowsSize < 0) dirShadowsSize = 0;
dirShadowMapProjViewTransLoc = loc(u_dirShadowMapProjViewTrans0);
dirShadowMapProjViewTransSize = loc(u_dirShadowMapProjViewTrans1) - dirShadowMapProjViewTransLoc;
dirShadowMapUVTransformLoc = loc(u_dirShadowMapUVTransform0);
dirShadowMapUVTransformSize = loc(u_dirShadowMapUVTransform1) - dirShadowMapUVTransformLoc;
// Spot Shadow
spotShadowsLoc = loc(u_spotShadows0uvTransform);
spotShadowsUvTransformOffset = loc(u_spotShadows0uvTransform) - spotShadowsLoc;
spotShadowsSize = loc(u_spotShadows1uvTransform) - spotShadowsLoc;
if (spotShadowsSize < 0) spotShadowsSize = 0;
spotShadowMapProjViewTransLoc = loc(u_spotShadowMapProjViewTrans0);
spotShadowMapProjViewTransSize = loc(u_spotShadowMapProjViewTrans1) - spotShadowMapProjViewTransLoc;
spotShadowMapUVTransformLoc = loc(u_spotShadowMapUVTransform0);
spotShadowMapUVTransformSize = loc(u_spotShadowMapUVTransform1) - spotShadowMapUVTransformLoc;
}
@Override
protected void bindLights (final Renderable renderable, final Attributes attributes) {
super.bindLights(renderable, attributes);
final Environment environment = renderable.environment;
bindDirectionalShadows(attributes);
bindSpotShadows(attributes);
if (shadowSystem.getTexture() != null) {
set(u_shadowTexture, shadowSystem.getTexture());
}
}
public void bindDirectionalShadows (final Attributes attributes) {
final DirectionalLightsAttribute dla = attributes.get(DirectionalLightsAttribute.class, DirectionalLightsAttribute.Type);
final Array<DirectionalLight> dirs = dla == null ? null : dla.lights;
if (dirLightsLoc >= 0) {
for (int i = 0; i < directionalLights.length; i++) {
if (dirs == null || dirs.size <= i) {
continue;
}
int idx = dirShadowsLoc + i * dirShadowsSize;
// Shadow
ObjectMap<DirectionalLight, LightProperties> dirCameras = shadowSystem.getDirectionalCameras();
DirectionalLight dl = dirs.get(i);
if (shadowSystem.hasLight(dl)) {
// UVTransform
final TextureRegion tr = dirCameras.get(dl).region;
Camera cam = dirCameras.get(dl).camera;
if (cam != null) {
program.setUniformf(idx + dirShadowsUvTransformOffset, tr.getU(), tr.getV(), tr.getU2() - tr.getU(),
tr.getV2() - tr.getV());
// ProjViewTrans
idx = dirShadowMapProjViewTransLoc + i * dirShadowMapProjViewTransSize;
program.setUniformMatrix(idx, dirCameras.get(dl).camera.combined);
}
}
if (dirLightsSize <= 0) break;
}
}
}
public void bindSpotShadows (final Attributes attributes) {
final SpotLightsAttribute sla = attributes.get(SpotLightsAttribute.class, SpotLightsAttribute.Type);
final Array<SpotLight> spots = sla == null ? null : sla.lights;
if (spotLightsLoc >= 0) {
for (int i = 0; i < spotLights.length; i++) {
if (spots == null || spots.size <= i) {
continue;
}
int idx = spotShadowsLoc + i * spotShadowsSize;
// Shadow
ObjectMap<SpotLight, LightProperties> spotCameras = shadowSystem.getSpotCameras();
SpotLight sl = spots.get(i);
if (shadowSystem.hasLight(sl)) {
// UVTransform
final TextureRegion tr = spotCameras.get(sl).region;
Camera cam = spotCameras.get(sl).camera;
if (cam != null) {
program.setUniformf(idx + spotShadowsUvTransformOffset, tr.getU(), tr.getV(), tr.getU2() - tr.getU(),
tr.getV2() - tr.getV());
// ProjViewTrans
idx = spotShadowMapProjViewTransLoc + i * spotShadowMapProjViewTransSize;
program.setUniformMatrix(idx, spotCameras.get(sl).camera.combined);
}
}
if (spotLightsSize <= 0) break;
}
}
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/com/badlogic/gdx/physics/box2d/joints/GearJointDef.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.physics.box2d.joints;
import com.badlogic.gdx.physics.box2d.Joint;
import com.badlogic.gdx.physics.box2d.JointDef;
/** Gear joint definition. This definition requires two existing revolute or prismatic joints (any combination will work). The
* provided joints must attach a dynamic body to a static body. */
public class GearJointDef extends JointDef {
public GearJointDef () {
type = JointType.GearJoint;
}
/** The first revolute/prismatic joint attached to the gear joint. */
public Joint joint1 = null;
/** The second revolute/prismatic joint attached to the gear joint. */
public Joint joint2 = null;
/** The gear ratio.
* @see GearJoint for explanation. */
public float ratio = 1;
@Override
public org.jbox2d.dynamics.joints.JointDef toJBox2d () {
org.jbox2d.dynamics.joints.GearJointDef jd = new org.jbox2d.dynamics.joints.GearJointDef();
jd.bodyA = bodyA.body;
jd.bodyB = bodyB.body;
jd.collideConnected = collideConnected;
jd.joint1 = joint1.getJBox2DJoint();
jd.joint2 = joint2.getJBox2DJoint();
jd.ratio = ratio;
jd.type = org.jbox2d.dynamics.joints.JointType.GEAR;
return jd;
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.physics.box2d.joints;
import com.badlogic.gdx.physics.box2d.Joint;
import com.badlogic.gdx.physics.box2d.JointDef;
/** Gear joint definition. This definition requires two existing revolute or prismatic joints (any combination will work). The
* provided joints must attach a dynamic body to a static body. */
public class GearJointDef extends JointDef {
public GearJointDef () {
type = JointType.GearJoint;
}
/** The first revolute/prismatic joint attached to the gear joint. */
public Joint joint1 = null;
/** The second revolute/prismatic joint attached to the gear joint. */
public Joint joint2 = null;
/** The gear ratio.
* @see GearJoint for explanation. */
public float ratio = 1;
@Override
public org.jbox2d.dynamics.joints.JointDef toJBox2d () {
org.jbox2d.dynamics.joints.GearJointDef jd = new org.jbox2d.dynamics.joints.GearJointDef();
jd.bodyA = bodyA.body;
jd.bodyB = bodyB.body;
jd.collideConnected = collideConnected;
jd.joint1 = joint1.getJBox2DJoint();
jd.joint2 = joint2.getJBox2DJoint();
jd.ratio = ratio;
jd.type = org.jbox2d.dynamics.joints.JointType.GEAR;
return jd;
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./tests/gdx-tests/src/com/badlogic/gdx/tests/TableLayoutTest.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.tests.utils.GdxTest;
public class TableLayoutTest extends GdxTest {
Stage stage;
public void create () {
stage = new Stage();
Gdx.input.setInputProcessor(stage);
Skin skin = new Skin(Gdx.files.internal("data/uiskin.json"));
Label nameLabel = new Label("Name:", skin);
TextField nameText = new TextField("", skin);
Label addressLabel = new Label("Address:", skin);
TextField addressText = new TextField("", skin);
Table table = new Table();
stage.addActor(table);
table.setSize(260, 195);
table.setPosition(190, 142);
// table.align(Align.right | Align.bottom);
table.debug();
TextureRegion upRegion = skin.getRegion("default-slider-knob");
TextureRegion downRegion = skin.getRegion("default-slider-knob");
BitmapFont buttonFont = skin.getFont("default-font");
TextButton button = new TextButton("Button 1", skin);
button.addListener(new InputListener() {
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
System.out.println("touchDown 1");
return false;
}
});
table.add(button);
// table.setTouchable(Touchable.disabled);
Table table2 = new Table();
stage.addActor(table2);
table2.setFillParent(true);
table2.bottom();
TextButton button2 = new TextButton("Button 2", skin);
button2.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
System.out.println("2!");
}
});
button2.addListener(new InputListener() {
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
System.out.println("touchDown 2");
return false;
}
});
table2.add(button2);
}
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
public void resize (int width, int height) {
stage.getViewport().update(width, height, true);
}
public void dispose () {
stage.dispose();
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.tests.utils.GdxTest;
public class TableLayoutTest extends GdxTest {
Stage stage;
public void create () {
stage = new Stage();
Gdx.input.setInputProcessor(stage);
Skin skin = new Skin(Gdx.files.internal("data/uiskin.json"));
Label nameLabel = new Label("Name:", skin);
TextField nameText = new TextField("", skin);
Label addressLabel = new Label("Address:", skin);
TextField addressText = new TextField("", skin);
Table table = new Table();
stage.addActor(table);
table.setSize(260, 195);
table.setPosition(190, 142);
// table.align(Align.right | Align.bottom);
table.debug();
TextureRegion upRegion = skin.getRegion("default-slider-knob");
TextureRegion downRegion = skin.getRegion("default-slider-knob");
BitmapFont buttonFont = skin.getFont("default-font");
TextButton button = new TextButton("Button 1", skin);
button.addListener(new InputListener() {
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
System.out.println("touchDown 1");
return false;
}
});
table.add(button);
// table.setTouchable(Touchable.disabled);
Table table2 = new Table();
stage.addActor(table2);
table2.setFillParent(true);
table2.bottom();
TextButton button2 = new TextButton("Button 2", skin);
button2.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
System.out.println("2!");
}
});
button2.addListener(new InputListener() {
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
System.out.println("touchDown 2");
return false;
}
});
table2.add(button2);
}
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
public void resize (int width, int height) {
stage.getViewport().update(width, height, true);
}
public void dispose () {
stage.dispose();
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btConvexTriangleCallback.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
public class btConvexTriangleCallback extends btTriangleCallback {
private long swigCPtr;
protected btConvexTriangleCallback (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btConvexTriangleCallback_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btConvexTriangleCallback, normally you should not need this constructor it's intended for low-level
* usage. */
public btConvexTriangleCallback (long cPtr, boolean cMemoryOwn) {
this("btConvexTriangleCallback", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btConvexTriangleCallback_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btConvexTriangleCallback obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btConvexTriangleCallback(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
protected void swigDirectorDisconnect () {
swigCMemOwn = false;
delete();
}
public void swigReleaseOwnership () {
swigCMemOwn = false;
CollisionJNI.btConvexTriangleCallback_change_ownership(this, swigCPtr, false);
}
public void swigTakeOwnership () {
swigCMemOwn = true;
CollisionJNI.btConvexTriangleCallback_change_ownership(this, swigCPtr, true);
}
public long operatorNew (long sizeInBytes) {
return CollisionJNI.btConvexTriangleCallback_operatorNew__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDelete (long ptr) {
CollisionJNI.btConvexTriangleCallback_operatorDelete__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNew (long arg0, long ptr) {
return CollisionJNI.btConvexTriangleCallback_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDelete (long arg0, long arg1) {
CollisionJNI.btConvexTriangleCallback_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1);
}
public long operatorNewArray (long sizeInBytes) {
return CollisionJNI.btConvexTriangleCallback_operatorNewArray__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDeleteArray (long ptr) {
CollisionJNI.btConvexTriangleCallback_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNewArray (long arg0, long ptr) {
return CollisionJNI.btConvexTriangleCallback_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDeleteArray (long arg0, long arg1) {
CollisionJNI.btConvexTriangleCallback_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1);
}
public void setTriangleCount (int value) {
CollisionJNI.btConvexTriangleCallback_triangleCount_set(swigCPtr, this, value);
}
public int getTriangleCount () {
return CollisionJNI.btConvexTriangleCallback_triangleCount_get(swigCPtr, this);
}
public void setManifoldPtr (btPersistentManifold value) {
CollisionJNI.btConvexTriangleCallback_manifoldPtr_set(swigCPtr, this, btPersistentManifold.getCPtr(value), value);
}
public btPersistentManifold getManifoldPtr () {
long cPtr = CollisionJNI.btConvexTriangleCallback_manifoldPtr_get(swigCPtr, this);
return (cPtr == 0) ? null : new btPersistentManifold(cPtr, false);
}
public btConvexTriangleCallback (btDispatcher dispatcher, btCollisionObjectWrapper body0Wrap,
btCollisionObjectWrapper body1Wrap, boolean isSwapped) {
this(CollisionJNI.new_btConvexTriangleCallback(btDispatcher.getCPtr(dispatcher), dispatcher,
btCollisionObjectWrapper.getCPtr(body0Wrap), body0Wrap, btCollisionObjectWrapper.getCPtr(body1Wrap), body1Wrap,
isSwapped), true);
CollisionJNI.btConvexTriangleCallback_director_connect(this, swigCPtr, swigCMemOwn, true);
}
public void setTimeStepAndCounters (float collisionMarginTriangle, btDispatcherInfo dispatchInfo,
btCollisionObjectWrapper convexBodyWrap, btCollisionObjectWrapper triBodyWrap, btManifoldResult resultOut) {
CollisionJNI.btConvexTriangleCallback_setTimeStepAndCounters(swigCPtr, this, collisionMarginTriangle,
btDispatcherInfo.getCPtr(dispatchInfo), dispatchInfo, btCollisionObjectWrapper.getCPtr(convexBodyWrap), convexBodyWrap,
btCollisionObjectWrapper.getCPtr(triBodyWrap), triBodyWrap, btManifoldResult.getCPtr(resultOut), resultOut);
}
public void clearWrapperData () {
CollisionJNI.btConvexTriangleCallback_clearWrapperData(swigCPtr, this);
}
public void processTriangle (btVector3 triangle, int partId, int triangleIndex) {
if (getClass() == btConvexTriangleCallback.class)
CollisionJNI.btConvexTriangleCallback_processTriangle(swigCPtr, this, btVector3.getCPtr(triangle), triangle, partId,
triangleIndex);
else
CollisionJNI.btConvexTriangleCallback_processTriangleSwigExplicitbtConvexTriangleCallback(swigCPtr, this,
btVector3.getCPtr(triangle), triangle, partId, triangleIndex);
}
public void clearCache () {
CollisionJNI.btConvexTriangleCallback_clearCache(swigCPtr, this);
}
public Vector3 getAabbMin () {
return CollisionJNI.btConvexTriangleCallback_getAabbMin(swigCPtr, this);
}
public Vector3 getAabbMax () {
return CollisionJNI.btConvexTriangleCallback_getAabbMax(swigCPtr, this);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
public class btConvexTriangleCallback extends btTriangleCallback {
private long swigCPtr;
protected btConvexTriangleCallback (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btConvexTriangleCallback_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btConvexTriangleCallback, normally you should not need this constructor it's intended for low-level
* usage. */
public btConvexTriangleCallback (long cPtr, boolean cMemoryOwn) {
this("btConvexTriangleCallback", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btConvexTriangleCallback_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btConvexTriangleCallback obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btConvexTriangleCallback(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
protected void swigDirectorDisconnect () {
swigCMemOwn = false;
delete();
}
public void swigReleaseOwnership () {
swigCMemOwn = false;
CollisionJNI.btConvexTriangleCallback_change_ownership(this, swigCPtr, false);
}
public void swigTakeOwnership () {
swigCMemOwn = true;
CollisionJNI.btConvexTriangleCallback_change_ownership(this, swigCPtr, true);
}
public long operatorNew (long sizeInBytes) {
return CollisionJNI.btConvexTriangleCallback_operatorNew__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDelete (long ptr) {
CollisionJNI.btConvexTriangleCallback_operatorDelete__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNew (long arg0, long ptr) {
return CollisionJNI.btConvexTriangleCallback_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDelete (long arg0, long arg1) {
CollisionJNI.btConvexTriangleCallback_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1);
}
public long operatorNewArray (long sizeInBytes) {
return CollisionJNI.btConvexTriangleCallback_operatorNewArray__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDeleteArray (long ptr) {
CollisionJNI.btConvexTriangleCallback_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNewArray (long arg0, long ptr) {
return CollisionJNI.btConvexTriangleCallback_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDeleteArray (long arg0, long arg1) {
CollisionJNI.btConvexTriangleCallback_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1);
}
public void setTriangleCount (int value) {
CollisionJNI.btConvexTriangleCallback_triangleCount_set(swigCPtr, this, value);
}
public int getTriangleCount () {
return CollisionJNI.btConvexTriangleCallback_triangleCount_get(swigCPtr, this);
}
public void setManifoldPtr (btPersistentManifold value) {
CollisionJNI.btConvexTriangleCallback_manifoldPtr_set(swigCPtr, this, btPersistentManifold.getCPtr(value), value);
}
public btPersistentManifold getManifoldPtr () {
long cPtr = CollisionJNI.btConvexTriangleCallback_manifoldPtr_get(swigCPtr, this);
return (cPtr == 0) ? null : new btPersistentManifold(cPtr, false);
}
public btConvexTriangleCallback (btDispatcher dispatcher, btCollisionObjectWrapper body0Wrap,
btCollisionObjectWrapper body1Wrap, boolean isSwapped) {
this(CollisionJNI.new_btConvexTriangleCallback(btDispatcher.getCPtr(dispatcher), dispatcher,
btCollisionObjectWrapper.getCPtr(body0Wrap), body0Wrap, btCollisionObjectWrapper.getCPtr(body1Wrap), body1Wrap,
isSwapped), true);
CollisionJNI.btConvexTriangleCallback_director_connect(this, swigCPtr, swigCMemOwn, true);
}
public void setTimeStepAndCounters (float collisionMarginTriangle, btDispatcherInfo dispatchInfo,
btCollisionObjectWrapper convexBodyWrap, btCollisionObjectWrapper triBodyWrap, btManifoldResult resultOut) {
CollisionJNI.btConvexTriangleCallback_setTimeStepAndCounters(swigCPtr, this, collisionMarginTriangle,
btDispatcherInfo.getCPtr(dispatchInfo), dispatchInfo, btCollisionObjectWrapper.getCPtr(convexBodyWrap), convexBodyWrap,
btCollisionObjectWrapper.getCPtr(triBodyWrap), triBodyWrap, btManifoldResult.getCPtr(resultOut), resultOut);
}
public void clearWrapperData () {
CollisionJNI.btConvexTriangleCallback_clearWrapperData(swigCPtr, this);
}
public void processTriangle (btVector3 triangle, int partId, int triangleIndex) {
if (getClass() == btConvexTriangleCallback.class)
CollisionJNI.btConvexTriangleCallback_processTriangle(swigCPtr, this, btVector3.getCPtr(triangle), triangle, partId,
triangleIndex);
else
CollisionJNI.btConvexTriangleCallback_processTriangleSwigExplicitbtConvexTriangleCallback(swigCPtr, this,
btVector3.getCPtr(triangle), triangle, partId, triangleIndex);
}
public void clearCache () {
CollisionJNI.btConvexTriangleCallback_clearCache(swigCPtr, this);
}
public Vector3 getAabbMin () {
return CollisionJNI.btConvexTriangleCallback_getAabbMin(swigCPtr, this);
}
public Vector3 getAabbMax () {
return CollisionJNI.btConvexTriangleCallback_getAabbMax(swigCPtr, this);
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-tools/src/com/badlogic/gdx/tools/flame/RegularEmitterPanel.java |
package com.badlogic.gdx.tools.flame;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.SwingConstants;
import com.badlogic.gdx.graphics.g3d.particles.emitters.RegularEmitter;
/** @author Inferno */
public class RegularEmitterPanel extends EditorPanel<RegularEmitter> {
CountPanel countPanel;
RangedNumericPanel delayPanel, durationPanel;
ScaledNumericPanel emissionPanel, lifePanel, lifeOffsetPanel;
JCheckBox continuousCheckbox;
public RegularEmitterPanel (FlameMain particleEditor3D, RegularEmitter emitter) {
super(particleEditor3D, "Regular Emitter", "This is a generic emitter used to generate particles regularly.");
initializeComponents(emitter);
setValue(null);
}
private void initializeComponents (RegularEmitter emitter) {
continuousCheckbox = new JCheckBox("Continuous");
continuousCheckbox.setSelected(emitter.isContinuous());
continuousCheckbox.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
RegularEmitter emitter = (RegularEmitter)editor.getEmitter().emitter;
emitter.setContinuous(continuousCheckbox.isSelected());
}
});
continuousCheckbox.setHorizontalTextPosition(SwingConstants.LEFT);
int i = 0;
addContent(i++, 0, continuousCheckbox, GridBagConstraints.WEST, GridBagConstraints.NONE);
addContent(i++, 0,
countPanel = new CountPanel(editor, "Count", "Min number of particles at all times, max number of particles allowed.",
emitter.minParticleCount, emitter.maxParticleCount));
addContent(i++, 0, delayPanel = new RangedNumericPanel(editor, emitter.getDelay(), "Delay",
"Time from beginning of effect to emission start, in milliseconds.", false));
addContent(i++, 0, durationPanel = new RangedNumericPanel(editor, emitter.getDuration(), "Duration",
"Time particles will be emitted, in milliseconds."));
addContent(i++, 0, emissionPanel = new ScaledNumericPanel(editor, emitter.getEmission(), "Duration", "Emission",
"Number of particles emitted per second."));
addContent(i++, 0, lifePanel = new ScaledNumericPanel(editor, emitter.getLife(), "Duration", "Life",
"Time particles will live, in milliseconds."));
addContent(i++, 0, lifeOffsetPanel = new ScaledNumericPanel(editor, emitter.getLifeOffset(), "Duration", "Life Offset",
"Particle starting life consumed, in milliseconds.", false));
}
}
|
package com.badlogic.gdx.tools.flame;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.SwingConstants;
import com.badlogic.gdx.graphics.g3d.particles.emitters.RegularEmitter;
/** @author Inferno */
public class RegularEmitterPanel extends EditorPanel<RegularEmitter> {
CountPanel countPanel;
RangedNumericPanel delayPanel, durationPanel;
ScaledNumericPanel emissionPanel, lifePanel, lifeOffsetPanel;
JCheckBox continuousCheckbox;
public RegularEmitterPanel (FlameMain particleEditor3D, RegularEmitter emitter) {
super(particleEditor3D, "Regular Emitter", "This is a generic emitter used to generate particles regularly.");
initializeComponents(emitter);
setValue(null);
}
private void initializeComponents (RegularEmitter emitter) {
continuousCheckbox = new JCheckBox("Continuous");
continuousCheckbox.setSelected(emitter.isContinuous());
continuousCheckbox.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
RegularEmitter emitter = (RegularEmitter)editor.getEmitter().emitter;
emitter.setContinuous(continuousCheckbox.isSelected());
}
});
continuousCheckbox.setHorizontalTextPosition(SwingConstants.LEFT);
int i = 0;
addContent(i++, 0, continuousCheckbox, GridBagConstraints.WEST, GridBagConstraints.NONE);
addContent(i++, 0,
countPanel = new CountPanel(editor, "Count", "Min number of particles at all times, max number of particles allowed.",
emitter.minParticleCount, emitter.maxParticleCount));
addContent(i++, 0, delayPanel = new RangedNumericPanel(editor, emitter.getDelay(), "Delay",
"Time from beginning of effect to emission start, in milliseconds.", false));
addContent(i++, 0, durationPanel = new RangedNumericPanel(editor, emitter.getDuration(), "Duration",
"Time particles will be emitted, in milliseconds."));
addContent(i++, 0, emissionPanel = new ScaledNumericPanel(editor, emitter.getEmission(), "Duration", "Emission",
"Number of particles emitted per second."));
addContent(i++, 0, lifePanel = new ScaledNumericPanel(editor, emitter.getLife(), "Duration", "Life",
"Time particles will live, in milliseconds."));
addContent(i++, 0, lifeOffsetPanel = new ScaledNumericPanel(editor, emitter.getLifeOffset(), "Duration", "Life Offset",
"Particle starting life consumed, in milliseconds.", false));
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./tests/gdx-tests/src/com/badlogic/gdx/tests/box2d/CharacterCollision.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
/*
* Copyright 2010 Mario Zechner ([email protected]), Nathan Sweet ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.badlogic.gdx.tests.box2d;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.EdgeShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
public class CharacterCollision extends Box2DTest {
@Override
protected void createWorld (World world) {
{
BodyDef bd = new BodyDef();
Body ground = world.createBody(bd);
EdgeShape shape = new EdgeShape();
shape.set(new Vector2(-20, 0), new Vector2(20, 0));
ground.createFixture(shape, 0);
shape.dispose();
}
{
BodyDef bd = new BodyDef();
Body ground = world.createBody(bd);
EdgeShape shape = new EdgeShape();
shape.setRadius(0);
shape.set(new Vector2(-8, 1), new Vector2(-6, 1));
ground.createFixture(shape, 0);
shape.set(new Vector2(-6, 1), new Vector2(-4, 1));
ground.createFixture(shape, 0);
shape.set(new Vector2(-4, 1), new Vector2(-2, 1));
ground.createFixture(shape, 0);
shape.dispose();
}
{
BodyDef bd = new BodyDef();
Body ground = world.createBody(bd);
PolygonShape shape = new PolygonShape();
shape.setAsBox(1, 1, new Vector2(4, 3), 0);
ground.createFixture(shape, 0);
shape.setAsBox(1, 1, new Vector2(6, 3), 0);
ground.createFixture(shape, 0);
shape.setAsBox(1, 1, new Vector2(8, 3), 0);
ground.createFixture(shape, 0);
shape.dispose();
}
{
BodyDef bd = new BodyDef();
Body ground = world.createBody(bd);
EdgeShape shape = new EdgeShape();
float d = 2 * 2 * 0.005f;
shape.setRadius(0);
shape.set(new Vector2(-1 + d, 3), new Vector2(1 - d, 3));
ground.createFixture(shape, 0);
shape.set(new Vector2(1, 3 + d), new Vector2(1, 5 - d));
ground.createFixture(shape, 0);
shape.set(new Vector2(1 - d, 5), new Vector2(-1 + d, 5));
ground.createFixture(shape, 0);
shape.set(new Vector2(-1, 5 - d), new Vector2(-1, 3 + d));
ground.createFixture(shape, 0);
shape.dispose();
}
{
BodyDef bd = new BodyDef();
bd.position.set(-3, 5);
bd.type = BodyType.DynamicBody;
bd.fixedRotation = true;
bd.allowSleep = false;
Body body = world.createBody(bd);
PolygonShape shape = new PolygonShape();
shape.setAsBox(0.5f, 0.5f);
FixtureDef fd = new FixtureDef();
fd.shape = shape;
fd.density = 20.0f;
body.createFixture(fd);
shape.dispose();
}
{
BodyDef bd = new BodyDef();
bd.position.set(-5, 5);
bd.type = BodyType.DynamicBody;
bd.fixedRotation = true;
bd.allowSleep = false;
Body body = world.createBody(bd);
float angle = 0;
float delta = (float)Math.PI / 3;
Vector2[] vertices = new Vector2[6];
for (int i = 0; i < 6; i++) {
vertices[i] = new Vector2(0.5f * (float)Math.cos(angle), 0.5f * (float)Math.sin(angle));
angle += delta;
}
PolygonShape shape = new PolygonShape();
shape.set(vertices);
FixtureDef fd = new FixtureDef();
fd.shape = shape;
fd.density = 20.0f;
body.createFixture(fd);
shape.dispose();
}
{
BodyDef bd = new BodyDef();
bd.position.set(3, 5);
bd.type = BodyType.DynamicBody;
bd.fixedRotation = true;
bd.allowSleep = false;
Body body = world.createBody(bd);
CircleShape shape = new CircleShape();
shape.setRadius(0.5f);
FixtureDef fd = new FixtureDef();
fd.shape = shape;
fd.density = 20.0f;
body.createFixture(fd);
shape.dispose();
}
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
/*
* Copyright 2010 Mario Zechner ([email protected]), Nathan Sweet ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.badlogic.gdx.tests.box2d;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.EdgeShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
public class CharacterCollision extends Box2DTest {
@Override
protected void createWorld (World world) {
{
BodyDef bd = new BodyDef();
Body ground = world.createBody(bd);
EdgeShape shape = new EdgeShape();
shape.set(new Vector2(-20, 0), new Vector2(20, 0));
ground.createFixture(shape, 0);
shape.dispose();
}
{
BodyDef bd = new BodyDef();
Body ground = world.createBody(bd);
EdgeShape shape = new EdgeShape();
shape.setRadius(0);
shape.set(new Vector2(-8, 1), new Vector2(-6, 1));
ground.createFixture(shape, 0);
shape.set(new Vector2(-6, 1), new Vector2(-4, 1));
ground.createFixture(shape, 0);
shape.set(new Vector2(-4, 1), new Vector2(-2, 1));
ground.createFixture(shape, 0);
shape.dispose();
}
{
BodyDef bd = new BodyDef();
Body ground = world.createBody(bd);
PolygonShape shape = new PolygonShape();
shape.setAsBox(1, 1, new Vector2(4, 3), 0);
ground.createFixture(shape, 0);
shape.setAsBox(1, 1, new Vector2(6, 3), 0);
ground.createFixture(shape, 0);
shape.setAsBox(1, 1, new Vector2(8, 3), 0);
ground.createFixture(shape, 0);
shape.dispose();
}
{
BodyDef bd = new BodyDef();
Body ground = world.createBody(bd);
EdgeShape shape = new EdgeShape();
float d = 2 * 2 * 0.005f;
shape.setRadius(0);
shape.set(new Vector2(-1 + d, 3), new Vector2(1 - d, 3));
ground.createFixture(shape, 0);
shape.set(new Vector2(1, 3 + d), new Vector2(1, 5 - d));
ground.createFixture(shape, 0);
shape.set(new Vector2(1 - d, 5), new Vector2(-1 + d, 5));
ground.createFixture(shape, 0);
shape.set(new Vector2(-1, 5 - d), new Vector2(-1, 3 + d));
ground.createFixture(shape, 0);
shape.dispose();
}
{
BodyDef bd = new BodyDef();
bd.position.set(-3, 5);
bd.type = BodyType.DynamicBody;
bd.fixedRotation = true;
bd.allowSleep = false;
Body body = world.createBody(bd);
PolygonShape shape = new PolygonShape();
shape.setAsBox(0.5f, 0.5f);
FixtureDef fd = new FixtureDef();
fd.shape = shape;
fd.density = 20.0f;
body.createFixture(fd);
shape.dispose();
}
{
BodyDef bd = new BodyDef();
bd.position.set(-5, 5);
bd.type = BodyType.DynamicBody;
bd.fixedRotation = true;
bd.allowSleep = false;
Body body = world.createBody(bd);
float angle = 0;
float delta = (float)Math.PI / 3;
Vector2[] vertices = new Vector2[6];
for (int i = 0; i < 6; i++) {
vertices[i] = new Vector2(0.5f * (float)Math.cos(angle), 0.5f * (float)Math.sin(angle));
angle += delta;
}
PolygonShape shape = new PolygonShape();
shape.set(vertices);
FixtureDef fd = new FixtureDef();
fd.shape = shape;
fd.density = 20.0f;
body.createFixture(fd);
shape.dispose();
}
{
BodyDef bd = new BodyDef();
bd.position.set(3, 5);
bd.type = BodyType.DynamicBody;
bd.fixedRotation = true;
bd.allowSleep = false;
Body body = world.createBody(bd);
CircleShape shape = new CircleShape();
shape.setRadius(0.5f);
FixtureDef fd = new FixtureDef();
fd.shape = shape;
fd.density = 20.0f;
body.createFixture(fd);
shape.dispose();
}
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/com/badlogic/gdx/physics/box2d/FixtureDef.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.physics.box2d;
/** A fixture definition is used to create a fixture. This class defines an abstract fixture definition. You can reuse fixture
* definitions safely.
* @author mzechner */
public class FixtureDef {
/** The shape, this must be set. The shape will be cloned, so you can create the shape on the stack. */
public Shape shape;
/** The friction coefficient, usually in the range [0,1]. **/
public float friction = 0.2f;
/** The restitution (elasticity) usually in the range [0,1]. **/
public float restitution = 0;
/** The density, usually in kg/m^2. **/
public float density = 0;
/** A sensor shape collects contact information but never generates a collision response. */
public boolean isSensor = false;
/** Contact filtering data. **/
public final Filter filter = new Filter();
public org.jbox2d.dynamics.FixtureDef toJBox2d () {
org.jbox2d.dynamics.FixtureDef fd = new org.jbox2d.dynamics.FixtureDef();
fd.density = density;
fd.filter = new org.jbox2d.dynamics.Filter();
fd.filter.categoryBits = filter.categoryBits;
fd.filter.groupIndex = filter.groupIndex;
fd.filter.maskBits = filter.maskBits;
fd.friction = friction;
fd.isSensor = isSensor;
fd.restitution = restitution;
fd.shape = shape.shape;
return fd;
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.physics.box2d;
/** A fixture definition is used to create a fixture. This class defines an abstract fixture definition. You can reuse fixture
* definitions safely.
* @author mzechner */
public class FixtureDef {
/** The shape, this must be set. The shape will be cloned, so you can create the shape on the stack. */
public Shape shape;
/** The friction coefficient, usually in the range [0,1]. **/
public float friction = 0.2f;
/** The restitution (elasticity) usually in the range [0,1]. **/
public float restitution = 0;
/** The density, usually in kg/m^2. **/
public float density = 0;
/** A sensor shape collects contact information but never generates a collision response. */
public boolean isSensor = false;
/** Contact filtering data. **/
public final Filter filter = new Filter();
public org.jbox2d.dynamics.FixtureDef toJBox2d () {
org.jbox2d.dynamics.FixtureDef fd = new org.jbox2d.dynamics.FixtureDef();
fd.density = density;
fd.filter = new org.jbox2d.dynamics.Filter();
fd.filter.categoryBits = filter.categoryBits;
fd.filter.groupIndex = filter.groupIndex;
fd.filter.maskBits = filter.maskBits;
fd.friction = friction;
fd.isSensor = isSensor;
fd.restitution = restitution;
fd.shape = shape.shape;
return fd;
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/graphics/glutils/IndexBufferObject.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics.glutils;
import java.nio.ShortBuffer;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.GdxRuntimeException;
/**
* <p>
* In IndexBufferObject wraps OpenGL's index buffer functionality to be used in conjunction with VBOs. This class can be
* seamlessly used with OpenGL ES 1.x and 2.0.
* </p>
*
* <p>
* Uses indirect Buffers on Android 1.5/1.6 to fix GC invocation due to leaking PlatformAddress instances.
* </p>
*
* <p>
* You can also use this to store indices for vertex arrays. Do not call {@link #bind()} or {@link #unbind()} in this case but
* rather use {@link #getBuffer()} to use the buffer directly with glDrawElements. You must also create the IndexBufferObject with
* the second constructor and specify isDirect as true as glDrawElements in conjunction with vertex arrays needs direct buffers.
* </p>
*
* <p>
* VertexBufferObjects must be disposed via the {@link #dispose()} method when no longer needed
* </p>
*
* @author mzechner */
public class IndexBufferObject implements IndexData {
ShortBuffer buffer;
int bufferHandle;
final boolean isDirect;
boolean isDirty = true;
boolean isBound = false;
final int usage;
/** Creates a new IndexBufferObject.
*
* @param isStatic whether the index buffer is static
* @param maxIndices the maximum number of indices this buffer can hold */
public IndexBufferObject (boolean isStatic, int maxIndices) {
isDirect = true;
buffer = BufferUtils.newShortBuffer(maxIndices);
buffer.flip();
bufferHandle = Gdx.gl20.glGenBuffer();
usage = isStatic ? GL20.GL_STATIC_DRAW : GL20.GL_DYNAMIC_DRAW;
}
/** Creates a new IndexBufferObject to be used with vertex arrays.
*
* @param maxIndices the maximum number of indices this buffer can hold */
public IndexBufferObject (int maxIndices) {
this.isDirect = true;
buffer = BufferUtils.newShortBuffer(maxIndices);
buffer.flip();
bufferHandle = Gdx.gl20.glGenBuffer();
usage = GL20.GL_STATIC_DRAW;
}
/** @return the number of indices currently stored in this buffer */
public int getNumIndices () {
return buffer.limit();
}
/** @return the maximum number of indices this IndexBufferObject can store. */
public int getNumMaxIndices () {
return buffer.capacity();
}
/**
* <p>
* Sets the indices of this IndexBufferObject, discarding the old indices. The count must equal the number of indices to be
* copied to this IndexBufferObject.
* </p>
*
* <p>
* This can be called in between calls to {@link #bind()} and {@link #unbind()}. The index data will be updated instantly.
* </p>
*
* @param indices the vertex data
* @param offset the offset to start copying the data from
* @param count the number of shorts to copy */
public void setIndices (short[] indices, int offset, int count) {
isDirty = true;
buffer.clear();
buffer.put(indices, offset, count);
buffer.flip();
if (isBound) {
Gdx.gl20.glBufferData(GL20.GL_ELEMENT_ARRAY_BUFFER, buffer.limit(), buffer, usage);
isDirty = false;
}
}
public void setIndices (ShortBuffer indices) {
isDirty = true;
buffer.clear();
buffer.put(indices);
buffer.flip();
if (isBound) {
Gdx.gl20.glBufferData(GL20.GL_ELEMENT_ARRAY_BUFFER, buffer.limit(), buffer, usage);
isDirty = false;
}
}
@Override
public void updateIndices (int targetOffset, short[] indices, int offset, int count) {
isDirty = true;
final int pos = buffer.position();
buffer.position(targetOffset);
BufferUtils.copy(indices, offset, buffer, count);
buffer.position(pos);
if (isBound) {
Gdx.gl20.glBufferData(GL20.GL_ELEMENT_ARRAY_BUFFER, buffer.limit(), buffer, usage);
isDirty = false;
}
}
/** @deprecated use {@link #getBuffer(boolean)} instead */
@Override
@Deprecated
public ShortBuffer getBuffer () {
isDirty = true;
return buffer;
}
@Override
public ShortBuffer getBuffer (boolean forWriting) {
isDirty |= forWriting;
return buffer;
}
/** Binds this IndexBufferObject for rendering with glDrawElements. */
public void bind () {
if (bufferHandle == 0) throw new GdxRuntimeException("No buffer allocated!");
Gdx.gl20.glBindBuffer(GL20.GL_ELEMENT_ARRAY_BUFFER, bufferHandle);
if (isDirty) {
Gdx.gl20.glBufferData(GL20.GL_ELEMENT_ARRAY_BUFFER, buffer.limit(), buffer, usage);
isDirty = false;
}
isBound = true;
}
/** Unbinds this IndexBufferObject. */
public void unbind () {
Gdx.gl20.glBindBuffer(GL20.GL_ELEMENT_ARRAY_BUFFER, 0);
isBound = false;
}
/** Invalidates the IndexBufferObject so a new OpenGL buffer handle is created. Use this in case of a context loss. */
public void invalidate () {
bufferHandle = Gdx.gl20.glGenBuffer();
isDirty = true;
}
/** Disposes this IndexBufferObject and all its associated OpenGL resources. */
public void dispose () {
GL20 gl = Gdx.gl20;
gl.glBindBuffer(GL20.GL_ELEMENT_ARRAY_BUFFER, 0);
gl.glDeleteBuffer(bufferHandle);
bufferHandle = 0;
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics.glutils;
import java.nio.ShortBuffer;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.GdxRuntimeException;
/**
* <p>
* In IndexBufferObject wraps OpenGL's index buffer functionality to be used in conjunction with VBOs. This class can be
* seamlessly used with OpenGL ES 1.x and 2.0.
* </p>
*
* <p>
* Uses indirect Buffers on Android 1.5/1.6 to fix GC invocation due to leaking PlatformAddress instances.
* </p>
*
* <p>
* You can also use this to store indices for vertex arrays. Do not call {@link #bind()} or {@link #unbind()} in this case but
* rather use {@link #getBuffer()} to use the buffer directly with glDrawElements. You must also create the IndexBufferObject with
* the second constructor and specify isDirect as true as glDrawElements in conjunction with vertex arrays needs direct buffers.
* </p>
*
* <p>
* VertexBufferObjects must be disposed via the {@link #dispose()} method when no longer needed
* </p>
*
* @author mzechner */
public class IndexBufferObject implements IndexData {
ShortBuffer buffer;
int bufferHandle;
final boolean isDirect;
boolean isDirty = true;
boolean isBound = false;
final int usage;
/** Creates a new IndexBufferObject.
*
* @param isStatic whether the index buffer is static
* @param maxIndices the maximum number of indices this buffer can hold */
public IndexBufferObject (boolean isStatic, int maxIndices) {
isDirect = true;
buffer = BufferUtils.newShortBuffer(maxIndices);
buffer.flip();
bufferHandle = Gdx.gl20.glGenBuffer();
usage = isStatic ? GL20.GL_STATIC_DRAW : GL20.GL_DYNAMIC_DRAW;
}
/** Creates a new IndexBufferObject to be used with vertex arrays.
*
* @param maxIndices the maximum number of indices this buffer can hold */
public IndexBufferObject (int maxIndices) {
this.isDirect = true;
buffer = BufferUtils.newShortBuffer(maxIndices);
buffer.flip();
bufferHandle = Gdx.gl20.glGenBuffer();
usage = GL20.GL_STATIC_DRAW;
}
/** @return the number of indices currently stored in this buffer */
public int getNumIndices () {
return buffer.limit();
}
/** @return the maximum number of indices this IndexBufferObject can store. */
public int getNumMaxIndices () {
return buffer.capacity();
}
/**
* <p>
* Sets the indices of this IndexBufferObject, discarding the old indices. The count must equal the number of indices to be
* copied to this IndexBufferObject.
* </p>
*
* <p>
* This can be called in between calls to {@link #bind()} and {@link #unbind()}. The index data will be updated instantly.
* </p>
*
* @param indices the vertex data
* @param offset the offset to start copying the data from
* @param count the number of shorts to copy */
public void setIndices (short[] indices, int offset, int count) {
isDirty = true;
buffer.clear();
buffer.put(indices, offset, count);
buffer.flip();
if (isBound) {
Gdx.gl20.glBufferData(GL20.GL_ELEMENT_ARRAY_BUFFER, buffer.limit(), buffer, usage);
isDirty = false;
}
}
public void setIndices (ShortBuffer indices) {
isDirty = true;
buffer.clear();
buffer.put(indices);
buffer.flip();
if (isBound) {
Gdx.gl20.glBufferData(GL20.GL_ELEMENT_ARRAY_BUFFER, buffer.limit(), buffer, usage);
isDirty = false;
}
}
@Override
public void updateIndices (int targetOffset, short[] indices, int offset, int count) {
isDirty = true;
final int pos = buffer.position();
buffer.position(targetOffset);
BufferUtils.copy(indices, offset, buffer, count);
buffer.position(pos);
if (isBound) {
Gdx.gl20.glBufferData(GL20.GL_ELEMENT_ARRAY_BUFFER, buffer.limit(), buffer, usage);
isDirty = false;
}
}
/** @deprecated use {@link #getBuffer(boolean)} instead */
@Override
@Deprecated
public ShortBuffer getBuffer () {
isDirty = true;
return buffer;
}
@Override
public ShortBuffer getBuffer (boolean forWriting) {
isDirty |= forWriting;
return buffer;
}
/** Binds this IndexBufferObject for rendering with glDrawElements. */
public void bind () {
if (bufferHandle == 0) throw new GdxRuntimeException("No buffer allocated!");
Gdx.gl20.glBindBuffer(GL20.GL_ELEMENT_ARRAY_BUFFER, bufferHandle);
if (isDirty) {
Gdx.gl20.glBufferData(GL20.GL_ELEMENT_ARRAY_BUFFER, buffer.limit(), buffer, usage);
isDirty = false;
}
isBound = true;
}
/** Unbinds this IndexBufferObject. */
public void unbind () {
Gdx.gl20.glBindBuffer(GL20.GL_ELEMENT_ARRAY_BUFFER, 0);
isBound = false;
}
/** Invalidates the IndexBufferObject so a new OpenGL buffer handle is created. Use this in case of a context loss. */
public void invalidate () {
bufferHandle = Gdx.gl20.glGenBuffer();
isDirty = true;
}
/** Disposes this IndexBufferObject and all its associated OpenGL resources. */
public void dispose () {
GL20 gl = Gdx.gl20;
gl.glBindBuffer(GL20.GL_ELEMENT_ARRAY_BUFFER, 0);
gl.glDeleteBuffer(bufferHandle);
bufferHandle = 0;
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./gdx/src/com/badlogic/gdx/graphics/glutils/HdpiMode.java |
package com.badlogic.gdx.graphics.glutils;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.graphics.GL20;
public enum HdpiMode {
/** mouse coordinates, {@link Graphics#getWidth()} and {@link Graphics#getHeight()} will return logical coordinates according
* to the system defined HDPI scaling. Rendering will be performed to a backbuffer at raw resolution. Use {@link HdpiUtils}
* when calling {@link GL20#glScissor} or {@link GL20#glViewport} which expect raw coordinates. */
Logical,
/** Mouse coordinates, {@link Graphics#getWidth()} and {@link Graphics#getHeight()} will return raw pixel coordinates
* irrespective of the system defined HDPI scaling. */
Pixels
}
|
package com.badlogic.gdx.graphics.glutils;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.graphics.GL20;
public enum HdpiMode {
/** mouse coordinates, {@link Graphics#getWidth()} and {@link Graphics#getHeight()} will return logical coordinates according
* to the system defined HDPI scaling. Rendering will be performed to a backbuffer at raw resolution. Use {@link HdpiUtils}
* when calling {@link GL20#glScissor} or {@link GL20#glViewport} which expect raw coordinates. */
Logical,
/** Mouse coordinates, {@link Graphics#getWidth()} and {@link Graphics#getHeight()} will return raw pixel coordinates
* irrespective of the system defined HDPI scaling. */
Pixels
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btConvexInternalShapeData.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btConvexInternalShapeData extends BulletBase {
private long swigCPtr;
protected btConvexInternalShapeData (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btConvexInternalShapeData, normally you should not need this constructor it's intended for low-level
* usage. */
public btConvexInternalShapeData (long cPtr, boolean cMemoryOwn) {
this("btConvexInternalShapeData", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btConvexInternalShapeData obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btConvexInternalShapeData(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setCollisionShapeData (btCollisionShapeData value) {
CollisionJNI.btConvexInternalShapeData_collisionShapeData_set(swigCPtr, this, btCollisionShapeData.getCPtr(value), value);
}
public btCollisionShapeData getCollisionShapeData () {
long cPtr = CollisionJNI.btConvexInternalShapeData_collisionShapeData_get(swigCPtr, this);
return (cPtr == 0) ? null : new btCollisionShapeData(cPtr, false);
}
public void setLocalScaling (btVector3FloatData value) {
CollisionJNI.btConvexInternalShapeData_localScaling_set(swigCPtr, this, btVector3FloatData.getCPtr(value), value);
}
public btVector3FloatData getLocalScaling () {
long cPtr = CollisionJNI.btConvexInternalShapeData_localScaling_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setImplicitShapeDimensions (btVector3FloatData value) {
CollisionJNI.btConvexInternalShapeData_implicitShapeDimensions_set(swigCPtr, this, btVector3FloatData.getCPtr(value),
value);
}
public btVector3FloatData getImplicitShapeDimensions () {
long cPtr = CollisionJNI.btConvexInternalShapeData_implicitShapeDimensions_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setCollisionMargin (float value) {
CollisionJNI.btConvexInternalShapeData_collisionMargin_set(swigCPtr, this, value);
}
public float getCollisionMargin () {
return CollisionJNI.btConvexInternalShapeData_collisionMargin_get(swigCPtr, this);
}
public void setPadding (int value) {
CollisionJNI.btConvexInternalShapeData_padding_set(swigCPtr, this, value);
}
public int getPadding () {
return CollisionJNI.btConvexInternalShapeData_padding_get(swigCPtr, this);
}
public btConvexInternalShapeData () {
this(CollisionJNI.new_btConvexInternalShapeData(), true);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btConvexInternalShapeData extends BulletBase {
private long swigCPtr;
protected btConvexInternalShapeData (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btConvexInternalShapeData, normally you should not need this constructor it's intended for low-level
* usage. */
public btConvexInternalShapeData (long cPtr, boolean cMemoryOwn) {
this("btConvexInternalShapeData", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btConvexInternalShapeData obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btConvexInternalShapeData(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setCollisionShapeData (btCollisionShapeData value) {
CollisionJNI.btConvexInternalShapeData_collisionShapeData_set(swigCPtr, this, btCollisionShapeData.getCPtr(value), value);
}
public btCollisionShapeData getCollisionShapeData () {
long cPtr = CollisionJNI.btConvexInternalShapeData_collisionShapeData_get(swigCPtr, this);
return (cPtr == 0) ? null : new btCollisionShapeData(cPtr, false);
}
public void setLocalScaling (btVector3FloatData value) {
CollisionJNI.btConvexInternalShapeData_localScaling_set(swigCPtr, this, btVector3FloatData.getCPtr(value), value);
}
public btVector3FloatData getLocalScaling () {
long cPtr = CollisionJNI.btConvexInternalShapeData_localScaling_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setImplicitShapeDimensions (btVector3FloatData value) {
CollisionJNI.btConvexInternalShapeData_implicitShapeDimensions_set(swigCPtr, this, btVector3FloatData.getCPtr(value),
value);
}
public btVector3FloatData getImplicitShapeDimensions () {
long cPtr = CollisionJNI.btConvexInternalShapeData_implicitShapeDimensions_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setCollisionMargin (float value) {
CollisionJNI.btConvexInternalShapeData_collisionMargin_set(swigCPtr, this, value);
}
public float getCollisionMargin () {
return CollisionJNI.btConvexInternalShapeData_collisionMargin_get(swigCPtr, this);
}
public void setPadding (int value) {
CollisionJNI.btConvexInternalShapeData_padding_set(swigCPtr, this, value);
}
public int getPadding () {
return CollisionJNI.btConvexInternalShapeData_padding_get(swigCPtr, this);
}
public btConvexInternalShapeData () {
this(CollisionJNI.new_btConvexInternalShapeData(), true);
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-box2d/gdx-box2d/src/com/badlogic/gdx/physics/box2d/joints/PrismaticJoint.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.physics.box2d.joints;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Joint;
import com.badlogic.gdx.physics.box2d.World;
/** A prismatic joint. This joint provides one degree of freedom: translation along an axis fixed in body1. Relative rotation is
* prevented. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint
* friction. */
public class PrismaticJoint extends Joint {
// @off
/*JNI
#include <Box2D/Box2D.h>
*/
private final float[] tmp = new float[2];
private final Vector2 localAnchorA = new Vector2();
private final Vector2 localAnchorB = new Vector2();
private final Vector2 localAxisA = new Vector2();
public PrismaticJoint (World world, long addr) {
super(world, addr);
}
public Vector2 getLocalAnchorA () {
jniGetLocalAnchorA(addr, tmp);
localAnchorA.set(tmp[0], tmp[1]);
return localAnchorA;
}
private native void jniGetLocalAnchorA (long addr, float[] anchor); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
anchor[0] = joint->GetLocalAnchorA().x;
anchor[1] = joint->GetLocalAnchorA().y;
*/
public Vector2 getLocalAnchorB () {
jniGetLocalAnchorB(addr, tmp);
localAnchorB.set(tmp[0], tmp[1]);
return localAnchorB;
}
private native void jniGetLocalAnchorB (long addr, float[] anchor); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
anchor[0] = joint->GetLocalAnchorB().x;
anchor[1] = joint->GetLocalAnchorB().y;
*/
public Vector2 getLocalAxisA () {
jniGetLocalAxisA(addr, tmp);
localAxisA.set(tmp[0], tmp[1]);
return localAxisA;
}
private native void jniGetLocalAxisA (long addr, float[] anchor); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
anchor[0] = joint->GetLocalAxisA().x;
anchor[1] = joint->GetLocalAxisA().y;
*/
/** Get the current joint translation, usually in meters. */
public float getJointTranslation () {
return jniGetJointTranslation(addr);
}
private native float jniGetJointTranslation (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetJointTranslation();
*/
/** Get the current joint translation speed, usually in meters per second. */
public float getJointSpeed () {
return jniGetJointSpeed(addr);
}
private native float jniGetJointSpeed (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetJointSpeed();
*/
/** Is the joint limit enabled? */
public boolean isLimitEnabled () {
return jniIsLimitEnabled(addr);
}
private native boolean jniIsLimitEnabled (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->IsLimitEnabled();
*/
/** Enable/disable the joint limit. */
public void enableLimit (boolean flag) {
jniEnableLimit(addr, flag);
}
private native void jniEnableLimit (long addr, boolean flag); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
joint->EnableLimit(flag);
*/
/** Get the lower joint limit, usually in meters. */
public float getLowerLimit () {
return jniGetLowerLimit(addr);
}
private native float jniGetLowerLimit (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetLowerLimit();
*/
/** Get the upper joint limit, usually in meters. */
public float getUpperLimit () {
return jniGetUpperLimit(addr);
}
private native float jniGetUpperLimit (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetUpperLimit();
*/
/** Set the joint limits, usually in meters. */
public void setLimits (float lower, float upper) {
jniSetLimits(addr, lower, upper);
}
private native void jniSetLimits (long addr, float lower, float upper); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
joint->SetLimits(lower, upper );
*/
/** Is the joint motor enabled? */
public boolean isMotorEnabled () {
return jniIsMotorEnabled(addr);
}
private native boolean jniIsMotorEnabled (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->IsMotorEnabled();
*/
/** Enable/disable the joint motor. */
public void enableMotor (boolean flag) {
jniEnableMotor(addr, flag);
}
private native void jniEnableMotor (long addr, boolean flag); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
joint->EnableMotor(flag);
*/
/** Set the motor speed, usually in meters per second. */
public void setMotorSpeed (float speed) {
jniSetMotorSpeed(addr, speed);
}
private native void jniSetMotorSpeed (long addr, float speed); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
joint->SetMotorSpeed(speed);
*/
/** Get the motor speed, usually in meters per second. */
public float getMotorSpeed () {
return jniGetMotorSpeed(addr);
}
private native float jniGetMotorSpeed (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetMotorSpeed();
*/
/** Set the maximum motor force, usually in N. */
public void setMaxMotorForce (float force) {
jniSetMaxMotorForce(addr, force);
}
private native void jniSetMaxMotorForce (long addr, float force); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
joint->SetMaxMotorForce(force);
*/
/** Get the current motor force given the inverse time step, usually in N. */
public float getMotorForce (float invDt) {
return jniGetMotorForce(addr, invDt);
}
private native float jniGetMotorForce (long addr, float invDt); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetMotorForce(invDt);
*/
/** Get the max motor force, usually in N. */
public float getMaxMotorForce () {
return jniGetMaxMotorForce(addr);
}
private native float jniGetMaxMotorForce (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetMaxMotorForce();
*/
/** Get the reference angle. */
public float getReferenceAngle () {
return jniGetReferenceAngle(addr);
}
private native float jniGetReferenceAngle (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetReferenceAngle();
*/
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.physics.box2d.joints;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Joint;
import com.badlogic.gdx.physics.box2d.World;
/** A prismatic joint. This joint provides one degree of freedom: translation along an axis fixed in body1. Relative rotation is
* prevented. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint
* friction. */
public class PrismaticJoint extends Joint {
// @off
/*JNI
#include <Box2D/Box2D.h>
*/
private final float[] tmp = new float[2];
private final Vector2 localAnchorA = new Vector2();
private final Vector2 localAnchorB = new Vector2();
private final Vector2 localAxisA = new Vector2();
public PrismaticJoint (World world, long addr) {
super(world, addr);
}
public Vector2 getLocalAnchorA () {
jniGetLocalAnchorA(addr, tmp);
localAnchorA.set(tmp[0], tmp[1]);
return localAnchorA;
}
private native void jniGetLocalAnchorA (long addr, float[] anchor); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
anchor[0] = joint->GetLocalAnchorA().x;
anchor[1] = joint->GetLocalAnchorA().y;
*/
public Vector2 getLocalAnchorB () {
jniGetLocalAnchorB(addr, tmp);
localAnchorB.set(tmp[0], tmp[1]);
return localAnchorB;
}
private native void jniGetLocalAnchorB (long addr, float[] anchor); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
anchor[0] = joint->GetLocalAnchorB().x;
anchor[1] = joint->GetLocalAnchorB().y;
*/
public Vector2 getLocalAxisA () {
jniGetLocalAxisA(addr, tmp);
localAxisA.set(tmp[0], tmp[1]);
return localAxisA;
}
private native void jniGetLocalAxisA (long addr, float[] anchor); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
anchor[0] = joint->GetLocalAxisA().x;
anchor[1] = joint->GetLocalAxisA().y;
*/
/** Get the current joint translation, usually in meters. */
public float getJointTranslation () {
return jniGetJointTranslation(addr);
}
private native float jniGetJointTranslation (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetJointTranslation();
*/
/** Get the current joint translation speed, usually in meters per second. */
public float getJointSpeed () {
return jniGetJointSpeed(addr);
}
private native float jniGetJointSpeed (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetJointSpeed();
*/
/** Is the joint limit enabled? */
public boolean isLimitEnabled () {
return jniIsLimitEnabled(addr);
}
private native boolean jniIsLimitEnabled (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->IsLimitEnabled();
*/
/** Enable/disable the joint limit. */
public void enableLimit (boolean flag) {
jniEnableLimit(addr, flag);
}
private native void jniEnableLimit (long addr, boolean flag); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
joint->EnableLimit(flag);
*/
/** Get the lower joint limit, usually in meters. */
public float getLowerLimit () {
return jniGetLowerLimit(addr);
}
private native float jniGetLowerLimit (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetLowerLimit();
*/
/** Get the upper joint limit, usually in meters. */
public float getUpperLimit () {
return jniGetUpperLimit(addr);
}
private native float jniGetUpperLimit (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetUpperLimit();
*/
/** Set the joint limits, usually in meters. */
public void setLimits (float lower, float upper) {
jniSetLimits(addr, lower, upper);
}
private native void jniSetLimits (long addr, float lower, float upper); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
joint->SetLimits(lower, upper );
*/
/** Is the joint motor enabled? */
public boolean isMotorEnabled () {
return jniIsMotorEnabled(addr);
}
private native boolean jniIsMotorEnabled (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->IsMotorEnabled();
*/
/** Enable/disable the joint motor. */
public void enableMotor (boolean flag) {
jniEnableMotor(addr, flag);
}
private native void jniEnableMotor (long addr, boolean flag); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
joint->EnableMotor(flag);
*/
/** Set the motor speed, usually in meters per second. */
public void setMotorSpeed (float speed) {
jniSetMotorSpeed(addr, speed);
}
private native void jniSetMotorSpeed (long addr, float speed); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
joint->SetMotorSpeed(speed);
*/
/** Get the motor speed, usually in meters per second. */
public float getMotorSpeed () {
return jniGetMotorSpeed(addr);
}
private native float jniGetMotorSpeed (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetMotorSpeed();
*/
/** Set the maximum motor force, usually in N. */
public void setMaxMotorForce (float force) {
jniSetMaxMotorForce(addr, force);
}
private native void jniSetMaxMotorForce (long addr, float force); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
joint->SetMaxMotorForce(force);
*/
/** Get the current motor force given the inverse time step, usually in N. */
public float getMotorForce (float invDt) {
return jniGetMotorForce(addr, invDt);
}
private native float jniGetMotorForce (long addr, float invDt); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetMotorForce(invDt);
*/
/** Get the max motor force, usually in N. */
public float getMaxMotorForce () {
return jniGetMaxMotorForce(addr);
}
private native float jniGetMaxMotorForce (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetMaxMotorForce();
*/
/** Get the reference angle. */
public float getReferenceAngle () {
return jniGetReferenceAngle(addr);
}
private native float jniGetReferenceAngle (long addr); /*
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetReferenceAngle();
*/
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-tools/src/com/badlogic/gdx/tiledmappacker/TiledMapPacker.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tiledmappacker;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.loaders.resolvers.AbsoluteFileHandleResolver;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTile;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileSet;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.tiles.AnimatedTiledMapTile;
import com.badlogic.gdx.maps.tiled.tiles.StaticTiledMapTile;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.tools.texturepacker.TexturePacker;
import com.badlogic.gdx.tools.texturepacker.TexturePacker.Settings;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.IntArray;
import com.badlogic.gdx.utils.ObjectMap;
/** Given one or more TMX tilemaps, packs all tileset resources used across the maps, or the resources used per map, into a
* single, or multiple (one per map), {@link TextureAtlas} and produces a new TMX file to be loaded with an AtlasTiledMapLoader
* loader. Optionally, it can keep track of unused tiles and omit them from the generated atlas, reducing the resource size.
*
* The original TMX map file will be parsed by using the {@link TmxMapLoader} loader, thus access to a valid OpenGL context is
* <b>required</b>, that's why an LwjglApplication is created by this preprocessor.
*
* The new TMX map file will contains a new property, namely "atlas", whose value will enable the AtlasTiledMapLoader to correctly
* read the associated TextureAtlas representing the tileset.
*
* @author David Fraska and others (initial implementation, tell me who you are!)
* @author Manuel Bua */
public class TiledMapPacker {
private TexturePacker packer;
private TiledMap map;
private TmxMapLoader mapLoader = new TmxMapLoader(new AbsoluteFileHandleResolver());
private TiledMapPackerSettings settings;
private static final String TilesetsOutputDir = "tileset";
static String AtlasOutputName = "packed";
private HashMap<String, IntArray> tilesetUsedIds = new HashMap<String, IntArray>();
private ObjectMap<String, TiledMapTileSet> tilesetsToPack;
static File inputDir;
static File outputDir;
private FileHandle currentDir;
private static class TmxFilter implements FilenameFilter {
public TmxFilter () {
}
@Override
public boolean accept (File dir, String name) {
return (name.endsWith(".tmx"));
}
}
private static class DirFilter implements FilenameFilter {
public DirFilter () {
}
@Override
public boolean accept (File f, String s) {
return (new File(f, s).isDirectory());
}
}
/** Constructs a new preprocessor by using the default packing settings */
public TiledMapPacker () {
this(new TiledMapPackerSettings());
}
/** Constructs a new preprocessor by using the specified packing settings */
public TiledMapPacker (TiledMapPackerSettings settings) {
this.settings = settings;
}
/** You can either run the {@link TiledMapPacker#main(String[])} method or reference this class in your own project and call
* this method. If working with libGDX sources, you can also run this file to create a run configuration then export it as a
* Runnable Jar. To run from a nightly build:
*
* <code> <br><br>
* Linux / OS X <br>
java -cp gdx.jar:gdx-natives.jar:gdx-backend-lwjgl.jar:gdx-backend-lwjgl-natives.jar:gdx-tiled-preprocessor.jar:extensions/gdx-tools/gdx-tools.jar
com.badlogic.gdx.tiledmappacker.TiledMapPacker inputDir [outputDir] [--strip-unused] [--combine-tilesets] [-v]
* <br><br>
*
* Windows <br>
java -cp gdx.jar;gdx-natives.jar;gdx-backend-lwjgl.jar;gdx-backend-lwjgl-natives.jar;gdx-tiled-preprocessor.jar;extensions/gdx-tools/gdx-tools.jar
com.badlogic.gdx.tiledmappacker.TiledMapPacker inputDir [outputDir] [--strip-unused] [--combine-tilesets] [-v]
* <br><br> </code>
*
* Keep in mind that this preprocessor will need to load the maps by using the {@link TmxMapLoader} loader and this in turn
* will need a valid OpenGL context to work.
*
* Process a directory containing TMX map files representing Tiled maps and produce multiple, or a single, TextureAtlas as well
* as new processed TMX map files, correctly referencing the generated {@link TextureAtlas} by using the "atlas" custom map
* property. */
public void processInputDir (Settings texturePackerSettings) throws IOException {
FileHandle inputDirHandle = new FileHandle(inputDir.getCanonicalPath());
File[] mapFilesInCurrentDir = inputDir.listFiles(new TmxFilter());
tilesetsToPack = new ObjectMap<String, TiledMapTileSet>();
// Processes the maps inside inputDir
for (File mapFile : mapFilesInCurrentDir) {
processSingleMap(mapFile, inputDirHandle, texturePackerSettings);
}
processSubdirectories(inputDirHandle, texturePackerSettings);
boolean combineTilesets = this.settings.combineTilesets;
if (combineTilesets == true) {
packTilesets(inputDirHandle, texturePackerSettings);
}
}
/** Looks for subdirectories inside parentHandle, processes maps in subdirectory, repeat.
* @param currentDir The directory to look for maps and other directories
* @throws IOException */
private void processSubdirectories (FileHandle currentDir, Settings texturePackerSettings) throws IOException {
File parentPath = new File(currentDir.path());
File[] directories = parentPath.listFiles(new DirFilter());
for (File directory : directories) {
currentDir = new FileHandle(directory.getCanonicalPath());
File[] mapFilesInCurrentDir = directory.listFiles(new TmxFilter());
for (File mapFile : mapFilesInCurrentDir) {
processSingleMap(mapFile, currentDir, texturePackerSettings);
}
processSubdirectories(currentDir, texturePackerSettings);
}
}
private void processSingleMap (File mapFile, FileHandle dirHandle, Settings texturePackerSettings) throws IOException {
boolean combineTilesets = this.settings.combineTilesets;
if (combineTilesets == false) {
tilesetUsedIds = new HashMap<String, IntArray>();
tilesetsToPack = new ObjectMap<String, TiledMapTileSet>();
}
map = mapLoader.load(mapFile.getCanonicalPath());
// if enabled, build a list of used tileids for the tileset used by this map
boolean stripUnusedTiles = this.settings.stripUnusedTiles;
if (stripUnusedTiles) {
stripUnusedTiles();
} else {
for (TiledMapTileSet tileset : map.getTileSets()) {
String tilesetName = tileset.getName();
if (!tilesetsToPack.containsKey(tilesetName)) {
tilesetsToPack.put(tilesetName, tileset);
}
}
}
if (combineTilesets == false) {
FileHandle tmpHandle = new FileHandle(mapFile.getName());
this.settings.atlasOutputName = tmpHandle.nameWithoutExtension();
packTilesets(dirHandle, texturePackerSettings);
}
FileHandle tmxFile = new FileHandle(mapFile.getCanonicalPath());
writeUpdatedTMX(map, tmxFile);
}
private void stripUnusedTiles () {
int mapWidth = map.getProperties().get("width", Integer.class);
int mapHeight = map.getProperties().get("height", Integer.class);
int numlayers = map.getLayers().getCount();
int bucketSize = mapWidth * mapHeight * numlayers;
Iterator<MapLayer> it = map.getLayers().iterator();
while (it.hasNext()) {
MapLayer layer = it.next();
// some layers can be plain MapLayer instances (ie. object groups), just ignore them
if (layer instanceof TiledMapTileLayer) {
TiledMapTileLayer tlayer = (TiledMapTileLayer)layer;
for (int y = 0; y < mapHeight; ++y) {
for (int x = 0; x < mapWidth; ++x) {
if (tlayer.getCell(x, y) != null) {
TiledMapTile tile = tlayer.getCell(x, y).getTile();
if (tile instanceof AnimatedTiledMapTile) {
AnimatedTiledMapTile aTile = (AnimatedTiledMapTile)tile;
for (StaticTiledMapTile t : aTile.getFrameTiles()) {
addTile(t, bucketSize);
}
}
// Adds non-animated tiles and the base animated tile
addTile(tile, bucketSize);
}
}
}
}
}
}
private void addTile (TiledMapTile tile, int bucketSize) {
int tileid = tile.getId() & ~0xE0000000;
String tilesetName = tilesetNameFromTileId(map, tileid);
IntArray usedIds = getUsedIdsBucket(tilesetName, bucketSize);
usedIds.add(tileid);
// track this tileset to be packed if not already tracked
if (!tilesetsToPack.containsKey(tilesetName)) {
tilesetsToPack.put(tilesetName, map.getTileSets().getTileSet(tilesetName));
}
}
private String tilesetNameFromTileId (TiledMap map, int tileid) {
String name = "";
if (tileid == 0) {
return "";
}
for (TiledMapTileSet tileset : map.getTileSets()) {
int firstgid = tileset.getProperties().get("firstgid", -1, Integer.class);
if (firstgid == -1) continue; // skip this tileset
if (tileid >= firstgid) {
name = tileset.getName();
} else {
return name;
}
}
return name;
}
/** Returns the usedIds bucket for the given tileset name. If it doesn't exist one will be created with the specified size if
* its > 0, else null will be returned.
*
* @param size The size to use to create a new bucket if it doesn't exist, else specify 0 or lower to return null instead
* @return a bucket */
private IntArray getUsedIdsBucket (String tilesetName, int size) {
if (tilesetUsedIds.containsKey(tilesetName)) {
return tilesetUsedIds.get(tilesetName);
}
if (size <= 0) {
return null;
}
IntArray bucket = new IntArray(size);
tilesetUsedIds.put(tilesetName, bucket);
return bucket;
}
/** Traverse the specified tilesets, optionally lookup the used ids and pass every tile image to the {@link TexturePacker},
* optionally ignoring unused tile ids */
private void packTilesets (FileHandle inputDirHandle, Settings texturePackerSettings) throws IOException {
BufferedImage tile;
Vector2 tileLocation;
Graphics g;
packer = new TexturePacker(texturePackerSettings);
for (TiledMapTileSet set : tilesetsToPack.values()) {
String tilesetName = set.getName();
System.out.println("Processing tileset " + tilesetName);
IntArray usedIds = this.settings.stripUnusedTiles ? getUsedIdsBucket(tilesetName, -1) : null;
int tileWidth = set.getProperties().get("tilewidth", Integer.class);
int tileHeight = set.getProperties().get("tileheight", Integer.class);
int firstgid = set.getProperties().get("firstgid", Integer.class);
String imageName = set.getProperties().get("imagesource", String.class);
TileSetLayout layout = new TileSetLayout(firstgid, set, inputDirHandle);
for (int gid = layout.firstgid, i = 0; i < layout.numTiles; gid++, i++) {
boolean verbose = this.settings.verbose;
if (usedIds != null && !usedIds.contains(gid)) {
if (verbose) {
System.out.println("Stripped id #" + gid + " from tileset \"" + tilesetName + "\"");
}
continue;
}
tileLocation = layout.getLocation(gid);
tile = new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_4BYTE_ABGR);
g = tile.createGraphics();
g.drawImage(layout.image, 0, 0, tileWidth, tileHeight, (int)tileLocation.x, (int)tileLocation.y,
(int)tileLocation.x + tileWidth, (int)tileLocation.y + tileHeight, null);
if (verbose) {
System.out.println(
"Adding " + tileWidth + "x" + tileHeight + " (" + (int)tileLocation.x + ", " + (int)tileLocation.y + ")");
}
// AtlasTmxMapLoader expects every tileset's index to begin at zero for the first tile in every tileset.
// so the region's adjusted gid is (gid - layout.firstgid). firstgid will be added back in AtlasTmxMapLoader on load
int adjustedGid = gid - layout.firstgid;
final String separator = "_";
String regionName = tilesetName + separator + adjustedGid;
packer.addImage(tile, regionName);
}
}
String tilesetOutputDir = outputDir.toString() + "/" + this.settings.tilesetOutputDirectory;
File relativeTilesetOutputDir = new File(tilesetOutputDir);
File outputDirTilesets = new File(relativeTilesetOutputDir.getCanonicalPath());
outputDirTilesets.mkdirs();
packer.pack(outputDirTilesets, this.settings.atlasOutputName + ".atlas");
}
private void writeUpdatedTMX (TiledMap tiledMap, FileHandle tmxFileHandle) throws IOException {
Document doc;
DocumentBuilder docBuilder;
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
try {
docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.parse(tmxFileHandle.read());
Node map = doc.getFirstChild();
while (map.getNodeType() != Node.ELEMENT_NODE || map.getNodeName() != "map") {
if ((map = map.getNextSibling()) == null) {
throw new GdxRuntimeException("Couldn't find map node!");
}
}
setProperty(doc, map, "atlas", settings.tilesetOutputDirectory + "/" + settings.atlasOutputName + ".atlas");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
outputDir.mkdirs();
StreamResult result = new StreamResult(new File(outputDir, tmxFileHandle.name()));
transformer.transform(source, result);
} catch (ParserConfigurationException e) {
throw new RuntimeException("ParserConfigurationException: " + e.getMessage());
} catch (SAXException e) {
throw new RuntimeException("SAXException: " + e.getMessage());
} catch (TransformerConfigurationException e) {
throw new RuntimeException("TransformerConfigurationException: " + e.getMessage());
} catch (TransformerException e) {
throw new RuntimeException("TransformerException: " + e.getMessage());
}
}
private static void setProperty (Document doc, Node parent, String name, String value) {
Node properties = getFirstChildNodeByName(parent, "properties");
Node property = getFirstChildByNameAttrValue(properties, "property", "name", name);
NamedNodeMap attributes = property.getAttributes();
Node valueNode = attributes.getNamedItem("value");
if (valueNode == null) {
valueNode = doc.createAttribute("value");
valueNode.setNodeValue(value);
attributes.setNamedItem(valueNode);
} else {
valueNode.setNodeValue(value);
}
}
/** If the child node doesn't exist, it is created. */
private static Node getFirstChildNodeByName (Node parent, String child) {
NodeList childNodes = parent.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
if (childNodes.item(i).getNodeName().equals(child)) {
return childNodes.item(i);
}
}
Node newNode = parent.getOwnerDocument().createElement(child);
if (childNodes.item(0) != null)
return parent.insertBefore(newNode, childNodes.item(0));
else
return parent.appendChild(newNode);
}
/** If the child node or attribute doesn't exist, it is created. Usage example: Node property =
* getFirstChildByAttrValue(properties, "property", "name"); */
private static Node getFirstChildByNameAttrValue (Node node, String childName, String attr, String value) {
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
if (childNodes.item(i).getNodeName().equals(childName)) {
NamedNodeMap attributes = childNodes.item(i).getAttributes();
Node attribute = attributes.getNamedItem(attr);
if (attribute.getNodeValue().equals(value)) return childNodes.item(i);
}
}
Node newNode = node.getOwnerDocument().createElement(childName);
NamedNodeMap attributes = newNode.getAttributes();
Attr nodeAttr = node.getOwnerDocument().createAttribute(attr);
nodeAttr.setNodeValue(value);
attributes.setNamedItem(nodeAttr);
if (childNodes.item(0) != null) {
return node.insertBefore(newNode, childNodes.item(0));
} else {
return node.appendChild(newNode);
}
}
/** Processes a directory of Tile Maps, compressing each tile set contained in any map once.
*
* @param args args[0]: the input directory containing the tmx files (and tile sets, relative to the path listed in the tmx
* file). args[1]: The output directory for the tmx files, should be empty before running. args[2-4] options */
public static void main (String[] args) {
final Settings texturePackerSettings = new Settings();
texturePackerSettings.paddingX = 2;
texturePackerSettings.paddingY = 2;
texturePackerSettings.edgePadding = true;
texturePackerSettings.duplicatePadding = true;
texturePackerSettings.bleed = true;
texturePackerSettings.alias = true;
texturePackerSettings.useIndexes = true;
final TiledMapPackerSettings packerSettings = new TiledMapPackerSettings();
if (args.length == 0) {
printUsage();
System.exit(0);
} else if (args.length == 1) {
inputDir = new File(args[0]);
outputDir = new File(inputDir, "../output/");
} else if (args.length == 2) {
inputDir = new File(args[0]);
outputDir = new File(args[1]);
} else {
inputDir = new File(args[0]);
outputDir = new File(args[1]);
processExtraArgs(args, packerSettings);
}
TiledMapPacker packer = new TiledMapPacker(packerSettings);
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.forceExit = false;
config.width = 100;
config.height = 50;
config.title = "TiledMapPacker";
new LwjglApplication(new ApplicationListener() {
@Override
public void resume () {
}
@Override
public void resize (int width, int height) {
}
@Override
public void render () {
}
@Override
public void pause () {
}
@Override
public void dispose () {
}
@Override
public void create () {
TiledMapPacker packer = new TiledMapPacker(packerSettings);
if (!inputDir.exists()) {
System.out.println(inputDir.getAbsolutePath());
throw new RuntimeException("Input directory does not exist: " + inputDir);
}
try {
packer.processInputDir(texturePackerSettings);
} catch (IOException e) {
throw new RuntimeException("Error processing map: " + e.getMessage());
}
System.out.println("Finished processing.");
Gdx.app.exit();
}
}, config);
}
private static void processExtraArgs (String[] args, TiledMapPackerSettings packerSettings) {
String stripUnused = "--strip-unused";
String combineTilesets = "--combine-tilesets";
String verbose = "-v";
int length = args.length - 2;
String[] argsNotDir = new String[length];
System.arraycopy(args, 2, argsNotDir, 0, length);
for (String string : argsNotDir) {
if (stripUnused.equals(string)) {
packerSettings.stripUnusedTiles = true;
} else if (combineTilesets.equals(string)) {
packerSettings.combineTilesets = true;
} else if (verbose.equals(string)) {
packerSettings.verbose = true;
} else {
System.out.println("\nOption \"" + string + "\" not recognized.\n");
printUsage();
System.exit(0);
}
}
}
private static void printUsage () {
System.out.println("Usage: INPUTDIR [OUTPUTDIR] [--strip-unused] [--combine-tilesets] [-v]");
System.out.println("Processes a directory of Tiled .tmx maps. Unable to process maps with XML");
System.out.println("tile layer format.");
System.out.println(" --strip-unused omits all tiles that are not used. Speeds up");
System.out.println(" the processing. Smaller tilesets.");
System.out.println(" --combine-tilesets instead of creating a tileset for each map,");
System.out.println(" this combines the tilesets into some kind");
System.out.println(" of monster tileset. Has problems with tileset");
System.out.println(" location. Has problems with nested folders.");
System.out.println(" Not recommended.");
System.out.println(" -v outputs which tiles are stripped and included");
System.out.println();
}
public static class TiledMapPackerSettings {
public boolean stripUnusedTiles = false;
public boolean combineTilesets = false;
public boolean verbose = false;
public String tilesetOutputDirectory = TilesetsOutputDir;
public String atlasOutputName = AtlasOutputName;
}
}
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tiledmappacker;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.loaders.resolvers.AbsoluteFileHandleResolver;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTile;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileSet;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.tiles.AnimatedTiledMapTile;
import com.badlogic.gdx.maps.tiled.tiles.StaticTiledMapTile;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.tools.texturepacker.TexturePacker;
import com.badlogic.gdx.tools.texturepacker.TexturePacker.Settings;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.IntArray;
import com.badlogic.gdx.utils.ObjectMap;
/** Given one or more TMX tilemaps, packs all tileset resources used across the maps, or the resources used per map, into a
* single, or multiple (one per map), {@link TextureAtlas} and produces a new TMX file to be loaded with an AtlasTiledMapLoader
* loader. Optionally, it can keep track of unused tiles and omit them from the generated atlas, reducing the resource size.
*
* The original TMX map file will be parsed by using the {@link TmxMapLoader} loader, thus access to a valid OpenGL context is
* <b>required</b>, that's why an LwjglApplication is created by this preprocessor.
*
* The new TMX map file will contains a new property, namely "atlas", whose value will enable the AtlasTiledMapLoader to correctly
* read the associated TextureAtlas representing the tileset.
*
* @author David Fraska and others (initial implementation, tell me who you are!)
* @author Manuel Bua */
public class TiledMapPacker {
private TexturePacker packer;
private TiledMap map;
private TmxMapLoader mapLoader = new TmxMapLoader(new AbsoluteFileHandleResolver());
private TiledMapPackerSettings settings;
private static final String TilesetsOutputDir = "tileset";
static String AtlasOutputName = "packed";
private HashMap<String, IntArray> tilesetUsedIds = new HashMap<String, IntArray>();
private ObjectMap<String, TiledMapTileSet> tilesetsToPack;
static File inputDir;
static File outputDir;
private FileHandle currentDir;
private static class TmxFilter implements FilenameFilter {
public TmxFilter () {
}
@Override
public boolean accept (File dir, String name) {
return (name.endsWith(".tmx"));
}
}
private static class DirFilter implements FilenameFilter {
public DirFilter () {
}
@Override
public boolean accept (File f, String s) {
return (new File(f, s).isDirectory());
}
}
/** Constructs a new preprocessor by using the default packing settings */
public TiledMapPacker () {
this(new TiledMapPackerSettings());
}
/** Constructs a new preprocessor by using the specified packing settings */
public TiledMapPacker (TiledMapPackerSettings settings) {
this.settings = settings;
}
/** You can either run the {@link TiledMapPacker#main(String[])} method or reference this class in your own project and call
* this method. If working with libGDX sources, you can also run this file to create a run configuration then export it as a
* Runnable Jar. To run from a nightly build:
*
* <code> <br><br>
* Linux / OS X <br>
java -cp gdx.jar:gdx-natives.jar:gdx-backend-lwjgl.jar:gdx-backend-lwjgl-natives.jar:gdx-tiled-preprocessor.jar:extensions/gdx-tools/gdx-tools.jar
com.badlogic.gdx.tiledmappacker.TiledMapPacker inputDir [outputDir] [--strip-unused] [--combine-tilesets] [-v]
* <br><br>
*
* Windows <br>
java -cp gdx.jar;gdx-natives.jar;gdx-backend-lwjgl.jar;gdx-backend-lwjgl-natives.jar;gdx-tiled-preprocessor.jar;extensions/gdx-tools/gdx-tools.jar
com.badlogic.gdx.tiledmappacker.TiledMapPacker inputDir [outputDir] [--strip-unused] [--combine-tilesets] [-v]
* <br><br> </code>
*
* Keep in mind that this preprocessor will need to load the maps by using the {@link TmxMapLoader} loader and this in turn
* will need a valid OpenGL context to work.
*
* Process a directory containing TMX map files representing Tiled maps and produce multiple, or a single, TextureAtlas as well
* as new processed TMX map files, correctly referencing the generated {@link TextureAtlas} by using the "atlas" custom map
* property. */
public void processInputDir (Settings texturePackerSettings) throws IOException {
FileHandle inputDirHandle = new FileHandle(inputDir.getCanonicalPath());
File[] mapFilesInCurrentDir = inputDir.listFiles(new TmxFilter());
tilesetsToPack = new ObjectMap<String, TiledMapTileSet>();
// Processes the maps inside inputDir
for (File mapFile : mapFilesInCurrentDir) {
processSingleMap(mapFile, inputDirHandle, texturePackerSettings);
}
processSubdirectories(inputDirHandle, texturePackerSettings);
boolean combineTilesets = this.settings.combineTilesets;
if (combineTilesets == true) {
packTilesets(inputDirHandle, texturePackerSettings);
}
}
/** Looks for subdirectories inside parentHandle, processes maps in subdirectory, repeat.
* @param currentDir The directory to look for maps and other directories
* @throws IOException */
private void processSubdirectories (FileHandle currentDir, Settings texturePackerSettings) throws IOException {
File parentPath = new File(currentDir.path());
File[] directories = parentPath.listFiles(new DirFilter());
for (File directory : directories) {
currentDir = new FileHandle(directory.getCanonicalPath());
File[] mapFilesInCurrentDir = directory.listFiles(new TmxFilter());
for (File mapFile : mapFilesInCurrentDir) {
processSingleMap(mapFile, currentDir, texturePackerSettings);
}
processSubdirectories(currentDir, texturePackerSettings);
}
}
private void processSingleMap (File mapFile, FileHandle dirHandle, Settings texturePackerSettings) throws IOException {
boolean combineTilesets = this.settings.combineTilesets;
if (combineTilesets == false) {
tilesetUsedIds = new HashMap<String, IntArray>();
tilesetsToPack = new ObjectMap<String, TiledMapTileSet>();
}
map = mapLoader.load(mapFile.getCanonicalPath());
// if enabled, build a list of used tileids for the tileset used by this map
boolean stripUnusedTiles = this.settings.stripUnusedTiles;
if (stripUnusedTiles) {
stripUnusedTiles();
} else {
for (TiledMapTileSet tileset : map.getTileSets()) {
String tilesetName = tileset.getName();
if (!tilesetsToPack.containsKey(tilesetName)) {
tilesetsToPack.put(tilesetName, tileset);
}
}
}
if (combineTilesets == false) {
FileHandle tmpHandle = new FileHandle(mapFile.getName());
this.settings.atlasOutputName = tmpHandle.nameWithoutExtension();
packTilesets(dirHandle, texturePackerSettings);
}
FileHandle tmxFile = new FileHandle(mapFile.getCanonicalPath());
writeUpdatedTMX(map, tmxFile);
}
private void stripUnusedTiles () {
int mapWidth = map.getProperties().get("width", Integer.class);
int mapHeight = map.getProperties().get("height", Integer.class);
int numlayers = map.getLayers().getCount();
int bucketSize = mapWidth * mapHeight * numlayers;
Iterator<MapLayer> it = map.getLayers().iterator();
while (it.hasNext()) {
MapLayer layer = it.next();
// some layers can be plain MapLayer instances (ie. object groups), just ignore them
if (layer instanceof TiledMapTileLayer) {
TiledMapTileLayer tlayer = (TiledMapTileLayer)layer;
for (int y = 0; y < mapHeight; ++y) {
for (int x = 0; x < mapWidth; ++x) {
if (tlayer.getCell(x, y) != null) {
TiledMapTile tile = tlayer.getCell(x, y).getTile();
if (tile instanceof AnimatedTiledMapTile) {
AnimatedTiledMapTile aTile = (AnimatedTiledMapTile)tile;
for (StaticTiledMapTile t : aTile.getFrameTiles()) {
addTile(t, bucketSize);
}
}
// Adds non-animated tiles and the base animated tile
addTile(tile, bucketSize);
}
}
}
}
}
}
private void addTile (TiledMapTile tile, int bucketSize) {
int tileid = tile.getId() & ~0xE0000000;
String tilesetName = tilesetNameFromTileId(map, tileid);
IntArray usedIds = getUsedIdsBucket(tilesetName, bucketSize);
usedIds.add(tileid);
// track this tileset to be packed if not already tracked
if (!tilesetsToPack.containsKey(tilesetName)) {
tilesetsToPack.put(tilesetName, map.getTileSets().getTileSet(tilesetName));
}
}
private String tilesetNameFromTileId (TiledMap map, int tileid) {
String name = "";
if (tileid == 0) {
return "";
}
for (TiledMapTileSet tileset : map.getTileSets()) {
int firstgid = tileset.getProperties().get("firstgid", -1, Integer.class);
if (firstgid == -1) continue; // skip this tileset
if (tileid >= firstgid) {
name = tileset.getName();
} else {
return name;
}
}
return name;
}
/** Returns the usedIds bucket for the given tileset name. If it doesn't exist one will be created with the specified size if
* its > 0, else null will be returned.
*
* @param size The size to use to create a new bucket if it doesn't exist, else specify 0 or lower to return null instead
* @return a bucket */
private IntArray getUsedIdsBucket (String tilesetName, int size) {
if (tilesetUsedIds.containsKey(tilesetName)) {
return tilesetUsedIds.get(tilesetName);
}
if (size <= 0) {
return null;
}
IntArray bucket = new IntArray(size);
tilesetUsedIds.put(tilesetName, bucket);
return bucket;
}
/** Traverse the specified tilesets, optionally lookup the used ids and pass every tile image to the {@link TexturePacker},
* optionally ignoring unused tile ids */
private void packTilesets (FileHandle inputDirHandle, Settings texturePackerSettings) throws IOException {
BufferedImage tile;
Vector2 tileLocation;
Graphics g;
packer = new TexturePacker(texturePackerSettings);
for (TiledMapTileSet set : tilesetsToPack.values()) {
String tilesetName = set.getName();
System.out.println("Processing tileset " + tilesetName);
IntArray usedIds = this.settings.stripUnusedTiles ? getUsedIdsBucket(tilesetName, -1) : null;
int tileWidth = set.getProperties().get("tilewidth", Integer.class);
int tileHeight = set.getProperties().get("tileheight", Integer.class);
int firstgid = set.getProperties().get("firstgid", Integer.class);
String imageName = set.getProperties().get("imagesource", String.class);
TileSetLayout layout = new TileSetLayout(firstgid, set, inputDirHandle);
for (int gid = layout.firstgid, i = 0; i < layout.numTiles; gid++, i++) {
boolean verbose = this.settings.verbose;
if (usedIds != null && !usedIds.contains(gid)) {
if (verbose) {
System.out.println("Stripped id #" + gid + " from tileset \"" + tilesetName + "\"");
}
continue;
}
tileLocation = layout.getLocation(gid);
tile = new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_4BYTE_ABGR);
g = tile.createGraphics();
g.drawImage(layout.image, 0, 0, tileWidth, tileHeight, (int)tileLocation.x, (int)tileLocation.y,
(int)tileLocation.x + tileWidth, (int)tileLocation.y + tileHeight, null);
if (verbose) {
System.out.println(
"Adding " + tileWidth + "x" + tileHeight + " (" + (int)tileLocation.x + ", " + (int)tileLocation.y + ")");
}
// AtlasTmxMapLoader expects every tileset's index to begin at zero for the first tile in every tileset.
// so the region's adjusted gid is (gid - layout.firstgid). firstgid will be added back in AtlasTmxMapLoader on load
int adjustedGid = gid - layout.firstgid;
final String separator = "_";
String regionName = tilesetName + separator + adjustedGid;
packer.addImage(tile, regionName);
}
}
String tilesetOutputDir = outputDir.toString() + "/" + this.settings.tilesetOutputDirectory;
File relativeTilesetOutputDir = new File(tilesetOutputDir);
File outputDirTilesets = new File(relativeTilesetOutputDir.getCanonicalPath());
outputDirTilesets.mkdirs();
packer.pack(outputDirTilesets, this.settings.atlasOutputName + ".atlas");
}
private void writeUpdatedTMX (TiledMap tiledMap, FileHandle tmxFileHandle) throws IOException {
Document doc;
DocumentBuilder docBuilder;
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
try {
docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.parse(tmxFileHandle.read());
Node map = doc.getFirstChild();
while (map.getNodeType() != Node.ELEMENT_NODE || map.getNodeName() != "map") {
if ((map = map.getNextSibling()) == null) {
throw new GdxRuntimeException("Couldn't find map node!");
}
}
setProperty(doc, map, "atlas", settings.tilesetOutputDirectory + "/" + settings.atlasOutputName + ".atlas");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
outputDir.mkdirs();
StreamResult result = new StreamResult(new File(outputDir, tmxFileHandle.name()));
transformer.transform(source, result);
} catch (ParserConfigurationException e) {
throw new RuntimeException("ParserConfigurationException: " + e.getMessage());
} catch (SAXException e) {
throw new RuntimeException("SAXException: " + e.getMessage());
} catch (TransformerConfigurationException e) {
throw new RuntimeException("TransformerConfigurationException: " + e.getMessage());
} catch (TransformerException e) {
throw new RuntimeException("TransformerException: " + e.getMessage());
}
}
private static void setProperty (Document doc, Node parent, String name, String value) {
Node properties = getFirstChildNodeByName(parent, "properties");
Node property = getFirstChildByNameAttrValue(properties, "property", "name", name);
NamedNodeMap attributes = property.getAttributes();
Node valueNode = attributes.getNamedItem("value");
if (valueNode == null) {
valueNode = doc.createAttribute("value");
valueNode.setNodeValue(value);
attributes.setNamedItem(valueNode);
} else {
valueNode.setNodeValue(value);
}
}
/** If the child node doesn't exist, it is created. */
private static Node getFirstChildNodeByName (Node parent, String child) {
NodeList childNodes = parent.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
if (childNodes.item(i).getNodeName().equals(child)) {
return childNodes.item(i);
}
}
Node newNode = parent.getOwnerDocument().createElement(child);
if (childNodes.item(0) != null)
return parent.insertBefore(newNode, childNodes.item(0));
else
return parent.appendChild(newNode);
}
/** If the child node or attribute doesn't exist, it is created. Usage example: Node property =
* getFirstChildByAttrValue(properties, "property", "name"); */
private static Node getFirstChildByNameAttrValue (Node node, String childName, String attr, String value) {
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
if (childNodes.item(i).getNodeName().equals(childName)) {
NamedNodeMap attributes = childNodes.item(i).getAttributes();
Node attribute = attributes.getNamedItem(attr);
if (attribute.getNodeValue().equals(value)) return childNodes.item(i);
}
}
Node newNode = node.getOwnerDocument().createElement(childName);
NamedNodeMap attributes = newNode.getAttributes();
Attr nodeAttr = node.getOwnerDocument().createAttribute(attr);
nodeAttr.setNodeValue(value);
attributes.setNamedItem(nodeAttr);
if (childNodes.item(0) != null) {
return node.insertBefore(newNode, childNodes.item(0));
} else {
return node.appendChild(newNode);
}
}
/** Processes a directory of Tile Maps, compressing each tile set contained in any map once.
*
* @param args args[0]: the input directory containing the tmx files (and tile sets, relative to the path listed in the tmx
* file). args[1]: The output directory for the tmx files, should be empty before running. args[2-4] options */
public static void main (String[] args) {
final Settings texturePackerSettings = new Settings();
texturePackerSettings.paddingX = 2;
texturePackerSettings.paddingY = 2;
texturePackerSettings.edgePadding = true;
texturePackerSettings.duplicatePadding = true;
texturePackerSettings.bleed = true;
texturePackerSettings.alias = true;
texturePackerSettings.useIndexes = true;
final TiledMapPackerSettings packerSettings = new TiledMapPackerSettings();
if (args.length == 0) {
printUsage();
System.exit(0);
} else if (args.length == 1) {
inputDir = new File(args[0]);
outputDir = new File(inputDir, "../output/");
} else if (args.length == 2) {
inputDir = new File(args[0]);
outputDir = new File(args[1]);
} else {
inputDir = new File(args[0]);
outputDir = new File(args[1]);
processExtraArgs(args, packerSettings);
}
TiledMapPacker packer = new TiledMapPacker(packerSettings);
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.forceExit = false;
config.width = 100;
config.height = 50;
config.title = "TiledMapPacker";
new LwjglApplication(new ApplicationListener() {
@Override
public void resume () {
}
@Override
public void resize (int width, int height) {
}
@Override
public void render () {
}
@Override
public void pause () {
}
@Override
public void dispose () {
}
@Override
public void create () {
TiledMapPacker packer = new TiledMapPacker(packerSettings);
if (!inputDir.exists()) {
System.out.println(inputDir.getAbsolutePath());
throw new RuntimeException("Input directory does not exist: " + inputDir);
}
try {
packer.processInputDir(texturePackerSettings);
} catch (IOException e) {
throw new RuntimeException("Error processing map: " + e.getMessage());
}
System.out.println("Finished processing.");
Gdx.app.exit();
}
}, config);
}
private static void processExtraArgs (String[] args, TiledMapPackerSettings packerSettings) {
String stripUnused = "--strip-unused";
String combineTilesets = "--combine-tilesets";
String verbose = "-v";
int length = args.length - 2;
String[] argsNotDir = new String[length];
System.arraycopy(args, 2, argsNotDir, 0, length);
for (String string : argsNotDir) {
if (stripUnused.equals(string)) {
packerSettings.stripUnusedTiles = true;
} else if (combineTilesets.equals(string)) {
packerSettings.combineTilesets = true;
} else if (verbose.equals(string)) {
packerSettings.verbose = true;
} else {
System.out.println("\nOption \"" + string + "\" not recognized.\n");
printUsage();
System.exit(0);
}
}
}
private static void printUsage () {
System.out.println("Usage: INPUTDIR [OUTPUTDIR] [--strip-unused] [--combine-tilesets] [-v]");
System.out.println("Processes a directory of Tiled .tmx maps. Unable to process maps with XML");
System.out.println("tile layer format.");
System.out.println(" --strip-unused omits all tiles that are not used. Speeds up");
System.out.println(" the processing. Smaller tilesets.");
System.out.println(" --combine-tilesets instead of creating a tileset for each map,");
System.out.println(" this combines the tilesets into some kind");
System.out.println(" of monster tileset. Has problems with tileset");
System.out.println(" location. Has problems with nested folders.");
System.out.println(" Not recommended.");
System.out.println(" -v outputs which tiles are stripped and included");
System.out.println();
}
public static class TiledMapPackerSettings {
public boolean stripUnusedTiles = false;
public boolean combineTilesets = false;
public boolean verbose = false;
public String tilesetOutputDirectory = TilesetsOutputDir;
public String atlasOutputName = AtlasOutputName;
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./.git/hooks/prepare-commit-msg.sample | #!/bin/sh
#
# An example hook script to prepare the commit log message.
# Called by "git commit" with the name of the file that has the
# commit message, followed by the description of the commit
# message's source. The hook's purpose is to edit the commit
# message file. If the hook fails with a non-zero status,
# the commit is aborted.
#
# To enable this hook, rename this file to "prepare-commit-msg".
# This hook includes three examples. The first one removes the
# "# Please enter the commit message..." help message.
#
# The second includes the output of "git diff --name-status -r"
# into the message, just before the "git status" output. It is
# commented because it doesn't cope with --amend or with squashed
# commits.
#
# The third example adds a Signed-off-by line to the message, that can
# still be edited. This is rarely a good idea.
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3
/usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE"
# case "$COMMIT_SOURCE,$SHA1" in
# ,|template,)
# /usr/bin/perl -i.bak -pe '
# print "\n" . `git diff --cached --name-status -r`
# if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;;
# *) ;;
# esac
# SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE"
# if test -z "$COMMIT_SOURCE"
# then
# /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE"
# fi
| #!/bin/sh
#
# An example hook script to prepare the commit log message.
# Called by "git commit" with the name of the file that has the
# commit message, followed by the description of the commit
# message's source. The hook's purpose is to edit the commit
# message file. If the hook fails with a non-zero status,
# the commit is aborted.
#
# To enable this hook, rename this file to "prepare-commit-msg".
# This hook includes three examples. The first one removes the
# "# Please enter the commit message..." help message.
#
# The second includes the output of "git diff --name-status -r"
# into the message, just before the "git status" output. It is
# commented because it doesn't cope with --amend or with squashed
# commits.
#
# The third example adds a Signed-off-by line to the message, that can
# still be edited. This is rarely a good idea.
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3
/usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE"
# case "$COMMIT_SOURCE,$SHA1" in
# ,|template,)
# /usr/bin/perl -i.bak -pe '
# print "\n" . `git diff --cached --name-status -r`
# if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;;
# *) ;;
# esac
# SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE"
# if test -z "$COMMIT_SOURCE"
# then
# /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE"
# fi
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./gdx/res/com/badlogic/gdx/utils/JsonReader.rl | // Do not edit this file! Generated by Ragel.
// Ragel.exe -J -o ../../../../../src/com/badlogic/gdx/utils/JsonReader.java JsonReader.rl
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Arrays;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.JsonValue.ValueType;
/** Lightweight JSON parser.<br>
* <br>
* The default behavior is to parse the JSON into a DOM containing {@link JsonValue} objects. Extend this class and override
* methods to perform event driven parsing. When this is done, the parse methods will return null.
* @author Nathan Sweet */
public class JsonReader implements BaseJsonReader {
public JsonValue parse (String json) {
char[] data = json.toCharArray();
return parse(data, 0, data.length);
}
public JsonValue parse (Reader reader) {
char[] data = new char[1024];
int offset = 0;
try {
while (true) {
int length = reader.read(data, offset, data.length - offset);
if (length == -1) break;
if (length == 0) {
char[] newData = new char[data.length * 2];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
} else
offset += length;
}
} catch (IOException ex) {
throw new SerializationException("Error reading input.", ex);
} finally {
StreamUtils.closeQuietly(reader);
}
return parse(data, 0, offset);
}
public JsonValue parse (InputStream input) {
Reader reader;
try {
reader = new InputStreamReader(input, "UTF-8");
} catch (Exception ex) {
throw new SerializationException("Error reading stream.", ex);
}
return parse(reader);
}
public JsonValue parse (FileHandle file) {
Reader reader;
try {
reader = file.reader("UTF-8");
} catch (Exception ex) {
throw new SerializationException("Error reading file: " + file, ex);
}
try {
return parse(reader);
} catch (Exception ex) {
throw new SerializationException("Error parsing file: " + file, ex);
}
}
public JsonValue parse (char[] data, int offset, int length) {
stop = false;
int cs, p = offset, pe = length, eof = pe, top = 0;
int[] stack = new int[4];
int s = 0;
Array<String> names = new Array(8);
boolean needsUnescape = false, stringIsName = false, stringIsUnquoted = false;
RuntimeException parseRuntimeEx = null;
boolean debug = false;
if (debug) System.out.println();
try {
%%{
machine json;
prepush {
if (top == stack.length) stack = Arrays.copyOf(stack, stack.length * 2);
}
action name {
stringIsName = true;
}
action string {
String value = new String(data, s, p - s);
if (needsUnescape) value = unescape(value);
outer:
if (stringIsName) {
stringIsName = false;
if (debug) System.out.println("name: " + value);
names.add(value);
} else {
String name = names.size > 0 ? names.pop() : null;
if (stringIsUnquoted) {
if (value.equals("true")) {
if (debug) System.out.println("boolean: " + name + "=true");
bool(name, true);
break outer;
} else if (value.equals("false")) {
if (debug) System.out.println("boolean: " + name + "=false");
bool(name, false);
break outer;
} else if (value.equals("null")) {
string(name, null);
break outer;
}
boolean couldBeDouble = false, couldBeLong = true;
outer2:
for (int i = s; i < p; i++) {
switch (data[i]) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
case '+':
break;
case '.':
case 'e':
case 'E':
couldBeDouble = true;
couldBeLong = false;
break;
default:
couldBeDouble = false;
couldBeLong = false;
break outer2;
}
}
if (couldBeDouble) {
try {
if (debug) System.out.println("double: " + name + "=" + Double.parseDouble(value));
number(name, Double.parseDouble(value), value);
break outer;
} catch (NumberFormatException ignored) {
}
} else if (couldBeLong) {
if (debug) System.out.println("double: " + name + "=" + Double.parseDouble(value));
try {
number(name, Long.parseLong(value), value);
break outer;
} catch (NumberFormatException ignored) {
}
}
}
if (debug) System.out.println("string: " + name + "=" + value);
string(name, value);
}
if (stop) break _goto;
stringIsUnquoted = false;
s = p;
}
action startObject {
String name = names.size > 0 ? names.pop() : null;
if (debug) System.out.println("startObject: " + name);
startObject(name);
if (stop) break _goto;
fcall object;
}
action endObject {
if (debug) System.out.println("endObject");
pop();
if (stop) break _goto;
fret;
}
action startArray {
String name = names.size > 0 ? names.pop() : null;
if (debug) System.out.println("startArray: " + name);
startArray(name);
if (stop) break _goto;
fcall array;
}
action endArray {
if (debug) System.out.println("endArray");
pop();
if (stop) break _goto;
fret;
}
action comment {
int start = p - 1;
if (data[p++] == '/') {
while (p != eof && data[p] != '\n')
p++;
p--;
} else {
while (p + 1 < eof && data[p] != '*' || data[p + 1] != '/')
p++;
p++;
}
if (debug) System.out.println("comment " + new String(data, start, p - start));
}
action unquotedChars {
if (debug) System.out.println("unquotedChars");
s = p;
needsUnescape = false;
stringIsUnquoted = true;
if (stringIsName) {
outer:
while (true) {
switch (data[p]) {
case '\\':
needsUnescape = true;
break;
case '/':
if (p + 1 == eof) break;
char c = data[p + 1];
if (c == '/' || c == '*') break outer;
break;
case ':':
case '\r':
case '\n':
break outer;
}
if (debug) System.out.println("unquotedChar (name): '" + data[p] + "'");
p++;
if (p == eof) break;
}
} else {
outer:
while (true) {
switch (data[p]) {
case '\\':
needsUnescape = true;
break;
case '/':
if (p + 1 == eof) break;
char c = data[p + 1];
if (c == '/' || c == '*') break outer;
break;
case '}':
case ']':
case ',':
case '\r':
case '\n':
break outer;
}
if (debug) System.out.println("unquotedChar (value): '" + data[p] + "'");
p++;
if (p == eof) break;
}
}
p--;
while (Character.isSpace(data[p]))
p--;
}
action quotedChars {
if (debug) System.out.println("quotedChars");
s = ++p;
needsUnescape = false;
outer:
while (true) {
switch (data[p]) {
case '\\':
needsUnescape = true;
p++;
break;
case '"':
break outer;
}
if (debug) System.out.println("quotedChar: '" + data[p] + "'");
p++;
if (p == eof) break;
}
p--;
}
comment = ('//' | '/*') @comment;
ws = [\r\n\t ] | comment;
ws2 = [\t ] | comment;
comma = ',' | ([\r\n] ws* ','?);
quotedString = '"' @quotedChars %string '"';
nameString = quotedString | ^[":,}/\r\n\t ] >unquotedChars %string;
valueString = quotedString | ^[":,{[\]/\r\n\t ] >unquotedChars %string;
value = '{' @startObject | '[' @startArray | valueString;
nameValue = nameString >name ws* ':' ws* value;
object := ws* nameValue? ws2* <: (comma ws* nameValue ws2*)** :>> (','? ws* '}' @endObject);
array := ws* value? ws2* <: (comma ws* value ws2*)** :>> (','? ws* ']' @endArray);
main := ws* value ws*;
write init;
write exec;
}%%
} catch (RuntimeException ex) {
parseRuntimeEx = ex;
}
JsonValue root = this.root;
this.root = null;
current = null;
lastChild.clear();
if (!stop) {
if (p < pe) {
int lineNumber = 1;
for (int i = 0; i < p; i++)
if (data[i] == '\n') lineNumber++;
int start = Math.max(0, p - 32);
throw new SerializationException("Error parsing JSON on line " + lineNumber + " near: "
+ new String(data, start, p - start) + "*ERROR*" + new String(data, p, Math.min(64, pe - p)), parseRuntimeEx);
}
if (elements.size != 0) {
JsonValue element = elements.peek();
elements.clear();
if (element != null && element.isObject())
throw new SerializationException("Error parsing JSON, unmatched brace.");
else
throw new SerializationException("Error parsing JSON, unmatched bracket.");
}
if (parseRuntimeEx != null) throw new SerializationException("Error parsing JSON: " + new String(data), parseRuntimeEx);
}
return root;
}
%% write data;
private final Array<JsonValue> elements = new Array(8);
private final Array<JsonValue> lastChild = new Array(8);
private JsonValue root, current;
private boolean stop;
/** Causes parsing to stop after the current or next object, array, or value. */
public void stop () {
stop = true;
}
/** @param name May be null. */
private void addChild (@Null String name, JsonValue child) {
child.setName(name);
if (current == null) {
current = child;
root = child;
} else if (current.isArray() || current.isObject()) {
child.parent = current;
if (current.size == 0)
current.child = child;
else {
JsonValue last = lastChild.pop();
last.next = child;
child.prev = last;
}
lastChild.add(child);
current.size++;
} else
root = current;
}
/** @param name May be null. */
protected void startObject (@Null String name) {
JsonValue value = new JsonValue(ValueType.object);
if (current != null) addChild(name, value);
elements.add(value);
current = value;
}
/** @param name May be null. */
protected void startArray (@Null String name) {
JsonValue value = new JsonValue(ValueType.array);
if (current != null) addChild(name, value);
elements.add(value);
current = value;
}
protected void pop () {
root = elements.pop();
if (current.size > 0) lastChild.pop();
current = elements.size > 0 ? elements.peek() : null;
}
protected void string (String name, String value) {
addChild(name, new JsonValue(value));
}
protected void number (String name, double value, String stringValue) {
addChild(name, new JsonValue(value, stringValue));
}
protected void number (String name, long value, String stringValue) {
addChild(name, new JsonValue(value, stringValue));
}
protected void bool (String name, boolean value) {
addChild(name, new JsonValue(value));
}
private String unescape (String value) {
int length = value.length();
StringBuilder buffer = new StringBuilder(length + 16);
for (int i = 0; i < length;) {
char c = value.charAt(i++);
if (c != '\\') {
buffer.append(c);
continue;
}
if (i == length) break;
c = value.charAt(i++);
if (c == 'u') {
buffer.append(Character.toChars(Integer.parseInt(value.substring(i, i + 4), 16)));
i += 4;
continue;
}
switch (c) {
case '"':
case '\\':
case '/':
break;
case 'b':
c = '\b';
break;
case 'f':
c = '\f';
break;
case 'n':
c = '\n';
break;
case 'r':
c = '\r';
break;
case 't':
c = '\t';
break;
default:
throw new SerializationException("Illegal escaped character: \\" + c);
}
buffer.append(c);
}
return buffer.toString();
}
}
| // Do not edit this file! Generated by Ragel.
// Ragel.exe -J -o ../../../../../src/com/badlogic/gdx/utils/JsonReader.java JsonReader.rl
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Arrays;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.JsonValue.ValueType;
/** Lightweight JSON parser.<br>
* <br>
* The default behavior is to parse the JSON into a DOM containing {@link JsonValue} objects. Extend this class and override
* methods to perform event driven parsing. When this is done, the parse methods will return null.
* @author Nathan Sweet */
public class JsonReader implements BaseJsonReader {
public JsonValue parse (String json) {
char[] data = json.toCharArray();
return parse(data, 0, data.length);
}
public JsonValue parse (Reader reader) {
char[] data = new char[1024];
int offset = 0;
try {
while (true) {
int length = reader.read(data, offset, data.length - offset);
if (length == -1) break;
if (length == 0) {
char[] newData = new char[data.length * 2];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
} else
offset += length;
}
} catch (IOException ex) {
throw new SerializationException("Error reading input.", ex);
} finally {
StreamUtils.closeQuietly(reader);
}
return parse(data, 0, offset);
}
public JsonValue parse (InputStream input) {
Reader reader;
try {
reader = new InputStreamReader(input, "UTF-8");
} catch (Exception ex) {
throw new SerializationException("Error reading stream.", ex);
}
return parse(reader);
}
public JsonValue parse (FileHandle file) {
Reader reader;
try {
reader = file.reader("UTF-8");
} catch (Exception ex) {
throw new SerializationException("Error reading file: " + file, ex);
}
try {
return parse(reader);
} catch (Exception ex) {
throw new SerializationException("Error parsing file: " + file, ex);
}
}
public JsonValue parse (char[] data, int offset, int length) {
stop = false;
int cs, p = offset, pe = length, eof = pe, top = 0;
int[] stack = new int[4];
int s = 0;
Array<String> names = new Array(8);
boolean needsUnescape = false, stringIsName = false, stringIsUnquoted = false;
RuntimeException parseRuntimeEx = null;
boolean debug = false;
if (debug) System.out.println();
try {
%%{
machine json;
prepush {
if (top == stack.length) stack = Arrays.copyOf(stack, stack.length * 2);
}
action name {
stringIsName = true;
}
action string {
String value = new String(data, s, p - s);
if (needsUnescape) value = unescape(value);
outer:
if (stringIsName) {
stringIsName = false;
if (debug) System.out.println("name: " + value);
names.add(value);
} else {
String name = names.size > 0 ? names.pop() : null;
if (stringIsUnquoted) {
if (value.equals("true")) {
if (debug) System.out.println("boolean: " + name + "=true");
bool(name, true);
break outer;
} else if (value.equals("false")) {
if (debug) System.out.println("boolean: " + name + "=false");
bool(name, false);
break outer;
} else if (value.equals("null")) {
string(name, null);
break outer;
}
boolean couldBeDouble = false, couldBeLong = true;
outer2:
for (int i = s; i < p; i++) {
switch (data[i]) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
case '+':
break;
case '.':
case 'e':
case 'E':
couldBeDouble = true;
couldBeLong = false;
break;
default:
couldBeDouble = false;
couldBeLong = false;
break outer2;
}
}
if (couldBeDouble) {
try {
if (debug) System.out.println("double: " + name + "=" + Double.parseDouble(value));
number(name, Double.parseDouble(value), value);
break outer;
} catch (NumberFormatException ignored) {
}
} else if (couldBeLong) {
if (debug) System.out.println("double: " + name + "=" + Double.parseDouble(value));
try {
number(name, Long.parseLong(value), value);
break outer;
} catch (NumberFormatException ignored) {
}
}
}
if (debug) System.out.println("string: " + name + "=" + value);
string(name, value);
}
if (stop) break _goto;
stringIsUnquoted = false;
s = p;
}
action startObject {
String name = names.size > 0 ? names.pop() : null;
if (debug) System.out.println("startObject: " + name);
startObject(name);
if (stop) break _goto;
fcall object;
}
action endObject {
if (debug) System.out.println("endObject");
pop();
if (stop) break _goto;
fret;
}
action startArray {
String name = names.size > 0 ? names.pop() : null;
if (debug) System.out.println("startArray: " + name);
startArray(name);
if (stop) break _goto;
fcall array;
}
action endArray {
if (debug) System.out.println("endArray");
pop();
if (stop) break _goto;
fret;
}
action comment {
int start = p - 1;
if (data[p++] == '/') {
while (p != eof && data[p] != '\n')
p++;
p--;
} else {
while (p + 1 < eof && data[p] != '*' || data[p + 1] != '/')
p++;
p++;
}
if (debug) System.out.println("comment " + new String(data, start, p - start));
}
action unquotedChars {
if (debug) System.out.println("unquotedChars");
s = p;
needsUnescape = false;
stringIsUnquoted = true;
if (stringIsName) {
outer:
while (true) {
switch (data[p]) {
case '\\':
needsUnescape = true;
break;
case '/':
if (p + 1 == eof) break;
char c = data[p + 1];
if (c == '/' || c == '*') break outer;
break;
case ':':
case '\r':
case '\n':
break outer;
}
if (debug) System.out.println("unquotedChar (name): '" + data[p] + "'");
p++;
if (p == eof) break;
}
} else {
outer:
while (true) {
switch (data[p]) {
case '\\':
needsUnescape = true;
break;
case '/':
if (p + 1 == eof) break;
char c = data[p + 1];
if (c == '/' || c == '*') break outer;
break;
case '}':
case ']':
case ',':
case '\r':
case '\n':
break outer;
}
if (debug) System.out.println("unquotedChar (value): '" + data[p] + "'");
p++;
if (p == eof) break;
}
}
p--;
while (Character.isSpace(data[p]))
p--;
}
action quotedChars {
if (debug) System.out.println("quotedChars");
s = ++p;
needsUnescape = false;
outer:
while (true) {
switch (data[p]) {
case '\\':
needsUnescape = true;
p++;
break;
case '"':
break outer;
}
if (debug) System.out.println("quotedChar: '" + data[p] + "'");
p++;
if (p == eof) break;
}
p--;
}
comment = ('//' | '/*') @comment;
ws = [\r\n\t ] | comment;
ws2 = [\t ] | comment;
comma = ',' | ([\r\n] ws* ','?);
quotedString = '"' @quotedChars %string '"';
nameString = quotedString | ^[":,}/\r\n\t ] >unquotedChars %string;
valueString = quotedString | ^[":,{[\]/\r\n\t ] >unquotedChars %string;
value = '{' @startObject | '[' @startArray | valueString;
nameValue = nameString >name ws* ':' ws* value;
object := ws* nameValue? ws2* <: (comma ws* nameValue ws2*)** :>> (','? ws* '}' @endObject);
array := ws* value? ws2* <: (comma ws* value ws2*)** :>> (','? ws* ']' @endArray);
main := ws* value ws*;
write init;
write exec;
}%%
} catch (RuntimeException ex) {
parseRuntimeEx = ex;
}
JsonValue root = this.root;
this.root = null;
current = null;
lastChild.clear();
if (!stop) {
if (p < pe) {
int lineNumber = 1;
for (int i = 0; i < p; i++)
if (data[i] == '\n') lineNumber++;
int start = Math.max(0, p - 32);
throw new SerializationException("Error parsing JSON on line " + lineNumber + " near: "
+ new String(data, start, p - start) + "*ERROR*" + new String(data, p, Math.min(64, pe - p)), parseRuntimeEx);
}
if (elements.size != 0) {
JsonValue element = elements.peek();
elements.clear();
if (element != null && element.isObject())
throw new SerializationException("Error parsing JSON, unmatched brace.");
else
throw new SerializationException("Error parsing JSON, unmatched bracket.");
}
if (parseRuntimeEx != null) throw new SerializationException("Error parsing JSON: " + new String(data), parseRuntimeEx);
}
return root;
}
%% write data;
private final Array<JsonValue> elements = new Array(8);
private final Array<JsonValue> lastChild = new Array(8);
private JsonValue root, current;
private boolean stop;
/** Causes parsing to stop after the current or next object, array, or value. */
public void stop () {
stop = true;
}
/** @param name May be null. */
private void addChild (@Null String name, JsonValue child) {
child.setName(name);
if (current == null) {
current = child;
root = child;
} else if (current.isArray() || current.isObject()) {
child.parent = current;
if (current.size == 0)
current.child = child;
else {
JsonValue last = lastChild.pop();
last.next = child;
child.prev = last;
}
lastChild.add(child);
current.size++;
} else
root = current;
}
/** @param name May be null. */
protected void startObject (@Null String name) {
JsonValue value = new JsonValue(ValueType.object);
if (current != null) addChild(name, value);
elements.add(value);
current = value;
}
/** @param name May be null. */
protected void startArray (@Null String name) {
JsonValue value = new JsonValue(ValueType.array);
if (current != null) addChild(name, value);
elements.add(value);
current = value;
}
protected void pop () {
root = elements.pop();
if (current.size > 0) lastChild.pop();
current = elements.size > 0 ? elements.peek() : null;
}
protected void string (String name, String value) {
addChild(name, new JsonValue(value));
}
protected void number (String name, double value, String stringValue) {
addChild(name, new JsonValue(value, stringValue));
}
protected void number (String name, long value, String stringValue) {
addChild(name, new JsonValue(value, stringValue));
}
protected void bool (String name, boolean value) {
addChild(name, new JsonValue(value));
}
private String unescape (String value) {
int length = value.length();
StringBuilder buffer = new StringBuilder(length + 16);
for (int i = 0; i < length;) {
char c = value.charAt(i++);
if (c != '\\') {
buffer.append(c);
continue;
}
if (i == length) break;
c = value.charAt(i++);
if (c == 'u') {
buffer.append(Character.toChars(Integer.parseInt(value.substring(i, i + 4), 16)));
i += 4;
continue;
}
switch (c) {
case '"':
case '\\':
case '/':
break;
case 'b':
c = '\b';
break;
case 'f':
c = '\f';
break;
case 'n':
c = '\n';
break;
case 'r':
c = '\r';
break;
case 't':
c = '\t';
break;
default:
throw new SerializationException("Illegal escaped character: \\" + c);
}
buffer.append(c);
}
return buffer.toString();
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/org/jbox2d/particle/ParticleGroup.java |
package org.jbox2d.particle;
import org.jbox2d.common.Transform;
import org.jbox2d.common.Vec2;
public class ParticleGroup {
ParticleSystem m_system;
int m_firstIndex;
int m_lastIndex;
int m_groupFlags;
float m_strength;
ParticleGroup m_prev;
ParticleGroup m_next;
int m_timestamp;
float m_mass;
float m_inertia;
final Vec2 m_center = new Vec2();
final Vec2 m_linearVelocity = new Vec2();
float m_angularVelocity;
final Transform m_transform = new Transform();
boolean m_destroyAutomatically;
boolean m_toBeDestroyed;
boolean m_toBeSplit;
Object m_userData;
public ParticleGroup () {
// m_system = null;
m_firstIndex = 0;
m_lastIndex = 0;
m_groupFlags = 0;
m_strength = 1.0f;
m_timestamp = -1;
m_mass = 0;
m_inertia = 0;
m_angularVelocity = 0;
m_transform.setIdentity();
m_destroyAutomatically = true;
m_toBeDestroyed = false;
m_toBeSplit = false;
}
public ParticleGroup getNext () {
return m_next;
}
public int getParticleCount () {
return m_lastIndex - m_firstIndex;
}
public int getBufferIndex () {
return m_firstIndex;
}
public int getGroupFlags () {
return m_groupFlags;
}
public void setGroupFlags (int flags) {
m_groupFlags = flags;
}
public float getMass () {
updateStatistics();
return m_mass;
}
public float getInertia () {
updateStatistics();
return m_inertia;
}
public Vec2 getCenter () {
updateStatistics();
return m_center;
}
public Vec2 getLinearVelocity () {
updateStatistics();
return m_linearVelocity;
}
public float getAngularVelocity () {
updateStatistics();
return m_angularVelocity;
}
public Transform getTransform () {
return m_transform;
}
public Vec2 getPosition () {
return m_transform.p;
}
public float getAngle () {
return m_transform.q.getAngle();
}
public Object getUserData () {
return m_userData;
}
public void setUserData (Object data) {
m_userData = data;
}
public void updateStatistics () {
if (m_timestamp != m_system.m_timestamp) {
float m = m_system.getParticleMass();
m_mass = 0;
m_center.setZero();
m_linearVelocity.setZero();
for (int i = m_firstIndex; i < m_lastIndex; i++) {
m_mass += m;
Vec2 pos = m_system.m_positionBuffer.data[i];
m_center.x += m * pos.x;
m_center.y += m * pos.y;
Vec2 vel = m_system.m_velocityBuffer.data[i];
m_linearVelocity.x += m * vel.x;
m_linearVelocity.y += m * vel.y;
}
if (m_mass > 0) {
m_center.x *= 1 / m_mass;
m_center.y *= 1 / m_mass;
m_linearVelocity.x *= 1 / m_mass;
m_linearVelocity.y *= 1 / m_mass;
}
m_inertia = 0;
m_angularVelocity = 0;
for (int i = m_firstIndex; i < m_lastIndex; i++) {
Vec2 pos = m_system.m_positionBuffer.data[i];
Vec2 vel = m_system.m_velocityBuffer.data[i];
float px = pos.x - m_center.x;
float py = pos.y - m_center.y;
float vx = vel.x - m_linearVelocity.x;
float vy = vel.y - m_linearVelocity.y;
m_inertia += m * (px * px + py * py);
m_angularVelocity += m * (px * vy - py * vx);
}
if (m_inertia > 0) {
m_angularVelocity *= 1 / m_inertia;
}
m_timestamp = m_system.m_timestamp;
}
}
}
|
package org.jbox2d.particle;
import org.jbox2d.common.Transform;
import org.jbox2d.common.Vec2;
public class ParticleGroup {
ParticleSystem m_system;
int m_firstIndex;
int m_lastIndex;
int m_groupFlags;
float m_strength;
ParticleGroup m_prev;
ParticleGroup m_next;
int m_timestamp;
float m_mass;
float m_inertia;
final Vec2 m_center = new Vec2();
final Vec2 m_linearVelocity = new Vec2();
float m_angularVelocity;
final Transform m_transform = new Transform();
boolean m_destroyAutomatically;
boolean m_toBeDestroyed;
boolean m_toBeSplit;
Object m_userData;
public ParticleGroup () {
// m_system = null;
m_firstIndex = 0;
m_lastIndex = 0;
m_groupFlags = 0;
m_strength = 1.0f;
m_timestamp = -1;
m_mass = 0;
m_inertia = 0;
m_angularVelocity = 0;
m_transform.setIdentity();
m_destroyAutomatically = true;
m_toBeDestroyed = false;
m_toBeSplit = false;
}
public ParticleGroup getNext () {
return m_next;
}
public int getParticleCount () {
return m_lastIndex - m_firstIndex;
}
public int getBufferIndex () {
return m_firstIndex;
}
public int getGroupFlags () {
return m_groupFlags;
}
public void setGroupFlags (int flags) {
m_groupFlags = flags;
}
public float getMass () {
updateStatistics();
return m_mass;
}
public float getInertia () {
updateStatistics();
return m_inertia;
}
public Vec2 getCenter () {
updateStatistics();
return m_center;
}
public Vec2 getLinearVelocity () {
updateStatistics();
return m_linearVelocity;
}
public float getAngularVelocity () {
updateStatistics();
return m_angularVelocity;
}
public Transform getTransform () {
return m_transform;
}
public Vec2 getPosition () {
return m_transform.p;
}
public float getAngle () {
return m_transform.q.getAngle();
}
public Object getUserData () {
return m_userData;
}
public void setUserData (Object data) {
m_userData = data;
}
public void updateStatistics () {
if (m_timestamp != m_system.m_timestamp) {
float m = m_system.getParticleMass();
m_mass = 0;
m_center.setZero();
m_linearVelocity.setZero();
for (int i = m_firstIndex; i < m_lastIndex; i++) {
m_mass += m;
Vec2 pos = m_system.m_positionBuffer.data[i];
m_center.x += m * pos.x;
m_center.y += m * pos.y;
Vec2 vel = m_system.m_velocityBuffer.data[i];
m_linearVelocity.x += m * vel.x;
m_linearVelocity.y += m * vel.y;
}
if (m_mass > 0) {
m_center.x *= 1 / m_mass;
m_center.y *= 1 / m_mass;
m_linearVelocity.x *= 1 / m_mass;
m_linearVelocity.y *= 1 / m_mass;
}
m_inertia = 0;
m_angularVelocity = 0;
for (int i = m_firstIndex; i < m_lastIndex; i++) {
Vec2 pos = m_system.m_positionBuffer.data[i];
Vec2 vel = m_system.m_velocityBuffer.data[i];
float px = pos.x - m_center.x;
float py = pos.y - m_center.y;
float vx = vel.x - m_linearVelocity.x;
float vy = vel.y - m_linearVelocity.y;
m_inertia += m * (px * px + py * py);
m_angularVelocity += m * (px * vy - py * vx);
}
if (m_inertia > 0) {
m_angularVelocity *= 1 / m_inertia;
}
m_timestamp = m_system.m_timestamp;
}
}
}
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-bullet/jni/src/bullet/BulletCollision/Gimpact/btGenericPoolAllocator.h | /*! \file btGenericPoolAllocator.h
\author Francisco Leon Najera. email [email protected]
General purpose allocator class
*/
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_GENERIC_POOL_ALLOCATOR_H
#define BT_GENERIC_POOL_ALLOCATOR_H
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include "LinearMath/btAlignedAllocator.h"
#define BT_UINT_MAX UINT_MAX
#define BT_DEFAULT_MAX_POOLS 16
//! Generic Pool class
class btGenericMemoryPool
{
public:
unsigned char * m_pool; //[m_element_size*m_max_element_count];
size_t * m_free_nodes; //[m_max_element_count];//! free nodes
size_t * m_allocated_sizes;//[m_max_element_count];//! Number of elements allocated per node
size_t m_allocated_count;
size_t m_free_nodes_count;
protected:
size_t m_element_size;
size_t m_max_element_count;
size_t allocate_from_free_nodes(size_t num_elements);
size_t allocate_from_pool(size_t num_elements);
public:
void init_pool(size_t element_size, size_t element_count);
void end_pool();
btGenericMemoryPool(size_t element_size, size_t element_count)
{
init_pool(element_size, element_count);
}
~btGenericMemoryPool()
{
end_pool();
}
inline size_t get_pool_capacity()
{
return m_element_size*m_max_element_count;
}
inline size_t gem_element_size()
{
return m_element_size;
}
inline size_t get_max_element_count()
{
return m_max_element_count;
}
inline size_t get_allocated_count()
{
return m_allocated_count;
}
inline size_t get_free_positions_count()
{
return m_free_nodes_count;
}
inline void * get_element_data(size_t element_index)
{
return &m_pool[element_index*m_element_size];
}
//! Allocates memory in pool
/*!
\param size_bytes size in bytes of the buffer
*/
void * allocate(size_t size_bytes);
bool freeMemory(void * pointer);
};
//! Generic Allocator with pools
/*!
General purpose Allocator which can create Memory Pools dynamiacally as needed.
*/
class btGenericPoolAllocator
{
protected:
size_t m_pool_element_size;
size_t m_pool_element_count;
public:
btGenericMemoryPool * m_pools[BT_DEFAULT_MAX_POOLS];
size_t m_pool_count;
inline size_t get_pool_capacity()
{
return m_pool_element_size*m_pool_element_count;
}
protected:
// creates a pool
btGenericMemoryPool * push_new_pool();
void * failback_alloc(size_t size_bytes);
bool failback_free(void * pointer);
public:
btGenericPoolAllocator(size_t pool_element_size, size_t pool_element_count)
{
m_pool_count = 0;
m_pool_element_size = pool_element_size;
m_pool_element_count = pool_element_count;
}
virtual ~btGenericPoolAllocator();
//! Allocates memory in pool
/*!
\param size_bytes size in bytes of the buffer
*/
void * allocate(size_t size_bytes);
bool freeMemory(void * pointer);
};
void * btPoolAlloc(size_t size);
void * btPoolRealloc(void *ptr, size_t oldsize, size_t newsize);
void btPoolFree(void *ptr);
#endif
| /*! \file btGenericPoolAllocator.h
\author Francisco Leon Najera. email [email protected]
General purpose allocator class
*/
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_GENERIC_POOL_ALLOCATOR_H
#define BT_GENERIC_POOL_ALLOCATOR_H
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include "LinearMath/btAlignedAllocator.h"
#define BT_UINT_MAX UINT_MAX
#define BT_DEFAULT_MAX_POOLS 16
//! Generic Pool class
class btGenericMemoryPool
{
public:
unsigned char * m_pool; //[m_element_size*m_max_element_count];
size_t * m_free_nodes; //[m_max_element_count];//! free nodes
size_t * m_allocated_sizes;//[m_max_element_count];//! Number of elements allocated per node
size_t m_allocated_count;
size_t m_free_nodes_count;
protected:
size_t m_element_size;
size_t m_max_element_count;
size_t allocate_from_free_nodes(size_t num_elements);
size_t allocate_from_pool(size_t num_elements);
public:
void init_pool(size_t element_size, size_t element_count);
void end_pool();
btGenericMemoryPool(size_t element_size, size_t element_count)
{
init_pool(element_size, element_count);
}
~btGenericMemoryPool()
{
end_pool();
}
inline size_t get_pool_capacity()
{
return m_element_size*m_max_element_count;
}
inline size_t gem_element_size()
{
return m_element_size;
}
inline size_t get_max_element_count()
{
return m_max_element_count;
}
inline size_t get_allocated_count()
{
return m_allocated_count;
}
inline size_t get_free_positions_count()
{
return m_free_nodes_count;
}
inline void * get_element_data(size_t element_index)
{
return &m_pool[element_index*m_element_size];
}
//! Allocates memory in pool
/*!
\param size_bytes size in bytes of the buffer
*/
void * allocate(size_t size_bytes);
bool freeMemory(void * pointer);
};
//! Generic Allocator with pools
/*!
General purpose Allocator which can create Memory Pools dynamiacally as needed.
*/
class btGenericPoolAllocator
{
protected:
size_t m_pool_element_size;
size_t m_pool_element_count;
public:
btGenericMemoryPool * m_pools[BT_DEFAULT_MAX_POOLS];
size_t m_pool_count;
inline size_t get_pool_capacity()
{
return m_pool_element_size*m_pool_element_count;
}
protected:
// creates a pool
btGenericMemoryPool * push_new_pool();
void * failback_alloc(size_t size_bytes);
bool failback_free(void * pointer);
public:
btGenericPoolAllocator(size_t pool_element_size, size_t pool_element_count)
{
m_pool_count = 0;
m_pool_element_size = pool_element_size;
m_pool_element_count = pool_element_count;
}
virtual ~btGenericPoolAllocator();
//! Allocates memory in pool
/*!
\param size_bytes size in bytes of the buffer
*/
void * allocate(size_t size_bytes);
bool freeMemory(void * pointer);
};
void * btPoolAlloc(size_t size);
void * btPoolRealloc(void *ptr, size_t oldsize, size_t newsize);
void btPoolFree(void *ptr);
#endif
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./extensions/gdx-lwjgl3-angle/build.gradle | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
apply plugin: "java"
dependencies {
api project(":gdx")
api libraries.lwjgl3GLES
}
sourceSets.main.java.srcDirs = ["src"]
sourceSets.main.resources.srcDirs = ["res"]
tasks.withType(Jar) { duplicatesStrategy = DuplicatesStrategy.INCLUDE }
| /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
apply plugin: "java"
dependencies {
api project(":gdx")
api libraries.lwjgl3GLES
}
sourceSets.main.java.srcDirs = ["src"]
sourceSets.main.resources.srcDirs = ["res"]
tasks.withType(Jar) { duplicatesStrategy = DuplicatesStrategy.INCLUDE }
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./CLA.txt | Individual Contributor License Agreement ("Agreement") V2.0
http://www.apache.org/licenses/
Thank you for your interest in libGDX. In order to clarify the intellectual
property license granted with Contributions from any person or entity, Mario
Zechner and Nathan Sweet ("Project Owners") must have a Contributor License Agreement ("CLA")
on file that has been signed by each Contributor, indicating agreement to the
license terms below. This license is for your protection as a Contributor as
well as the protection of the Project Owners and the project's users; it does
not change your rights to use your own Contributions for any other purpose.
If you have not already done so, please complete and sign, then scan and
email a pdf file of this Agreement to [email protected]. If
necessary, send an original signed Agreement to
Mario Zechner, Steyrergasse 23. 8010 Graz, Styria, Austria.
Please read this document carefully before signing and keep a copy for your records.
Full name: ______________________________________________________
Mailing Address: ________________________________________________
_________________________________________________________________
Country: ______________________________________________________
Telephone: ______________________________________________________
Facsimile: ______________________________________________________
E-Mail: ______________________________________________________
You accept and agree to the following terms and conditions for Your
present and future Contributions submitted to the Project Owners. In
return, the Project Owners shall not use Your Contributions in a way that
is contrary to the public benefit or inconsistent with its nonprofit
status and bylaws in effect at the time of the Contribution. Except
for the license granted herein to the Project Owners and recipients of
software distributed by the Project Owners, You reserve all right, title,
and interest in and to Your Contributions.
1. Definitions.
"You" (or "Your") shall mean the copyright owner or legal entity
authorized by the copyright owner that is making this Agreement
with the Project Owners. For legal entities, the entity making a
Contribution and all other entities that control, are controlled
by, or are under common control with that entity are considered to
be a single Contributor. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"Contribution" shall mean any original work of authorship,
including any modifications or additions to an existing work, that
is intentionally submitted by You to the Project Owners for inclusion
in, or documentation of, any of the products owned or managed by
the Project Owners (the "Work"). For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written
communication sent to the Project Owners or its representatives,
including but not limited to communication on electronic mailing
lists, source code control systems, and issue tracking systems that
are managed by, or on behalf of, the Project Owners for the purpose of
discussing and improving the Work, but excluding communication that
is conspicuously marked or otherwise designated in writing by You
as "Not a Contribution."
2. Grant of Copyright License. Subject to the terms and conditions of
this Agreement, You hereby grant to the Project Owners and to
recipients of software distributed by the Project Owners a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare derivative works of,
publicly display, publicly perform, sublicense, and distribute Your
Contributions and such derivative works.
3. Grant of Patent License. Subject to the terms and conditions of
this Agreement, You hereby grant to the Project Owners and to
recipients of software distributed by the Project Owners a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the
Work, where such license applies only to those patent claims
licensable by You that are necessarily infringed by Your
Contribution(s) alone or by combination of Your Contribution(s)
with the Work to which such Contribution(s) was submitted. If any
entity institutes patent litigation against You or any other entity
(including a cross-claim or counterclaim in a lawsuit) alleging
that your Contribution, or the Work to which you have contributed,
constitutes direct or contributory patent infringement, then any
patent licenses granted to that entity under this Agreement for
that Contribution or Work shall terminate as of the date such
litigation is filed.
4. You represent that you are legally entitled to grant the above
license. If your employer(s) has rights to intellectual property
that you create that includes your Contributions, you represent
that you have received permission to make Contributions on behalf
of that employer, that your employer has waived such rights for
your Contributions to the Project Owners's project, or that your employer
has executed a separate Corporate CLA with the Project Owners.
5. You represent that each of Your Contributions is Your original
creation (see section 7 for submissions on behalf of others). You
represent that Your Contribution submissions include complete
details of any third-party license or other restriction (including,
but not limited to, related patents and trademarks) of which you
are personally aware and which are associated with any part of Your
Contributions.
6. You are not expected to provide support for Your Contributions,
except to the extent You desire to provide support. You may provide
support for free, for a fee, or not at all. Unless required by
applicable law or agreed to in writing, You provide Your
Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied, including, without
limitation, any warranties or conditions of TITLE, NON-
INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
7. Should You wish to submit work that is not Your original creation,
You may submit it to the Project Owners separately from any
Contribution, identifying the complete details of its source and of
any license or other restriction (including, but not limited to,
related patents, trademarks, and license agreements) of which you
are personally aware, and conspicuously marking the work as
"Submitted on behalf of a third-party: [named here]".
8. You agree to notify the Project Owners of any facts or circumstances of
which you become aware that would make these representations
inaccurate in any respect.
Please sign: __________________________________ Date: ________________
| Individual Contributor License Agreement ("Agreement") V2.0
http://www.apache.org/licenses/
Thank you for your interest in libGDX. In order to clarify the intellectual
property license granted with Contributions from any person or entity, Mario
Zechner and Nathan Sweet ("Project Owners") must have a Contributor License Agreement ("CLA")
on file that has been signed by each Contributor, indicating agreement to the
license terms below. This license is for your protection as a Contributor as
well as the protection of the Project Owners and the project's users; it does
not change your rights to use your own Contributions for any other purpose.
If you have not already done so, please complete and sign, then scan and
email a pdf file of this Agreement to [email protected]. If
necessary, send an original signed Agreement to
Mario Zechner, Steyrergasse 23. 8010 Graz, Styria, Austria.
Please read this document carefully before signing and keep a copy for your records.
Full name: ______________________________________________________
Mailing Address: ________________________________________________
_________________________________________________________________
Country: ______________________________________________________
Telephone: ______________________________________________________
Facsimile: ______________________________________________________
E-Mail: ______________________________________________________
You accept and agree to the following terms and conditions for Your
present and future Contributions submitted to the Project Owners. In
return, the Project Owners shall not use Your Contributions in a way that
is contrary to the public benefit or inconsistent with its nonprofit
status and bylaws in effect at the time of the Contribution. Except
for the license granted herein to the Project Owners and recipients of
software distributed by the Project Owners, You reserve all right, title,
and interest in and to Your Contributions.
1. Definitions.
"You" (or "Your") shall mean the copyright owner or legal entity
authorized by the copyright owner that is making this Agreement
with the Project Owners. For legal entities, the entity making a
Contribution and all other entities that control, are controlled
by, or are under common control with that entity are considered to
be a single Contributor. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"Contribution" shall mean any original work of authorship,
including any modifications or additions to an existing work, that
is intentionally submitted by You to the Project Owners for inclusion
in, or documentation of, any of the products owned or managed by
the Project Owners (the "Work"). For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written
communication sent to the Project Owners or its representatives,
including but not limited to communication on electronic mailing
lists, source code control systems, and issue tracking systems that
are managed by, or on behalf of, the Project Owners for the purpose of
discussing and improving the Work, but excluding communication that
is conspicuously marked or otherwise designated in writing by You
as "Not a Contribution."
2. Grant of Copyright License. Subject to the terms and conditions of
this Agreement, You hereby grant to the Project Owners and to
recipients of software distributed by the Project Owners a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare derivative works of,
publicly display, publicly perform, sublicense, and distribute Your
Contributions and such derivative works.
3. Grant of Patent License. Subject to the terms and conditions of
this Agreement, You hereby grant to the Project Owners and to
recipients of software distributed by the Project Owners a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the
Work, where such license applies only to those patent claims
licensable by You that are necessarily infringed by Your
Contribution(s) alone or by combination of Your Contribution(s)
with the Work to which such Contribution(s) was submitted. If any
entity institutes patent litigation against You or any other entity
(including a cross-claim or counterclaim in a lawsuit) alleging
that your Contribution, or the Work to which you have contributed,
constitutes direct or contributory patent infringement, then any
patent licenses granted to that entity under this Agreement for
that Contribution or Work shall terminate as of the date such
litigation is filed.
4. You represent that you are legally entitled to grant the above
license. If your employer(s) has rights to intellectual property
that you create that includes your Contributions, you represent
that you have received permission to make Contributions on behalf
of that employer, that your employer has waived such rights for
your Contributions to the Project Owners's project, or that your employer
has executed a separate Corporate CLA with the Project Owners.
5. You represent that each of Your Contributions is Your original
creation (see section 7 for submissions on behalf of others). You
represent that Your Contribution submissions include complete
details of any third-party license or other restriction (including,
but not limited to, related patents and trademarks) of which you
are personally aware and which are associated with any part of Your
Contributions.
6. You are not expected to provide support for Your Contributions,
except to the extent You desire to provide support. You may provide
support for free, for a fee, or not at all. Unless required by
applicable law or agreed to in writing, You provide Your
Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied, including, without
limitation, any warranties or conditions of TITLE, NON-
INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
7. Should You wish to submit work that is not Your original creation,
You may submit it to the Project Owners separately from any
Contribution, identifying the complete details of its source and of
any license or other restriction (including, but not limited to,
related patents, trademarks, and license agreements) of which you
are personally aware, and conspicuously marking the work as
"Submitted on behalf of a third-party: [named here]".
8. You agree to notify the Project Owners of any facts or circumstances of
which you become aware that would make these representations
inaccurate in any respect.
Please sign: __________________________________ Date: ________________
| -1 |
libgdx/libgdx | 7,213 | Fix some casts in ParticleEditor and Flame. | This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | tommyettinger | 2023-08-19T06:24:28Z | 2023-09-20T21:42:35Z | bb799a9cd0a92cadb0425acd6064654cd7a4d6c8 | 42f48cda37a20bb26d7610222a714a74738dc613 | Fix some casts in ParticleEditor and Flame.. This is just a small fix for what seems to be a crash in ParticleEditor; it looks like it affects Flame as well. The issue stems from:
- We have a `NumericValue` that stores a `float`.
- We get that float and assign it to a `JSpinner` with a `SpinnerNumberModel`.
- Inside the `JSpinner`, it is promoted and assigned to either a `double` or a `Double`, I'm not sure which.
- We later get a value from the `JSpinner`, which gets returned as a boxed `Double`.
- We try to cast this to `Float` so it can be auto-unboxed.
- This causes a crash! `Double` cannot be cast to `Float`, even though their primitive forms can.
In this PR, we cast to `Number` instead of `Float`, and call `.floatValue()` on it. This is a pattern already used heavily in Hiero.
There are no other changes in this PR. Happy reviewing! | ./tests/gdx-tests-android/assets/data/g3d/materials/badlogic_normal.png | PNG
IHDR ?1 pHYs cHRM z% u0 ` : o_F IDATxڔɓeIv ӝlt3=<3 JH4@)RȒZ֪j-vzۋ^H%R!@D16;_N/{ E<35}W?zO?[R!]S`aQK#F|K%QQ9]:n b%AY|f#^)VsԖ6 ]S`nZ>s1/bMɎcɱ&2h@:'}l8JCU @~GT
+i4@:X)%0@Q4I85Z%9@A8c1gP+mGRmQKm
)9P}#jx]c7bLmzUrRnQp(5vK#(+$˵ ŢTh֍bHKGEt8h"Q*V1ԎK5fӂ5olXia픏c7ϙ;
6F)\?k-mn6O8 !?@(,~1f0GEYٲOi~hH cW. "ee˲8n ~歹L8O=ku7t{8H,y]uɝPި{@;J/koVrx{.{JŪ^V,M¡ۏ{TZUVEˍxڈUT7Gfyd^~"lhYʛbwُV-8I8t|oJ9XAe:oůWcJ9VE+ﭒ{bI9
OOcۧshwԢiά8 Zɘc(UqKo+1b-x]|N&7vq/B\N
Q3T~8˴ʓE}@{q5q{R"m~tх;k8t8)_肥Z8K-|'nŭʿs%jU_.X:߯$x3յV߹T/Y:{%n7q
\)VcH5l}t|nIPb,'堦KWƫt9ة-`&Th_lѴUݸ2~ihJg;c$-Ǣ}N٢chna|0/Nټp'utE8].6Ոkmd7'}E[~ݴKFm5̦lpdVtMkGjl9if?3{YL66ܺus_i=ts݂Ve_ozsgϚ'g;is'|yr1\^mP;v6|8݊ZMxBVo`qorNwjG
i$:xn졗djCc]^i>~^ݽBbӖ
3nKcS^i>}Vݻx]UlK}^ݻBbƂgk1{(]\Vs>y49FvYquҰ"s¼tg{~P=7>zѯsf4sbN]|AԾ鳾ɤb$R-|r/v\q}?(T<w"sW;wKʧjT9"faغojz +왘.;Sg:wQ~wnn܃ޖM|_ӄqa9^Aâtgjwo={z-2*(,νoNlY}!TzNtqݣwlYu>HϸvG[#}VݽBb^=o0<u)T;ǩSdةͨ{J)}z깢tgbN=|}o2ag;*-Yjwp:+/v
Fa
7<xxDsu_\HF/%T\E:Ɓ|>#%.7wǏ+E?h]vg<
#&n17de<`ĒѴ]0YAw>>=`â~13G(>3esGw嗟az2,Vŧ:2|=64K?'
YshrQb%h) y>~?t[.֓8w8Ɇ{;l>ѝ;,߬{Eeg,X4m3[O;gݢbmqמF/,NӟwogQzG>#7SGB|7~.6͝
ܻ~_l;Ohes8
;8s,d=6aQ}R[s17`'(w,x%G_Ҩ2q}tw?\6,eVjewV2 xT/a<nBBbP]ewxIwE/s?a9DO[hx#zQyW>.hy'h?y%~wWtp#V-wf9'z|}_ؕU~wg
⎛ړfp{MY;OϏVo,o/žWON}<ا;g2}[<((LP䇸ߎO߳ͮ0(:/u5} dt=^tj-P?2(@jQկ;tg̯{^ "S4->MߏnM??ZͿvug7d'&sw܃E7f,w4nnF^QwE7
2ʟmP-es1ZEGk#^.?ڠHV 膪N/eDE\`F M,l"[R,̗2oB:_ǃw#S|~dw Xtg163twZUB= %C{~w̄VsBt!Zv\ *1{~TtbtjB9 Z7%#:33[Gv/i.5]/$E>?j-fnW+&>>?
myǷ&c1*[=/yq:e4CP'^qBeˎOo~Jhypt-5Qs-n3dSm<&=?6
mG7ge1x]=Oʤ,B'c/kՆg^DsxVz'nNJ[=Ȋ#jfb{[b0Ҷt=S5{SX4aUrޜsݝQ:t
R֓@2E'/NMh
'ms{;R.4R7+Fg&hқ-V\TM=Th/褝l^M_i+q]k\.@0^x^(
8ef/n~Ji-q$F即ai1c/5uxռZ p()Uo'~AR\z*J%o~A2vf-Y
LBS(nx
D0uJEHAÁ)@y.+zp3}ފz yW~
j VybŊEa
uZ/K531Ʒ>fGpI2Hb:u5dy%Cn)f/&ܦ~~eFs ]
%!uE*;C|/͍ܿ4M %ws[ .˂h=w])8vB~+ytMQ5Q70rN3rq1)(łSGҊ_7
_Q*CzPbܿ)RPQ^2SL8!9k`gu<,(3i8"LC"xM 8@O<L~q֚uG1l9dr}xcIfޝsW8ASi|~u48z3yJ|5w{x{|3[j-y*OiSoώwN?wO͍OUTGEcmc G_p&`Kc(fx!J"!!0pk@WՍ4oFNϞ̒u(V7$qOqg1 R[eLyhDq(}ܗNs
5{><mz.1ى=[9ࣲU>fQE= /. ueEۧ6_LTz/ >h~y zK?{
>~L$=VU.V_~AOxnAZ-_
?TvZSŲG3Y3kvĜ$r,i3Web𬝵}avnڏO=m?
'GD98HlgCd u;$?NR`=߇O?xt'N|8=t0:{t/^{ݾ.lJk%{Ӆ. 칃$-䝤Gpr`\OiYI ]cP$@ X@ X "g ,;g)9yKo&=^f|?2syDŽn?jE#HA$OMv-ZW%`8#@@ej P6Ar/t7w[;k{?4'W8;Ց˳YguϿXRV)#R !Xg! ( 4NеAW;!d+y2^~kUQZ*zKSy7j~>߃O=xv<cmO-mnu'?'=<O_7Iq+g\N렻TX=:lL9?2v[Bx`?;:~λ}wρ=m|;L+k36˓ h?/+k2Wj}&xvQbB|ְV˟Tq+;/ޟ_Z4.EK\/MNxЮ%
(To8Mgp.ӊyKψ!kk_x{Ր.,.5JUPTJ*wٷ_3}Fodwv?j wϟ6mޓJ|߬U~Ynәfc+mǪwOw=bigMc/w9ݖ/[!/?/ ,jpE*Ne
Y[ͤa}^{!AŦfsd
N+\FWf1JEM+F?UwiKn>ϟ"wt?wÕ%JoA1A'NM
~zHnXZh> *gt#Gney?۞tb#z7p,*{1,?Vup(%jW "PKo 2ЁW5/{e;߿ =e0ZZ~ti pbq=(PMovbvV;Ij8-*Ӡ9}8\xHҟ-b%߮Fzj6߷q ث26
+-+j̯;AZUC+ZҾ]`,A5Z^e7l! jeޠ&TQl{A[̫̂}Ylw:C#wJ3WYt赼2R>,0/vTGUF,3r_M0oX]r 0zB9d,d
/b6!ڦfY]q ;0_\\數/#$0Y2SAO[̶#Śkjp(Ir+0
b8rqEd/K^Y<iY)Jl$]4fY +[N#jfR1ŃQ]X \I{
ŀIFP5:{%0,gA c[}8 "0XŜfj楟ݓƳmQg7:"N&VE|
EÚ~Xs鈁e&ڀ|zCvt`Ѱ⒰lH;LnjjaK
68լU_Zq6"z%&"Mkfg.,|T+;c`WPiظl[C X: zb`F $ Xڂ8B I.GzJh$ˀH @8
&`A8iӝ}%c-JD&8($3U۔uAN霳)9ufzN`r3
I tи wݘݦ8eūf",75p34R<`7܌fot퇗;ͫa
q`<\yz&_.)!ItF~ a^qJE^AvU7 pNFyHQ`Q@p8d! ( @8P8$@p`y bI6aC`@Hu
Ad$5'lFict`5F@Fg0O9Ђv8x vSlCd@[b10p ڂk1vv*8 !`@NrHg7q AG(f-1zkjB @j/f*H)qwmX r`@@ I_%
YôFYU㛓rh8̕lASը uk݀ l/_~n~@p$N{?@gVn%a)9o"~((Z;i]`@k8b @D͠G 8C8^8@B8 Z"DDo3 Vl
0K# $"@9rr g 0UGP塨}hZZ/hZ8)Ɔ*sYm̴,%YbZSRl1sLk맦e)2ؔjAO1@eRIѯ zM%G¸.[Lm9\xUzw
AѤ|fUh̓;D+##uEJ/'ռc7\VCzs5I(9B` (dnC 80!-(Uis&S-:mbi<>1!6
-`=oC3MkdBeM`@]XfBkNt%Eg;u[e9/W\A qelfZ"'3Ҧi#/˝$jʒ-L)b z2VXה:\ضq@X1JY44%ô*5{CԘE#@zi9Tϴ4۔ʖc%gmY'hfg.9_8Rge
7;O]/)mNk)gge?;8\t%.rhl֪{%=KITVctKH*^tE3e
QZi
?%/fqRzQ}x!ILN^2m[LAJw27bwM,`
JCE4#ZyYKη$E=k{zhQ2I#GufU[?ɨ:gEAB5
cnEy8̵5㹬|Q3*lh w&?b=!|ع>FGG
Vf,1A41IUy
3E&j,/jhf7a`ټ8χw`JWi*'Vmv#8ţ6Ûˮejcjo]w1dIO7(Wo[.~.8"2ȅ[RƆfJe\#/ P
`Yj79sn8NiVXr-5̹X.U}HE AuaׯjٮȻrҩ*Ѱ.FR7z o6p9 0"fYjp
qBMf-Uۘ$:RTwW{81Q DAZ# fn-4°vF
^?+N 8tcIWf`DWE(2eec4R^^ݠi!wnN !Iy2YV(x+t9쉀a
8SYtЙuVQE]%U;FB3_T{7ϖ!,ϋy96%o~6^^bEDUK*g?:j4%oA[!sl9i
%fv5jU5ȋ&/^nc9snǣtvZ\ڢ}XVyƍh*8NfS56ۖ",<[<H.Ӯ"Ψ2N[AÏçwLv9l?2lE9zp\(ݔ<o7˿=?g E[MڿqMv,T$/=jK Bb$3'7?wޝMJw'MԘnQ\i$-*ca !p0ըgXT+mBP{pI,44鲨Br%eb:WTyZ6XtkQ\54u|#)5/~˻/ӥg,M]FgXclSP61*.0ő^φu^s?E6p&cL+T'#~C$«©<Ϙ4lNO{O/o+=\ݐrHUbrxzIR_z-dP{HW뿈R7mڢn]Wwl]o?>%vX z'f1yHeNnv7O\$?{œentuy#Fw~\R?:v]]ܺ<*QЁO;K;=j|Yo'IO_@x)K7;ˀ54ך"j8m#x7o:͓^Qa3"+1(GZD0vra[SIk c\<.Kq(?mȰ%T\ŋIP.5.J0?x-~@ax`ZBVRU][neK{7۵#ҫDǪ֜ԧpϕ
5_iک0̳4Vq0-.xX[Mo1;
a yQ[OR}=9/?E8ait>ʭ7~sy<zuk#ݵ:g? FT0jKޫH܃/2NbœgYێ&x&3)HjvO'wMkwa&[.f$|qĴj}$2z}O3
_c5zRQXH#C/IJ
An E@1= rE??ܮ7U9
&e 膧)-GtAp#B.
]vz
痪%=k<cY<+V ./RZ<8%dcǺ!qi9Kݪ>_QT
}l @ t=,Ɍ+Q8Ob"0Jm_a>ejc)v0uqDdCs^h]A!-?V[ճJI -x6xqDgl^\_o<O;E"{ՠ8l!"bq F֮Z(nbCNGd1-~pd+^l u
:2|^ rh^,Q 80aEaygQr͠RrG)Cc!KXZXP @Jk?[&b%J
)Ix/wbWa
z6i-̗Oӆ*
H0)!+$zޭ}#N|W
gh5x+Yh9- XBзcM2|-լYXY#F!
A(j YszAՂljX,Ԕ2*8 $ u^+nʩn A)^,='2bq,
;ထ@ ^[Ѻd6~k" "Y%hu=>n'8orߏ/eWkf'ӝvL/'t-UZ+:nے[ԬA|ʧ8Zu?\;]0qpXcՔk Lq?Qb
L35
ih4u PH IdW2ѕT;maz\QqEµ MeQ~Ni%zQ
+{͢?Z2]\;Ωy*L
[H,yUyK<IͥoQ"یO B@=tͿxRW'w
/ډݠl1p_?1Yp@$+T6zE)qy:T&iDtYse-bFQ,WH]NZw;ҟ]ͦ t<͔/JW^7~5oNd~0YhE_wag᧳f9'wVZq@?:;䎥.ݾ;G?QmVܽulrx֥&t6+R7wo}Ovh'jeoo==_+wΛӏ珟
zh7BS۸2o!'0&YLhNV:FCSM YUYݖ+|c~p>y~h]ZAjV=9S&Vͪ}2A
1곒YzZğK*Y?Oq~8MR5ëVuX0ňr
o_df<NzAd浜ޙlEqA\zY̌lm&OIP["M!r-rxU dt"G3UW;߿7C/-8"qHfedAGM\þ;G?imVܹ1w1>\[m~͢^sx:w`Ϗ"~~'9lewf^FW~7o
duv+MxiOD<
/nJTeE_F<
nJޖn O&=5@3~Q42o`o__Sg;{\=ʬ^ESr\R`ψD'Ŝ8r`WF
e5ՆqH?hED$ŪB?_rY'`:X'p'\(u$3xizҜu3bi#^5؍y$ FI^-f+;:uYKq-! }MW5>6hGV([U"~ʐAq= fedJ؎R*U~.`x݃ꆗvO9۴-'D;0:/n^yj%[#w"[]%nǀ[u^[]FA/sTUzy5]U2qh_jՙhǦ&E>HKy5͒by^UCjOt⛺Ey)Z'ڵZn]r\TQwhu RtyϖhwVNp=eh2<]1j3k![
lB8r #}}'8`Vq
fa;]EjㅁW @Re?WWv{(;RJ ^X3&Me^d")w^+UNTAp*nj74dַL9\`N_`~.<ydXgyjqi) AYP%/2cSaڨ*9!cQ,ScKfE{Z̖(nʝ4\1~k?Ukm}M|R<ݺukۑ).TAc$e0@;^$fE a },0g+kS?[@?nERE ;a Wފ? ;~y$,K"eG,r%xك[&
^$deSMνrȌ9֭#Boq&} Jt3!c1ueR둋LEg=zeH6-!U5$btRVB_("JFf\*z?ńo$Υݔ?&Dx^f2.xCqm Br}샃|/yK7Ռ4noYp(kN#Ҁ;:zsECm9Y&8q`u(sE"S|a4h>ּXC_E_z0/T5u@,r:jIbbzCqb;~2,W1(LJ|#GY0{;szX,AZhA<FCX R 0p'D ݊Xx}xA : ,\OjP9lXbc]{[6G/r5_ <R"(d
8یhl _ 玉 !#%g 6CdΗ&U`kCE;8zvTtLFaG9WEM.e.z7fv^`Q%oDof@tQ8˝n|GOb+|VtGN?7UE E#Q|P *>*89@
C2gqP4aD`uA9l |)\0, dB:>bc+Ď @1clfhW|N$ 6ɞ1s:@'PX'3 N^&g22t@6B uA_;CFX'Ml]^D
U&DH#?˛W
*.4HQ LLwvQvۂ;Q `3%/(7kudRa/Ռea!eӈVV~k:8ZiPDF{H_f;yמCJBy(W`>_ҋ+7j֫$[7qX^eH8BBd-Zl"ɓ]ۆ!o2::pt* &nI7~CD[{"pm><.: A'1TTV`:@%PTZYMiP:
c,]]`Cl,J;ցC`dNfh,Usu DH C@rTM S%2m
嫏"^kTBkII^3mdqS2Gc!HF>3wV@<\roÍ;m2j?+y!kc1lA/Ͼ}l0|:I1o(1(oPePrIt.'4jޱ7"pY :
Ph,Meimf@-+[Yʐ
PspՅak#(m<q]ðѮ*Lt_+&
qKׯ9,y!:Z!![]`KH-7B<zWh%4kU/C}ԋX䥛.5P7k팳|Qi2ye">OC@U;2H;氺_↥N(aoo;JI""M#sOm5^k'
5
ɂSB`ҋZe>XK'̊di)4}B8Ü_eQQ|m&tJg3g1kD*l2|)sϟ!x AqlE<*Y*^uӯ]aHr;L_\Wg5k붏 8C@
q f>^,L¡ۍ{LEmDZ鮍ԋ5q8\C++q-]ro
ݍ6w=g>lιy89Ĕƽ'ΦswrzhnI߹R|?l~ߤ^IZgK~] ?[Q||A#ɑo`u"VC4 ߆r1lq9 qzHpg@U-ϯD8`|>թƯ"ʫdPqI xIDFhY
a(1
#1=/e^ \0.יыX`= F".Vi~hZ#jyG5 xHs+:^_["r^-:%ؽ#&|40k,&}Nr!z+W_2zh-::qoo1hw*,~vp^JK
&>\cJw3Ëa]pG98Θm4Mty\~qϹm4bRE
Y`ae~zʝ64Uvw'?@\>6
o:ڴ3MJ4eWc.Ew٦C"p qciW^yl$`9'q,[,z`i̒X("ƁicVjjPqGpi:psmN۞{tڑ5WCr0ieu-Uy>Wx`,ea&XqB7a_`YzOZ:3ϚoݓާgNM\a?yzw35,+
;_<LZ9Nհ|QV31aԽӾ΄`^Q^5x?}7нԻs+
v2sP i>_ƹۘRƔ{
إtn8"\@Uh
@{?>״Ty:2X@Uh
}:w'>
Tp;G=`=KqkeÈV ۀ6M:
Lv,5WUt88ڳr/myG)/+{0[^wBK,z<$Hq@-Ӻj}f&<ٯ+BA) ߄
EUA\ī\SƢsH|km@H|]5 'X3P" +ǔ3i` 0F MϮ,;1ռ_2-o+ȷ.w~MF5[ۗoTŰ|C<x^4~t}z%K',˂zV'Q%HIML<Qs?: a
@]nGkZWhڇŠzEKx--+qȐjVZv
z187lx
]b+L7Dyp+A"39O/?W\"YZXVy?9
+]ht@J Z<z*Gd=c-Ի27`pL17̎A!pCp*Y+L4Mŭfd^-qmTl3Z'd$|"K-}9*R
c9HX.]#EmUa@6z"U.s8w;!yKBG̃*x)k[̗FyGÈވqULU>G#h#oq;iv:FAG $]z ]rt_&VKDPV`~TtbtfB9 @Χw/a {Mvʉfls%\dkMC"tdM-*nɼ{bqPEe(=\MqܝXA/t~1Uu9 8`}D_$,F$P]6tpz-?0팠I`: IIJY?ԾGE%Ds 1qWYYFz}&+o<\uĔg{YZ D6kmA~B/
ľ0ވI_5]`TdG/n~Jil8Bq`J}Ņ)ס)Ukk Tww;G8n7p5Zuݥ5{˸W)CEy%Bjp^۞kVf$+eM6&vf96D_.:BK\;*kdU4̞rƫyZ*'eK H4- ?J4_A[׳iiRrVg\9 -2o\U K)/eRsik 5:, 2;/0aX*UZ~Y !q )M.cJVGe4(U][x[Q
} i;!gbR݊OɫnZ
]_
'V7-8ֵkp\7eܧ3_),i3Po? pyk }>l--E3HW'wφ>2deD
ҵݟעg1.UXW>6?":ЖАhDHBeqI;G.Lz-S #
d5n՞q SwܫWՄ2sWYDBbHc8.gȓgJiOQչK8|rp3|80NRRa"~^Z7s~hß8=_ՠ43O=jYid]=x9>
K:;3ƭȯ@؞`ѽ.y9yx4kCb|39.fp{xh䤛l%VHǭt?5tŚ<$TuL)hg{BM;[7Hk ;L-kYRuqgn^T[ot\$f
D)u@^)!2䞔[qpG`:KRj*Hݴ=qY#02_ 7K%0l
4(N]Œy:g"t"㙐k`EAM:e(YW&?ЙQFY&iZd4Ero1I7;DL p@$Dzq\8\(*d\Γ'i!̴H~4W[/@WNԍttZs-j`vޞa;{6ۋƷ~+u^x}[5Qp
\~vtۓ%L|gUwZ^}s7O 5kA~^KF>ǭHtkWhUQXn>hUZ
YR%o xB 1J
{c7B!ȁ =>p鐽ͶK`0^*X 0$ \HGM@uC7VaSD_Paa3V=KyõƂuH&ȐqJ( yM_ˤ[um4+Y=%ۀ-4`y8LrWqDF#H=DLiƓ~̋i
K+CQ?jaV;]gkJȯ7Ƀ`hSĬP/9Oy:qU`%1Pw.HVKޭ%Jo^1P.O}?|{K:7;'NN*^* @;
tBu,E4KL.`)/ḥ ԱAK5[Z5nvSm gMT:03{ _Y]ͽ~@Ho9okSK,3YW~``\P}[J@=z4_6h"'t|6,&oˆh-ɭsR8"\HyehUq4O-3%ϥӔh|U+qi UN1Md<eξ@_VK0HH"Q[tNoE@
:YdW"sC1bg7ܯ."D6
aK"6ݚO!"Ч}Z+q渖Wyt쵽2R>w%gFK.-5wӁZT^q-ǝŮ
.u5yGcҢt
j'BZXPVfDnȎn
k*ie.Zlr$z]qa&Z*˲+)Y҈}#CoT8wzCOV"d!~d;Z6s Z6ݏ'IzOb%(s9'Á@Z=*3fP1ڑϛ1$g[ZD*1%D+
JkDXq.5Qi V2gUJy!B&7"T?窮67zz "Hi]Dw7Bq"ȬCk 3a;OG (u~ˋBtt7-iyzjaQVo˨ʧ$ٺp"M
W\ТgBcظbnyrӶ[,M*f枧.V\Dؐ:v
c%-w]Es_qq[ AC*AE $Bp@F` MKP8P K@$6yykq TY<Iqr ѮVɆIp:@"_Hz9Z0bD6s߯"rhhCsҾUƕHD16=YT,չ\5@z}O
@{ՈMFuUpbEUE}N(1 Pm۩Uݫ2ϧa#SYM4RԵշ)ٍiLV @kT7VkWV
Ĭ^KC#UzOۗ:-^uAźmoqI҉lF
a8xA<=j<cU#JGȁ֠`,x#)AP402
9 D2 EmX$@ !F]CBG A660j3h+`8$oTaG P\ZpݼyLB9$3iiu?ҫ <"0!r@dsA^zjQKzZ\-L{ L^
+ly6
(8R5Ufܯ/r._peK/nϋ%c3|xQ\ݜ̂Ų_45) S CefƘZiE'Y//U!!l`,g{fn_jUY `
12I_^PR12*ܙcz~ԗq y3F6[a?
縻xÛg7,͖;
̡@F5MyIf:i:0!n_cz5O:y |! K`_i` eOSě~4 {2yzQ.F^#DS<ĢٖE;~FUj1\I8JGQGڌ(B%v! uТYjR%U=AD\2VN Q6&w /[/~+æ5t+gliƦƯpy=)`,N
N\(B/eKwY]#@^vܪG?鋢;]jm-A'LVĹT~-Uɢ3USoyg2GgZ?ZNlq8Q$ms+gi9^^Mڸq&#CzI!=IXXb'Ya-w㴭KdrW|JiP/Nٍ8؝)jk2qQ+!=NkuyaŰr]Aׯb5x^:oy=talH^jvE3.7pܞj/,ڲ(?Kh/`ʿZerH- uo8l^LN{|@-dpVf7E1~q߈y57*7e|Q8bwyMh0X_*vNXf猙n+`RI8 E7hIIi)("^jNVx7K,fzXc~+@9\>;w$鬲ΗQc˚EB@l*Bm˦~ځ$K|0 EKSdEaz\TՊb%TGHsÀa0 19W0k@1ujoXirO4ynHR4^c^3[gq|` Ai&{gA}Ӱ<8I5a`[H^8A(7Onlzzhb
E\xA+F\9yW.E{
Ŋq
\O-]9E P51 d-+Z$NJ\B>B)DpClQC\[Q=a=p
4c:MLzQ'eBc%u'z;?+3CH #ۨ۴\./"~iٕ3$ǂH\JDmR9t-Q_$!aZ3zɊJs4~fU-zAlh$pIl$[eC r_ A ەnWB#`p JHD6VN.5Kt.n00[ɦiW[a- 챏7=]8i FhE
yjΚEʗulW.:H[u],n'lPG.1~U3nȃPb5e?ǍgS"_}wG߿8PryK_
)W7O] ԍx
@}[0-}{{?o}r?zow\̳I#98E۠8jFf}ozw"}wh CP%.֬W
_gN-7>>M 5mz9@
'A+,dŁ .adiFr~, S>[H9\/ŗw X'א7K6L$8 {ծ]IB=q/np%H A-]r,ONq6g}iX/=yvxm.DܺVh{;ۿ+x0(^lH>{ZJ~F?fU|ǃO~w{s?Woq˿n<u?xo^1MY_z% Uߕh|RyQ۷2Ӿe>>NQFO=mݵE
ɰ'.AcMmK5Ek2 /d$uQv2<??
3ծo;haK)4"!}$h+`SrsCk4j}0jK8ۤzFxy,uсDž,)Cę{G66\"
F#Z~qK4@ al($AvORc?UgЛ9v킘9DzcNv3_/Rݾwߕpm$~yqoOe6v{kF?*<\p-_qp\b4Y1KLLӛճ`@O ,?^_7G8_x4>Zcdc;i#/˸֯ZX,4;z:3s3U#j3.bAM̿E<n~;}u@[-d6|ikyJ)1<OC4^} w[@dpnI˖ӗLv:9`?x+>Ep¯YAgWlMPRBf Oçs=vbGi0\FzqtvBAX0s9mdnzY5{>X_Lc9`:4҃kFA>yT؟E2G 5@ Tc
Ӵi(p@囜WbdaMK/i|
8"\hQ>[%2 /<ʞ-Uv/ţ|74__a.3A_8ŢUa@UM'u5az!/?Ͳy'==
LlSv~+EZ؆/bHkY`4N&,J4kJ^/I.lwk7V]>7
/v#?]N̎E/jZEd^P[R&Idgv6vKkq@:vw
(v}d^t#EyvW{~DWL5v
@k Զ^w#6#XN^ա>v/,W_hΝ݃[/*fSXh4<]rDVĿx{ !K&86w[&g6:%Dqgy<|ʹR>"c=Dںܚ/~;; tgSrQl&R\ c[WK7Dk113A!89y}u3^tYѸmՖ hX.}egBcCZ:|s;Qԥ[X{#=Σt|s'U{p}-0_ɉ}B. Hwrmػl/t_Aͪ-yK}
?0|vevnӏSiM,FN{w ڿw+o?~_>/?^on?.uYoT˳I؝N}c^A^rujh.t("y.[Σs+B<H@#BZQYaץtn:: Ė1؋xQqɁ+bkpSK^}ÕrF
kfMkA2x^2~uDpMyGV+d'4de q2ul*Ynїq*j4 ~_Q3qkPK5Kr~g<엣bewu%{ ߸Nk1һڸ^ۅϠ˙,u0~K}=9u8n]M`q?߅ߠ̫2i:`lw^~ U@&7Կ~cV
;Q}'QjTiwy!yyUNL`op7H W~9/ñ@ _qh)q3Lpp asPeкM_SxKyP
9G R50tPm}c"Ctuobl`Qx"j-|VK"ոg&\bd ~:e=-[ZM'-3n;L p 싑\-'Fx35Pԁ-=lgK=߄>'.wk'Bk$Ұeo#b_ ǽ< 7Oۭ(/(̪Si{zi:>씉W ̗\M h%wVzv=q_2>jWmrLz0}w6!`Uڳl2NTmil]>Z274{ r$D& C-9!!ڷDP@!z){v m+ N5D^sd!s|&}.dGlp>0J520(JZţqzy@PЅnaF4dVe|aU;}&yML6B0
Pxq#{^fuxRa寃R.zG;V_V|ku;=0#ڰab5jGk$ݯK8nb
ǝḅ1t t0F [0T^%k *{$}tZ F^[qfs=P)~ijUvdH桭=_ɲbBd_ӆ_2WMI$2 : 6Z !
ln
k.3n^ݴV6
ꢿxNtrZ?!SJk>lK sS?+=͔ʚʃˮYͪ7K 0lqI#h5A}[GlaPWq/z\E0U6떄j/
Zt_C2aeU\R57EYDO#FֈԚ>)<
9@P 8bHd pR
M־'!Kv~ҘUkgNa`]עe-nn~rpjM ǫ-pj5:!z@_y-Ơ+lݹ1fܡE[eXOeU1`9M.gم,3D^@V+Rn*%uoh<Cʖڒؓ)Y9S:+QKf2_{*,\Ac 8B
zC!x0G@ @b` 5)s`Oc0u8ih֝ls+@隱ח[[+1^,!/`;`a^|1kɩI͎(Q6fq0.|.Yn2ka//#Nzn oRuophpXqVHZ{|u %fUvq\82AwywJ?@xw\&U;'-$Av/oz*OQ'.wr*NmΩ"*40{rS-n
N^{a%t[n:mݸFĒCfÖl 4YK7Qvds1t"jNn\[Xrm#:"FlUiWwDrz
5K_cZW&n{^+%ܝMҮ8Od&+R=l|m[66d_ɮd_ohz ? xZۿ/eplխFYw5Veή3a!4Ƭ)cwQo+>VjxYew9{ki$\=ot/.GgTݱ7s8pLNB)bX iH6tMa5g.K ̀
gO'}'v{om1$$@iIL1e86f*ӳ?BhD! h4vuwUݺ[f"2߾CDͼ[=͌_w?"AŰ(+DBvj`ދ5/t]GD8.1ܸ^>x榪aa{(W@@akL(չ,:FKnXNBf47o98<u"x-T6wP۹)e57gnҫ&i:S/QMyrֺyJlZ5k \thsga7PXL|#0 +/`k%5fF`Vu+HE6嗔e-wONg3-jiՔѵMo0NUBϙ!Q#hSLS*% 54EO*@|
Egm.ly_}@t\5FŜtE@fL=NĴgڊi,n/^9A^I(o9!5Wv:űPM^X9w)1F8OvSQwaǫWi%n^~%\M22
T=f0dcnD.g6V9m Cj+%zӢ?lt=A{~=sn-UrIא½sn,]86g*3kh~pGJha>z~Qk:y%4x4dT̨>=)|[,2(6OO/ݽ<vZ_};.ANxֲ~+/xwn\m|^|֭M}/T>\ty{;7εtmz59iu)Ĝ35|Y^WnrzKNCZU0RU\U E6qi?<OBKChy8Dp'f;ޝ_
eRѨJnغdב,܌RiC\#Y^no~-\[s4viLyˢ|)/k?\IG_>9ZB!*s]p>Ɏ&O,Wd,qg6n>CY2'n1_^_p|xY9$,M!% `POr\~c Mix=~C^ѫZ;-tv&/oOSD.4"Bir.,,vL b-la. u{_ovh*7Q?+rſsǿqu_>X&O0=^u4Yx#>j؉L}oae'#6[Ac R QUi~wX[=@^+UEKI'<Sw&X35`87{
guLyS~{>7nFvKdM@_yrp#,V~5+xkxЈB^-.L"Kq#WZvaBMV X]BPeYw1;xԫ7y1U 7 P
||-a_|,;# ]['ѓ{þY>~o
r"zbRؖ]hn"Q5!KCQVS;70
y#4+R
S!r,;;(D46߈g5ob"zUasU.|np
e:צ`c{q7XnNqAxBw'ڎg-$:5UM7xO0N|
'IqYWddMb|yF~n Z2m`3HyL(pE ~>?u |51(tXtgaqw)e%yl<iTyTq
3by^F僱
WvobJ.֚$mv)ch
0LXa]U/fQ|Ϫu4YWBKHgBy&/vVp0O<*Q/i1څSl/vړslMLmIQf(,
M8[B#߾m4;䨞D쪛X`=}n1n[f1w5T]d"`χ a>[l㺞۱]/[m
\Ф*<gwwYٌ4I~\w
qW&E,,FTH&f1F\_Umׄfk|]GDZKLAc3W[2Mzpm)U?_{lNI6
?ȌvY"q_
,WTZ]AH]̷۫ic'Pez|x-wkDC kܗzU̍zi~ajnؿKoyޭ{;,
ϷN4TDNnt6]ڇPx,'>,NŤEET\V *8k"}"ΓZK
XpPeIdjhy$l
4CR=_?ޟn>)
31_}p4%T6GNwdڬjv~#t>Cˠe5/%^Yņ4;ӱw~)&s;_dCػ7ۨâ=&?L<hwx)
~R%ϊy.!hά}Д<OlO2/VoV2g_>e!Ye w;k:x%[RS&L+4me9OL]~Tgݚ6acbF\ӷ=}1,R}YKVHoD2ZbÙZz {g
x{__bJ15zqCWfByQ^]9@;GWȣyG%yڃZmjᩕk,p-`Çvl^tꏇc;M6'ѽ)JZ;ӽzyn{yekk'k\@okw߸[C -h7)x}2E sr0?{Vd#.kY=Fo8M۞;ղlV(wm/GF֯NzƢxAvU(Jب(@ (/)ˌތd6xNd{ሉϑל|wC(.P_/oFhDygfu,S^1)atޙK\0"8p]S7k2"}~&wΦopL*q]uNft"y0-4GfN;wYZW]i'(vnsJo{UxJh;Zk'*3X
~r>9y Qjn
7~.$3MEQqC ObDFv/[,z2ꇳHB"fvdZq*-@I;wJh4l+Z@bcd3k{oL_D-MDVY:4 T9s$I]KK)
CHb-K#9 "\R)
m(ԒG]ICQdѬ>-~wt\{3j_\[?v&[ wߒ"mv3*[ӭzJh436
^[F1-eAJ[0䭹gz< ml|{|RRlZC7jxh{!"%9t|+._,7tjTD28z(Qt)_,@WlZ0R1"Ρ
,:U4!p,Xc90"Z2 PRP7gnIU۾܆6g1><EYjͶ;;m7 ܍bUp&9Ovvb$Q7}Y
No,i_
N4]S04/fldk%4w|fMs*Sl3JM̈́fZugs!;lvt|X0$H2.Ic"5VHU#݀=_( g 1\ H܄ȣKcܴBp`+3`(p us֬(1KbU+%$ v7P3},s::dH;{֛M[7m+wKQ9v=dC%gl|ZN}|S;\o9j?v'wɄqo|gp*\U0㳧Α@~z%\Ef5Һ&UP)KݔY֎vգoZ}ʆaÞ=[d#EnpP@+F(`
kyf:ZBp٪hbeD@"Z HDx;Z#{2{&m#z
Y[:T+pm+u1rr)S99疱iܷ>;fe/)!Ej̾sg'HQg:['Cs2q[;C)K`}]ֶb
BvO
Nԟe4ώ 09Ɲ;;ͥ^
zFi5&,QRzN;9&I.[Haj/bҔF&YY6ײ\HQ\"%lodki#8-'dey\:|cҺLk\߫t:?BJ/,Es6l\\y,SiuvzNNËbMbaJgy2[,zdR\K0 ,ٝV;J\YXBz3j]jȺM
Y"Se2Q$'HWJndv*찎<-- R!ZUڈx%Q"湴m;lONfE1'?}TLyۍZ~~R]/<[Ks6̗8L)٭DϷ
wapP73ݤ#"H*3vp<v^&)
f~2]Љ.D·Ŭ8>x!~<I[IQ1:F\ڭ UE<.0PPށ({s D^嵜%LQx7;XB!\}i!`D`5
e&aˬ7LZ<ج\J,_NGnꢓcªGF#ubZ#]Xi=s.͞/p<|cǟjt{<E D@yl:yXKpjAw{~ϾQ]o6HPw)
RYM ˛ Q]H6iqTx^>CY9B7Ud$ZMJiM]W_=ArrEW0_N'?ִ8HG|:gMՅ>Zo[_0YGAbVB+خWԛ- j5/S*[|-2
+6ԑxr`ET&rtn{Q@`E(JC썌';Gͬl
2fuw| lͶ?"Ȭ|d"rU<,͝;VSXwb1@c<9
.R[}&k:|qTpȰh9U.ƭR]r9ÿܞ{߷@ҵ*Gc0'k$%I/z~?j]qY_|~7jIN2.iٷ~oy\{4G6~=_?? 7m0ׇ@Q0J*+ubiJ̲5Մ/blj:;8{4H+Z?煗 %rG[ͧEfBeϏ(qK pKk[腥vfӭFU+<{GG_pj|o~-,],K;`mR@X!M
(ꛎ2@/'~eRNYR)pf/T%I}^Ho߲WaYO_pV#˃&royl#V`6|˻[Mb{4Ykl& |