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:com.ardor3d.extension.model.collada.jdom.ColladaInputPipe.java

License:Open Source License

private Element getCommonAccessor(final Element source) {
    final Element techniqueCommon = source.getChild("technique_common");
    if (techniqueCommon != null) {
        return techniqueCommon.getChild("accessor");
    }/*from w  w w. j  av  a2 s  . co m*/
    return null;
}

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

License:Open Source License

/**
 * Find and apply the given material to the given Mesh.
 * //from   w  ww. jav  a 2  s.  c  om
 * @param materialName
 *            our material name
 * @param mesh
 *            the mesh to apply material to.
 */
public void applyMaterial(final String materialName, final Mesh mesh) {
    if (materialName == null) {
        logger.warning("materialName is null");
        return;
    }

    Element mat = _dataCache.getBoundMaterial(materialName);
    if (mat == null) {
        logger.warning("material not bound: " + materialName + ", trying search with id.");
        mat = _colladaDOMUtil.findTargetWithId(materialName);
    }
    if (mat == null || !"material".equals(mat.getName())) {
        logger.warning("material not found: " + materialName);
        return;
    }

    final String originalMaterial = mat.getAttributeValue("id");
    MaterialInfo mInfo = null;
    if (!_dataCache.getMaterialInfoMap().containsKey(originalMaterial)) {
        mInfo = new MaterialInfo();
        mInfo.setMaterialName(originalMaterial);
        _dataCache.getMaterialInfoMap().put(originalMaterial, mInfo);
    }
    _dataCache.getMeshMaterialMap().put(mesh, originalMaterial);

    final Element child = mat.getChild("instance_effect");
    final Element effectNode = _colladaDOMUtil.findTargetWithId(child.getAttributeValue("url"));
    if (effectNode == null) {
        logger.warning(
                "material effect not found: " + mat.getChild("instance_material").getAttributeValue("url"));
        return;
    }

    if ("effect".equals(effectNode.getName())) {
        /*
         * temp cache for textures, we do not want to add textures twice (for example, transparant map might point
         * to diffuse texture)
         */
        final HashMap<String, Texture> loadedTextures = new HashMap<String, Texture>();
        final Element effect = effectNode;
        // XXX: For now, just grab the common technique:
        final Element common = effect.getChild("profile_COMMON");
        if (common != null) {
            if (mInfo != null) {
                mInfo.setProfile("COMMON");
            }

            final Element commonExtra = common.getChild("extra");
            if (commonExtra != null) {
                // process with any plugins
                _importer.readExtra(commonExtra, mesh);
            }

            final Element technique = common.getChild("technique");
            String type = "blinn";
            if (technique.getChild(type) == null) {
                type = "phong";
                if (technique.getChild(type) == null) {
                    type = "lambert";
                    if (technique.getChild(type) == null) {
                        type = "constant";
                        if (technique.getChild(type) == null) {
                            ColladaMaterialUtils.logger.warning("COMMON material has unusuable techinque. "
                                    + child.getAttributeValue("url"));
                            return;
                        }
                    }
                }
            }
            final Element blinnPhongLambert = technique.getChild(type);
            if (mInfo != null) {
                mInfo.setTechnique(type);
            }
            final MaterialState mState = new MaterialState();

            // TODO: implement proper transparency handling
            Texture diffuseTexture = null;
            ColorRGBA transparent = new ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f);
            float transparency = 1.0f;
            boolean useTransparency = false;
            String opaqueMode = "A_ONE";

            /*
             * place holder for current property, we import material properties in fixed order (for texture order)
             */
            Element property = null;
            /* Diffuse property */
            property = blinnPhongLambert.getChild("diffuse");
            if (property != null) {
                final Element propertyValue = property.getChildren().get(0);
                if ("color".equals(propertyValue.getName())) {
                    final ColorRGBA color = _colladaDOMUtil.getColor(propertyValue.getText());
                    mState.setDiffuse(MaterialFace.FrontAndBack, color);
                } else if ("texture".equals(propertyValue.getName()) && _loadTextures) {
                    diffuseTexture = populateTextureState(mesh, propertyValue, effect, loadedTextures, mInfo,
                            "diffuse");
                }
            }
            /* Ambient property */
            property = blinnPhongLambert.getChild("ambient");
            if (property != null) {
                final Element propertyValue = property.getChildren().get(0);
                if ("color".equals(propertyValue.getName())) {
                    final ColorRGBA color = _colladaDOMUtil.getColor(propertyValue.getText());
                    mState.setAmbient(MaterialFace.FrontAndBack, color);
                } else if ("texture".equals(propertyValue.getName()) && _loadTextures) {
                    populateTextureState(mesh, propertyValue, effect, loadedTextures, mInfo, "ambient");
                }
            }
            /* Transparent property */
            property = blinnPhongLambert.getChild("transparent");
            if (property != null) {
                final Element propertyValue = property.getChildren().get(0);
                if ("color".equals(propertyValue.getName())) {
                    transparent = _colladaDOMUtil.getColor(propertyValue.getText());
                    // TODO: use this
                    useTransparency = true;
                } else if ("texture".equals(propertyValue.getName()) && _loadTextures) {
                    populateTextureState(mesh, propertyValue, effect, loadedTextures, mInfo, "transparent");
                }
                opaqueMode = property.getAttributeValue("opaque", "A_ONE");
            }
            /* Transparency property */
            property = blinnPhongLambert.getChild("transparency");
            if (property != null) {
                final Element propertyValue = property.getChildren().get(0);
                if ("float".equals(propertyValue.getName())) {
                    transparency = Float.parseFloat(propertyValue.getText().replace(",", "."));
                    // TODO: use this
                    if (_flipTransparency) {
                        transparency = 1f - transparency;
                    }
                    useTransparency = true;
                } else if ("texture".equals(propertyValue.getName()) && _loadTextures) {
                    populateTextureState(mesh, propertyValue, effect, loadedTextures, mInfo, "transparency");
                }
            }
            /* Emission property */
            property = blinnPhongLambert.getChild("emission");
            if (property != null) {
                final Element propertyValue = property.getChildren().get(0);
                if ("color".equals(propertyValue.getName())) {
                    mState.setEmissive(MaterialFace.FrontAndBack,
                            _colladaDOMUtil.getColor(propertyValue.getText()));
                } else if ("texture".equals(propertyValue.getName()) && _loadTextures) {
                    populateTextureState(mesh, propertyValue, effect, loadedTextures, mInfo, "emissive");
                }
            }
            /* Specular property */
            property = blinnPhongLambert.getChild("specular");
            if (property != null) {
                final Element propertyValue = property.getChildren().get(0);
                if ("color".equals(propertyValue.getName())) {
                    mState.setSpecular(MaterialFace.FrontAndBack,
                            _colladaDOMUtil.getColor(propertyValue.getText()));
                } else if ("texture".equals(propertyValue.getName()) && _loadTextures) {
                    populateTextureState(mesh, propertyValue, effect, loadedTextures, mInfo, "specular");
                }
            }
            /* Shininess property */
            property = blinnPhongLambert.getChild("shininess");
            if (property != null) {
                final Element propertyValue = property.getChildren().get(0);
                if ("float".equals(propertyValue.getName())) {
                    float shininess = Float.parseFloat(propertyValue.getText().replace(",", "."));
                    if (shininess >= 0.0f && shininess <= 1.0f) {
                        final float oldShininess = shininess;
                        shininess *= 128;
                        logger.finest("Shininess - " + oldShininess
                                + " - was in the [0,1] range. Scaling to [0, 128] - " + shininess);
                    } else if (shininess < 0 || shininess > 128) {
                        final float oldShininess = shininess;
                        shininess = MathUtils.clamp(shininess, 0, 128);
                        logger.warning("Shininess must be between 0 and 128. Shininess " + oldShininess
                                + " was clamped to " + shininess);
                    }
                    mState.setShininess(MaterialFace.FrontAndBack, shininess);
                } else if ("texture".equals(propertyValue.getName()) && _loadTextures) {
                    populateTextureState(mesh, propertyValue, effect, loadedTextures, mInfo, "shininess");
                }
            }
            /* Reflectivity property */
            float reflectivity = 1.0f;
            property = blinnPhongLambert.getChild("reflectivity");
            if (property != null) {
                final Element propertyValue = property.getChildren().get(0);
                if ("float".equals(propertyValue.getName())) {
                    reflectivity = Float.parseFloat(propertyValue.getText().replace(",", "."));
                }
            }
            /* Reflective property. Texture only */
            property = blinnPhongLambert.getChild("reflective");
            if (property != null) {
                final Element propertyValue = property.getChildren().get(0);
                if ("texture".equals(propertyValue.getName()) && _loadTextures) {
                    final Texture reflectiveTexture = populateTextureState(mesh, propertyValue, effect,
                            loadedTextures, mInfo, "reflective");

                    reflectiveTexture.setEnvironmentalMapMode(Texture.EnvironmentalMapMode.SphereMap);
                    reflectiveTexture.setApply(ApplyMode.Combine);

                    reflectiveTexture.setCombineFuncRGB(CombinerFunctionRGB.Interpolate);
                    // color 1
                    reflectiveTexture.setCombineSrc0RGB(CombinerSource.CurrentTexture);
                    reflectiveTexture.setCombineOp0RGB(CombinerOperandRGB.SourceColor);
                    // color 2
                    reflectiveTexture.setCombineSrc1RGB(CombinerSource.Previous);
                    reflectiveTexture.setCombineOp1RGB(CombinerOperandRGB.SourceColor);
                    // interpolate param will come from alpha of constant color
                    reflectiveTexture.setCombineSrc2RGB(CombinerSource.Constant);
                    reflectiveTexture.setCombineOp2RGB(CombinerOperandRGB.SourceAlpha);

                    reflectiveTexture.setConstantColor(new ColorRGBA(1, 1, 1, reflectivity));
                }
            }

            /*
             * An extra tag defines some materials not part of the collada standard. Since we're not able to parse
             * we simply extract the textures from the element (such that shaders etc can at least pick up on them)
             */
            property = technique.getChild("extra");
            if (property != null) {
                // process with any plugins
                if (!_importer.readExtra(property, mesh)) {
                    // no plugin processed our mesh, so process ourselves.
                    getTexturesFromElement(mesh, property, effect, loadedTextures, mInfo);
                }
            }

            // XXX: There are some issues with clarity on how to use alpha blending in OpenGL FFP.
            // The best interpretation I have seen is that if transparent has a texture == diffuse,
            // Turn on alpha blending and use diffuse alpha.

            // check to make sure we actually need this.
            // testing separately for a transparency of 0.0 is to hack around erroneous exports, since usually
            // there is no use in exporting something with 100% transparency.
            if ("A_ONE".equals(opaqueMode) && ColorRGBA.WHITE.equals(transparent) && transparency == 1.0
                    || transparency == 0.0) {
                useTransparency = false;
            }

            if (useTransparency) {
                if (diffuseTexture != null) {
                    final BlendState blend = new BlendState();
                    blend.setBlendEnabled(true);
                    blend.setTestEnabled(true);
                    blend.setSourceFunction(BlendState.SourceFunction.SourceAlpha);
                    blend.setDestinationFunction(BlendState.DestinationFunction.OneMinusSourceAlpha);
                    mesh.setRenderState(blend);
                } else {
                    final BlendState blend = new BlendState();
                    blend.setBlendEnabled(true);
                    blend.setTestEnabled(true);
                    transparent.setAlpha(transparent.getAlpha() * transparency);
                    blend.setConstantColor(transparent);
                    blend.setSourceFunction(BlendState.SourceFunction.ConstantAlpha);
                    blend.setDestinationFunction(BlendState.DestinationFunction.OneMinusConstantAlpha);
                    mesh.setRenderState(blend);
                }

                mesh.getSceneHints().setRenderBucketType(RenderBucketType.Transparent);
            }

            if (mInfo != null) {
                if (useTransparency) {
                    mInfo.setUseTransparency(useTransparency);
                    if (diffuseTexture == null) {
                        mInfo.setTransparency(transparent.getAlpha() * transparency);
                    }
                }
                mInfo.setMaterialState(mState);
            }
            mesh.setRenderState(mState);
        }
    } else {
        ColladaMaterialUtils.logger.warning(
                "material effect not found: " + mat.getChild("instance_material").getAttributeValue("url"));
    }
}

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

