Search in sources :

Example 6 with Transformations

use of net.drewke.tdme.engine.Transformations in project tdme by andreasdr.

the class World method update.

/**
	 * Update world
	 * @param delta time
	 */
public void update(float deltaTime) {
    // lazy initiate constraints solver
    if (constraintsSolver == null) {
        constraintsSolver = new ConstraintsSolver(rigidBodies);
    }
    // apply gravity
    for (int i = 0; i < rigidBodies.size(); i++) {
        // update rigid body
        RigidBody rigidBody = rigidBodies.get(i);
        // skip on disabled, static
        if (rigidBody.enabled == false) {
            // System.out.println("World::update()::gravity::skipping " + rigidBody.id + "::disabled");
            continue;
        }
        if (rigidBody.isStatic == true) {
            continue;
        }
        // unset sleeping if velocity change occured
        if (rigidBody.checkVelocityChange() == true) {
            rigidBody.awake(true);
        }
        // skip on sleeping
        if (rigidBody.isSleeping == true) {
            continue;
        }
        // add gravity
        rigidBody.addForce(worldPosForce.set(rigidBody.getPosition()).setY(10000f), gravityForce.set(0f, -rigidBody.getMass() * MathTools.g, 0f));
    }
    // do the collision tests,
    // take every rigid body with every other rigid body into account
    int collisionsTests = 0;
    rigidBodyTestedCollisions.clear();
    for (int i = 0; i < rigidBodies.size(); i++) {
        RigidBody rigidBody1 = rigidBodies.get(i);
        // skip on disabled
        if (rigidBody1.enabled == false) {
            // System.out.println("World::update()::collision::skipping " + rigidBody1.id + "::disabled");
            continue;
        }
        /**
			for (int j = 0; j < rigidBodies.size(); j++) {
				RigidBody rigidBody2 = rigidBodies.get(j);
			*/
        int nearObjects = 0;
        // dont test test which had been done in reverse order
        for (RigidBody rigidBody2 : partition.getObjectsNearTo(rigidBody1.cbv)) {
            // skip on disabled
            if (rigidBody2.enabled == false) {
                // System.out.println("World::update()::collision::skipping " + rigidBody2.id + "::disabled");
                continue;
            }
            // skip if both are static
            if (rigidBody1.isStatic == true && rigidBody2.isStatic == true)
                continue;
            // skip on same rigid body
            if (rigidBody1 == rigidBody2)
                continue;
            // skip on rigid body 1 static, 2 non static and sleeping
            if (rigidBody1.isStatic == true && rigidBody2.isStatic == false && rigidBody2.isSleeping == true) {
                continue;
            }
            // skip on rigid body 2 static, 1 non static and sleeping
            if (rigidBody2.isStatic == true && rigidBody1.isStatic == false && rigidBody1.isSleeping == true) {
                continue;
            }
            // check if rigid body 2 want to have collision with rigid body 1
            if (((rigidBody1.typeId & rigidBody2.collisionTypeIds) == rigidBody1.typeId) == false) {
                continue;
            }
            // check if rigid body 1 want to have collision with rigid body 2
            if (((rigidBody2.typeId & rigidBody1.collisionTypeIds) == rigidBody2.typeId) == false) {
                continue;
            }
            //
            nearObjects++;
            // create rigidBody12 key
            Key rigidBodyKey = constraintsSolver.allocateKey();
            rigidBodyKey.reset();
            rigidBodyKey.append(rigidBody1.idx);
            rigidBodyKey.append(",");
            rigidBodyKey.append(rigidBody2.idx);
            // check if collision has been tested already
            if (rigidBodyTestedCollisions.get(rigidBodyKey) != null) {
                constraintsSolver.releaseKey();
                continue;
            }
            /*
				// create rigidbody21 key
				rigidBodyKey.reset();
				rigidBodyKey.append(rigidBody2.idx);
				rigidBodyKey.append(",");
				rigidBodyKey.append(rigidBody1.idx);

				if (rigidBodyTestedCollisions.get(rigidBodyKey) != null) {
					constraintsSolver.releaseKey();
					continue;
				}
				*/
            // nope, add 12 key
            rigidBodyTestedCollisions.put(rigidBodyKey, rigidBodyKey);
            //
            collisionsTests++;
            // determine collision movement
            collisionMovement.set(rigidBody1.movement);
            if (collisionMovement.computeLength() < MathTools.EPSILON) {
                collisionMovement.set(rigidBody2.movement);
                collisionMovement.scale(-1f);
            }
            // do collision test
            if (rigidBody1.cbv.doesCollideWith(rigidBody2.cbv, collisionMovement, collision) == true && collision.hasPenetration() == true) {
                // check for hit point count
                if (collision.getHitPointsCount() == 0)
                    continue;
                // we have a collision, so register it
                Key rigidBodyCollisionKey = rigidBodyCollisionsKeyPoolCurrentFrame.allocate();
                rigidBodyCollisionKey.reset();
                rigidBodyCollisionKey.append(rigidBody1.idx);
                rigidBodyCollisionKey.append(",");
                rigidBodyCollisionKey.append(rigidBody2.idx);
                rigidBodyCollisionsCurrentFrame.put(rigidBodyCollisionKey, rigidBodyCollisionKey);
                // 	on collision begin
                if (rigidBodyCollisionsLastFrame.get(rigidBodyCollisionKey) == null) {
                    rigidBody1.fireOnCollisionBegin(rigidBody2, collision);
                }
                // 	on collision
                rigidBody1.fireOnCollision(rigidBody2, collision);
                // unset sleeping if both non static and colliding
                if (rigidBody1.isStatic == false && rigidBody2.isStatic == false) {
                    rigidBody1.awake(true);
                    rigidBody2.awake(true);
                }
                // add constraint entity
                constraintsSolver.allocateConstraintsEntity().set(rigidBody1, rigidBody2, constraintsSolver.allocateCollision().fromResponse(collision));
            }
        }
    // System.out.println(rigidBody1.id + ":" + nearObjects);
    }
    //	check each collision last frame that disappeared in current frame
    for (Key key : rigidBodyCollisionsLastFrame.getKeysIterator()) {
        Key rigidBodyCollisionKey = rigidBodyCollisionsCurrentFrame.get(key);
        if (rigidBodyCollisionKey == null) {
            char[] keyData = key.getData();
            int rigidBodyIdx1 = 0;
            int rigidBodyIdx2 = 0;
            rigidBodyIdx1 += (int) keyData[0] << 0;
            rigidBodyIdx1 += (int) keyData[1] << 8;
            rigidBodyIdx1 += (int) keyData[2] << 16;
            rigidBodyIdx1 += (int) keyData[3] << 24;
            rigidBodyIdx2 += (int) keyData[5] << 0;
            rigidBodyIdx2 += (int) keyData[6] << 8;
            rigidBodyIdx2 += (int) keyData[7] << 16;
            rigidBodyIdx2 += (int) keyData[8] << 24;
            RigidBody rigidBody1 = rigidBodies.get(rigidBodyIdx1);
            RigidBody rigidBody2 = rigidBodies.get(rigidBodyIdx2);
            rigidBody1.fireOnCollisionEnd(rigidBody2);
        }
    }
    // swap rigid body collisions current and last frame
    Pool<Key> rigidBodyCollisionsKeyPoolTmp = rigidBodyCollisionsKeyPoolLastFrame;
    HashMap<Key, Key> rigidBodyCollisionsTmp = rigidBodyCollisionsLastFrame;
    rigidBodyCollisionsLastFrame = rigidBodyCollisionsCurrentFrame;
    rigidBodyCollisionsKeyPoolLastFrame = rigidBodyCollisionsKeyPoolCurrentFrame;
    rigidBodyCollisionsCurrentFrame = rigidBodyCollisionsTmp;
    rigidBodyCollisionsKeyPoolCurrentFrame = rigidBodyCollisionsKeyPoolTmp;
    // reset current frame
    rigidBodyCollisionsCurrentFrame.clear();
    rigidBodyCollisionsKeyPoolCurrentFrame.reset();
    // do the solving
    constraintsSolver.compute(deltaTime);
    constraintsSolver.updateAllBodies(deltaTime);
    constraintsSolver.reset();
    // update transformations for rigid body 
    for (int i = 0; i < rigidBodies.size(); i++) {
        RigidBody rigidBody = rigidBodies.get(i);
        // skip if enabled and remove partition
        if (rigidBody.enabled == false) {
            partition.removeRigidBody(rigidBody);
            continue;
        }
        // skip on static
        if (rigidBody.isStatic == true || rigidBody.isSleeping == true) {
            continue;
        }
        // set up transformations, keep care that only 3 rotations exists (x, y, z axis)
        Rotations rotations = rigidBody.transformations.getRotations();
        while (rotations.size() > 1) {
            rotations.remove(rotations.size() - 1);
        }
        while (rotations.size() < 1) {
            rotations.add(new Rotation());
        }
        // set up orientation
        rotations.get(0).fromQuaternion(rigidBody.orientation);
        rotations.get(0).getAxix().getArray()[1] *= -1f;
        //	second set up position
        Transformations transformations = rigidBody.transformations;
        transformations.getTranslation().set(rigidBody.position);
        // update
        transformations.update();
        // update bounding volume
        rigidBody.cbv.fromBoundingVolumeWithTransformations(rigidBody.obv, transformations);
        // update partition
        partition.updateRigidBody(rigidBody);
    }
}
Also used : Transformations(net.drewke.tdme.engine.Transformations) Rotation(net.drewke.tdme.engine.Rotation) Key(net.drewke.tdme.utils.Key) Rotations(net.drewke.tdme.engine.Rotations)

