Example usage for org.jdom2 Element getName

List of usage examples for org.jdom2 Element getName

Introduction

In this page you can find the example usage for org.jdom2 Element getName.

Prototype

public String getName() 

Source Link

Document

Returns the (local) name of the element (without any namespace prefix).

Usage

From source file:com.abyala.decisiontree.SimpleDecisionTreeParser.java

License:Open Source License

private ResultAttribute parseResultAttribute(final Element element, final Method method)
        throws DecisionTreeParserException {
    final String elementType = element.getName();
    final String attributeName = element.getAttributeValue("name");
    if ("string-attribute".equals(elementType)) {
        return parseResultStringAttribute(element, attributeName, method);
    } else if ("boolean-attribute".equals(elementType)) {
        return parseResultBooleanAttribute(element, attributeName, method);
    } else if ("text-attribute".equals(elementType)) {
        return parseResultTextAttribute(element, attributeName, method);
    } else if ("integer-attribute".equals(elementType)) {
        return parseResultIntegerAttribute(element, attributeName, method);
    } else {//from www  .  j  av  a 2 s. co  m
        throw new DecisionTreeParserException("Unknown result attribute type: " + elementType);
    }
}

From source file:com.abyala.decisiontree.SimpleDecisionTreeParser.java

License:Open Source License

private String getInputName(final String path, final List<Element> children)
        throws DecisionTreeParserException {
    if (children.isEmpty())
        throw new DecisionTreeParserException("Node at path " + path + " has no children");

    final Set<String> inputTypes = new HashSet<String>();
    for (Element element : children) {
        inputTypes.add(element.getName());
    }//from   w  w  w.  j  a va  2 s  .  co m

    if (inputTypes.size() != 1) {
        throw new DecisionTreeParserException("Node at path " + path + " must have only one child type.");
    } else {
        return inputTypes.iterator().next();
    }
}

From source file:com.abyala.decisiontree.SimpleDecisionTreeParser.java

License:Open Source License

private InputType parseInputType(final Element typeElement) throws DecisionTreeParserException {
    final String typeName = typeElement.getName();
    if ("string-type".equals(typeName)) {
        return parseStringInputType(typeElement);
    } else if ("integer-type".equals(typeName)) {
        return parseIntegerInputType(typeElement);
    } else if ("boolean-type".equals(typeName)) {
        return parseBooleanInputType(typeElement);
    } else {/*from  w  w w .  ja va 2  s  . c  o  m*/
        throw new DecisionTreeParserException("Unknown input-type: " + typeName);
    }
}

From source file:com.ardor3d.extension.model.collada.jdom.ColladaAnimUtils.java

License:Open Source License

/**
 * Construct skin mesh(es) from the skin element and attach them (under a single new Node) to the given parent Node.
 * //  w  ww .j  a  v a2s  .c o m
 * @param ardorParentNode
 *            Ardor3D Node to attach our skin node to.
 * @param instanceController
 *            the <instance_controller> element. We'll parse the skeleton reference from here.
 * @param controller
 *            the referenced <controller> element. Used for naming purposes.
 * @param skin
 *            our <skin> element.
 */
