Example usage for org.jdom2 Element getChild

List of usage examples for org.jdom2 Element getChild

Introduction

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

Prototype

public Element getChild(final String cname) 

Source Link

Document

This returns the first child element within this element with the given local name and belonging to no namespace.

Usage

From source file:Codigo.XMLReader.java

/**
 * Metodo utilizado para crear los grupos del mundial con la informacion de todos
 * los encuentros por grupo//from  w  w w .j a  va 2  s.co m
 * @param pEquipos equipos participantes del mundial
 * @param pEstadios estadio del mundial
 * @return lista de los grupos del mundial
 */
public ListaGrupos cargarCalendarioYGrupos(ListaEquipos pEquipos, ListaEstadios pEstadios) {

    // Formato que se va a establecer en la creacion de cada fecha
    SimpleDateFormat formatoFecha = new SimpleDateFormat("d/M/yy h:mm a");
    // Se crea la lista de los Grupos del mundial, que se va a retornar
    ListaGrupos listaDeGrupos = new ListaGrupos();
    //Se crea un SAXBuilder para poder parsear el archivo
    SAXBuilder builder = new SAXBuilder();

    try {
        File xmlFile = new File(getClass().getResource("/XML/CalendarioGrupos.xml").toURI());
        //Se crea el documento a traves del archivo
        Document document = (Document) builder.build(xmlFile);
        //Se obtiene la raiz 'Grupos'
        Element raizXML = document.getRootElement();

        //Se obtiene la lista de hijos de la raiz 'Grupos' (Todos los grupos del mundial)
        List listaGruposXML = raizXML.getChildren("Grupo");

        // RECORRE LA LISTA DE GRUPOS DEL MUNDIAL
        for (int i = 0; i < listaGruposXML.size(); i++) {
            //Se obtiene el elemento 'Grupo' en la posicion i de la lista
            Element grupo = (Element) listaGruposXML.get(i);

            // Obtengo el atributo con la letra del grupo
            char letraDelGrupo = grupo.getAttributeValue("letra").charAt(0);

            // Se obtine la lista de los equipos que conforma el grupo
            List selecciones = grupo.getChild("Equipos").getChildren("Equipo");
            // Se crea un arreglo que almacenara las selecciones integrantes
            NodoEquipo[] equiposDelGrupo = new NodoEquipo[selecciones.size()];
            // RECORRE LA LISTA DE EQUIPOS PERTENECIENTES A ESTE GRUPO
            for (int j = 0; j < selecciones.size(); j++) {
                Element equipo = (Element) selecciones.get(j);
                // Obtiene el nombre del equipo 'j'
                NodoEquipo nombreDelEquipo = pEquipos.getNodoEquipo(equipo.getText());
                // Inserta nombre del equipo, en el arreglo de equiposDelGrupo
                equiposDelGrupo[j] = nombreDelEquipo;
            }

            // SE CREA LA LISTA QUE ALMACENARA LOS ENCUENTROS DEL GRUPO                
            ListaCalendario calendarioDelGrupo = new ListaCalendario();
            // Se obtiene la lista de todo los Encuentros correspondientes al grupo
            List listaDeEncuentros = grupo.getChild("Encuentros").getChildren("Partido");
            // RECORRE LA LISTA DE PARTIDOS CORRESPONDIENTES A LOS EQUIPOS DEL GRUPO ACTUAL
            for (int j = 0; j < listaDeEncuentros.size(); j++) {
                Element partido = (Element) listaDeEncuentros.get(j);

                // Obtiene los datos de fecha y hora del encuentro
                String fechaDelPartido = partido.getChildText("Fecha");
                String horaDelPartido = partido.getChildText("Hora");
                Date fechaYHora = formatoFecha.parse(fechaDelPartido + " " + horaDelPartido);

                // Obtiene los datos de condiciones climaticas del encuentro
                String humedad = partido.getChildText("Humedad");
                String velocidadViento = partido.getChildText("VelocidadViento");
                String temperatura = partido.getChildText("Temperatura");
                String condicionClimatica = partido.getChildText("CondicionClimatica");

                // Obtiene el estadio sede del encuentro
                String nombreEstadioSede = partido.getChildText("Sede");
                NodoEstadio estadioSede = pEstadios.getNodoEstadio(nombreEstadioSede);

                // Obtiene los equipos casa y visita que se enfrentan en el encuentro
                String nombreEquipoCasa = partido.getChildText("EquipoCasa");
                NodoEquipo equipoCasa = pEquipos.getNodoEquipo(nombreEquipoCasa);
                String nombreEquipoVisita = partido.getChildText("EquipoVisita");
                NodoEquipo equipoVisita = pEquipos.getNodoEquipo(nombreEquipoVisita);

                // Obtiene la cantidad de goles por equipo, en el encuentro
                int golesCasa = Integer.parseInt(partido.getChild("GolesCasa").getAttributeValue("goles"));
                String anotadoresCasa = "";
                int golesVisita = Integer.parseInt(partido.getChild("GolesVisita").getAttributeValue("goles"));
                String anotadoresVisita = "";

                // COMPRUEBA SI HUBIERON ANOTACIONES, DE LOS LOCALES, PARA OBTENER LOS ANOTADORES
                if (golesCasa > 0) {
                    List anotadores = partido.getChild("GolesCasa").getChild("Anotadores")
                            .getChildren("Anotador");
                    // RECORRE LA LISTA PARA OBTENER LOS ANOTADORES Y EL MINUTO DEL GOL
                    for (int k = 0; k < anotadores.size(); k++) {
                        Element anotador = (Element) anotadores.get(k);
                        // OBTENGO LOS DATOS DEL ANOTADOR 'k'
                        String nombre = anotador.getChildText("Nombre");
                        String minuto = anotador.getChildText("Minuto");
                        if (k < (anotadores.size() - 1)) {
                            anotadoresCasa += minuto + '\'' + "  " + nombre + '\n';
                        } else {
                            anotadoresCasa += minuto + '\'' + "  " + nombre;
                        }
                    }
                }
                // COMPRUEBA SI HUBIERON ANOTACIONES, DE LA VISITA, PARA OBTENER LOS ANOTADORES
                if (golesVisita > 0) {
                    List anotadores = partido.getChild("GolesVisita").getChild("Anotadores")
                            .getChildren("Anotador");
                    // RECORRE LA LISTA PARA OBTENER LOS ANOTADORES Y EL MINUTO DEL GOL
                    for (int k = 0; k < anotadores.size(); k++) {
                        Element anotador = (Element) anotadores.get(k);
                        // OBTENGO LOS DATOS DEL ANOTADOR 'k'
                        String nombre = anotador.getChildText("Nombre");
                        String minuto = anotador.getChildText("Minuto");
                        if (k < (anotadores.size() - 1)) {
                            anotadoresVisita += minuto + '\'' + "  " + nombre + '\n';
                        } else {
                            anotadoresVisita += minuto + '\'' + "  " + nombre;
                        }
                    }
                }
                // Crea un nuevo nodo Encuentro y lo inserta en la lista de Calendario
                NodoEncuentro encuentro = new NodoEncuentro(fechaYHora, humedad, velocidadViento, temperatura,
                        estadioSede, equipoCasa, equipoVisita, golesCasa, golesVisita, anotadoresCasa,
                        anotadoresVisita, condicionClimatica);

                // Inserta el nuevo nodo en la lista de Encuentros
                calendarioDelGrupo.insertarOrdenadoPorFecha(encuentro);
            }
            // Crea un nodo Grupo con toda la informacion del grupo actual
            NodoGrupo grupoDelMundial = new NodoGrupo(letraDelGrupo, equiposDelGrupo, calendarioDelGrupo);
            // Inserta el grupo a la lista de grupos
            listaDeGrupos.insertarOrdenado(grupoDelMundial);
        }
        // Retorna la lista de todos los equipos
        return listaDeGrupos;

    } catch (IOException | JDOMException | URISyntaxException | ParseException io) {
        System.out.println(io.getMessage());
        return null;
    }
}

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

