Search in sources :

Example 1 with HashMap

use of net.drewke.tdme.utils.HashMap in project tdme by andreasdr.

the class DAEReader method readNode.

/**
	 * Reads a DAE visual scene group node
	 * @param authoring tool
	 * @param path name
	 * @param model
	 * @param parent group
	 * @param xml node
	 * @param xml root
	 * @param frames per seconds
	 * @throws Exception
	 * @return group
	 */
private static Group readNode(AuthoringTool authoringTool, String pathName, Model model, Group parentGroup, Element xmlRoot, Element xmlNode, float fps) throws Exception {
    String xmlNodeId = xmlNode.getAttribute("id");
    String xmlNodeName = xmlNode.getAttribute("name");
    if (xmlNodeId.length() == 0)
        xmlNodeId = xmlNodeName;
    StringTokenizer t = null;
    // default node matrix
    Matrix4x4 transformationsMatrix = null;
    // set up local transformations matrix
    List<Element> xmlMatrixElements = getChildrenByTagName(xmlNode, "matrix");
    if (xmlMatrixElements.size() == 1) {
        String xmlMatrix = getChildrenByTagName(xmlNode, "matrix").get(0).getTextContent();
        t = new StringTokenizer(xmlMatrix, " \n\r");
        // 
        transformationsMatrix = new Matrix4x4(Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken())).transpose();
    }
    // tdme model definitions
    Group group = new Group(model, parentGroup, xmlNodeId, xmlNodeName);
    //
    if (transformationsMatrix != null) {
        group.getTransformationsMatrix().multiply(transformationsMatrix);
    }
    // parse animations
    List<Element> xmlAnimationsLibrary = getChildrenByTagName(xmlRoot, "library_animations");
    if (xmlAnimationsLibrary.isEmpty() == false) {
        List<Element> xmlAnimations = getChildrenByTagName(xmlAnimationsLibrary.get(0), "animation");
        for (Element xmlAnimation : xmlAnimations) {
            // older DAE has animation/animation xml nodes
            List<Element> _xmlAnimation = getChildrenByTagName(xmlAnimation, "animation");
            if (_xmlAnimation.isEmpty() == false) {
                xmlAnimation = _xmlAnimation.get(0);
            }
            // find sampler source
            String xmlSamplerSource = null;
            Element xmlChannel = getChildrenByTagName(xmlAnimation, "channel").get(0);
            if (xmlChannel.getAttribute("target").startsWith(xmlNodeId + "/")) {
                xmlSamplerSource = xmlChannel.getAttribute("source").substring(1);
            }
            // check for sampler source
            if (xmlSamplerSource == null) {
                continue;
            }
            // parse animation output matrices
            String xmlSamplerOutputSource = null;
            String xmlSamplerInputSource = null;
            Element xmlSampler = getChildrenByTagName(xmlAnimation, "sampler").get(0);
            for (Element xmlSamplerInput : getChildrenByTagName(xmlSampler, "input")) {
                if (xmlSamplerInput.getAttribute("semantic").equals("OUTPUT")) {
                    xmlSamplerOutputSource = xmlSamplerInput.getAttribute("source").substring(1);
                } else if (xmlSamplerInput.getAttribute("semantic").equals("INPUT")) {
                    xmlSamplerInputSource = xmlSamplerInput.getAttribute("source").substring(1);
                }
            }
            // check for sampler source
            if (xmlSamplerOutputSource == null) {
                throw new ModelFileIOException("Could not find xml sampler output source for animation for " + xmlNodeId);
            }
            // load animation input matrices
            // TODO: check accessor "time"
            float[] keyFrameTimes = null;
            for (Element xmlAnimationSource : getChildrenByTagName(xmlAnimation, "source")) {
                if (xmlAnimationSource.getAttribute("id").equals(xmlSamplerInputSource)) {
                    Element xmlFloatArray = getChildrenByTagName(xmlAnimationSource, "float_array").get(0);
                    int frames = Integer.parseInt(xmlFloatArray.getAttribute("count"));
                    String valueString = xmlFloatArray.getTextContent();
                    int keyFrameIdx = 0;
                    keyFrameTimes = new float[frames];
                    t = new StringTokenizer(valueString, " \n\r");
                    while (t.hasMoreTokens()) {
                        keyFrameTimes[keyFrameIdx++] = Float.parseFloat(t.nextToken());
                    }
                }
            }
            // load animation output matrices
            // TODO: check accessor "transform"
            Matrix4x4[] keyFrameMatrices = null;
            for (Element xmlAnimationSource : getChildrenByTagName(xmlAnimation, "source")) {
                if (xmlAnimationSource.getAttribute("id").equals(xmlSamplerOutputSource)) {
                    Element xmlFloatArray = getChildrenByTagName(xmlAnimationSource, "float_array").get(0);
                    int keyFrames = Integer.parseInt(xmlFloatArray.getAttribute("count")) / 16;
                    // some models have animations without frames
                    if (keyFrames > 0) {
                        String valueString = xmlFloatArray.getTextContent();
                        t = new StringTokenizer(valueString, " \n\r");
                        // parse key frame
                        int keyFrameIdx = 0;
                        keyFrameMatrices = new Matrix4x4[keyFrames];
                        while (t.hasMoreTokens()) {
                            // set animation transformation matrix at frame
                            keyFrameMatrices[keyFrameIdx] = new Matrix4x4(Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken())).transpose();
                            keyFrameIdx++;
                        }
                    }
                }
            }
            // create linear animation by key frame times and key frames
            if (keyFrameTimes != null && keyFrameMatrices != null) {
                int frames = (int) Math.ceil(keyFrameTimes[keyFrameTimes.length - 1] * fps);
                // create default animation
                ModelHelper.createDefaultAnimation(model, frames);
                //
                Animation animation = group.createAnimation(frames);
                Matrix4x4[] transformationsMatrices = animation.getTransformationsMatrices();
                Matrix4x4 tansformationsMatrixLast = keyFrameMatrices[0];
                int keyFrameIdx = 0;
                int frameIdx = 0;
                float timeStampLast = 0.0f;
                for (float keyFrameTime : keyFrameTimes) {
                    Matrix4x4 transformationsMatrixCurrent = keyFrameMatrices[(keyFrameIdx) % keyFrameMatrices.length];
                    float timeStamp;
                    for (timeStamp = timeStampLast; timeStamp < keyFrameTime; timeStamp += 1.0f / fps) {
                        if (frameIdx >= frames) {
                            System.out.println("Warning: skipping frame: " + frameIdx);
                            frameIdx++;
                            continue;
                        }
                        Matrix4x4.interpolateLinear(tansformationsMatrixLast, transformationsMatrixCurrent, (timeStamp - timeStampLast) / (keyFrameTime - timeStampLast), transformationsMatrices[frameIdx]);
                        frameIdx++;
                    }
                    timeStampLast = timeStamp;
                    tansformationsMatrixLast = transformationsMatrixCurrent;
                    keyFrameIdx++;
                }
            }
        }
    }
    // parse sub groups
    for (Element _xmlNode : getChildrenByTagName(xmlNode, "node")) {
        Group _group = readVisualSceneNode(authoringTool, pathName, model, group, xmlRoot, _xmlNode, fps);
        if (_group != null) {
            group.getSubGroups().put(_group.getId(), _group);
            model.getGroups().put(_group.getId(), _group);
        }
    }
    // check for geometry data
    String xmlInstanceGeometryId = null;
    List<Element> xmlInstanceGeometryElements = getChildrenByTagName(xmlNode, "instance_geometry");
    if (xmlInstanceGeometryElements.isEmpty() == false) {
        Element xmlInstanceGeometryElement = xmlInstanceGeometryElements.get(0);
        // fetch instance geometry url
        xmlInstanceGeometryId = xmlInstanceGeometryElement.getAttribute("url").substring(1);
        // determine bound materials
        HashMap<String, String> materialSymbols = new HashMap<String, String>();
        for (Element xmlBindMaterial : getChildrenByTagName(xmlInstanceGeometryElement, "bind_material")) for (Element xmlTechniqueCommon : getChildrenByTagName(xmlBindMaterial, "technique_common")) for (Element xmlInstanceMaterial : getChildrenByTagName(xmlTechniqueCommon, "instance_material")) {
            materialSymbols.put(xmlInstanceMaterial.getAttribute("symbol"), xmlInstanceMaterial.getAttribute("target"));
        }
        // parse geometry
        readGeometry(authoringTool, pathName, model, group, xmlRoot, xmlInstanceGeometryId, materialSymbols);
        //
        return group;
    }
    // otherwise check for "instance_node"
    String xmlInstanceNodeId = null;
    for (Element xmlInstanceNodeElement : getChildrenByTagName(xmlNode, "instance_node")) {
        xmlInstanceNodeId = xmlInstanceNodeElement.getAttribute("url").substring(1);
    }
    // do we have a instance node id?
    if (xmlInstanceNodeId != null) {
        for (Element xmlLibraryNodes : getChildrenByTagName(xmlRoot, "library_nodes")) for (Element xmlLibraryNode : getChildrenByTagName(xmlLibraryNodes, "node")) if (xmlLibraryNode.getAttribute("id").equals(xmlInstanceNodeId)) {
            // parse sub groups
            for (Element _xmlNode : getChildrenByTagName(xmlLibraryNode, "node")) {
                Group _group = readVisualSceneNode(authoringTool, pathName, model, parentGroup, xmlRoot, _xmlNode, fps);
                if (_group != null) {
                    group.getSubGroups().put(_group.getId(), _group);
                    model.getGroups().put(_group.getId(), _group);
                }
            }
            // parse geometry 
            for (Element xmlInstanceGeometry : getChildrenByTagName(xmlLibraryNode, "instance_geometry")) {
                String xmlGeometryId = xmlInstanceGeometry.getAttribute("url").substring(1);
                // parse material symbols
                HashMap<String, String> materialSymbols = new HashMap<String, String>();
                for (Element xmlBindMaterial : getChildrenByTagName(xmlInstanceGeometry, "bind_material")) for (Element xmlTechniqueCommon : getChildrenByTagName(xmlBindMaterial, "technique_common")) for (Element xmlInstanceMaterial : getChildrenByTagName(xmlTechniqueCommon, "instance_material")) {
                    materialSymbols.put(xmlInstanceMaterial.getAttribute("symbol"), xmlInstanceMaterial.getAttribute("target"));
                }
                // parse geometry
                readGeometry(authoringTool, pathName, model, group, xmlRoot, xmlGeometryId, materialSymbols);
            }
        }
    }
    //
    return group;
}
Also used : Group(net.drewke.tdme.engine.model.Group) HashMap(net.drewke.tdme.utils.HashMap) Element(org.w3c.dom.Element) Matrix4x4(net.drewke.tdme.math.Matrix4x4) Joint(net.drewke.tdme.engine.model.Joint) StringTokenizer(java.util.StringTokenizer) Animation(net.drewke.tdme.engine.model.Animation)