Example 7 with Transformations

use of net.drewke.tdme.engine.Transformations in project tdme by andreasdr.

the class EntityBoundingVolumeSubScreenController method onBoundingVolumeObbApply.

/**
	 * On bounding volume OBB apply
	 * @param entity
	 * @param idx
	 */
public void onBoundingVolumeObbApply(LevelEditorEntity entity, int idx) {
    try {
        // rotation axes by rotation angle for x,y,z
        Transformations rotations = new Transformations();
        rotations.getRotations().add(new Rotation(Tools.convertToFloat(boundingvolumeObbRotationZ[idx].getController().getValue().toString()), OrientedBoundingBox.AABB_AXIS_Z));
        rotations.getRotations().add(new Rotation(Tools.convertToFloat(boundingvolumeObbRotationY[idx].getController().getValue().toString()), OrientedBoundingBox.AABB_AXIS_Y));
        rotations.getRotations().add(new Rotation(Tools.convertToFloat(boundingvolumeObbRotationX[idx].getController().getValue().toString()), OrientedBoundingBox.AABB_AXIS_X));
        rotations.update();
        // extract axes from matrix
        Vector3 xAxis = new Vector3();
        Vector3 yAxis = new Vector3();
        Vector3 zAxis = new Vector3();
        rotations.getTransformationsMatrix().getAxes(xAxis, yAxis, zAxis);
        // delegate to view
        view.applyBoundingVolumeObb(entity, idx, Tools.convertToVector3(boundingvolumeObbCenter[idx].getController().getValue().toString()), xAxis, yAxis, zAxis, Tools.convertToVector3(boundingvolumeObbHalfextension[idx].getController().getValue().toString()));
    } catch (NumberFormatException nfe) {
        showErrorPopUp("Warning", "Invalid number entered");
    }
}
Also used : Transformations(net.drewke.tdme.engine.Transformations) Vector3(net.drewke.tdme.math.Vector3) Rotation(net.drewke.tdme.engine.Rotation)

