Code: Select all
const str = await RES.getResAsync("truck_json") as string
console.log(str)
this.world = new Box2D.Dynamics.b2World(new Box2D.Common.Math.b2Vec2(0, 10), false)
new RubeEditor.Rubeloader().readFromString(str, "", this.world)
let sprite = new egret.Sprite()
//sprite.scaleX = 32
//sprite.scaleY = 32
this.addChild(sprite)
let debug = new Box2D.Dynamics.b2DebugDraw()
debug.SetFlags(Box2D.Dynamics.b2DebugDraw.e_shapeBit)
debug.SetDrawScale(32)
// debug.SetLineThickness(1);
//debug.SetAlpha(0.8);
//debug.SetFillAlpha(0.5);
debug.SetSprite(sprite)
this.world.SetDebugDraw(debug)
this.addEventListener(egret.Event.ENTER_FRAME, this.loop, this);
}
private loop(e: egret.Event) {
this.world.Step(1 / 60, 10, 10);
this.world.DrawDebugData();
}
https://pasteboard.co/HCSWUmQ.png
Code: Select all
module RubeEditor {
import Vec2 = Box2D.Common.Math.b2Vec2
import b2Body = Box2D.Dynamics.b2Body
import b2Fixture = Box2D.Dynamics.b2Fixture
import World = Box2D.Dynamics.b2World
import BodyDef = Box2D.Dynamics.b2BodyDef
import MassData = Box2D.Collision.Shapes.b2MassData
import Joint = Box2D.Dynamics.Joints.b2Joint
import FixtureDef = Box2D.Dynamics.b2FixtureDef
import CircleShape = Box2D.Collision.Shapes.b2CircleShape
import EdgeShape = Box2D.Collision.Shapes.b2EdgeShape
import ChainShape = Box2D.Collision.Shapes.b2EdgeChainDef
import PolygonShape = Box2D.Collision.Shapes.b2PolygonShape
import RevoluteJointDef = Box2D.Dynamics.Joints.b2RevoluteJointDef
import RevoluteJoint = Box2D.Dynamics.Joints.b2RevoluteJoint
import PrismaticJointDef = Box2D.Dynamics.Joints.b2PrismaticJointDef
import PrismaticJoint = Box2D.Dynamics.Joints.b2PrismaticJoint
import DistanceJointDef = Box2D.Dynamics.Joints.b2DistanceJointDef
import DistanceJoint = Box2D.Dynamics.Joints.b2DistanceJoint
import PulleyJointDef = Box2D.Dynamics.Joints.b2PullyJointDef
import PulleyJoint = Box2D.Dynamics.Joints.b2PullyJoint
import MouseJointDef = Box2D.Dynamics.Joints.b2MouseJointDef
import MouseJoint = Box2D.Dynamics.Joints.b2MouseJoint
import GearJointDef = Box2D.Dynamics.Joints.b2GearJointDef
import GearJoint = Box2D.Dynamics.Joints.b2GearJoint
import WeldJointDef = Box2D.Dynamics.Joints.b2WeldJointDef
import WeldJoint = Box2D.Dynamics.Joints.b2WeldJoint
import FrictionJointDef = Box2D.Dynamics.Joints.b2FrictionJointDef
import FrictionJoint = Box2D.Dynamics.Joints.b2FrictionJoint
import JointDef = Box2D.Dynamics.Joints.b2JointDef
export class Rubeloader {
m_useHumanReadableFloats: boolean
m_simulationPositionIterations: number
m_simulationVelocityIterations: number;
m_simulationFPS: number;
m_indexToBodyMap: Map<number, Box2D.Dynamics.b2Body>
m_bodyToIndexMap: Map<Box2D.Dynamics.b2Body, number>
m_jointToIndexMap: Map<Box2D.Dynamics.Joints.b2Joint, number>
m_bodies: Box2D.Dynamics.b2Body[]
m_joints: Joint[]
m_images: Jb2dJsonImage[];
m_bodyToNameMap: Map<Box2D.Dynamics.b2Body, string>
m_fixtureToNameMap: Map<Box2D.Dynamics.b2Fixture, string>
m_jointToNameMap: Map<Box2D.Dynamics.Joints.b2Joint, string>
m_imageToNameMap: Map<Jb2dJsonImage, string>
m_bodyToPathMap: Map<Box2D.Dynamics.b2Body, string>
m_fixtureToPathMap: Map<Box2D.Dynamics.b2Fixture, string>
m_jointToPathMap: Map<Box2D.Dynamics.Joints.b2Joint, string>
m_imageToPathMap: Map<Jb2dJsonImage, string>
// This maps an item (Body, Fixture etc) to a set of custom properties.
// Use null for world properties.
m_customPropertiesMap: Map<Object, Jb2dJsonCustomProperties>
protected m_bodiesWithCustomProperties: Set<Box2D.Dynamics.b2Body>
protected m_fixturesWithCustomProperties: Set<Box2D.Dynamics.b2Fixture>
protected m_jointsWithCustomProperties: Set<Box2D.Dynamics.Joints.b2Joint>
protected m_imagesWithCustomProperties: Set<Jb2dJsonImage>
protected m_worldsWithCustomProperties: Set<Box2D.Dynamics.b2World>
public constructor() {
this.Rubeloader(true)
}
public Rubeloader(m_useHumanReadableFloats: boolean) {
if (!m_useHumanReadableFloats) {
// The floatToHex function is not giving the same results
// as the original C++ version... not critical so worry about it
// later.
console.log("Non human readable floats are not implemented yet")
//System.out.println("Non human readable floats are not implemented yet");
this.m_useHumanReadableFloats = true;
}
this.m_useHumanReadableFloats = m_useHumanReadableFloats;
this.m_simulationPositionIterations = 3;
this.m_simulationVelocityIterations = 8;
this.m_simulationFPS = 60;
this.m_indexToBodyMap = new Map()
this.m_bodyToIndexMap = new Map()
this.m_jointToIndexMap = new Map()
this.m_bodies = new Array<b2Body>();
this.m_joints = new Array<Joint>();
this.m_images = new Array<Jb2dJsonImage>();
this.m_bodyToNameMap = new Map()
this.m_fixtureToNameMap = new Map()
this.m_jointToNameMap = new Map()
this.m_imageToNameMap = new Map()
this.m_bodyToPathMap = new Map()
this.m_fixtureToPathMap = new Map()
this.m_jointToPathMap = new Map()
this.m_imageToPathMap = new Map()
this.m_customPropertiesMap = new Map()
this.m_bodiesWithCustomProperties = new Set()
this.m_fixturesWithCustomProperties = new Set()
this.m_jointsWithCustomProperties = new Set()
this.m_imagesWithCustomProperties = new Set()
this.m_worldsWithCustomProperties = new Set()
}
public readFromString(str: string, errorMsg: string, existingWorld: Box2D.Dynamics.b2World): Box2D.Dynamics.b2World {
try {
let worldValue = str;//JSON.parse(str);
return this.j2b2World(worldValue, existingWorld);
} catch (e) {
errorMsg += "Failed to parse JSON"
//e.printStackTrace();
console.log(e)
return null;
}
}
public j2b2World(worldValue: any, existingWorld: Box2D.Dynamics.b2World): Box2D.Dynamics.b2World {
//console.log(worldValue);
let world = existingWorld;
if (world == null) {
world = new World(this.jsonToVec("gravity", worldValue), worldValue["allowSleep"]);
}
//console.log(world)
//world.setAutoClearForces(worldValue.getBoolean("autoClearForces"));
//world.setWarmStarting(worldValue.getBoolean("warmStarting"));
//world.setContinuousPhysics(worldValue.getBoolean("continuousPhysics"));
this.readWorldCustomPropertiesFromJson(world, worldValue);
var i = 0;
let bodyValues = worldValue["body"] as Array<b2Body>;
if (null != bodyValues) {
var numBodyValues = bodyValues.length;
for (i = 0; i < numBodyValues; i++) {
let bodyValue = bodyValues[i];
let body = this.j2b2Body(world, bodyValue);
this.readBodyCustomPropertiesFromJson(body, bodyValue);
this.m_bodies.push(body);
//this.m_bodies.add(body);
//this.m_indexToBodyMap.put(i, body);
this.m_indexToBodyMap.set(i, body);
}
}
let jointValues = worldValue["joint"] as Array<any>;
if (null != jointValues) {
let numJointValues = jointValues.length;
for (i = 0; i < numJointValues; i++) {
let jointValue = jointValues[i];
if (((jointValue["type"] as string) || "") != ("gear")) {
let joint = this.j2b2Joint(world, jointValue);
this.readJointCustomPropertiesFromJson(joint, jointValue);
if (joint != null)
this.m_joints.push(joint)
}
}
for (i = 0; i < numJointValues; i++) {
let jointValue = jointValues[i];
if ((jointValue["type"] as string || "") == ("gear")) {
let joint = this.j2b2Joint(world, jointValue);
this.readJointCustomPropertiesFromJson(joint, jointValue);
if (joint != null) {
this.m_joints.push(joint);
}
}
}
}
i = 0;
let imageValues = worldValue["image"] as Array<any>;
if (null != imageValues) {
let numImageValues = imageValues.length;
for (i = 0; i < numImageValues; i++) {
let imageValue = imageValues[i];
let image = this.j2b2dJsonImage(imageValue);
this.readImageCustomPropertiesFromJson(image, imageValue);
this.m_images.push(image);
}
}
return world;
}
readImageCustomPropertiesFromJson(item, value) {
if (null == item)
return;
if (!value.hasOwnProperty("customProperties"))
return;
var i = 0;
let propValues = value["customProperties"] as Array<any>;
if (null != propValues) {
let numPropValues = propValues.length;
for (i = 0; i < numPropValues; i++) {
let propValue = propValues[i];
let propertyName = propValue["name"] as string;
if (propValue.hasOwnProperty("int"))
this.setCustomInt(item, propertyName, propValue["int"] as number);
if (propValue.hasOwnProperty("float"))
this.setCustomFloat(item, propertyName, propValue["float"] as number);
if (propValue.hasOwnProperty("string"))
this.setCustomString(item, propertyName, propValue["string"] as string);
if (propValue.hasOwnProperty("vec2"))
this.setCustomVector(item, propertyName, this.jsonToVec("vec2", propValue));
if (propValue.hasOwnProperty("bool"))
this.setCustomBool(item, propertyName, propValue["bool"] as boolean);
}
}
}
j2b2dJsonImage(imageValue): Jb2dJsonImage {
let img = new Jb2dJsonImage();
let bodyIndex = (imageValue["body"] as number) || -1;
if (-1 != bodyIndex)
img.body = this.lookupBodyFromIndex(bodyIndex);
let imageName = (imageValue["name"] as string) || "";
if (imageName != ("")) {
img.name = imageName;
this.setImageName(img, imageName);
}
let imagePath = (imageValue["path"] as string) || "";
if (imagePath != ("")) {
img.path = imagePath;
this.setImagePath(img, imagePath);
}
let fileName = (imageValue["file"] as string) || "";
if (fileName != (""))
img.file = fileName;
img.center = this.jsonToVec("center", imageValue);
img.angle = this.jsonToFloat("angle", imageValue);
img.scale = this.jsonToFloat("scale", imageValue);
img.aspectScale = this.jsonToFloat("aspectScale", imageValue);
img.opacity = this.jsonToFloat("opacity", imageValue);
img.renderOrder = this.jsonToFloat("renderOrder", imageValue);
let colorTintArray = imageValue["colorTint"] as Array<any>;
if (null != colorTintArray) {
for (var i = 0; i < 4; i++) {
img.colorTint[i] = colorTintArray[i] as number;
}
}
img.flip = (imageValue["flip"] as boolean) || false;
img.filter = (imageValue["filter"] as number) || 1;
img.corners = Array<Vec2>(4);
for (var i = 0; i < 4; i++)
img.corners[i] = this.jsonToVec3("corners", imageValue, i);
let vertexPointerArray = imageValue["glVertexPointer"] as Array<any>;
let texCoordArray = imageValue["glVertexPointer"] as Array<any>;
if (null != vertexPointerArray && null != texCoordArray && vertexPointerArray.length == texCoordArray.length) {
let numFloats = vertexPointerArray.length;
img.numPoints = numFloats / 2;
img.points = new Array<number>(numFloats);
img.uvCoords = new Array<number>(numFloats);
for (var i = 0; i < numFloats; i++) {
img.points[i] = this.jsonToFloat3("glVertexPointer", imageValue, i);
img.uvCoords[i] = this.jsonToFloat3("glTexCoordPointer", imageValue, i);
}
}
let drawElementsArray = imageValue["glDrawElements"] as Array<any>;
if (null != drawElementsArray) {
img.numIndices = drawElementsArray.length;
img.indices = new Array<number>(img.numIndices);
for (var i = 0; i < img.numIndices; i++)
img.indices[i] = drawElementsArray[i] as number;
}
return img;
}
lookupBodyFromIndex(index): b2Body {
if (this.m_indexToBodyMap.has(index))
return this.m_indexToBodyMap.get(index);
else
return null;
}
lookupBodyIndex(body): number {
let val = this.m_bodyToIndexMap.get(body);
if (null != val)
return val as number;
else
return -1;
}
lookupJointIndex(joint): number {
let val = this.m_jointToIndexMap.get(joint);
if (null != val)
return val as number;
else
return -1;
}
readJointCustomPropertiesFromJson(item, value) {
if (null == item)
return;
if (!value.hasOwnProperty("customProperties"))
return;
var i = 0;
let propValues = value["customProperties"] as Array<any>
if (null != propValues) {
let numPropValues = propValues.length;
for (i = 0; i < numPropValues; i++) {
let propValue = propValues[i];
let propertyName = propValue["name"] as string;
if (propValue.hasOwnProperty("int"))
this.setCustomInt(item, propertyName, propValue["int"] as number);
if (propValue.hasOwnProperty("float"))
this.setCustomFloat(item, propertyName, propValue["float"] as number);
if (propValue.hasOwnProperty("string"))
this.setCustomString(item, propertyName, propValue["string"] as string);
if (propValue.hasOwnProperty("vec2"))
this.setCustomVector(item, propertyName, this.jsonToVec("vec2", propValue));
if (propValue.hasOwnProperty("bool"))
this.setCustomBool(item, propertyName, propValue["bool"] as boolean);
}
}
}
j2b2Joint(world: World, jointValue): Joint {
var joint = null;
let bodyIndexA = jointValue["bodyA"] as number;
let bodyIndexB = jointValue["bodyB"] as number;
if (bodyIndexA >= this.m_bodies.length || bodyIndexB >= this.m_bodies.length) {
return null;
}
var revoluteDef: RevoluteJointDef;
var prismaticDef: PrismaticJointDef;
var distanceDef: DistanceJointDef;
var pulleyDef: PulleyJointDef;
var mouseDef: MouseJointDef;
var gearDef: GearJointDef;
// WheelJointDef wheelDef;
var weldDef: WeldJointDef;
var frictionDef: FrictionJointDef;
//var ropeDef: RopeJointDef;
let jointDef: JointDef = null;
let mouseJointTarget = new Vec2(0, 0);
let type = (jointValue["type"] as string) || "";
if (type == "revolute") {
jointDef = revoluteDef = new RevoluteJointDef();
revoluteDef.localAnchorA = this.jsonToVec("anchorA", jointValue);
revoluteDef.localAnchorB = this.jsonToVec("anchorB", jointValue);
revoluteDef.referenceAngle = this.jsonToFloat("refAngle", jointValue);
revoluteDef.enableLimit = (jointValue["enableLimit"] as boolean) || false;
revoluteDef.lowerAngle = this.jsonToFloat("lowerLimit", jointValue);
revoluteDef.upperAngle = this.jsonToFloat("upperLimit", jointValue);
revoluteDef.enableMotor = (jointValue["enableMotor"] as boolean) || false;
revoluteDef.motorSpeed = this.jsonToFloat("motorSpeed", jointValue);
revoluteDef.maxMotorTorque = this.jsonToFloat("maxMotorTorque", jointValue);
} else if (type == "prismatic") {
jointDef = prismaticDef = new PrismaticJointDef();
prismaticDef.localAnchorA = this.jsonToVec("anchorA", jointValue);
prismaticDef.localAnchorB = this.jsonToVec("anchorB", jointValue);
if (jointValue["localAxisA"] != null)
prismaticDef.localAxisA = this.jsonToVec("localAxisA", jointValue);
else
prismaticDef.localAxisA = this.jsonToVec("localAxis1", jointValue);
prismaticDef.referenceAngle = this.jsonToFloat("refAngle", jointValue);
prismaticDef.enableLimit = (jointValue["enableLimit"] as boolean)
prismaticDef.lowerTranslation = this.jsonToFloat("lowerLimit", jointValue);
prismaticDef.upperTranslation = this.jsonToFloat("upperLimit", jointValue);
prismaticDef.enableMotor = jointValue.optBoolean("enableMotor");
prismaticDef.motorSpeed = this.jsonToFloat("motorSpeed", jointValue);
prismaticDef.maxMotorForce = this.jsonToFloat("maxMotorForce", jointValue);
} else if (type == "distance") {
jointDef = distanceDef = new DistanceJointDef();
distanceDef.localAnchorA = (this.jsonToVec("anchorA", jointValue));
distanceDef.localAnchorB = (this.jsonToVec("anchorB", jointValue));
distanceDef.length = this.jsonToFloat("length", jointValue);
distanceDef.frequencyHz = this.jsonToFloat("frequency", jointValue);
distanceDef.dampingRatio = this.jsonToFloat("dampingRatio", jointValue);
} else if (type == ("pulley")) {
jointDef = pulleyDef = new PulleyJointDef();
pulleyDef.groundAnchorA = (this.jsonToVec("groundAnchorA", jointValue));
pulleyDef.groundAnchorB = (this.jsonToVec("groundAnchorB", jointValue));
pulleyDef.localAnchorA = (this.jsonToVec("anchorA", jointValue));
pulleyDef.localAnchorB = (this.jsonToVec("anchorB", jointValue));
pulleyDef.lengthA = this.jsonToFloat("lengthA", jointValue);
pulleyDef.lengthB = this.jsonToFloat("lengthB", jointValue);
pulleyDef.ratio = this.jsonToFloat("ratio", jointValue);
} else if (type == ("mouse")) {
jointDef = mouseDef = new MouseJointDef();
mouseJointTarget = this.jsonToVec("target", jointValue);
//mouseDef.target = this.jsonToVec("anchorB", jointValue);
mouseDef.maxForce = this.jsonToFloat("maxForce", jointValue);
mouseDef.frequencyHz = this.jsonToFloat("frequency", jointValue);
mouseDef.dampingRatio = this.jsonToFloat("dampingRatio", jointValue);
} else if (type == ("wheel")) {
jointDef = revoluteDef = new RevoluteJointDef();
revoluteDef.localAnchorA = this.jsonToVec("anchorA", jointValue);
revoluteDef.localAnchorB = this.jsonToVec("anchorB", jointValue);
revoluteDef.enableMotor = jointValue["enableMotor"] || false;
revoluteDef.motorSpeed = this.jsonToFloat("motorSpeed", jointValue);
revoluteDef.maxMotorTorque = this.jsonToFloat("maxMotorTorque", jointValue);
} else if (type == ("weld")) {
jointDef = weldDef = new WeldJointDef();
weldDef.localAnchorA = (this.jsonToVec("anchorA", jointValue));
weldDef.localAnchorB = (this.jsonToVec("anchorB", jointValue));
weldDef.referenceAngle = 0;
} else if (type == ("friction")) {
jointDef = frictionDef = new FrictionJointDef();
frictionDef.localAnchorA = (this.jsonToVec("anchorA", jointValue));
frictionDef.localAnchorB = (this.jsonToVec("anchorB", jointValue));
frictionDef.maxForce = this.jsonToFloat("maxForce", jointValue);
frictionDef.maxTorque = this.jsonToFloat("maxTorque", jointValue);
} else if (type == ("rope")) {
console.log("not support rope joint")
/*jointDef = ropeDef = new RopeJointDef();
ropeDef.localAnchorA.set(jsonToVec("anchorA", jointValue));
ropeDef.localAnchorB.set(jsonToVec("anchorB", jointValue));
ropeDef.maxLength = jsonToFloat("maxLength", jointValue);*/
}
if (null != jointDef) {
// set features common to all joints
jointDef.bodyA = this.m_bodies[bodyIndexA];
jointDef.bodyB = this.m_bodies[bodyIndexB];
jointDef.collideConnected = (jointValue["collideConnected"] as boolean) || false;
joint = world.CreateJoint(jointDef);
if (type == "mouse")
(joint as MouseJoint).SetTarget(mouseJointTarget);
let jointName = jointValue["name"] || "";
if (jointName != "") {
this.setJointName(joint, jointName);
}
let jointPath = (jointValue["path"] as string) || "";
if (jointPath != "") {
this.setJointPath(joint, jointPath);
}
}
return joint
}
public j2b2Body(world: World, bodyValue): b2Body {
let bodyDef = new BodyDef();
switch (bodyValue["type"] as number) {
case 0:
bodyDef.type = b2Body.b2_staticBody;
break;
case 1:
bodyDef.type = b2Body.b2_kinematicBody;
break;
case 2:
bodyDef.type = b2Body.b2_dynamicBody;
break;
}
bodyDef.position = this.jsonToVec("position", bodyValue);
bodyDef.angle = this.jsonToFloat("angle", bodyValue);
bodyDef.linearVelocity = this.jsonToVec("linearVelocity", bodyValue);
bodyDef.angularVelocity = this.jsonToFloat("angularVelocity", bodyValue);
bodyDef.linearDamping = this.jsonToFloat4("linearDamping", bodyValue, -1, 0);
bodyDef.angularDamping = this.jsonToFloat4("angularDamping", bodyValue, -1, 0);
//bodyDef.gravityScale = this.jsonToFloat4("gravityScale", bodyValue, -1, 1);
bodyDef.allowSleep = (bodyValue["allowSleep"] as boolean) || true;
bodyDef.awake = (bodyValue["awake"] as boolean) || false;
bodyDef.fixedRotation = bodyValue["fixedRotation"] as boolean;
bodyDef.bullet = (bodyValue["bullet"] as boolean) || false;
bodyDef.active = (bodyValue["active"] as boolean) || true;
let body = world.CreateBody(bodyDef);
let bodyName = bodyValue["name"] as string;
if ("" != bodyName) {
this.setBodyName(body, bodyName);
}
let bodyPath = bodyValue["path"] as string;
if ("" != bodyPath) {
this.setBodyPath(body, bodyPath);
}
let i = 0;
let fixtureValues = bodyValue["fixture"] as Array<any>;
if (null != fixtureValues) {
let numFixtureValues = fixtureValues.length;
for (i = 0; i < numFixtureValues; i++) {
let fixtureValue = fixtureValues[i];
let fixture = this.j2b2Fixture(body, fixtureValue);
this.readFixtureCustomPropertiesFromJson(fixture, fixtureValue);
}
}
let massData = new MassData();
massData.mass = this.jsonToFloat("massData-mass", bodyValue);
massData.center = this.jsonToVec("massData-center", bodyValue);
massData.I = this.jsonToFloat("massData-I", bodyValue);
body.SetMassData(massData);
return body
}
j2b2Fixture(body: b2Body, fixtureValue): b2Fixture {
if (null == fixtureValue)
return null;
let fixtureDef = new FixtureDef();
fixtureDef.restitution = this.jsonToFloat("restitution", fixtureValue);
fixtureDef.friction = this.jsonToFloat("friction", fixtureValue);
fixtureDef.density = this.jsonToFloat("density", fixtureValue);
fixtureDef.isSensor = (fixtureValue["sensor"] as boolean) || false;
fixtureDef.filter.categoryBits = (fixtureValue["filter-categoryBits"] as number) || 0x0001;
fixtureDef.filter.maskBits = (fixtureValue["filter-maskBits"] as number) || 0xffff;
fixtureDef.filter.groupIndex = (fixtureValue["filter-groupIndex"] as number) || 0;
let fixture = null;
if (null != fixtureValue["circle"]) {
console.log("--->circle")
let circleValue = fixtureValue["circle"];
let circleShape = new CircleShape();
circleShape.SetRadius(this.jsonToFloat("radius", circleValue));
circleShape.SetLocalPosition(this.jsonToVec("center", circleValue));
fixtureDef.shape = circleShape;
fixture = body.CreateFixture(fixtureDef);
} else if (null != fixtureValue["edge"]) {
console.log("--->edge")
let edgeValue = fixtureValue["edge"];
let edgeShape = new EdgeShape(this.jsonToVec("vertex1", edgeValue), this.jsonToVec("vertex2", edgeValue));
//edgeShape.m_vertex1.set(jsonToVec("vertex1", edgeValue));
//edgeShape.m_vertex2.set(jsonToVec("vertex2", edgeValue));
/*edgeShape.m_hasVertex0 = edgeValue.optBoolean("hasVertex0", false);
edgeShape.m_hasVertex3 = edgeValue.optBoolean("hasVertex3", false);
if (edgeShape.m_hasVertex0)
edgeShape.m_vertex0.set(jsonToVec("vertex0", edgeValue));
if (edgeShape.m_hasVertex3)
edgeShape.m_vertex3.set(jsonToVec("vertex3", edgeValue));*/
fixtureDef.shape = edgeShape;
fixture = body.CreateFixture(fixtureDef);
} else if (null != fixtureValue["loop"]) {// support old
console.log("not support loop")
// format (r197)
/*let chainValue = fixtureValue["loop"];
let chainShape = new ChainShape();
let numVertices = (chainValue["x"] as Array<any>).length;
let vertices = new Vec2[numVertices];
for (var i = 0; i < numVertices; i++){
vertices[i] = this.jsonToVec3("vertices", chainValue, i);
}
chainShape.isALoop = true
chainShape.vertexCount = numVertices
chainShape.vertices = vertices
//chainShape.createLoop(vertices, numVertices);
fixtureDef.shape = chainShape;
fixture = body.CreateFixture(fixtureDef);*/
} else if (null != fixtureValue["chain"]) {
console.log("not support chain")
/*JSONObject chainValue = fixtureValue.getJSONObject("chain");
ChainShape chainShape = new ChainShape();
int numVertices = chainValue.getJSONObject("vertices").getJSONArray("x").length();
Vec2 vertices[] = new Vec2[numVertices];
for (int i = 0; i < numVertices; i++)
vertices[i] = jsonToVec("vertices", chainValue, i);
chainShape.createChain(vertices, numVertices);
chainShape.m_hasPrevVertex = chainValue.optBoolean("hasPrevVertex", false);
chainShape.m_hasNextVertex = chainValue.optBoolean("hasNextVertex", false);
if (chainShape.m_hasPrevVertex)
chainShape.m_prevVertex.set(jsonToVec("prevVertex", chainValue));
if (chainShape.m_hasNextVertex)
chainShape.m_nextVertex.set(jsonToVec("nextVertex", chainValue));
fixtureDef.shape = chainShape;
fixture = body.createFixture(fixtureDef);*/
} else if (null != fixtureValue["polygon"]) {
console.log("-->polygon")
let polygonValue = fixtureValue["polygon"];
let vertices = Array<Vec2>(8);
let numVertices = polygonValue["vertices"]["x"].length;
if (numVertices > 8) {
console.log("Ignoring polygon fixture with too many vertices.");
} else if (numVertices < 2) {
console.log("Ignoring polygon fixture less than two vertices.");
} else if (numVertices == 2) {
console.log("Creating edge shape instead of polygon with two vertices.");
let edgeShape = new EdgeShape(this.jsonToVec3("vertices", polygonValue, 0), this.jsonToVec3("vertices", polygonValue, 1));
//edgeShape.m_vertex1.set(jsonToVec("vertices", polygonValue, 0));
//edgeShape.m_vertex2.set(jsonToVec("vertices", polygonValue, 1));
fixtureDef.shape = edgeShape;
fixture = body.CreateFixture(fixtureDef);
} else {
let polygonShape = new PolygonShape();
for (var i = 0; i < numVertices; i++) {
vertices[i] = this.jsonToVec3("vertices", polygonValue, i);
}
polygonShape.SetAsArray(vertices, numVertices);
fixtureDef.shape = polygonShape;
fixture = body.CreateFixture(fixtureDef);
}
}
let fixtureName = (fixtureValue["name"] as string) || "";
if (fixtureName != "") {
this.setFixtureName(fixture, fixtureName);
}
let fixturePath = (fixtureValue["path"] as string) || "";
if (fixturePath != ("")) {
this.setFixturePath(fixture, fixturePath);
}
return fixture;
}
setBodyName(body: b2Body, name) {
this.m_bodyToNameMap.set(body, name);
}
setFixtureName(fixture: b2Fixture, name) {
this.m_fixtureToNameMap.set(fixture, name);
}
setJointName(joint: Joint, name) {
this.m_jointToNameMap.set(joint, name);
}
setImageName(image: Jb2dJsonImage, name) {
this.m_imageToNameMap.set(image, name);
}
setBodyPath(body, path) {
this.m_bodyToPathMap.set(body, path);
}
setFixturePath(fixture, path) {
this.m_fixtureToPathMap.set(fixture, path);
}
setJointPath(joint, path) {
this.m_jointToPathMap.set(joint, path);
}
setImagePath(image, path) {
this.m_imageToPathMap.set(image, path);
}
readFixtureCustomPropertiesFromJson(item: b2Fixture, value) {
if (null == item)
return;
if (!value.hasOwnProperty("customProperties"))
return;
var i = 0;
let propValues = value["customProperties"] as Array<any>;
if (null != propValues) {
let numPropValues = propValues.length;
for (i = 0; i < numPropValues; i++) {
let propValue = propValues[i];
let propertyName = propValue["name"];
if (propValue.hasOwnProperty("int"))
this.setCustomInt(item, propertyName, propValue["int"] as number);
if (propValue.hasOwnProperty("float"))
this.setCustomFloat(item, propertyName, propValue["float"] as number);
if (propValue.hasOwnProperty("string"))
this.setCustomString(item, propertyName, propValue["string"] as string);
if (propValue.hasOwnProperty("vec2"))
this.setCustomVector(item, propertyName, this.jsonToVec("vec2", propValue));
if (propValue.hasOwnProperty("bool"))
this.setCustomBool(item, propertyName, propValue["bool"] as boolean);
}
}
}
readWorldCustomPropertiesFromJson(item: World, value) {
if (null == item)
return;
//console.log("-->" + value["customProperties"])
//console.log("--->" + value.hasOwnProperty("customProperties"));
if (!value.hasOwnProperty("customProperties"))
return;
let i = 0;
let propValues = value["customProperties"] as Array<any>;
if (null != propValues) {
let numPropValues = propValues.length;
for (i = 0; i < numPropValues; i++) {
let propValue = propValues[i];
let propertyName = propValue["name"];
if (propValue.hasOwnProperty("int"))
console.log(propValue["int"])
this.setCustomInt(item, propertyName, propValue["int"] as number);
if (propValue.hasOwnProperty("float"))
this.setCustomFloat(item, propertyName, propValue["float"] as number);
if (propValue.hasOwnProperty("string"))
this.setCustomString(item, propertyName, propValue["string"]);
if (propValue.hasOwnProperty("vec2"))
this.setCustomVector(item, propertyName, this.jsonToVec("vec2", propValue));
if (propValue.hasOwnProperty("bool")) {
}
this.setCustomBool(item, propertyName, propValue["bool"] as boolean);
}
}
}
readBodyCustomPropertiesFromJson(item: b2Body, value) {
if (null == item)
return;
if (!value.hasOwnProperty("customProperties"))
return;
let i = 0;
let propValues = value["customProperties"] as Array<any>;
if (null != propValues) {
let numPropValues = propValues.length;
for (i = 0; i < numPropValues; i++) {
let propValue = propValues[i];
let propertyName = propValue["name"] as string;
if (propValue.hasOwnProperty("int"))
this.setCustomInt(item, propertyName, propValue["int"] as number);
if (propValue.hasOwnProperty("float"))
this.setCustomFloat(item, propertyName, propValue["float"] as number);
if (propValue.hasOwnProperty("string"))
this.setCustomString(item, propertyName, propValue["string"] as string);
if (propValue.hasOwnProperty("vec2"))
this.setCustomVector(item, propertyName, this.jsonToVec("vec2", propValue));
if (propValue.hasOwnProperty("bool"))
this.setCustomBool(item, propertyName, propValue["bool"] as boolean);
}
}
}
setCustomInt(item, propertyName: string, val: number) {
this.getCustomPropertiesForItem(item, true).m_customPropertyMap_int.set(propertyName, val);
}
setCustomFloat(item, propertyName: string, val: number) {
this.getCustomPropertiesForItem(item, true).m_customPropertyMap_float.set(propertyName, val);
}
setCustomString(item, propertyName: string, val: string) {
this.getCustomPropertiesForItem(item, true).m_customPropertyMap_string.set(propertyName, val);
}
setCustomVector(item, propertyName: string, val: Vec2) {
this.getCustomPropertiesForItem(item, true).m_customPropertyMap_vec2.set(propertyName, val);
}
setCustomBool(item, propertyName: string, val: boolean) {
this.getCustomPropertiesForItem(item, true).m_customPropertyMap_bool.set(propertyName, val);
}
public getCustomPropertiesForItem(item, createIfNotExisting: boolean): Jb2dJsonCustomProperties {
if (this.m_customPropertiesMap.has(item))
return this.m_customPropertiesMap.get(item);
if (!createIfNotExisting)
return null;
let props = new Jb2dJsonCustomProperties();
this.m_customPropertiesMap.set(item, props);
return props;
}
jsonToVec(name: string, value: any): Vec2 {
return this.jsonToVec4(name, value, -1, new Vec2(0, 0));
}
jsonToVec3(name: string, value: any, index: number): Vec2 {
return this.jsonToVec4(name, value, index, new Vec2(0, 0));
}
public jsonToVec4(name: string, value: any, index: number, defaultValue: Vec2): Vec2 {
let vec = defaultValue;
try {
if (!(value[name]))
return defaultValue;
} catch (error) {
//console.log(error)
return defaultValue;
}
if (index > -1) {
let vecValue = value[name];
let arrayX = vecValue["x"] as Array<any>;
let arrayY = vecValue["y"] as Array<any>;
// if ( arrayX[index].isString() )
// vec.x = hexToFloat(value[name]["x"][index].asString());
// else
vec.x = arrayX[index] as number;
// if ( arrayX[index].isString() )
// vec.y = hexToFloat(value[name]["y"][index].asString());
// else
vec.y = arrayY[index] as number;
} else {
let vecValue = value[name];
if (null == vecValue)
return defaultValue;
else if (!vecValue.hasOwnProperty("x")) // should be zero vector
vec.Set(0, 0)
//vec.set(0, 0);
else {
vec.x = this.jsonToFloat("x", vecValue);
vec.y = this.jsonToFloat("y", vecValue);
}
}
return vec;
}
jsonToFloat(name: string, value: any): number {
return this.jsonToFloat4(name, value, -1, 0);
}
jsonToFloat3(name: string, value: any, index: number): number {
return this.jsonToFloat4(name, value, index, 0);
}
jsonToFloat4(name: string, value: any, index: number, defaultValue: number): number {
if (!value.hasOwnProperty(name))
return defaultValue;
if (index > -1) {
var array = null;
try {
array = value[name] as Array<any>;
} catch (e) {
console.log(e)
}
if (null == array)
return defaultValue;
let obj = array[index];
if (null == obj)
return defaultValue;
// else if ( value[name].isString() )
// return hexToFloat( value[name].asString() );
else
return obj as number;
} else {
let obj = value[name];
if (null == obj)
return defaultValue;
// else if ( value[name].isString() )
// return hexToFloat( value[name].asString() );
else
return obj as number
}
}
}
export class Jb2dJsonImage {
name: String
path: String
file: String
body: Box2D.Dynamics.b2Body
center: Vec2
angle: number
scale: number
aspectScale: number
flip: boolean
opacity: number
filter: number; // 0 = nearest, 1 = linear
renderOrder: number
colorTint: number[]
corners: Vec2[]
numPoints: number
points: number[];
uvCoords: number[]
numIndices: number
indices: number[]
public Jb2dJsonImage() {
this.colorTint = [0, 0, 0, 0];
}
}
export class Jb2dJsonCustomProperties {
//m_customPropertyMap_int: Map<String, Integer> ;
m_customPropertyMap_int: Map<string, number>
//Map<String, Double> m_customPropertyMap_float;
m_customPropertyMap_float: Map<string, number>
//Map<String, String> m_customPropertyMap_string;
m_customPropertyMap_string: Map<string, string>
//Map<String, Vec2> m_customPropertyMap_vec2;
m_customPropertyMap_vec2: Map<string, Vec2>
//Map<String, Boolean> m_customPropertyMap_bool;
m_customPropertyMap_bool: Map<string, boolean>
public Jb2dJsonCustomProperties() {
this.m_customPropertyMap_int = new Map()
this.m_customPropertyMap_float = new Map()
this.m_customPropertyMap_string = new Map()
this.m_customPropertyMap_vec2 = new Map()
this.m_customPropertyMap_bool = new Map()
}
}
}