List of usage examples for org.jdom2 Element getChildren
public List<Element> getChildren(final String cname)
List
of all the child elements nested directly (one level deep) within this element with the given local name and belonging to no namespace, returned as Element
objects. From source file:com.archimatetool.model.viewpoints.ViewpointManager.java
License:Open Source License
/** * Load viewpoints from XML file/* w w w. jav a 2 s. c om*/ */ 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.TemplateManager.java
License:Open Source License
/** * Load all user templates as declared in the manifest *///from ww w . j av a 2 s. c o m protected void loadUserTemplates() { fUserTemplates = new ArrayList<ITemplate>(); fUserTemplateGroups = new ArrayList<ITemplateGroup>(); if (!getUserTemplatesManifestFile().exists()) { return; } Document doc = null; try { doc = JDOMUtils.readXMLFile(getUserTemplatesManifestFile()); } catch (Exception ex) { ex.printStackTrace(); return; } HashMap<String, ITemplate> userTemplateMap = new HashMap<String, ITemplate>(); Element rootElement = doc.getRootElement(); // Templates for (Object child : rootElement.getChildren(XML_TEMPLATE_ELEMENT_TEMPLATE)) { Element templateElement = (Element) child; String type = templateElement.getAttributeValue(XML_TEMPLATE_ATTRIBUTE_TYPE); ITemplate template = createTemplate(type); if (template != null) { String id = templateElement.getAttributeValue(XML_TEMPLATE_ATTRIBUTE_ID); String path = templateElement.getAttributeValue(XML_TEMPLATE_ATTRIBUTE_FILE); if (id != null && path != null) { File file = new File(path); if (file.exists()) { template.setID(id); template.setFile(file); fUserTemplates.add(template); userTemplateMap.put(id, template); } } } } // Groups for (Object child : rootElement.getChildren(XML_TEMPLATE_ELEMENT_GROUP)) { Element groupElement = (Element) child; ITemplateGroup templateGroup = new TemplateGroup(); templateGroup.setName(groupElement.getAttributeValue(XML_TEMPLATE_ATTRIBUTE_NAME)); fUserTemplateGroups.add(templateGroup); // Template refs for (Object child2 : groupElement.getChildren(XML_TEMPLATE_ELEMENT_TEMPLATE_REF)) { Element templateRefElement = (Element) child2; String ref = templateRefElement.getAttributeValue(XML_TEMPLATE_ATTRIBUTE_REF); if (ref != null) { ITemplate template = userTemplateMap.get(ref); if (template != null) { templateGroup.addTemplate(template); } } } } }
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.j a v a 2s . c om * @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
/** * Gather up all animation channels based on what nodes they affect. * //w w w. j a v a2 s . c om * @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.ColladaDOMUtil.java
License:Open Source License
/** * Find Element with semantic POSITION under an element with inputs * //from www . ja v a2s . 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); }
From source file:com.ardor3d.extension.model.collada.jdom.ColladaInputPipe.java
License:Open Source License
@SuppressWarnings("unchecked") public ColladaInputPipe(final ColladaDOMUtil colladaDOMUtil, final Element input) { // Setup our type try {/*from w w w .j ava 2 s . c o m*/ _type = Type.valueOf(input.getAttributeValue("semantic")); } catch (final Exception ex) { ColladaInputPipe.logger.warning("Unknown input type: " + input.getAttributeValue("semantic")); _type = Type.UNKNOWN; } // Locate our source final Element n = colladaDOMUtil.findTargetWithId(input.getAttributeValue("source")); if (n == null) { throw new ColladaException("Input source not found: " + input.getAttributeValue("source"), input); } if ("source".equals(n.getName())) { _source = n; } else if ("vertices".equals(n.getName())) { _source = colladaDOMUtil.getPositionSource(n); } else { throw new ColladaException("Input source not found: " + input.getAttributeValue("source"), input); } // TODO: Need to go through the params and see if they have a name set, and skip values if not when // parsing the array? _sourceData = new SourceData(); if (_source.getChild("float_array") != null) { _sourceData.floatArray = colladaDOMUtil.parseFloatArray(_source.getChild("float_array")); _sourceData.paramType = ParamType.float_param; } else if (_source.getChild("bool_array") != null) { _sourceData.boolArray = colladaDOMUtil.parseBooleanArray(_source.getChild("bool_array")); _sourceData.paramType = ParamType.bool_param; } else if (_source.getChild("int_array") != null) { _sourceData.intArray = colladaDOMUtil.parseIntArray(_source.getChild("int_array")); _sourceData.paramType = ParamType.int_param; } else if (_source.getChild("Name_array") != null) { _sourceData.stringArray = colladaDOMUtil.parseStringArray(_source.getChild("Name_array")); _sourceData.paramType = ParamType.name_param; } else if (_source.getChild("IDREF_array") != null) { _sourceData.stringArray = colladaDOMUtil.parseStringArray(_source.getChild("IDREF_array")); _sourceData.paramType = ParamType.idref_param; } // add a hook to our params from the technique_common final Element accessor = getCommonAccessor(_source); if (accessor != null) { if (ColladaInputPipe.logger.isLoggable(Level.FINE)) { ColladaInputPipe.logger.fine("Creating buffers for: " + _source.getAttributeValue("id")); } final List<Element> params = accessor.getChildren("param"); _paramCount = params.size(); // Might use this info for real later, but use for testing for unsupported param skipping. boolean skippedParam = false; for (final Element param : params) { final String paramName = param.getAttributeValue("name"); if (paramName == null) { skippedParam = true; break; } // String paramType = param.getAttributeValue("type"); } if (_paramCount > 1 && skippedParam) { ColladaInputPipe.logger.warning("Parameter skipping not yet supported when parsing sources. " + _source.getAttributeValue("id")); } _sourceData.count = colladaDOMUtil.getAttributeIntValue(accessor, "count", 0); _sourceData.stride = colladaDOMUtil.getAttributeIntValue(accessor, "stride", 1); _sourceData.offset = colladaDOMUtil.getAttributeIntValue(accessor, "offset", 0); } // save our offset _offset = colladaDOMUtil.getAttributeIntValue(input, "offset", 0); _set = colladaDOMUtil.getAttributeIntValue(input, "set", 0); _texCoord = 0; }
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./*from w w w. j a v a 2 s . 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
public Mesh buildMeshPolygons(final Element colladaGeometry, final Element polys) { if (polys == null || polys.getChild("input") == null) { return null; }/* w w w . j a v a2 s. 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
/** * Extract our pipes from the given parent element. * //from w ww .j a v a2 s. com * @param inputsParent * @param pipesStore * the store for our pipes * @return the max offset of our pipes. */ private int extractPipes(final Element inputsParent, final LinkedList<ColladaInputPipe> pipesStore) { int maxOffset = 0; int texCount = 0; for (final Element input : inputsParent.getChildren("input")) { maxOffset = Math.max(maxOffset, _colladaDOMUtil.getAttributeIntValue(input, "offset", 0)); try { final Type type = Type.valueOf(input.getAttributeValue("semantic")); if (type == Type.VERTEX) { final Element vertexElement = _colladaDOMUtil .findTargetWithId(input.getAttributeValue("source")); for (final Element vertexInput : vertexElement.getChildren("input")) { vertexInput.setAttribute("offset", input.getAttributeValue("offset")); vertexInput.setAttribute("isVertexDefined", "true"); final ColladaInputPipe pipe = new ColladaInputPipe(_colladaDOMUtil, vertexInput); if (pipe.getType() == Type.TEXCOORD) { pipe.setTexCoord(texCount++); } pipesStore.add(pipe); } } else { final ColladaInputPipe pipe = new ColladaInputPipe(_colladaDOMUtil, input); if (pipe.getType() == Type.TEXCOORD) { pipe.setTexCoord(texCount++); } pipesStore.add(pipe); } } catch (final Exception ex) { logger.warning("Unknown input type: " + input.getAttributeValue("semantic")); continue; } } return maxOffset; }
From source file:com.ardor3d.extension.model.collada.jdom.ColladaNodeUtils.java
License:Open Source License
/** * Retrieves the scene and returns it as an Ardor3D Node. * /* w w w. ja v a 2 s .com*/ * @param colladaRoot * The collada root element * @return Scene as an Node or null if not found */ @SuppressWarnings("unchecked") public Node getVisualScene(final Element colladaRoot) { if (colladaRoot.getChild("scene") == null) { logger.warning("No scene found in collada file!"); return null; } final Element instance_visual_scene = colladaRoot.getChild("scene").getChild("instance_visual_scene"); if (instance_visual_scene == null) { logger.warning("No instance_visual_scene found in collada file!"); return null; } final Element visualScene = _colladaDOMUtil .findTargetWithId(instance_visual_scene.getAttributeValue("url")); if (visualScene != null) { final Node sceneRoot = new Node( visualScene.getAttributeValue("name") != null ? visualScene.getAttributeValue("name") : "Collada Root"); // Load each sub node and attach final JointNode baseJointNode = new JointNode(null); _dataCache.setRootJointNode(baseJointNode); for (final Element n : visualScene.getChildren("node")) { final Node subNode = buildNode(n, baseJointNode); if (subNode != null) { sceneRoot.attachChild(subNode); } } // build a list of joints - one list per skeleton - and build a skeleton for each joint list. for (final JointNode jointChildNode : _dataCache.getRootJointNode().getChildren()) { final List<Joint> jointList = Lists.newArrayList(); buildJointLists(jointChildNode, jointList); final Joint[] joints = jointList.toArray(new Joint[jointList.size()]); final Skeleton skeleton = new Skeleton(joints[0].getName() + "_skeleton", joints); if (logger.isLoggable(Level.FINE)) { logger.fine("skeleton created: " + skeleton.getName()); } for (final Joint joint : jointList) { _dataCache.getJointSkeletonMapping().put(joint, skeleton); if (logger.isLoggable(Level.FINE)) { logger.fine("- Joint " + joint.getName() + " - index: " + joint.getIndex() + " parent index: " + joint.getParentIndex()); } } _dataCache.addSkeleton(skeleton); } // update our world transforms so we can use them to init the default bind matrix of any joints. sceneRoot.updateWorldTransform(true); initDefaultJointTransforms(baseJointNode); // Setup our skinned mesh objects. for (final ControllerStore controllerStore : _dataCache.getControllers()) { _colladaMaterialUtils.bindMaterials(controllerStore.instanceController.getChild("bind_material")); _colladaAnimUtils.buildController(controllerStore.ardorParentNode, controllerStore.instanceController); _colladaMaterialUtils.unbindMaterials(controllerStore.instanceController.getChild("bind_material")); } return sceneRoot; } return null; }