Example 8 with Transformations

use of net.drewke.tdme.engine.Transformations in project tdme by andreasdr.

the class Tools method oseInit.

/**
	 * Init off screen engine for making thumbails
	 * @param drawable
	 */
public static void oseInit(GLAutoDrawable drawable) {
    osEngine = Engine.createOffScreenInstance(drawable, 128, 128);
    osEngine.setPartition(new PartitionNone());
    setDefaultLight(osEngine.getLightAt(0));
    oseScale = 0.75f;
    oseLookFromRotations = new Transformations();
    oseLookFromRotations.getRotations().add(new Rotation(-45f, new Vector3(0f, 1f, 0f)));
    oseLookFromRotations.getRotations().add(new Rotation(-45f, new Vector3(1f, 0f, 0f)));
    oseLookFromRotations.getRotations().add(new Rotation(0f, new Vector3(0f, 0f, 1f)));
    oseLookFromRotations.update();
}
Also used : PartitionNone(net.drewke.tdme.engine.PartitionNone) Transformations(net.drewke.tdme.engine.Transformations) Vector3(net.drewke.tdme.math.Vector3) Rotation(net.drewke.tdme.engine.Rotation)

Example 9 with Transformations

use of net.drewke.tdme.engine.Transformations in project tdme by andreasdr.