@SuppressWarnings("unchecked")
private void buildSkinMeshes(final Node ardorParentNode, final Element instanceController,
        final Element controller, final Element skin) {
    final String skinSource = skin.getAttributeValue("source");

    final Element skinNodeEL = _colladaDOMUtil.findTargetWithId(skinSource);
    if (skinNodeEL == null || !"geometry".equals(skinNodeEL.getName())) {
        throw new ColladaException(
                "Expected a mesh for skin source with url: " + skinSource + " got instead: " + skinNodeEL,
                skin);
    }

    final Element geometry = skinNodeEL;

    final Node meshNode = _colladaMeshUtils.buildMesh(geometry);
    if (meshNode != null) {
        // Look for skeleton entries in the original <instance_controller> element
        final List<Element> skeletonRoots = Lists.newArrayList();
        for (final Element sk : instanceController.getChildren("skeleton")) {
            final Element skroot = _colladaDOMUtil.findTargetWithId(sk.getText());
            if (skroot != null) {
                // add as a possible root for when we need to locate a joint by name later.
                skeletonRoots.add(skroot);
            } else {
                throw new ColladaException(
                        "Unable to find node with id: " + sk.getText() + ", referenced from skeleton " + sk,
                        sk);
            }
        }

        // Read in our joints node
        final Element jointsEL = skin.getChild("joints");
        if (jointsEL == null) {
            throw new ColladaException("skin found without joints.", skin);
        }

        // Pull out our joint names and bind matrices
        final List<String> jointNames = Lists.newArrayList();
        final List<Transform> bindMatrices = Lists.newArrayList();
        final List<ColladaInputPipe.ParamType> paramTypes = Lists.newArrayList();

        for (final Element inputEL : jointsEL.getChildren("input")) {
            final ColladaInputPipe pipe = new ColladaInputPipe(_colladaDOMUtil, inputEL);
            final ColladaInputPipe.SourceData sd = pipe.getSourceData();
            if (pipe.getType() == ColladaInputPipe.Type.JOINT) {
                final String[] namesData = sd.stringArray;
                for (int i = sd.offset; i < namesData.length; i += sd.stride) {
                    jointNames.add(namesData[i]);
                    paramTypes.add(sd.paramType);
                }
            } else if (pipe.getType() == ColladaInputPipe.Type.INV_BIND_MATRIX) {
                final float[] floatData = sd.floatArray;
                final FloatBuffer source = BufferUtils.createFloatBufferOnHeap(16);
                for (int i = sd.offset; i < floatData.length; i += sd.stride) {
                    source.rewind();
                    source.put(floatData, i, 16);
                    source.flip();
                    final Matrix4 mat = new Matrix4().fromFloatBuffer(source);
                    bindMatrices.add(new Transform().fromHomogeneousMatrix(mat));
                }
            }
        }

        // Use the skeleton information from the instance_controller to set the parent array locations on the
        // joints.
        Skeleton ourSkeleton = null; // TODO: maybe not the best way. iterate
        final int[] order = new int[jointNames.size()];
        for (int i = 0; i < jointNames.size(); i++) {
            final String name = jointNames.get(i);
            final ParamType paramType = paramTypes.get(i);
            final String searcher = paramType == ParamType.idref_param ? "id" : "sid";
            Element found = null;
            for (final Element root : skeletonRoots) {
                if (name.equals(root.getAttributeValue(searcher))) {
                    found = root;
                } else if (paramType == ParamType.idref_param) {
                    found = _colladaDOMUtil.findTargetWithId(name);
                } else {
                    found = (Element) _colladaDOMUtil.selectSingleNode(root, ".//*[@sid='" + name + "']");
                }

                // Last resorts (bad exporters)
                if (found == null) {
                    found = _colladaDOMUtil.findTargetWithId(name);
                }
                if (found == null) {
                    found = (Element) _colladaDOMUtil.selectSingleNode(root, ".//*[@name='" + name + "']");
                }

                if (found != null) {
                    break;
                }
            }
            if (found == null) {
                if (paramType == ParamType.idref_param) {
                    found = _colladaDOMUtil.findTargetWithId(name);
                } else {
                    found = (Element) _colladaDOMUtil.selectSingleNode(geometry,
                            "/*//visual_scene//*[@sid='" + name + "']");
                }

                // Last resorts (bad exporters)
                if (found == null) {
                    found = _colladaDOMUtil.findTargetWithId(name);
                }
                if (found == null) {
                    found = (Element) _colladaDOMUtil.selectSingleNode(geometry,
                            "/*//visual_scene//*[@name='" + name + "']");
                }

                if (found == null) {
                    throw new ColladaException("Unable to find joint with " + searcher + ": " + name, skin);
                }
            }

            final Joint joint = _dataCache.getElementJointMapping().get(found);
            if (joint == null) {
                logger.warning("unable to parse joint for: " + found.getName() + " " + name);
                return;
            }
            joint.setInverseBindPose(bindMatrices.get(i));

            ourSkeleton = _dataCache.getJointSkeletonMapping().get(joint);
            order[i] = joint.getIndex();
        }

        // Make our skeleton pose
        SkeletonPose skPose = _dataCache.getSkeletonPoseMapping().get(ourSkeleton);
        if (skPose == null) {
            skPose = new SkeletonPose(ourSkeleton);
            _dataCache.getSkeletonPoseMapping().put(ourSkeleton, skPose);

            // attach any attachment points found for the skeleton's joints
            addAttachments(skPose);

            // Skeleton's default to bind position, so update the global transforms.
            skPose.updateTransforms();
        }

        // Read in our vertex_weights node
        final Element weightsEL = skin.getChild("vertex_weights");
        if (weightsEL == null) {
            throw new ColladaException("skin found without vertex_weights.", skin);
        }

        // Pull out our per vertex joint indices and weights
        final List<Short> jointIndices = Lists.newArrayList();
        final List<Float> jointWeights = Lists.newArrayList();
        int indOff = 0, weightOff = 0;

        int maxOffset = 0;
        for (final Element inputEL : weightsEL.getChildren("input")) {
            final ColladaInputPipe pipe = new ColladaInputPipe(_colladaDOMUtil, inputEL);
            final ColladaInputPipe.SourceData sd = pipe.getSourceData();
            if (pipe.getOffset() > maxOffset) {
                maxOffset = pipe.getOffset();
            }
            if (pipe.getType() == ColladaInputPipe.Type.JOINT) {
                indOff = pipe.getOffset();
                final String[] namesData = sd.stringArray;
                for (int i = sd.offset; i < namesData.length; i += sd.stride) {
                    // XXX: the Collada spec says this could be -1?
                    final String name = namesData[i];
                    final int index = jointNames.indexOf(name);
                    if (index >= 0) {
                        jointIndices.add((short) index);
                    } else {
                        throw new ColladaException("Unknown joint accessed: " + name, inputEL);
                    }
                }
            } else if (pipe.getType() == ColladaInputPipe.Type.WEIGHT) {
                weightOff = pipe.getOffset();
                final float[] floatData = sd.floatArray;
                for (int i = sd.offset; i < floatData.length; i += sd.stride) {
                    jointWeights.add(floatData[i]);
                }
            }
        }

        // Pull our values array
        int firstIndex = 0, count = 0;
        final int[] vals = _colladaDOMUtil.parseIntArray(weightsEL.getChild("v"));
        try {
            count = weightsEL.getAttribute("count").getIntValue();
        } catch (final DataConversionException e) {
            throw new ColladaException("Unable to parse count attribute.", weightsEL);
        }
        // use the vals to fill our vert weight map
        final int[][] vertWeightMap = new int[count][];
        int index = 0;
        for (final int length : _colladaDOMUtil.parseIntArray(weightsEL.getChild("vcount"))) {
            final int[] entry = new int[(maxOffset + 1) * length];
            vertWeightMap[index++] = entry;

            System.arraycopy(vals, (maxOffset + 1) * firstIndex, entry, 0, entry.length);

            firstIndex += length;
        }

        // Create a record for the global ColladaStorage.
        final String storeName = getSkinStoreName(instanceController, controller);
        final SkinData skinDataStore = new SkinData(storeName);
        // add pose to store
        skinDataStore.setPose(skPose);

        // Create a base Node for our skin meshes
        final Node skinNode = new Node(meshNode.getName());
        // copy Node render states across.
        copyRenderStates(meshNode, skinNode);
        // add node to store
        skinDataStore.setSkinBaseNode(skinNode);

        // Grab the bind_shape_matrix from skin
        final Element bindShapeMatrixEL = skin.getChild("bind_shape_matrix");
        final Transform bindShapeMatrix = new Transform();
        if (bindShapeMatrixEL != null) {
            final double[] array = _colladaDOMUtil.parseDoubleArray(bindShapeMatrixEL);
            bindShapeMatrix.fromHomogeneousMatrix(new Matrix4().fromArray(array));
        }

        // Visit our Node and pull out any Mesh children. Turn them into SkinnedMeshes
        for (final Spatial spat : meshNode.getChildren()) {
            if (spat instanceof Mesh && ((Mesh) spat).getMeshData().getVertexCount() > 0) {
                final Mesh sourceMesh = (Mesh) spat;
                final SkinnedMesh skMesh = new SkinnedMesh(sourceMesh.getName());
                skMesh.setCurrentPose(skPose);

                // copy material info mapping for later use
                final String material = _dataCache.getMeshMaterialMap().get(sourceMesh);
                _dataCache.getMeshMaterialMap().put(skMesh, material);

                // copy mesh render states across.
                copyRenderStates(sourceMesh, skMesh);

                // copy hints across
                skMesh.getSceneHints().set(sourceMesh.getSceneHints());

                try {
                    // Use source mesh as bind pose data in the new SkinnedMesh
                    final MeshData bindPose = copyMeshData(sourceMesh.getMeshData());
                    skMesh.setBindPoseData(bindPose);

                    // Apply our BSM
                    if (!bindShapeMatrix.isIdentity()) {
                        bindPose.transformVertices(bindShapeMatrix);
                        if (bindPose.getNormalBuffer() != null) {
                            bindPose.transformNormals(bindShapeMatrix, true);
                        }
                    }

                    // TODO: This is only needed for CPU skinning... consider a way of making it optional.
                    // Copy bind pose to mesh data to setup for CPU skinning
                    final MeshData meshData = copyMeshData(skMesh.getBindPoseData());
                    meshData.getVertexCoords().setVboAccessMode(VBOAccessMode.StreamDraw);
                    if (meshData.getNormalCoords() != null) {
                        meshData.getNormalCoords().setVboAccessMode(VBOAccessMode.StreamDraw);
                    }
                    skMesh.setMeshData(meshData);
                } catch (final IOException e) {
                    e.printStackTrace();
                    throw new ColladaException("Unable to copy skeleton bind pose data.", geometry);
                }

                // Grab the MeshVertPairs from Global for this mesh.
                final Collection<MeshVertPairs> vertPairsList = _dataCache.getVertMappings().get(geometry);
                MeshVertPairs pairsMap = null;
                if (vertPairsList != null) {
                    for (final MeshVertPairs pairs : vertPairsList) {
                        if (pairs.getMesh() == sourceMesh) {
                            pairsMap = pairs;
                            break;
                        }
                    }
                }

                if (pairsMap == null) {
                    throw new ColladaException("Unable to locate pair map for geometry.", geometry);
                }

                // Check for a remapping, if we optimized geometry
                final VertMap vertMap = _dataCache.getMeshVertMap().get(sourceMesh);

                // Use pairs map and vertWeightMap to build our weights and joint indices.
                {
                    // count number of weights used
                    int maxWeightsPerVert = 0;
                    int weightCount;
                    for (final int originalIndex : pairsMap.getIndices()) {
                        weightCount = 0;

                        // get weights and joints at original index and add weights up to get divisor sum
                        // we'll assume 0's for vertices with no matching weight.
                        if (vertWeightMap.length > originalIndex) {
                            final int[] data = vertWeightMap[originalIndex];
                            for (int i = 0; i < data.length; i += maxOffset + 1) {
                                final float weight = jointWeights.get(data[i + weightOff]);
                                if (weight != 0) {
                                    weightCount++;
                                }
                            }
                            if (weightCount > maxWeightsPerVert) {
                                maxWeightsPerVert = weightCount;
                            }
                        }
                    }

                    final int verts = skMesh.getMeshData().getVertexCount();
                    final FloatBuffer weightBuffer = BufferUtils.createFloatBuffer(verts * maxWeightsPerVert);
                    final ShortBuffer jointIndexBuffer = BufferUtils
                            .createShortBuffer(verts * maxWeightsPerVert);
                    int j;
                    float sum = 0;
                    final float[] weights = new float[maxWeightsPerVert];
                    final short[] indices = new short[maxWeightsPerVert];
                    int originalIndex;
                    for (int x = 0; x < verts; x++) {
                        if (vertMap != null) {
                            originalIndex = pairsMap.getIndices()[vertMap.getFirstOldIndex(x)];
                        } else {
                            originalIndex = pairsMap.getIndices()[x];
                        }

                        j = 0;
                        sum = 0;

                        // get weights and joints at original index and add weights up to get divisor sum
                        // we'll assume 0's for vertices with no matching weight.
                        if (vertWeightMap.length > originalIndex) {
                            final int[] data = vertWeightMap[originalIndex];
                            for (int i = 0; i < data.length; i += maxOffset + 1) {
                                final float weight = jointWeights.get(data[i + weightOff]);
                                if (weight != 0) {
                                    weights[j] = jointWeights.get(data[i + weightOff]);
                                    indices[j] = (short) order[jointIndices.get(data[i + indOff])];
                                    sum += weights[j++];
                                }
                            }
                        }
                        // add extra padding as needed
                        while (j < maxWeightsPerVert) {
                            weights[j] = 0;
                            indices[j++] = 0;
                        }
                        // add weights to weightBuffer / sum
                        for (final float w : weights) {
                            weightBuffer.put(sum != 0 ? w / sum : 0);
                        }
                        // add joint indices to jointIndexBuffer
                        jointIndexBuffer.put(indices);
                    }

                    final float[] totalWeights = new float[weightBuffer.capacity()];
                    weightBuffer.flip();
                    weightBuffer.get(totalWeights);
                    skMesh.setWeights(totalWeights);

                    final short[] totalIndices = new short[jointIndexBuffer.capacity()];
                    jointIndexBuffer.flip();
                    jointIndexBuffer.get(totalIndices);
                    skMesh.setJointIndices(totalIndices);

                    skMesh.setWeightsPerVert(maxWeightsPerVert);
                }

                // add to the skinNode.
                skinNode.attachChild(skMesh);

                // Manually apply our bind pose to the skin mesh.
                skMesh.applyPose();

                // Update the model bounding.
                skMesh.updateModelBound();

                // add mesh to store
                skinDataStore.getSkins().add(skMesh);
            }
        }

        // add to Node
        ardorParentNode.attachChild(skinNode);

        // Add skin record to storage.
        _colladaStorage.getSkins().add(skinDataStore);
    }
}