License:Open Source License

/**
 * Convert a <texture> element to an Ardor3D representation and store in the given state.
 * //from ww w .j  av  a  2 s .  co  m
 * @param mesh
 *            the Ardor3D Mesh to add the Texture to.
 * @param daeTexture
 *            our <texture> element
 * @param effect
 *            our <instance_effect> element
 * @return the created Texture.
 */
private Texture populateTextureState(final Mesh mesh, final Element daeTexture, final Element effect,
        final HashMap<String, Texture> loadedTextures, final MaterialInfo info, String textureSlot) {
    // TODO: Use vert data to determine which texcoords and set to use.
    // final String uvName = daeTexture.getAttributeValue("texcoord");
    TextureState tState = (TextureState) mesh.getLocalRenderState(RenderState.StateType.Texture);
    if (tState == null) {
        tState = new TextureState();
        mesh.setRenderState(tState);
    }

    // Use texture attrib to find correct sampler
    final String textureReference = daeTexture.getAttributeValue("texture");
    if (textureSlot == null) {
        // if we have no texture slot defined (like in the case of an "extra" texture), we'll use the
        // textureReference.
        textureSlot = textureReference;
    }

    /* only add the texture to the state once */
    if (loadedTextures.containsKey(textureReference)) {
        final Texture tex = loadedTextures.get(textureReference);
        if (info != null) {
            info.setTextureSlot(textureSlot, textureReference, tex, null);
        }
        return tex;
    }

    Element node = _colladaDOMUtil.findTargetWithSid(textureReference);
    if (node == null) {
        // Not sure if this is quite right, but spec seems to indicate looking for global id
        node = _colladaDOMUtil.findTargetWithId("#" + textureReference);
    }

    if ("newparam".equals(node.getName())) {
        node = node.getChildren().get(0);
    }

    Element sampler = null;
    Element surface = null;
    Element image = null;

    Texture.MinificationFilter min = Texture.MinificationFilter.BilinearNoMipMaps;
    if ("sampler2D".equals(node.getName())) {
        sampler = node;
        if (sampler.getChild("minfilter") != null) {
            final String minfilter = sampler.getChild("minfilter").getText();
            min = Enum.valueOf(SamplerTypes.MinFilterType.class, minfilter).getArdor3dFilter();
        }
        // Use sampler to get correct surface
        node = _colladaDOMUtil.findTargetWithSid(sampler.getChild("source").getText());
        // node = resolveSid(effect, sampler.getSource());
    }

    if ("newparam".equals(node.getName())) {
        node = node.getChildren().get(0);
    }

    if ("surface".equals(node.getName())) {
        surface = node;
        // image(s) will come from surface.
    } else if ("image".equals(node.getName())) {
        image = node;
    }

    // Ok, a few possibilities here...
    Texture texture = null;
    String fileName = null;
    if (surface == null && image != null) {
        // Only an image found (no sampler). Assume 2d texture. Load.
        fileName = image.getChild("init_from").getText();
        texture = loadTexture2D(fileName, min);
    } else if (surface != null) {
        // We have a surface, pull images from that.
        if ("2D".equals(surface.getAttributeValue("type"))) {
            // look for an init_from with lowest mip and use that. (usually 0)

            // TODO: mip?
            final Element lowest = surface.getChildren("init_from").get(0);
            // Element lowest = null;
            // for (final Element i : (List<Element>) surface.getChildren("init_from")) {
            // if (lowest == null || lowest.getMip() > i.getMip()) {
            // lowest = i;
            // }
            // }

            if (lowest == null) {
                logger.warning("surface given with no usable init_from: " + surface);
                return null;
            }

            image = _colladaDOMUtil.findTargetWithId("#" + lowest.getText());
            // image = (DaeImage) root.resolveUrl("#" + lowest.getValue());
            if (image != null) {
                fileName = image.getChild("init_from").getText();
                texture = loadTexture2D(fileName, min);
            }

            // TODO: add support for mip map levels other than 0.
        }
        // TODO: add support for the other texture types.
    } else {
        // No surface OR image... warn.
        logger.warning("texture given with no matching <sampler*> or <image> found.");
        if (info != null) {
            info.setTextureSlot(textureSlot, textureReference, null, null);
        }
        return null;
    }

    if (texture != null) {
        if (sampler != null) {
            // Apply params from our sampler.
            applySampler(sampler, texture);
        }

        // Add to texture state.
        tState.setTexture(texture, tState.getNumberOfSetTextures());
        loadedTextures.put(textureReference, texture);
        if (info != null) {
            info.setTextureSlot(textureSlot, textureReference, texture, fileName);
        }
    } else {
        logger.warning("unable to load texture: " + daeTexture);
        if (info != null) {
            info.setTextureSlot(textureSlot, textureReference, null, fileName);
        }
    }

    return texture;
}

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