License:Open Source License

protected DecisionTree parseDocument(final Document doc) throws DecisionTreeParserException {
    final Element rootElement = doc.getRootElement();
    final Map<String, InputType> types = parseInputTypes(rootElement.getChild("input-types"));
    final ResultSpec resultSpec = parseResultClass(rootElement.getChild("result-type"));
    final Node rootNode = parseTable(rootElement.getChild("tree"), types, resultSpec);
    return new DecisionTree(rootNode, types.values());
}

From source file:com.android.helpme.demo.utils.position.Position.java

License:Apache License

public Position(Element object) {
    Element position = object.getChild(User.POSITION);
    if (position != null) {
        this.longitude = new Double(position.getAttributeValue(LONGITUDE));
        this.latitude = new Double(position.getAttributeValue(LATITUDE));
        this.speed = new Double(position.getAttributeValue(SPEED));
        this.direction = new Double(position.getAttributeValue(DIRECTION));
        this.precision = new Double(position.getAttributeValue(PRECISION));
        this.date = new Long(position.getAttributeValue(DATE));
    } else {//w  ww. j a v a2s .c  o m
        this.longitude = new Double(object.getAttributeValue(LONGITUDE));
        this.latitude = new Double(object.getAttributeValue(LATITUDE));
        this.speed = new Double(object.getAttributeValue(SPEED));
        this.direction = new Double(object.getAttributeValue(DIRECTION));
        this.precision = new Double(object.getAttributeValue(PRECISION));
        this.date = new Long(object.getAttributeValue(DATE));
    }

}

