Skip to content

The basic functions

William CLOT edited this page Sep 4, 2018 · 5 revisions

Now that we know the how the bones work we can dive into the basic function of the app. The main function that does all the magic here is placeMesh():

function placeMesh(
  meshName,
  bodyPartClass,
  MeshType,
  parentAttachment,
  childAttachment,
  rotation,
  firstLoad,
  highLight, 
  bones,
  poseData
) {
  // bodyPartClass : {arm, head, hand, torso, leg, foot}
  // MeshType : {ArmR, ArmL, Head, HandR, HandL, LegR, LegL, FootR, FootL, Torso}
  loader.load(
    "models/" + bodyPartClass + "/" + meshName + ".glb",
    gltf => {
      var root = gltf.scene.children[0];
      root.traverse( function(child){
        if (child instanceof THREE.Mesh){
          child.castShadow = true;
          child.material.color = {r:0.5,g:0.5,b:0.5};
        }
      })

      group.add(root);

      scene.updateMatrixWorld(true);

      loadedMeshes[MeshType].name = meshName;
      loadedMeshes[MeshType].rotation = rotation;

      if (MeshType === 'Head' && firstLoad){
        changeColor("Head", color)
      }

      if (highLight) {
        changeColor(MeshType, color);
      }

      // Putting the new mesh in the pose configuration if any pose as been selected
      if(poseData){
        root.traverse(function(child){
          if (child instanceof THREE.Bone){
            if (poseData[child.name]){
              window.changeRotation(child.name, poseData[child.name].x, "x")
              window.changeRotation(child.name, poseData[child.name].y, "y")
              window.changeRotation(child.name, poseData[child.name].z, "z")
            }
          }
        })
      }

      if(typeof parentAttachment !== "undefined" && typeof childAttachment !== "undefined"){
        let targetBone = scene.getObjectByName(parentAttachment);
        let object = scene.getObjectByName(childAttachment);
        clearPosition(object);
        rotateElement(object, true);
        rotateElement(object, false, rotation);
        targetBone.add(object);
      }

      //Going to look for all children of current mesh
      let children = childrenList[MeshType];
      if (children) {
        for (let i = 0; i < children.length; i++) {
          replaceMesh(children[i], firstLoad, bones, poseData);
        }
      }

      if (MeshType === "FootR"){
        if (scene.getObjectByName("FootL_Toes_L")){
          scene.updateMatrixWorld()
          placeStand()
        }
      }
      else if (MeshType === "FootL"){
        if (scene.getObjectByName("FootR_Toes_R")){
          scene.updateMatrixWorld()
          placeStand()
        }
      }
      window.partloaded = true;
    },
    null,
    function ( error ) {
      console.log(error);
    }
  );
}