License:Open Source License

private void applySampler(final Element sampler, final Texture texture) {
    if (sampler.getChild("minfilter") != null) {
        final String minfilter = sampler.getChild("minfilter").getText();
        texture.setMinificationFilter(/*  ww  w.j a  va  2  s  . c  om*/
                Enum.valueOf(SamplerTypes.MinFilterType.class, minfilter).getArdor3dFilter());
    }
    if (sampler.getChild("magfilter") != null) {
        final String magfilter = sampler.getChild("magfilter").getText();
        texture.setMagnificationFilter(
                Enum.valueOf(SamplerTypes.MagFilterType.class, magfilter).getArdor3dFilter());
    }
    if (sampler.getChild("wrap_s") != null) {
        final String wrapS = sampler.getChild("wrap_s").getText();
        texture.setWrap(Texture.WrapAxis.S,
                Enum.valueOf(SamplerTypes.WrapModeType.class, wrapS).getArdor3dWrapMode());
    }
    if (sampler.getChild("wrap_t") != null) {
        final String wrapT = sampler.getChild("wrap_t").getText();
        texture.setWrap(Texture.WrapAxis.T,
                Enum.valueOf(SamplerTypes.WrapModeType.class, wrapT).getArdor3dWrapMode());
    }
    if (sampler.getChild("border_color") != null) {
        texture.setBorderColor(_colladaDOMUtil.getColor(sampler.getChild("border_color").getText()));
    }
}

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