Example 2 with HashMap

use of net.drewke.tdme.utils.HashMap in project tdme by andreasdr.

the class WFObjReader method readMaterials.

/**
	 * Reads a wavefront object material library
	 * @param path name
	 * @param file name
	 * @return
	 */
private static HashMap<String, Material> readMaterials(String pathName, String fileName) throws IOException {
    HashMap<String, Material> materials = new HashMap<String, Material>();
    Material current = null;
    //
    DataInputStream inputStream = new DataInputStream(FileSystem.getInstance().getInputStream(pathName, fileName));
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String line;
    float alpha = 1.0f;
    while ((line = reader.readLine()) != null) {
        line = line.trim();
        // skip on comments
        if (line.startsWith("#")) {
            continue;
        }
        // determine index of first ' ' which will separate command from arguments
        int commandEndIdx = line.indexOf(' ');
        if (commandEndIdx == -1)
            commandEndIdx = line.length();
        // determine command
        String command = line.substring(0, commandEndIdx).trim().toLowerCase();
        // determine arguments if any exist
        String arguments = command.length() + 1 > line.length() ? "" : line.substring(command.length() + 1);
        // parse
        if (command.equals("newmtl")) {
            String name = arguments;
            current = new Material(name);
            materials.put(name, current);
        } else if (command.equals("map_ka")) {
            current.setDiffuseTexture(pathName, arguments);
        } else if (command.equals("map_kd")) {
            current.setDiffuseTexture(pathName, arguments);
        } else if (command.equals("ka")) {
            StringTokenizer t = new StringTokenizer(arguments, " ");
            current.getAmbientColor().set(Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), alpha);
        } else if (command.equals("kd")) {
            StringTokenizer t = new StringTokenizer(arguments, " ");
            current.getDiffuseColor().set(Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), alpha);
        } else if (command.equals("ks")) {
            StringTokenizer t = new StringTokenizer(arguments, " ");
            current.getSpecularColor().set(Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), alpha);
        } else if (command.equals("tr")) {
            alpha = Float.parseFloat(arguments);
            current.getAmbientColor().setAlpha(alpha);
            current.getDiffuseColor().setAlpha(alpha);
            current.getSpecularColor().setAlpha(alpha);
            current.getEmissionColor().setAlpha(alpha);
        } else if (command.equals("d")) {
            alpha = Float.parseFloat(arguments);
            current.getAmbientColor().setAlpha(alpha);
            current.getDiffuseColor().setAlpha(alpha);
            current.getSpecularColor().setAlpha(alpha);
            current.getEmissionColor().setAlpha(alpha);
        }
    }
    // Close the input stream
    inputStream.close();
    //
    return materials;
}
Also used : StringTokenizer(java.util.StringTokenizer) InputStreamReader(java.io.InputStreamReader) HashMap(net.drewke.tdme.utils.HashMap) BufferedReader(java.io.BufferedReader) Material(net.drewke.tdme.engine.model.Material) DataInputStream(java.io.DataInputStream)