the class DAEReader method readLevel.

/**
	 * Reads Collada DAE file level
	 * @param path name
	 * @param file name
	 * @throws Exception
	 * @return Model instance
	 */
public static LevelEditorLevel readLevel(String pathName, String fileName) throws Exception {
    // (re)create tm files folder
    File tmFilesFolder = new File(pathName + "/" + fileName + "-models");
    if (tmFilesFolder.exists()) {
        tmFilesFolder.delete();
    }
    tmFilesFolder.mkdir();
    // create level
    LevelEditorLevel levelEditorLevel = new LevelEditorLevel();
    LevelPropertyPresets.getInstance().setDefaultLevelProperties(levelEditorLevel);
    // load dae xml document
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = builder.parse(FileSystem.getInstance().getInputStream(pathName, fileName));
    Element xmlRoot = document.getDocumentElement();
    // authoring tool
    AuthoringTool authoringTool = getAuthoringTool(xmlRoot);
    // up vector and rotation order
    UpVector upVector = getUpVector(xmlRoot);
    RotationOrder rotationOrder = null;
    switch(upVector) {
        case Y_UP:
            rotationOrder = RotationOrder.ZYX;
        case Z_UP:
            rotationOrder = RotationOrder.YZX;
    }
    levelEditorLevel.setRotationOrder(rotationOrder);
    // parse scene from xml
    String xmlSceneId = null;
    Element xmlScene = getChildrenByTagName(xmlRoot, "scene").get(0);
    for (Element xmlInstanceVisualscene : getChildrenByTagName(xmlScene, "instance_visual_scene")) {
        xmlSceneId = xmlInstanceVisualscene.getAttribute("url").substring(1);
    }
    // check for xml scene id
    if (xmlSceneId == null) {
        throw new ModelFileIOException("No scene id found");
    }
    // parse visual scenes
    Element xmlLibraryVisualScenes = getChildrenByTagName(xmlRoot, "library_visual_scenes").get(0);
    for (Element xmlLibraryVisualScene : getChildrenByTagName(xmlLibraryVisualScenes, "visual_scene")) {
        String xmlVisualSceneId = xmlLibraryVisualScene.getAttribute("id");
        if (xmlVisualSceneId.equals(xmlSceneId)) {
            // default FPS
            float fps = 30f;
            // parse frames per second
            List<Element> xmlExtraNodes = getChildrenByTagName(xmlLibraryVisualScene, "extra");
            if (xmlExtraNodes.isEmpty() == false) {
                Element xmlExtraNode = xmlExtraNodes.get(0);
                for (Element xmlTechnique : getChildrenByTagName(xmlExtraNode, "technique")) {
                    List<Element> xmlFrameRateNodes = getChildrenByTagName(xmlTechnique, "frame_rate");
                    if (xmlFrameRateNodes.isEmpty() == false) {
                        fps = Float.parseFloat(xmlFrameRateNodes.get(0).getTextContent());
                        break;
                    }
                }
            }
            // visual scene root nodes
            LevelEditorEntityLibrary entityLibrary = levelEditorLevel.getEntityLibrary();
            LevelEditorEntity emptyEntity = null;
            int nodeIdx = 0;
            for (Element xmlNode : getChildrenByTagName(xmlLibraryVisualScene, "node")) {
                // derive model name from node id
                String modelName = xmlNode.getAttribute("id");
                // replace blender _|-NUMBER, not sure if this is a good idea for all cases, we will see
                modelName = modelName.replaceAll("[\\-\\_]{1}+[0-9]+$", "");
                // replace number at the end still, not sure if this is a good idea for all cases, we will see
                modelName = modelName.replaceAll("[0-9]+$", "");
                // check if name is available, if not extend with numbers :DDD
                boolean haveName = entityLibrary.getEntityCount() == 0;
                if (haveName == false) {
                    for (int i = 0; i < 10000; i++) {
                        haveName = true;
                        String modelNameTry = modelName + (i == 0 ? "" : String.valueOf(i));
                        for (int entityIdx = 0; entityIdx < entityLibrary.getEntityCount(); entityIdx++) {
                            LevelEditorEntity entity = entityLibrary.getEntityAt(entityIdx);
                            if (entity.getName().equals(modelNameTry) == true) {
                                haveName = false;
                                break;
                            }
                        }
                        if (haveName == true) {
                            modelName = modelNameTry;
                            break;
                        }
                    }
                }
                // do we have a name now?
                if (haveName == false) {
                    // nope, cant imagine this will happen 
                    System.out.println("DAEReader::readLevel(): Skipping model '" + modelName + "' as no name could be created for it.");
                    continue;
                }
                // 	create model
                Model model = new Model(pathName + File.separator + fileName + '-' + modelName, fileName + '-' + modelName, upVector, rotationOrder, null);
                // import matrix
                setupModelImportRotationMatrix(xmlRoot, model);
                Matrix4x4 modelImportRotationMatrix = new Matrix4x4(model.getImportTransformationsMatrix());
                setupModelImportScaleMatrix(xmlRoot, model);
                // translation, scaling, rotation
                Vector3 translation = new Vector3();
                Vector3 scale = new Vector3();
                Vector3 rotation = new Vector3();
                Vector3 xAxis = new Vector3();
                Vector3 yAxis = new Vector3();
                Vector3 zAxis = new Vector3();
                // set up local transformations matrix
                Matrix4x4 nodeTransformationsMatrix = null;
                List<Element> xmlMatrixElements = getChildrenByTagName(xmlNode, "matrix");
                if (xmlMatrixElements.size() == 1) {
                    String xmlMatrix = xmlMatrixElements.get(0).getTextContent();
                    StringTokenizer t = new StringTokenizer(xmlMatrix, " \n\r");
                    // 
                    nodeTransformationsMatrix = new Matrix4x4(Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken())).transpose();
                }
                // check if we have node transformations matrix
                if (nodeTransformationsMatrix == null) {
                    throw new ModelFileIOException("missing node transformations matrix for node " + xmlNode.getAttribute("id"));
                }
                // extract coordinate system axes
                nodeTransformationsMatrix.getAxes(xAxis, yAxis, zAxis);
                nodeTransformationsMatrix.getTranslation(translation);
                nodeTransformationsMatrix.getScale(scale);
                // normalize coordinate axes
                xAxis.normalize();
                yAxis.normalize();
                zAxis.normalize();
                // write back normalized x axis
                nodeTransformationsMatrix.setAxes(xAxis, yAxis, zAxis);
                // TODO: move me into Matrix4x4 decomposing code?
                if ((upVector == UpVector.Y_UP && Vector3.computeDotProduct(Vector3.computeCrossProduct(xAxis, yAxis), zAxis) < 0.0f) || (upVector == UpVector.Z_UP && Vector3.computeDotProduct(Vector3.computeCrossProduct(xAxis, zAxis), yAxis) < 0.0f)) {
                    // negate axes
                    xAxis.scale(-1f);
                    yAxis.scale(-1f);
                    zAxis.scale(-1f);
                    // and write back to node transformation matrices
                    nodeTransformationsMatrix.setAxes(xAxis, yAxis, zAxis);
                    // scale
                    scale.scale(-1f);
                }
                // determine rotation
                nodeTransformationsMatrix.computeEulerAngles(rotation);
                // apply model import matrix
                modelImportRotationMatrix.multiply(scale, scale);
                modelImportRotationMatrix.multiply(rotation, rotation);
                model.getImportTransformationsMatrix().multiply(translation, translation);
                // set up frames per seconds
                model.setFPS(fps);
                // read sub groups
                Group group = readVisualSceneNode(authoringTool, pathName, model, null, xmlRoot, xmlNode, fps);
                if (group != null) {
                    group.getTransformationsMatrix().identity();
                    model.getSubGroups().put(group.getId(), group);
                    model.getGroups().put(group.getId(), group);
                }
                // set up joints
                ModelHelper.setupJoints(model);
                // fix animation length
                ModelHelper.fixAnimationLength(model);
                // prepare for indexed rendering
                ModelHelper.prepareForIndexedRendering(model);
                // check if empty model
                EntityType entityType = EntityType.MODEL;
                ModelStatistics modelStatistics = ModelUtilities.computeModelStatistics(model);
                if (modelStatistics.getOpaqueFaceCount() == 0 && modelStatistics.getTransparentFaceCount() == 0) {
                    entityType = EntityType.EMPTY;
                }
                // level editor entity
                LevelEditorEntity levelEditorEntity = null;
                // model
                if (entityType == EntityType.MODEL) {
                    // check if we have that model already
                    for (int i = 0; i < levelEditorLevel.getEntityLibrary().getEntityCount(); i++) {
                        LevelEditorEntity levelEditorEntityCompare = levelEditorLevel.getEntityLibrary().getEntityAt(i);
                        if (levelEditorEntityCompare.getType() != EntityType.MODEL)
                            continue;
                        if (ModelUtilities.equals(model, levelEditorEntityCompare.getModel()) == true) {
                            levelEditorEntity = levelEditorEntityCompare;
                            break;
                        }
                    }
                    // create level editor model, if not yet exists
                    if (levelEditorEntity == null) {
                        // save model
                        TMWriter.write(model, pathName + "/" + fileName + "-models", modelName + ".tm");
                        // create level editor entity
                        levelEditorEntity = entityLibrary.addModel(nodeIdx++, modelName, modelName, pathName + "/" + fileName + "-models", modelName + ".tm", new Vector3());
                    }
                } else // empty
                if (entityType == EntityType.EMPTY) {
                    if (emptyEntity == null) {
                        emptyEntity = entityLibrary.addEmpty(nodeIdx++, "Default Empty", "");
                    }
                    levelEditorEntity = emptyEntity;
                } else {
                    System.out.println("DAEReader::readLevel(): unknown entity type. Skipping");
                    continue;
                }
                // level editor object transformations
                Transformations levelEditorObjectTransformations = new Transformations();
                levelEditorObjectTransformations.getTranslation().set(translation);
                levelEditorObjectTransformations.getRotations().add(new Rotation(rotation.getArray()[rotationOrder.getAxis0VectorIndex()], rotationOrder.getAxis0()));
                levelEditorObjectTransformations.getRotations().add(new Rotation(rotation.getArray()[rotationOrder.getAxis1VectorIndex()], rotationOrder.getAxis1()));
                levelEditorObjectTransformations.getRotations().add(new Rotation(rotation.getArray()[rotationOrder.getAxis2VectorIndex()], rotationOrder.getAxis2()));
                levelEditorObjectTransformations.getScale().set(scale);
                levelEditorObjectTransformations.update();
                // level editor object
                LevelEditorObject object = new LevelEditorObject(xmlNode.getAttribute("id"), xmlNode.getAttribute("id"), levelEditorObjectTransformations, levelEditorEntity);
                // add object to level
                levelEditorLevel.addObject(object);
            }
        }
    }
    // save level
    LevelFileExport.export(pathName + "/" + fileName + ".tl", levelEditorLevel);
    //
    return levelEditorLevel;
}
Also used : Group(net.drewke.tdme.engine.model.Group) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) ModelStatistics(net.drewke.tdme.engine.subsystems.object.ModelUtilitiesInternal.ModelStatistics) LevelEditorObject(net.drewke.tdme.tools.shared.model.LevelEditorObject) LevelEditorEntity(net.drewke.tdme.tools.shared.model.LevelEditorEntity) UpVector(net.drewke.tdme.engine.model.Model.UpVector) Vector3(net.drewke.tdme.math.Vector3) Rotation(net.drewke.tdme.engine.Rotation) Joint(net.drewke.tdme.engine.model.Joint) Matrix4x4(net.drewke.tdme.math.Matrix4x4) EntityType(net.drewke.tdme.tools.shared.model.LevelEditorEntity.EntityType) LevelEditorEntityLibrary(net.drewke.tdme.tools.shared.model.LevelEditorEntityLibrary) StringTokenizer(java.util.StringTokenizer) LevelEditorLevel(net.drewke.tdme.tools.shared.model.LevelEditorLevel) DocumentBuilder(javax.xml.parsers.DocumentBuilder) RotationOrder(net.drewke.tdme.engine.model.RotationOrder) Model(net.drewke.tdme.engine.model.Model) Transformations(net.drewke.tdme.engine.Transformations) File(java.io.File)