From source file:com.ardor3d.extension.model.collada.jdom.ColladaAnimUtils.java

License:Open Source License

/**
 * Construct morph mesh(es) from the <morph> element and attach them (under a single new Node) to the given parent
 * Node.//  ww  w.  j  av a 2 s .  co  m
 * 
 * Note: This method current does not do anything but attach the referenced mesh since Ardor3D does not yet support
 * morph target animation.
 * 
 * @param ardorParentNode
 *            Ardor3D Node to attach our morph mesh to.
 * @param controller
 *            the referenced <controller> element. Used for naming purposes.
 * @param morph
 *            our <morph> element
 */
private void buildMorphMeshes(final Node ardorParentNode, final Element controller, final Element morph) {
    final String skinSource = morph.getAttributeValue("source");

    final Element skinNode = _colladaDOMUtil.findTargetWithId(skinSource);
    if (skinNode == null || !"geometry".equals(skinNode.getName())) {
        throw new ColladaException("Expected a mesh for morph source with url: " + skinSource
                + " (line number is referring morph)", morph);
    }

    final Element geometry = skinNode;

    final Spatial baseMesh = _colladaMeshUtils.buildMesh(geometry);

    // TODO: support morph animations someday.
    if (logger.isLoggable(Level.WARNING)) {
        logger.warning("Morph target animation not yet supported.");
    }

    // Just add mesh.
    if (baseMesh != null) {
        ardorParentNode.attachChild(baseMesh);
    }
}