License:Open Source License

@SuppressWarnings("unchecked")
public void bindMaterials(final Element bindMaterial) {
    if (bindMaterial == null || bindMaterial.getChildren().isEmpty()) {
        return;/* ww w.  j a va  2s.c  om*/
    }

    for (final Element instance : bindMaterial.getChild("technique_common").getChildren("instance_material")) {
        final Element matNode = _colladaDOMUtil.findTargetWithId(instance.getAttributeValue("target"));
        if (matNode != null && "material".equals(matNode.getName())) {
            _dataCache.bindMaterial(instance.getAttributeValue("symbol"), matNode);
        } else {
            logger.warning("instance material target not found: " + instance.getAttributeValue("target"));
        }

        // TODO: need to store bound vert data as local data. (also unstore on unbind.)
    }
}

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

License:Open Source License

@SuppressWarnings("unchecked")
public void unbindMaterials(final Element bindMaterial) {
    if (bindMaterial == null || bindMaterial.getChildren().isEmpty()) {
        return;//ww w  .j a  v a  2 s  . co m
    }
    for (final Element instance : bindMaterial.getChild("technique_common").getChildren("instance_material")) {
        _dataCache.unbindMaterial(instance.getAttributeValue("symbol"));
    }
}

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

License:Open Source License

/**
 * Builds a mesh from a Collada geometry element. Currently supported mesh types: mesh, polygons, polylist,
 * triangles, lines. Not supported yet: linestrips, trifans, tristrips. If no meshtype is found, a pointcloud is
 * built.//w w  w.  java2s  . c  om
 * 
 * @param colladaGeometry
 * @return a Node containing all of the Ardor3D meshes we've parsed from this geometry element.
 */