Example 10 with Transformations

use of net.drewke.tdme.engine.Transformations in project tdme by andreasdr.

the class LevelEditorView method placeObject.

/**
	 * Places selected model on given object
	 */
public void placeObject(Entity selectedObject) {
    if (selectedEntity != null && selectedObject != null) {
        // get selected level entity if it is one
        LevelEditorObject selectedLevelEditorObject = level.getObjectById(selectedObject.getId());
        // create level entity
        Transformations levelEditorObjectTransformations = new Transformations();
        // take translation of selected object as base
        levelEditorObjectTransformations.getTranslation().set(selectedObject.getTranslation());
        Vector3 centerSelectedObject = selectedObject.getBoundingBox().getMin().clone().add(selectedObject.getBoundingBox().getMax()).scale(0.5f);
        // compute center of selected model
        Vector3 centerNewObject = selectedEntity.getModel() != null ? selectedEntity.getModel().getBoundingBox().getCenter().clone() : new Vector3(0f, 0f, 0f);
        // put new object on middle of selected object
        levelEditorObjectTransformations.getTranslation().add(centerNewObject.clone().add(centerSelectedObject));
        // set on selected object / y
        if (selectedLevelEditorObject == null || selectedLevelEditorObject.getEntity().getType() == EntityType.PARTICLESYSTEM || selectedEntity.getType() == EntityType.PARTICLESYSTEM) {
            levelEditorObjectTransformations.getTranslation().setY(gridY + (selectedEntity.getModel() != null ? -selectedEntity.getModel().getBoundingBox().getMin().getY() : 0f));
        } else {
            // create transformed level editor object bounding box
            BoundingVolume bv = selectedLevelEditorObject.getEntity().getModel().getBoundingBox().clone();
            bv.fromBoundingVolumeWithTransformations(selectedLevelEditorObject.getEntity().getModel().getBoundingBox(), selectedLevelEditorObject.getTransformations());
            //
            levelEditorObjectTransformations.getTranslation().setY(bv.computeDimensionOnAxis(new Vector3(0f, 1f, 0f)) / 2 + bv.getCenter().getY() + -selectedEntity.getModel().getBoundingBox().getMin().getY());
        }
        // standard scale
        levelEditorObjectTransformations.getScale().set(new Vector3(1f, 1f, 1f));
        // standard rotations
        levelEditorObjectTransformations.getPivot().set(selectedEntity.getPivot());
        levelEditorObjectTransformations.getRotations().add(new Rotation(0f, level.getRotationOrder().getAxis0()));
        levelEditorObjectTransformations.getRotations().add(new Rotation(0f, level.getRotationOrder().getAxis1()));
        levelEditorObjectTransformations.getRotations().add(new Rotation(0f, level.getRotationOrder().getAxis2()));
        levelEditorObjectTransformations.update();
        // check if entity already exists
        for (int i = 0; i < level.getObjectCount(); i++) {
            LevelEditorObject levelEditorObject = level.getObjectAt(i);
            if (levelEditorObject.getEntity() == selectedEntity && levelEditorObject.getTransformations().getTranslation().equals(levelEditorObjectTransformations.getTranslation())) {
                // we already have a object with selected model on this translation
                return;
            }
        }
        // create new level editor object
        LevelEditorObject levelEditorObject = new LevelEditorObject(selectedEntity.getName() + "_" + level.allocateObjectId(), "", levelEditorObjectTransformations, selectedEntity);
        //	add to level
        level.addObject(levelEditorObject);
        // add model to 3d engine
        if (levelEditorObject.getEntity().getModel() != null) {
            Object3D object = new Object3D(levelEditorObject.getId(), levelEditorObject.getEntity().getModel());
            object.fromTransformations(levelEditorObjectTransformations);
            object.setPickable(true);
            engine.addEntity(object);
        }
        // add particle system to 3d engine
        if (levelEditorObject.getEntity().getType() == EntityType.PARTICLESYSTEM) {
            Entity object = Level.createParticleSystem(levelEditorObject.getEntity().getParticleSystem(), levelEditorObject.getId(), false);
            object.fromTransformations(levelEditorObjectTransformations);
            object.setPickable(true);
            engine.addEntity(object);
        }
        // add to objects listbox
        levelEditorScreenController.setObjectListbox(level.getObjectIdsIterator());
    }
}
Also used : Entity(net.drewke.tdme.engine.Entity) LevelEditorEntity(net.drewke.tdme.tools.shared.model.LevelEditorEntity) FacesEntity(net.drewke.tdme.engine.model.FacesEntity) BoundingVolume(net.drewke.tdme.engine.primitives.BoundingVolume) Transformations(net.drewke.tdme.engine.Transformations) Vector3(net.drewke.tdme.math.Vector3) LevelEditorObject(net.drewke.tdme.tools.shared.model.LevelEditorObject) Rotation(net.drewke.tdme.engine.Rotation) Object3D(net.drewke.tdme.engine.Object3D)