Example 3 with HashMap

use of net.drewke.tdme.utils.HashMap in project tdme by andreasdr.

the class ModelUtilitiesInternal method computeModelStatistics.

/**
	 * Compute model statistics
	 * @param object 3d model internal
	 * @return model statistics
	 */
public static ModelStatistics computeModelStatistics(Object3DModelInternal object3DModelInternal) {
    HashMap<String, Integer> materialCountById = new HashMap<String, Integer>();
    int opaqueFaceCount = 0;
    int transparentFaceCount = 0;
    for (Object3DGroup object3DGroup : object3DModelInternal.object3dGroups) {
        // check each faces entity
        FacesEntity[] facesEntities = object3DGroup.group.getFacesEntities();
        int facesEntityIdxCount = facesEntities.length;
        for (int faceEntityIdx = 0; faceEntityIdx < facesEntityIdxCount; faceEntityIdx++) {
            FacesEntity facesEntity = facesEntities[faceEntityIdx];
            int faces = facesEntity.getFaces().length;
            // material
            Material material = facesEntity.getMaterial();
            // determine if transparent
            boolean transparentFacesEntity = false;
            //	via material
            if (material != null) {
                if (material.hasTransparency() == true)
                    transparentFacesEntity = true;
            }
            // setup material usage
            String materialId = material == null ? "tdme.material.none" : material.getId();
            Integer materialCount = materialCountById.get(materialId);
            if (materialCount == null) {
                materialCountById.put(materialId, 1);
            } else {
                materialCount++;
            }
            // skip, if requested
            if (transparentFacesEntity == true) {
                // keep track of rendered faces
                transparentFaceCount += faces;
                // skip to next entity
                continue;
            }
            opaqueFaceCount += faces;
        }
    }
    // determine final material count
    int materialCount = 0;
    for (Integer material : materialCountById.getValuesIterator()) {
        materialCount++;
    }
    //
    return new ModelStatistics(opaqueFaceCount, transparentFaceCount, materialCount);
}
Also used : FacesEntity(net.drewke.tdme.engine.model.FacesEntity) HashMap(net.drewke.tdme.utils.HashMap) Material(net.drewke.tdme.engine.model.Material)