public Node buildMesh(final Element colladaGeometry) {
    if (colladaGeometry.getChild("mesh") != null) {
        final Element cMesh = colladaGeometry.getChild("mesh");
        final Node meshNode = new Node(colladaGeometry.getAttributeValue("name", colladaGeometry.getName()));

        // Grab all mesh types (polygons, triangles, etc.)
        // Create each as an Ardor3D Mesh, and attach to node
        boolean hasChild = false;
        if (cMesh.getChild("polygons") != null) {
            for (final Element p : cMesh.getChildren("polygons")) {
                final Mesh child = buildMeshPolygons(colladaGeometry, p);
                if (child != null) {
                    if (child.getName() == null) {
                        child.setName(meshNode.getName() + "_polygons");
                    }
                    meshNode.attachChild(child);
                    hasChild = true;
                }
            }
        }
        if (cMesh.getChild("polylist") != null) {
            for (final Element p : cMesh.getChildren("polylist")) {
                final Mesh child = buildMeshPolylist(colladaGeometry, p);
                if (child != null) {
                    if (child.getName() == null) {
                        child.setName(meshNode.getName() + "_polylist");
                    }
                    meshNode.attachChild(child);
                    hasChild = true;
                }
            }
        }
        if (cMesh.getChild("triangles") != null) {
            for (final Element t : cMesh.getChildren("triangles")) {
                final Mesh child = buildMeshTriangles(colladaGeometry, t);
                if (child != null) {
                    if (child.getName() == null) {
                        child.setName(meshNode.getName() + "_triangles");
                    }
                    meshNode.attachChild(child);
                    hasChild = true;
                }
            }
        }
        if (cMesh.getChild("lines") != null) {
            for (final Element l : cMesh.getChildren("lines")) {
                final Line child = buildMeshLines(colladaGeometry, l);
                if (child != null) {
                    if (child.getName() == null) {
                        child.setName(meshNode.getName() + "_lines");
                    }
                    meshNode.attachChild(child);
                    hasChild = true;
                }
            }
        }
        if (cMesh.getChild("linestrips") != null) {
            logger.warning("<linestrips> not currently supported.");
            hasChild = true;
            // TODO: Add support
        }
        if (cMesh.getChild("trifans") != null) {
            logger.warning("<trifan> not currently supported.");
            hasChild = true;
            // TODO: Add support
        }
        if (cMesh.getChild("tristrips") != null) {
            logger.warning("<tristrip> not currently supported.");
            hasChild = true;
            // TODO: Add support
        }

        // If we did not find a valid child, the spec says to add verts as a "cloud of points"
        if (!hasChild) {
            logger.warning("No valid child found, creating 'cloud of points'");
            final Point points = buildPoints(colladaGeometry, cMesh);
            if (points != null) {
                if (points.getName() == null) {
                    points.setName(meshNode.getName() + "_points");
                }
                meshNode.attachChild(points);
            }
        }

        return meshNode;
    }
    return null;
}

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