Aggregations

Transformations (net.drewke.tdme.engine.Transformations)10 Rotation (net.drewke.tdme.engine.Rotation)8 Vector3 (net.drewke.tdme.math.Vector3)7 LevelEditorObject (net.drewke.tdme.tools.shared.model.LevelEditorObject)6 LevelEditorEntity (net.drewke.tdme.tools.shared.model.LevelEditorEntity)5 File (java.io.File)3 Object3D (net.drewke.tdme.engine.Object3D)3 BoundingVolume (net.drewke.tdme.engine.primitives.BoundingVolume)3 IOException (java.io.IOException)2 Entity (net.drewke.tdme.engine.Entity)2 FacesEntity (net.drewke.tdme.engine.model.FacesEntity)2 Model (net.drewke.tdme.engine.model.Model)2 LevelEditorEntityLibrary (net.drewke.tdme.tools.shared.model.LevelEditorEntityLibrary)2 LevelEditorLight (net.drewke.tdme.tools.shared.model.LevelEditorLight)2 PropertyModelClass (net.drewke.tdme.tools.shared.model.PropertyModelClass)2 JSONArray (org.json.JSONArray)2 JSONObject (org.json.JSONObject)2 FileOutputStream (java.io.FileOutputStream)1 InputStream (java.io.InputStream)1 PrintStream (java.io.PrintStream)1