From source file:com.ardor3d.extension.model.collada.jdom.ColladaAnimUtils.java

License:Open Source License

/**
 * Merge all animation channels into Ardor jointchannels
 * //from w  w w.java 2  s  .c  o  m
 * @param entry
 */
@SuppressWarnings("unchecked")
private void buildAnimations(final Element parentElement, final Collection<TargetChannel> targetList) {

    final List<Element> elementTransforms = new ArrayList<Element>();
    for (final Element child : parentElement.getChildren()) {
        if (_dataCache.getTransformTypes().contains(child.getName())) {
            elementTransforms.add(child);
        }
    }
    final List<TransformElement> transformList = getNodeTransformList(elementTransforms);

    AnimationItem animationItemRoot = null;
    for (final TargetChannel targetChannel : targetList) {
        if (animationItemRoot == null) {
            animationItemRoot = targetChannel.animationItemRoot;
        }
        final String source = targetChannel.source;
        // final Target target = targetChannel.target;
        final Element targetNode = targetChannel.targetNode;

        final int targetIndex = elementTransforms.indexOf(targetNode);
        if (logger.isLoggable(Level.FINE)) {
            logger.fine(parentElement.getName() + "(" + parentElement.getAttributeValue("name") + ") -> "
                    + targetNode.getName() + "(" + targetIndex + ")");
        }

        final EnumMap<Type, ColladaInputPipe> pipes = Maps.newEnumMap(Type.class);

        final Element samplerElement = _colladaDOMUtil.findTargetWithId(source);
        for (final Element inputElement : samplerElement.getChildren("input")) {
            final ColladaInputPipe pipe = new ColladaInputPipe(_colladaDOMUtil, inputElement);
            pipes.put(pipe.getType(), pipe);
        }

        // get input (which is TIME for now)
        final ColladaInputPipe inputPipe = pipes.get(Type.INPUT);
        final ColladaInputPipe.SourceData sdIn = inputPipe.getSourceData();
        final float[] time = sdIn.floatArray;
        targetChannel.time = time;
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("inputPipe: " + Arrays.toString(time));
        }

        // get output data
        final ColladaInputPipe outputPipe = pipes.get(Type.OUTPUT);
        final ColladaInputPipe.SourceData sdOut = outputPipe.getSourceData();
        final float[] animationData = sdOut.floatArray;
        targetChannel.animationData = animationData;
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("outputPipe: " + Arrays.toString(animationData));
        }

        // TODO: Need to add support for other interpolation types.

        // get target array from transform list
        final TransformElement transformElement = transformList.get(targetIndex);
        final double[] array = transformElement.getArray();
        targetChannel.array = array;

        final int stride = sdOut.stride;
        targetChannel.stride = stride;

        targetChannel.currentPos = 0;
    }

    final List<Float> finalTimeList = Lists.newArrayList();
    final List<Transform> finalTransformList = Lists.newArrayList();
    final List<TargetChannel> workingChannels = Lists.newArrayList();
    for (;;) {
        float lowestTime = Float.MAX_VALUE;
        boolean found = false;
        for (final TargetChannel targetChannel : targetList) {
            if (targetChannel.currentPos < targetChannel.time.length) {
                final float time = targetChannel.time[targetChannel.currentPos];
                if (time < lowestTime) {
                    lowestTime = time;
                }
                found = true;
            }
        }
        if (!found) {
            break;
        }

        workingChannels.clear();
        for (final TargetChannel targetChannel : targetList) {
            if (targetChannel.currentPos < targetChannel.time.length) {
                final float time = targetChannel.time[targetChannel.currentPos];
                if (time == lowestTime) {
                    workingChannels.add(targetChannel);
                }
            }
        }

        for (final TargetChannel targetChannel : workingChannels) {
            final Target target = targetChannel.target;
            final float[] animationData = targetChannel.animationData;
            final double[] array = targetChannel.array;

            // set the correct values depending on accessor
            final int position = targetChannel.currentPos * targetChannel.stride;
            if (target.accessorType == AccessorType.None) {
                for (int j = 0; j < array.length; j++) {
                    array[j] = animationData[position + j];
                }
            } else {
                if (target.accessorType == AccessorType.Vector) {
                    array[target.accessorIndexX] = animationData[position];
                } else if (target.accessorType == AccessorType.Matrix) {
                    array[target.accessorIndexY * 4 + target.accessorIndexX] = animationData[position];
                }
            }
            targetChannel.currentPos++;
        }

        // bake the transform
        final Transform transform = bakeTransforms(transformList);
        finalTimeList.add(lowestTime);
        finalTransformList.add(transform);
    }

    final float[] time = new float[finalTimeList.size()];
    for (int i = 0; i < finalTimeList.size(); i++) {
        time[i] = finalTimeList.get(i);
    }
    final Transform[] transforms = finalTransformList.toArray(new Transform[finalTransformList.size()]);

    AnimationClip animationClip = animationItemRoot.getAnimationClip();
    if (animationClip == null) {
        animationClip = new AnimationClip(animationItemRoot.getName());
        animationItemRoot.setAnimationClip(animationClip);
    }

    // Make an animation channel - first find if we have a matching joint
    Joint joint = _dataCache.getElementJointMapping().get(parentElement);
    if (joint == null) {
        String nodeName = parentElement.getAttributeValue("name", (String) null);
        if (nodeName == null) { // use id if name doesn't exist
            nodeName = parentElement.getAttributeValue("id", parentElement.getName());
        }
        if (nodeName != null) {
            joint = _dataCache.getExternalJointMapping().get(nodeName);
        }

        if (joint == null) {
            // no joint still, so make a transform channel.
            final TransformChannel transformChannel = new TransformChannel(nodeName, time, transforms);
            animationClip.addChannel(transformChannel);
            _colladaStorage.getAnimationChannels().add(transformChannel);
            return;
        }
    }

    // create joint channel
    final JointChannel jointChannel = new JointChannel(joint, time, transforms);
    animationClip.addChannel(jointChannel);
    _colladaStorage.getAnimationChannels().add(jointChannel);
}