License:Open Source License

private Point buildPoints(final Element colladaGeometry, final Element mesh) {
    if (mesh == null || mesh.getChild("vertices") == null
            || mesh.getChild("vertices").getChild("input") == null) {
        return null;
    }/*from w  w  w  .  j  av  a2s  . c om*/
    final Point points = new Point();
    points.setName(mesh.getAttributeValue("name", mesh.getName()));

    // Find POSITION vertices source
    final Element source = _colladaDOMUtil.getPositionSource(mesh.getChild("vertices"));
    if (source == null) {
        return null;
    }

    if (source.getChild("float_array") != null) {
        // Turn into Floatbuffer if we have float array data
        final Element floatArray = source.getChild("float_array");
        if ("0".equals(floatArray.getAttributeValue("count"))) {
            return null;
        }
        final FloatBuffer vertices = BufferUtils.createFloatBuffer(_colladaDOMUtil.parseFloatArray(floatArray));
        // Add to points
        points.getMeshData().setVertexBuffer(vertices);
    } else if (source.getChild("int_array") != null) {
        // Turn into Floatbuffer if we have int array data
        final Element intArray = source.getChild("int_array");
        if ("0".equals(intArray.getAttributeValue("count"))) {
            return null;
        }
        final int[] data = _colladaDOMUtil.parseIntArray(intArray);
        final FloatBuffer vertices = BufferUtils.createFloatBuffer(data.length);
        for (final int i : data) {
            vertices.put(i);
        }
        // Add to points
        points.getMeshData().setVertexBuffer(vertices);
    }

    // Add to vert mapping
    final int[] indices = new int[points.getMeshData().getVertexCount()];
    for (int i = 0; i < indices.length; i++) {
        indices[i] = i;
    }
    final MeshVertPairs mvp = new MeshVertPairs(points, indices);
    _dataCache.getVertMappings().put(colladaGeometry, mvp);

    if (_optimizeMeshes) {
        final VertMap map = _geometryTool.minimizeVerts(points, _optimizeSettings);
        _dataCache.setMeshVertMap(points, map);
    }

    // Update bound
    points.updateModelBound();

    // return
    return points;
}

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

