-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathSplitDemo.java
733 lines (645 loc) · 26.2 KB
/
SplitDemo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
/*
Copyright (c) 2020-2022, Stephen Gold
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 jme3utilities.minie.test;
import com.jme3.app.Application;
import com.jme3.app.StatsAppState;
import com.jme3.app.state.AppState;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.PhysicsSpace;
import com.jme3.bullet.SoftPhysicsAppState;
import com.jme3.bullet.collision.PhysicsCollisionObject;
import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.bullet.collision.shapes.CompoundCollisionShape;
import com.jme3.bullet.collision.shapes.HullCollisionShape;
import com.jme3.bullet.collision.shapes.infos.ChildCollisionShape;
import com.jme3.bullet.debug.BulletDebugAppState;
import com.jme3.bullet.debug.DebugInitListener;
import com.jme3.bullet.objects.PhysicsBody;
import com.jme3.bullet.objects.PhysicsRigidBody;
import com.jme3.bullet.util.DebugShapeFactory;
import com.jme3.font.Rectangle;
import com.jme3.input.CameraInput;
import com.jme3.input.KeyInput;
import com.jme3.light.AmbientLight;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.material.RenderState;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Plane;
import com.jme3.math.Quaternion;
import com.jme3.math.Transform;
import com.jme3.math.Triangle;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Limits;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Line;
import com.jme3.system.AppSettings;
import com.jme3.util.BufferUtils;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import jme3utilities.Heart;
import jme3utilities.MeshNormals;
import jme3utilities.MyAsset;
import jme3utilities.MyCamera;
import jme3utilities.MyString;
import jme3utilities.math.MyMath;
import jme3utilities.math.MyVector3f;
import jme3utilities.math.noise.Generator;
import jme3utilities.minie.test.common.PhysicsDemo;
import jme3utilities.minie.test.shape.ShapeGenerator;
import jme3utilities.ui.CameraOrbitAppState;
import jme3utilities.ui.InputMode;
import jme3utilities.ui.Signals;
/**
* Test/demonstrate splitting of rigid bodies.
* <p>
* Collision objects are rendered entirely by debug visualization.
*
* @author Stephen Gold [email protected]
*/
public class SplitDemo
extends PhysicsDemo
implements DebugInitListener {
// *************************************************************************
// constants and loggers
/**
* message logger for this class
*/
final public static Logger logger
= Logger.getLogger(SplitDemo.class.getName());
/**
* application name (for the title bar of the app's window)
*/
final private static String applicationName
= SplitDemo.class.getSimpleName();
// *************************************************************************
// fields
/**
* AppState to manage the PhysicsSpace
*/
private BulletAppState bulletAppState;
/**
* angle between the normal of the splitting plane and default camera's "up"
* vector (in radians, ≥0, <Pi)
*/
private float splitAngle = 0f;
/**
* visualize the splitting plane
*/
private Geometry splitterGeometry;
/**
* AppState to manage the status overlay
*/
private SplitDemoStatus status;
/**
* first screen location used to define the splitting plane (measured from
* the lower left corner)
*/
final private Vector2f screen1 = new Vector2f();
/**
* 2nd screen location used to define the splitting plane (measured from the
* lower left corner)
*/
final private Vector2f screen2 = new Vector2f();
/**
* first world location used to define the splitting plane
*/
final private Vector3f world1 = new Vector3f();
/**
* 2nd world location used to define the splitting plane
*/
final private Vector3f world2 = new Vector3f();
// *************************************************************************
// new methods exposed
/**
* Count how many rigid bodies are active.
*/
int countActive() {
int result = 0;
Collection<PhysicsRigidBody> rigidBodies
= getPhysicsSpace().getRigidBodyList();
for (PhysicsRigidBody rigidBody : rigidBodies) {
if (rigidBody.isActive()) {
++result;
}
}
return result;
}
/**
* Main entry point for the SplitDemo application.
*
* @param arguments array of command-line arguments (not null)
*/
public static void main(String[] arguments) {
String title = applicationName + " " + MyString.join(arguments);
// Mute the chatty loggers in certain packages.
Heart.setLoggingLevels(Level.WARNING);
// Enable direct-memory tracking.
BufferUtils.setTrackDirectMemoryEnabled(true);
boolean loadDefaults = true;
AppSettings settings = new AppSettings(loadDefaults);
settings.setAudioRenderer(null);
settings.setResizable(true);
settings.setSamples(4); // anti-aliasing
settings.setTitle(title); // Customize the window's title bar.
Application application = new SplitDemo();
application.setSettings(settings);
application.start();
}
/**
* Restart the current scenario.
*/
void restartScenario() {
PhysicsSpace physicsSpace = getPhysicsSpace();
physicsSpace.destroy();
assert physicsSpace.isEmpty();
setUpShape();
}
/**
* Update the debug materials of all collision objects.
*/
void setDebugMaterialsAll() {
PhysicsSpace physicsSpace = getPhysicsSpace();
for (PhysicsCollisionObject pco : physicsSpace.getPcoList()) {
setDebugMaterial(pco);
}
}
/**
* Return the inclination angle of the splitting plane.
*
* @return the angle between the plane normal and the default camera's "up"
* vector (in radians, ≥0, <Pi)
*/
float splitAngle() {
assert splitAngle >= 0f : splitAngle;
assert splitAngle < FastMath.PI : splitAngle;
return splitAngle;
}
// *************************************************************************
// PhysicsDemo methods
/**
* Initialize this application.
*/
@Override
public void acorusInit() {
this.status = new SplitDemoStatus();
boolean success = stateManager.attach(status);
assert success;
super.acorusInit();
configureCamera();
configureDumper();
generateMaterials();
configurePhysics();
generateShapes();
// Hide the render-statistics overlay.
stateManager.getState(StatsAppState.class).toggleStats();
ColorRGBA skyColor = new ColorRGBA(0.1f, 0.2f, 0.4f, 1f);
viewPort.setBackgroundColor(skyColor);
Integer maxDegree = renderer.getLimits().get(Limits.TextureAnisotropy);
int degree = (maxDegree == null) ? 1 : Math.min(8, maxDegree);
renderer.setDefaultAnisotropicFilter(degree);
Line lineMesh = new Line(Vector3f.ZERO, Vector3f.ZERO);
this.splitterGeometry = new Geometry("plane", lineMesh);
Material splitter = MyAsset.createWireframeMaterial(
assetManager, ColorRGBA.White);
splitterGeometry.setMaterial(splitter);
rootNode.attachChild(splitterGeometry);
restartScenario();
}
/**
* Calculate screen bounds for the detailed help node.
*
* @param viewPortWidth (in pixels, >0)
* @param viewPortHeight (in pixels, >0)
* @return a new instance
*/
@Override
public Rectangle detailedHelpBounds(int viewPortWidth, int viewPortHeight) {
// Position help nodes below the status.
float margin = 10f; // in pixels
float leftX = margin;
float topY = viewPortHeight - 70f - margin;
float width = viewPortWidth - leftX - margin;
float height = topY - margin;
Rectangle result = new Rectangle(leftX, topY, width, height);
return result;
}
/**
* Initialize the library of named materials during startup.
*/
@Override
public void generateMaterials() {
super.generateMaterials();
ColorRGBA red = new ColorRGBA(0.5f, 0f, 0f, 1f);
Material missile = MyAsset.createShinyMaterial(assetManager, red);
missile.setFloat("Shininess", 15f);
registerMaterial("missile", missile); // TODO used?
ColorRGBA color = new ColorRGBA(0.2f, 0f, 0f, 1f);
Material solid = MyAsset.createShinyMaterial(assetManager, color);
solid.setFloat("Shininess", 15f);
RenderState additional = solid.getAdditionalRenderState();
additional.setFaceCullMode(RenderState.FaceCullMode.Off);
registerMaterial("solid", solid);
}
/**
* Access the active BulletAppState.
*
* @return the pre-existing instance (not null)
*/
@Override
protected BulletAppState getBulletAppState() {
assert bulletAppState != null;
return bulletAppState;
}
/**
* Determine the length of physics-debug arrows (when they're visible).
*
* @return the desired length (in physics-space units, ≥0)
*/
@Override
protected float maxArrowLength() {
return 2f;
}
/**
* Add application-specific hotkey bindings (and override existing ones, if
* necessary).
*/
@Override
public void moreDefaultBindings() {
InputMode dim = getDefaultInputMode();
dim.bind(asCollectGarbage, KeyInput.KEY_G);
dim.bind(asDumpSpace, KeyInput.KEY_O);
dim.bind(asDumpViewport, KeyInput.KEY_P);
dim.bind("next field", KeyInput.KEY_NUMPAD2);
dim.bind("next value", KeyInput.KEY_EQUALS, KeyInput.KEY_NUMPAD6);
dim.bind("previous field", KeyInput.KEY_NUMPAD8);
dim.bind("previous value", KeyInput.KEY_MINUS, KeyInput.KEY_NUMPAD4);
dim.bind("restart", KeyInput.KEY_NUMPAD5);
dim.bindSignal(CameraInput.FLYCAM_LOWER, KeyInput.KEY_DOWN);
dim.bindSignal(CameraInput.FLYCAM_RISE, KeyInput.KEY_UP);
dim.bindSignal("orbitLeft", KeyInput.KEY_LEFT);
dim.bindSignal("orbitRight", KeyInput.KEY_RIGHT);
dim.bindSignal("rotatePlaneCcw", KeyInput.KEY_LBRACKET);
dim.bindSignal("rotatePlaneCw", KeyInput.KEY_RBRACKET);
dim.bind("split", KeyInput.KEY_RETURN, KeyInput.KEY_INSERT,
KeyInput.KEY_NUMPAD0);
dim.bind(asToggleAabbs, KeyInput.KEY_APOSTROPHE);
dim.bind(asToggleCcdSpheres, KeyInput.KEY_L);
dim.bind("toggle childColor", KeyInput.KEY_COMMA);
dim.bind(asToggleHelp, KeyInput.KEY_H);
dim.bind(asTogglePause, KeyInput.KEY_PAUSE, KeyInput.KEY_PERIOD);
dim.bind(asTogglePcoAxes, KeyInput.KEY_SEMICOLON);
dim.bind("toggle wireframe", KeyInput.KEY_SLASH);
}
/**
* Process an action that wasn't handled by the active InputMode.
*
* @param actionString textual description of the action (not null)
* @param ongoing true if the action is ongoing, otherwise false
* @param tpf time interval between frames (in seconds, ≥0)
*/
@Override
public void onAction(String actionString, boolean ongoing, float tpf) {
if (ongoing) {
switch (actionString) {
case "next field":
status.advanceSelectedField(+1);
return;
case "next value":
status.advanceValue(+1);
return;
case "previous field":
status.advanceSelectedField(-1);
return;
case "previous value":
status.advanceValue(-1);
return;
case "restart":
restartScenario();
return;
case "split":
splitAll(); // TODO do this on the physics thread
return;
case "toggle childColor":
status.toggleChildColor();
setDebugMaterialsAll();
return;
case "toggle wireframe":
status.toggleWireframe();
setDebugMaterialsAll();
return;
default:
}
}
// The action is not handled: forward it to the superclass.
super.onAction(actionString, ongoing, tpf);
}
/**
* Update the GUI layout and proposed settings after a resize.
*
* @param newWidth the new width of the framebuffer (in pixels, >0)
* @param newHeight the new height of the framebuffer (in pixels, >0)
*/
@Override
public void onViewPortResize(int newWidth, int newHeight) {
status.resize(newWidth, newHeight);
super.onViewPortResize(newWidth, newHeight);
}
/**
* Callback invoked after adding a collision object to the PhysicsSpace.
*
* @param pco the object that was added (not null)
*/
@Override
public void postAdd(PhysicsCollisionObject pco) {
pco.setDebugMeshResolution(DebugShapeFactory.highResolution);
setDebugMaterial(pco);
}
/**
* Callback invoked once per frame.
*
* @param tpf the time interval between frames (in seconds, ≥0)
*/
@Override
public void simpleUpdate(float tpf) {
super.simpleUpdate(tpf);
Signals signals = getSignals();
if (signals.test("rotatePlaneCcw")) {
this.splitAngle += tpf;
}
if (signals.test("rotatePlaneCw")) {
this.splitAngle -= tpf;
}
this.splitAngle = MyMath.modulo(splitAngle, FastMath.PI);
float w = cam.getWidth();
float h = cam.getHeight();
if (Math.abs(splitAngle - FastMath.HALF_PI) < FastMath.QUARTER_PI) {
// The plane is more vertical than horizontal.
float cotangent = FastMath.tan(FastMath.HALF_PI - splitAngle);
screen1.x = 0.5f * (w + h * cotangent);
screen1.y = h;
screen2.x = 0.5f * (w - h * cotangent);
screen2.y = 0f;
} else { // The plane is more horizontal than vertical.
float tangent = FastMath.tan(splitAngle);
screen1.x = w;
screen1.y = 0.5f * (h + w * tangent);
screen2.x = 0f;
screen2.y = 0.5f * (h - w * tangent);
}
cam.getWorldCoordinates(screen1, 0.1f, world1);
cam.getWorldCoordinates(screen2, 0.1f, world2);
Line planeMesh = (Line) splitterGeometry.getMesh();
planeMesh.updatePoints(world1, world2);
splitterGeometry.setMesh(planeMesh); // to update the geometry's bounds
}
// *************************************************************************
// DebugInitListener methods
/**
* Callback from BulletDebugAppState, invoked just before the debug scene is
* added to the debug viewports.
*
* @param physicsDebugRootNode the root node of the debug scene (not null)
*/
@Override
public void bulletDebugInit(Node physicsDebugRootNode) {
addLighting(physicsDebugRootNode);
}
// *************************************************************************
// private methods
/**
* Add lighting to the specified scene.
*/
private void addLighting(Spatial rootSpatial) {
ColorRGBA ambientColor = new ColorRGBA(0.1f, 0.1f, 0.1f, 1f);
AmbientLight ambient = new AmbientLight(ambientColor);
rootSpatial.addLight(ambient);
ambient.setName("ambient");
ColorRGBA directColor = new ColorRGBA(0.7f, 0.7f, 0.7f, 1f);
Vector3f direction = new Vector3f(1f, -3f, -1f).normalizeLocal();
DirectionalLight sun = new DirectionalLight(direction, directColor);
rootSpatial.addLight(sun);
sun.setName("sun");
}
/**
* Create a rigid body with the specified shape and debug normals and add it
* to the PhysicsSpace at the origin, with random rotation.
*
* @param shape the collision shape to use (not null)
* @param debugMeshNormals how to generate normals for debug visualization
* (not null)
*/
private void addRigidBody(
CollisionShape shape, MeshNormals debugMeshNormals) {
PhysicsRigidBody body = new PhysicsRigidBody(shape);
body.setDebugMeshNormals(debugMeshNormals);
Generator random = getGenerator();
Quaternion rotation = random.nextQuaternion(); // TODO garbage
body.setPhysicsRotation(rotation);
addCollisionObject(body);
}
/**
* Configure the camera during startup.
*/
private void configureCamera() {
float near = 0.1f;
float far = 500f;
MyCamera.setNearFar(cam, near, far);
flyCam.setDragToRotate(true);
flyCam.setMoveSpeed(10f);
flyCam.setZoomSpeed(10f);
cam.setLocation(new Vector3f(0f, 1.5f, 6.8f));
cam.setRotation(new Quaternion(-0.002f, 0.991408f, -0.1295f, 0.0184f));
AppState orbitState
= new CameraOrbitAppState(cam, "orbitLeft", "orbitRight");
stateManager.attach(orbitState);
}
/**
* Configure physics during startup.
*/
private void configurePhysics() {
PhysicsBody.setDeactivationEnabled(false); // avoid a distraction
this.bulletAppState = new SoftPhysicsAppState();
bulletAppState.setDebugEnabled(true);
bulletAppState.setDebugInitListener(this);
stateManager.attach(bulletAppState);
PhysicsSpace physicsSpace = getPhysicsSpace();
physicsSpace.setGravity(Vector3f.ZERO);
}
/**
* Update the debug materials of the specified collision object.
*
* @param pco the object to update (not null, modified)
*/
private void setDebugMaterial(PhysicsCollisionObject pco) {
CollisionShape shape = pco.getCollisionShape();
Material debugMaterial;
if (status.isWireframe()) {
debugMaterial = null;
} else if (status.isChildColoring()
&& shape instanceof CompoundCollisionShape) {
debugMaterial = BulletDebugAppState.enableChildColoring;
} else { // use the yellow lit/shaded material
debugMaterial = findMaterial("solid");
}
pco.setDebugMaterial(debugMaterial);
}
/**
* Add a dynamic rigid body with the selected shape.
*/
private void setUpShape() {
ShapeGenerator random = getGenerator();
String shapeName = status.shapeName();
CollisionShape shape;
switch (shapeName) {
case "box":
case "frame":
case "halfPipe":
case "hull":
case "iBeam":
case "lidlessBox":
case "platonic":
case "prism":
case "pyramid":
case "star":
case "tetrahedron":
case "triangularFrame":
case "trident":
case "washer":
shape = random.nextShape(shapeName);
addRigidBody(shape, MeshNormals.Facet);
break;
case "capsule":
case "cone":
case "cylinder":
case "dome":
case "football":
case "multiSphere":
case "snowman":
case "torus":
shape = random.nextShape(shapeName);
addRigidBody(shape, MeshNormals.Smooth);
break;
default:
String message = "shapeName = " + MyString.quote(shapeName);
throw new RuntimeException(message);
}
}
/**
* Split all rigid bodies in the PhysicsSpace.
*/
private void splitAll() {
Vector3f world3 = cam.getLocation(); // alias
Triangle triangle = new Triangle(world1, world2, world3);
PhysicsSpace space = getPhysicsSpace();
Collection<PhysicsCollisionObject> allPcos = space.getPcoList();
for (PhysicsCollisionObject pco : allPcos) {
PhysicsRigidBody body = (PhysicsRigidBody) pco;
splitBody(body, triangle);
}
}
/**
* Split the specified rigid body using the plane of the specified triangle.
*
* @param oldBody (not null, added to the PhysicsSpace)
* @param worldTriangle a triangle that defines the splitting plane (in
* world coordinates, not null, unaffected)
*/
private void splitBody(PhysicsRigidBody oldBody, Triangle worldTriangle) {
// Transform the triangle to the descaled shape coordinate system.
Transform shapeToWorld = oldBody.getTransform(null);
Vector3f w1 = worldTriangle.get1(); // alias
Vector3f s1 = shapeToWorld.transformInverseVector(w1, null);
Vector3f w2 = worldTriangle.get2(); // alias
Vector3f s2 = shapeToWorld.transformInverseVector(w2, null);
Vector3f w3 = worldTriangle.get3(); // alias
Vector3f s3 = shapeToWorld.transformInverseVector(w3, null);
Triangle shapeTriangle = new Triangle(s1, s2, s3);
Vector3f shapeNormal = shapeTriangle.getNormal(); // alias
Plane shapePlane = new Plane(shapeNormal, s3);
CollisionShape splitShape;
CollisionShape oldShape = oldBody.getCollisionShape();
if (oldShape instanceof HullCollisionShape) {
HullCollisionShape hullShape = (HullCollisionShape) oldShape;
splitShape = hullShape.split(shapePlane);
if (splitShape == oldShape) {
// The split plane doesn't intersect this body.
return;
}
CompoundCollisionShape compound
= (CompoundCollisionShape) splitShape;
ChildCollisionShape[] children = compound.listChildren();
assert children.length == 2 : children.length;
CollisionShape[] shapes = new CollisionShape[2];
float[] volumes = new float[2];
Vector3f[] locations = new Vector3f[2];
Vector3f[] velocities = new Vector3f[2];
for (int i = 0; i < 2; ++i) {
ChildCollisionShape child = children[i];
shapes[i] = child.getShape();
HullCollisionShape hull = (HullCollisionShape) shapes[i];
volumes[i] = hull.scaledVolume();
Vector3f location = child.copyOffset(null);
if (i == 0) {
MyVector3f.accumulateScaled(location, shapeNormal, -0.04f);
} else {
MyVector3f.accumulateScaled(location, shapeNormal, +0.04f);
}
shapeToWorld.transformVector(location, location);
locations[i] = location;
velocities[i] = new Vector3f(); // Values are set below!
}
Vector3f v = oldBody.getLinearVelocity(null);
Vector3f worldNormal = worldTriangle.getNormal(); // alias
MyVector3f.accumulateScaled(velocities[0], worldNormal, -0.04f);
MyVector3f.accumulateScaled(velocities[1], worldNormal, +0.04f);
float totalVolume = volumes[0] + volumes[1];
assert totalVolume > 0f : totalVolume;
float totalMass = oldBody.getMass();
Vector3f w = oldBody.getAngularVelocity(null);
PhysicsSpace space = getPhysicsSpace();
space.removeCollisionObject(oldBody);
for (int i = 0; i < 2; ++i) {
float mass = totalMass * volumes[i] / totalVolume;
PhysicsRigidBody body = new PhysicsRigidBody(shapes[i], mass);
body.setPhysicsLocation(locations[i]);
body.setLinearVelocity(velocities[i]);
body.setPhysicsRotation(shapeToWorld.getRotation());
body.setAngularVelocity(w);
body.setDebugMeshNormals(MeshNormals.Facet);
addCollisionObject(body);
}
} else {
String className = oldShape.getClass().getSimpleName();
System.out.println("Shape not split: class=" + className);
System.out.flush();
}
}
}