From source file:com.archimatetool.model.viewpoints.ViewpointManager.java

License:Open Source License

/**
 * Load viewpoints from XML file/*from  ww w.  ja v  a2s  .  com*/
 */
void loadDefaultViewpointsFile() throws IOException, JDOMException {
    URL url = Platform.getBundle(BUNDLE_ID).getEntry(VIEWPOINTS_FILE);

    Document doc = new SAXBuilder().build(url);
    Element rootElement = doc.getRootElement();

    for (Element xmlViewpoint : rootElement.getChildren("viewpoint")) { //$NON-NLS-1$

        String id = xmlViewpoint.getAttributeValue("id"); //$NON-NLS-1$
        if (id == null || "".equals(id)) { //$NON-NLS-1$
            System.err.println("Blank id for viewpoint"); //$NON-NLS-1$
            continue;
        }

        Element xmlName = xmlViewpoint.getChild("name"); //$NON-NLS-1$
        if (xmlName == null) {
            System.err.println("No name element for viewpoint"); //$NON-NLS-1$
            continue;
        }

        String name = xmlName.getText();
        if (name == null || "".equals(name)) { //$NON-NLS-1$
            System.err.println("Blank name for viewpoint"); //$NON-NLS-1$
            continue;
        }

        Viewpoint vp = new Viewpoint(id, name);

        for (Element xmlConcept : xmlViewpoint.getChildren("concept")) { //$NON-NLS-1$
            String conceptName = xmlConcept.getText();
            if (conceptName == null || "".equals(conceptName)) { //$NON-NLS-1$
                System.err.println("Blank concept name for viewpoint"); //$NON-NLS-1$
                continue;
            }

            if (ELEMENTS_MAP.containsKey(conceptName)) {
                addCollection(vp, conceptName);
            } else {
                EClass eClass = (EClass) IArchimatePackage.eINSTANCE.getEClassifier(conceptName);
                if (eClass != null) {
                    addConcept(vp, eClass);
                } else {
                    System.err.println("Couldn't get eClass: " + conceptName); //$NON-NLS-1$
                }

            }
        }

        VIEWPOINTS.put(id, vp);
    }
}

From source file:com.archimatetool.templates.model.AbstractTemplate.java

License:Open Source License