License:Open Source License

public Mesh buildMeshPolygons(final Element colladaGeometry, final Element polys) {
    if (polys == null || polys.getChild("input") == null) {
        return null;
    }/*from  w  ww.jav  a  2s.  c o m*/
    final Mesh polyMesh = new Mesh(extractName(colladaGeometry, polys));
    polyMesh.getMeshData().setIndexMode(IndexMode.Triangles);

    // Build and set RenderStates for our material
    _colladaMaterialUtils.applyMaterial(polys.getAttributeValue("material"), polyMesh);

    final LinkedList<ColladaInputPipe> pipes = new LinkedList<ColladaInputPipe>();
    final int maxOffset = extractPipes(polys, pipes);
    final int interval = maxOffset + 1;

    // use interval & sum of sizes of p entries to determine buffer sizes.
    int numEntries = 0;
    int numIndices = 0;
    for (final Element vals : polys.getChildren("p")) {
        final int length = _colladaDOMUtil.parseIntArray(vals).length;
        numEntries += length;
        numIndices += (length / interval - 2) * 3;
    }
    numEntries /= interval;

    // Construct nio buffers for specified inputs.
    for (final ColladaInputPipe pipe : pipes) {
        pipe.setupBuffer(numEntries, polyMesh.getMeshData(), _dataCache);
    }

    // Add to vert mapping
    final int[] indices = new int[numEntries];
    final MeshVertPairs mvp = new MeshVertPairs(polyMesh, indices);
    _dataCache.getVertMappings().put(colladaGeometry, mvp);

    // Prepare indices buffer
    final IndexBufferData<?> meshIndices = BufferUtils.createIndexBufferData(numIndices,
            polyMesh.getMeshData().getVertexCount() - 1);
    polyMesh.getMeshData().setIndices(meshIndices);

    // go through the polygon entries
    int firstIndex = 0, vecIndex;
    final int[] currentVal = new int[interval];
    for (final Element dia : polys.getChildren("p")) {
        // for each p, iterate using max offset
        final int[] vals = _colladaDOMUtil.parseIntArray(dia);

        final int first = firstIndex + 0;
        System.arraycopy(vals, 0, currentVal, 0, interval);
        vecIndex = processPipes(pipes, currentVal);
        if (vecIndex != Integer.MIN_VALUE) {
            indices[firstIndex + 0] = vecIndex;
        }

        int prev = firstIndex + 1;
        System.arraycopy(vals, interval, currentVal, 0, interval);
        vecIndex = processPipes(pipes, currentVal);
        if (vecIndex != Integer.MIN_VALUE) {
            indices[firstIndex + 1] = vecIndex;
        }

        // first add the first two entries to the buffers.

        // Now go through remaining entries and create a polygon as a triangle fan.
        for (int j = 2, max = vals.length / interval; j < max; j++) {
            // add first as index
            meshIndices.put(first);
            // add prev as index
            meshIndices.put(prev);

            // set prev to current
            prev = firstIndex + j;
            // add current to buffers
            System.arraycopy(vals, j * interval, currentVal, 0, interval);
            vecIndex = processPipes(pipes, currentVal);
            if (vecIndex != Integer.MIN_VALUE) {
                indices[firstIndex + j] = vecIndex;
            }
            // add current as index
            meshIndices.put(prev);
        }
        firstIndex += vals.length / interval;
    }

    if (_optimizeMeshes) {
        final VertMap map = _geometryTool.minimizeVerts(polyMesh, _optimizeSettings);
        _dataCache.setMeshVertMap(polyMesh, map);
    }

    // update bounds
    polyMesh.updateModelBound();

    // return
    return polyMesh;
}

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