Example 4 with HashMap

use of net.drewke.tdme.utils.HashMap in project tdme by andreasdr.

the class GUITest method init.

/*
	 * (non-Javadoc)
	 * @see com.jogamp.opengl.GLEventListener#init(com.jogamp.opengl.GLAutoDrawable)
	 */
public void init(GLAutoDrawable drawable) {
    // init engine
    engine.init(drawable);
    // register gui to mouse, keyboard events
    glWindow.addMouseListener(engine.getGUI());
    glWindow.addKeyListener(engine.getGUI());
    //
    try {
        engine.getGUI().addScreen("test", GUIParser.parse("resources/tests/gui", "test.xml"));
        engine.getGUI().getScreen("test").setScreenSize(640, 480);
        engine.getGUI().getScreen("test").addActionListener(new GUIActionListener() {

            public void onActionPerformed(GUIActionListener.Type type, GUIElementNode node) {
                // check if button 1 is pressed
                if (type == Type.PERFORMED && node.getName().equals("button")) {
                    // action performed
                    System.out.println(node.getId() + ".actionPerformed()");
                    // test get values
                    HashMap<String, MutableString> values = new HashMap<String, MutableString>();
                    node.getScreenNode().getValues(values);
                    System.out.println(values);
                    // test set values
                    values.clear();
                    values.put("select", new MutableString("8"));
                    values.put("input", new MutableString("Enter some more text here!"));
                    values.put("checkbox1", new MutableString("1"));
                    values.put("checkbox2", new MutableString("1"));
                    values.put("checkbox3", new MutableString("1"));
                    values.put("dropdown", new MutableString("11"));
                    values.put("radio", new MutableString("3"));
                    values.put("selectmultiple", new MutableString("|1|2|3|15|16|17|"));
                    node.getScreenNode().setValues(values);
                    // test GUI tab controller select tab method
                    ((GUITabController) node.getScreenNode().getNodeById("tab1").getController()).selectTab();
                } else // check if button 2 is pressed
                if (type == Type.PERFORMED && node.getName().equals("button2")) {
                    try {
                        {
                            GUIParentNode parentNode = (GUIParentNode) (node.getScreenNode().getNodeById("sadd_inner"));
                            parentNode.replaceSubNodes("<dropdown-option text=\"Option 1\" value=\"1\" />" + "<dropdown-option text=\"Option 2\" value=\"2\" />" + "<dropdown-option text=\"Option 3\" value=\"3\" />" + "<dropdown-option text=\"Option 4\" value=\"4\" />" + "<dropdown-option text=\"Option 5\" value=\"5\" />" + "<dropdown-option text=\"Option 6\" value=\"6\" />" + "<dropdown-option text=\"Option 7\" value=\"7\" />" + "<dropdown-option text=\"Option 8\" value=\"8\" selected=\"true\" />" + "<dropdown-option text=\"Option 9\" value=\"9\" />" + "<dropdown-option text=\"Option 10\" value=\"10\" />", true);
                        }
                        {
                            //
                            GUIParentNode parentNode = (GUIParentNode) (node.getScreenNode().getNodeById("sasb_inner"));
                            parentNode.replaceSubNodes("<selectbox-option text=\"Option 1\" value=\"1\" />" + "<selectbox-option text=\"Option 2\" value=\"2\" />" + "<selectbox-option text=\"Option 3\" value=\"3\" />" + "<selectbox-option text=\"Option 4\" value=\"4\" selected=\"true\" />" + "<selectbox-option text=\"Option 5\" value=\"5\" />" + "<selectbox-option text=\"Option 6\" value=\"6\" />" + "<selectbox-option text=\"Option 7\" value=\"7\" />" + "<selectbox-option text=\"Option 8\" value=\"8\" />" + "<selectbox-option text=\"Option 9\" value=\"9\" />" + "<selectbox-option text=\"Option 10\" value=\"10\" />", true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // test GUI tab controller select tab method
                    ((GUITabController) node.getScreenNode().getNodeById("tab2").getController()).selectTab();
                }
            }
        });
        engine.getGUI().getScreen("test").addChangeListener(new GUIChangeListener() {

            public void onValueChanged(GUIElementNode node) {
                System.out.println(node.getName() + ":onValueChanged: " + node.getController().getValue());
            }
        });
        // layout
        engine.getGUI().getScreen("test").layout();
        // add fade in effect
        GUIColorEffect effectFadeIn = new GUIColorEffect();
        effectFadeIn.getColorMulStart().set(0f, 0f, 0f, 1f);
        effectFadeIn.getColorMulEnd().set(1f, 1f, 1f, 1f);
        effectFadeIn.setTimeTotal(1f);
        effectFadeIn.start();
        engine.getGUI().getScreen("test").addEffect("fadein", effectFadeIn);
        // add scroll in effect
        GUIPositionEffect effectScrollIn = new GUIPositionEffect();
        effectScrollIn.setPositionXStart(-800f);
        effectScrollIn.setPositionXEnd(0f);
        effectScrollIn.setTimeTotal(1f);
        effectScrollIn.start();
        engine.getGUI().getScreen("test").addEffect("scrollin", effectScrollIn);
        // add to render queue
        engine.getGUI().addRenderScreen("test");
    } catch (Exception exception) {
        exception.printStackTrace();
    }
}
Also used : GUITabController(net.drewke.tdme.gui.elements.GUITabController) GUIParentNode(net.drewke.tdme.gui.nodes.GUIParentNode) HashMap(net.drewke.tdme.utils.HashMap) GUIChangeListener(net.drewke.tdme.gui.events.GUIChangeListener) MutableString(net.drewke.tdme.utils.MutableString) GUIColorEffect(net.drewke.tdme.gui.effects.GUIColorEffect) MutableString(net.drewke.tdme.utils.MutableString) GUIElementNode(net.drewke.tdme.gui.nodes.GUIElementNode) GUIActionListener(net.drewke.tdme.gui.events.GUIActionListener) GUIPositionEffect(net.drewke.tdme.gui.effects.GUIPositionEffect)

Example 5 with HashMap

use of net.drewke.tdme.utils.HashMap in project tdme by andreasdr.

the class DAEReader method readMaterial.

/**
	 * Reads a material
	 * @param authoring tool
	 * @param path name
	 * @param model
	 * @param xml root
	 * @param xml node id
	 * @return material
	 * @throws Exception
	 */
public static Material readMaterial(AuthoringTool authoringTool, String pathName, Model model, Element xmlRoot, String xmlNodeId) throws Exception {
    // determine effect id
    String xmlEffectId = null;
    Element xmlLibraryMaterials = getChildrenByTagName(xmlRoot, "library_materials").get(0);
    for (Element xmlMaterial : getChildrenByTagName(xmlLibraryMaterials, "material")) {
        if (xmlMaterial.getAttribute("id").equals(xmlNodeId)) {
            Element xmlInstanceEffect = getChildrenByTagName(xmlMaterial, "instance_effect").get(0);
            xmlEffectId = xmlInstanceEffect.getAttribute("url").substring(1);
        }
    }
    if (xmlEffectId == null) {
        System.out.println("Could not determine effect id for '" + xmlNodeId + "'");
        return null;
    }
    // parse effect
    Material material = new Material(xmlNodeId);
    String xmlDiffuseTextureId = null;
    String xmlSpecularTextureId = null;
    String xmlBumpTextureId = null;
    Element xmlLibraryEffects = getChildrenByTagName(xmlRoot, "library_effects").get(0);
    for (Element xmlEffect : getChildrenByTagName(xmlLibraryEffects, "effect")) {
        if (xmlEffect.getAttribute("id").equals(xmlEffectId)) {
            // diffuse texture
            Element xmlProfile = getChildrenByTagName(xmlEffect, "profile_COMMON").get(0);
            HashMap<String, String> samplerSurfaceMapping = new HashMap<String, String>();
            HashMap<String, String> surfaceImageMapping = new HashMap<String, String>();
            for (Element xmlNewParam : getChildrenByTagName(xmlProfile, "newparam")) {
                String xmlNewParamSID = xmlNewParam.getAttribute("sid");
                for (Element xmlSurface : getChildrenByTagName(xmlNewParam, "surface")) for (Element xmlSurfaceInitFrom : getChildrenByTagName(xmlSurface, "init_from")) {
                    surfaceImageMapping.put(xmlNewParamSID, xmlSurfaceInitFrom.getTextContent());
                }
                for (Element xmlSampler2D : getChildrenByTagName(xmlNewParam, "sampler2D")) for (Element xmlSampler2DSource : getChildrenByTagName(xmlSampler2D, "source")) {
                    samplerSurfaceMapping.put(xmlNewParamSID, xmlSampler2DSource.getTextContent());
                }
            }
            // 
            for (Element xmlTechnique : getChildrenByTagName(xmlProfile, "technique")) {
                NodeList xmlTechniqueNodes = xmlTechnique.getChildNodes();
                for (int i = 0; i < xmlTechniqueNodes.getLength(); i++) {
                    Node xmlTechniqueNode = xmlTechniqueNodes.item(i);
                    // skip if not an element
                    if (xmlTechniqueNode.getNodeType() != Node.ELEMENT_NODE)
                        continue;
                    // diffuse
                    for (Element xmlDiffuse : getChildrenByTagName((Element) xmlTechniqueNode, "diffuse")) {
                        // texture
                        for (Element xmlTexture : getChildrenByTagName(xmlDiffuse, "texture")) {
                            xmlDiffuseTextureId = xmlTexture.getAttribute("texture");
                            String sample2Surface = samplerSurfaceMapping.get(xmlDiffuseTextureId);
                            String surface2Image = null;
                            if (sample2Surface != null)
                                surface2Image = surfaceImageMapping.get(sample2Surface);
                            if (surface2Image != null)
                                xmlDiffuseTextureId = surface2Image;
                        }
                        // color
                        for (Element xmlColor : getChildrenByTagName(xmlDiffuse, "color")) {
                            StringTokenizer t = new StringTokenizer(xmlColor.getTextContent(), " ");
                            material.getDiffuseColor().set(Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()));
                        }
                    }
                    // ambient
                    for (Element xmlAmbient : getChildrenByTagName((Element) xmlTechniqueNode, "ambient")) {
                        // color
                        for (Element xmlColor : getChildrenByTagName(xmlAmbient, "color")) {
                            StringTokenizer t = new StringTokenizer(xmlColor.getTextContent(), " ");
                            material.getAmbientColor().set(Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()));
                        }
                    }
                    // emission
                    for (Element xmlEmission : getChildrenByTagName((Element) xmlTechniqueNode, "emission")) {
                        // color
                        for (Element xmlColor : getChildrenByTagName(xmlEmission, "color")) {
                            StringTokenizer t = new StringTokenizer(xmlColor.getTextContent(), " ");
                            material.getEmissionColor().set(Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()));
                        }
                    }
                    // specular
                    boolean hasSpecularMap = false;
                    boolean hasSpecularColor = false;
                    for (Element xmlSpecular : getChildrenByTagName((Element) xmlTechniqueNode, "specular")) {
                        // texture
                        for (Element xmlTexture : getChildrenByTagName(xmlSpecular, "texture")) {
                            xmlSpecularTextureId = xmlTexture.getAttribute("texture");
                            String sample2Surface = samplerSurfaceMapping.get(xmlSpecularTextureId);
                            String surface2Image = null;
                            if (sample2Surface != null)
                                surface2Image = surfaceImageMapping.get(sample2Surface);
                            if (surface2Image != null)
                                xmlSpecularTextureId = surface2Image;
                            hasSpecularMap = true;
                        }
                        // color
                        for (Element xmlColor : getChildrenByTagName(xmlSpecular, "color")) {
                            StringTokenizer t = new StringTokenizer(xmlColor.getTextContent(), " ");
                            material.getSpecularColor().set(Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()), Float.parseFloat(t.nextToken()));
                            hasSpecularColor = true;
                        }
                    }
                    // set up specular color if not yet done but spec maps is available
                    if (hasSpecularMap == true && hasSpecularColor == false) {
                        material.getSpecularColor().set(1f, 1f, 1f, 1f);
                    }
                    // shininess
                    for (Element xmlShininess : getChildrenByTagName((Element) xmlTechniqueNode, "shininess")) {
                        // color
                        for (Element xmlFloat : getChildrenByTagName(xmlShininess, "float")) {
                            material.setShininess(Float.parseFloat(xmlFloat.getTextContent()));
                        }
                    }
                }
                // bump / normal map
                for (Element xmlBumpExtra : getChildrenByTagName(xmlTechnique, "extra")) for (Element xmlBumpTechnique : getChildrenByTagName(xmlBumpExtra, "technique")) for (Element xmlBumpTechniqueBump : getChildrenByTagName(xmlBumpTechnique, "bump")) for (Element xmlBumpTexture : getChildrenByTagName(xmlBumpTechniqueBump, "texture")) {
                    xmlBumpTextureId = xmlBumpTexture.getAttribute("texture");
                    String sample2Surface = samplerSurfaceMapping.get(xmlBumpTextureId);
                    String surface2Image = null;
                    if (sample2Surface != null)
                        surface2Image = surfaceImageMapping.get(sample2Surface);
                    if (surface2Image != null)
                        xmlBumpTextureId = surface2Image;
                }
            }
        }
    }
    // diffuse texture
    String xmlDiffuseTextureFilename = null;
    if (xmlDiffuseTextureId != null) {
        xmlDiffuseTextureFilename = getTextureFileNameById(xmlRoot, xmlDiffuseTextureId);
        // do we have a file name
        if (xmlDiffuseTextureFilename != null) {
            xmlDiffuseTextureFilename = makeFileNameRelative(xmlDiffuseTextureFilename);
            // add texture
            material.setDiffuseTexture(pathName, xmlDiffuseTextureFilename);
        }
    }
    // specular texture
    String xmlSpecularTextureFilename = null;
    if (xmlSpecularTextureId != null) {
        xmlSpecularTextureFilename = getTextureFileNameById(xmlRoot, xmlSpecularTextureId);
        // do we have a file name
        if (xmlSpecularTextureFilename != null) {
            xmlSpecularTextureFilename = makeFileNameRelative(xmlSpecularTextureFilename);
            // add texture
            material.setSpecularTexture(pathName, xmlSpecularTextureFilename);
        }
    }
    // normal map
    String xmlBumpTextureFilename = null;
    if (xmlBumpTextureId != null) {
        xmlBumpTextureFilename = getTextureFileNameById(xmlRoot, xmlBumpTextureId);
        // do we have a file name
        if (xmlBumpTextureFilename != null) {
            xmlBumpTextureFilename = makeFileNameRelative(xmlBumpTextureFilename);
            // add texture
            material.setNormalTexture(pathName, xmlBumpTextureFilename);
        }
    }
    // determine displacement map file name 
    String xmlDisplacementFilename = null;
    //  by diffuse file name
    if (xmlDiffuseTextureFilename != null) {
        xmlDisplacementFilename = determineDisplacementFilename(pathName, "diffuse", xmlDiffuseTextureFilename);
    }
    // 	by normal file name
    if (xmlDisplacementFilename == null && xmlBumpTextureFilename != null) {
        xmlDisplacementFilename = determineDisplacementFilename(pathName, "normal", xmlBumpTextureFilename);
    }
    // add texture
    if (xmlDisplacementFilename != null) {
        material.setDisplacementTexture(pathName, xmlDisplacementFilename);
    }
    // adjust ambient light with blender
    if (authoringTool == AuthoringTool.BLENDER && material.getAmbientColor().equals(BLENDER_AMBIENT_NONE)) {
        material.getAmbientColor().set(material.getDiffuseColor().getRed() * BLENDER_AMBIENT_FROM_DIFFUSE_SCALE, material.getDiffuseColor().getGreen() * BLENDER_AMBIENT_FROM_DIFFUSE_SCALE, material.getDiffuseColor().getBlue() * BLENDER_AMBIENT_FROM_DIFFUSE_SCALE, 1.0f);
        material.getDiffuseColor().set(material.getDiffuseColor().getRed() * BLENDER_DIFFUSE_SCALE, material.getDiffuseColor().getGreen() * BLENDER_DIFFUSE_SCALE, material.getDiffuseColor().getBlue() * BLENDER_DIFFUSE_SCALE, material.getDiffuseColor().getAlpha());
    }
    // add material to library
    model.getMaterials().put(material.getId(), material);
    //
    return material;
}
Also used : StringTokenizer(java.util.StringTokenizer) HashMap(net.drewke.tdme.utils.HashMap) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Material(net.drewke.tdme.engine.model.Material) Joint(net.drewke.tdme.engine.model.Joint)