From source file:com.ardor3d.extension.model.collada.jdom.ColladaAnimUtils.java

License:Open Source License

/**
 * Gather up all animation channels based on what nodes they affect.
 * //  w w  w  . ja v a  2  s.c  o  m
 * @param channelMap
 * @param animationRoot
 * @param animationItemRoot
 */
@SuppressWarnings("unchecked")
private void parseAnimations(final Multimap<Element, TargetChannel> channelMap, final Element animationRoot,
        final AnimationItem animationItemRoot) {
    if (animationRoot.getChild("animation") != null) {
        Attribute nameAttribute = animationRoot.getAttribute("name");
        if (nameAttribute == null) {
            nameAttribute = animationRoot.getAttribute("id");
        }
        final String name = nameAttribute != null ? nameAttribute.getValue() : "Default";

        final AnimationItem animationItem = new AnimationItem(name);
        animationItemRoot.getChildren().add(animationItem);

        for (final Element animationElement : animationRoot.getChildren("animation")) {
            parseAnimations(channelMap, animationElement, animationItem);
        }
    }
    if (animationRoot.getChild("channel") != null) {
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("\n-- Parsing animation channels --");
        }
        final List<Element> channels = animationRoot.getChildren("channel");
        for (final Element channel : channels) {
            final String source = channel.getAttributeValue("source");

            final String targetString = channel.getAttributeValue("target");
            if (targetString == null || targetString.isEmpty()) {
                return;
            }

            final Target target = processTargetString(targetString);
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("channel source: " + target.toString());
            }
            final Element targetNode = findTargetNode(target);
            if (targetNode == null || !_dataCache.getTransformTypes().contains(targetNode.getName())) {
                // TODO: pass with warning or exception or nothing?
                // throw new ColladaException("No target transform node found for target: " + target, target);
                continue;
            }
            if ("rotate".equals(targetNode.getName())) {
                target.accessorType = AccessorType.Vector;
                target.accessorIndexX = 3;
            }

            channelMap.put(targetNode.getParentElement(),
                    new TargetChannel(target, targetNode, source, animationItemRoot));
        }
    }
}