License:Open Source License

public Mesh buildMeshPolylist(final Element colladaGeometry, final Element polys) {
    if (polys == null || polys.getChild("input") == null) {
        return null;
    }//w  w w  .  j av a 2s .  c  o m
    final Mesh polyMesh = new Mesh(extractName(colladaGeometry, polys));
    polyMesh.getMeshData().setIndexMode(IndexMode.Triangles);

    // Build and set RenderStates for our material
    _colladaMaterialUtils.applyMaterial(polys.getAttributeValue("material"), polyMesh);

    final LinkedList<ColladaInputPipe> pipes = new LinkedList<ColladaInputPipe>();
    final int maxOffset = extractPipes(polys, pipes);
    final int interval = maxOffset + 1;

    // use interval & sum of sizes of vcount to determine buffer sizes.
    int numEntries = 0;
    int numIndices = 0;
    for (final int length : _colladaDOMUtil.parseIntArray(polys.getChild("vcount"))) {
        numEntries += length;
        numIndices += (length - 2) * 3;
    }

    // Construct nio buffers for specified inputs.
    for (final ColladaInputPipe pipe : pipes) {
        pipe.setupBuffer(numEntries, polyMesh.getMeshData(), _dataCache);
    }

    // Add to vert mapping
    final int[] indices = new int[numEntries];
    final MeshVertPairs mvp = new MeshVertPairs(polyMesh, indices);
    _dataCache.getVertMappings().put(colladaGeometry, mvp);

    // Prepare indices buffer
    final IndexBufferData<?> meshIndices = BufferUtils.createIndexBufferData(numIndices,
            polyMesh.getMeshData().getVertexCount() - 1);
    polyMesh.getMeshData().setIndices(meshIndices);

    // go through the polygon entries
    int firstIndex = 0;
    int vecIndex;
    final int[] vals = _colladaDOMUtil.parseIntArray(polys.getChild("p"));
    for (final int length : _colladaDOMUtil.parseIntArray(polys.getChild("vcount"))) {
        final int[] currentVal = new int[interval];

        // first add the first two entries to the buffers.
        final int first = firstIndex + 0;
        System.arraycopy(vals, (first * interval), currentVal, 0, interval);
        vecIndex = processPipes(pipes, currentVal);
        if (vecIndex != Integer.MIN_VALUE) {
            indices[firstIndex + 0] = vecIndex;
        }

        int prev = firstIndex + 1;
        System.arraycopy(vals, (prev * interval), currentVal, 0, interval);
        vecIndex = processPipes(pipes, currentVal);
        if (vecIndex != Integer.MIN_VALUE) {
            indices[firstIndex + 1] = vecIndex;
        }

        // Now go through remaining entries and create a polygon as a triangle fan.
        for (int j = 2, max = length; j < max; j++) {
            // add first as index
            meshIndices.put(first);
            // add prev as index
            meshIndices.put(prev);

            // set prev to current
            prev = firstIndex + j;
            // add current to buffers
            System.arraycopy(vals, (prev * interval), currentVal, 0, interval);
            vecIndex = processPipes(pipes, currentVal);
            if (vecIndex != Integer.MIN_VALUE) {
                indices[firstIndex + j] = vecIndex;
            }
            // add current as index
            meshIndices.put(prev);
        }
        firstIndex += length;
    }

    if (_optimizeMeshes) {
        final VertMap map = _geometryTool.minimizeVerts(polyMesh, _optimizeSettings);
        _dataCache.setMeshVertMap(polyMesh, map);
    }

    // update bounds
    polyMesh.updateModelBound();

    // return
    return polyMesh;
}