Aggregations

HashMap (net.drewke.tdme.utils.HashMap)6 StringTokenizer (java.util.StringTokenizer)4 Joint (net.drewke.tdme.engine.model.Joint)3 Material (net.drewke.tdme.engine.model.Material)3 Element (org.w3c.dom.Element)3 Group (net.drewke.tdme.engine.model.Group)2 Matrix4x4 (net.drewke.tdme.math.Matrix4x4)2 BufferedReader (java.io.BufferedReader)1 DataInputStream (java.io.DataInputStream)1 InputStreamReader (java.io.InputStreamReader)1 ArrayList (java.util.ArrayList)1 Animation (net.drewke.tdme.engine.model.Animation)1 FacesEntity (net.drewke.tdme.engine.model.FacesEntity)1 JointWeight (net.drewke.tdme.engine.model.JointWeight)1 Skinning (net.drewke.tdme.engine.model.Skinning)1 GUIColorEffect (net.drewke.tdme.gui.effects.GUIColorEffect)1 GUIPositionEffect (net.drewke.tdme.gui.effects.GUIPositionEffect)1 GUITabController (net.drewke.tdme.gui.elements.GUITabController)1 GUIActionListener (net.drewke.tdme.gui.events.GUIActionListener)1 GUIChangeListener (net.drewke.tdme.gui.events.GUIChangeListener)1