From source file:com.ardor3d.extension.model.collada.jdom.ColladaAnimUtils.java

License:Open Source License

/**
 * Convert a list of collada elements into a list of TransformElements
 * /*from  w w w.  j  a va  2  s . co m*/
 * @param transforms
 * @return
 */
private List<TransformElement> getNodeTransformList(final List<Element> transforms) {
    final List<TransformElement> transformList = Lists.newArrayList();

    for (final Element transform : transforms) {
        final double[] array = _colladaDOMUtil.parseDoubleArray(transform);

        if ("translate".equals(transform.getName())) {
            transformList.add(new TransformElement(array, TransformElementType.Translation));
        } else if ("rotate".equals(transform.getName())) {
            transformList.add(new TransformElement(array, TransformElementType.Rotation));
        } else if ("scale".equals(transform.getName())) {
            transformList.add(new TransformElement(array, TransformElementType.Scale));
        } else if ("matrix".equals(transform.getName())) {
            transformList.add(new TransformElement(array, TransformElementType.Matrix));
        } else if ("lookat".equals(transform.getName())) {
            transformList.add(new TransformElement(array, TransformElementType.Lookat));
        } else {
            if (logger.isLoggable(Level.WARNING)) {
                logger.warning("transform not currently supported: " + transform.getClass().getCanonicalName());
            }
        }
    }

    return transformList;
}