private void loadManifest() {
    // Default first
    fManifestLoaded = true;//ww  w.j  a  va  2s .c  o m
    fName = ""; //$NON-NLS-1$
    fDescription = ""; //$NON-NLS-1$

    if (fFile != null && fFile.exists()) {
        try {
            // Manifest
            String manifest = ZipUtils.extractZipEntry(fFile, TemplateManager.ZIP_ENTRY_MANIFEST);
            if (manifest != null) {
                Document doc = JDOMUtils.readXMLString(manifest);
                Element rootElement = doc.getRootElement();

                // Name
                Element nameElement = rootElement.getChild(XML_TEMPLATE_ELEMENT_NAME);
                if (nameElement != null) {
                    fName = nameElement.getText();
                }

                // Description
                Element descriptionElement = rootElement.getChild(XML_TEMPLATE_ELEMENT_DESCRIPTION);
                if (nameElement != null) {
                    fDescription = descriptionElement.getText();
                }

                // Key thumbnail
                Element keyThumbnailElement = rootElement.getChild(XML_TEMPLATE_ELEMENT_KEY_THUMBNAIL);
                if (keyThumbnailElement != null) {
                    fKeyThumbnailPath = keyThumbnailElement.getText();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

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

License:Open Source License

/**
 * Builds data based on an instance controller element.
 * /*from   www.j av a  2 s.  co m*/
 * @param node
 *            Ardor3D parent Node
 * @param instanceController
 */
void buildController(final Node node, final Element instanceController) {
    final Element controller = _colladaDOMUtil.findTargetWithId(instanceController.getAttributeValue("url"));

    if (controller == null) {
        throw new ColladaException(
                "Unable to find controller with id: " + instanceController.getAttributeValue("url"),
                instanceController);
    }

    final Element skin = controller.getChild("skin");
    if (skin != null) {
        buildSkinMeshes(node, instanceController, controller, skin);
    } else {
        // look for morph... can only be one or the other according to Collada
        final Element morph = controller.getChild("morph");
        if (morph != null) {
            buildMorphMeshes(node, controller, morph);
        }
    }
}

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.
 * /*from w w w.  java  2s  .com*/
 * @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

/**
 * Parse all animations in library_animations
 * /*from   w w w .ja  v a 2s.  co  m*/
 * @param colladaRoot
 */
public void parseLibraryAnimations(final Element colladaRoot) {
    final Element libraryAnimations = colladaRoot.getChild("library_animations");

    if (libraryAnimations == null || libraryAnimations.getChildren().isEmpty()) {
        if (logger.isLoggable(Level.WARNING)) {
            logger.warning("No animations found in collada file!");
        }
        return;
    }

    final AnimationItem animationItemRoot = new AnimationItem("Animation Root");
    _colladaStorage.setAnimationItemRoot(animationItemRoot);

    final Multimap<Element, TargetChannel> channelMap = ArrayListMultimap.create();

    parseAnimations(channelMap, libraryAnimations, animationItemRoot);

    for (final Element key : channelMap.keySet()) {
        buildAnimations(key, channelMap.get(key));
    }
}

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.
 * /*from   w ww  .ja va  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.ColladaImporter.java

License:Open Source License

/**
 * Reads a Collada file from the given resource and returns it as a ColladaStorage object.
 * /*w  ww  .  j av a2  s  . c  om*/
 * @param resource
 *            the name of the resource to find.
 * @param geometryTool
 *            the geometry tool used to minimize the vertex count.
 * @return a ColladaStorage data object containing the Collada scene and other useful elements.
 * @throws IOException
 *             if the resource can not be loaded for some reason.
 */
public ColladaStorage load(final ResourceSource resource, final GeometryTool geometryTool) throws IOException {
    final ColladaStorage colladaStorage = new ColladaStorage();
    final DataCache dataCache = new DataCache();
    if (_externalJointMapping != null) {
        dataCache.getExternalJointMapping().putAll(_externalJointMapping);
    }
    final ColladaDOMUtil colladaDOMUtil = new ColladaDOMUtil(dataCache);
    final ColladaMaterialUtils colladaMaterialUtils = new ColladaMaterialUtils(this, dataCache, colladaDOMUtil);
    final ColladaMeshUtils colladaMeshUtils = new ColladaMeshUtils(dataCache, colladaDOMUtil,
            colladaMaterialUtils, _optimizeMeshes, _optimizeSettings, geometryTool);
    final ColladaAnimUtils colladaAnimUtils = new ColladaAnimUtils(colladaStorage, dataCache, colladaDOMUtil,
            colladaMeshUtils);
    final ColladaNodeUtils colladaNodeUtils = new ColladaNodeUtils(dataCache, colladaDOMUtil,
            colladaMaterialUtils, colladaMeshUtils, colladaAnimUtils);

    try {
        // Pull in the DOM tree of the Collada resource.
        final Element collada = readCollada(resource, dataCache);

        // if we don't specify a texture locator, add a temporary texture locator at the location of this model
        // resource..
        final boolean addLocator = _textureLocator == null;

        final RelativeResourceLocator loc;
        if (addLocator) {
            loc = new RelativeResourceLocator(resource);
            ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, loc);
        } else {
            loc = null;
        }

        final AssetData assetData = colladaNodeUtils.parseAsset(collada.getChild("asset"));

        // Collada may or may not have a scene, so this can return null.
        final Node scene = colladaNodeUtils.getVisualScene(collada);

        if (_loadAnimations) {
            colladaAnimUtils.parseLibraryAnimations(collada);
        }

        // reattach attachments to scene
        if (scene != null) {
            colladaNodeUtils.reattachAttachments(scene);
        }

        // set our scene into storage
        colladaStorage.setScene(scene);

        // set our asset data into storage
        colladaStorage.setAssetData(assetData);

        // drop our added locator if needed.
        if (addLocator) {
            ResourceLocatorTool.removeResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, loc);
        }

        // copy across our mesh colors - only for objects with multiple channels
        final Multimap<MeshData, FloatBuffer> colors = ArrayListMultimap.create();
        final Multimap<MeshData, FloatBuffer> temp = dataCache.getParsedVertexColors();
        for (final MeshData key : temp.keySet()) {
            // only copy multiple channels since their data is lost
            final Collection<FloatBuffer> val = temp.get(key);
            if (val != null && val.size() > 1) {
                colors.putAll(key, val);
            }
        }
        colladaStorage.setParsedVertexColors(colors);

        // copy across our mesh material info
        colladaStorage.setMeshMaterialInfo(dataCache.getMeshMaterialMap());
        colladaStorage.setMaterialMap(dataCache.getMaterialInfoMap());

        // return storage
        return colladaStorage;
    } catch (final Exception e) {
        throw new IOException("Unable to load collada resource from URL: " + resource, e);
    }
}