From source file:com.ardor3d.extension.model.collada.jdom.ColladaAnimUtils.java

License:Open Source License

@SuppressWarnings("unchecked")
private static void getElementString(final Element e, final StringBuilder str, final int depth,
        final int maxDepth, final boolean showDots) {
    addSpacing(str, depth);/*from  w w  w.  ja  v  a2  s. c  om*/
    str.append('<');
    str.append(e.getName());
    str.append(' ');
    final List<Attribute> attrs = e.getAttributes();
    for (int i = 0; i < attrs.size(); i++) {
        final Attribute attr = attrs.get(i);
        str.append(attr.getName());
        str.append("=\"");
        str.append(attr.getValue());
        str.append('"');
        if (i < attrs.size() - 1) {
            str.append(' ');
        }
    }
    if (!e.getChildren().isEmpty() || !"".equals(e.getText())) {
        str.append('>');
        if (depth < maxDepth) {
            str.append('\n');
            for (final Element child : (List<Element>) e.getChildren()) {
                getElementString(child, str, depth + 1, maxDepth, showDots);
            }
            if (!"".equals(e.getText())) {
                addSpacing(str, depth + 1);
                str.append(e.getText());
                str.append('\n');
            }
        } else if (showDots) {
            str.append('\n');
            addSpacing(str, depth + 1);
            str.append("...");
            str.append('\n');
        }
        addSpacing(str, depth);
        str.append("</");
        str.append(e.getName());
        str.append('>');
    } else {
        str.append("/>");
    }
    str.append('\n');
}

From source file:com.ardor3d.extension.model.collada.jdom.ColladaDOMUtil.java

License:Open Source License

/**
 * Find Element with semantic POSITION under an element with inputs
 * //from w  w w .  j  a  v  a  2 s  . co m
 * @param v
 * @return
 */
@SuppressWarnings("unchecked")
public Element getPositionSource(final Element v) {
    for (final Element input : v.getChildren("input")) {
        if ("POSITION".equals(input.getAttributeValue("semantic"))) {
            final Element n = findTargetWithId(input.getAttributeValue("source"));
            if (n != null && "source".equals(n.getName())) {
                return n;
            }
        }
    }

    // changed this to throw an exception instead - otherwise, there will just be a nullpointer exception
    // outside. This provides much more information about what went wrong / Petter
    // return null;
    throw new ColladaException("Unable to find POSITION semantic for inputs under DaeVertices", v);
}