From b85f36c1ef403329fcd22edcfa915a11d882f8a5 Mon Sep 17 00:00:00 2001 From: raveenajain Date: Mon, 13 May 2019 17:25:12 -0700 Subject: [PATCH 01/31] fixes avatar collision, shape info and model bounding --- libraries/fbx/src/GLTFSerializer.cpp | 70 ++++++++++++++++------------ 1 file changed, 40 insertions(+), 30 deletions(-) diff --git a/libraries/fbx/src/GLTFSerializer.cpp b/libraries/fbx/src/GLTFSerializer.cpp index 9952072668..bb8c2dd9c8 100755 --- a/libraries/fbx/src/GLTFSerializer.cpp +++ b/libraries/fbx/src/GLTFSerializer.cpp @@ -794,7 +794,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& parents[child] = nodecount; } sortedNodes.push_back(nodecount); - nodecount++; + ++nodecount; } @@ -810,7 +810,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& _file.nodes[nodecount].transforms.push_back(getModelTransform(parentNode)); parentIndex = parents[parentIndex]; } - nodecount++; + ++nodecount; } @@ -824,7 +824,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& int parentIndex = parents[currentNode]; if (parentIndex == -1 || hasBeenSorted[parentIndex]) { hasBeenSorted[currentNode] = true; - i++; + ++i; } else { int j = i + 1; // index of node to be sorted while (j < numNodes) { @@ -835,19 +835,19 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& hasBeenSorted[nextNode] = true; sortedNodes[i] = nextNode; sortedNodes[j] = currentNode; - i++; + ++i; currentNode = sortedNodes[i]; } - j++; + ++j; } } } - + // Build map from original to new indices QVector originalToNewNodeIndexMap; originalToNewNodeIndexMap.fill(-1, numNodes); - for (int i = 0; i < numNodes; i++) { + for (int i = 0; i < numNodes; ++i) { originalToNewNodeIndexMap[sortedNodes[i]] = i; } @@ -856,20 +856,26 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& HFMJoint joint; joint.distanceToParent = 0; hfmModel.jointIndices["x"] = numNodes; + QVector globalTransforms; + globalTransforms.resize(numNodes + 1); for (int nodeIndex : sortedNodes) { auto& node = _file.nodes[nodeIndex]; - joint.parentIndex = parents[nodeIndex]; - if (joint.parentIndex != -1) { - joint.parentIndex = originalToNewNodeIndexMap[joint.parentIndex]; - } joint.transform = node.transforms.first(); joint.translation = extractTranslation(joint.transform); joint.rotation = glmExtractRotation(joint.transform); glm::vec3 scale = extractScale(joint.transform); joint.postTransform = glm::scale(glm::mat4(), scale); + joint.parentIndex = parents[nodeIndex]; + globalTransforms[numNodes] = joint.transform * globalTransforms[numNodes]; // accumulate for all nodes + globalTransforms[nodeIndex] = joint.transform; + if (joint.parentIndex != -1) { + globalTransforms[nodeIndex] = globalTransforms[joint.parentIndex] * globalTransforms[nodeIndex]; + joint.parentIndex = originalToNewNodeIndexMap[joint.parentIndex]; + } + joint.name = node.name; joint.isSkeletonJoint = false; hfmModel.joints.push_back(joint); @@ -886,11 +892,11 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& std::vector> inverseBindValues; getSkinInverseBindMatrices(inverseBindValues); - for (int jointIndex = 0; jointIndex < numNodes; jointIndex++) { + for (int jointIndex = 0; jointIndex < numNodes; ++jointIndex) { int nodeIndex = sortedNodes[jointIndex]; auto joint = hfmModel.joints[jointIndex]; - for (int s = 0; s < _file.skins.size(); s++) { + for (int s = 0; s < _file.skins.size(); ++s) { const auto& skin = _file.skins[s]; int matrixIndex = skin.joints.indexOf(nodeIndex); joint.isSkeletonJoint = skin.joints.contains(nodeIndex); @@ -924,7 +930,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& materialIDs.push_back(mid); } - for (int i = 0; i < materialIDs.size(); i++) { + for (int i = 0; i < materialIDs.size(); ++i) { QString& matid = materialIDs[i]; hfmModel.materials[matid] = HFMMaterial(); HFMMaterial& hfmMaterial = hfmModel.materials[matid]; @@ -935,6 +941,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& // Build meshes nodecount = 0; + hfmModel.meshExtents.reset(); for (int nodeIndex : sortedNodes) { auto& node = _file.nodes[nodeIndex]; @@ -949,7 +956,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& cluster.inverseBindTransform = Transform(cluster.inverseBindMatrix); mesh.clusters.append(cluster); } else { // skinned model - for (int j = 0; j < numNodes; j++) { + for (int j = 0; j < numNodes; ++j) { HFMCluster cluster; cluster.jointIndex = j; cluster.inverseBindMatrix = jointInverseBindTransforms[j]; @@ -1106,7 +1113,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& qWarning(modelformat) << "There was a problem reading glTF JOINTS_0 data for model " << _url; continue; } - for (int n = 0; n < joints.size(); n++) { + for (int n = 0; n < joints.size(); ++n) { clusterJoints.push_back(joints[n]); } } else if (key == "WEIGHTS_0") { @@ -1121,7 +1128,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& qWarning(modelformat) << "There was a problem reading glTF WEIGHTS_0 data for model " << _url; continue; } - for (int n = 0; n < weights.size(); n++) { + for (int n = 0; n < weights.size(); ++n) { clusterWeights.push_back(weights[n]); } } @@ -1136,7 +1143,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& mesh.clusterIndices.fill(mesh.clusters.size() - 1, numClusterIndices); mesh.clusterWeights.fill(0, numClusterIndices); - for (int c = 0; c < clusterJoints.size(); c++) { + for (int c = 0; c < clusterJoints.size(); ++c) { mesh.clusterIndices[c] = originalToNewNodeIndexMap[_file.skins[node.skin].joints[clusterJoints[c]]]; } @@ -1166,7 +1173,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& // populate the texture coordinates if they don't exist if (mesh.texCoords.size() == 0 && !hfmModel.hasSkeletonJoints) { - for (int i = 0; i < part.triangleIndices.size(); i++) { mesh.texCoords.push_back(glm::vec2(0.0, 1.0)); } + for (int i = 0; i < part.triangleIndices.size(); ++i) { mesh.texCoords.push_back(glm::vec2(0.0, 1.0)); } } // Build morph targets (blend shapes) @@ -1177,7 +1184,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& hifi::VariantHash blendshapeMappings = mapping.value("bs").toHash(); QMultiHash blendshapeIndices; - for (int i = 0;; i++) { + for (int i = 0;; ++i) { hifi::ByteArray blendshapeName = FACESHIFT_BLENDSHAPES[i]; if (blendshapeName.isEmpty()) { break; @@ -1197,7 +1204,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& auto names = _file.meshes[node.mesh].extras.targetNames; QVector weights = _file.meshes[node.mesh].weights; - for (int weightedIndex = 0; weightedIndex < values.size(); weightedIndex++) { + for (int weightedIndex = 0; weightedIndex < values.size(); ++weightedIndex) { float weight = 0.1f; int indexFromMapping = weightedIndex; int targetIndex = weightedIndex; @@ -1238,29 +1245,32 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } else { blendshape.vertices[count] = blendshape.vertices[count] + vertices[i]; blendshape.normals[count] = blendshape.normals[count] + normals[i]; - count++; + ++count; } } } } - for (int clusterIndex = 0; clusterIndex < mesh.clusters.size() - 1; clusterIndex++) { + for (int clusterIndex = 0; clusterIndex < mesh.clusters.size() - 1; ++clusterIndex) { + auto joint = hfmModel.joints[clusterIndex]; ShapeVertices& points = hfmModel.shapeVertices.at(clusterIndex); + glm::mat4 modelTransform = glm::mat4(0.1f) * globalTransforms[numNodes] * joint.transform; for (glm::vec3 vertex : mesh.vertices) { - points.push_back(vertex); + glm::vec3 transformedVertex = glm::vec3(modelTransform * glm::vec4(vertex, 1.0f)); + points.push_back(transformedVertex); } } - mesh.meshExtents.reset(); foreach(const glm::vec3& vertex, mesh.vertices) { - mesh.meshExtents.addPoint(vertex); - hfmModel.meshExtents.addPoint(vertex); + glm::vec3 transformedVertex = glm::vec3(globalTransforms[nodeIndex] * glm::vec4(vertex, 1.0f)); + mesh.meshExtents.addPoint(transformedVertex); + hfmModel.meshExtents.addPoint(transformedVertex); } mesh.meshIndex = hfmModel.meshes.size(); } } - nodecount++; + ++nodecount; } return true; @@ -1511,8 +1521,8 @@ bool GLTFSerializer::readArray(const hifi::ByteArray& bin, int byteOffset, int c blobstream.unsetDevice(); return false; } - for (int i = 0; i < count; i++) { - for (int j = 0; j < bufferCount; j++) { + for (int i = 0; i < count; ++i) { + for (int j = 0; j < bufferCount; ++j) { if (!blobstream.atEnd()) { T value; blobstream >> value; From 9693f586a2154f5b69552a3de7ef0501ab832f67 Mon Sep 17 00:00:00 2001 From: raveenajain Date: Wed, 22 May 2019 14:24:09 -0700 Subject: [PATCH 02/31] bounding boxes, avatar walking, temp collision --- libraries/fbx/src/GLTFSerializer.cpp | 103 +++++++++++++++------------ 1 file changed, 58 insertions(+), 45 deletions(-) diff --git a/libraries/fbx/src/GLTFSerializer.cpp b/libraries/fbx/src/GLTFSerializer.cpp index d6fcfaba36..dc5f52f938 100755 --- a/libraries/fbx/src/GLTFSerializer.cpp +++ b/libraries/fbx/src/GLTFSerializer.cpp @@ -841,7 +841,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& parents[child] = nodecount; } sortedNodes.push_back(nodecount); - nodecount++; + ++nodecount; } @@ -857,7 +857,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& _file.nodes[nodecount].transforms.push_back(getModelTransform(parentNode)); parentIndex = parents[parentIndex]; } - nodecount++; + ++nodecount; } @@ -871,7 +871,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& int parentIndex = parents[currentNode]; if (parentIndex == -1 || hasBeenSorted[parentIndex]) { hasBeenSorted[currentNode] = true; - i++; + ++i; } else { int j = i + 1; // index of node to be sorted while (j < numNodes) { @@ -882,10 +882,10 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& hasBeenSorted[nextNode] = true; sortedNodes[i] = nextNode; sortedNodes[j] = currentNode; - i++; + ++i; currentNode = sortedNodes[i]; } - j++; + ++j; } } } @@ -894,7 +894,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& // Build map from original to new indices QVector originalToNewNodeIndexMap; originalToNewNodeIndexMap.fill(-1, numNodes); - for (int i = 0; i < numNodes; i++) { + for (int i = 0; i < numNodes; ++i) { originalToNewNodeIndexMap[sortedNodes[i]] = i; } @@ -903,6 +903,8 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& HFMJoint joint; joint.distanceToParent = 0; hfmModel.jointIndices["x"] = numNodes; + QVector globalTransforms; + globalTransforms.resize(numNodes); for (int nodeIndex : sortedNodes) { auto& node = _file.nodes[nodeIndex]; @@ -917,6 +919,13 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& glm::vec3 scale = extractScale(joint.transform); joint.postTransform = glm::scale(glm::mat4(), scale); + joint.parentIndex = parents[nodeIndex]; + globalTransforms[nodeIndex] = joint.transform; + if (joint.parentIndex != -1) { + globalTransforms[nodeIndex] = globalTransforms[joint.parentIndex] * globalTransforms[nodeIndex]; + joint.parentIndex = originalToNewNodeIndexMap[joint.parentIndex]; + } + joint.name = node.name; joint.isSkeletonJoint = false; hfmModel.joints.push_back(joint); @@ -926,18 +935,19 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& // Build skeleton std::vector jointInverseBindTransforms; + std::vector globalBindTransforms; jointInverseBindTransforms.resize(numNodes); + globalBindTransforms.resize(numNodes); hfmModel.hasSkeletonJoints = !_file.skins.isEmpty(); if (hfmModel.hasSkeletonJoints) { - hfmModel.hasSkeletonJoints = true; std::vector> inverseBindValues; getSkinInverseBindMatrices(inverseBindValues); - for (int jointIndex = 0; jointIndex < numNodes; jointIndex++) { + for (int jointIndex = 0; jointIndex < numNodes; ++jointIndex) { int nodeIndex = sortedNodes[jointIndex]; auto joint = hfmModel.joints[jointIndex]; - for (int s = 0; s < _file.skins.size(); s++) { + for (int s = 0; s < _file.skins.size(); ++s) { const auto& skin = _file.skins[s]; int matrixIndex = skin.joints.indexOf(nodeIndex); joint.isSkeletonJoint = skin.joints.contains(nodeIndex); @@ -954,6 +964,10 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } else { jointInverseBindTransforms[jointIndex] = glm::mat4(); } + globalBindTransforms[jointIndex] = jointInverseBindTransforms[jointIndex]; + if (joint.parentIndex != -1) { + globalBindTransforms[jointIndex] = globalBindTransforms[joint.parentIndex] * globalBindTransforms[jointIndex]; + } glm::vec3 bindTranslation = extractTranslation(hfmModel.offset * glm::inverse(jointInverseBindTransforms[jointIndex])); hfmModel.bindExtents.addPoint(bindTranslation); } @@ -962,13 +976,13 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } - //Build materials + // Build materials QVector materialIDs; QString unknown = "Default"; int ukcount = 0; foreach(auto material, _file.materials) { if (!material.defined["name"]) { - QString name = unknown + QString::number(ukcount++); + QString name = unknown + QString::number(++ukcount); material.name = name; material.defined.insert("name", true); } @@ -977,7 +991,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& materialIDs.push_back(mid); } - for (int i = 0; i < materialIDs.size(); i++) { + for (int i = 0; i < materialIDs.size(); ++i) { QString& matid = materialIDs[i]; hfmModel.materials[matid] = HFMMaterial(); HFMMaterial& hfmMaterial = hfmModel.materials[matid]; @@ -989,6 +1003,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& // Build meshes nodecount = 0; + hfmModel.meshExtents.reset(); for (int nodeIndex : sortedNodes) { auto& node = _file.nodes[nodeIndex]; @@ -1003,7 +1018,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& cluster.inverseBindTransform = Transform(cluster.inverseBindMatrix); mesh.clusters.append(cluster); } else { // skinned model - for (int j = 0; j < numNodes; j++) { + for (int j = 0; j < numNodes; ++j) { HFMCluster cluster; cluster.jointIndex = j; cluster.inverseBindMatrix = jointInverseBindTransforms[j]; @@ -1300,7 +1315,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } QVector validatedIndices; - for (int n = 0; n < indices.count(); n++) { + for (int n = 0; n < indices.count(); ++n) { if (indices[n] < partVerticesCount) { validatedIndices.push_back(indices[n] + prevMeshVerticesCount); } else { @@ -1332,7 +1347,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } } else { if (meshAttributes.contains("TANGENT")) { - for (int i = 0; i < partVerticesCount; i++) { + for (int i = 0; i < partVerticesCount; ++i) { mesh.tangents.push_back(glm::vec3(0.0f, 0.0f, 0.0f)); } } @@ -1344,7 +1359,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } } else { if (meshAttributes.contains("TEXCOORD_0")) { - for (int i = 0; i < partVerticesCount; i++) { + for (int i = 0; i < partVerticesCount; ++i) { mesh.texCoords.push_back(glm::vec2(0.0f, 0.0f)); } } @@ -1356,7 +1371,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } } else { if (meshAttributes.contains("TEXCOORD_1")) { - for (int i = 0; i < partVerticesCount; i++) { + for (int i = 0; i < partVerticesCount; ++i) { mesh.texCoords1.push_back(glm::vec2(0.0f, 0.0f)); } } @@ -1368,7 +1383,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } } else { if (meshAttributes.contains("COLOR_0")) { - for (int i = 0; i < partVerticesCount; i++) { + for (int i = 0; i < partVerticesCount; ++i) { mesh.colors.push_back(glm::vec3(1.0f, 1.0f, 1.0f)); } } @@ -1398,8 +1413,8 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } } else { if (meshAttributes.contains("JOINTS_0")) { - for (int i = 0; i < partVerticesCount; i++) { - for (int j = 0; j < 4; j++) { + for (int i = 0; i < partVerticesCount; ++i) { + for (int j = 0; j < 4; ++j) { clusterJoints.push_back(0); } } @@ -1430,9 +1445,9 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } } else { if (meshAttributes.contains("WEIGHTS_0")) { - for (int i = 0; i < partVerticesCount; i++) { + for (int i = 0; i < partVerticesCount; ++i) { clusterWeights.push_back(1.0f); - for (int j = 1; j < 4; j++) { + for (int j = 1; j < 4; ++j) { clusterWeights.push_back(0.0f); } } @@ -1448,12 +1463,12 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& int numVertices = mesh.vertices.size() - prevMeshVerticesCount; // Append new cluster indices and weights for this mesh part - for (int i = 0; i < numVertices * WEIGHTS_PER_VERTEX; i++) { + for (int i = 0; i < numVertices * WEIGHTS_PER_VERTEX; ++i) { mesh.clusterIndices.push_back(mesh.clusters.size() - 1); mesh.clusterWeights.push_back(0); } - for (int c = 0; c < clusterJoints.size(); c++) { + for (int c = 0; c < clusterJoints.size(); ++c) { mesh.clusterIndices[prevMeshClusterIndexCount + c] = originalToNewNodeIndexMap[_file.skins[node.skin].joints[clusterJoints[c]]]; } @@ -1484,7 +1499,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& // populate the texture coordinates if they don't exist if (mesh.texCoords.size() == 0 && !hfmModel.hasSkeletonJoints) { - for (int i = 0; i < part.triangleIndices.size(); i++) { mesh.texCoords.push_back(glm::vec2(0.0, 1.0)); } + for (int i = 0; i < part.triangleIndices.size(); ++i) { mesh.texCoords.push_back(glm::vec2(0.0, 1.0)); } } // Build morph targets (blend shapes) @@ -1495,7 +1510,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& hifi::VariantHash blendshapeMappings = mapping.value("bs").toHash(); QMultiHash blendshapeIndices; - for (int i = 0;; i++) { + for (int i = 0;; ++i) { hifi::ByteArray blendshapeName = FACESHIFT_BLENDSHAPES[i]; if (blendshapeName.isEmpty()) { break; @@ -1515,7 +1530,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& auto names = _file.meshes[node.mesh].extras.targetNames; QVector weights = _file.meshes[node.mesh].weights; - for (int weightedIndex = 0; weightedIndex < values.size(); weightedIndex++) { + for (int weightedIndex = 0; weightedIndex < values.size(); ++weightedIndex) { float weight = 0.1f; int indexFromMapping = weightedIndex; int targetIndex = weightedIndex; @@ -1556,34 +1571,32 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } else { blendshape.vertices[count] = blendshape.vertices[count] + vertices[i]; blendshape.normals[count] = blendshape.normals[count] + normals[i]; - count++; + ++count; } } } } - for (int clusterIndex = 0; clusterIndex < mesh.clusters.size() - 1; clusterIndex++) { + for (int clusterIndex = 0; clusterIndex < mesh.clusters.size() - 1; ++clusterIndex) { ShapeVertices& points = hfmModel.shapeVertices.at(clusterIndex); + // TODO: fix modelTransform value + const glm::mat4 modelTransform = glm::inverse(globalBindTransforms[originalToNewNodeIndexMap[nodeIndex]]) * + globalTransforms[originalToNewNodeIndexMap[clusterIndex]] * glm::mat4(0.1f); for (glm::vec3 vertex : mesh.vertices) { - points.push_back(vertex); + glm::vec3 transformedVertex = glm::vec3(modelTransform * glm::vec4(vertex, 1.0f)); + points.push_back(transformedVertex); } } - mesh.meshExtents.reset(); foreach(const glm::vec3& vertex, mesh.vertices) { - mesh.meshExtents.addPoint(vertex); - hfmModel.meshExtents.addPoint(vertex); + glm::vec3 transformedVertex = glm::vec3(globalTransforms[nodeIndex] * glm::vec4(vertex, 1.0f)); + mesh.meshExtents.addPoint(transformedVertex); + hfmModel.meshExtents.addPoint(transformedVertex); } mesh.meshIndex = hfmModel.meshes.size(); } - mesh.meshExtents.reset(); - foreach(const glm::vec3& vertex, mesh.vertices) { - mesh.meshExtents.addPoint(vertex); - hfmModel.meshExtents.addPoint(vertex); - } - // Add epsilon to mesh extents to compensate for planar meshes mesh.meshExtents.minimum -= glm::vec3(EPSILON, EPSILON, EPSILON); mesh.meshExtents.maximum += glm::vec3(EPSILON, EPSILON, EPSILON); @@ -1592,7 +1605,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& mesh.meshIndex = hfmModel.meshes.size(); } - nodecount++; + ++nodecount; } return true; @@ -1839,8 +1852,8 @@ bool GLTFSerializer::readArray(const hifi::ByteArray& bin, int byteOffset, int c blobstream.unsetDevice(); return false; } - for (int i = 0; i < count; i++) { - for (int j = 0; j < bufferCount; j++) { + for (int i = 0; i < count; ++i) { + for (int j = 0; j < bufferCount; ++j) { if (!blobstream.atEnd()) { T value; blobstream >> value; @@ -1893,7 +1906,7 @@ bool GLTFSerializer::addArrayFromAccessor(GLTFAccessor& accessor, QVector& ou success = addArrayOfType(buffer.blob, bufferview.byteOffset + accBoffset, accessor.count, outarray, accessor.type, accessor.componentType); } else { - for (int i = 0; i < accessor.count; i++) { + for (int i = 0; i < accessor.count; ++i) { T value; memset(&value, 0, sizeof(T)); // Make sure the dummy array is initalised to zero. outarray.push_back(value); @@ -1924,10 +1937,10 @@ bool GLTFSerializer::addArrayFromAccessor(GLTFAccessor& accessor, QVector& ou accessor.sparse.count, out_sparse_values_array, accessor.type, accessor.componentType); if (success) { - for (int i = 0; i < accessor.sparse.count; i++) { + for (int i = 0; i < accessor.sparse.count; ++i) { if ((i * 3) + 2 < out_sparse_values_array.size()) { if ((out_sparse_indices_array[i] * 3) + 2 < outarray.length()) { - for (int j = 0; j < 3; j++) { + for (int j = 0; j < 3; ++j) { outarray[(out_sparse_indices_array[i] * 3) + j] = out_sparse_values_array[(i * 3) + j]; } } else { From 3019a132406d1802173d41c066babe67b265ec05 Mon Sep 17 00:00:00 2001 From: raveenajain Date: Mon, 3 Jun 2019 11:35:23 -0700 Subject: [PATCH 03/31] stable point for collision capsules --- libraries/fbx/src/GLTFSerializer.cpp | 38 ++++++++++++++++++---------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/libraries/fbx/src/GLTFSerializer.cpp b/libraries/fbx/src/GLTFSerializer.cpp index dc5f52f938..dca9e9fefa 100755 --- a/libraries/fbx/src/GLTFSerializer.cpp +++ b/libraries/fbx/src/GLTFSerializer.cpp @@ -933,11 +933,20 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& hfmModel.shapeVertices.resize(hfmModel.joints.size()); + // get offset transform from mapping + float unitScaleFactor = 1.0f; + float offsetScale = mapping.value("scale", 1.0f).toFloat() * unitScaleFactor; + glm::quat offsetRotation = glm::quat(glm::radians(glm::vec3(mapping.value("rx").toFloat(), mapping.value("ry").toFloat(), mapping.value("rz").toFloat()))); + hfmModel.offset = glm::translate(glm::mat4(), glm::vec3(mapping.value("tx").toFloat(), mapping.value("ty").toFloat(), mapping.value("tz").toFloat())) * + glm::mat4_cast(offsetRotation) * glm::scale(glm::mat4(), glm::vec3(offsetScale, offsetScale, offsetScale)); + + // Build skeleton std::vector jointInverseBindTransforms; std::vector globalBindTransforms; jointInverseBindTransforms.resize(numNodes); globalBindTransforms.resize(numNodes); + hfmModel.hasSkeletonJoints = !_file.skins.isEmpty(); if (hfmModel.hasSkeletonJoints) { std::vector> inverseBindValues; @@ -1489,6 +1498,20 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } else { mesh.clusterWeights[prevMeshClusterWeightCount + j] = (uint16_t)((float)(UINT16_MAX) + ALMOST_HALF); } + for (int clusterIndex = 0; clusterIndex < mesh.clusters.size() - 1; ++clusterIndex) { + ShapeVertices& points = hfmModel.shapeVertices.at(clusterIndex); + glm::vec3 globalMeshScale = extractScale(globalTransforms[nodeIndex]); + const glm::mat4 meshToJoint = glm::scale(glm::mat4(), globalMeshScale) * jointInverseBindTransforms[clusterIndex]; + + const float EXPANSION_WEIGHT_THRESHOLD = 0.25f; + if (mesh.clusterWeights[j] >= EXPANSION_WEIGHT_THRESHOLD) { + // TODO: fix transformed vertices being pushed back + auto& vertex = mesh.vertices[i]; + const glm::mat4 vertexTransform = meshToJoint * (glm::translate(glm::mat4(), vertex)); + glm::vec3 transformedVertex = hfmModel.joints[clusterIndex].translation * (extractTranslation(vertexTransform)); + points.push_back(transformedVertex); + } + } } } @@ -1577,24 +1600,11 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } } - for (int clusterIndex = 0; clusterIndex < mesh.clusters.size() - 1; ++clusterIndex) { - ShapeVertices& points = hfmModel.shapeVertices.at(clusterIndex); - // TODO: fix modelTransform value - const glm::mat4 modelTransform = glm::inverse(globalBindTransforms[originalToNewNodeIndexMap[nodeIndex]]) * - globalTransforms[originalToNewNodeIndexMap[clusterIndex]] * glm::mat4(0.1f); - for (glm::vec3 vertex : mesh.vertices) { - glm::vec3 transformedVertex = glm::vec3(modelTransform * glm::vec4(vertex, 1.0f)); - points.push_back(transformedVertex); - } - } - foreach(const glm::vec3& vertex, mesh.vertices) { glm::vec3 transformedVertex = glm::vec3(globalTransforms[nodeIndex] * glm::vec4(vertex, 1.0f)); mesh.meshExtents.addPoint(transformedVertex); hfmModel.meshExtents.addPoint(transformedVertex); - } - - mesh.meshIndex = hfmModel.meshes.size(); + } } // Add epsilon to mesh extents to compensate for planar meshes From e572057d7cc6192049017a97294d03884fd13af4 Mon Sep 17 00:00:00 2001 From: luiscuenca Date: Thu, 6 Jun 2019 13:37:22 -0700 Subject: [PATCH 04/31] Password case insensitive and encoded. Proper uninstall --- launchers/win32/LauncherDlg.cpp | 137 ++++++++++++++++++---------- launchers/win32/LauncherDlg.h | 1 + launchers/win32/LauncherManager.cpp | 71 +++++++++++--- launchers/win32/LauncherManager.h | 4 + launchers/win32/LauncherUtils.cpp | 47 +++++++++- launchers/win32/LauncherUtils.h | 19 +++- 6 files changed, 219 insertions(+), 60 deletions(-) diff --git a/launchers/win32/LauncherDlg.cpp b/launchers/win32/LauncherDlg.cpp index 07fb57ddcd..7751c9cd6b 100644 --- a/launchers/win32/LauncherDlg.cpp +++ b/launchers/win32/LauncherDlg.cpp @@ -46,6 +46,10 @@ CLauncherDlg::CLauncherDlg(CWnd* pParent) EnableD2DSupport(); } +CLauncherDlg::~CLauncherDlg() { + theApp._manager.closeLog(); +} + void CLauncherDlg::DoDataExchange(CDataExchange* pDX) { DDX_Control(pDX, IDC_BUTTON_NEXT, m_btnNext); @@ -154,25 +158,50 @@ HCURSOR CLauncherDlg::OnQueryDragIcon() } void CLauncherDlg::startProcess() { - if (theApp._manager.needsUpdate()) { - setDrawDialog(DrawStep::DrawProcessUpdate); - } else { - setDrawDialog(DrawStep::DrawProcessSetup); - } - - CString installDir; - theApp._manager.getAndCreatePaths(LauncherManager::PathType::Interface_Directory, installDir); - CString interfaceExe = installDir += "\\interface.exe"; - if (!theApp._manager.isLoggedIn()) { - theApp._manager.downloadContent(); - } else { - theApp._manager.downloadApplication(); - } + if (theApp._manager.needsUpdate()) { + theApp._manager.addToLog(_T("Starting Process Update")); + setDrawDialog(DrawStep::DrawProcessUpdate); + } else { + theApp._manager.addToLog(_T("Starting Process Setup")); + setDrawDialog(DrawStep::DrawProcessSetup); + } + theApp._manager.addToLog(_T("Deleting directories before install")); + + CString installDir; + theApp._manager.getAndCreatePaths(LauncherManager::PathType::Interface_Directory, installDir); + CString downloadDir; + theApp._manager.getAndCreatePaths(LauncherManager::PathType::Download_Directory, downloadDir); + + LauncherUtils::deleteDirectoriesOnThread(installDir, downloadDir, [&](int error) { + LauncherUtils::DeleteDirError deleteError = (LauncherUtils::DeleteDirError)error; + if (error == LauncherUtils::DeleteDirError::NoErrorDeleting) { + theApp._manager.addToLog(_T("Install directory deleted.")); + theApp._manager.addToLog(_T("Downloads directory deleted.")); + // CString interfaceExe = installPath += "\\interface.exe"; + if (!theApp._manager.isLoggedIn()) { + theApp._manager.addToLog(_T("Downloading Content")); + theApp._manager.downloadContent(); + } else { + theApp._manager.addToLog(_T("Downloading App")); + theApp._manager.downloadApplication(); + } + } + if (error == LauncherUtils::DeleteDirError::ErrorDeletingPath1 || + error == LauncherUtils::DeleteDirError::ErrorDeletingPaths) { + theApp._manager.addToLog(_T("Error deleting install directory.")); + } + if (error == LauncherUtils::DeleteDirError::ErrorDeletingPath2 || + error == LauncherUtils::DeleteDirError::ErrorDeletingPaths) { + theApp._manager.addToLog(_T("Error deleting downloads directory.")); + } + }); } BOOL CLauncherDlg::getHQInfo(const CString& orgname) { CString hash; - LauncherUtils::hMac256(orgname, LAUNCHER_HMAC_SECRET, hash); + CString lowerOrgName = orgname; + lowerOrgName.MakeLower(); + LauncherUtils::hMac256(lowerOrgName, LAUNCHER_HMAC_SECRET, hash); return theApp._manager.readOrganizationJSON(hash) == LauncherUtils::ResponseError::NoError; } @@ -181,33 +210,44 @@ afx_msg void CLauncherDlg::OnTroubleClicked() { } afx_msg void CLauncherDlg::OnNextClicked() { - if (_drawStep != DrawStep::DrawChoose) { - CString token; - CString username, password, orgname; - m_orgname.GetWindowTextW(orgname); - m_username.GetWindowTextW(username); - m_password.GetWindowTextW(password); - LauncherUtils::ResponseError error; - if (orgname.GetLength() > 0 && username.GetLength() > 0 && password.GetLength() > 0) { - if (getHQInfo(orgname)) { - error = theApp._manager.getAccessTokenForCredentials(username, password); - if (error == LauncherUtils::ResponseError::NoError) { - setDrawDialog(DrawStep::DrawChoose); - } else if (error == LauncherUtils::ResponseError::BadCredentials) { - setDrawDialog(DrawStep::DrawLoginErrorCred); - } else { - MessageBox(L"Error Reading or retreaving response.", L"Network Error", MB_OK | MB_ICONERROR); - } - } else { - setDrawDialog(DrawStep::DrawLoginErrorOrg); - } - } - } else { - CString displayName; - m_username.GetWindowTextW(displayName); - theApp._manager.setDisplayName(displayName); - startProcess(); - } + if (_drawStep != DrawStep::DrawChoose) { + CString token; + CString username, password, orgname; + m_orgname.GetWindowTextW(orgname); + m_username.GetWindowTextW(username); + m_password.GetWindowTextW(password); + + username = LauncherUtils::urlEncodeString(username); + password = LauncherUtils::urlEncodeString(password); + LauncherUtils::ResponseError error; + if (orgname.GetLength() > 0 && username.GetLength() > 0 && password.GetLength() > 0) { + theApp._manager.addToLog(_T("Trying to get organization data")); + if (getHQInfo(orgname)) { + theApp._manager.addToLog(_T("Organization data received.")); + theApp._manager.addToLog(_T("Trying to log in with credentials")); + error = theApp._manager.getAccessTokenForCredentials(username, password); + if (error == LauncherUtils::ResponseError::NoError) { + theApp._manager.addToLog(_T("Logged in correctly.")); + setDrawDialog(DrawStep::DrawChoose); + } else if (error == LauncherUtils::ResponseError::BadCredentials) { + theApp._manager.addToLog(_T("Bad credentials. Try again")); + setDrawDialog(DrawStep::DrawLoginErrorCred); + } else { + theApp._manager.addToLog(_T("Error Reading or retreaving response.")); + MessageBox(L"Error Reading or retreaving response.", L"Network Error", MB_OK | MB_ICONERROR); + } + } else { + theApp._manager.addToLog(_T("Organization name does not exist.")); + setDrawDialog(DrawStep::DrawLoginErrorOrg); + } + } + } else { + CString displayName; + m_username.GetWindowTextW(displayName); + theApp._manager.setDisplayName(displayName); + theApp._manager.addToLog(_T("Setting display name: " + displayName)); + startProcess(); + } } void CLauncherDlg::drawBackground(CHwndRenderTarget* pRenderTarget) { @@ -534,11 +574,13 @@ void CLauncherDlg::OnTimer(UINT_PTR nIDEvent) { } if (_showSplash) { if (_splashStep == 0){ - if (theApp._manager.needsUninstall()) { - setDrawDialog(DrawStep::DrawProcessUninstall); - } else { - setDrawDialog(DrawStep::DrawLogo); - } + if (theApp._manager.needsUninstall()) { + theApp._manager.addToLog(_T("Waiting to unistall")); + setDrawDialog(DrawStep::DrawProcessUninstall); + } else { + theApp._manager.addToLog(_T("Start splash screen")); + setDrawDialog(DrawStep::DrawLogo); + } } else if (_splashStep > 100) { _showSplash = false; if (theApp._manager.shouldShutDown()) { @@ -551,6 +593,7 @@ void CLauncherDlg::OnTimer(UINT_PTR nIDEvent) { theApp._manager.uninstallApplication(); exit(0); } else { + theApp._manager.addToLog(_T("Starting login")); setDrawDialog(DrawStep::DrawLoginLogin); } } diff --git a/launchers/win32/LauncherDlg.h b/launchers/win32/LauncherDlg.h index 55bc97f205..d743dd31d2 100644 --- a/launchers/win32/LauncherDlg.h +++ b/launchers/win32/LauncherDlg.h @@ -38,6 +38,7 @@ public: }; CLauncherDlg(CWnd* pParent = nullptr); + ~CLauncherDlg(); virtual BOOL PreTranslateMessage(MSG* pMsg); void setDrawDialog(DrawStep step, BOOL isUpdate = FALSE); diff --git a/launchers/win32/LauncherManager.cpp b/launchers/win32/LauncherManager.cpp index 94a659a4d7..3dc7ddedcc 100644 --- a/launchers/win32/LauncherManager.cpp +++ b/launchers/win32/LauncherManager.cpp @@ -9,6 +9,7 @@ // #include "stdafx.h" +#include #include #include "LauncherManager.h" @@ -24,19 +25,57 @@ LauncherManager::~LauncherManager() } void LauncherManager::init() { - getMostRecentBuild(_latestApplicationURL, _latestVersion); - CString currentVersion; - if (isApplicationInstalled(currentVersion, _domainURL, _contentURL, _loggedIn) && _loggedIn) { - if (_latestVersion.Compare(currentVersion) == 0) { - launchApplication(); - _shouldShutdown = TRUE; - } else { - _shouldUpdate = TRUE; - } - } + initLog(); + addToLog(_T("Getting most recent build")); + getMostRecentBuild(_latestApplicationURL, _latestVersion); + addToLog(_T("Latest version: ") + _latestVersion); + CString currentVersion; + if (isApplicationInstalled(currentVersion, _domainURL, _contentURL, _loggedIn) && _loggedIn) { + addToLog(_T("Installed version: ") + currentVersion); + if (_latestVersion.Compare(currentVersion) == 0) { + addToLog(_T("Already running most recent build. Launching interface.exe")); + launchApplication(); + _shouldShutdown = TRUE; + } else { + addToLog(_T("New build found. Updating")); + _shouldUpdate = TRUE; + } + } +} + +BOOL LauncherManager::initLog() { + CString logPath; + auto result = getAndCreatePaths(PathType::Launcher_Directory, logPath); + if (result) { + logPath += _T("log.txt"); + return result = _logFile.Open(logPath, CFile::modeCreate | CFile::modeReadWrite); + } + return FALSE; +} + +BOOL LauncherManager::addToLog(const CString& line) { + if (_logFile.m_hFile != CStdioFile::hFileNull) { + char buff[100]; + time_t now = time(0); + tm ltm; + localtime_s(<m, &now); + + strftime(buff, 100, "%Y-%m-%d %H:%M:%S", <m); + CString timeStr = CString(buff); + _logFile.WriteString(timeStr + _T(" ") + line + _T("\n")); + return TRUE; + } + return FALSE; +} + +void LauncherManager::closeLog() { + if (_logFile.m_hFile != CStdioFile::hFileNull) { + _logFile.Close(); + } } BOOL LauncherManager::installLauncher() { + addToLog(_T("Installing Launcher.")); CString appPath; BOOL result = getAndCreatePaths(PathType::Running_Path, appPath); if (!result) { @@ -60,6 +99,7 @@ BOOL LauncherManager::installLauncher() { CopyFile(appPath, instalationPath, FALSE); } } else if (_shouldUninstall) { + addToLog(_T("Launching uninstall mode.")); CString tempPath; if (getAndCreatePaths(PathType::Temp_Directory, tempPath)) { tempPath += _T("\\HQ_uninstaller_tmp.exe"); @@ -73,6 +113,7 @@ BOOL LauncherManager::installLauncher() { BOOL LauncherManager::createShortcuts() { CString desktopLnkPath; + addToLog(_T("Creating shortcuts.")); getAndCreatePaths(PathType::Desktop_Directory, desktopLnkPath); desktopLnkPath += _T("\\HQ Launcher.lnk"); CString installDir; @@ -100,6 +141,7 @@ BOOL LauncherManager::createShortcuts() { BOOL LauncherManager::deleteShortcuts() { CString desktopLnkPath; + addToLog(_T("Deleting shortcuts.")); getAndCreatePaths(PathType::Desktop_Directory, desktopLnkPath); desktopLnkPath += _T("\\HQ Launcher.lnk"); BOOL success = LauncherUtils::deleteFileOrDirectory(desktopLnkPath); @@ -353,13 +395,17 @@ BOOL LauncherManager::uninstallApplication() { void LauncherManager::onZipExtracted(ZipType type, int size) { if (type == ZipType::ZipContent) { + addToLog(_T("Downloading application.")); downloadApplication(); } else if (type == ZipType::ZipApplication) { createShortcuts(); CString versionPath; getAndCreatePaths(LauncherManager::PathType::Launcher_Directory, versionPath); - createConfigJSON(); + addToLog(_T("Creating config.json")); + createConfigJSON(); + addToLog(_T("Launching application.")); launchApplication(_tokensJSON); + addToLog(_T("Creating registry keys.")); createApplicationRegistryKeys(size); _shouldShutdown = TRUE; } @@ -377,8 +423,10 @@ BOOL LauncherManager::extractApplication() { void LauncherManager::onFileDownloaded(DownloadType type) { if (type == DownloadType::DownloadContent) { + addToLog(_T("Installing content.")); installContent(); } else if (type == DownloadType::DownloadApplication) { + addToLog(_T("Installing application.")); extractApplication(); } } @@ -412,6 +460,7 @@ BOOL LauncherManager::downloadFile(DownloadType type, const CString& url, CStrin } BOOL LauncherManager::downloadContent() { + addToLog(_T("Downloading content.")); CString contentURL = getContentURL(); return downloadFile(DownloadType::DownloadContent, contentURL, _contentZipPath); } diff --git a/launchers/win32/LauncherManager.h b/launchers/win32/LauncherManager.h index 3ad21694f6..4bc09b49ca 100644 --- a/launchers/win32/LauncherManager.h +++ b/launchers/win32/LauncherManager.h @@ -53,6 +53,9 @@ public: LauncherManager(); ~LauncherManager(); void init(); + BOOL initLog(); + BOOL addToLog(const CString& line); + void closeLog(); BOOL getAndCreatePaths(PathType type, CString& outPath); BOOL getInstalledVersion(const CString& path, CString& version); BOOL isApplicationInstalled(CString& version, CString& domain, @@ -105,5 +108,6 @@ private: BOOL _shouldUpdate{ FALSE }; BOOL _shouldUninstall{ FALSE }; BOOL _shouldShutdown{ FALSE }; + CStdioFile _logFile; }; diff --git a/launchers/win32/LauncherUtils.cpp b/launchers/win32/LauncherUtils.cpp index 8a75747e9b..8cf1d78ebf 100644 --- a/launchers/win32/LauncherUtils.cpp +++ b/launchers/win32/LauncherUtils.cpp @@ -17,6 +17,24 @@ #include "LauncherUtils.h" +CString LauncherUtils::urlEncodeString(const CString& url) { + std::map specialCharsMap = { { _T("$"), _T("%24") }, { _T(" "), _T("%20") }, { _T("#"), _T("%23") }, + { _T("@"), _T("%40") }, { _T("`"), _T("%60") }, { _T("&"), _T("%26") }, + { _T("/"), _T("%2F") }, { _T(":"), _T("%3A") }, { _T(";"), _T("%3B") }, + { _T("<"), _T("%3C") }, { _T(">"), _T("%3E") }, { _T("="), _T("%3D") }, + { _T("?"), _T("%3F") }, { _T("["), _T("%5B") }, { _T("\\"), _T("%5C") }, + { _T("]"), _T("%5D") }, { _T("^"), _T("%5E") }, { _T("{"), _T("%7B") }, + { _T("|"), _T("%7C") }, { _T("}"), _T("%7D") }, { _T("~"), _T("%7E") }, + { _T("“"), _T("%22") }, { _T("‘"), _T("%27") }, { _T("+"), _T("%2B") }, + { _T(","), _T("%2C") } }; + CString stringOut = url; + stringOut.Replace(_T("%"), _T("%25")); + for (auto& itr = specialCharsMap.begin(); itr != specialCharsMap.end(); itr++) { + stringOut.Replace(itr->first, itr->second); + } + return stringOut; +} + BOOL LauncherUtils::IsProcessRunning(const wchar_t *processName) { bool exists = false; PROCESSENTRY32 entry; @@ -374,6 +392,19 @@ DWORD WINAPI LauncherUtils::downloadThread(LPVOID lpParameter) return 0; } +DWORD WINAPI LauncherUtils::deleteDirectoriesThread(LPVOID lpParameter) { + DeleteThreadData& data = *((DeleteThreadData*)lpParameter); + DeleteDirError error = DeleteDirError::NoErrorDeleting; + if (!LauncherUtils::deleteFileOrDirectory(data._path1)) { + error = DeleteDirError::ErrorDeletingPath1; + } + if (!LauncherUtils::deleteFileOrDirectory(data._path2)) { + error = error == NoError ? DeleteDirError::ErrorDeletingPath2 : DeleteDirError::ErrorDeletingPaths; + } + data.callback(error); + return 0; +} + BOOL LauncherUtils::unzipFileOnThread(int type, const std::string& zipFile, const std::string& path, std::function callback) { DWORD myThreadID; UnzipThreadData* unzipThreadData = new UnzipThreadData(); @@ -402,4 +433,18 @@ BOOL LauncherUtils::downloadFileOnThread(int type, const CString& url, const CSt return TRUE; } return FALSE; -} \ No newline at end of file +} + +BOOL LauncherUtils::deleteDirectoriesOnThread(const CString& dir1, const CString& dir2, std::function callback) { + DWORD myThreadID; + DeleteThreadData* deleteThreadData = new DeleteThreadData(); + deleteThreadData->_path1 = dir1; + deleteThreadData->_path2 = dir2; + deleteThreadData->setCallback(callback); + HANDLE myHandle = CreateThread(0, 0, deleteDirectoriesThread, deleteThreadData, 0, &myThreadID); + if (myHandle) { + CloseHandle(myHandle); + return TRUE; + } + return FALSE; +} diff --git a/launchers/win32/LauncherUtils.h b/launchers/win32/LauncherUtils.h index 3e9f18d892..4add0fb931 100644 --- a/launchers/win32/LauncherUtils.h +++ b/launchers/win32/LauncherUtils.h @@ -30,6 +30,13 @@ public: NoError }; + enum DeleteDirError { + NoErrorDeleting = 0, + ErrorDeletingPath1, + ErrorDeletingPath2, + ErrorDeletingPaths + }; + struct DownloadThreadData { int _type; CString _url; @@ -52,6 +59,13 @@ public: } }; + struct DeleteThreadData { + CString _path1; + CString _path2; + std::function callback; + void setCallback(std::function fn) { callback = std::bind(fn, std::placeholders::_1); } + }; + static BOOL parseJSON(const CString& jsonTxt, Json::Value& jsonObject); static ResponseError makeHTTPCall(const CString& callerName, const CString& mainUrl, const CString& dirUrl, const CString& contentType, @@ -69,9 +83,12 @@ public: static BOOL deleteRegistryKey(const CString& registryPath); static BOOL unzipFileOnThread(int type, const std::string& zipFile, const std::string& path, std::function callback); static BOOL downloadFileOnThread(int type, const CString& url, const CString& file, std::function callback); + static BOOL deleteDirectoriesOnThread(const CString& dir1, const CString& dir2, std::function callback); + static CString urlEncodeString(const CString& url); -private: + private: // Threads static DWORD WINAPI unzipThread(LPVOID lpParameter); static DWORD WINAPI downloadThread(LPVOID lpParameter); + static DWORD WINAPI deleteDirectoriesThread(LPVOID lpParameter); }; \ No newline at end of file From 36e1366cc467133056f587a8b122e665999a9e83 Mon Sep 17 00:00:00 2001 From: Preston Bezos Date: Thu, 6 Jun 2019 14:19:37 -0700 Subject: [PATCH 05/31] added Notifies to various QProperties in order to remove warnings in interface logs --- interface/src/avatar/MyAvatar.cpp | 1 + interface/src/avatar/MyAvatar.h | 9 ++++++++- interface/src/scripting/AudioDevices.h | 2 +- libraries/shared/src/shared/Camera.h | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index ad39b6663a..f3172772ab 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -5014,6 +5014,7 @@ float MyAvatar::getAnalogSprintSpeed() const { void MyAvatar::setAnalogPlusWalkSpeed(float value) { _analogPlusWalkSpeed.set(value); + analogPlusWalkSpeedChanged(value); // Sprint speed for Analog Plus should be double walk speed. _analogPlusSprintSpeed.set(value * 2.0f); } diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index 9fb6c85a78..7736eba7ea 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -370,7 +370,7 @@ class MyAvatar : public Avatar { Q_PROPERTY(QUuid SELF_ID READ getSelfID CONSTANT) Q_PROPERTY(float walkSpeed READ getWalkSpeed WRITE setWalkSpeed); - Q_PROPERTY(float analogPlusWalkSpeed READ getAnalogPlusWalkSpeed WRITE setAnalogPlusWalkSpeed); + Q_PROPERTY(float analogPlusWalkSpeed READ getAnalogPlusWalkSpeed WRITE setAnalogPlusWalkSpeed NOTIFY analogPlusWalkSpeedChanged); Q_PROPERTY(float analogPlusSprintSpeed READ getAnalogPlusSprintSpeed WRITE setAnalogPlusSprintSpeed); Q_PROPERTY(float walkBackwardSpeed READ getWalkBackwardSpeed WRITE setWalkBackwardSpeed); Q_PROPERTY(float sprintSpeed READ getSprintSpeed WRITE setSprintSpeed); @@ -2161,6 +2161,13 @@ signals: */ void audioListenerModeChanged(); + /**jsdoc + * Notifies when the analogPlusWalkSpeed value changed. + * @function MyAvatar.analogPlusWalkSpeedChanged + * @returns {Signal} + */ + void analogPlusWalkSpeedChanged(float value); + /**jsdoc * @function MyAvatar.transformChanged * @returns {Signal} diff --git a/interface/src/scripting/AudioDevices.h b/interface/src/scripting/AudioDevices.h index 3d12f93113..2ea034d9fe 100644 --- a/interface/src/scripting/AudioDevices.h +++ b/interface/src/scripting/AudioDevices.h @@ -80,7 +80,7 @@ public: class AudioInputDeviceList : public AudioDeviceList { Q_OBJECT - Q_PROPERTY(bool peakValuesAvailable READ peakValuesAvailable) + Q_PROPERTY(bool peakValuesAvailable READ peakValuesAvailable CONSTANT) Q_PROPERTY(bool peakValuesEnabled READ peakValuesEnabled WRITE setPeakValuesEnabled NOTIFY peakValuesEnabledChanged) public: diff --git a/libraries/shared/src/shared/Camera.h b/libraries/shared/src/shared/Camera.h index f41183479c..0df83cfb9a 100644 --- a/libraries/shared/src/shared/Camera.h +++ b/libraries/shared/src/shared/Camera.h @@ -38,7 +38,7 @@ class Camera : public QObject { Q_PROPERTY(glm::vec3 position READ getPosition WRITE setPosition) Q_PROPERTY(glm::quat orientation READ getOrientation WRITE setOrientation) - Q_PROPERTY(QString mode READ getModeString WRITE setModeString) + Q_PROPERTY(QString mode READ getModeString WRITE setModeString NOTIFY modeUpdated) Q_PROPERTY(QVariantMap frustum READ getViewFrustum CONSTANT) public: From a7a765b025fe8b5bb9ad13a06deb345fd0b896c5 Mon Sep 17 00:00:00 2001 From: Preston Bezos Date: Thu, 6 Jun 2019 16:23:54 -0700 Subject: [PATCH 06/31] added a couple more notifies and fixed a couple of jsdocs --- interface/src/avatar/MyAvatar.cpp | 876 +++++++++++++++--------------- interface/src/avatar/MyAvatar.h | 33 +- 2 files changed, 452 insertions(+), 457 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index f3172772ab..4cf12dc2d3 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -71,9 +71,9 @@ using namespace std; const float DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES = 30.0f; const float YAW_SPEED_DEFAULT = 100.0f; // degrees/sec -const float PITCH_SPEED_DEFAULT = 75.0f; // degrees/sec +const float PITCH_SPEED_DEFAULT = 75.0f; // degrees/sec -const float MAX_BOOST_SPEED = 0.5f * DEFAULT_AVATAR_MAX_WALKING_SPEED; // action motor gets additive boost below this speed +const float MAX_BOOST_SPEED = 0.5f * DEFAULT_AVATAR_MAX_WALKING_SPEED; // action motor gets additive boost below this speed const float MIN_AVATAR_SPEED = 0.05f; float MIN_SCRIPTED_MOTOR_TIMESCALE = 0.005f; @@ -83,7 +83,8 @@ const int SCRIPTED_MOTOR_AVATAR_FRAME = 1; const int SCRIPTED_MOTOR_WORLD_FRAME = 2; const int SCRIPTED_MOTOR_SIMPLE_MODE = 0; const int SCRIPTED_MOTOR_DYNAMIC_MODE = 1; -const QString& DEFAULT_AVATAR_COLLISION_SOUND_URL = "https://hifi-public.s3.amazonaws.com/sounds/Collisions-otherorganic/Body_Hits_Impact.wav"; +const QString& DEFAULT_AVATAR_COLLISION_SOUND_URL = + "https://hifi-public.s3.amazonaws.com/sounds/Collisions-otherorganic/Body_Hits_Impact.wav"; const float MyAvatar::ZOOM_MIN = 0.5f; const float MyAvatar::ZOOM_MAX = 25.0f; @@ -92,7 +93,7 @@ const float MIN_SCALE_CHANGED_DELTA = 0.001f; const int MODE_READINGS_RING_BUFFER_SIZE = 500; const float CENTIMETERS_PER_METER = 100.0f; -const QString AVATAR_SETTINGS_GROUP_NAME { "Avatar" }; +const QString AVATAR_SETTINGS_GROUP_NAME{ "Avatar" }; static const QString USER_RECENTER_MODEL_FORCE_SIT = QStringLiteral("ForceSit"); static const QString USER_RECENTER_MODEL_FORCE_STAND = QStringLiteral("ForceStand"); @@ -113,50 +114,33 @@ MyAvatar::SitStandModelType stringToUserRecenterModel(const QString& str) { QString userRecenterModelToString(MyAvatar::SitStandModelType model) { switch (model) { - case MyAvatar::ForceSit: - return USER_RECENTER_MODEL_FORCE_SIT; - case MyAvatar::ForceStand: - return USER_RECENTER_MODEL_FORCE_STAND; - case MyAvatar::DisableHMDLean: - return USER_RECENTER_MODEL_DISABLE_HMD_LEAN; - case MyAvatar::Auto: - default: - return USER_RECENTER_MODEL_AUTO; + case MyAvatar::ForceSit: + return USER_RECENTER_MODEL_FORCE_SIT; + case MyAvatar::ForceStand: + return USER_RECENTER_MODEL_FORCE_STAND; + case MyAvatar::DisableHMDLean: + return USER_RECENTER_MODEL_DISABLE_HMD_LEAN; + case MyAvatar::Auto: + default: + return USER_RECENTER_MODEL_AUTO; } } MyAvatar::MyAvatar(QThread* thread) : - Avatar(thread), - _yawSpeed(YAW_SPEED_DEFAULT), - _pitchSpeed(PITCH_SPEED_DEFAULT), - _scriptedMotorTimescale(DEFAULT_SCRIPTED_MOTOR_TIMESCALE), - _scriptedMotorFrame(SCRIPTED_MOTOR_CAMERA_FRAME), - _scriptedMotorMode(SCRIPTED_MOTOR_SIMPLE_MODE), - _motionBehaviors(AVATAR_MOTION_DEFAULTS), - _characterController(std::shared_ptr(this)), - _eyeContactTarget(LEFT_EYE), - _realWorldFieldOfView("realWorldFieldOfView", - DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES), - _useAdvancedMovementControls("advancedMovementForHandControllersIsChecked", true), - _showPlayArea("showPlayArea", true), - _smoothOrientationTimer(std::numeric_limits::max()), - _smoothOrientationInitial(), - _smoothOrientationTarget(), - _hmdSensorMatrix(), - _hmdSensorOrientation(), - _hmdSensorPosition(), - _recentModeReadings(MODE_READINGS_RING_BUFFER_SIZE), - _bodySensorMatrix(), - _goToPending(false), - _goToSafe(true), - _goToFeetAjustment(false), - _goToPosition(), - _goToOrientation(), - _prevShouldDrawHead(true), - _audioListenerMode(FROM_HEAD), + Avatar(thread), _yawSpeed(YAW_SPEED_DEFAULT), _pitchSpeed(PITCH_SPEED_DEFAULT), + _scriptedMotorTimescale(DEFAULT_SCRIPTED_MOTOR_TIMESCALE), _scriptedMotorFrame(SCRIPTED_MOTOR_CAMERA_FRAME), + _scriptedMotorMode(SCRIPTED_MOTOR_SIMPLE_MODE), _motionBehaviors(AVATAR_MOTION_DEFAULTS), + _characterController(std::shared_ptr(this)), _eyeContactTarget(LEFT_EYE), + _realWorldFieldOfView("realWorldFieldOfView", DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES), + _useAdvancedMovementControls("advancedMovementForHandControllersIsChecked", true), _showPlayArea("showPlayArea", true), + _smoothOrientationTimer(std::numeric_limits::max()), _smoothOrientationInitial(), _smoothOrientationTarget(), + _hmdSensorMatrix(), _hmdSensorOrientation(), _hmdSensorPosition(), _recentModeReadings(MODE_READINGS_RING_BUFFER_SIZE), + _bodySensorMatrix(), _goToPending(false), _goToSafe(true), _goToFeetAjustment(false), _goToPosition(), _goToOrientation(), + _prevShouldDrawHead(true), _audioListenerMode(FROM_HEAD), _dominantHandSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "dominantHand", DOMINANT_RIGHT_HAND), _strafeEnabledSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "strafeEnabled", DEFAULT_STRAFE_ENABLED), - _hmdAvatarAlignmentTypeSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "hmdAvatarAlignmentType", DEFAULT_HMD_AVATAR_ALIGNMENT_TYPE), + _hmdAvatarAlignmentTypeSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "hmdAvatarAlignmentType", + DEFAULT_HMD_AVATAR_ALIGNMENT_TYPE), _headPitchSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "", 0.0f), _scaleSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "scale", _targetScale), _yawSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "yawSpeed", _yawSpeed), @@ -172,17 +156,19 @@ MyAvatar::MyAvatar(QThread* thread) : _userHeightSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userHeight", DEFAULT_AVATAR_HEIGHT), _flyingHMDSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "flyingHMD", _flyingPrefHMD), _movementReferenceSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "movementReference", _movementReference), - _avatarEntityCountSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" << "size", 0), + _avatarEntityCountSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" + << "size", + 0), _driveGear1Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear1", _driveGear1), _driveGear2Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear2", _driveGear2), _driveGear3Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear3", _driveGear3), _driveGear4Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear4", _driveGear4), _driveGear5Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear5", _driveGear5), _analogWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogWalkSpeed", _analogWalkSpeed.get()), - _analogPlusWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogPlusWalkSpeed", _analogPlusWalkSpeed.get()), + _analogPlusWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogPlusWalkSpeed", + _analogPlusWalkSpeed.get()), _controlSchemeIndexSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "controlSchemeIndex", _controlSchemeIndex), - _userRecenterModelSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userRecenterModel", USER_RECENTER_MODEL_AUTO) -{ + _userRecenterModelSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userRecenterModel", USER_RECENTER_MODEL_AUTO) { _clientTraitsHandler.reset(new ClientTraitsHandler(this)); // give the pointer to our head to inherited _headData variable from AvatarData @@ -203,7 +189,7 @@ MyAvatar::MyAvatar(QThread* thread) : qApp->loadAvatarScripts(hfmModel.scripts); _shouldLoadScripts = false; } - // Load and convert old attachments to avatar entities + // Load and convert old attachments to avatar entities if (_oldAttachmentData.size() > 0) { setAttachmentData(_oldAttachmentData); _oldAttachmentData.clear(); @@ -220,11 +206,11 @@ MyAvatar::MyAvatar(QThread* thread) : clearDriveKeys(); // Necessary to select the correct slot - using SlotType = void(MyAvatar::*)(const glm::vec3&, bool, const glm::quat&, bool); + using SlotType = void (MyAvatar::*)(const glm::vec3&, bool, const glm::quat&, bool); // connect to AddressManager signal for location jumps - connect(DependencyManager::get().data(), &AddressManager::locationChangeRequired, - this, static_cast(&MyAvatar::goToFeetLocation)); + connect(DependencyManager::get().data(), &AddressManager::locationChangeRequired, this, + static_cast(&MyAvatar::goToFeetLocation)); // handle scale constraints imposed on us by the domain-server auto& domainHandler = DependencyManager::get()->getDomainHandler(); @@ -287,7 +273,6 @@ MyAvatar::MyAvatar(QThread* thread) : if (recordingInterface->getPlayerUseSkeletonModel() && dummyAvatar.getSkeletonModelURL().isValid() && (dummyAvatar.getSkeletonModelURL() != getSkeletonModelURL())) { - setSkeletonModelURL(dummyAvatar.getSkeletonModelURL()); } @@ -383,7 +368,8 @@ void MyAvatar::enableHandTouchForID(const QUuid& entityID) { } void MyAvatar::registerMetaTypes(ScriptEnginePointer engine) { - QScriptValue value = engine->newQObject(this, QScriptEngine::QtOwnership, QScriptEngine::ExcludeDeleteLater | QScriptEngine::ExcludeChildObjects); + QScriptValue value = engine->newQObject(this, QScriptEngine::QtOwnership, + QScriptEngine::ExcludeDeleteLater | QScriptEngine::ExcludeChildObjects); engine->globalObject().setProperty("MyAvatar", value); QScriptValue driveKeys = engine->newObject(); @@ -446,7 +432,6 @@ void MyAvatar::resetSensorsAndBody() { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "resetSensorsAndBody"); return; - } qApp->getActiveDisplayPlugin()->resetSensors(); @@ -460,7 +445,7 @@ void MyAvatar::centerBody() { } // derive the desired body orientation from the current hmd orientation, before the sensor reset. - auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. // transform this body into world space auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix; @@ -497,7 +482,6 @@ void MyAvatar::clearIKJointLimitHistory() { } void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { - assert(QThread::currentThread() == thread()); // Reset dynamic state. @@ -506,14 +490,14 @@ void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { if (andReload) { _skeletonModel->reset(); } - if (andHead) { // which drives camera in desktop + if (andHead) { // which drives camera in desktop getHead()->reset(); } setThrust(glm::vec3(0.0f)); if (andRecenter) { // derive the desired body orientation from the *old* hmd orientation, before the sensor reset. - auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. // transform this body into world space auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix; @@ -540,8 +524,8 @@ void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { void MyAvatar::updateSitStandState(float newHeightReading, float dt) { const float STANDING_HEIGHT_MULTIPLE = 1.2f; const float SITTING_HEIGHT_MULTIPLE = 0.833f; - const float SITTING_TIMEOUT = 4.0f; // 4 seconds - const float STANDING_TIMEOUT = 0.3333f; // 1/3 second + const float SITTING_TIMEOUT = 4.0f; // 4 seconds + const float STANDING_TIMEOUT = 0.3333f; // 1/3 second const float SITTING_UPPER_BOUND = 1.52f; if (!getIsSitStandStateLocked()) { if (!getIsAway() && getControllerPoseInAvatarFrame(controller::Action::HEAD).isValid()) { @@ -601,9 +585,9 @@ void MyAvatar::updateSitStandState(float newHeightReading, float dt) { void MyAvatar::update(float deltaTime) { // update moving average of HMD facing in xz plane. const float HMD_FACING_TIMESCALE = getRotationRecenterFilterLength(); - const float PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH = 0.0f; // 100 percent shoulders + const float PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH = 0.0f; // 100 percent shoulders const float COSINE_THIRTY_DEGREES = 0.866f; - const float SQUATTY_TIMEOUT = 30.0f; // 30 seconds + const float SQUATTY_TIMEOUT = 30.0f; // 30 seconds const float HEIGHT_FILTER_COEFFICIENT = 0.01f; float tau = deltaTime / HMD_FACING_TIMESCALE; @@ -612,8 +596,8 @@ void MyAvatar::update(float deltaTime) { // put the average hand azimuth into sensor space. // then mix it with head facing direction to determine rotation recenter int spine2Index = _skeletonModel->getRig().indexOfJoint("Spine2"); - if (getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND).isValid() && getControllerPoseInAvatarFrame(controller::Action::RIGHT_HAND).isValid() && !(spine2Index < 0)) { - + if (getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND).isValid() && + getControllerPoseInAvatarFrame(controller::Action::RIGHT_HAND).isValid() && !(spine2Index < 0)) { // use the spine for the azimuth origin. glm::quat spine2Rot = getAbsoluteJointRotationInObjectFrame(spine2Index); glm::vec3 handHipAzimuthAvatarSpace = spine2Rot * glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y); @@ -623,8 +607,10 @@ void MyAvatar::update(float deltaTime) { glm::vec3 handHipAzimuthSensorSpace = transformVectorFast(worldToSensorMat, handHipAzimuthWorldSpace); glm::vec2 normedHandHipAzimuthSensorSpace(0.0f, 1.0f); if (glm::length(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)) > 0.0f) { - normedHandHipAzimuthSensorSpace = glm::normalize(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)); - glm::vec2 headFacingPlusHandHipAzimuthMix = lerp(normedHandHipAzimuthSensorSpace, _headControllerFacing, PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH); + normedHandHipAzimuthSensorSpace = + glm::normalize(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)); + glm::vec2 headFacingPlusHandHipAzimuthMix = + lerp(normedHandHipAzimuthSensorSpace, _headControllerFacing, PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH); _headControllerFacingMovingAverage = lerp(_headControllerFacingMovingAverage, headFacingPlusHandHipAzimuthMix, tau); } else { // use head facing if the chest arms vector is up or down. @@ -642,7 +628,8 @@ void MyAvatar::update(float deltaTime) { controller::Pose newHeightReading = getControllerPoseInSensorFrame(controller::Action::HEAD); if (newHeightReading.isValid()) { int newHeightReadingInCentimeters = glm::floor(newHeightReading.getTranslation().y * CENTIMETERS_PER_METER); - _averageUserHeightSensorSpace = lerp(_averageUserHeightSensorSpace, newHeightReading.getTranslation().y, HEIGHT_FILTER_COEFFICIENT); + _averageUserHeightSensorSpace = + lerp(_averageUserHeightSensorSpace, newHeightReading.getTranslation().y, HEIGHT_FILTER_COEFFICIENT); _recentModeReadings.insert(newHeightReadingInCentimeters); setCurrentStandingHeight(computeStandingHeightMode(newHeightReading)); setAverageHeadRotation(computeAverageHeadRotation(getControllerPoseInAvatarFrame(controller::Action::HEAD))); @@ -658,10 +645,9 @@ void MyAvatar::update(float deltaTime) { } float angleSpine2 = glm::dot(upSpine2, glm::vec3(0.0f, 1.0f, 0.0f)); - if (getControllerPoseInAvatarFrame(controller::Action::HEAD).getTranslation().y < (headDefaultPositionAvatarSpace.y - SQUAT_THRESHOLD) && - (angleSpine2 > COSINE_THIRTY_DEGREES) && - (getUserRecenterModel() != MyAvatar::SitStandModelType::ForceStand)) { - + if (getControllerPoseInAvatarFrame(controller::Action::HEAD).getTranslation().y < + (headDefaultPositionAvatarSpace.y - SQUAT_THRESHOLD) && + (angleSpine2 > COSINE_THIRTY_DEGREES) && (getUserRecenterModel() != MyAvatar::SitStandModelType::ForceStand)) { _squatTimer += deltaTime; if (_squatTimer > SQUATTY_TIMEOUT) { _squatTimer = 0.0f; @@ -677,20 +663,24 @@ void MyAvatar::update(float deltaTime) { if (_drawAverageFacingEnabled) { auto sensorHeadPose = getControllerPoseInSensorFrame(controller::Action::HEAD); glm::vec3 worldHeadPos = transformPoint(getSensorToWorldMatrix(), sensorHeadPose.getTranslation()); - glm::vec3 worldFacingAverage = transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacingMovingAverage.x, 0.0f, _headControllerFacingMovingAverage.y)); - glm::vec3 worldFacing = transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacing.x, 0.0f, _headControllerFacing.y)); + glm::vec3 worldFacingAverage = + transformVectorFast(getSensorToWorldMatrix(), + glm::vec3(_headControllerFacingMovingAverage.x, 0.0f, _headControllerFacingMovingAverage.y)); + glm::vec3 worldFacing = + transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacing.x, 0.0f, _headControllerFacing.y)); DebugDraw::getInstance().drawRay(worldHeadPos, worldHeadPos + worldFacing, glm::vec4(0.0f, 1.0f, 0.0f, 1.0f)); DebugDraw::getInstance().drawRay(worldHeadPos, worldHeadPos + worldFacingAverage, glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)); // draw hand azimuth vector - glm::vec3 handAzimuthMidpoint = transformPoint(getTransform().getMatrix(), glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y)); + glm::vec3 handAzimuthMidpoint = + transformPoint(getTransform().getMatrix(), glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y)); DebugDraw::getInstance().drawRay(getWorldPosition(), handAzimuthMidpoint, glm::vec4(0.0f, 1.0f, 1.0f, 1.0f)); } if (_goToPending) { setWorldPosition(_goToPosition); setWorldOrientation(_goToOrientation); - _headControllerFacingMovingAverage = _headControllerFacing; // reset moving average + _headControllerFacingMovingAverage = _headControllerFacing; // reset moving average _goToPending = false; // updateFromHMDSensorMatrix (called from paintGL) expects that the sensorToWorldMatrix is updated for any position changes // that happen between render and Application::update (which calls updateSensorToWorldMatrix to do so). @@ -700,7 +690,7 @@ void MyAvatar::update(float deltaTime) { emit positionGoneTo(); // Run safety tests as soon as we can after goToLocation, or clear if we're not colliding. _physicsSafetyPending = getCollisionsEnabled(); - _characterController.recomputeFlying(); // In case we've gone to into the sky. + _characterController.recomputeFlying(); // In case we've gone to into the sky. } if (_goToFeetAjustment && _skeletonModelLoaded) { auto feetAjustment = getWorldPosition() - getWorldFeetPosition(); @@ -712,7 +702,7 @@ void MyAvatar::update(float deltaTime) { // When needed and ready, arrange to check and fix. _physicsSafetyPending = false; if (_goToSafe) { - safeLanding(_goToPosition); // no-op if already safe + safeLanding(_goToPosition); // no-op if already safe } } @@ -720,7 +710,8 @@ void MyAvatar::update(float deltaTime) { head->relax(deltaTime); updateFromTrackers(deltaTime); - if (getIsInWalkingState() && glm::length(getControllerPoseInAvatarFrame(controller::Action::HEAD).getVelocity()) < DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { + if (getIsInWalkingState() && glm::length(getControllerPoseInAvatarFrame(controller::Action::HEAD).getVelocity()) < + DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { setIsInWalkingState(false); } @@ -731,12 +722,13 @@ void MyAvatar::update(float deltaTime) { setAudioLoudness(audio->getLastInputLoudness()); setAudioAverageLoudness(audio->getAudioAverageInputLoudness()); - glm::vec3 halfBoundingBoxDimensions(_characterController.getCapsuleRadius(), _characterController.getCapsuleHalfHeight(), _characterController.getCapsuleRadius()); + glm::vec3 halfBoundingBoxDimensions(_characterController.getCapsuleRadius(), _characterController.getCapsuleHalfHeight(), + _characterController.getCapsuleRadius()); // This might not be right! Isn't the capsule local offset in avatar space? -HRS 5/26/17 halfBoundingBoxDimensions += _characterController.getCapsuleLocalOffset(); QMetaObject::invokeMethod(audio, "setAvatarBoundingBoxParameters", - Q_ARG(glm::vec3, (getWorldPosition() - halfBoundingBoxDimensions)), - Q_ARG(glm::vec3, (halfBoundingBoxDimensions*2.0f))); + Q_ARG(glm::vec3, (getWorldPosition() - halfBoundingBoxDimensions)), + Q_ARG(glm::vec3, (halfBoundingBoxDimensions * 2.0f))); simulate(deltaTime, true); @@ -744,23 +736,20 @@ void MyAvatar::update(float deltaTime) { currentEnergy -= getAccelerationEnergy(); currentEnergy -= getAudioEnergy(); - if(didTeleport()) { + if (didTeleport()) { currentEnergy = 0.0f; } - currentEnergy = max(0.0f, min(currentEnergy,1.0f)); + currentEnergy = max(0.0f, min(currentEnergy, 1.0f)); emit energyChanged(currentEnergy); updateEyeContactTarget(deltaTime); } void MyAvatar::updateEyeContactTarget(float deltaTime) { - _eyeContactTargetTimer -= deltaTime; if (_eyeContactTargetTimer < 0.0f) { - const float CHANCE_OF_CHANGING_TARGET = 0.01f; if (randFloat() < CHANCE_OF_CHANGING_TARGET) { - float const FIFTY_FIFTY_CHANCE = 0.5f; float const EYE_TO_MOUTH_CHANCE = 0.25f; switch (_eyeContactTarget) { @@ -828,21 +817,20 @@ void MyAvatar::simulate(float deltaTime, bool inView) { if (isChildOfHead && !object->hasGrabs()) { // Cauterize or display children of head per head drawing state. updateChildCauterization(object, !_prevShouldDrawHead); - object->forEachDescendant([&](SpatiallyNestablePointer descendant) { - updateChildCauterization(descendant, !_prevShouldDrawHead); - }); + object->forEachDescendant( + [&](SpatiallyNestablePointer descendant) { updateChildCauterization(descendant, !_prevShouldDrawHead); }); _cauterizedChildrenOfHead.insert(object); objectsToUncauterize.erase(object); } else if (objectsToUncauterize.find(object) == objectsToUncauterize.end()) { objectsToUncauterize.insert(object); - object->forEachDescendant([&](SpatiallyNestablePointer descendant) { - objectsToUncauterize.insert(descendant); - }); + object->forEachDescendant( + [&](SpatiallyNestablePointer descendant) { objectsToUncauterize.insert(descendant); }); } }); // Redisplay cauterized entities that are no longer children of the avatar. - for (auto cauterizedChild = objectsToUncauterize.begin(); cauterizedChild != objectsToUncauterize.end(); cauterizedChild++) { + for (auto cauterizedChild = objectsToUncauterize.begin(); cauterizedChild != objectsToUncauterize.end(); + cauterizedChild++) { updateChildCauterization(*cauterizedChild, false); } } @@ -886,7 +874,7 @@ void MyAvatar::simulate(float deltaTime, bool inView) { if (!_skeletonModel->hasSkeleton()) { // All the simulation that can be done has been done - getHead()->setPosition(getWorldPosition()); // so audio-position isn't 0,0,0 + getHead()->setPosition(getWorldPosition()); // so audio-position isn't 0,0,0 return; } @@ -967,8 +955,7 @@ void MyAvatar::updateFromHMDSensorMatrix(const glm::mat4& hmdSensorMatrix) { _hmdSensorMatrix = hmdSensorMatrix; auto newHmdSensorPosition = extractTranslation(hmdSensorMatrix); - if (newHmdSensorPosition != getHMDSensorPosition() && - glm::length(newHmdSensorPosition) > MAX_HMD_ORIGIN_DISTANCE) { + if (newHmdSensorPosition != getHMDSensorPosition() && glm::length(newHmdSensorPosition) > MAX_HMD_ORIGIN_DISTANCE) { qWarning() << "Invalid HMD sensor position " << newHmdSensorPosition; // Ignore unreasonable HMD sensor data return; @@ -996,8 +983,8 @@ glm::vec2 MyAvatar::computeHandAzimuth() const { glm::vec2 latestHipToHandController = _hipToHandController; int spine2Index = _skeletonModel->getRig().indexOfJoint("Spine2"); - if (leftHandPoseAvatarSpace.isValid() && rightHandPoseAvatarSpace.isValid() && headPoseAvatarSpace.isValid() && !(spine2Index < 0)) { - + if (leftHandPoseAvatarSpace.isValid() && rightHandPoseAvatarSpace.isValid() && headPoseAvatarSpace.isValid() && + !(spine2Index < 0)) { glm::vec3 spine2Position = getAbsoluteJointTranslationInObjectFrame(spine2Index); glm::quat spine2Rotation = getAbsoluteJointRotationInObjectFrame(spine2Index); @@ -1009,8 +996,10 @@ glm::vec2 MyAvatar::computeHandAzimuth() const { // we need the old azimuth reading to prevent flipping the facing direction 180 // in the case where the hands go from being slightly less than 180 apart to slightly more than 180 apart. glm::vec2 oldAzimuthReading = _hipToHandController; - if ((glm::length(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)) > 0.0f) && (glm::length(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)) > 0.0f)) { - latestHipToHandController = lerp(glm::normalize(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)), glm::normalize(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)), HALFWAY); + if ((glm::length(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)) > 0.0f) && + (glm::length(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)) > 0.0f)) { + latestHipToHandController = lerp(glm::normalize(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)), + glm::normalize(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)), HALFWAY); } else { latestHipToHandController = glm::vec2(0.0f, 1.0f); } @@ -1058,11 +1047,11 @@ void MyAvatar::updateJointFromController(controller::Action poseKey, ThreadSafeV // update sensor to world matrix from current body position and hmd sensor. // This is so the correct camera can be used for rendering. void MyAvatar::updateSensorToWorldMatrix() { - // update the sensor mat so that the body position will end up in the desired // position when driven from the head. float sensorToWorldScale = getEyeHeight() / getUserEyeHeight(); - glm::mat4 desiredMat = createMatFromScaleQuatAndPos(glm::vec3(sensorToWorldScale), getWorldOrientation(), getWorldPosition()); + glm::mat4 desiredMat = + createMatFromScaleQuatAndPos(glm::vec3(sensorToWorldScale), getWorldOrientation(), getWorldPosition()); _sensorToWorldMatrix = desiredMat * glm::inverse(_bodySensorMatrix); bool hasSensorToWorldScaleChanged = false; @@ -1080,11 +1069,10 @@ void MyAvatar::updateSensorToWorldMatrix() { _sensorToWorldMatrixCache.set(_sensorToWorldMatrix); updateJointFromController(controller::Action::LEFT_HAND, _controllerLeftHandMatrixCache); updateJointFromController(controller::Action::RIGHT_HAND, _controllerRightHandMatrixCache); - + if (hasSensorToWorldScaleChanged) { emit sensorToWorldScaleChanged(sensorToWorldScale); } - } // Update avatar head rotation with sensor data @@ -1109,8 +1097,7 @@ void MyAvatar::updateFromTrackers(float deltaTime) { const float TRACKER_YAW_TURN_SENSITIVITY = 0.5f; const float TRACKER_MIN_YAW_TURN = 15.0f; const float TRACKER_MAX_YAW_TURN = 50.0f; - if ( (fabs(estimatedRotation.y) > TRACKER_MIN_YAW_TURN) && - (fabs(estimatedRotation.y) < TRACKER_MAX_YAW_TURN) ) { + if ((fabs(estimatedRotation.y) > TRACKER_MIN_YAW_TURN) && (fabs(estimatedRotation.y) < TRACKER_MAX_YAW_TURN)) { if (estimatedRotation.y > 0.0f) { _bodyYawDelta += (estimatedRotation.y - TRACKER_MIN_YAW_TURN) * TRACKER_YAW_TURN_SENSITIVITY; } else { @@ -1125,7 +1112,6 @@ void MyAvatar::updateFromTrackers(float deltaTime) { // their head only 30 degrees or so, this may correspond to a 90 degree field of view. // Note that roll is magnified by a constant because it is not related to field of view. - Head* head = getHead(); if (hasHead || playing) { head->setDeltaPitch(estimatedRotation.x); @@ -1191,15 +1177,15 @@ controller::Pose MyAvatar::getRightHandTipPose() const { void MyAvatar::render(RenderArgs* renderArgs) { // don't render if we've been asked to disable local rendering if (!_shouldRender) { - return; // exit early + return; // exit early } Avatar::render(renderArgs); } void MyAvatar::overrideAnimation(const QString& url, float fps, bool loop, float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "overrideAnimation", Q_ARG(const QString&, url), Q_ARG(float, fps), - Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); + QMetaObject::invokeMethod(this, "overrideAnimation", Q_ARG(const QString&, url), Q_ARG(float, fps), Q_ARG(bool, loop), + Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); return; } _skeletonModel->getRig().overrideAnimation(url, fps, loop, firstFrame, lastFrame); @@ -1207,8 +1193,8 @@ void MyAvatar::overrideAnimation(const QString& url, float fps, bool loop, float void MyAvatar::overrideHandAnimation(bool isLeft, const QString& url, float fps, bool loop, float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "overrideHandAnimation", Q_ARG(bool, isLeft), Q_ARG(const QString&, url), Q_ARG(float, fps), - Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); + QMetaObject::invokeMethod(this, "overrideHandAnimation", Q_ARG(bool, isLeft), Q_ARG(const QString&, url), + Q_ARG(float, fps), Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); return; } _skeletonModel->getRig().overrideHandAnimation(isLeft, url, fps, loop, firstFrame, lastFrame); @@ -1239,8 +1225,12 @@ QStringList MyAvatar::getAnimationRoles() { return _skeletonModel->getRig().getAnimationRoles(); } -void MyAvatar::overrideRoleAnimation(const QString& role, const QString& url, float fps, bool loop, - float firstFrame, float lastFrame) { +void MyAvatar::overrideRoleAnimation(const QString& role, + const QString& url, + float fps, + bool loop, + float firstFrame, + float lastFrame) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "overrideRoleAnimation", Q_ARG(const QString&, role), Q_ARG(const QString&, url), Q_ARG(float, fps), Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); @@ -1259,9 +1249,9 @@ void MyAvatar::restoreRoleAnimation(const QString& role) { void MyAvatar::saveAvatarUrl() { if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid()) { - _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() ? - "" : - _fullAvatarURLFromPreferences.toString()); + _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() + ? "" + : _fullAvatarURLFromPreferences.toString()); } } @@ -1278,10 +1268,12 @@ void MyAvatar::resizeAvatarEntitySettingHandles(uint32_t maxIndex) { uint32_t settingsIndex = (uint32_t)_avatarEntityIDSettings.size() + 1; while (settingsIndex <= maxIndex) { Setting::Handle idHandle(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" - << QString::number(settingsIndex) << "id", QUuid()); + << QString::number(settingsIndex) << "id", + QUuid()); _avatarEntityIDSettings.push_back(idHandle); Setting::Handle dataHandle(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" - << QString::number(settingsIndex) << "properties", QByteArray()); + << QString::number(settingsIndex) << "properties", + QByteArray()); _avatarEntityDataSettings.push_back(dataHandle); settingsIndex++; } @@ -1299,10 +1291,10 @@ void MyAvatar::saveData() { // only save the fullAvatarURL if it has not been overwritten on command line // (so the overrideURL is not valid), or it was overridden _and_ we specified // --replaceAvatarURL (so _saveAvatarOverrideUrl is true) - if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid() ) { - _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() ? - "" : - _fullAvatarURLFromPreferences.toString()); + if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid()) { + _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() + ? "" + : _fullAvatarURLFromPreferences.toString()); } _fullAvatarModelNameSetting.set(_fullAvatarModelName); @@ -1472,16 +1464,12 @@ void MyAvatar::setEnableInverseKinematics(bool isEnabled) { void MyAvatar::storeAvatarEntityDataPayload(const QUuid& entityID, const QByteArray& payload) { AvatarData::storeAvatarEntityDataPayload(entityID, payload); - _avatarEntitiesLock.withWriteLock([&] { - _cachedAvatarEntityBlobsToAddOrUpdate.push_back(entityID); - }); + _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobsToAddOrUpdate.push_back(entityID); }); } void MyAvatar::clearAvatarEntity(const QUuid& entityID, bool requiresRemovalFromTree) { AvatarData::clearAvatarEntity(entityID, requiresRemovalFromTree); - _avatarEntitiesLock.withWriteLock([&] { - _cachedAvatarEntityBlobsToDelete.push_back(entityID); - }); + _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobsToDelete.push_back(entityID); }); } void MyAvatar::sanitizeAvatarEntityProperties(EntityItemProperties& properties) const { @@ -1506,9 +1494,7 @@ void MyAvatar::sanitizeAvatarEntityProperties(EntityItemProperties& properties) void MyAvatar::handleChangedAvatarEntityData() { // NOTE: this is a per-frame update - if (getID().isNull() || - getID() == AVATAR_SELF_ID || - DependencyManager::get()->getSessionUUID() == QUuid()) { + if (getID().isNull() || getID() == AVATAR_SELF_ID || DependencyManager::get()->getSessionUUID() == QUuid()) { // wait until MyAvatar and this Node gets an ID before doing this. Otherwise, various things go wrong: // things get their parent fixed up from AVATAR_SELF_ID to a null uuid which means "no parent". return; @@ -1554,7 +1540,7 @@ void MyAvatar::handleChangedAvatarEntityData() { entitiesToUpdate = std::move(_entitiesToUpdate); }); - auto removeAllInstancesHelper = [] (const QUuid& id, std::vector& v) { + auto removeAllInstancesHelper = [](const QUuid& id, std::vector& v) { uint32_t i = 0; while (i < v.size()) { if (id == v[i]) { @@ -1582,9 +1568,7 @@ void MyAvatar::handleChangedAvatarEntityData() { // DELETE real entities for (const auto& id : entitiesToDelete) { - entityTree->withWriteLock([&] { - entityTree->deleteEntity(id); - }); + entityTree->withWriteLock([&] { entityTree->deleteEntity(id); }); } // ADD real entities @@ -1595,21 +1579,19 @@ void MyAvatar::handleChangedAvatarEntityData() { _avatarEntitiesLock.withReadLock([&] { AvatarEntityMap::iterator itr = _cachedAvatarEntityBlobs.find(id); if (itr == _cachedAvatarEntityBlobs.end()) { - blobFailed = true; // blob doesn't exist + blobFailed = true; // blob doesn't exist return; } std::lock_guard guard(_scriptEngineLock); if (!EntityItemProperties::blobToProperties(*_scriptEngine, itr.value(), properties)) { - blobFailed = true; // blob is corrupt + blobFailed = true; // blob is corrupt } }); if (blobFailed) { // remove from _cachedAvatarEntityBlobUpdatesToSkip just in case: // avoids a resource leak when blob updates to be skipped are never actually skipped // when the blob fails to result in a real EntityItem - _avatarEntitiesLock.withWriteLock([&] { - removeAllInstancesHelper(id, _cachedAvatarEntityBlobUpdatesToSkip); - }); + _avatarEntitiesLock.withWriteLock([&] { removeAllInstancesHelper(id, _cachedAvatarEntityBlobUpdatesToSkip); }); continue; } sanitizeAvatarEntityProperties(properties); @@ -1679,7 +1661,7 @@ void MyAvatar::handleChangedAvatarEntityData() { _cachedAvatarEntityBlobUpdatesToSkip[i] = _cachedAvatarEntityBlobUpdatesToSkip.back(); _cachedAvatarEntityBlobUpdatesToSkip.pop_back(); skip = true; - break; // assume no duplicates + break; // assume no duplicates } else { ++i; } @@ -1743,9 +1725,7 @@ bool MyAvatar::updateStaleAvatarEntityBlobs() const { std::lock_guard guard(_scriptEngineLock); EntityItemProperties::propertiesToBlob(*_scriptEngine, getID(), properties, blob); } - _avatarEntitiesLock.withWriteLock([&] { - _cachedAvatarEntityBlobs[id] = blob; - }); + _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobs[id] = blob; }); } } return true; @@ -1772,9 +1752,7 @@ AvatarEntityMap MyAvatar::getAvatarEntityData() const { // NOTE: the return value is expected to be a map of unfortunately-formatted-binary-blobs updateStaleAvatarEntityBlobs(); AvatarEntityMap result; - _avatarEntitiesLock.withReadLock([&] { - result = _cachedAvatarEntityBlobs; - }); + _avatarEntitiesLock.withReadLock([&] { result = _cachedAvatarEntityBlobs; }); return result; } @@ -1875,7 +1853,9 @@ void MyAvatar::avatarEntityDataToJson(QJsonObject& root) const { AvatarEntityMap::const_iterator itr = _cachedAvatarEntityBlobs.begin(); while (itr != _cachedAvatarEntityBlobs.end()) { QVariantMap entityData; - QUuid id = _avatarEntityForRecording.size() == _cachedAvatarEntityBlobs.size() ? _avatarEntityForRecording.values()[entityCount++] : itr.key(); + QUuid id = _avatarEntityForRecording.size() == _cachedAvatarEntityBlobs.size() + ? _avatarEntityForRecording.values()[entityCount++] + : itr.key(); entityData.insert("id", id); entityData.insert("properties", itr.value().toBase64()); avatarEntityJson.push_back(QVariant(entityData).toJsonObject()); @@ -1905,7 +1885,7 @@ void MyAvatar::loadData() { loadAvatarEntityDataFromSettings(); // Flying preferences must be loaded before calling setFlyingEnabled() - Setting::Handle firstRunVal { Settings::firstRun, true }; + Setting::Handle firstRunVal{ Settings::firstRun, true }; setFlyingHMDPref(firstRunVal.get() ? false : _flyingHMDSetting.get()); setMovementReference(firstRunVal.get() ? false : _movementReferenceSetting.get()); setDriveGear1(firstRunVal.get() ? DEFAULT_GEAR_1 : _driveGear1Setting.get()); @@ -1931,7 +1911,7 @@ void MyAvatar::loadData() { setUserRecenterModel(stringToUserRecenterModel(_userRecenterModelSetting.get(USER_RECENTER_MODEL_AUTO))); setEnableMeshVisible(Menu::getInstance()->isOptionChecked(MenuOption::MeshVisible)); - _follow.setToggleHipsFollowing (Menu::getInstance()->isOptionChecked(MenuOption::ToggleHipsFollowing)); + _follow.setToggleHipsFollowing(Menu::getInstance()->isOptionChecked(MenuOption::ToggleHipsFollowing)); setEnableDebugDrawBaseOfSupport(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawBaseOfSupport)); setEnableDebugDrawDefaultPose(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawDefaultPose)); setEnableDebugDrawAnimPose(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawAnimPose)); @@ -1959,7 +1939,7 @@ void MyAvatar::loadAvatarEntityDataFromSettings() { _entitiesToAdd.reserve(numEntities); // TODO: build map between old and new IDs so we can restitch parent-child relationships for (int i = 0; i < numEntities; i++) { - QUuid id = QUuid::createUuid(); // generate a new ID + QUuid id = QUuid::createUuid(); // generate a new ID _cachedAvatarEntityBlobs[id] = _avatarEntityDataSettings[i].get(); _entitiesToAdd.push_back(id); // this blob is the "authoritative source" for this AvatarEntity and we want to avoid overwriting it @@ -2029,10 +2009,9 @@ AttachmentData MyAvatar::loadAttachmentData(const QUrl& modelURL, const QString& return attachment; } - int MyAvatar::parseDataFromBuffer(const QByteArray& buffer) { qCDebug(interfaceapp) << "Error: ignoring update packet for MyAvatar" - << " packetLength = " << buffer.size(); + << " packetLength = " << buffer.size(); // this packet is just bad, so we pretend that we unpacked it ALL return buffer.size(); } @@ -2046,8 +2025,12 @@ ScriptAvatarData* MyAvatar::getTargetAvatar() const { } } -static float lookAtCostFunction(const glm::vec3& myForward, const glm::vec3& myPosition, const glm::vec3& otherForward, const glm::vec3& otherPosition, - bool otherIsTalking, bool lookingAtOtherAlready) { +static float lookAtCostFunction(const glm::vec3& myForward, + const glm::vec3& myPosition, + const glm::vec3& otherForward, + const glm::vec3& otherPosition, + bool otherIsTalking, + bool lookingAtOtherAlready) { const float DISTANCE_FACTOR = 3.14f; const float MY_ANGLE_FACTOR = 1.0f; const float OTHER_ANGLE_FACTOR = 1.0f; @@ -2055,7 +2038,7 @@ static float lookAtCostFunction(const glm::vec3& myForward, const glm::vec3& myP const float LOOKING_AT_OTHER_ALREADY_TERM = lookingAtOtherAlready ? -0.2f : 0.0f; const float GREATEST_LOOKING_AT_DISTANCE = 10.0f; // meters - const float MAX_MY_ANGLE = PI / 8.0f; // 22.5 degrees, Don't look too far away from the head facing. + const float MAX_MY_ANGLE = PI / 8.0f; // 22.5 degrees, Don't look too far away from the head facing. const float MAX_OTHER_ANGLE = (3.0f * PI) / 4.0f; // 135 degrees, Don't stare at the back of another avatars head. glm::vec3 d = otherPosition - myPosition; @@ -2067,11 +2050,8 @@ static float lookAtCostFunction(const glm::vec3& myForward, const glm::vec3& myP if (distance > GREATEST_LOOKING_AT_DISTANCE || myAngle > MAX_MY_ANGLE || otherAngle > MAX_OTHER_ANGLE) { return FLT_MAX; } else { - return (DISTANCE_FACTOR * distance + - MY_ANGLE_FACTOR * myAngle + - OTHER_ANGLE_FACTOR * otherAngle + - OTHER_IS_TALKING_TERM + - LOOKING_AT_OTHER_ALREADY_TERM); + return (DISTANCE_FACTOR * distance + MY_ANGLE_FACTOR * myAngle + OTHER_ANGLE_FACTOR * otherAngle + + OTHER_IS_TALKING_TERM + LOOKING_AT_OTHER_ALREADY_TERM); } } @@ -2094,7 +2074,8 @@ void MyAvatar::computeMyLookAtTarget(const AvatarHash& hash) { const float TIME_WITHOUT_TALKING_THRESHOLD = 1.0f; bool otherIsTalking = avatar->getHead()->getTimeWithoutTalking() <= TIME_WITHOUT_TALKING_THRESHOLD; bool lookingAtOtherAlready = _lookAtTargetAvatar.lock().get() == avatar.get(); - float cost = lookAtCostFunction(myForward, myPosition, otherForward, otherPosition, otherIsTalking, lookingAtOtherAlready); + float cost = + lookAtCostFunction(myForward, myPosition, otherForward, otherPosition, otherIsTalking, lookingAtOtherAlready); if (cost < bestCost) { bestCost = cost; bestAvatar = avatar; @@ -2115,9 +2096,8 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { std::shared_ptr avatar = std::static_pointer_cast(avatarData); if (!avatar->isMyAvatar() && avatar->isInitialized()) { if (_lookAtSnappingEnabled && avatar->getLookAtSnappingEnabled() && isLookingAtMe(avatar)) { - // Alter their gaze to look directly at my camera; this looks more natural than looking at my avatar's face. - glm::vec3 lookAtPosition = avatar->getHead()->getLookAtPosition(); // A position, in world space, on my avatar. + glm::vec3 lookAtPosition = avatar->getHead()->getLookAtPosition(); // A position, in world space, on my avatar. // The camera isn't at the point midway between the avatar eyes. (Even without an HMD, the head can be offset a bit.) // Let's get everything to world space: @@ -2128,12 +2108,12 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { // (We will be adding that offset to the camera position, after making some other adjustments.) glm::vec3 gazeOffset = lookAtPosition - getHead()->getEyePosition(); - ViewFrustum viewFrustum; - qApp->copyViewFrustum(viewFrustum); + ViewFrustum viewFrustum; + qApp->copyViewFrustum(viewFrustum); - glm::vec3 viewPosition = viewFrustum.getPosition(); + glm::vec3 viewPosition = viewFrustum.getPosition(); #if DEBUG_ALWAYS_LOOKAT_EYES_NOT_CAMERA - viewPosition = (avatarLeftEye + avatarRightEye) / 2.0f; + viewPosition = (avatarLeftEye + avatarRightEye) / 2.0f; #endif // scale gazeOffset by IPD, if wearing an HMD. if (qApp->isHMDMode()) { @@ -2171,7 +2151,6 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { } void MyAvatar::updateLookAtTargetAvatar() { - // The AvatarManager is a mutable class shared by many threads. We make a thread-safe deep copy of it, // to avoid having to hold a lock while we iterate over all the avatars within. AvatarHash hash = DependencyManager::get()->getHashCopy(); @@ -2285,8 +2264,7 @@ void MyAvatar::setJointTranslation(int index, const glm::vec3& translation) { } default: { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "setJointTranslation", - Q_ARG(int, index), Q_ARG(const glm::vec3&, translation)); + QMetaObject::invokeMethod(this, "setJointTranslation", Q_ARG(int, index), Q_ARG(const glm::vec3&, translation)); return; } // HACK: ATM only JS scripts call setJointData() on MyAvatar so we hardcode the priority @@ -2325,9 +2303,7 @@ void MyAvatar::setJointData(const QString& name, const glm::quat& rotation, cons Q_ARG(const glm::vec3&, translation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { - setJointData(index, rotation, translation); - }); + writeLockWithNamedJointIndex(name, [&](int index) { setJointData(index, rotation, translation); }); } void MyAvatar::setJointRotation(const QString& name, const glm::quat& rotation) { @@ -2335,9 +2311,7 @@ void MyAvatar::setJointRotation(const QString& name, const glm::quat& rotation) QMetaObject::invokeMethod(this, "setJointRotation", Q_ARG(QString, name), Q_ARG(const glm::quat&, rotation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { - setJointRotation(index, rotation); - }); + writeLockWithNamedJointIndex(name, [&](int index) { setJointRotation(index, rotation); }); } void MyAvatar::setJointTranslation(const QString& name, const glm::vec3& translation) { @@ -2345,9 +2319,7 @@ void MyAvatar::setJointTranslation(const QString& name, const glm::vec3& transla QMetaObject::invokeMethod(this, "setJointTranslation", Q_ARG(QString, name), Q_ARG(const glm::vec3&, translation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { - setJointTranslation(index, translation); - }); + writeLockWithNamedJointIndex(name, [&](int index) { setJointTranslation(index, translation); }); } void MyAvatar::clearJointData(const QString& name) { @@ -2355,9 +2327,7 @@ void MyAvatar::clearJointData(const QString& name) { QMetaObject::invokeMethod(this, "clearJointData", Q_ARG(QString, name)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { - clearJointData(index); - }); + writeLockWithNamedJointIndex(name, [&](int index) { clearJointData(index); }); } void MyAvatar::clearJointsData() { @@ -2392,36 +2362,36 @@ void MyAvatar::setSkeletonModelURL(const QUrl& skeletonModelURL) { _skeletonModelLoaded = false; std::shared_ptr skeletonConnection = std::make_shared(); - *skeletonConnection = QObject::connect(_skeletonModel.get(), &SkeletonModel::skeletonLoaded, [this, skeletonModelChangeCount, skeletonConnection]() { - if (skeletonModelChangeCount == _skeletonModelChangeCount) { + *skeletonConnection = QObject::connect(_skeletonModel.get(), &SkeletonModel::skeletonLoaded, + [this, skeletonModelChangeCount, skeletonConnection]() { + if (skeletonModelChangeCount == _skeletonModelChangeCount) { + if (_fullAvatarModelName.isEmpty()) { + // Store the FST file name into preferences + const auto& mapping = _skeletonModel->getGeometry()->getMapping(); + if (mapping.value("name").isValid()) { + _fullAvatarModelName = mapping.value("name").toString(); + } + } - if (_fullAvatarModelName.isEmpty()) { - // Store the FST file name into preferences - const auto& mapping = _skeletonModel->getGeometry()->getMapping(); - if (mapping.value("name").isValid()) { - _fullAvatarModelName = mapping.value("name").toString(); - } - } + initHeadBones(); + _skeletonModel->setCauterizeBoneSet(_headBoneSet); + _fstAnimGraphOverrideUrl = + _skeletonModel->getGeometry()->getAnimGraphOverrideUrl(); + initAnimGraph(); + initFlowFromFST(); - initHeadBones(); - _skeletonModel->setCauterizeBoneSet(_headBoneSet); - _fstAnimGraphOverrideUrl = _skeletonModel->getGeometry()->getAnimGraphOverrideUrl(); - initAnimGraph(); - initFlowFromFST(); + _skeletonModelLoaded = true; + } + QObject::disconnect(*skeletonConnection); + }); - _skeletonModelLoaded = true; - } - QObject::disconnect(*skeletonConnection); - }); - saveAvatarUrl(); emit skeletonChanged(); } bool isWearableEntity(const EntityItemPointer& entity) { - return entity->isVisible() - && (entity->getParentID() == DependencyManager::get()->getSessionUUID() - || entity->getParentID() == AVATAR_SELF_ID); + return entity->isVisible() && (entity->getParentID() == DependencyManager::get()->getSessionUUID() || + entity->getParentID() == AVATAR_SELF_ID); } void MyAvatar::removeWornAvatarEntity(const EntityItemID& entityID) { @@ -2445,9 +2415,7 @@ void MyAvatar::removeWornAvatarEntity(const EntityItemID& entityID) { void MyAvatar::clearWornAvatarEntities() { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { - avatarEntityIDs = _packedAvatarEntityData.keys(); - }); + _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); for (auto entityID : avatarEntityIDs) { removeWornAvatarEntity(entityID); } @@ -2473,9 +2441,7 @@ QVariantList MyAvatar::getAvatarEntitiesVariant() { EntityTreePointer entityTree = treeRenderer ? treeRenderer->getTree() : nullptr; if (entityTree) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { - avatarEntityIDs = _packedAvatarEntityData.keys(); - }); + _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); for (const auto& entityID : avatarEntityIDs) { auto entity = entityTree->findEntityByID(entityID); if (!entity) { @@ -2500,7 +2466,6 @@ QVariantList MyAvatar::getAvatarEntitiesVariant() { return avatarEntitiesData; } - void MyAvatar::resetFullAvatarURL() { auto lastAvatarURL = getFullAvatarURLFromPreferences(); auto lastAvatarName = getFullAvatarModelName(); @@ -2509,11 +2474,8 @@ void MyAvatar::resetFullAvatarURL() { } void MyAvatar::useFullAvatarURL(const QUrl& fullAvatarURL, const QString& modelName) { - if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "useFullAvatarURL", - Q_ARG(const QUrl&, fullAvatarURL), - Q_ARG(const QString&, modelName)); + BLOCKING_INVOKE_METHOD(this, "useFullAvatarURL", Q_ARG(const QUrl&, fullAvatarURL), Q_ARG(const QString&, modelName)); return; } @@ -2567,7 +2529,7 @@ controller::Pose MyAvatar::getControllerPoseInSensorFrame(controller::Action act if (iter != _controllerPoseMap.end()) { return iter->second; } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2576,7 +2538,7 @@ controller::Pose MyAvatar::getControllerPoseInWorldFrame(controller::Action acti if (pose.valid) { return pose.transform(getSensorToWorldMatrix()); } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2586,7 +2548,7 @@ controller::Pose MyAvatar::getControllerPoseInAvatarFrame(controller::Action act glm::mat4 invAvatarMatrix = glm::inverse(createMatFromQuatAndPos(getWorldOrientation(), getWorldPosition())); return pose.transform(invAvatarMatrix); } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2608,7 +2570,7 @@ void MyAvatar::updateMotors() { float verticalMotorTimescale; if (_characterController.getState() == CharacterController::State::Hover || - _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { + _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { horizontalMotorTimescale = FLYING_MOTOR_TIMESCALE; verticalMotorTimescale = FLYING_MOTOR_TIMESCALE; } else { @@ -2618,7 +2580,7 @@ void MyAvatar::updateMotors() { if (_motionBehaviors & AVATAR_MOTION_ACTION_MOTOR_ENABLED) { if (_characterController.getState() == CharacterController::State::Hover || - _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { + _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { motorRotation = getMyHead()->getHeadOrientation(); } else { // non-hovering = walking: follow camera twist about vertical but not lift @@ -2626,14 +2588,15 @@ void MyAvatar::updateMotors() { // however, we need to perform the decomposition in the avatar-frame // using the local UP axis and then transform back into world-frame glm::quat orientation = getWorldOrientation(); - glm::quat headOrientation = glm::inverse(orientation) * getMyHead()->getHeadOrientation(); // avatar-frame + glm::quat headOrientation = glm::inverse(orientation) * getMyHead()->getHeadOrientation(); // avatar-frame glm::quat liftRotation; swingTwistDecomposition(headOrientation, Vectors::UNIT_Y, liftRotation, motorRotation); motorRotation = orientation * motorRotation; } if (_isPushing || _isBraking || !_isBeingPushed) { - _characterController.addMotor(_actionMotorVelocity, motorRotation, horizontalMotorTimescale, verticalMotorTimescale); + _characterController.addMotor(_actionMotorVelocity, motorRotation, horizontalMotorTimescale, + verticalMotorTimescale); } else { // _isBeingPushed must be true --> disable action motor by giving it a long timescale, // otherwise it's attempt to "stand in in place" could defeat scripted motor/thrusts @@ -2653,7 +2616,8 @@ void MyAvatar::updateMotors() { _characterController.addMotor(_scriptedMotorVelocity, motorRotation, _scriptedMotorTimescale); } else { // dynamic mode - _characterController.addMotor(_scriptedMotorVelocity, motorRotation, horizontalMotorTimescale, verticalMotorTimescale); + _characterController.addMotor(_scriptedMotorVelocity, motorRotation, horizontalMotorTimescale, + verticalMotorTimescale); } } @@ -2758,8 +2722,7 @@ void MyAvatar::setScriptedMotorVelocity(const glm::vec3& velocity) { void MyAvatar::setScriptedMotorTimescale(float timescale) { // we clamp the timescale on the large side (instead of just the low side) to prevent // obnoxiously large values from introducing NaN into avatar's velocity - _scriptedMotorTimescale = glm::clamp(timescale, MIN_SCRIPTED_MOTOR_TIMESCALE, - DEFAULT_SCRIPTED_MOTOR_TIMESCALE); + _scriptedMotorTimescale = glm::clamp(timescale, MIN_SCRIPTED_MOTOR_TIMESCALE, DEFAULT_SCRIPTED_MOTOR_TIMESCALE); } void MyAvatar::setScriptedMotorFrame(QString frame) { @@ -2800,21 +2763,18 @@ SharedSoundPointer MyAvatar::getCollisionSound() { return _collisionSound; } -void MyAvatar::attach(const QString& modelURL, const QString& jointName, - const glm::vec3& translation, const glm::quat& rotation, - float scale, bool isSoft, - bool allowDuplicates, bool useSaved) { +void MyAvatar::attach(const QString& modelURL, + const QString& jointName, + const glm::vec3& translation, + const glm::quat& rotation, + float scale, + bool isSoft, + bool allowDuplicates, + bool useSaved) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "attach", - Q_ARG(const QString&, modelURL), - Q_ARG(const QString&, jointName), - Q_ARG(const glm::vec3&, translation), - Q_ARG(const glm::quat&, rotation), - Q_ARG(float, scale), - Q_ARG(bool, isSoft), - Q_ARG(bool, allowDuplicates), - Q_ARG(bool, useSaved) - ); + BLOCKING_INVOKE_METHOD(this, "attach", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName), + Q_ARG(const glm::vec3&, translation), Q_ARG(const glm::quat&, rotation), Q_ARG(float, scale), + Q_ARG(bool, isSoft), Q_ARG(bool, allowDuplicates), Q_ARG(bool, useSaved)); return; } AttachmentData data; @@ -2832,10 +2792,7 @@ void MyAvatar::attach(const QString& modelURL, const QString& jointName, void MyAvatar::detachOne(const QString& modelURL, const QString& jointName) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "detachOne", - Q_ARG(const QString&, modelURL), - Q_ARG(const QString&, jointName) - ); + BLOCKING_INVOKE_METHOD(this, "detachOne", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName)); return; } QUuid entityID; @@ -2847,10 +2804,7 @@ void MyAvatar::detachOne(const QString& modelURL, const QString& jointName) { void MyAvatar::detachAll(const QString& modelURL, const QString& jointName) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "detachAll", - Q_ARG(const QString&, modelURL), - Q_ARG(const QString&, jointName) - ); + BLOCKING_INVOKE_METHOD(this, "detachAll", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName)); return; } QUuid entityID; @@ -2862,8 +2816,7 @@ void MyAvatar::detachAll(const QString& modelURL, const QString& jointName) { void MyAvatar::setAttachmentData(const QVector& attachmentData) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "setAttachmentData", - Q_ARG(const QVector&, attachmentData)); + BLOCKING_INVOKE_METHOD(this, "setAttachmentData", Q_ARG(const QVector&, attachmentData)); return; } std::vector newEntitiesProperties; @@ -2886,12 +2839,10 @@ void MyAvatar::setAttachmentData(const QVector& attachmentData) emit attachmentsChanged(); } -QVector MyAvatar::getAttachmentData() const { +QVector MyAvatar::getAttachmentData() const { QVector attachmentData; QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { - avatarEntityIDs = _packedAvatarEntityData.keys(); - }); + _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); for (const auto& entityID : avatarEntityIDs) { auto properties = DependencyManager::get()->getEntityProperties(entityID); AttachmentData data = entityPropertiesToAttachmentData(properties); @@ -2910,8 +2861,7 @@ QVariantList MyAvatar::getAttachmentsVariant() const { void MyAvatar::setAttachmentsVariant(const QVariantList& variant) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "setAttachmentsVariant", - Q_ARG(const QVariantList&, variant)); + BLOCKING_INVOKE_METHOD(this, "setAttachmentsVariant", Q_ARG(const QVariantList&, variant)); return; } QVector newAttachments; @@ -2922,14 +2872,12 @@ void MyAvatar::setAttachmentsVariant(const QVariantList& variant) { newAttachments.append(attachment); } } - setAttachmentData(newAttachments); + setAttachmentData(newAttachments); } bool MyAvatar::findAvatarEntity(const QString& modelURL, const QString& jointName, QUuid& entityID) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { - avatarEntityIDs = _packedAvatarEntityData.keys(); - }); + _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); for (const auto& entityID : avatarEntityIDs) { auto props = DependencyManager::get()->getEntityProperties(entityID); if (props.getModelURL() == modelURL && @@ -3030,7 +2978,7 @@ void MyAvatar::setAnimGraphUrl(const QUrl& url) { emit animGraphUrlChanged(url); destroyAnimGraph(); - _skeletonModel->reset(); // Why is this necessary? Without this, we crash in the next render. + _skeletonModel->reset(); // Why is this necessary? Without this, we crash in the next render. _currentAnimGraphUrl.set(url); _skeletonModel->getRig().initAnimGraph(url); @@ -3063,18 +3011,16 @@ void MyAvatar::destroyAnimGraph() { } void MyAvatar::animGraphLoaded() { - _bodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. - updateSensorToWorldMatrix(); // Uses updated position/orientation and _bodySensorMatrix changes + _bodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + updateSensorToWorldMatrix(); // Uses updated position/orientation and _bodySensorMatrix changes _isAnimatingScale = true; _cauterizationNeedsUpdate = true; disconnect(&(_skeletonModel->getRig()), SIGNAL(onLoadComplete()), this, SLOT(animGraphLoaded())); } void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { - Avatar::postUpdate(deltaTime, scene); if (_enableDebugDrawDefaultPose || _enableDebugDrawAnimPose) { - auto animSkeleton = _skeletonModel->getRig().getAnimSkeleton(); // the rig is in the skeletonModel frame @@ -3082,7 +3028,8 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { if (_enableDebugDrawDefaultPose && animSkeleton) { glm::vec4 gray(0.2f, 0.2f, 0.2f, 0.2f); - AnimDebugDraw::getInstance().addAbsolutePoses("myAvatarDefaultPoses", animSkeleton, _skeletonModel->getRig().getAbsoluteDefaultPoses(), xform, gray); + AnimDebugDraw::getInstance().addAbsolutePoses("myAvatarDefaultPoses", animSkeleton, + _skeletonModel->getRig().getAbsoluteDefaultPoses(), xform, gray); } if (_enableDebugDrawAnimPose && animSkeleton) { @@ -3103,13 +3050,15 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { auto rightHandPose = getControllerPoseInWorldFrame(controller::Action::RIGHT_HAND); if (leftHandPose.isValid()) { - DebugDraw::getInstance().addMarker("leftHandController", leftHandPose.getRotation(), leftHandPose.getTranslation(), glm::vec4(1)); + DebugDraw::getInstance().addMarker("leftHandController", leftHandPose.getRotation(), leftHandPose.getTranslation(), + glm::vec4(1)); } else { DebugDraw::getInstance().removeMarker("leftHandController"); } if (rightHandPose.isValid()) { - DebugDraw::getInstance().addMarker("rightHandController", rightHandPose.getRotation(), rightHandPose.getTranslation(), glm::vec4(1)); + DebugDraw::getInstance().addMarker("rightHandController", rightHandPose.getRotation(), + rightHandPose.getTranslation(), glm::vec4(1)); } else { DebugDraw::getInstance().removeMarker("rightHandController"); } @@ -3126,14 +3075,9 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { AnimPose rigToWorldPose(glm::vec3(1.0f), getWorldOrientation() * Quaternions::Y_180, getWorldPosition()); const int NUM_DEBUG_COLORS = 8; const glm::vec4 DEBUG_COLORS[NUM_DEBUG_COLORS] = { - glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), - glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), - glm::vec4(0.0f, 1.0f, 0.0f, 1.0f), - glm::vec4(0.25f, 0.25f, 1.0f, 1.0f), - glm::vec4(1.0f, 1.0f, 0.0f, 1.0f), - glm::vec4(0.25f, 1.0f, 1.0f, 1.0f), - glm::vec4(1.0f, 0.25f, 1.0f, 1.0f), - glm::vec4(1.0f, 0.65f, 0.0f, 1.0f) // Orange you glad I added this color? + glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 1.0f), + glm::vec4(0.25f, 0.25f, 1.0f, 1.0f), glm::vec4(1.0f, 1.0f, 0.0f, 1.0f), glm::vec4(0.25f, 1.0f, 1.0f, 1.0f), + glm::vec4(1.0f, 0.25f, 1.0f, 1.0f), glm::vec4(1.0f, 0.65f, 0.0f, 1.0f) // Orange you glad I added this color? }; if (_skeletonModel && _skeletonModel->isLoaded()) { @@ -3144,7 +3088,7 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { AnimPose jointPose; rig.getAbsoluteJointPoseInRigFrame(i, jointPose); const AnimPose pose = rigToWorldPose * jointPose; - auto &multiSphere = _multiSphereShapes[i]; + auto& multiSphere = _multiSphereShapes[i]; auto debugLines = multiSphere.getDebugLines(); DebugDraw::getInstance().drawRays(debugLines, DEBUG_COLORS[i % NUM_DEBUG_COLORS], pose.trans(), pose.rot()); } @@ -3154,7 +3098,6 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { } void MyAvatar::preDisplaySide(const RenderArgs* renderArgs) { - // toggle using the cauterizedBones depending on where the camera is and the rendering pass type. const bool shouldDrawHead = shouldRenderHead(renderArgs); if (shouldDrawHead != _prevShouldDrawHead) { @@ -3199,7 +3142,7 @@ int MyAvatar::sendAvatarDataPacket(bool sendAll) { // Compute the next send window based on how much data we sent and what // data rate we're trying to max at. - milliseconds timeUntilNextSend { bytesSent / maxDataRateBytesPerMilliseconds }; + milliseconds timeUntilNextSend{ bytesSent / maxDataRateBytesPerMilliseconds }; _nextTraitsSendWindow += timeUntilNextSend; // Don't let the next send window lag behind if we're not sending a lot of data. @@ -3284,7 +3227,6 @@ void MyAvatar::setRotationThreshold(float angleRadians) { } void MyAvatar::updateOrientation(float deltaTime) { - // Smoothly rotate body with arrow keys float targetSpeed = getDriveKey(YAW) * _yawSpeed; if (targetSpeed != 0.0f) { @@ -3323,8 +3265,8 @@ void MyAvatar::updateOrientation(float deltaTime) { } // Use head/HMD roll to turn while flying, but not when standing still. - if (qApp->isHMDMode() && getCharacterController()->getState() == CharacterController::State::Hover && _hmdRollControlEnabled && hasDriveInput()) { - + if (qApp->isHMDMode() && getCharacterController()->getState() == CharacterController::State::Hover && + _hmdRollControlEnabled && hasDriveInput()) { // Turn with head roll. const float MIN_CONTROL_SPEED = 2.0f * getSensorToWorldScale(); // meters / sec const glm::vec3 characterForward = getWorldOrientation() * Vectors::UNIT_NEG_Z; @@ -3332,7 +3274,6 @@ void MyAvatar::updateOrientation(float deltaTime) { // only enable roll-turns if we are moving forward or backward at greater then MIN_CONTROL_SPEED if (fabsf(forwardSpeed) >= MIN_CONTROL_SPEED) { - float direction = forwardSpeed > 0.0f ? 1.0f : -1.0f; float rollAngle = glm::degrees(asinf(glm::dot(IDENTITY_UP, _hmdSensorOrientation * IDENTITY_RIGHT))); float rollSign = rollAngle < 0.0f ? -1.0f : 1.0f; @@ -3379,8 +3320,8 @@ void MyAvatar::updateOrientation(float deltaTime) { head->setBaseRoll(ROLL(euler)); } else { head->setBaseYaw(0.0f); - head->setBasePitch(getHead()->getBasePitch() + getDriveKey(PITCH) * _pitchSpeed * deltaTime - + getDriveKey(DELTA_PITCH) * _pitchSpeed / PITCH_SPEED_DEFAULT); + head->setBasePitch(getHead()->getBasePitch() + getDriveKey(PITCH) * _pitchSpeed * deltaTime + + getDriveKey(DELTA_PITCH) * _pitchSpeed / PITCH_SPEED_DEFAULT); head->setBaseRoll(0.0f); } } @@ -3390,20 +3331,15 @@ float MyAvatar::calculateGearedSpeed(const float driveKey) { float sign = (driveKey < 0.0f) ? -1.0f : 1.0f; if (absDriveKey > getDriveGear5()) { return sign * 1.0f; - } - else if (absDriveKey > getDriveGear4()) { + } else if (absDriveKey > getDriveGear4()) { return sign * 0.8f; - } - else if (absDriveKey > getDriveGear3()) { + } else if (absDriveKey > getDriveGear3()) { return sign * 0.6f; - } - else if (absDriveKey > getDriveGear2()) { + } else if (absDriveKey > getDriveGear2()) { return sign * 0.4f; - } - else if (absDriveKey > getDriveGear1()) { + } else if (absDriveKey > getDriveGear1()) { return sign * 0.2f; - } - else { + } else { return sign * 0.0f; } } @@ -3435,8 +3371,10 @@ glm::vec3 MyAvatar::scaleMotorSpeed(const glm::vec3 forward, const glm::vec3 rig case LocomotionControlsMode::CONTROLS_ANALOG: case LocomotionControlsMode::CONTROLS_ANALOG_PLUS: if (zSpeed || xSpeed) { - glm::vec3 scaledForward = getSensorToWorldScale() * calculateGearedSpeed(zSpeed) * _walkSpeedScalar * ((zSpeed >= stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * forward; - glm::vec3 scaledRight = getSensorToWorldScale() * calculateGearedSpeed(xSpeed) * _walkSpeedScalar * ((xSpeed > stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * right; + glm::vec3 scaledForward = getSensorToWorldScale() * calculateGearedSpeed(zSpeed) * _walkSpeedScalar * + ((zSpeed >= stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * forward; + glm::vec3 scaledRight = getSensorToWorldScale() * calculateGearedSpeed(xSpeed) * _walkSpeedScalar * + ((xSpeed > stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * right; direction = scaledForward + scaledRight; return direction; } else { @@ -3458,7 +3396,7 @@ glm::vec3 MyAvatar::scaleMotorSpeed(const glm::vec3 forward, const glm::vec3 rig } } -glm::vec3 MyAvatar::calculateScaledDirection(){ +glm::vec3 MyAvatar::calculateScaledDirection() { CharacterController::State state = _characterController.getState(); // compute action input @@ -3514,8 +3452,8 @@ glm::vec3 MyAvatar::calculateScaledDirection(){ void MyAvatar::updateActionMotor(float deltaTime) { bool thrustIsPushing = (glm::length2(_thrust) > EPSILON); - bool scriptedMotorIsPushing = (_motionBehaviors & AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED) - && _scriptedMotorTimescale < MAX_CHARACTER_MOTOR_TIMESCALE; + bool scriptedMotorIsPushing = + (_motionBehaviors & AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED) && _scriptedMotorTimescale < MAX_CHARACTER_MOTOR_TIMESCALE; _isBeingPushed = thrustIsPushing || scriptedMotorIsPushing; if (_isPushing || _isBeingPushed) { // we don't want the motor to brake if a script is pushing the avatar around @@ -3545,7 +3483,7 @@ void MyAvatar::updateActionMotor(float deltaTime) { float motorSpeed = glm::length(_actionMotorVelocity); float finalMaxMotorSpeed = sensorToWorldScale * DEFAULT_AVATAR_MAX_FLYING_SPEED * _walkSpeedScalar; - float speedGrowthTimescale = 2.0f; + float speedGrowthTimescale = 2.0f; float speedIncreaseFactor = 1.8f * _walkSpeedScalar; motorSpeed *= 1.0f + glm::clamp(deltaTime / speedGrowthTimescale, 0.0f, 1.0f) * speedIncreaseFactor; const float maxBoostSpeed = sensorToWorldScale * MAX_BOOST_SPEED; @@ -3585,7 +3523,7 @@ void MyAvatar::updatePosition(float deltaTime) { float sensorToWorldScale2 = sensorToWorldScale * sensorToWorldScale; vec3 velocity = getWorldVelocity(); float speed2 = glm::length2(velocity); - const float MOVING_SPEED_THRESHOLD_SQUARED = 0.0001f; // 0.01 m/s + const float MOVING_SPEED_THRESHOLD_SQUARED = 0.0001f; // 0.01 m/s _moving = speed2 > sensorToWorldScale2 * MOVING_SPEED_THRESHOLD_SQUARED; if (_moving) { // scan for walkability @@ -3610,12 +3548,17 @@ void MyAvatar::updateViewBoom() { } } -void MyAvatar::updateCollisionSound(const glm::vec3 &penetration, float deltaTime, float frequency) { +void MyAvatar::updateCollisionSound(const glm::vec3& penetration, float deltaTime, float frequency) { // COLLISION SOUND API in Audio has been removed } -bool findAvatarAvatarPenetration(const glm::vec3 positionA, float radiusA, float heightA, - const glm::vec3 positionB, float radiusB, float heightB, glm::vec3& penetration) { +bool findAvatarAvatarPenetration(const glm::vec3 positionA, + float radiusA, + float heightA, + const glm::vec3 positionB, + float radiusB, + float heightB, + glm::vec3& penetration) { glm::vec3 positionBA = positionB - positionA; float xzDistance = sqrt(positionBA.x * positionBA.x + positionBA.z * positionBA.z); if (xzDistance < (radiusA + radiusB)) { @@ -3677,9 +3620,7 @@ void MyAvatar::setSessionUUID(const QUuid& sessionUUID) { EntityTreePointer entityTree = treeRenderer ? treeRenderer->getTree() : nullptr; if (entityTree) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { - avatarEntityIDs = _packedAvatarEntityData.keys(); - }); + _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); bool sendPackets = !DependencyManager::get()->getSessionUUID().isNull(); EntityEditPacketSender* packetSender = qApp->getEntityEditPacketSender(); entityTree->withWriteLock([&] { @@ -3823,16 +3764,18 @@ void MyAvatar::goToLocation(const QVariant& propertiesVar) { } void MyAvatar::goToFeetLocation(const glm::vec3& newPosition, - bool hasOrientation, const glm::quat& newOrientation, + bool hasOrientation, + const glm::quat& newOrientation, bool shouldFaceLocation) { _goToFeetAjustment = true; goToLocation(newPosition, hasOrientation, newOrientation, shouldFaceLocation); } void MyAvatar::goToLocation(const glm::vec3& newPosition, - bool hasOrientation, const glm::quat& newOrientation, - bool shouldFaceLocation, bool withSafeLanding) { - + bool hasOrientation, + const glm::quat& newOrientation, + bool shouldFaceLocation, + bool withSafeLanding) { // Most cases of going to a place or user go through this now. Some possible improvements to think about in the future: // - It would be nice if this used the same teleport steps and smoothing as in the teleport.js script, as long as it // still worked if the target is in the air. @@ -3846,16 +3789,16 @@ void MyAvatar::goToLocation(const glm::vec3& newPosition, // compute the position (e.g., so that if I'm on stage, going to me would compute an available seat in the audience rather than // being in my face on-stage). Note that this could work for going to an entity as well as to a person. - qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - moving to " << newPosition.x << ", " - << newPosition.y << ", " << newPosition.z; + qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - moving to " << newPosition.x << ", " << newPosition.y << ", " + << newPosition.z; _goToPending = true; _goToPosition = newPosition; _goToSafe = withSafeLanding; _goToOrientation = getWorldOrientation(); if (hasOrientation) { - qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - new orientation is " - << newOrientation.x << ", " << newOrientation.y << ", " << newOrientation.z << ", " << newOrientation.w; + qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - new orientation is " << newOrientation.x << ", " + << newOrientation.y << ", " << newOrientation.z << ", " << newOrientation.w; // orient the user to face the target glm::quat quatOrientation = cancelOutRollAndPitch(newOrientation); @@ -3874,7 +3817,7 @@ void MyAvatar::goToLocation(const glm::vec3& newPosition, emit transformChanged(); } -void MyAvatar::goToLocationAndEnableCollisions(const glm::vec3& position) { // See use case in safeLanding. +void MyAvatar::goToLocationAndEnableCollisions(const glm::vec3& position) { // See use case in safeLanding. goToLocation(position); QMetaObject::invokeMethod(this, "setCollisionsEnabled", Qt::QueuedConnection, Q_ARG(bool, true)); } @@ -3900,29 +3843,29 @@ bool MyAvatar::safeLanding(const glm::vec3& position) { } if (!getCollisionsEnabled()) { goToLocation(better); // recurses on next update - } else { // If you try to go while stuck, physics will keep you stuck. + } else { // If you try to go while stuck, physics will keep you stuck. setCollisionsEnabled(false); // Don't goToLocation just yet. Yield so that physics can act on the above. - QMetaObject::invokeMethod(this, "goToLocationAndEnableCollisions", Qt::QueuedConnection, // The equivalent of javascript nextTick - Q_ARG(glm::vec3, better)); - } - return true; + QMetaObject::invokeMethod(this, "goToLocationAndEnableCollisions", + Qt::QueuedConnection, // The equivalent of javascript nextTick + Q_ARG(glm::vec3, better)); + } + return true; } // If position is not reliably safe from being stuck by physics, answer true and place a candidate better position in betterPositionOut. bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& betterPositionOut) { - // We begin with utilities and tests. The Algorithm in four parts is below. // NOTE: we use estimated avatar height here instead of the bullet capsule halfHeight, because // the domain avatar height limiting might not have taken effect yet on the actual bullet shape. auto halfHeight = 0.5f * getHeight(); if (halfHeight == 0) { - return false; // zero height avatar + return false; // zero height avatar } auto entityTree = DependencyManager::get()->getTree(); if (!entityTree) { - return false; // no entity tree + return false; // no entity tree } // More utilities. const auto capsuleCenter = positionIn; @@ -3934,21 +3877,26 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette betterPositionOut = upperIntersection + (up * halfHeight); return true; }; - auto findIntersection = [&](const glm::vec3& startPointIn, const glm::vec3& directionIn, glm::vec3& intersectionOut, EntityItemID& entityIdOut, glm::vec3& normalOut) { + auto findIntersection = [&](const glm::vec3& startPointIn, const glm::vec3& directionIn, glm::vec3& intersectionOut, + EntityItemID& entityIdOut, glm::vec3& normalOut) { OctreeElementPointer element; float distance; BoxFace face; - const auto lockType = Octree::Lock; // Should we refactor to take a lock just once? + const auto lockType = Octree::Lock; // Should we refactor to take a lock just once? bool* accurateResult = NULL; // This isn't quite what we really want here. findRayIntersection always works on mesh, skipping entirely based on collidable. // What we really want is to use the collision hull! // See https://highfidelity.fogbugz.com/f/cases/5003/findRayIntersection-has-option-to-use-collidableOnly-but-doesn-t-actually-use-colliders QVariantMap extraInfo; - EntityItemID entityID = entityTree->evalRayIntersection(startPointIn, directionIn, include, ignore, - PickFilter(PickFilter::getBitMask(PickFilter::FlagBit::COLLIDABLE) | PickFilter::getBitMask(PickFilter::FlagBit::PRECISE) - | PickFilter::getBitMask(PickFilter::FlagBit::DOMAIN_ENTITIES) | PickFilter::getBitMask(PickFilter::FlagBit::AVATAR_ENTITIES)), // exclude Local entities - element, distance, face, normalOut, extraInfo, lockType, accurateResult); + EntityItemID entityID = + entityTree->evalRayIntersection(startPointIn, directionIn, include, ignore, + PickFilter(PickFilter::getBitMask(PickFilter::FlagBit::COLLIDABLE) | + PickFilter::getBitMask(PickFilter::FlagBit::PRECISE) | + PickFilter::getBitMask(PickFilter::FlagBit::DOMAIN_ENTITIES) | + PickFilter::getBitMask( + PickFilter::FlagBit::AVATAR_ENTITIES)), // exclude Local entities + element, distance, face, normalOut, extraInfo, lockType, accurateResult); if (entityID.isNull()) { return false; } @@ -3963,12 +3911,12 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette // We currently believe that physics will reliably push us out if our feet are embedded, // as long as our capsule center is out and there's room above us. Here we have those // conditions, so no need to check our feet below. - return false; // nothing above + return false; // nothing above } if (!findIntersection(capsuleCenter, down, lowerIntersection, lowerId, lowerNormal)) { // Our head may be embedded, but our center is out and there's room below. See corresponding comment above. - return false; // nothing below + return false; // nothing below } // See if we have room between entities above and below, but that we are not contained. @@ -3976,7 +3924,8 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette // I.e., we are in a clearing between two objects. if (isDown(upperNormal) && isUp(lowerNormal)) { auto spaceBetween = glm::distance(upperIntersection, lowerIntersection); - const float halfHeightFactor = 2.25f; // Until case 5003 is fixed (and maybe after?), we need a fudge factor. Also account for content modelers not being precise. + const float halfHeightFactor = + 2.25f; // Until case 5003 is fixed (and maybe after?), we need a fudge factor. Also account for content modelers not being precise. if (spaceBetween > (halfHeightFactor * halfHeight)) { // There is room for us to fit in that clearing. If there wasn't, physics would oscilate us between the objects above and below. // We're now going to iterate upwards through successive upperIntersections, testing to see if we're contained within the top surface of some entity. @@ -3988,7 +3937,7 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette ignore.push_back(upperId); if (!findIntersection(upperIntersection, up, upperIntersection, upperId, upperNormal)) { // We're not inside an entity, and from the nested tests, we have room between what is above and below. So position is good! - return false; // enough room + return false; // enough room } if (isUp(upperNormal)) { // This new intersection is the top surface of an entity that we have not yet seen, which means we're contained within it. @@ -4003,19 +3952,18 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette } } - include.push_back(upperId); // We're now looking for the intersection from above onto this entity. + include.push_back(upperId); // We're now looking for the intersection from above onto this entity. const float big = (float)TREE_SCALE; const auto skyHigh = up * big; auto fromAbove = capsuleCenter + skyHigh; if (!findIntersection(fromAbove, down, upperIntersection, upperId, upperNormal)) { - return false; // Unable to find a landing + return false; // Unable to find a landing } // Our arbitrary rule is to always go up. There's no need to look down or sideways for a "closer" safe candidate. return mustMove(); } void MyAvatar::updateMotionBehaviorFromMenu() { - if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "updateMotionBehaviorFromMenu"); return; @@ -4099,7 +4047,7 @@ int MyAvatar::getMovementReference() { return _movementReference; } -void MyAvatar::setControlSchemeIndex(int index){ +void MyAvatar::setControlSchemeIndex(int index) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setControlSchemeIndex", Q_ARG(int, index)); return; @@ -4117,7 +4065,8 @@ void MyAvatar::setDriveGear1(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear1", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) + return; _driveGear1 = (shiftPoint < _driveGear2) ? shiftPoint : _driveGear1; } @@ -4138,7 +4087,8 @@ void MyAvatar::setDriveGear2(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear2", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) + return; _driveGear2 = (shiftPoint < _driveGear3 && shiftPoint >= _driveGear1) ? shiftPoint : _driveGear2; } @@ -4159,7 +4109,8 @@ void MyAvatar::setDriveGear3(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear3", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) + return; _driveGear3 = (shiftPoint < _driveGear4 && shiftPoint >= _driveGear2) ? shiftPoint : _driveGear3; } @@ -4180,7 +4131,8 @@ void MyAvatar::setDriveGear4(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear4", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) + return; _driveGear4 = (shiftPoint < _driveGear5 && shiftPoint >= _driveGear3) ? shiftPoint : _driveGear4; } @@ -4201,7 +4153,8 @@ void MyAvatar::setDriveGear5(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear5", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) + return; _driveGear5 = (shiftPoint > _driveGear4) ? shiftPoint : _driveGear5; } @@ -4227,7 +4180,6 @@ float MyAvatar::getAvatarScale() { } void MyAvatar::setAvatarScale(float val) { - if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setAvatarScale", Q_ARG(float, val)); return; @@ -4237,7 +4189,6 @@ void MyAvatar::setAvatarScale(float val) { } void MyAvatar::setCollisionsEnabled(bool enabled) { - if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setCollisionsEnabled", Q_ARG(bool, enabled)); return; @@ -4253,7 +4204,6 @@ bool MyAvatar::getCollisionsEnabled() { } void MyAvatar::setOtherAvatarsCollisionsEnabled(bool enabled) { - if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setOtherAvatarsCollisionsEnabled", Q_ARG(bool, enabled)); return; @@ -4409,7 +4359,7 @@ glm::mat4 MyAvatar::deriveBodyFromHMDSensor() const { // AJT: TODO: can remove this Y_180, if we remove the higher level one. glm::vec3 headToNeck = headOrientation * Quaternions::Y_180 * (localNeck - localHead); - glm::vec3 neckToRoot = headOrientationYawOnly * Quaternions::Y_180 * -localNeck; + glm::vec3 neckToRoot = headOrientationYawOnly * Quaternions::Y_180 * -localNeck; float invSensorToWorldScale = getUserEyeHeight() / getEyeHeight(); glm::vec3 bodyPos = headPosition + invSensorToWorldScale * (headToNeck + neckToRoot); @@ -4445,7 +4395,8 @@ glm::mat4 MyAvatar::getSpine2RotationRigSpace() const { spine2UpRigSpace = glm::vec3(0.0f, 1.0f, 0.0f); } generateBasisVectors(spine2UpRigSpace, spine2FwdRigSpace, u, v, w); - glm::mat4 spine2RigSpace(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), glm::vec4(glm::vec3(0.0f, 0.0f, 0.0f), 1.0f)); + glm::mat4 spine2RigSpace(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), + glm::vec4(glm::vec3(0.0f, 0.0f, 0.0f), 1.0f)); return spine2RigSpace; } @@ -4502,7 +4453,7 @@ glm::vec3 MyAvatar::computeCounterBalance() { QString name; float weight; glm::vec3 position; - JointMass() {}; + JointMass(){}; JointMass(QString n, float w, glm::vec3 p) { name = n; weight = w; @@ -4523,12 +4474,14 @@ glm::vec3 MyAvatar::computeCounterBalance() { tposeHead = getAbsoluteDefaultJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgHeadMass.name)); } if (_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name) != -1) { - cgLeftHandMass.position = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name)); + cgLeftHandMass.position = + getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name)); } else { cgLeftHandMass.position = DEFAULT_AVATAR_LEFTHAND_POS; } if (_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name) != -1) { - cgRightHandMass.position = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name)); + cgRightHandMass.position = + getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name)); } else { cgRightHandMass.position = DEFAULT_AVATAR_RIGHTHAND_POS; } @@ -4540,7 +4493,8 @@ glm::vec3 MyAvatar::computeCounterBalance() { } // find the current center of gravity position based on head and hand moments - glm::vec3 sumOfMoments = (cgHeadMass.weight * cgHeadMass.position) + (cgLeftHandMass.weight * cgLeftHandMass.position) + (cgRightHandMass.weight * cgRightHandMass.position); + glm::vec3 sumOfMoments = (cgHeadMass.weight * cgHeadMass.position) + (cgLeftHandMass.weight * cgLeftHandMass.position) + + (cgRightHandMass.weight * cgRightHandMass.position); float totalMass = cgHeadMass.weight + cgLeftHandMass.weight + cgRightHandMass.weight; glm::vec3 currentCg = (1.0f / totalMass) * sumOfMoments; @@ -4580,7 +4534,6 @@ glm::vec3 MyAvatar::computeCounterBalance() { // headOrientation, headPosition and hipsPosition are in avatar space // returns the matrix of the hips in Avatar space static glm::mat4 computeNewHipsMatrix(glm::quat headOrientation, glm::vec3 headPosition, glm::vec3 hipsPosition) { - glm::quat bodyOrientation = computeBodyFacingFromHead(headOrientation, Vectors::UNIT_Y); const float MIX_RATIO = 0.3f; @@ -4590,10 +4543,7 @@ static glm::mat4 computeNewHipsMatrix(glm::quat headOrientation, glm::vec3 headP glm::vec3 spineVec = headPosition - hipsPosition; glm::vec3 u, v, w; generateBasisVectors(glm::normalize(spineVec), hipsFacing, u, v, w); - return glm::mat4(glm::vec4(w, 0.0f), - glm::vec4(u, 0.0f), - glm::vec4(v, 0.0f), - glm::vec4(hipsPosition, 1.0f)); + return glm::mat4(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), glm::vec4(hipsPosition, 1.0f)); } static void drawBaseOfSupport(float baseOfSupportScale, float footLocal, glm::mat4 avatarToWorld) { @@ -4634,7 +4584,8 @@ glm::mat4 MyAvatar::deriveBodyUsingCgModel() { if (_enableDebugDrawBaseOfSupport) { float scaleBaseOfSupport = getUserEyeHeight() / DEFAULT_AVATAR_EYE_HEIGHT; - glm::vec3 rightFootPositionLocal = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint("RightFoot")); + glm::vec3 rightFootPositionLocal = + getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint("RightFoot")); drawBaseOfSupport(scaleBaseOfSupport, rightFootPositionLocal.y, avatarToWorldMat); } @@ -4642,7 +4593,8 @@ glm::mat4 MyAvatar::deriveBodyUsingCgModel() { glm::vec3 cgHipsPosition = computeCounterBalance(); // find the new hips rotation using the new head-hips axis as the up axis - glm::mat4 avatarHipsMat = computeNewHipsMatrix(glmExtractRotation(avatarHeadMat), extractTranslation(avatarHeadMat), cgHipsPosition); + glm::mat4 avatarHipsMat = + computeNewHipsMatrix(glmExtractRotation(avatarHeadMat), extractTranslation(avatarHeadMat), cgHipsPosition); // convert hips from avatar to sensor space // The Y_180 is to convert from z forward to -z forward. @@ -4666,7 +4618,7 @@ static bool withinBaseOfSupport(const controller::Pose& head) { bool withinFrontBase = isInsideLine(userScale * frontLeft, userScale * frontRight, head.getTranslation()); bool withinBackBase = isInsideLine(userScale * backRight, userScale * backLeft, head.getTranslation()); bool withinLateralBase = (isInsideLine(userScale * frontRight, userScale * backRight, head.getTranslation()) && - isInsideLine(userScale * backLeft, userScale * frontLeft, head.getTranslation())); + isInsideLine(userScale * backLeft, userScale * frontLeft, head.getTranslation())); isWithinSupport = (withinFrontBase && withinBackBase && withinLateralBase); } return isWithinSupport; @@ -4700,7 +4652,8 @@ float MyAvatar::computeStandingHeightMode(const controller::Pose& head) { float modeInMeters = getCurrentStandingHeight(); if (head.isValid()) { std::map freq; - for(auto recentModeReadingsIterator = _recentModeReadings.begin(); recentModeReadingsIterator != _recentModeReadings.end(); ++recentModeReadingsIterator) { + for (auto recentModeReadingsIterator = _recentModeReadings.begin(); + recentModeReadingsIterator != _recentModeReadings.end(); ++recentModeReadingsIterator) { freq[*recentModeReadingsIterator] += 1; if (freq[*recentModeReadingsIterator] > greatestFrequency) { greatestFrequency = freq[*recentModeReadingsIterator]; @@ -4713,21 +4666,23 @@ float MyAvatar::computeStandingHeightMode(const controller::Pose& head) { // if not greater check for a reset if (getResetMode() && getControllerPoseInAvatarFrame(controller::Action::HEAD).isValid()) { setResetMode(false); - float resetModeInCentimeters = glm::floor((head.getTranslation().y - MODE_CORRECTION_FACTOR)*CENTIMETERS_PER_METER); + float resetModeInCentimeters = + glm::floor((head.getTranslation().y - MODE_CORRECTION_FACTOR) * CENTIMETERS_PER_METER); modeInMeters = (resetModeInCentimeters / CENTIMETERS_PER_METER); _recentModeReadings.clear(); } else { // if not greater and no reset, keep the mode as it is modeInMeters = getCurrentStandingHeight(); - } } } return modeInMeters; } -static bool handDirectionMatchesHeadDirection(const controller::Pose& leftHand, const controller::Pose& rightHand, const controller::Pose& head) { +static bool handDirectionMatchesHeadDirection(const controller::Pose& leftHand, + const controller::Pose& rightHand, + const controller::Pose& head) { const float VELOCITY_EPSILON = 0.02f; bool leftHandDirectionMatchesHead = true; bool rightHandDirectionMatchesHead = true; @@ -4765,7 +4720,7 @@ static bool handAngularVelocityBelowThreshold(const controller::Pose& leftHand, rightHandXZAngularVelocity = glm::length(xzRightHandAngularVelocity); } return ((leftHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD) && - (rightHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD)); + (rightHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD)); } static bool headVelocityGreaterThanThreshold(const controller::Pose& head) { @@ -4788,7 +4743,8 @@ static bool isHeadLevel(const controller::Pose& head, const glm::quat& averageHe glm::vec3 currentHeadEulers = glm::degrees(safeEulerAngles(head.getRotation())); diffFromAverageEulers = averageHeadEulers - currentHeadEulers; } - return ((fabs(diffFromAverageEulers.x) < DEFAULT_HEAD_PITCH_STEPPING_TOLERANCE) && (fabs(diffFromAverageEulers.z) < DEFAULT_HEAD_ROLL_STEPPING_TOLERANCE)); + return ((fabs(diffFromAverageEulers.x) < DEFAULT_HEAD_PITCH_STEPPING_TOLERANCE) && + (fabs(diffFromAverageEulers.z) < DEFAULT_HEAD_ROLL_STEPPING_TOLERANCE)); } float MyAvatar::getUserHeight() const { @@ -4838,7 +4794,6 @@ float MyAvatar::getWalkSpeed() const { } else { return _defaultWalkSpeed.get(); } - } float MyAvatar::getWalkBackwardSpeed() const { @@ -4855,7 +4810,6 @@ float MyAvatar::getWalkBackwardSpeed() const { } else { return _defaultWalkBackwardSpeed.get(); } - } bool MyAvatar::isReadyForPhysics() const { @@ -4865,8 +4819,7 @@ bool MyAvatar::isReadyForPhysics() const { void MyAvatar::setSprintMode(bool sprint) { if (qApp->isHMDMode()) { _walkSpeedScalar = sprint ? AVATAR_DESKTOP_SPRINT_SPEED_SCALAR : AVATAR_WALK_SPEED_SCALAR; - } - else { + } else { _walkSpeedScalar = sprint ? AVATAR_HMD_SPRINT_SPEED_SCALAR : AVATAR_WALK_SPEED_SCALAR; } } @@ -4890,7 +4843,6 @@ void MyAvatar::setIsInSittingState(bool isSitting) { } void MyAvatar::setUserRecenterModel(MyAvatar::SitStandModelType modelName) { - _userRecenterModel.set(modelName); switch (modelName) { @@ -4947,35 +4899,54 @@ void MyAvatar::setWalkSpeed(float value) { } void MyAvatar::setWalkBackwardSpeed(float value) { + bool changed = true; + float prevVal; switch (_controlSchemeIndex) { case LocomotionControlsMode::CONTROLS_DEFAULT: + prevVal = _defaultWalkBackwardSpeed.get(); _defaultWalkBackwardSpeed.set(value); break; case LocomotionControlsMode::CONTROLS_ANALOG: + prevVal = _analogWalkBackwardSpeed.get(); _analogWalkBackwardSpeed.set(value); break; case LocomotionControlsMode::CONTROLS_ANALOG_PLUS: + prevVal = _analogPlusWalkBackwardSpeed.get(); _analogPlusWalkBackwardSpeed.set(value); break; default: + changed = false; break; } + + if (changed && prevVal != value) { + emit walkBackwardSpeedChanged(value); + } } void MyAvatar::setSprintSpeed(float value) { + bool changed = true; + float prevVal; switch (_controlSchemeIndex) { case LocomotionControlsMode::CONTROLS_DEFAULT: + prevVal = _defaultSprintSpeed.get(); _defaultSprintSpeed.set(value); break; case LocomotionControlsMode::CONTROLS_ANALOG: + prevVal = _analogSprintSpeed.get(); _analogSprintSpeed.set(value); break; case LocomotionControlsMode::CONTROLS_ANALOG_PLUS: + prevVal = _analogPlusSprintSpeed.get(); _analogPlusSprintSpeed.set(value); break; default: break; } + + if (changed && prevVal != value) { + emit walkBackwardSpeedChanged(value); + } } float MyAvatar::getSprintSpeed() const { @@ -5014,7 +4985,7 @@ float MyAvatar::getAnalogSprintSpeed() const { void MyAvatar::setAnalogPlusWalkSpeed(float value) { _analogPlusWalkSpeed.set(value); - analogPlusWalkSpeedChanged(value); + emit analogPlusWalkSpeedChanged(value); // Sprint speed for Analog Plus should be double walk speed. _analogPlusSprintSpeed.set(value * 2.0f); } @@ -5025,6 +4996,7 @@ float MyAvatar::getAnalogPlusWalkSpeed() const { void MyAvatar::setAnalogPlusSprintSpeed(float value) { _analogPlusSprintSpeed.set(value); + emit analogPlusSprintSpeedChanged(value); } float MyAvatar::getAnalogPlusSprintSpeed() const { @@ -5112,7 +5084,6 @@ void driveKeysFromScriptValue(const QScriptValue& object, MyAvatar::DriveKeys& d driveKeys = static_cast(object.toUInt16()); } - void MyAvatar::lateUpdatePalms() { Avatar::updatePalms(); } @@ -5170,13 +5141,17 @@ void MyAvatar::FollowHelper::decrementTimeRemaining(float dt) { } } -bool MyAvatar::FollowHelper::shouldActivateRotation(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateRotation(const MyAvatar& myAvatar, + const glm::mat4& desiredBodyMatrix, + const glm::mat4& currentBodyMatrix) const { const float FOLLOW_ROTATION_THRESHOLD = cosf(myAvatar.getRotationThreshold()); glm::vec2 bodyFacing = getFacingDir2D(currentBodyMatrix); return glm::dot(-myAvatar.getHeadControllerFacingMovingAverage(), bodyFacing) < FOLLOW_ROTATION_THRESHOLD; } -bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, + const glm::mat4& desiredBodyMatrix, + const glm::mat4& currentBodyMatrix) const { // -z axis of currentBodyMatrix in world space. glm::vec3 forward = glm::normalize(glm::vec3(-currentBodyMatrix[0][2], -currentBodyMatrix[1][2], -currentBodyMatrix[2][2])); // x axis of currentBodyMatrix in world space. @@ -5207,7 +5182,6 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, } bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) const { - // get the current readings controller::Pose currentHeadPose = myAvatar.getControllerPoseInAvatarFrame(controller::Action::HEAD); controller::Pose currentLeftHandPose = myAvatar.getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND); @@ -5220,8 +5194,7 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons if (myAvatar.getIsInWalkingState()) { stepDetected = true; } else { - if (!withinBaseOfSupport(currentHeadPose) && - headAngularVelocityBelowThreshold(currentHeadPose) && + if (!withinBaseOfSupport(currentHeadPose) && headAngularVelocityBelowThreshold(currentHeadPose) && isWithinThresholdHeightMode(currentHeadSensorPose, myAvatar.getCurrentStandingHeight(), myScale) && handDirectionMatchesHeadDirection(currentLeftHandPose, currentRightHandPose, currentHeadPose) && handAngularVelocityBelowThreshold(currentLeftHandPose, currentRightHandPose) && @@ -5233,13 +5206,15 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons myAvatar.setIsInWalkingState(true); } } else { - glm::vec3 defaultHipsPosition = myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Hips")); - glm::vec3 defaultHeadPosition = myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Head")); + glm::vec3 defaultHipsPosition = + myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Hips")); + glm::vec3 defaultHeadPosition = + myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Head")); glm::vec3 currentHeadPosition = currentHeadPose.getTranslation(); float anatomicalHeadToHipsDistance = glm::length(defaultHeadPosition - defaultHipsPosition); - if (!isActive(Horizontal) && - (!isActive(Vertical)) && - (glm::length(currentHeadPosition - defaultHipsPosition) > (anatomicalHeadToHipsDistance + (DEFAULT_AVATAR_SPINE_STRETCH_LIMIT * anatomicalHeadToHipsDistance)))) { + if (!isActive(Horizontal) && (!isActive(Vertical)) && + (glm::length(currentHeadPosition - defaultHipsPosition) > + (anatomicalHeadToHipsDistance + (DEFAULT_AVATAR_SPINE_STRETCH_LIMIT * anatomicalHeadToHipsDistance)))) { myAvatar.setResetMode(true); stepDetected = true; if (glm::length(currentHeadPose.velocity) > DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { @@ -5251,7 +5226,9 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons return stepDetected; } -bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, + const glm::mat4& desiredBodyMatrix, + const glm::mat4& currentBodyMatrix) const { const float CYLINDER_TOP = 2.0f; const float CYLINDER_BOTTOM = -1.5f; const float SITTING_BOTTOM = -0.02f; @@ -5282,11 +5259,11 @@ bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, co return returnValue; } -void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, - const glm::mat4& currentBodyMatrix, bool hasDriveInput) { - - if (myAvatar.getHMDLeanRecenterEnabled() && - qApp->getCamera().getMode() != CAMERA_MODE_MIRROR) { +void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, + const glm::mat4& desiredBodyMatrix, + const glm::mat4& currentBodyMatrix, + bool hasDriveInput) { + if (myAvatar.getHMDLeanRecenterEnabled() && qApp->getCamera().getMode() != CAMERA_MODE_MIRROR) { if (!isActive(Rotation) && (shouldActivateRotation(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { activate(Rotation); myAvatar.setHeadControllerFacingMovingAverage(myAvatar.getHeadControllerFacing()); @@ -5301,7 +5278,8 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat } } else { // center of gravity model is not enabled - if (!isActive(Horizontal) && (shouldActivateHorizontal(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { + if (!isActive(Horizontal) && + (shouldActivateHorizontal(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { activate(Horizontal); if (myAvatar.getEnableStepResetRotation() && !myAvatar.getIsInSittingState()) { activate(Rotation); @@ -5338,7 +5316,7 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat glm::quat currentHipsLocal = myAvatar.getAbsoluteJointRotationInObjectFrame(myAvatar.getJointIndex("Hips")); const glm::quat hipsinWorldSpace = followWorldPose.rot() * (Quaternions::Y_180 * (currentHipsLocal)); - const glm::vec3 avatarUpWorld = glm::normalize(followWorldPose.rot()*(Vectors::UP)); + const glm::vec3 avatarUpWorld = glm::normalize(followWorldPose.rot() * (Vectors::UP)); glm::quat resultingSwingInWorld; glm::quat resultingTwistInWorld; swingTwistDecomposition(hipsinWorldSpace, avatarUpWorld, resultingSwingInWorld, resultingTwistInWorld); @@ -5347,8 +5325,8 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat followWorldPose.scale() = glm::vec3(1.0f); if (isActive(Rotation)) { - //use the hmd reading for the hips follow - followWorldPose.rot() = glmExtractRotation(desiredWorldMatrix); + //use the hmd reading for the hips follow + followWorldPose.rot() = glmExtractRotation(desiredWorldMatrix); } if (isActive(Horizontal)) { glm::vec3 desiredTranslation = extractTranslation(desiredWorldMatrix); @@ -5376,7 +5354,8 @@ glm::mat4 MyAvatar::FollowHelper::postPhysicsUpdate(MyAvatar& myAvatar, const gl glm::mat4 worldToSensorMatrix = glm::inverse(sensorToWorldMatrix); glm::vec3 sensorLinearDisplacement = transformVectorFast(worldToSensorMatrix, worldLinearDisplacement); - glm::quat sensorAngularDisplacement = glmExtractRotation(worldToSensorMatrix) * worldAngularDisplacement * glmExtractRotation(sensorToWorldMatrix); + glm::quat sensorAngularDisplacement = + glmExtractRotation(worldToSensorMatrix) * worldAngularDisplacement * glmExtractRotation(sensorToWorldMatrix); glm::mat4 newBodyMat = createMatFromQuatAndPos(sensorAngularDisplacement * glmExtractRotation(currentBodyMatrix), sensorLinearDisplacement + extractTranslation(currentBodyMatrix)); @@ -5444,7 +5423,8 @@ bool MyAvatar::didTeleport() { } bool MyAvatar::hasDriveInput() const { - return fabsf(getDriveKey(TRANSLATE_X)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Y)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Z)) > 0.0f; + return fabsf(getDriveKey(TRANSLATE_X)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Y)) > 0.0f || + fabsf(getDriveKey(TRANSLATE_Z)) > 0.0f; } void MyAvatar::setAway(bool value) { @@ -5460,7 +5440,6 @@ void MyAvatar::setAway(bool value) { // Specificly, if we are rendering using a third person camera. We would like to render the hand controllers in front of the camera, // not in front of the avatar. glm::mat4 MyAvatar::computeCameraRelativeHandControllerMatrix(const glm::mat4& controllerSensorMatrix) const { - // Fetch the current camera transform. glm::mat4 cameraWorldMatrix = qApp->getCamera().getTransform(); if (qApp->getCamera().getMode() == CAMERA_MODE_MIRROR) { @@ -5487,7 +5466,7 @@ glm::mat4 MyAvatar::computeCameraRelativeHandControllerMatrix(const glm::mat4& c glm::quat MyAvatar::getAbsoluteJointRotationInObjectFrame(int index) const { if (index < 0) { - index += numeric_limits::max() + 1; // 65536 + index += numeric_limits::max() + 1; // 65536 } switch (index) { @@ -5516,15 +5495,13 @@ glm::quat MyAvatar::getAbsoluteJointRotationInObjectFrame(int index) const { glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix(); return glmExtractRotation(invAvatarMat * qApp->getCamera().getTransform()); } - default: { - return Avatar::getAbsoluteJointRotationInObjectFrame(index); - } + default: { return Avatar::getAbsoluteJointRotationInObjectFrame(index); } } } glm::vec3 MyAvatar::getAbsoluteJointTranslationInObjectFrame(int index) const { if (index < 0) { - index += numeric_limits::max() + 1; // 65536 + index += numeric_limits::max() + 1; // 65536 } switch (index) { @@ -5553,9 +5530,7 @@ glm::vec3 MyAvatar::getAbsoluteJointTranslationInObjectFrame(int index) const { glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix(); return extractTranslation(invAvatarMat * qApp->getCamera().getTransform()); } - default: { - return Avatar::getAbsoluteJointTranslationInObjectFrame(index); - } + default: { return Avatar::getAbsoluteJointTranslationInObjectFrame(index); } } } @@ -5564,12 +5539,15 @@ glm::mat4 MyAvatar::getCenterEyeCalibrationMat() const { int rightEyeIndex = _skeletonModel->getRig().indexOfJoint("RightEye"); int leftEyeIndex = _skeletonModel->getRig().indexOfJoint("LeftEye"); if (rightEyeIndex >= 0 && leftEyeIndex >= 0) { - auto centerEyePos = (getAbsoluteDefaultJointTranslationInObjectFrame(rightEyeIndex) + getAbsoluteDefaultJointTranslationInObjectFrame(leftEyeIndex)) * 0.5f; + auto centerEyePos = (getAbsoluteDefaultJointTranslationInObjectFrame(rightEyeIndex) + + getAbsoluteDefaultJointTranslationInObjectFrame(leftEyeIndex)) * + 0.5f; auto centerEyeRot = Quaternions::Y_180; return createMatFromQuatAndPos(centerEyeRot, centerEyePos / getSensorToWorldScale()); } else { glm::mat4 headMat = getHeadCalibrationMat(); - return createMatFromQuatAndPos(DEFAULT_AVATAR_MIDDLE_EYE_ROT, extractTranslation(headMat) + DEFAULT_AVATAR_HEAD_TO_MIDDLE_EYE_OFFSET); + return createMatFromQuatAndPos(DEFAULT_AVATAR_MIDDLE_EYE_ROT, + extractTranslation(headMat) + DEFAULT_AVATAR_HEAD_TO_MIDDLE_EYE_OFFSET); } } @@ -5738,7 +5716,6 @@ void MyAvatar::updateHoldActions(const AnimPose& prePhysicsPose, const AnimPose& if (entityTree) { // lateAvatarUpdate will modify entity position & orientation, so we need an entity write lock entityTree->withWriteLock([&] { - // to prevent actions from adding or removing themselves from the _holdActions vector // while we are iterating, we need to enter a critical section. std::lock_guard guard(_holdActionsMutex); @@ -5774,26 +5751,24 @@ SpatialParentTree* MyAvatar::getParentTree() const { return entityTree.get(); } -const QUuid MyAvatar::grab(const QUuid& targetID, int parentJointIndex, - glm::vec3 positionalOffset, glm::quat rotationalOffset) { +const QUuid MyAvatar::grab(const QUuid& targetID, + int parentJointIndex, + glm::vec3 positionalOffset, + glm::quat rotationalOffset) { auto grabID = QUuid::createUuid(); // create a temporary grab object to get grabData QString hand = "none"; - if (parentJointIndex == CONTROLLER_RIGHTHAND_INDEX || - parentJointIndex == CAMERA_RELATIVE_CONTROLLER_RIGHTHAND_INDEX || - parentJointIndex == FARGRAB_RIGHTHAND_INDEX || - parentJointIndex == getJointIndex("RightHand")) { + if (parentJointIndex == CONTROLLER_RIGHTHAND_INDEX || parentJointIndex == CAMERA_RELATIVE_CONTROLLER_RIGHTHAND_INDEX || + parentJointIndex == FARGRAB_RIGHTHAND_INDEX || parentJointIndex == getJointIndex("RightHand")) { hand = "right"; - } else if (parentJointIndex == CONTROLLER_LEFTHAND_INDEX || - parentJointIndex == CAMERA_RELATIVE_CONTROLLER_LEFTHAND_INDEX || - parentJointIndex == FARGRAB_LEFTHAND_INDEX || - parentJointIndex == getJointIndex("LeftHand")) { + } else if (parentJointIndex == CONTROLLER_LEFTHAND_INDEX || parentJointIndex == CAMERA_RELATIVE_CONTROLLER_LEFTHAND_INDEX || + parentJointIndex == FARGRAB_LEFTHAND_INDEX || parentJointIndex == getJointIndex("LeftHand")) { hand = "left"; } - Grab tmpGrab(DependencyManager::get()->getSessionUUID(), - targetID, parentJointIndex, hand, positionalOffset, rotationalOffset); + Grab tmpGrab(DependencyManager::get()->getSessionUUID(), targetID, parentJointIndex, hand, positionalOffset, + rotationalOffset); QByteArray grabData = tmpGrab.toByteArray(); bool dataChanged = updateAvatarGrabData(grabID, grabData); @@ -5806,10 +5781,9 @@ const QUuid MyAvatar::grab(const QUuid& targetID, int parentJointIndex, } void MyAvatar::releaseGrab(const QUuid& grabID) { - bool tellHandler { false }; + bool tellHandler{ false }; _avatarGrabsLock.withWriteLock([&] { - std::map::iterator itr; itr = _avatarGrabs.find(grabID); if (itr != _avatarGrabs.end()) { @@ -5838,13 +5812,12 @@ void MyAvatar::releaseGrab(const QUuid& grabID) { void MyAvatar::addAvatarHandsToFlow(const std::shared_ptr& otherAvatar) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "addAvatarHandsToFlow", - Q_ARG(const std::shared_ptr&, otherAvatar)); + QMetaObject::invokeMethod(this, "addAvatarHandsToFlow", Q_ARG(const std::shared_ptr&, otherAvatar)); return; } - auto &flow = _skeletonModel->getRig().getFlow(); + auto& flow = _skeletonModel->getRig().getFlow(); if (otherAvatar != nullptr && flow.getActive()) { - for (auto &handJointName : HAND_COLLISION_JOINTS) { + for (auto& handJointName : HAND_COLLISION_JOINTS) { int jointIndex = otherAvatar->getJointIndex(handJointName); if (jointIndex != -1) { glm::vec3 position = otherAvatar->getJointPosition(jointIndex); @@ -5872,18 +5845,18 @@ void MyAvatar::addAvatarHandsToFlow(const std::shared_ptr& otherAvatar) * @property {number} [radius=0.05] - Collision sphere radius. * @property {number} [offset=Vec3.ZERO] - Offset of the collision sphere from the joint. */ -void MyAvatar::useFlow(bool isActive, bool isCollidable, const QVariantMap& physicsConfig, const QVariantMap& collisionsConfig) { +void MyAvatar::useFlow(bool isActive, + bool isCollidable, + const QVariantMap& physicsConfig, + const QVariantMap& collisionsConfig) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "useFlow", - Q_ARG(bool, isActive), - Q_ARG(bool, isCollidable), - Q_ARG(const QVariantMap&, physicsConfig), - Q_ARG(const QVariantMap&, collisionsConfig)); + QMetaObject::invokeMethod(this, "useFlow", Q_ARG(bool, isActive), Q_ARG(bool, isCollidable), + Q_ARG(const QVariantMap&, physicsConfig), Q_ARG(const QVariantMap&, collisionsConfig)); return; } if (_skeletonModel->isLoaded()) { - auto &flow = _skeletonModel->getRig().getFlow(); - auto &collisionSystem = flow.getCollisionSystem(); + auto& flow = _skeletonModel->getRig().getFlow(); + auto& collisionSystem = flow.getCollisionSystem(); if (!flow.isInitialized() && isActive) { _skeletonModel->getRig().initFlow(true); } else { @@ -5892,7 +5865,7 @@ void MyAvatar::useFlow(bool isActive, bool isCollidable, const QVariantMap& phys collisionSystem.setActive(isCollidable); auto physicsGroups = physicsConfig.keys(); if (physicsGroups.size() > 0) { - for (auto &groupName : physicsGroups) { + for (auto& groupName : physicsGroups) { auto settings = physicsConfig[groupName].toMap(); FlowPhysicsSettings physicsSettings; if (settings.contains("active")) { @@ -5922,7 +5895,7 @@ void MyAvatar::useFlow(bool isActive, bool isCollidable, const QVariantMap& phys auto collisionJoints = collisionsConfig.keys(); if (collisionJoints.size() > 0) { collisionSystem.clearSelfCollisions(); - for (auto &jointName : collisionJoints) { + for (auto& jointName : collisionJoints) { int jointIndex = getJointIndex(jointName); FlowCollisionSettings collisionsSettings; auto settings = collisionsConfig[jointName].toMap(); @@ -5976,14 +5949,13 @@ void MyAvatar::useFlow(bool isActive, bool isCollidable, const QVariantMap& phys QVariantMap MyAvatar::getFlowData() { QVariantMap result; if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "getFlowData", - Q_RETURN_ARG(QVariantMap, result)); + BLOCKING_INVOKE_METHOD(this, "getFlowData", Q_RETURN_ARG(QVariantMap, result)); return result; } if (_skeletonModel->isLoaded()) { auto jointNames = getJointNames(); - auto &flow = _skeletonModel->getRig().getFlow(); - auto &collisionSystem = flow.getCollisionSystem(); + auto& flow = _skeletonModel->getRig().getFlow(); + auto& collisionSystem = flow.getCollisionSystem(); bool initialized = flow.isInitialized(); result.insert("initialized", initialized); result.insert("active", flow.getActive()); @@ -5993,17 +5965,17 @@ QVariantMap MyAvatar::getFlowData() { QVariantMap threadData; std::map groupJointsMap; QVariantList jointCollisionData; - auto &groups = flow.getGroupSettings(); - for (auto &joint : flow.getJoints()) { - auto &groupName = joint.second.getGroup(); + auto& groups = flow.getGroupSettings(); + for (auto& joint : flow.getJoints()) { + auto& groupName = joint.second.getGroup(); if (groups.find(groupName) != groups.end()) { if (groupJointsMap.find(groupName) == groupJointsMap.end()) { groupJointsMap.insert(std::pair(groupName, QVariantList())); } groupJointsMap[groupName].push_back(joint.second.getIndex()); } - } - for (auto &group : groups) { + } + for (auto& group : groups) { QVariantMap settingsObject; QString groupName = group.first; FlowPhysicsSettings groupSettings = group.second; @@ -6018,8 +5990,8 @@ QVariantMap MyAvatar::getFlowData() { physicsData.insert(groupName, settingsObject); } - auto &collisions = collisionSystem.getCollisions(); - for (auto &collision : collisions) { + auto& collisions = collisionSystem.getCollisions(); + for (auto& collision : collisions) { QVariantMap collisionObject; collisionObject.insert("offset", vec3toVariant(collision._offset)); collisionObject.insert("radius", collision._radius); @@ -6027,7 +5999,7 @@ QVariantMap MyAvatar::getFlowData() { QString jointName = jointNames.size() > collision._jointIndex ? jointNames[collision._jointIndex] : "unknown"; collisionsData.insert(jointName, collisionObject); } - for (auto &thread : flow.getThreads()) { + for (auto& thread : flow.getThreads()) { QVariantList indices; for (int index : thread._joints) { indices.append(index); @@ -6044,14 +6016,13 @@ QVariantMap MyAvatar::getFlowData() { QVariantList MyAvatar::getCollidingFlowJoints() { QVariantList result; if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "getCollidingFlowJoints", - Q_RETURN_ARG(QVariantList, result)); + BLOCKING_INVOKE_METHOD(this, "getCollidingFlowJoints", Q_RETURN_ARG(QVariantList, result)); return result; } if (_skeletonModel->isLoaded()) { auto& flow = _skeletonModel->getRig().getFlow(); - for (auto &joint : flow.getJoints()) { + for (auto& joint : flow.getJoints()) { if (joint.second.isColliding()) { result.append(joint.second.getIndex()); } @@ -6062,7 +6033,7 @@ QVariantList MyAvatar::getCollidingFlowJoints() { void MyAvatar::initFlowFromFST() { if (_skeletonModel->isLoaded()) { - auto &flowData = _skeletonModel->getHFMModel().flowData; + auto& flowData = _skeletonModel->getHFMModel().flowData; if (flowData.shouldInitFlow()) { useFlow(true, flowData.shouldInitCollisions(), flowData._physicsConfig, flowData._collisionsConfig); } @@ -6080,4 +6051,3 @@ void MyAvatar::sendPacket(const QUuid& entityID) const { }); } } - diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index 7736eba7ea..1bd4f10944 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -371,9 +371,9 @@ class MyAvatar : public Avatar { Q_PROPERTY(float walkSpeed READ getWalkSpeed WRITE setWalkSpeed); Q_PROPERTY(float analogPlusWalkSpeed READ getAnalogPlusWalkSpeed WRITE setAnalogPlusWalkSpeed NOTIFY analogPlusWalkSpeedChanged); - Q_PROPERTY(float analogPlusSprintSpeed READ getAnalogPlusSprintSpeed WRITE setAnalogPlusSprintSpeed); - Q_PROPERTY(float walkBackwardSpeed READ getWalkBackwardSpeed WRITE setWalkBackwardSpeed); - Q_PROPERTY(float sprintSpeed READ getSprintSpeed WRITE setSprintSpeed); + Q_PROPERTY(float analogPlusSprintSpeed READ getAnalogPlusSprintSpeed WRITE setAnalogPlusSprintSpeed NOTIFY analogPlusSprintSpeedChanged); + Q_PROPERTY(float walkBackwardSpeed READ getWalkBackwardSpeed WRITE setWalkBackwardSpeed NOTIFY walkBackwardSpeedChanged); + Q_PROPERTY(float sprintSpeed READ getSprintSpeed WRITE setSprintSpeed NOTIFY sprintSpeedChanged); Q_PROPERTY(bool isInSittingState READ getIsInSittingState WRITE setIsInSittingState); Q_PROPERTY(MyAvatar::SitStandModelType userRecenterModel READ getUserRecenterModel WRITE setUserRecenterModel); Q_PROPERTY(bool isSitStandStateLocked READ getIsSitStandStateLocked WRITE setIsSitStandStateLocked); @@ -2162,12 +2162,37 @@ signals: void audioListenerModeChanged(); /**jsdoc - * Notifies when the analogPlusWalkSpeed value changed. + * Notifies when the analogPlusWalkSpeed value is changed. * @function MyAvatar.analogPlusWalkSpeedChanged + * @param {float} speed - the new avatar walk speed * @returns {Signal} */ void analogPlusWalkSpeedChanged(float value); + /**jsdoc + * Notifies when the analogPlusSprintSpeed value is changed. + * @function MyAvatar.analogPlusSprintSpeedChanged + * @param {float} speed - the new avatar sprint speed + * @returns {Signal} + */ + void analogPlusSprintSpeedChanged(float value); + + /**jsdoc + * Notifies when the sprintSpeed value is changed. + * @function MyAvatar.sprintSpeedChanged + * @param {float} speed - the new avatar sprint speed + * @returns {Signal} + */ + void sprintSpeedChanged(float value); + + /**jsdoc + * Notifies when the walkBackwardSpeed value is changed. + * @function MyAvatar.walkBackwardSpeedChanged + * @param {float} speed - the new avatar walk backward speed + * @returns {Signal} + */ + void walkBackwardSpeedChanged(float value); + /**jsdoc * @function MyAvatar.transformChanged * @returns {Signal} From 3bb645b2d78d9b6ed65d6270aecc331dc6cc587f Mon Sep 17 00:00:00 2001 From: SamGondelman Date: Thu, 6 Jun 2019 17:17:18 -0700 Subject: [PATCH 07/31] put avatar spheres in r3 in simulation --- interface/src/avatar/OtherAvatar.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/avatar/OtherAvatar.cpp b/interface/src/avatar/OtherAvatar.cpp index 06dcd9767d..6f83c61cd6 100755 --- a/interface/src/avatar/OtherAvatar.cpp +++ b/interface/src/avatar/OtherAvatar.cpp @@ -219,7 +219,7 @@ bool OtherAvatar::isInPhysicsSimulation() const { } bool OtherAvatar::shouldBeInPhysicsSimulation() const { - return !isDead() && _workloadRegion < workload::Region::R3; + return !isDead() && _workloadRegion <= workload::Region::R3; } bool OtherAvatar::needsPhysicsUpdate() const { From ad1333b0d3a4ec36ec525e5fa62269ade220035d Mon Sep 17 00:00:00 2001 From: luiscuenca Date: Fri, 7 Jun 2019 09:21:50 -0700 Subject: [PATCH 08/31] add review changes --- launchers/win32/LauncherDlg.cpp | 28 ++++++++++++++++------------ launchers/win32/LauncherUtils.cpp | 16 +++++++++------- launchers/win32/LauncherUtils.h | 16 +++++++++------- 3 files changed, 34 insertions(+), 26 deletions(-) diff --git a/launchers/win32/LauncherDlg.cpp b/launchers/win32/LauncherDlg.cpp index 7751c9cd6b..d2d149348e 100644 --- a/launchers/win32/LauncherDlg.cpp +++ b/launchers/win32/LauncherDlg.cpp @@ -174,10 +174,10 @@ void CLauncherDlg::startProcess() { LauncherUtils::deleteDirectoriesOnThread(installDir, downloadDir, [&](int error) { LauncherUtils::DeleteDirError deleteError = (LauncherUtils::DeleteDirError)error; - if (error == LauncherUtils::DeleteDirError::NoErrorDeleting) { + switch(error) { + case LauncherUtils::DeleteDirError::NoErrorDeleting: theApp._manager.addToLog(_T("Install directory deleted.")); theApp._manager.addToLog(_T("Downloads directory deleted.")); - // CString interfaceExe = installPath += "\\interface.exe"; if (!theApp._manager.isLoggedIn()) { theApp._manager.addToLog(_T("Downloading Content")); theApp._manager.downloadContent(); @@ -185,14 +185,18 @@ void CLauncherDlg::startProcess() { theApp._manager.addToLog(_T("Downloading App")); theApp._manager.downloadApplication(); } - } - if (error == LauncherUtils::DeleteDirError::ErrorDeletingPath1 || - error == LauncherUtils::DeleteDirError::ErrorDeletingPaths) { - theApp._manager.addToLog(_T("Error deleting install directory.")); - } - if (error == LauncherUtils::DeleteDirError::ErrorDeletingPath2 || - error == LauncherUtils::DeleteDirError::ErrorDeletingPaths) { + break; + case LauncherUtils::DeleteDirError::ErrorDeletingBothDirs: + theApp._manager.addToLog(_T("Error deleting directories.")); + break; + case LauncherUtils::DeleteDirError::ErrorDeletingApplicationDir: + theApp._manager.addToLog(_T("Error deleting application directory.")); + break; + case LauncherUtils::DeleteDirError::ErrorDeletingDownloadsDir: theApp._manager.addToLog(_T("Error deleting downloads directory.")); + break; + default: + break; } }); } @@ -233,8 +237,8 @@ afx_msg void CLauncherDlg::OnNextClicked() { theApp._manager.addToLog(_T("Bad credentials. Try again")); setDrawDialog(DrawStep::DrawLoginErrorCred); } else { - theApp._manager.addToLog(_T("Error Reading or retreaving response.")); - MessageBox(L"Error Reading or retreaving response.", L"Network Error", MB_OK | MB_ICONERROR); + theApp._manager.addToLog(_T("Error Reading or retrieving response.")); + MessageBox(L"Error Reading or retrieving response.", L"Network Error", MB_OK | MB_ICONERROR); } } else { theApp._manager.addToLog(_T("Organization name does not exist.")); @@ -575,7 +579,7 @@ void CLauncherDlg::OnTimer(UINT_PTR nIDEvent) { if (_showSplash) { if (_splashStep == 0){ if (theApp._manager.needsUninstall()) { - theApp._manager.addToLog(_T("Waiting to unistall")); + theApp._manager.addToLog(_T("Waiting to uninstall")); setDrawDialog(DrawStep::DrawProcessUninstall); } else { theApp._manager.addToLog(_T("Start splash screen")); diff --git a/launchers/win32/LauncherUtils.cpp b/launchers/win32/LauncherUtils.cpp index 8cf1d78ebf..22724ac499 100644 --- a/launchers/win32/LauncherUtils.cpp +++ b/launchers/win32/LauncherUtils.cpp @@ -395,11 +395,11 @@ DWORD WINAPI LauncherUtils::downloadThread(LPVOID lpParameter) DWORD WINAPI LauncherUtils::deleteDirectoriesThread(LPVOID lpParameter) { DeleteThreadData& data = *((DeleteThreadData*)lpParameter); DeleteDirError error = DeleteDirError::NoErrorDeleting; - if (!LauncherUtils::deleteFileOrDirectory(data._path1)) { - error = DeleteDirError::ErrorDeletingPath1; + if (!LauncherUtils::deleteFileOrDirectory(data._applicationDir)) { + error = DeleteDirError::ErrorDeletingApplicationDir; } - if (!LauncherUtils::deleteFileOrDirectory(data._path2)) { - error = error == NoError ? DeleteDirError::ErrorDeletingPath2 : DeleteDirError::ErrorDeletingPaths; + if (!LauncherUtils::deleteFileOrDirectory(data._downloadsDir)) { + error = error == NoError ? DeleteDirError::ErrorDeletingDownloadsDir : DeleteDirError::ErrorDeletingBothDirs; } data.callback(error); return 0; @@ -435,11 +435,13 @@ BOOL LauncherUtils::downloadFileOnThread(int type, const CString& url, const CSt return FALSE; } -BOOL LauncherUtils::deleteDirectoriesOnThread(const CString& dir1, const CString& dir2, std::function callback) { +BOOL LauncherUtils::deleteDirectoriesOnThread(const CString& applicationDir, + const CString& downloadsDir, + std::function callback) { DWORD myThreadID; DeleteThreadData* deleteThreadData = new DeleteThreadData(); - deleteThreadData->_path1 = dir1; - deleteThreadData->_path2 = dir2; + deleteThreadData->_applicationDir = applicationDir; + deleteThreadData->_downloadsDir = downloadsDir; deleteThreadData->setCallback(callback); HANDLE myHandle = CreateThread(0, 0, deleteDirectoriesThread, deleteThreadData, 0, &myThreadID); if (myHandle) { diff --git a/launchers/win32/LauncherUtils.h b/launchers/win32/LauncherUtils.h index 4add0fb931..47a8fc56c8 100644 --- a/launchers/win32/LauncherUtils.h +++ b/launchers/win32/LauncherUtils.h @@ -32,9 +32,9 @@ public: enum DeleteDirError { NoErrorDeleting = 0, - ErrorDeletingPath1, - ErrorDeletingPath2, - ErrorDeletingPaths + ErrorDeletingApplicationDir, + ErrorDeletingDownloadsDir, + ErrorDeletingBothDirs }; struct DownloadThreadData { @@ -60,8 +60,8 @@ public: }; struct DeleteThreadData { - CString _path1; - CString _path2; + CString _applicationDir; + CString _downloadsDir; std::function callback; void setCallback(std::function fn) { callback = std::bind(fn, std::placeholders::_1); } }; @@ -83,10 +83,12 @@ public: static BOOL deleteRegistryKey(const CString& registryPath); static BOOL unzipFileOnThread(int type, const std::string& zipFile, const std::string& path, std::function callback); static BOOL downloadFileOnThread(int type, const CString& url, const CString& file, std::function callback); - static BOOL deleteDirectoriesOnThread(const CString& dir1, const CString& dir2, std::function callback); + static BOOL deleteDirectoriesOnThread(const CString& applicationDir, + const CString& downloadsDir, + std::function callback); static CString urlEncodeString(const CString& url); - private: +private: // Threads static DWORD WINAPI unzipThread(LPVOID lpParameter); static DWORD WINAPI downloadThread(LPVOID lpParameter); From b1df463f56ddc96bbfba17006d229add5eb0af95 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Fri, 7 Jun 2019 10:16:36 -0700 Subject: [PATCH 09/31] disabling dde initialization due to random crashes while closing down the socket connection on mac --- interface/src/Application.cpp | 19 +++++++++++++++++-- interface/src/devices/DdeFaceTracker.h | 3 ++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 4a0bce5103..7efa17cb8c 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -867,7 +867,11 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { DependencyManager::set(); DependencyManager::set(); DependencyManager::set(); + +#ifdef HAVE_DDE DependencyManager::set(); +#endif + DependencyManager::set(); DependencyManager::set(); DependencyManager::set(); @@ -3324,7 +3328,9 @@ void Application::onDesktopRootContextCreated(QQmlContext* surfaceContext) { surfaceContext->setContextProperty("AccountServices", AccountServicesScriptingInterface::getInstance()); surfaceContext->setContextProperty("DialogsManager", _dialogsManagerScriptingInterface); +#ifdef HAVE_DDE surfaceContext->setContextProperty("FaceTracker", DependencyManager::get().data()); +#endif surfaceContext->setContextProperty("AvatarManager", DependencyManager::get().data()); surfaceContext->setContextProperty("LODManager", DependencyManager::get().data()); surfaceContext->setContextProperty("HMD", DependencyManager::get().data()); @@ -5176,7 +5182,11 @@ ivec2 Application::getMouse() const { FaceTracker* Application::getActiveFaceTracker() { auto dde = DependencyManager::get(); - return dde->isActive() ? static_cast(dde.data()) : nullptr; + if(dde){ + return dde->isActive() ? static_cast(dde.data()) : nullptr; + }else{ + return nullptr; + } } FaceTracker* Application::getSelectedFaceTracker() { @@ -7010,7 +7020,10 @@ void Application::copyDisplayViewFrustum(ViewFrustum& viewOut) const { // feature. However, we still use this to reset face trackers, eye trackers, audio and to optionally re-load the avatar // rig and animations from scratch. void Application::resetSensors(bool andReload) { +#ifdef HAVE_DDE DependencyManager::get()->reset(); +#endif + DependencyManager::get()->reset(); _overlayConductor.centerUI(); getActiveDisplayPlugin()->resetSensors(); @@ -7402,8 +7415,10 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointe scriptEngine->registerGlobalObject("AccountServices", AccountServicesScriptingInterface::getInstance()); qScriptRegisterMetaType(scriptEngine.data(), DownloadInfoResultToScriptValue, DownloadInfoResultFromScriptValue); +#ifdef HAVE_DDE scriptEngine->registerGlobalObject("FaceTracker", DependencyManager::get().data()); - +#endif + scriptEngine->registerGlobalObject("AvatarManager", DependencyManager::get().data()); scriptEngine->registerGlobalObject("LODManager", DependencyManager::get().data()); diff --git a/interface/src/devices/DdeFaceTracker.h b/interface/src/devices/DdeFaceTracker.h index 0ad8d85c62..dc451134f0 100644 --- a/interface/src/devices/DdeFaceTracker.h +++ b/interface/src/devices/DdeFaceTracker.h @@ -14,8 +14,9 @@ #include +//Disabling dde due to random crashes with closing the socket on macos. all the accompanying code is wrapped with the ifdef HAVE_DDE. uncomment the define below to enable #if defined(Q_OS_WIN) || defined(Q_OS_OSX) - #define HAVE_DDE + //#define HAVE_DDE #endif #include From 54906a270e29d87b58cccc7fbf7504558a3342e9 Mon Sep 17 00:00:00 2001 From: Seth Alves Date: Fri, 7 Jun 2019 10:31:48 -0700 Subject: [PATCH 10/31] don't hang if somehow setting display plugin to the current one --- .../src/display-plugins/OpenGLDisplayPlugin.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/display-plugins/src/display-plugins/OpenGLDisplayPlugin.cpp b/libraries/display-plugins/src/display-plugins/OpenGLDisplayPlugin.cpp index bb94195f85..6c6c2aee80 100644 --- a/libraries/display-plugins/src/display-plugins/OpenGLDisplayPlugin.cpp +++ b/libraries/display-plugins/src/display-plugins/OpenGLDisplayPlugin.cpp @@ -170,9 +170,9 @@ public: glFinish(); } currentPlugin = newPlugin; - _newPluginQueue.pop(); - _condition.notify_one(); } + _newPluginQueue.pop(); + _condition.notify_one(); } } From 3ab4be6b8d7f0887adbc5ba4db3848b21ccf02e7 Mon Sep 17 00:00:00 2001 From: Preston Bezos Date: Fri, 7 Jun 2019 10:42:31 -0700 Subject: [PATCH 11/31] I got clanged --- interface/src/avatar/MyAvatar.cpp | 854 ++++++++++++++++-------------- 1 file changed, 452 insertions(+), 402 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 4cf12dc2d3..92a88cac38 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -71,9 +71,9 @@ using namespace std; const float DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES = 30.0f; const float YAW_SPEED_DEFAULT = 100.0f; // degrees/sec -const float PITCH_SPEED_DEFAULT = 75.0f; // degrees/sec +const float PITCH_SPEED_DEFAULT = 75.0f; // degrees/sec -const float MAX_BOOST_SPEED = 0.5f * DEFAULT_AVATAR_MAX_WALKING_SPEED; // action motor gets additive boost below this speed +const float MAX_BOOST_SPEED = 0.5f * DEFAULT_AVATAR_MAX_WALKING_SPEED; // action motor gets additive boost below this speed const float MIN_AVATAR_SPEED = 0.05f; float MIN_SCRIPTED_MOTOR_TIMESCALE = 0.005f; @@ -83,8 +83,7 @@ const int SCRIPTED_MOTOR_AVATAR_FRAME = 1; const int SCRIPTED_MOTOR_WORLD_FRAME = 2; const int SCRIPTED_MOTOR_SIMPLE_MODE = 0; const int SCRIPTED_MOTOR_DYNAMIC_MODE = 1; -const QString& DEFAULT_AVATAR_COLLISION_SOUND_URL = - "https://hifi-public.s3.amazonaws.com/sounds/Collisions-otherorganic/Body_Hits_Impact.wav"; +const QString& DEFAULT_AVATAR_COLLISION_SOUND_URL = "https://hifi-public.s3.amazonaws.com/sounds/Collisions-otherorganic/Body_Hits_Impact.wav"; const float MyAvatar::ZOOM_MIN = 0.5f; const float MyAvatar::ZOOM_MAX = 25.0f; @@ -93,7 +92,7 @@ const float MIN_SCALE_CHANGED_DELTA = 0.001f; const int MODE_READINGS_RING_BUFFER_SIZE = 500; const float CENTIMETERS_PER_METER = 100.0f; -const QString AVATAR_SETTINGS_GROUP_NAME{ "Avatar" }; +const QString AVATAR_SETTINGS_GROUP_NAME { "Avatar" }; static const QString USER_RECENTER_MODEL_FORCE_SIT = QStringLiteral("ForceSit"); static const QString USER_RECENTER_MODEL_FORCE_STAND = QStringLiteral("ForceStand"); @@ -114,33 +113,50 @@ MyAvatar::SitStandModelType stringToUserRecenterModel(const QString& str) { QString userRecenterModelToString(MyAvatar::SitStandModelType model) { switch (model) { - case MyAvatar::ForceSit: - return USER_RECENTER_MODEL_FORCE_SIT; - case MyAvatar::ForceStand: - return USER_RECENTER_MODEL_FORCE_STAND; - case MyAvatar::DisableHMDLean: - return USER_RECENTER_MODEL_DISABLE_HMD_LEAN; - case MyAvatar::Auto: - default: - return USER_RECENTER_MODEL_AUTO; + case MyAvatar::ForceSit: + return USER_RECENTER_MODEL_FORCE_SIT; + case MyAvatar::ForceStand: + return USER_RECENTER_MODEL_FORCE_STAND; + case MyAvatar::DisableHMDLean: + return USER_RECENTER_MODEL_DISABLE_HMD_LEAN; + case MyAvatar::Auto: + default: + return USER_RECENTER_MODEL_AUTO; } } MyAvatar::MyAvatar(QThread* thread) : - Avatar(thread), _yawSpeed(YAW_SPEED_DEFAULT), _pitchSpeed(PITCH_SPEED_DEFAULT), - _scriptedMotorTimescale(DEFAULT_SCRIPTED_MOTOR_TIMESCALE), _scriptedMotorFrame(SCRIPTED_MOTOR_CAMERA_FRAME), - _scriptedMotorMode(SCRIPTED_MOTOR_SIMPLE_MODE), _motionBehaviors(AVATAR_MOTION_DEFAULTS), - _characterController(std::shared_ptr(this)), _eyeContactTarget(LEFT_EYE), - _realWorldFieldOfView("realWorldFieldOfView", DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES), - _useAdvancedMovementControls("advancedMovementForHandControllersIsChecked", true), _showPlayArea("showPlayArea", true), - _smoothOrientationTimer(std::numeric_limits::max()), _smoothOrientationInitial(), _smoothOrientationTarget(), - _hmdSensorMatrix(), _hmdSensorOrientation(), _hmdSensorPosition(), _recentModeReadings(MODE_READINGS_RING_BUFFER_SIZE), - _bodySensorMatrix(), _goToPending(false), _goToSafe(true), _goToFeetAjustment(false), _goToPosition(), _goToOrientation(), - _prevShouldDrawHead(true), _audioListenerMode(FROM_HEAD), + Avatar(thread), + _yawSpeed(YAW_SPEED_DEFAULT), + _pitchSpeed(PITCH_SPEED_DEFAULT), + _scriptedMotorTimescale(DEFAULT_SCRIPTED_MOTOR_TIMESCALE), + _scriptedMotorFrame(SCRIPTED_MOTOR_CAMERA_FRAME), + _scriptedMotorMode(SCRIPTED_MOTOR_SIMPLE_MODE), + _motionBehaviors(AVATAR_MOTION_DEFAULTS), + _characterController(std::shared_ptr(this)), + _eyeContactTarget(LEFT_EYE), + _realWorldFieldOfView("realWorldFieldOfView", + DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES), + _useAdvancedMovementControls("advancedMovementForHandControllersIsChecked", true), + _showPlayArea("showPlayArea", true), + _smoothOrientationTimer(std::numeric_limits::max()), + _smoothOrientationInitial(), + _smoothOrientationTarget(), + _hmdSensorMatrix(), + _hmdSensorOrientation(), + _hmdSensorPosition(), + _recentModeReadings(MODE_READINGS_RING_BUFFER_SIZE), + _bodySensorMatrix(), + _goToPending(false), + _goToSafe(true), + _goToFeetAjustment(false), + _goToPosition(), + _goToOrientation(), + _prevShouldDrawHead(true), + _audioListenerMode(FROM_HEAD), _dominantHandSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "dominantHand", DOMINANT_RIGHT_HAND), _strafeEnabledSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "strafeEnabled", DEFAULT_STRAFE_ENABLED), - _hmdAvatarAlignmentTypeSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "hmdAvatarAlignmentType", - DEFAULT_HMD_AVATAR_ALIGNMENT_TYPE), + _hmdAvatarAlignmentTypeSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "hmdAvatarAlignmentType", DEFAULT_HMD_AVATAR_ALIGNMENT_TYPE), _headPitchSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "", 0.0f), _scaleSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "scale", _targetScale), _yawSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "yawSpeed", _yawSpeed), @@ -156,19 +172,17 @@ MyAvatar::MyAvatar(QThread* thread) : _userHeightSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userHeight", DEFAULT_AVATAR_HEIGHT), _flyingHMDSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "flyingHMD", _flyingPrefHMD), _movementReferenceSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "movementReference", _movementReference), - _avatarEntityCountSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" - << "size", - 0), + _avatarEntityCountSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" << "size", 0), _driveGear1Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear1", _driveGear1), _driveGear2Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear2", _driveGear2), _driveGear3Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear3", _driveGear3), _driveGear4Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear4", _driveGear4), _driveGear5Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear5", _driveGear5), _analogWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogWalkSpeed", _analogWalkSpeed.get()), - _analogPlusWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogPlusWalkSpeed", - _analogPlusWalkSpeed.get()), + _analogPlusWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogPlusWalkSpeed", _analogPlusWalkSpeed.get()), _controlSchemeIndexSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "controlSchemeIndex", _controlSchemeIndex), - _userRecenterModelSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userRecenterModel", USER_RECENTER_MODEL_AUTO) { + _userRecenterModelSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userRecenterModel", USER_RECENTER_MODEL_AUTO) +{ _clientTraitsHandler.reset(new ClientTraitsHandler(this)); // give the pointer to our head to inherited _headData variable from AvatarData @@ -189,7 +203,7 @@ MyAvatar::MyAvatar(QThread* thread) : qApp->loadAvatarScripts(hfmModel.scripts); _shouldLoadScripts = false; } - // Load and convert old attachments to avatar entities + // Load and convert old attachments to avatar entities if (_oldAttachmentData.size() > 0) { setAttachmentData(_oldAttachmentData); _oldAttachmentData.clear(); @@ -206,11 +220,11 @@ MyAvatar::MyAvatar(QThread* thread) : clearDriveKeys(); // Necessary to select the correct slot - using SlotType = void (MyAvatar::*)(const glm::vec3&, bool, const glm::quat&, bool); + using SlotType = void(MyAvatar::*)(const glm::vec3&, bool, const glm::quat&, bool); // connect to AddressManager signal for location jumps - connect(DependencyManager::get().data(), &AddressManager::locationChangeRequired, this, - static_cast(&MyAvatar::goToFeetLocation)); + connect(DependencyManager::get().data(), &AddressManager::locationChangeRequired, + this, static_cast(&MyAvatar::goToFeetLocation)); // handle scale constraints imposed on us by the domain-server auto& domainHandler = DependencyManager::get()->getDomainHandler(); @@ -273,6 +287,7 @@ MyAvatar::MyAvatar(QThread* thread) : if (recordingInterface->getPlayerUseSkeletonModel() && dummyAvatar.getSkeletonModelURL().isValid() && (dummyAvatar.getSkeletonModelURL() != getSkeletonModelURL())) { + setSkeletonModelURL(dummyAvatar.getSkeletonModelURL()); } @@ -368,8 +383,7 @@ void MyAvatar::enableHandTouchForID(const QUuid& entityID) { } void MyAvatar::registerMetaTypes(ScriptEnginePointer engine) { - QScriptValue value = engine->newQObject(this, QScriptEngine::QtOwnership, - QScriptEngine::ExcludeDeleteLater | QScriptEngine::ExcludeChildObjects); + QScriptValue value = engine->newQObject(this, QScriptEngine::QtOwnership, QScriptEngine::ExcludeDeleteLater | QScriptEngine::ExcludeChildObjects); engine->globalObject().setProperty("MyAvatar", value); QScriptValue driveKeys = engine->newObject(); @@ -432,6 +446,7 @@ void MyAvatar::resetSensorsAndBody() { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "resetSensorsAndBody"); return; + } qApp->getActiveDisplayPlugin()->resetSensors(); @@ -445,7 +460,7 @@ void MyAvatar::centerBody() { } // derive the desired body orientation from the current hmd orientation, before the sensor reset. - auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. // transform this body into world space auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix; @@ -482,6 +497,7 @@ void MyAvatar::clearIKJointLimitHistory() { } void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { + assert(QThread::currentThread() == thread()); // Reset dynamic state. @@ -490,14 +506,14 @@ void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { if (andReload) { _skeletonModel->reset(); } - if (andHead) { // which drives camera in desktop + if (andHead) { // which drives camera in desktop getHead()->reset(); } setThrust(glm::vec3(0.0f)); if (andRecenter) { // derive the desired body orientation from the *old* hmd orientation, before the sensor reset. - auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. // transform this body into world space auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix; @@ -524,8 +540,8 @@ void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { void MyAvatar::updateSitStandState(float newHeightReading, float dt) { const float STANDING_HEIGHT_MULTIPLE = 1.2f; const float SITTING_HEIGHT_MULTIPLE = 0.833f; - const float SITTING_TIMEOUT = 4.0f; // 4 seconds - const float STANDING_TIMEOUT = 0.3333f; // 1/3 second + const float SITTING_TIMEOUT = 4.0f; // 4 seconds + const float STANDING_TIMEOUT = 0.3333f; // 1/3 second const float SITTING_UPPER_BOUND = 1.52f; if (!getIsSitStandStateLocked()) { if (!getIsAway() && getControllerPoseInAvatarFrame(controller::Action::HEAD).isValid()) { @@ -585,9 +601,9 @@ void MyAvatar::updateSitStandState(float newHeightReading, float dt) { void MyAvatar::update(float deltaTime) { // update moving average of HMD facing in xz plane. const float HMD_FACING_TIMESCALE = getRotationRecenterFilterLength(); - const float PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH = 0.0f; // 100 percent shoulders + const float PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH = 0.0f; // 100 percent shoulders const float COSINE_THIRTY_DEGREES = 0.866f; - const float SQUATTY_TIMEOUT = 30.0f; // 30 seconds + const float SQUATTY_TIMEOUT = 30.0f; // 30 seconds const float HEIGHT_FILTER_COEFFICIENT = 0.01f; float tau = deltaTime / HMD_FACING_TIMESCALE; @@ -596,8 +612,8 @@ void MyAvatar::update(float deltaTime) { // put the average hand azimuth into sensor space. // then mix it with head facing direction to determine rotation recenter int spine2Index = _skeletonModel->getRig().indexOfJoint("Spine2"); - if (getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND).isValid() && - getControllerPoseInAvatarFrame(controller::Action::RIGHT_HAND).isValid() && !(spine2Index < 0)) { + if (getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND).isValid() && getControllerPoseInAvatarFrame(controller::Action::RIGHT_HAND).isValid() && !(spine2Index < 0)) { + // use the spine for the azimuth origin. glm::quat spine2Rot = getAbsoluteJointRotationInObjectFrame(spine2Index); glm::vec3 handHipAzimuthAvatarSpace = spine2Rot * glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y); @@ -607,10 +623,8 @@ void MyAvatar::update(float deltaTime) { glm::vec3 handHipAzimuthSensorSpace = transformVectorFast(worldToSensorMat, handHipAzimuthWorldSpace); glm::vec2 normedHandHipAzimuthSensorSpace(0.0f, 1.0f); if (glm::length(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)) > 0.0f) { - normedHandHipAzimuthSensorSpace = - glm::normalize(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)); - glm::vec2 headFacingPlusHandHipAzimuthMix = - lerp(normedHandHipAzimuthSensorSpace, _headControllerFacing, PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH); + normedHandHipAzimuthSensorSpace = glm::normalize(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)); + glm::vec2 headFacingPlusHandHipAzimuthMix = lerp(normedHandHipAzimuthSensorSpace, _headControllerFacing, PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH); _headControllerFacingMovingAverage = lerp(_headControllerFacingMovingAverage, headFacingPlusHandHipAzimuthMix, tau); } else { // use head facing if the chest arms vector is up or down. @@ -628,8 +642,7 @@ void MyAvatar::update(float deltaTime) { controller::Pose newHeightReading = getControllerPoseInSensorFrame(controller::Action::HEAD); if (newHeightReading.isValid()) { int newHeightReadingInCentimeters = glm::floor(newHeightReading.getTranslation().y * CENTIMETERS_PER_METER); - _averageUserHeightSensorSpace = - lerp(_averageUserHeightSensorSpace, newHeightReading.getTranslation().y, HEIGHT_FILTER_COEFFICIENT); + _averageUserHeightSensorSpace = lerp(_averageUserHeightSensorSpace, newHeightReading.getTranslation().y, HEIGHT_FILTER_COEFFICIENT); _recentModeReadings.insert(newHeightReadingInCentimeters); setCurrentStandingHeight(computeStandingHeightMode(newHeightReading)); setAverageHeadRotation(computeAverageHeadRotation(getControllerPoseInAvatarFrame(controller::Action::HEAD))); @@ -645,9 +658,10 @@ void MyAvatar::update(float deltaTime) { } float angleSpine2 = glm::dot(upSpine2, glm::vec3(0.0f, 1.0f, 0.0f)); - if (getControllerPoseInAvatarFrame(controller::Action::HEAD).getTranslation().y < - (headDefaultPositionAvatarSpace.y - SQUAT_THRESHOLD) && - (angleSpine2 > COSINE_THIRTY_DEGREES) && (getUserRecenterModel() != MyAvatar::SitStandModelType::ForceStand)) { + if (getControllerPoseInAvatarFrame(controller::Action::HEAD).getTranslation().y < (headDefaultPositionAvatarSpace.y - SQUAT_THRESHOLD) && + (angleSpine2 > COSINE_THIRTY_DEGREES) && + (getUserRecenterModel() != MyAvatar::SitStandModelType::ForceStand)) { + _squatTimer += deltaTime; if (_squatTimer > SQUATTY_TIMEOUT) { _squatTimer = 0.0f; @@ -663,24 +677,20 @@ void MyAvatar::update(float deltaTime) { if (_drawAverageFacingEnabled) { auto sensorHeadPose = getControllerPoseInSensorFrame(controller::Action::HEAD); glm::vec3 worldHeadPos = transformPoint(getSensorToWorldMatrix(), sensorHeadPose.getTranslation()); - glm::vec3 worldFacingAverage = - transformVectorFast(getSensorToWorldMatrix(), - glm::vec3(_headControllerFacingMovingAverage.x, 0.0f, _headControllerFacingMovingAverage.y)); - glm::vec3 worldFacing = - transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacing.x, 0.0f, _headControllerFacing.y)); + glm::vec3 worldFacingAverage = transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacingMovingAverage.x, 0.0f, _headControllerFacingMovingAverage.y)); + glm::vec3 worldFacing = transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacing.x, 0.0f, _headControllerFacing.y)); DebugDraw::getInstance().drawRay(worldHeadPos, worldHeadPos + worldFacing, glm::vec4(0.0f, 1.0f, 0.0f, 1.0f)); DebugDraw::getInstance().drawRay(worldHeadPos, worldHeadPos + worldFacingAverage, glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)); // draw hand azimuth vector - glm::vec3 handAzimuthMidpoint = - transformPoint(getTransform().getMatrix(), glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y)); + glm::vec3 handAzimuthMidpoint = transformPoint(getTransform().getMatrix(), glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y)); DebugDraw::getInstance().drawRay(getWorldPosition(), handAzimuthMidpoint, glm::vec4(0.0f, 1.0f, 1.0f, 1.0f)); } if (_goToPending) { setWorldPosition(_goToPosition); setWorldOrientation(_goToOrientation); - _headControllerFacingMovingAverage = _headControllerFacing; // reset moving average + _headControllerFacingMovingAverage = _headControllerFacing; // reset moving average _goToPending = false; // updateFromHMDSensorMatrix (called from paintGL) expects that the sensorToWorldMatrix is updated for any position changes // that happen between render and Application::update (which calls updateSensorToWorldMatrix to do so). @@ -690,7 +700,7 @@ void MyAvatar::update(float deltaTime) { emit positionGoneTo(); // Run safety tests as soon as we can after goToLocation, or clear if we're not colliding. _physicsSafetyPending = getCollisionsEnabled(); - _characterController.recomputeFlying(); // In case we've gone to into the sky. + _characterController.recomputeFlying(); // In case we've gone to into the sky. } if (_goToFeetAjustment && _skeletonModelLoaded) { auto feetAjustment = getWorldPosition() - getWorldFeetPosition(); @@ -702,7 +712,7 @@ void MyAvatar::update(float deltaTime) { // When needed and ready, arrange to check and fix. _physicsSafetyPending = false; if (_goToSafe) { - safeLanding(_goToPosition); // no-op if already safe + safeLanding(_goToPosition); // no-op if already safe } } @@ -710,8 +720,7 @@ void MyAvatar::update(float deltaTime) { head->relax(deltaTime); updateFromTrackers(deltaTime); - if (getIsInWalkingState() && glm::length(getControllerPoseInAvatarFrame(controller::Action::HEAD).getVelocity()) < - DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { + if (getIsInWalkingState() && glm::length(getControllerPoseInAvatarFrame(controller::Action::HEAD).getVelocity()) < DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { setIsInWalkingState(false); } @@ -722,13 +731,12 @@ void MyAvatar::update(float deltaTime) { setAudioLoudness(audio->getLastInputLoudness()); setAudioAverageLoudness(audio->getAudioAverageInputLoudness()); - glm::vec3 halfBoundingBoxDimensions(_characterController.getCapsuleRadius(), _characterController.getCapsuleHalfHeight(), - _characterController.getCapsuleRadius()); + glm::vec3 halfBoundingBoxDimensions(_characterController.getCapsuleRadius(), _characterController.getCapsuleHalfHeight(), _characterController.getCapsuleRadius()); // This might not be right! Isn't the capsule local offset in avatar space? -HRS 5/26/17 halfBoundingBoxDimensions += _characterController.getCapsuleLocalOffset(); QMetaObject::invokeMethod(audio, "setAvatarBoundingBoxParameters", - Q_ARG(glm::vec3, (getWorldPosition() - halfBoundingBoxDimensions)), - Q_ARG(glm::vec3, (halfBoundingBoxDimensions * 2.0f))); + Q_ARG(glm::vec3, (getWorldPosition() - halfBoundingBoxDimensions)), + Q_ARG(glm::vec3, (halfBoundingBoxDimensions*2.0f))); simulate(deltaTime, true); @@ -736,20 +744,23 @@ void MyAvatar::update(float deltaTime) { currentEnergy -= getAccelerationEnergy(); currentEnergy -= getAudioEnergy(); - if (didTeleport()) { + if(didTeleport()) { currentEnergy = 0.0f; } - currentEnergy = max(0.0f, min(currentEnergy, 1.0f)); + currentEnergy = max(0.0f, min(currentEnergy,1.0f)); emit energyChanged(currentEnergy); updateEyeContactTarget(deltaTime); } void MyAvatar::updateEyeContactTarget(float deltaTime) { + _eyeContactTargetTimer -= deltaTime; if (_eyeContactTargetTimer < 0.0f) { + const float CHANCE_OF_CHANGING_TARGET = 0.01f; if (randFloat() < CHANCE_OF_CHANGING_TARGET) { + float const FIFTY_FIFTY_CHANCE = 0.5f; float const EYE_TO_MOUTH_CHANCE = 0.25f; switch (_eyeContactTarget) { @@ -817,20 +828,21 @@ void MyAvatar::simulate(float deltaTime, bool inView) { if (isChildOfHead && !object->hasGrabs()) { // Cauterize or display children of head per head drawing state. updateChildCauterization(object, !_prevShouldDrawHead); - object->forEachDescendant( - [&](SpatiallyNestablePointer descendant) { updateChildCauterization(descendant, !_prevShouldDrawHead); }); + object->forEachDescendant([&](SpatiallyNestablePointer descendant) { + updateChildCauterization(descendant, !_prevShouldDrawHead); + }); _cauterizedChildrenOfHead.insert(object); objectsToUncauterize.erase(object); } else if (objectsToUncauterize.find(object) == objectsToUncauterize.end()) { objectsToUncauterize.insert(object); - object->forEachDescendant( - [&](SpatiallyNestablePointer descendant) { objectsToUncauterize.insert(descendant); }); + object->forEachDescendant([&](SpatiallyNestablePointer descendant) { + objectsToUncauterize.insert(descendant); + }); } }); // Redisplay cauterized entities that are no longer children of the avatar. - for (auto cauterizedChild = objectsToUncauterize.begin(); cauterizedChild != objectsToUncauterize.end(); - cauterizedChild++) { + for (auto cauterizedChild = objectsToUncauterize.begin(); cauterizedChild != objectsToUncauterize.end(); cauterizedChild++) { updateChildCauterization(*cauterizedChild, false); } } @@ -874,7 +886,7 @@ void MyAvatar::simulate(float deltaTime, bool inView) { if (!_skeletonModel->hasSkeleton()) { // All the simulation that can be done has been done - getHead()->setPosition(getWorldPosition()); // so audio-position isn't 0,0,0 + getHead()->setPosition(getWorldPosition()); // so audio-position isn't 0,0,0 return; } @@ -955,7 +967,8 @@ void MyAvatar::updateFromHMDSensorMatrix(const glm::mat4& hmdSensorMatrix) { _hmdSensorMatrix = hmdSensorMatrix; auto newHmdSensorPosition = extractTranslation(hmdSensorMatrix); - if (newHmdSensorPosition != getHMDSensorPosition() && glm::length(newHmdSensorPosition) > MAX_HMD_ORIGIN_DISTANCE) { + if (newHmdSensorPosition != getHMDSensorPosition() && + glm::length(newHmdSensorPosition) > MAX_HMD_ORIGIN_DISTANCE) { qWarning() << "Invalid HMD sensor position " << newHmdSensorPosition; // Ignore unreasonable HMD sensor data return; @@ -983,8 +996,8 @@ glm::vec2 MyAvatar::computeHandAzimuth() const { glm::vec2 latestHipToHandController = _hipToHandController; int spine2Index = _skeletonModel->getRig().indexOfJoint("Spine2"); - if (leftHandPoseAvatarSpace.isValid() && rightHandPoseAvatarSpace.isValid() && headPoseAvatarSpace.isValid() && - !(spine2Index < 0)) { + if (leftHandPoseAvatarSpace.isValid() && rightHandPoseAvatarSpace.isValid() && headPoseAvatarSpace.isValid() && !(spine2Index < 0)) { + glm::vec3 spine2Position = getAbsoluteJointTranslationInObjectFrame(spine2Index); glm::quat spine2Rotation = getAbsoluteJointRotationInObjectFrame(spine2Index); @@ -996,10 +1009,8 @@ glm::vec2 MyAvatar::computeHandAzimuth() const { // we need the old azimuth reading to prevent flipping the facing direction 180 // in the case where the hands go from being slightly less than 180 apart to slightly more than 180 apart. glm::vec2 oldAzimuthReading = _hipToHandController; - if ((glm::length(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)) > 0.0f) && - (glm::length(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)) > 0.0f)) { - latestHipToHandController = lerp(glm::normalize(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)), - glm::normalize(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)), HALFWAY); + if ((glm::length(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)) > 0.0f) && (glm::length(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)) > 0.0f)) { + latestHipToHandController = lerp(glm::normalize(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)), glm::normalize(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)), HALFWAY); } else { latestHipToHandController = glm::vec2(0.0f, 1.0f); } @@ -1047,11 +1058,11 @@ void MyAvatar::updateJointFromController(controller::Action poseKey, ThreadSafeV // update sensor to world matrix from current body position and hmd sensor. // This is so the correct camera can be used for rendering. void MyAvatar::updateSensorToWorldMatrix() { + // update the sensor mat so that the body position will end up in the desired // position when driven from the head. float sensorToWorldScale = getEyeHeight() / getUserEyeHeight(); - glm::mat4 desiredMat = - createMatFromScaleQuatAndPos(glm::vec3(sensorToWorldScale), getWorldOrientation(), getWorldPosition()); + glm::mat4 desiredMat = createMatFromScaleQuatAndPos(glm::vec3(sensorToWorldScale), getWorldOrientation(), getWorldPosition()); _sensorToWorldMatrix = desiredMat * glm::inverse(_bodySensorMatrix); bool hasSensorToWorldScaleChanged = false; @@ -1069,10 +1080,11 @@ void MyAvatar::updateSensorToWorldMatrix() { _sensorToWorldMatrixCache.set(_sensorToWorldMatrix); updateJointFromController(controller::Action::LEFT_HAND, _controllerLeftHandMatrixCache); updateJointFromController(controller::Action::RIGHT_HAND, _controllerRightHandMatrixCache); - + if (hasSensorToWorldScaleChanged) { emit sensorToWorldScaleChanged(sensorToWorldScale); } + } // Update avatar head rotation with sensor data @@ -1097,7 +1109,8 @@ void MyAvatar::updateFromTrackers(float deltaTime) { const float TRACKER_YAW_TURN_SENSITIVITY = 0.5f; const float TRACKER_MIN_YAW_TURN = 15.0f; const float TRACKER_MAX_YAW_TURN = 50.0f; - if ((fabs(estimatedRotation.y) > TRACKER_MIN_YAW_TURN) && (fabs(estimatedRotation.y) < TRACKER_MAX_YAW_TURN)) { + if ( (fabs(estimatedRotation.y) > TRACKER_MIN_YAW_TURN) && + (fabs(estimatedRotation.y) < TRACKER_MAX_YAW_TURN) ) { if (estimatedRotation.y > 0.0f) { _bodyYawDelta += (estimatedRotation.y - TRACKER_MIN_YAW_TURN) * TRACKER_YAW_TURN_SENSITIVITY; } else { @@ -1112,6 +1125,7 @@ void MyAvatar::updateFromTrackers(float deltaTime) { // their head only 30 degrees or so, this may correspond to a 90 degree field of view. // Note that roll is magnified by a constant because it is not related to field of view. + Head* head = getHead(); if (hasHead || playing) { head->setDeltaPitch(estimatedRotation.x); @@ -1177,15 +1191,15 @@ controller::Pose MyAvatar::getRightHandTipPose() const { void MyAvatar::render(RenderArgs* renderArgs) { // don't render if we've been asked to disable local rendering if (!_shouldRender) { - return; // exit early + return; // exit early } Avatar::render(renderArgs); } void MyAvatar::overrideAnimation(const QString& url, float fps, bool loop, float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "overrideAnimation", Q_ARG(const QString&, url), Q_ARG(float, fps), Q_ARG(bool, loop), - Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); + QMetaObject::invokeMethod(this, "overrideAnimation", Q_ARG(const QString&, url), Q_ARG(float, fps), + Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); return; } _skeletonModel->getRig().overrideAnimation(url, fps, loop, firstFrame, lastFrame); @@ -1193,8 +1207,8 @@ void MyAvatar::overrideAnimation(const QString& url, float fps, bool loop, float void MyAvatar::overrideHandAnimation(bool isLeft, const QString& url, float fps, bool loop, float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "overrideHandAnimation", Q_ARG(bool, isLeft), Q_ARG(const QString&, url), - Q_ARG(float, fps), Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); + QMetaObject::invokeMethod(this, "overrideHandAnimation", Q_ARG(bool, isLeft), Q_ARG(const QString&, url), Q_ARG(float, fps), + Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); return; } _skeletonModel->getRig().overrideHandAnimation(isLeft, url, fps, loop, firstFrame, lastFrame); @@ -1225,12 +1239,8 @@ QStringList MyAvatar::getAnimationRoles() { return _skeletonModel->getRig().getAnimationRoles(); } -void MyAvatar::overrideRoleAnimation(const QString& role, - const QString& url, - float fps, - bool loop, - float firstFrame, - float lastFrame) { +void MyAvatar::overrideRoleAnimation(const QString& role, const QString& url, float fps, bool loop, + float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "overrideRoleAnimation", Q_ARG(const QString&, role), Q_ARG(const QString&, url), Q_ARG(float, fps), Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); @@ -1249,9 +1259,9 @@ void MyAvatar::restoreRoleAnimation(const QString& role) { void MyAvatar::saveAvatarUrl() { if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid()) { - _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() - ? "" - : _fullAvatarURLFromPreferences.toString()); + _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() ? + "" : + _fullAvatarURLFromPreferences.toString()); } } @@ -1268,12 +1278,10 @@ void MyAvatar::resizeAvatarEntitySettingHandles(uint32_t maxIndex) { uint32_t settingsIndex = (uint32_t)_avatarEntityIDSettings.size() + 1; while (settingsIndex <= maxIndex) { Setting::Handle idHandle(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" - << QString::number(settingsIndex) << "id", - QUuid()); + << QString::number(settingsIndex) << "id", QUuid()); _avatarEntityIDSettings.push_back(idHandle); Setting::Handle dataHandle(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" - << QString::number(settingsIndex) << "properties", - QByteArray()); + << QString::number(settingsIndex) << "properties", QByteArray()); _avatarEntityDataSettings.push_back(dataHandle); settingsIndex++; } @@ -1291,10 +1299,10 @@ void MyAvatar::saveData() { // only save the fullAvatarURL if it has not been overwritten on command line // (so the overrideURL is not valid), or it was overridden _and_ we specified // --replaceAvatarURL (so _saveAvatarOverrideUrl is true) - if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid()) { - _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() - ? "" - : _fullAvatarURLFromPreferences.toString()); + if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid() ) { + _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() ? + "" : + _fullAvatarURLFromPreferences.toString()); } _fullAvatarModelNameSetting.set(_fullAvatarModelName); @@ -1464,12 +1472,16 @@ void MyAvatar::setEnableInverseKinematics(bool isEnabled) { void MyAvatar::storeAvatarEntityDataPayload(const QUuid& entityID, const QByteArray& payload) { AvatarData::storeAvatarEntityDataPayload(entityID, payload); - _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobsToAddOrUpdate.push_back(entityID); }); + _avatarEntitiesLock.withWriteLock([&] { + _cachedAvatarEntityBlobsToAddOrUpdate.push_back(entityID); + }); } void MyAvatar::clearAvatarEntity(const QUuid& entityID, bool requiresRemovalFromTree) { AvatarData::clearAvatarEntity(entityID, requiresRemovalFromTree); - _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobsToDelete.push_back(entityID); }); + _avatarEntitiesLock.withWriteLock([&] { + _cachedAvatarEntityBlobsToDelete.push_back(entityID); + }); } void MyAvatar::sanitizeAvatarEntityProperties(EntityItemProperties& properties) const { @@ -1494,7 +1506,9 @@ void MyAvatar::sanitizeAvatarEntityProperties(EntityItemProperties& properties) void MyAvatar::handleChangedAvatarEntityData() { // NOTE: this is a per-frame update - if (getID().isNull() || getID() == AVATAR_SELF_ID || DependencyManager::get()->getSessionUUID() == QUuid()) { + if (getID().isNull() || + getID() == AVATAR_SELF_ID || + DependencyManager::get()->getSessionUUID() == QUuid()) { // wait until MyAvatar and this Node gets an ID before doing this. Otherwise, various things go wrong: // things get their parent fixed up from AVATAR_SELF_ID to a null uuid which means "no parent". return; @@ -1540,7 +1554,7 @@ void MyAvatar::handleChangedAvatarEntityData() { entitiesToUpdate = std::move(_entitiesToUpdate); }); - auto removeAllInstancesHelper = [](const QUuid& id, std::vector& v) { + auto removeAllInstancesHelper = [] (const QUuid& id, std::vector& v) { uint32_t i = 0; while (i < v.size()) { if (id == v[i]) { @@ -1568,7 +1582,9 @@ void MyAvatar::handleChangedAvatarEntityData() { // DELETE real entities for (const auto& id : entitiesToDelete) { - entityTree->withWriteLock([&] { entityTree->deleteEntity(id); }); + entityTree->withWriteLock([&] { + entityTree->deleteEntity(id); + }); } // ADD real entities @@ -1579,19 +1595,21 @@ void MyAvatar::handleChangedAvatarEntityData() { _avatarEntitiesLock.withReadLock([&] { AvatarEntityMap::iterator itr = _cachedAvatarEntityBlobs.find(id); if (itr == _cachedAvatarEntityBlobs.end()) { - blobFailed = true; // blob doesn't exist + blobFailed = true; // blob doesn't exist return; } std::lock_guard guard(_scriptEngineLock); if (!EntityItemProperties::blobToProperties(*_scriptEngine, itr.value(), properties)) { - blobFailed = true; // blob is corrupt + blobFailed = true; // blob is corrupt } }); if (blobFailed) { // remove from _cachedAvatarEntityBlobUpdatesToSkip just in case: // avoids a resource leak when blob updates to be skipped are never actually skipped // when the blob fails to result in a real EntityItem - _avatarEntitiesLock.withWriteLock([&] { removeAllInstancesHelper(id, _cachedAvatarEntityBlobUpdatesToSkip); }); + _avatarEntitiesLock.withWriteLock([&] { + removeAllInstancesHelper(id, _cachedAvatarEntityBlobUpdatesToSkip); + }); continue; } sanitizeAvatarEntityProperties(properties); @@ -1661,7 +1679,7 @@ void MyAvatar::handleChangedAvatarEntityData() { _cachedAvatarEntityBlobUpdatesToSkip[i] = _cachedAvatarEntityBlobUpdatesToSkip.back(); _cachedAvatarEntityBlobUpdatesToSkip.pop_back(); skip = true; - break; // assume no duplicates + break; // assume no duplicates } else { ++i; } @@ -1725,7 +1743,9 @@ bool MyAvatar::updateStaleAvatarEntityBlobs() const { std::lock_guard guard(_scriptEngineLock); EntityItemProperties::propertiesToBlob(*_scriptEngine, getID(), properties, blob); } - _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobs[id] = blob; }); + _avatarEntitiesLock.withWriteLock([&] { + _cachedAvatarEntityBlobs[id] = blob; + }); } } return true; @@ -1752,7 +1772,9 @@ AvatarEntityMap MyAvatar::getAvatarEntityData() const { // NOTE: the return value is expected to be a map of unfortunately-formatted-binary-blobs updateStaleAvatarEntityBlobs(); AvatarEntityMap result; - _avatarEntitiesLock.withReadLock([&] { result = _cachedAvatarEntityBlobs; }); + _avatarEntitiesLock.withReadLock([&] { + result = _cachedAvatarEntityBlobs; + }); return result; } @@ -1853,9 +1875,7 @@ void MyAvatar::avatarEntityDataToJson(QJsonObject& root) const { AvatarEntityMap::const_iterator itr = _cachedAvatarEntityBlobs.begin(); while (itr != _cachedAvatarEntityBlobs.end()) { QVariantMap entityData; - QUuid id = _avatarEntityForRecording.size() == _cachedAvatarEntityBlobs.size() - ? _avatarEntityForRecording.values()[entityCount++] - : itr.key(); + QUuid id = _avatarEntityForRecording.size() == _cachedAvatarEntityBlobs.size() ? _avatarEntityForRecording.values()[entityCount++] : itr.key(); entityData.insert("id", id); entityData.insert("properties", itr.value().toBase64()); avatarEntityJson.push_back(QVariant(entityData).toJsonObject()); @@ -1885,7 +1905,7 @@ void MyAvatar::loadData() { loadAvatarEntityDataFromSettings(); // Flying preferences must be loaded before calling setFlyingEnabled() - Setting::Handle firstRunVal{ Settings::firstRun, true }; + Setting::Handle firstRunVal { Settings::firstRun, true }; setFlyingHMDPref(firstRunVal.get() ? false : _flyingHMDSetting.get()); setMovementReference(firstRunVal.get() ? false : _movementReferenceSetting.get()); setDriveGear1(firstRunVal.get() ? DEFAULT_GEAR_1 : _driveGear1Setting.get()); @@ -1911,7 +1931,7 @@ void MyAvatar::loadData() { setUserRecenterModel(stringToUserRecenterModel(_userRecenterModelSetting.get(USER_RECENTER_MODEL_AUTO))); setEnableMeshVisible(Menu::getInstance()->isOptionChecked(MenuOption::MeshVisible)); - _follow.setToggleHipsFollowing(Menu::getInstance()->isOptionChecked(MenuOption::ToggleHipsFollowing)); + _follow.setToggleHipsFollowing (Menu::getInstance()->isOptionChecked(MenuOption::ToggleHipsFollowing)); setEnableDebugDrawBaseOfSupport(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawBaseOfSupport)); setEnableDebugDrawDefaultPose(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawDefaultPose)); setEnableDebugDrawAnimPose(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawAnimPose)); @@ -1939,7 +1959,7 @@ void MyAvatar::loadAvatarEntityDataFromSettings() { _entitiesToAdd.reserve(numEntities); // TODO: build map between old and new IDs so we can restitch parent-child relationships for (int i = 0; i < numEntities; i++) { - QUuid id = QUuid::createUuid(); // generate a new ID + QUuid id = QUuid::createUuid(); // generate a new ID _cachedAvatarEntityBlobs[id] = _avatarEntityDataSettings[i].get(); _entitiesToAdd.push_back(id); // this blob is the "authoritative source" for this AvatarEntity and we want to avoid overwriting it @@ -2009,9 +2029,10 @@ AttachmentData MyAvatar::loadAttachmentData(const QUrl& modelURL, const QString& return attachment; } + int MyAvatar::parseDataFromBuffer(const QByteArray& buffer) { qCDebug(interfaceapp) << "Error: ignoring update packet for MyAvatar" - << " packetLength = " << buffer.size(); + << " packetLength = " << buffer.size(); // this packet is just bad, so we pretend that we unpacked it ALL return buffer.size(); } @@ -2025,12 +2046,8 @@ ScriptAvatarData* MyAvatar::getTargetAvatar() const { } } -static float lookAtCostFunction(const glm::vec3& myForward, - const glm::vec3& myPosition, - const glm::vec3& otherForward, - const glm::vec3& otherPosition, - bool otherIsTalking, - bool lookingAtOtherAlready) { +static float lookAtCostFunction(const glm::vec3& myForward, const glm::vec3& myPosition, const glm::vec3& otherForward, const glm::vec3& otherPosition, + bool otherIsTalking, bool lookingAtOtherAlready) { const float DISTANCE_FACTOR = 3.14f; const float MY_ANGLE_FACTOR = 1.0f; const float OTHER_ANGLE_FACTOR = 1.0f; @@ -2038,7 +2055,7 @@ static float lookAtCostFunction(const glm::vec3& myForward, const float LOOKING_AT_OTHER_ALREADY_TERM = lookingAtOtherAlready ? -0.2f : 0.0f; const float GREATEST_LOOKING_AT_DISTANCE = 10.0f; // meters - const float MAX_MY_ANGLE = PI / 8.0f; // 22.5 degrees, Don't look too far away from the head facing. + const float MAX_MY_ANGLE = PI / 8.0f; // 22.5 degrees, Don't look too far away from the head facing. const float MAX_OTHER_ANGLE = (3.0f * PI) / 4.0f; // 135 degrees, Don't stare at the back of another avatars head. glm::vec3 d = otherPosition - myPosition; @@ -2050,8 +2067,11 @@ static float lookAtCostFunction(const glm::vec3& myForward, if (distance > GREATEST_LOOKING_AT_DISTANCE || myAngle > MAX_MY_ANGLE || otherAngle > MAX_OTHER_ANGLE) { return FLT_MAX; } else { - return (DISTANCE_FACTOR * distance + MY_ANGLE_FACTOR * myAngle + OTHER_ANGLE_FACTOR * otherAngle + - OTHER_IS_TALKING_TERM + LOOKING_AT_OTHER_ALREADY_TERM); + return (DISTANCE_FACTOR * distance + + MY_ANGLE_FACTOR * myAngle + + OTHER_ANGLE_FACTOR * otherAngle + + OTHER_IS_TALKING_TERM + + LOOKING_AT_OTHER_ALREADY_TERM); } } @@ -2074,8 +2094,7 @@ void MyAvatar::computeMyLookAtTarget(const AvatarHash& hash) { const float TIME_WITHOUT_TALKING_THRESHOLD = 1.0f; bool otherIsTalking = avatar->getHead()->getTimeWithoutTalking() <= TIME_WITHOUT_TALKING_THRESHOLD; bool lookingAtOtherAlready = _lookAtTargetAvatar.lock().get() == avatar.get(); - float cost = - lookAtCostFunction(myForward, myPosition, otherForward, otherPosition, otherIsTalking, lookingAtOtherAlready); + float cost = lookAtCostFunction(myForward, myPosition, otherForward, otherPosition, otherIsTalking, lookingAtOtherAlready); if (cost < bestCost) { bestCost = cost; bestAvatar = avatar; @@ -2096,8 +2115,9 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { std::shared_ptr avatar = std::static_pointer_cast(avatarData); if (!avatar->isMyAvatar() && avatar->isInitialized()) { if (_lookAtSnappingEnabled && avatar->getLookAtSnappingEnabled() && isLookingAtMe(avatar)) { + // Alter their gaze to look directly at my camera; this looks more natural than looking at my avatar's face. - glm::vec3 lookAtPosition = avatar->getHead()->getLookAtPosition(); // A position, in world space, on my avatar. + glm::vec3 lookAtPosition = avatar->getHead()->getLookAtPosition(); // A position, in world space, on my avatar. // The camera isn't at the point midway between the avatar eyes. (Even without an HMD, the head can be offset a bit.) // Let's get everything to world space: @@ -2108,12 +2128,12 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { // (We will be adding that offset to the camera position, after making some other adjustments.) glm::vec3 gazeOffset = lookAtPosition - getHead()->getEyePosition(); - ViewFrustum viewFrustum; - qApp->copyViewFrustum(viewFrustum); + ViewFrustum viewFrustum; + qApp->copyViewFrustum(viewFrustum); - glm::vec3 viewPosition = viewFrustum.getPosition(); + glm::vec3 viewPosition = viewFrustum.getPosition(); #if DEBUG_ALWAYS_LOOKAT_EYES_NOT_CAMERA - viewPosition = (avatarLeftEye + avatarRightEye) / 2.0f; + viewPosition = (avatarLeftEye + avatarRightEye) / 2.0f; #endif // scale gazeOffset by IPD, if wearing an HMD. if (qApp->isHMDMode()) { @@ -2151,6 +2171,7 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { } void MyAvatar::updateLookAtTargetAvatar() { + // The AvatarManager is a mutable class shared by many threads. We make a thread-safe deep copy of it, // to avoid having to hold a lock while we iterate over all the avatars within. AvatarHash hash = DependencyManager::get()->getHashCopy(); @@ -2264,7 +2285,8 @@ void MyAvatar::setJointTranslation(int index, const glm::vec3& translation) { } default: { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "setJointTranslation", Q_ARG(int, index), Q_ARG(const glm::vec3&, translation)); + QMetaObject::invokeMethod(this, "setJointTranslation", + Q_ARG(int, index), Q_ARG(const glm::vec3&, translation)); return; } // HACK: ATM only JS scripts call setJointData() on MyAvatar so we hardcode the priority @@ -2303,7 +2325,9 @@ void MyAvatar::setJointData(const QString& name, const glm::quat& rotation, cons Q_ARG(const glm::vec3&, translation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { setJointData(index, rotation, translation); }); + writeLockWithNamedJointIndex(name, [&](int index) { + setJointData(index, rotation, translation); + }); } void MyAvatar::setJointRotation(const QString& name, const glm::quat& rotation) { @@ -2311,7 +2335,9 @@ void MyAvatar::setJointRotation(const QString& name, const glm::quat& rotation) QMetaObject::invokeMethod(this, "setJointRotation", Q_ARG(QString, name), Q_ARG(const glm::quat&, rotation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { setJointRotation(index, rotation); }); + writeLockWithNamedJointIndex(name, [&](int index) { + setJointRotation(index, rotation); + }); } void MyAvatar::setJointTranslation(const QString& name, const glm::vec3& translation) { @@ -2319,7 +2345,9 @@ void MyAvatar::setJointTranslation(const QString& name, const glm::vec3& transla QMetaObject::invokeMethod(this, "setJointTranslation", Q_ARG(QString, name), Q_ARG(const glm::vec3&, translation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { setJointTranslation(index, translation); }); + writeLockWithNamedJointIndex(name, [&](int index) { + setJointTranslation(index, translation); + }); } void MyAvatar::clearJointData(const QString& name) { @@ -2327,7 +2355,9 @@ void MyAvatar::clearJointData(const QString& name) { QMetaObject::invokeMethod(this, "clearJointData", Q_ARG(QString, name)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { clearJointData(index); }); + writeLockWithNamedJointIndex(name, [&](int index) { + clearJointData(index); + }); } void MyAvatar::clearJointsData() { @@ -2362,36 +2392,36 @@ void MyAvatar::setSkeletonModelURL(const QUrl& skeletonModelURL) { _skeletonModelLoaded = false; std::shared_ptr skeletonConnection = std::make_shared(); - *skeletonConnection = QObject::connect(_skeletonModel.get(), &SkeletonModel::skeletonLoaded, - [this, skeletonModelChangeCount, skeletonConnection]() { - if (skeletonModelChangeCount == _skeletonModelChangeCount) { - if (_fullAvatarModelName.isEmpty()) { - // Store the FST file name into preferences - const auto& mapping = _skeletonModel->getGeometry()->getMapping(); - if (mapping.value("name").isValid()) { - _fullAvatarModelName = mapping.value("name").toString(); - } - } + *skeletonConnection = QObject::connect(_skeletonModel.get(), &SkeletonModel::skeletonLoaded, [this, skeletonModelChangeCount, skeletonConnection]() { + if (skeletonModelChangeCount == _skeletonModelChangeCount) { - initHeadBones(); - _skeletonModel->setCauterizeBoneSet(_headBoneSet); - _fstAnimGraphOverrideUrl = - _skeletonModel->getGeometry()->getAnimGraphOverrideUrl(); - initAnimGraph(); - initFlowFromFST(); + if (_fullAvatarModelName.isEmpty()) { + // Store the FST file name into preferences + const auto& mapping = _skeletonModel->getGeometry()->getMapping(); + if (mapping.value("name").isValid()) { + _fullAvatarModelName = mapping.value("name").toString(); + } + } - _skeletonModelLoaded = true; - } - QObject::disconnect(*skeletonConnection); - }); + initHeadBones(); + _skeletonModel->setCauterizeBoneSet(_headBoneSet); + _fstAnimGraphOverrideUrl = _skeletonModel->getGeometry()->getAnimGraphOverrideUrl(); + initAnimGraph(); + initFlowFromFST(); + _skeletonModelLoaded = true; + } + QObject::disconnect(*skeletonConnection); + }); + saveAvatarUrl(); emit skeletonChanged(); } bool isWearableEntity(const EntityItemPointer& entity) { - return entity->isVisible() && (entity->getParentID() == DependencyManager::get()->getSessionUUID() || - entity->getParentID() == AVATAR_SELF_ID); + return entity->isVisible() + && (entity->getParentID() == DependencyManager::get()->getSessionUUID() + || entity->getParentID() == AVATAR_SELF_ID); } void MyAvatar::removeWornAvatarEntity(const EntityItemID& entityID) { @@ -2415,7 +2445,9 @@ void MyAvatar::removeWornAvatarEntity(const EntityItemID& entityID) { void MyAvatar::clearWornAvatarEntities() { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); + _avatarEntitiesLock.withReadLock([&] { + avatarEntityIDs = _packedAvatarEntityData.keys(); + }); for (auto entityID : avatarEntityIDs) { removeWornAvatarEntity(entityID); } @@ -2441,7 +2473,9 @@ QVariantList MyAvatar::getAvatarEntitiesVariant() { EntityTreePointer entityTree = treeRenderer ? treeRenderer->getTree() : nullptr; if (entityTree) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); + _avatarEntitiesLock.withReadLock([&] { + avatarEntityIDs = _packedAvatarEntityData.keys(); + }); for (const auto& entityID : avatarEntityIDs) { auto entity = entityTree->findEntityByID(entityID); if (!entity) { @@ -2466,6 +2500,7 @@ QVariantList MyAvatar::getAvatarEntitiesVariant() { return avatarEntitiesData; } + void MyAvatar::resetFullAvatarURL() { auto lastAvatarURL = getFullAvatarURLFromPreferences(); auto lastAvatarName = getFullAvatarModelName(); @@ -2474,8 +2509,11 @@ void MyAvatar::resetFullAvatarURL() { } void MyAvatar::useFullAvatarURL(const QUrl& fullAvatarURL, const QString& modelName) { + if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "useFullAvatarURL", Q_ARG(const QUrl&, fullAvatarURL), Q_ARG(const QString&, modelName)); + BLOCKING_INVOKE_METHOD(this, "useFullAvatarURL", + Q_ARG(const QUrl&, fullAvatarURL), + Q_ARG(const QString&, modelName)); return; } @@ -2529,7 +2567,7 @@ controller::Pose MyAvatar::getControllerPoseInSensorFrame(controller::Action act if (iter != _controllerPoseMap.end()) { return iter->second; } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2538,7 +2576,7 @@ controller::Pose MyAvatar::getControllerPoseInWorldFrame(controller::Action acti if (pose.valid) { return pose.transform(getSensorToWorldMatrix()); } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2548,7 +2586,7 @@ controller::Pose MyAvatar::getControllerPoseInAvatarFrame(controller::Action act glm::mat4 invAvatarMatrix = glm::inverse(createMatFromQuatAndPos(getWorldOrientation(), getWorldPosition())); return pose.transform(invAvatarMatrix); } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2570,7 +2608,7 @@ void MyAvatar::updateMotors() { float verticalMotorTimescale; if (_characterController.getState() == CharacterController::State::Hover || - _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { + _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { horizontalMotorTimescale = FLYING_MOTOR_TIMESCALE; verticalMotorTimescale = FLYING_MOTOR_TIMESCALE; } else { @@ -2580,7 +2618,7 @@ void MyAvatar::updateMotors() { if (_motionBehaviors & AVATAR_MOTION_ACTION_MOTOR_ENABLED) { if (_characterController.getState() == CharacterController::State::Hover || - _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { + _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { motorRotation = getMyHead()->getHeadOrientation(); } else { // non-hovering = walking: follow camera twist about vertical but not lift @@ -2588,15 +2626,14 @@ void MyAvatar::updateMotors() { // however, we need to perform the decomposition in the avatar-frame // using the local UP axis and then transform back into world-frame glm::quat orientation = getWorldOrientation(); - glm::quat headOrientation = glm::inverse(orientation) * getMyHead()->getHeadOrientation(); // avatar-frame + glm::quat headOrientation = glm::inverse(orientation) * getMyHead()->getHeadOrientation(); // avatar-frame glm::quat liftRotation; swingTwistDecomposition(headOrientation, Vectors::UNIT_Y, liftRotation, motorRotation); motorRotation = orientation * motorRotation; } if (_isPushing || _isBraking || !_isBeingPushed) { - _characterController.addMotor(_actionMotorVelocity, motorRotation, horizontalMotorTimescale, - verticalMotorTimescale); + _characterController.addMotor(_actionMotorVelocity, motorRotation, horizontalMotorTimescale, verticalMotorTimescale); } else { // _isBeingPushed must be true --> disable action motor by giving it a long timescale, // otherwise it's attempt to "stand in in place" could defeat scripted motor/thrusts @@ -2616,8 +2653,7 @@ void MyAvatar::updateMotors() { _characterController.addMotor(_scriptedMotorVelocity, motorRotation, _scriptedMotorTimescale); } else { // dynamic mode - _characterController.addMotor(_scriptedMotorVelocity, motorRotation, horizontalMotorTimescale, - verticalMotorTimescale); + _characterController.addMotor(_scriptedMotorVelocity, motorRotation, horizontalMotorTimescale, verticalMotorTimescale); } } @@ -2722,7 +2758,8 @@ void MyAvatar::setScriptedMotorVelocity(const glm::vec3& velocity) { void MyAvatar::setScriptedMotorTimescale(float timescale) { // we clamp the timescale on the large side (instead of just the low side) to prevent // obnoxiously large values from introducing NaN into avatar's velocity - _scriptedMotorTimescale = glm::clamp(timescale, MIN_SCRIPTED_MOTOR_TIMESCALE, DEFAULT_SCRIPTED_MOTOR_TIMESCALE); + _scriptedMotorTimescale = glm::clamp(timescale, MIN_SCRIPTED_MOTOR_TIMESCALE, + DEFAULT_SCRIPTED_MOTOR_TIMESCALE); } void MyAvatar::setScriptedMotorFrame(QString frame) { @@ -2763,18 +2800,21 @@ SharedSoundPointer MyAvatar::getCollisionSound() { return _collisionSound; } -void MyAvatar::attach(const QString& modelURL, - const QString& jointName, - const glm::vec3& translation, - const glm::quat& rotation, - float scale, - bool isSoft, - bool allowDuplicates, - bool useSaved) { +void MyAvatar::attach(const QString& modelURL, const QString& jointName, + const glm::vec3& translation, const glm::quat& rotation, + float scale, bool isSoft, + bool allowDuplicates, bool useSaved) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "attach", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName), - Q_ARG(const glm::vec3&, translation), Q_ARG(const glm::quat&, rotation), Q_ARG(float, scale), - Q_ARG(bool, isSoft), Q_ARG(bool, allowDuplicates), Q_ARG(bool, useSaved)); + BLOCKING_INVOKE_METHOD(this, "attach", + Q_ARG(const QString&, modelURL), + Q_ARG(const QString&, jointName), + Q_ARG(const glm::vec3&, translation), + Q_ARG(const glm::quat&, rotation), + Q_ARG(float, scale), + Q_ARG(bool, isSoft), + Q_ARG(bool, allowDuplicates), + Q_ARG(bool, useSaved) + ); return; } AttachmentData data; @@ -2792,7 +2832,10 @@ void MyAvatar::attach(const QString& modelURL, void MyAvatar::detachOne(const QString& modelURL, const QString& jointName) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "detachOne", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName)); + BLOCKING_INVOKE_METHOD(this, "detachOne", + Q_ARG(const QString&, modelURL), + Q_ARG(const QString&, jointName) + ); return; } QUuid entityID; @@ -2804,7 +2847,10 @@ void MyAvatar::detachOne(const QString& modelURL, const QString& jointName) { void MyAvatar::detachAll(const QString& modelURL, const QString& jointName) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "detachAll", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName)); + BLOCKING_INVOKE_METHOD(this, "detachAll", + Q_ARG(const QString&, modelURL), + Q_ARG(const QString&, jointName) + ); return; } QUuid entityID; @@ -2816,7 +2862,8 @@ void MyAvatar::detachAll(const QString& modelURL, const QString& jointName) { void MyAvatar::setAttachmentData(const QVector& attachmentData) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "setAttachmentData", Q_ARG(const QVector&, attachmentData)); + BLOCKING_INVOKE_METHOD(this, "setAttachmentData", + Q_ARG(const QVector&, attachmentData)); return; } std::vector newEntitiesProperties; @@ -2839,10 +2886,12 @@ void MyAvatar::setAttachmentData(const QVector& attachmentData) emit attachmentsChanged(); } -QVector MyAvatar::getAttachmentData() const { +QVector MyAvatar::getAttachmentData() const { QVector attachmentData; QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); + _avatarEntitiesLock.withReadLock([&] { + avatarEntityIDs = _packedAvatarEntityData.keys(); + }); for (const auto& entityID : avatarEntityIDs) { auto properties = DependencyManager::get()->getEntityProperties(entityID); AttachmentData data = entityPropertiesToAttachmentData(properties); @@ -2861,7 +2910,8 @@ QVariantList MyAvatar::getAttachmentsVariant() const { void MyAvatar::setAttachmentsVariant(const QVariantList& variant) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "setAttachmentsVariant", Q_ARG(const QVariantList&, variant)); + BLOCKING_INVOKE_METHOD(this, "setAttachmentsVariant", + Q_ARG(const QVariantList&, variant)); return; } QVector newAttachments; @@ -2872,12 +2922,14 @@ void MyAvatar::setAttachmentsVariant(const QVariantList& variant) { newAttachments.append(attachment); } } - setAttachmentData(newAttachments); + setAttachmentData(newAttachments); } bool MyAvatar::findAvatarEntity(const QString& modelURL, const QString& jointName, QUuid& entityID) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); + _avatarEntitiesLock.withReadLock([&] { + avatarEntityIDs = _packedAvatarEntityData.keys(); + }); for (const auto& entityID : avatarEntityIDs) { auto props = DependencyManager::get()->getEntityProperties(entityID); if (props.getModelURL() == modelURL && @@ -2978,7 +3030,7 @@ void MyAvatar::setAnimGraphUrl(const QUrl& url) { emit animGraphUrlChanged(url); destroyAnimGraph(); - _skeletonModel->reset(); // Why is this necessary? Without this, we crash in the next render. + _skeletonModel->reset(); // Why is this necessary? Without this, we crash in the next render. _currentAnimGraphUrl.set(url); _skeletonModel->getRig().initAnimGraph(url); @@ -3011,16 +3063,18 @@ void MyAvatar::destroyAnimGraph() { } void MyAvatar::animGraphLoaded() { - _bodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. - updateSensorToWorldMatrix(); // Uses updated position/orientation and _bodySensorMatrix changes + _bodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + updateSensorToWorldMatrix(); // Uses updated position/orientation and _bodySensorMatrix changes _isAnimatingScale = true; _cauterizationNeedsUpdate = true; disconnect(&(_skeletonModel->getRig()), SIGNAL(onLoadComplete()), this, SLOT(animGraphLoaded())); } void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { + Avatar::postUpdate(deltaTime, scene); if (_enableDebugDrawDefaultPose || _enableDebugDrawAnimPose) { + auto animSkeleton = _skeletonModel->getRig().getAnimSkeleton(); // the rig is in the skeletonModel frame @@ -3028,8 +3082,7 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { if (_enableDebugDrawDefaultPose && animSkeleton) { glm::vec4 gray(0.2f, 0.2f, 0.2f, 0.2f); - AnimDebugDraw::getInstance().addAbsolutePoses("myAvatarDefaultPoses", animSkeleton, - _skeletonModel->getRig().getAbsoluteDefaultPoses(), xform, gray); + AnimDebugDraw::getInstance().addAbsolutePoses("myAvatarDefaultPoses", animSkeleton, _skeletonModel->getRig().getAbsoluteDefaultPoses(), xform, gray); } if (_enableDebugDrawAnimPose && animSkeleton) { @@ -3050,15 +3103,13 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { auto rightHandPose = getControllerPoseInWorldFrame(controller::Action::RIGHT_HAND); if (leftHandPose.isValid()) { - DebugDraw::getInstance().addMarker("leftHandController", leftHandPose.getRotation(), leftHandPose.getTranslation(), - glm::vec4(1)); + DebugDraw::getInstance().addMarker("leftHandController", leftHandPose.getRotation(), leftHandPose.getTranslation(), glm::vec4(1)); } else { DebugDraw::getInstance().removeMarker("leftHandController"); } if (rightHandPose.isValid()) { - DebugDraw::getInstance().addMarker("rightHandController", rightHandPose.getRotation(), - rightHandPose.getTranslation(), glm::vec4(1)); + DebugDraw::getInstance().addMarker("rightHandController", rightHandPose.getRotation(), rightHandPose.getTranslation(), glm::vec4(1)); } else { DebugDraw::getInstance().removeMarker("rightHandController"); } @@ -3075,9 +3126,14 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { AnimPose rigToWorldPose(glm::vec3(1.0f), getWorldOrientation() * Quaternions::Y_180, getWorldPosition()); const int NUM_DEBUG_COLORS = 8; const glm::vec4 DEBUG_COLORS[NUM_DEBUG_COLORS] = { - glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 1.0f), - glm::vec4(0.25f, 0.25f, 1.0f, 1.0f), glm::vec4(1.0f, 1.0f, 0.0f, 1.0f), glm::vec4(0.25f, 1.0f, 1.0f, 1.0f), - glm::vec4(1.0f, 0.25f, 1.0f, 1.0f), glm::vec4(1.0f, 0.65f, 0.0f, 1.0f) // Orange you glad I added this color? + glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), + glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), + glm::vec4(0.0f, 1.0f, 0.0f, 1.0f), + glm::vec4(0.25f, 0.25f, 1.0f, 1.0f), + glm::vec4(1.0f, 1.0f, 0.0f, 1.0f), + glm::vec4(0.25f, 1.0f, 1.0f, 1.0f), + glm::vec4(1.0f, 0.25f, 1.0f, 1.0f), + glm::vec4(1.0f, 0.65f, 0.0f, 1.0f) // Orange you glad I added this color? }; if (_skeletonModel && _skeletonModel->isLoaded()) { @@ -3088,7 +3144,7 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { AnimPose jointPose; rig.getAbsoluteJointPoseInRigFrame(i, jointPose); const AnimPose pose = rigToWorldPose * jointPose; - auto& multiSphere = _multiSphereShapes[i]; + auto &multiSphere = _multiSphereShapes[i]; auto debugLines = multiSphere.getDebugLines(); DebugDraw::getInstance().drawRays(debugLines, DEBUG_COLORS[i % NUM_DEBUG_COLORS], pose.trans(), pose.rot()); } @@ -3098,6 +3154,7 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { } void MyAvatar::preDisplaySide(const RenderArgs* renderArgs) { + // toggle using the cauterizedBones depending on where the camera is and the rendering pass type. const bool shouldDrawHead = shouldRenderHead(renderArgs); if (shouldDrawHead != _prevShouldDrawHead) { @@ -3142,7 +3199,7 @@ int MyAvatar::sendAvatarDataPacket(bool sendAll) { // Compute the next send window based on how much data we sent and what // data rate we're trying to max at. - milliseconds timeUntilNextSend{ bytesSent / maxDataRateBytesPerMilliseconds }; + milliseconds timeUntilNextSend { bytesSent / maxDataRateBytesPerMilliseconds }; _nextTraitsSendWindow += timeUntilNextSend; // Don't let the next send window lag behind if we're not sending a lot of data. @@ -3227,6 +3284,7 @@ void MyAvatar::setRotationThreshold(float angleRadians) { } void MyAvatar::updateOrientation(float deltaTime) { + // Smoothly rotate body with arrow keys float targetSpeed = getDriveKey(YAW) * _yawSpeed; if (targetSpeed != 0.0f) { @@ -3265,8 +3323,8 @@ void MyAvatar::updateOrientation(float deltaTime) { } // Use head/HMD roll to turn while flying, but not when standing still. - if (qApp->isHMDMode() && getCharacterController()->getState() == CharacterController::State::Hover && - _hmdRollControlEnabled && hasDriveInput()) { + if (qApp->isHMDMode() && getCharacterController()->getState() == CharacterController::State::Hover && _hmdRollControlEnabled && hasDriveInput()) { + // Turn with head roll. const float MIN_CONTROL_SPEED = 2.0f * getSensorToWorldScale(); // meters / sec const glm::vec3 characterForward = getWorldOrientation() * Vectors::UNIT_NEG_Z; @@ -3274,6 +3332,7 @@ void MyAvatar::updateOrientation(float deltaTime) { // only enable roll-turns if we are moving forward or backward at greater then MIN_CONTROL_SPEED if (fabsf(forwardSpeed) >= MIN_CONTROL_SPEED) { + float direction = forwardSpeed > 0.0f ? 1.0f : -1.0f; float rollAngle = glm::degrees(asinf(glm::dot(IDENTITY_UP, _hmdSensorOrientation * IDENTITY_RIGHT))); float rollSign = rollAngle < 0.0f ? -1.0f : 1.0f; @@ -3320,8 +3379,8 @@ void MyAvatar::updateOrientation(float deltaTime) { head->setBaseRoll(ROLL(euler)); } else { head->setBaseYaw(0.0f); - head->setBasePitch(getHead()->getBasePitch() + getDriveKey(PITCH) * _pitchSpeed * deltaTime + - getDriveKey(DELTA_PITCH) * _pitchSpeed / PITCH_SPEED_DEFAULT); + head->setBasePitch(getHead()->getBasePitch() + getDriveKey(PITCH) * _pitchSpeed * deltaTime + + getDriveKey(DELTA_PITCH) * _pitchSpeed / PITCH_SPEED_DEFAULT); head->setBaseRoll(0.0f); } } @@ -3331,15 +3390,20 @@ float MyAvatar::calculateGearedSpeed(const float driveKey) { float sign = (driveKey < 0.0f) ? -1.0f : 1.0f; if (absDriveKey > getDriveGear5()) { return sign * 1.0f; - } else if (absDriveKey > getDriveGear4()) { + } + else if (absDriveKey > getDriveGear4()) { return sign * 0.8f; - } else if (absDriveKey > getDriveGear3()) { + } + else if (absDriveKey > getDriveGear3()) { return sign * 0.6f; - } else if (absDriveKey > getDriveGear2()) { + } + else if (absDriveKey > getDriveGear2()) { return sign * 0.4f; - } else if (absDriveKey > getDriveGear1()) { + } + else if (absDriveKey > getDriveGear1()) { return sign * 0.2f; - } else { + } + else { return sign * 0.0f; } } @@ -3371,10 +3435,8 @@ glm::vec3 MyAvatar::scaleMotorSpeed(const glm::vec3 forward, const glm::vec3 rig case LocomotionControlsMode::CONTROLS_ANALOG: case LocomotionControlsMode::CONTROLS_ANALOG_PLUS: if (zSpeed || xSpeed) { - glm::vec3 scaledForward = getSensorToWorldScale() * calculateGearedSpeed(zSpeed) * _walkSpeedScalar * - ((zSpeed >= stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * forward; - glm::vec3 scaledRight = getSensorToWorldScale() * calculateGearedSpeed(xSpeed) * _walkSpeedScalar * - ((xSpeed > stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * right; + glm::vec3 scaledForward = getSensorToWorldScale() * calculateGearedSpeed(zSpeed) * _walkSpeedScalar * ((zSpeed >= stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * forward; + glm::vec3 scaledRight = getSensorToWorldScale() * calculateGearedSpeed(xSpeed) * _walkSpeedScalar * ((xSpeed > stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * right; direction = scaledForward + scaledRight; return direction; } else { @@ -3396,7 +3458,7 @@ glm::vec3 MyAvatar::scaleMotorSpeed(const glm::vec3 forward, const glm::vec3 rig } } -glm::vec3 MyAvatar::calculateScaledDirection() { +glm::vec3 MyAvatar::calculateScaledDirection(){ CharacterController::State state = _characterController.getState(); // compute action input @@ -3452,8 +3514,8 @@ glm::vec3 MyAvatar::calculateScaledDirection() { void MyAvatar::updateActionMotor(float deltaTime) { bool thrustIsPushing = (glm::length2(_thrust) > EPSILON); - bool scriptedMotorIsPushing = - (_motionBehaviors & AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED) && _scriptedMotorTimescale < MAX_CHARACTER_MOTOR_TIMESCALE; + bool scriptedMotorIsPushing = (_motionBehaviors & AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED) + && _scriptedMotorTimescale < MAX_CHARACTER_MOTOR_TIMESCALE; _isBeingPushed = thrustIsPushing || scriptedMotorIsPushing; if (_isPushing || _isBeingPushed) { // we don't want the motor to brake if a script is pushing the avatar around @@ -3483,7 +3545,7 @@ void MyAvatar::updateActionMotor(float deltaTime) { float motorSpeed = glm::length(_actionMotorVelocity); float finalMaxMotorSpeed = sensorToWorldScale * DEFAULT_AVATAR_MAX_FLYING_SPEED * _walkSpeedScalar; - float speedGrowthTimescale = 2.0f; + float speedGrowthTimescale = 2.0f; float speedIncreaseFactor = 1.8f * _walkSpeedScalar; motorSpeed *= 1.0f + glm::clamp(deltaTime / speedGrowthTimescale, 0.0f, 1.0f) * speedIncreaseFactor; const float maxBoostSpeed = sensorToWorldScale * MAX_BOOST_SPEED; @@ -3523,7 +3585,7 @@ void MyAvatar::updatePosition(float deltaTime) { float sensorToWorldScale2 = sensorToWorldScale * sensorToWorldScale; vec3 velocity = getWorldVelocity(); float speed2 = glm::length2(velocity); - const float MOVING_SPEED_THRESHOLD_SQUARED = 0.0001f; // 0.01 m/s + const float MOVING_SPEED_THRESHOLD_SQUARED = 0.0001f; // 0.01 m/s _moving = speed2 > sensorToWorldScale2 * MOVING_SPEED_THRESHOLD_SQUARED; if (_moving) { // scan for walkability @@ -3548,17 +3610,12 @@ void MyAvatar::updateViewBoom() { } } -void MyAvatar::updateCollisionSound(const glm::vec3& penetration, float deltaTime, float frequency) { +void MyAvatar::updateCollisionSound(const glm::vec3 &penetration, float deltaTime, float frequency) { // COLLISION SOUND API in Audio has been removed } -bool findAvatarAvatarPenetration(const glm::vec3 positionA, - float radiusA, - float heightA, - const glm::vec3 positionB, - float radiusB, - float heightB, - glm::vec3& penetration) { +bool findAvatarAvatarPenetration(const glm::vec3 positionA, float radiusA, float heightA, + const glm::vec3 positionB, float radiusB, float heightB, glm::vec3& penetration) { glm::vec3 positionBA = positionB - positionA; float xzDistance = sqrt(positionBA.x * positionBA.x + positionBA.z * positionBA.z); if (xzDistance < (radiusA + radiusB)) { @@ -3620,7 +3677,9 @@ void MyAvatar::setSessionUUID(const QUuid& sessionUUID) { EntityTreePointer entityTree = treeRenderer ? treeRenderer->getTree() : nullptr; if (entityTree) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); + _avatarEntitiesLock.withReadLock([&] { + avatarEntityIDs = _packedAvatarEntityData.keys(); + }); bool sendPackets = !DependencyManager::get()->getSessionUUID().isNull(); EntityEditPacketSender* packetSender = qApp->getEntityEditPacketSender(); entityTree->withWriteLock([&] { @@ -3764,18 +3823,16 @@ void MyAvatar::goToLocation(const QVariant& propertiesVar) { } void MyAvatar::goToFeetLocation(const glm::vec3& newPosition, - bool hasOrientation, - const glm::quat& newOrientation, + bool hasOrientation, const glm::quat& newOrientation, bool shouldFaceLocation) { _goToFeetAjustment = true; goToLocation(newPosition, hasOrientation, newOrientation, shouldFaceLocation); } void MyAvatar::goToLocation(const glm::vec3& newPosition, - bool hasOrientation, - const glm::quat& newOrientation, - bool shouldFaceLocation, - bool withSafeLanding) { + bool hasOrientation, const glm::quat& newOrientation, + bool shouldFaceLocation, bool withSafeLanding) { + // Most cases of going to a place or user go through this now. Some possible improvements to think about in the future: // - It would be nice if this used the same teleport steps and smoothing as in the teleport.js script, as long as it // still worked if the target is in the air. @@ -3789,16 +3846,16 @@ void MyAvatar::goToLocation(const glm::vec3& newPosition, // compute the position (e.g., so that if I'm on stage, going to me would compute an available seat in the audience rather than // being in my face on-stage). Note that this could work for going to an entity as well as to a person. - qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - moving to " << newPosition.x << ", " << newPosition.y << ", " - << newPosition.z; + qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - moving to " << newPosition.x << ", " + << newPosition.y << ", " << newPosition.z; _goToPending = true; _goToPosition = newPosition; _goToSafe = withSafeLanding; _goToOrientation = getWorldOrientation(); if (hasOrientation) { - qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - new orientation is " << newOrientation.x << ", " - << newOrientation.y << ", " << newOrientation.z << ", " << newOrientation.w; + qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - new orientation is " + << newOrientation.x << ", " << newOrientation.y << ", " << newOrientation.z << ", " << newOrientation.w; // orient the user to face the target glm::quat quatOrientation = cancelOutRollAndPitch(newOrientation); @@ -3817,7 +3874,7 @@ void MyAvatar::goToLocation(const glm::vec3& newPosition, emit transformChanged(); } -void MyAvatar::goToLocationAndEnableCollisions(const glm::vec3& position) { // See use case in safeLanding. +void MyAvatar::goToLocationAndEnableCollisions(const glm::vec3& position) { // See use case in safeLanding. goToLocation(position); QMetaObject::invokeMethod(this, "setCollisionsEnabled", Qt::QueuedConnection, Q_ARG(bool, true)); } @@ -3843,29 +3900,29 @@ bool MyAvatar::safeLanding(const glm::vec3& position) { } if (!getCollisionsEnabled()) { goToLocation(better); // recurses on next update - } else { // If you try to go while stuck, physics will keep you stuck. + } else { // If you try to go while stuck, physics will keep you stuck. setCollisionsEnabled(false); // Don't goToLocation just yet. Yield so that physics can act on the above. - QMetaObject::invokeMethod(this, "goToLocationAndEnableCollisions", - Qt::QueuedConnection, // The equivalent of javascript nextTick - Q_ARG(glm::vec3, better)); - } - return true; + QMetaObject::invokeMethod(this, "goToLocationAndEnableCollisions", Qt::QueuedConnection, // The equivalent of javascript nextTick + Q_ARG(glm::vec3, better)); + } + return true; } // If position is not reliably safe from being stuck by physics, answer true and place a candidate better position in betterPositionOut. bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& betterPositionOut) { + // We begin with utilities and tests. The Algorithm in four parts is below. // NOTE: we use estimated avatar height here instead of the bullet capsule halfHeight, because // the domain avatar height limiting might not have taken effect yet on the actual bullet shape. auto halfHeight = 0.5f * getHeight(); if (halfHeight == 0) { - return false; // zero height avatar + return false; // zero height avatar } auto entityTree = DependencyManager::get()->getTree(); if (!entityTree) { - return false; // no entity tree + return false; // no entity tree } // More utilities. const auto capsuleCenter = positionIn; @@ -3877,26 +3934,21 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette betterPositionOut = upperIntersection + (up * halfHeight); return true; }; - auto findIntersection = [&](const glm::vec3& startPointIn, const glm::vec3& directionIn, glm::vec3& intersectionOut, - EntityItemID& entityIdOut, glm::vec3& normalOut) { + auto findIntersection = [&](const glm::vec3& startPointIn, const glm::vec3& directionIn, glm::vec3& intersectionOut, EntityItemID& entityIdOut, glm::vec3& normalOut) { OctreeElementPointer element; float distance; BoxFace face; - const auto lockType = Octree::Lock; // Should we refactor to take a lock just once? + const auto lockType = Octree::Lock; // Should we refactor to take a lock just once? bool* accurateResult = NULL; // This isn't quite what we really want here. findRayIntersection always works on mesh, skipping entirely based on collidable. // What we really want is to use the collision hull! // See https://highfidelity.fogbugz.com/f/cases/5003/findRayIntersection-has-option-to-use-collidableOnly-but-doesn-t-actually-use-colliders QVariantMap extraInfo; - EntityItemID entityID = - entityTree->evalRayIntersection(startPointIn, directionIn, include, ignore, - PickFilter(PickFilter::getBitMask(PickFilter::FlagBit::COLLIDABLE) | - PickFilter::getBitMask(PickFilter::FlagBit::PRECISE) | - PickFilter::getBitMask(PickFilter::FlagBit::DOMAIN_ENTITIES) | - PickFilter::getBitMask( - PickFilter::FlagBit::AVATAR_ENTITIES)), // exclude Local entities - element, distance, face, normalOut, extraInfo, lockType, accurateResult); + EntityItemID entityID = entityTree->evalRayIntersection(startPointIn, directionIn, include, ignore, + PickFilter(PickFilter::getBitMask(PickFilter::FlagBit::COLLIDABLE) | PickFilter::getBitMask(PickFilter::FlagBit::PRECISE) + | PickFilter::getBitMask(PickFilter::FlagBit::DOMAIN_ENTITIES) | PickFilter::getBitMask(PickFilter::FlagBit::AVATAR_ENTITIES)), // exclude Local entities + element, distance, face, normalOut, extraInfo, lockType, accurateResult); if (entityID.isNull()) { return false; } @@ -3911,12 +3963,12 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette // We currently believe that physics will reliably push us out if our feet are embedded, // as long as our capsule center is out and there's room above us. Here we have those // conditions, so no need to check our feet below. - return false; // nothing above + return false; // nothing above } if (!findIntersection(capsuleCenter, down, lowerIntersection, lowerId, lowerNormal)) { // Our head may be embedded, but our center is out and there's room below. See corresponding comment above. - return false; // nothing below + return false; // nothing below } // See if we have room between entities above and below, but that we are not contained. @@ -3924,8 +3976,7 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette // I.e., we are in a clearing between two objects. if (isDown(upperNormal) && isUp(lowerNormal)) { auto spaceBetween = glm::distance(upperIntersection, lowerIntersection); - const float halfHeightFactor = - 2.25f; // Until case 5003 is fixed (and maybe after?), we need a fudge factor. Also account for content modelers not being precise. + const float halfHeightFactor = 2.25f; // Until case 5003 is fixed (and maybe after?), we need a fudge factor. Also account for content modelers not being precise. if (spaceBetween > (halfHeightFactor * halfHeight)) { // There is room for us to fit in that clearing. If there wasn't, physics would oscilate us between the objects above and below. // We're now going to iterate upwards through successive upperIntersections, testing to see if we're contained within the top surface of some entity. @@ -3937,7 +3988,7 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette ignore.push_back(upperId); if (!findIntersection(upperIntersection, up, upperIntersection, upperId, upperNormal)) { // We're not inside an entity, and from the nested tests, we have room between what is above and below. So position is good! - return false; // enough room + return false; // enough room } if (isUp(upperNormal)) { // This new intersection is the top surface of an entity that we have not yet seen, which means we're contained within it. @@ -3952,18 +4003,19 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette } } - include.push_back(upperId); // We're now looking for the intersection from above onto this entity. + include.push_back(upperId); // We're now looking for the intersection from above onto this entity. const float big = (float)TREE_SCALE; const auto skyHigh = up * big; auto fromAbove = capsuleCenter + skyHigh; if (!findIntersection(fromAbove, down, upperIntersection, upperId, upperNormal)) { - return false; // Unable to find a landing + return false; // Unable to find a landing } // Our arbitrary rule is to always go up. There's no need to look down or sideways for a "closer" safe candidate. return mustMove(); } void MyAvatar::updateMotionBehaviorFromMenu() { + if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "updateMotionBehaviorFromMenu"); return; @@ -4047,7 +4099,7 @@ int MyAvatar::getMovementReference() { return _movementReference; } -void MyAvatar::setControlSchemeIndex(int index) { +void MyAvatar::setControlSchemeIndex(int index){ if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setControlSchemeIndex", Q_ARG(int, index)); return; @@ -4065,8 +4117,7 @@ void MyAvatar::setDriveGear1(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear1", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) - return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; _driveGear1 = (shiftPoint < _driveGear2) ? shiftPoint : _driveGear1; } @@ -4087,8 +4138,7 @@ void MyAvatar::setDriveGear2(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear2", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) - return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; _driveGear2 = (shiftPoint < _driveGear3 && shiftPoint >= _driveGear1) ? shiftPoint : _driveGear2; } @@ -4109,8 +4159,7 @@ void MyAvatar::setDriveGear3(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear3", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) - return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; _driveGear3 = (shiftPoint < _driveGear4 && shiftPoint >= _driveGear2) ? shiftPoint : _driveGear3; } @@ -4131,8 +4180,7 @@ void MyAvatar::setDriveGear4(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear4", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) - return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; _driveGear4 = (shiftPoint < _driveGear5 && shiftPoint >= _driveGear3) ? shiftPoint : _driveGear4; } @@ -4153,8 +4201,7 @@ void MyAvatar::setDriveGear5(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear5", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) - return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; _driveGear5 = (shiftPoint > _driveGear4) ? shiftPoint : _driveGear5; } @@ -4180,6 +4227,7 @@ float MyAvatar::getAvatarScale() { } void MyAvatar::setAvatarScale(float val) { + if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setAvatarScale", Q_ARG(float, val)); return; @@ -4189,6 +4237,7 @@ void MyAvatar::setAvatarScale(float val) { } void MyAvatar::setCollisionsEnabled(bool enabled) { + if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setCollisionsEnabled", Q_ARG(bool, enabled)); return; @@ -4204,6 +4253,7 @@ bool MyAvatar::getCollisionsEnabled() { } void MyAvatar::setOtherAvatarsCollisionsEnabled(bool enabled) { + if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setOtherAvatarsCollisionsEnabled", Q_ARG(bool, enabled)); return; @@ -4359,7 +4409,7 @@ glm::mat4 MyAvatar::deriveBodyFromHMDSensor() const { // AJT: TODO: can remove this Y_180, if we remove the higher level one. glm::vec3 headToNeck = headOrientation * Quaternions::Y_180 * (localNeck - localHead); - glm::vec3 neckToRoot = headOrientationYawOnly * Quaternions::Y_180 * -localNeck; + glm::vec3 neckToRoot = headOrientationYawOnly * Quaternions::Y_180 * -localNeck; float invSensorToWorldScale = getUserEyeHeight() / getEyeHeight(); glm::vec3 bodyPos = headPosition + invSensorToWorldScale * (headToNeck + neckToRoot); @@ -4395,8 +4445,7 @@ glm::mat4 MyAvatar::getSpine2RotationRigSpace() const { spine2UpRigSpace = glm::vec3(0.0f, 1.0f, 0.0f); } generateBasisVectors(spine2UpRigSpace, spine2FwdRigSpace, u, v, w); - glm::mat4 spine2RigSpace(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), - glm::vec4(glm::vec3(0.0f, 0.0f, 0.0f), 1.0f)); + glm::mat4 spine2RigSpace(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), glm::vec4(glm::vec3(0.0f, 0.0f, 0.0f), 1.0f)); return spine2RigSpace; } @@ -4453,7 +4502,7 @@ glm::vec3 MyAvatar::computeCounterBalance() { QString name; float weight; glm::vec3 position; - JointMass(){}; + JointMass() {}; JointMass(QString n, float w, glm::vec3 p) { name = n; weight = w; @@ -4474,14 +4523,12 @@ glm::vec3 MyAvatar::computeCounterBalance() { tposeHead = getAbsoluteDefaultJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgHeadMass.name)); } if (_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name) != -1) { - cgLeftHandMass.position = - getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name)); + cgLeftHandMass.position = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name)); } else { cgLeftHandMass.position = DEFAULT_AVATAR_LEFTHAND_POS; } if (_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name) != -1) { - cgRightHandMass.position = - getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name)); + cgRightHandMass.position = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name)); } else { cgRightHandMass.position = DEFAULT_AVATAR_RIGHTHAND_POS; } @@ -4493,8 +4540,7 @@ glm::vec3 MyAvatar::computeCounterBalance() { } // find the current center of gravity position based on head and hand moments - glm::vec3 sumOfMoments = (cgHeadMass.weight * cgHeadMass.position) + (cgLeftHandMass.weight * cgLeftHandMass.position) + - (cgRightHandMass.weight * cgRightHandMass.position); + glm::vec3 sumOfMoments = (cgHeadMass.weight * cgHeadMass.position) + (cgLeftHandMass.weight * cgLeftHandMass.position) + (cgRightHandMass.weight * cgRightHandMass.position); float totalMass = cgHeadMass.weight + cgLeftHandMass.weight + cgRightHandMass.weight; glm::vec3 currentCg = (1.0f / totalMass) * sumOfMoments; @@ -4534,6 +4580,7 @@ glm::vec3 MyAvatar::computeCounterBalance() { // headOrientation, headPosition and hipsPosition are in avatar space // returns the matrix of the hips in Avatar space static glm::mat4 computeNewHipsMatrix(glm::quat headOrientation, glm::vec3 headPosition, glm::vec3 hipsPosition) { + glm::quat bodyOrientation = computeBodyFacingFromHead(headOrientation, Vectors::UNIT_Y); const float MIX_RATIO = 0.3f; @@ -4543,7 +4590,10 @@ static glm::mat4 computeNewHipsMatrix(glm::quat headOrientation, glm::vec3 headP glm::vec3 spineVec = headPosition - hipsPosition; glm::vec3 u, v, w; generateBasisVectors(glm::normalize(spineVec), hipsFacing, u, v, w); - return glm::mat4(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), glm::vec4(hipsPosition, 1.0f)); + return glm::mat4(glm::vec4(w, 0.0f), + glm::vec4(u, 0.0f), + glm::vec4(v, 0.0f), + glm::vec4(hipsPosition, 1.0f)); } static void drawBaseOfSupport(float baseOfSupportScale, float footLocal, glm::mat4 avatarToWorld) { @@ -4584,8 +4634,7 @@ glm::mat4 MyAvatar::deriveBodyUsingCgModel() { if (_enableDebugDrawBaseOfSupport) { float scaleBaseOfSupport = getUserEyeHeight() / DEFAULT_AVATAR_EYE_HEIGHT; - glm::vec3 rightFootPositionLocal = - getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint("RightFoot")); + glm::vec3 rightFootPositionLocal = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint("RightFoot")); drawBaseOfSupport(scaleBaseOfSupport, rightFootPositionLocal.y, avatarToWorldMat); } @@ -4593,8 +4642,7 @@ glm::mat4 MyAvatar::deriveBodyUsingCgModel() { glm::vec3 cgHipsPosition = computeCounterBalance(); // find the new hips rotation using the new head-hips axis as the up axis - glm::mat4 avatarHipsMat = - computeNewHipsMatrix(glmExtractRotation(avatarHeadMat), extractTranslation(avatarHeadMat), cgHipsPosition); + glm::mat4 avatarHipsMat = computeNewHipsMatrix(glmExtractRotation(avatarHeadMat), extractTranslation(avatarHeadMat), cgHipsPosition); // convert hips from avatar to sensor space // The Y_180 is to convert from z forward to -z forward. @@ -4618,7 +4666,7 @@ static bool withinBaseOfSupport(const controller::Pose& head) { bool withinFrontBase = isInsideLine(userScale * frontLeft, userScale * frontRight, head.getTranslation()); bool withinBackBase = isInsideLine(userScale * backRight, userScale * backLeft, head.getTranslation()); bool withinLateralBase = (isInsideLine(userScale * frontRight, userScale * backRight, head.getTranslation()) && - isInsideLine(userScale * backLeft, userScale * frontLeft, head.getTranslation())); + isInsideLine(userScale * backLeft, userScale * frontLeft, head.getTranslation())); isWithinSupport = (withinFrontBase && withinBackBase && withinLateralBase); } return isWithinSupport; @@ -4652,8 +4700,7 @@ float MyAvatar::computeStandingHeightMode(const controller::Pose& head) { float modeInMeters = getCurrentStandingHeight(); if (head.isValid()) { std::map freq; - for (auto recentModeReadingsIterator = _recentModeReadings.begin(); - recentModeReadingsIterator != _recentModeReadings.end(); ++recentModeReadingsIterator) { + for(auto recentModeReadingsIterator = _recentModeReadings.begin(); recentModeReadingsIterator != _recentModeReadings.end(); ++recentModeReadingsIterator) { freq[*recentModeReadingsIterator] += 1; if (freq[*recentModeReadingsIterator] > greatestFrequency) { greatestFrequency = freq[*recentModeReadingsIterator]; @@ -4666,23 +4713,21 @@ float MyAvatar::computeStandingHeightMode(const controller::Pose& head) { // if not greater check for a reset if (getResetMode() && getControllerPoseInAvatarFrame(controller::Action::HEAD).isValid()) { setResetMode(false); - float resetModeInCentimeters = - glm::floor((head.getTranslation().y - MODE_CORRECTION_FACTOR) * CENTIMETERS_PER_METER); + float resetModeInCentimeters = glm::floor((head.getTranslation().y - MODE_CORRECTION_FACTOR)*CENTIMETERS_PER_METER); modeInMeters = (resetModeInCentimeters / CENTIMETERS_PER_METER); _recentModeReadings.clear(); } else { // if not greater and no reset, keep the mode as it is modeInMeters = getCurrentStandingHeight(); + } } } return modeInMeters; } -static bool handDirectionMatchesHeadDirection(const controller::Pose& leftHand, - const controller::Pose& rightHand, - const controller::Pose& head) { +static bool handDirectionMatchesHeadDirection(const controller::Pose& leftHand, const controller::Pose& rightHand, const controller::Pose& head) { const float VELOCITY_EPSILON = 0.02f; bool leftHandDirectionMatchesHead = true; bool rightHandDirectionMatchesHead = true; @@ -4720,7 +4765,7 @@ static bool handAngularVelocityBelowThreshold(const controller::Pose& leftHand, rightHandXZAngularVelocity = glm::length(xzRightHandAngularVelocity); } return ((leftHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD) && - (rightHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD)); + (rightHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD)); } static bool headVelocityGreaterThanThreshold(const controller::Pose& head) { @@ -4743,8 +4788,7 @@ static bool isHeadLevel(const controller::Pose& head, const glm::quat& averageHe glm::vec3 currentHeadEulers = glm::degrees(safeEulerAngles(head.getRotation())); diffFromAverageEulers = averageHeadEulers - currentHeadEulers; } - return ((fabs(diffFromAverageEulers.x) < DEFAULT_HEAD_PITCH_STEPPING_TOLERANCE) && - (fabs(diffFromAverageEulers.z) < DEFAULT_HEAD_ROLL_STEPPING_TOLERANCE)); + return ((fabs(diffFromAverageEulers.x) < DEFAULT_HEAD_PITCH_STEPPING_TOLERANCE) && (fabs(diffFromAverageEulers.z) < DEFAULT_HEAD_ROLL_STEPPING_TOLERANCE)); } float MyAvatar::getUserHeight() const { @@ -4794,6 +4838,7 @@ float MyAvatar::getWalkSpeed() const { } else { return _defaultWalkSpeed.get(); } + } float MyAvatar::getWalkBackwardSpeed() const { @@ -4810,6 +4855,7 @@ float MyAvatar::getWalkBackwardSpeed() const { } else { return _defaultWalkBackwardSpeed.get(); } + } bool MyAvatar::isReadyForPhysics() const { @@ -4819,7 +4865,8 @@ bool MyAvatar::isReadyForPhysics() const { void MyAvatar::setSprintMode(bool sprint) { if (qApp->isHMDMode()) { _walkSpeedScalar = sprint ? AVATAR_DESKTOP_SPRINT_SPEED_SCALAR : AVATAR_WALK_SPEED_SCALAR; - } else { + } + else { _walkSpeedScalar = sprint ? AVATAR_HMD_SPRINT_SPEED_SCALAR : AVATAR_WALK_SPEED_SCALAR; } } @@ -4843,6 +4890,7 @@ void MyAvatar::setIsInSittingState(bool isSitting) { } void MyAvatar::setUserRecenterModel(MyAvatar::SitStandModelType modelName) { + _userRecenterModel.set(modelName); switch (modelName) { @@ -5084,6 +5132,7 @@ void driveKeysFromScriptValue(const QScriptValue& object, MyAvatar::DriveKeys& d driveKeys = static_cast(object.toUInt16()); } + void MyAvatar::lateUpdatePalms() { Avatar::updatePalms(); } @@ -5141,17 +5190,13 @@ void MyAvatar::FollowHelper::decrementTimeRemaining(float dt) { } } -bool MyAvatar::FollowHelper::shouldActivateRotation(const MyAvatar& myAvatar, - const glm::mat4& desiredBodyMatrix, - const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateRotation(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { const float FOLLOW_ROTATION_THRESHOLD = cosf(myAvatar.getRotationThreshold()); glm::vec2 bodyFacing = getFacingDir2D(currentBodyMatrix); return glm::dot(-myAvatar.getHeadControllerFacingMovingAverage(), bodyFacing) < FOLLOW_ROTATION_THRESHOLD; } -bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, - const glm::mat4& desiredBodyMatrix, - const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { // -z axis of currentBodyMatrix in world space. glm::vec3 forward = glm::normalize(glm::vec3(-currentBodyMatrix[0][2], -currentBodyMatrix[1][2], -currentBodyMatrix[2][2])); // x axis of currentBodyMatrix in world space. @@ -5182,6 +5227,7 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, } bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) const { + // get the current readings controller::Pose currentHeadPose = myAvatar.getControllerPoseInAvatarFrame(controller::Action::HEAD); controller::Pose currentLeftHandPose = myAvatar.getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND); @@ -5194,7 +5240,8 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons if (myAvatar.getIsInWalkingState()) { stepDetected = true; } else { - if (!withinBaseOfSupport(currentHeadPose) && headAngularVelocityBelowThreshold(currentHeadPose) && + if (!withinBaseOfSupport(currentHeadPose) && + headAngularVelocityBelowThreshold(currentHeadPose) && isWithinThresholdHeightMode(currentHeadSensorPose, myAvatar.getCurrentStandingHeight(), myScale) && handDirectionMatchesHeadDirection(currentLeftHandPose, currentRightHandPose, currentHeadPose) && handAngularVelocityBelowThreshold(currentLeftHandPose, currentRightHandPose) && @@ -5206,15 +5253,13 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons myAvatar.setIsInWalkingState(true); } } else { - glm::vec3 defaultHipsPosition = - myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Hips")); - glm::vec3 defaultHeadPosition = - myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Head")); + glm::vec3 defaultHipsPosition = myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Hips")); + glm::vec3 defaultHeadPosition = myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Head")); glm::vec3 currentHeadPosition = currentHeadPose.getTranslation(); float anatomicalHeadToHipsDistance = glm::length(defaultHeadPosition - defaultHipsPosition); - if (!isActive(Horizontal) && (!isActive(Vertical)) && - (glm::length(currentHeadPosition - defaultHipsPosition) > - (anatomicalHeadToHipsDistance + (DEFAULT_AVATAR_SPINE_STRETCH_LIMIT * anatomicalHeadToHipsDistance)))) { + if (!isActive(Horizontal) && + (!isActive(Vertical)) && + (glm::length(currentHeadPosition - defaultHipsPosition) > (anatomicalHeadToHipsDistance + (DEFAULT_AVATAR_SPINE_STRETCH_LIMIT * anatomicalHeadToHipsDistance)))) { myAvatar.setResetMode(true); stepDetected = true; if (glm::length(currentHeadPose.velocity) > DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { @@ -5226,9 +5271,7 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons return stepDetected; } -bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, - const glm::mat4& desiredBodyMatrix, - const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { const float CYLINDER_TOP = 2.0f; const float CYLINDER_BOTTOM = -1.5f; const float SITTING_BOTTOM = -0.02f; @@ -5259,11 +5302,11 @@ bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, return returnValue; } -void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, - const glm::mat4& desiredBodyMatrix, - const glm::mat4& currentBodyMatrix, - bool hasDriveInput) { - if (myAvatar.getHMDLeanRecenterEnabled() && qApp->getCamera().getMode() != CAMERA_MODE_MIRROR) { +void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, + const glm::mat4& currentBodyMatrix, bool hasDriveInput) { + + if (myAvatar.getHMDLeanRecenterEnabled() && + qApp->getCamera().getMode() != CAMERA_MODE_MIRROR) { if (!isActive(Rotation) && (shouldActivateRotation(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { activate(Rotation); myAvatar.setHeadControllerFacingMovingAverage(myAvatar.getHeadControllerFacing()); @@ -5278,8 +5321,7 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, } } else { // center of gravity model is not enabled - if (!isActive(Horizontal) && - (shouldActivateHorizontal(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { + if (!isActive(Horizontal) && (shouldActivateHorizontal(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { activate(Horizontal); if (myAvatar.getEnableStepResetRotation() && !myAvatar.getIsInSittingState()) { activate(Rotation); @@ -5316,7 +5358,7 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, glm::quat currentHipsLocal = myAvatar.getAbsoluteJointRotationInObjectFrame(myAvatar.getJointIndex("Hips")); const glm::quat hipsinWorldSpace = followWorldPose.rot() * (Quaternions::Y_180 * (currentHipsLocal)); - const glm::vec3 avatarUpWorld = glm::normalize(followWorldPose.rot() * (Vectors::UP)); + const glm::vec3 avatarUpWorld = glm::normalize(followWorldPose.rot()*(Vectors::UP)); glm::quat resultingSwingInWorld; glm::quat resultingTwistInWorld; swingTwistDecomposition(hipsinWorldSpace, avatarUpWorld, resultingSwingInWorld, resultingTwistInWorld); @@ -5325,8 +5367,8 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, followWorldPose.scale() = glm::vec3(1.0f); if (isActive(Rotation)) { - //use the hmd reading for the hips follow - followWorldPose.rot() = glmExtractRotation(desiredWorldMatrix); + //use the hmd reading for the hips follow + followWorldPose.rot() = glmExtractRotation(desiredWorldMatrix); } if (isActive(Horizontal)) { glm::vec3 desiredTranslation = extractTranslation(desiredWorldMatrix); @@ -5354,8 +5396,7 @@ glm::mat4 MyAvatar::FollowHelper::postPhysicsUpdate(MyAvatar& myAvatar, const gl glm::mat4 worldToSensorMatrix = glm::inverse(sensorToWorldMatrix); glm::vec3 sensorLinearDisplacement = transformVectorFast(worldToSensorMatrix, worldLinearDisplacement); - glm::quat sensorAngularDisplacement = - glmExtractRotation(worldToSensorMatrix) * worldAngularDisplacement * glmExtractRotation(sensorToWorldMatrix); + glm::quat sensorAngularDisplacement = glmExtractRotation(worldToSensorMatrix) * worldAngularDisplacement * glmExtractRotation(sensorToWorldMatrix); glm::mat4 newBodyMat = createMatFromQuatAndPos(sensorAngularDisplacement * glmExtractRotation(currentBodyMatrix), sensorLinearDisplacement + extractTranslation(currentBodyMatrix)); @@ -5423,8 +5464,7 @@ bool MyAvatar::didTeleport() { } bool MyAvatar::hasDriveInput() const { - return fabsf(getDriveKey(TRANSLATE_X)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Y)) > 0.0f || - fabsf(getDriveKey(TRANSLATE_Z)) > 0.0f; + return fabsf(getDriveKey(TRANSLATE_X)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Y)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Z)) > 0.0f; } void MyAvatar::setAway(bool value) { @@ -5440,6 +5480,7 @@ void MyAvatar::setAway(bool value) { // Specificly, if we are rendering using a third person camera. We would like to render the hand controllers in front of the camera, // not in front of the avatar. glm::mat4 MyAvatar::computeCameraRelativeHandControllerMatrix(const glm::mat4& controllerSensorMatrix) const { + // Fetch the current camera transform. glm::mat4 cameraWorldMatrix = qApp->getCamera().getTransform(); if (qApp->getCamera().getMode() == CAMERA_MODE_MIRROR) { @@ -5466,7 +5507,7 @@ glm::mat4 MyAvatar::computeCameraRelativeHandControllerMatrix(const glm::mat4& c glm::quat MyAvatar::getAbsoluteJointRotationInObjectFrame(int index) const { if (index < 0) { - index += numeric_limits::max() + 1; // 65536 + index += numeric_limits::max() + 1; // 65536 } switch (index) { @@ -5495,13 +5536,15 @@ glm::quat MyAvatar::getAbsoluteJointRotationInObjectFrame(int index) const { glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix(); return glmExtractRotation(invAvatarMat * qApp->getCamera().getTransform()); } - default: { return Avatar::getAbsoluteJointRotationInObjectFrame(index); } + default: { + return Avatar::getAbsoluteJointRotationInObjectFrame(index); + } } } glm::vec3 MyAvatar::getAbsoluteJointTranslationInObjectFrame(int index) const { if (index < 0) { - index += numeric_limits::max() + 1; // 65536 + index += numeric_limits::max() + 1; // 65536 } switch (index) { @@ -5530,7 +5573,9 @@ glm::vec3 MyAvatar::getAbsoluteJointTranslationInObjectFrame(int index) const { glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix(); return extractTranslation(invAvatarMat * qApp->getCamera().getTransform()); } - default: { return Avatar::getAbsoluteJointTranslationInObjectFrame(index); } + default: { + return Avatar::getAbsoluteJointTranslationInObjectFrame(index); + } } } @@ -5539,15 +5584,12 @@ glm::mat4 MyAvatar::getCenterEyeCalibrationMat() const { int rightEyeIndex = _skeletonModel->getRig().indexOfJoint("RightEye"); int leftEyeIndex = _skeletonModel->getRig().indexOfJoint("LeftEye"); if (rightEyeIndex >= 0 && leftEyeIndex >= 0) { - auto centerEyePos = (getAbsoluteDefaultJointTranslationInObjectFrame(rightEyeIndex) + - getAbsoluteDefaultJointTranslationInObjectFrame(leftEyeIndex)) * - 0.5f; + auto centerEyePos = (getAbsoluteDefaultJointTranslationInObjectFrame(rightEyeIndex) + getAbsoluteDefaultJointTranslationInObjectFrame(leftEyeIndex)) * 0.5f; auto centerEyeRot = Quaternions::Y_180; return createMatFromQuatAndPos(centerEyeRot, centerEyePos / getSensorToWorldScale()); } else { glm::mat4 headMat = getHeadCalibrationMat(); - return createMatFromQuatAndPos(DEFAULT_AVATAR_MIDDLE_EYE_ROT, - extractTranslation(headMat) + DEFAULT_AVATAR_HEAD_TO_MIDDLE_EYE_OFFSET); + return createMatFromQuatAndPos(DEFAULT_AVATAR_MIDDLE_EYE_ROT, extractTranslation(headMat) + DEFAULT_AVATAR_HEAD_TO_MIDDLE_EYE_OFFSET); } } @@ -5716,6 +5758,7 @@ void MyAvatar::updateHoldActions(const AnimPose& prePhysicsPose, const AnimPose& if (entityTree) { // lateAvatarUpdate will modify entity position & orientation, so we need an entity write lock entityTree->withWriteLock([&] { + // to prevent actions from adding or removing themselves from the _holdActions vector // while we are iterating, we need to enter a critical section. std::lock_guard guard(_holdActionsMutex); @@ -5751,24 +5794,26 @@ SpatialParentTree* MyAvatar::getParentTree() const { return entityTree.get(); } -const QUuid MyAvatar::grab(const QUuid& targetID, - int parentJointIndex, - glm::vec3 positionalOffset, - glm::quat rotationalOffset) { +const QUuid MyAvatar::grab(const QUuid& targetID, int parentJointIndex, + glm::vec3 positionalOffset, glm::quat rotationalOffset) { auto grabID = QUuid::createUuid(); // create a temporary grab object to get grabData QString hand = "none"; - if (parentJointIndex == CONTROLLER_RIGHTHAND_INDEX || parentJointIndex == CAMERA_RELATIVE_CONTROLLER_RIGHTHAND_INDEX || - parentJointIndex == FARGRAB_RIGHTHAND_INDEX || parentJointIndex == getJointIndex("RightHand")) { + if (parentJointIndex == CONTROLLER_RIGHTHAND_INDEX || + parentJointIndex == CAMERA_RELATIVE_CONTROLLER_RIGHTHAND_INDEX || + parentJointIndex == FARGRAB_RIGHTHAND_INDEX || + parentJointIndex == getJointIndex("RightHand")) { hand = "right"; - } else if (parentJointIndex == CONTROLLER_LEFTHAND_INDEX || parentJointIndex == CAMERA_RELATIVE_CONTROLLER_LEFTHAND_INDEX || - parentJointIndex == FARGRAB_LEFTHAND_INDEX || parentJointIndex == getJointIndex("LeftHand")) { + } else if (parentJointIndex == CONTROLLER_LEFTHAND_INDEX || + parentJointIndex == CAMERA_RELATIVE_CONTROLLER_LEFTHAND_INDEX || + parentJointIndex == FARGRAB_LEFTHAND_INDEX || + parentJointIndex == getJointIndex("LeftHand")) { hand = "left"; } - Grab tmpGrab(DependencyManager::get()->getSessionUUID(), targetID, parentJointIndex, hand, positionalOffset, - rotationalOffset); + Grab tmpGrab(DependencyManager::get()->getSessionUUID(), + targetID, parentJointIndex, hand, positionalOffset, rotationalOffset); QByteArray grabData = tmpGrab.toByteArray(); bool dataChanged = updateAvatarGrabData(grabID, grabData); @@ -5781,9 +5826,10 @@ const QUuid MyAvatar::grab(const QUuid& targetID, } void MyAvatar::releaseGrab(const QUuid& grabID) { - bool tellHandler{ false }; + bool tellHandler { false }; _avatarGrabsLock.withWriteLock([&] { + std::map::iterator itr; itr = _avatarGrabs.find(grabID); if (itr != _avatarGrabs.end()) { @@ -5812,12 +5858,13 @@ void MyAvatar::releaseGrab(const QUuid& grabID) { void MyAvatar::addAvatarHandsToFlow(const std::shared_ptr& otherAvatar) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "addAvatarHandsToFlow", Q_ARG(const std::shared_ptr&, otherAvatar)); + QMetaObject::invokeMethod(this, "addAvatarHandsToFlow", + Q_ARG(const std::shared_ptr&, otherAvatar)); return; } - auto& flow = _skeletonModel->getRig().getFlow(); + auto &flow = _skeletonModel->getRig().getFlow(); if (otherAvatar != nullptr && flow.getActive()) { - for (auto& handJointName : HAND_COLLISION_JOINTS) { + for (auto &handJointName : HAND_COLLISION_JOINTS) { int jointIndex = otherAvatar->getJointIndex(handJointName); if (jointIndex != -1) { glm::vec3 position = otherAvatar->getJointPosition(jointIndex); @@ -5845,18 +5892,18 @@ void MyAvatar::addAvatarHandsToFlow(const std::shared_ptr& otherAvatar) * @property {number} [radius=0.05] - Collision sphere radius. * @property {number} [offset=Vec3.ZERO] - Offset of the collision sphere from the joint. */ -void MyAvatar::useFlow(bool isActive, - bool isCollidable, - const QVariantMap& physicsConfig, - const QVariantMap& collisionsConfig) { +void MyAvatar::useFlow(bool isActive, bool isCollidable, const QVariantMap& physicsConfig, const QVariantMap& collisionsConfig) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "useFlow", Q_ARG(bool, isActive), Q_ARG(bool, isCollidable), - Q_ARG(const QVariantMap&, physicsConfig), Q_ARG(const QVariantMap&, collisionsConfig)); + QMetaObject::invokeMethod(this, "useFlow", + Q_ARG(bool, isActive), + Q_ARG(bool, isCollidable), + Q_ARG(const QVariantMap&, physicsConfig), + Q_ARG(const QVariantMap&, collisionsConfig)); return; } if (_skeletonModel->isLoaded()) { - auto& flow = _skeletonModel->getRig().getFlow(); - auto& collisionSystem = flow.getCollisionSystem(); + auto &flow = _skeletonModel->getRig().getFlow(); + auto &collisionSystem = flow.getCollisionSystem(); if (!flow.isInitialized() && isActive) { _skeletonModel->getRig().initFlow(true); } else { @@ -5865,7 +5912,7 @@ void MyAvatar::useFlow(bool isActive, collisionSystem.setActive(isCollidable); auto physicsGroups = physicsConfig.keys(); if (physicsGroups.size() > 0) { - for (auto& groupName : physicsGroups) { + for (auto &groupName : physicsGroups) { auto settings = physicsConfig[groupName].toMap(); FlowPhysicsSettings physicsSettings; if (settings.contains("active")) { @@ -5895,7 +5942,7 @@ void MyAvatar::useFlow(bool isActive, auto collisionJoints = collisionsConfig.keys(); if (collisionJoints.size() > 0) { collisionSystem.clearSelfCollisions(); - for (auto& jointName : collisionJoints) { + for (auto &jointName : collisionJoints) { int jointIndex = getJointIndex(jointName); FlowCollisionSettings collisionsSettings; auto settings = collisionsConfig[jointName].toMap(); @@ -5949,13 +5996,14 @@ void MyAvatar::useFlow(bool isActive, QVariantMap MyAvatar::getFlowData() { QVariantMap result; if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "getFlowData", Q_RETURN_ARG(QVariantMap, result)); + BLOCKING_INVOKE_METHOD(this, "getFlowData", + Q_RETURN_ARG(QVariantMap, result)); return result; } if (_skeletonModel->isLoaded()) { auto jointNames = getJointNames(); - auto& flow = _skeletonModel->getRig().getFlow(); - auto& collisionSystem = flow.getCollisionSystem(); + auto &flow = _skeletonModel->getRig().getFlow(); + auto &collisionSystem = flow.getCollisionSystem(); bool initialized = flow.isInitialized(); result.insert("initialized", initialized); result.insert("active", flow.getActive()); @@ -5965,17 +6013,17 @@ QVariantMap MyAvatar::getFlowData() { QVariantMap threadData; std::map groupJointsMap; QVariantList jointCollisionData; - auto& groups = flow.getGroupSettings(); - for (auto& joint : flow.getJoints()) { - auto& groupName = joint.second.getGroup(); + auto &groups = flow.getGroupSettings(); + for (auto &joint : flow.getJoints()) { + auto &groupName = joint.second.getGroup(); if (groups.find(groupName) != groups.end()) { if (groupJointsMap.find(groupName) == groupJointsMap.end()) { groupJointsMap.insert(std::pair(groupName, QVariantList())); } groupJointsMap[groupName].push_back(joint.second.getIndex()); } - } - for (auto& group : groups) { + } + for (auto &group : groups) { QVariantMap settingsObject; QString groupName = group.first; FlowPhysicsSettings groupSettings = group.second; @@ -5990,8 +6038,8 @@ QVariantMap MyAvatar::getFlowData() { physicsData.insert(groupName, settingsObject); } - auto& collisions = collisionSystem.getCollisions(); - for (auto& collision : collisions) { + auto &collisions = collisionSystem.getCollisions(); + for (auto &collision : collisions) { QVariantMap collisionObject; collisionObject.insert("offset", vec3toVariant(collision._offset)); collisionObject.insert("radius", collision._radius); @@ -5999,7 +6047,7 @@ QVariantMap MyAvatar::getFlowData() { QString jointName = jointNames.size() > collision._jointIndex ? jointNames[collision._jointIndex] : "unknown"; collisionsData.insert(jointName, collisionObject); } - for (auto& thread : flow.getThreads()) { + for (auto &thread : flow.getThreads()) { QVariantList indices; for (int index : thread._joints) { indices.append(index); @@ -6016,13 +6064,14 @@ QVariantMap MyAvatar::getFlowData() { QVariantList MyAvatar::getCollidingFlowJoints() { QVariantList result; if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "getCollidingFlowJoints", Q_RETURN_ARG(QVariantList, result)); + BLOCKING_INVOKE_METHOD(this, "getCollidingFlowJoints", + Q_RETURN_ARG(QVariantList, result)); return result; } if (_skeletonModel->isLoaded()) { auto& flow = _skeletonModel->getRig().getFlow(); - for (auto& joint : flow.getJoints()) { + for (auto &joint : flow.getJoints()) { if (joint.second.isColliding()) { result.append(joint.second.getIndex()); } @@ -6033,7 +6082,7 @@ QVariantList MyAvatar::getCollidingFlowJoints() { void MyAvatar::initFlowFromFST() { if (_skeletonModel->isLoaded()) { - auto& flowData = _skeletonModel->getHFMModel().flowData; + auto &flowData = _skeletonModel->getHFMModel().flowData; if (flowData.shouldInitFlow()) { useFlow(true, flowData.shouldInitCollisions(), flowData._physicsConfig, flowData._collisionsConfig); } @@ -6051,3 +6100,4 @@ void MyAvatar::sendPacket(const QUuid& entityID) const { }); } } + From 00baaffb97ebd66fb5179cca8da8c8a7d50c7a09 Mon Sep 17 00:00:00 2001 From: dante ruiz Date: Fri, 7 Jun 2019 10:56:44 -0700 Subject: [PATCH 12/31] allow launcher to work from mounted dmg --- launchers/darwin/src/DownloadInterface.m | 2 ++ launchers/darwin/src/Launcher.h | 1 + launchers/darwin/src/Launcher.m | 11 +++++++---- launchers/darwin/src/main.mm | 2 +- 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/launchers/darwin/src/DownloadInterface.m b/launchers/darwin/src/DownloadInterface.m index b957197567..ed7aaf51c4 100644 --- a/launchers/darwin/src/DownloadInterface.m +++ b/launchers/darwin/src/DownloadInterface.m @@ -46,6 +46,8 @@ NSString* downloadFileName = [sharedLauncher getDownloadFilename]; NSLog(@"extract interface zip"); + NSLog(@"%@", appPath); + NSLog(@"%@", [appPath stringByAppendingString:downloadFileName]); [sharedLauncher extractZipFileAtDestination:appPath :[appPath stringByAppendingString:downloadFileName]]; NSLog(@"finished extracting interface zip"); diff --git a/launchers/darwin/src/Launcher.h b/launchers/darwin/src/Launcher.h index 5838e25a82..69484a378d 100644 --- a/launchers/darwin/src/Launcher.h +++ b/launchers/darwin/src/Launcher.h @@ -57,6 +57,7 @@ typedef enum LoginErrorTypes - (BOOL) loginShouldSetErrorState; - (void) displayErrorPage; - (void) showLoginScreen; +- (NSString*) getLauncherPath; - (ProcessState) currentProccessState; - (void) setCurrentProcessState:(ProcessState) aProcessState; - (void) setLoginErrorState:(LoginError) aLoginError; diff --git a/launchers/darwin/src/Launcher.m b/launchers/darwin/src/Launcher.m index 07fc8878da..3ab4379e7a 100644 --- a/launchers/darwin/src/Launcher.m +++ b/launchers/darwin/src/Launcher.m @@ -73,6 +73,11 @@ static BOOL const DELETE_ZIP_FILES = TRUE; return filePath; } +- (NSString*) getLauncherPath +{ + return [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/Contents/MacOS/"]; +} + - (void) extractZipFileAtDestination:(NSString *)destination :(NSString*)file { NSTask* task = [[NSTask alloc] init]; @@ -174,7 +179,7 @@ static BOOL const DELETE_ZIP_FILES = TRUE; - (NSString*) getAppPath { - return [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/Contents/MacOS/"]; + return [self getDownloadPathForContentAndScripts]; } - (BOOL) loginShouldSetErrorState @@ -317,7 +322,7 @@ static BOOL const DELETE_ZIP_FILES = TRUE; - (void) launchInterface { - NSString* launcherPath = [[self getAppPath] stringByAppendingString:@"HQ Launcher"]; + NSString* launcherPath = [[self getLauncherPath] stringByAppendingString:@"HQ Launcher"]; [[Settings sharedSettings] setLauncherPath:launcherPath]; [[Settings sharedSettings] save]; @@ -351,8 +356,6 @@ static BOOL const DELETE_ZIP_FILES = TRUE; } [workspace launchApplicationAtURL:url options:NSWorkspaceLaunchNewInstance configuration:[NSDictionary dictionaryWithObject:arguments forKey:NSWorkspaceLaunchConfigurationArguments] error:&error]; - //NSLog(@"arguments %@", [NSDictionary dictionaryWithObject:arguments forKey:NSWorkspaceLaunchConfigurationArguments]); - [NSApp terminate:self]; } diff --git a/launchers/darwin/src/main.mm b/launchers/darwin/src/main.mm index cdcd66f963..41e2986af7 100644 --- a/launchers/darwin/src/main.mm +++ b/launchers/darwin/src/main.mm @@ -17,7 +17,7 @@ void redirectLogToDocuments() int main(int argc, const char* argv[]) { //NSApp.appearance = [NSAppearance appearanceNamed: NSAppearanceNameAqua]; - redirectLogToDocuments(); + //redirectLogToDocuments(); NSArray* apps = [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.highfidelity.launcher"]; if ([apps count] > 1) { NSLog(@"launcher is already running"); From 5499da0b7b5bad88b8075ef348916eb0d2d7d685 Mon Sep 17 00:00:00 2001 From: dante ruiz Date: Fri, 7 Jun 2019 10:59:17 -0700 Subject: [PATCH 13/31] removing debug statments --- launchers/darwin/src/DownloadInterface.m | 2 -- launchers/darwin/src/main.mm | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/launchers/darwin/src/DownloadInterface.m b/launchers/darwin/src/DownloadInterface.m index ed7aaf51c4..b957197567 100644 --- a/launchers/darwin/src/DownloadInterface.m +++ b/launchers/darwin/src/DownloadInterface.m @@ -46,8 +46,6 @@ NSString* downloadFileName = [sharedLauncher getDownloadFilename]; NSLog(@"extract interface zip"); - NSLog(@"%@", appPath); - NSLog(@"%@", [appPath stringByAppendingString:downloadFileName]); [sharedLauncher extractZipFileAtDestination:appPath :[appPath stringByAppendingString:downloadFileName]]; NSLog(@"finished extracting interface zip"); diff --git a/launchers/darwin/src/main.mm b/launchers/darwin/src/main.mm index 41e2986af7..cdcd66f963 100644 --- a/launchers/darwin/src/main.mm +++ b/launchers/darwin/src/main.mm @@ -17,7 +17,7 @@ void redirectLogToDocuments() int main(int argc, const char* argv[]) { //NSApp.appearance = [NSAppearance appearanceNamed: NSAppearanceNameAqua]; - //redirectLogToDocuments(); + redirectLogToDocuments(); NSArray* apps = [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.highfidelity.launcher"]; if ([apps count] > 1) { NSLog(@"launcher is already running"); From e63d98e1374d3c3a6b38ebef1ab29a8a880c8af1 Mon Sep 17 00:00:00 2001 From: Preston Bezos Date: Fri, 7 Jun 2019 11:09:21 -0700 Subject: [PATCH 14/31] fixed a couple of doc errors and accounted for some edge cases --- interface/src/avatar/MyAvatar.cpp | 874 ++++++++++++++---------------- interface/src/avatar/MyAvatar.h | 8 +- 2 files changed, 418 insertions(+), 464 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 92a88cac38..3f921fd469 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -71,9 +71,9 @@ using namespace std; const float DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES = 30.0f; const float YAW_SPEED_DEFAULT = 100.0f; // degrees/sec -const float PITCH_SPEED_DEFAULT = 75.0f; // degrees/sec +const float PITCH_SPEED_DEFAULT = 75.0f; // degrees/sec -const float MAX_BOOST_SPEED = 0.5f * DEFAULT_AVATAR_MAX_WALKING_SPEED; // action motor gets additive boost below this speed +const float MAX_BOOST_SPEED = 0.5f * DEFAULT_AVATAR_MAX_WALKING_SPEED; // action motor gets additive boost below this speed const float MIN_AVATAR_SPEED = 0.05f; float MIN_SCRIPTED_MOTOR_TIMESCALE = 0.005f; @@ -83,7 +83,8 @@ const int SCRIPTED_MOTOR_AVATAR_FRAME = 1; const int SCRIPTED_MOTOR_WORLD_FRAME = 2; const int SCRIPTED_MOTOR_SIMPLE_MODE = 0; const int SCRIPTED_MOTOR_DYNAMIC_MODE = 1; -const QString& DEFAULT_AVATAR_COLLISION_SOUND_URL = "https://hifi-public.s3.amazonaws.com/sounds/Collisions-otherorganic/Body_Hits_Impact.wav"; +const QString& DEFAULT_AVATAR_COLLISION_SOUND_URL = + "https://hifi-public.s3.amazonaws.com/sounds/Collisions-otherorganic/Body_Hits_Impact.wav"; const float MyAvatar::ZOOM_MIN = 0.5f; const float MyAvatar::ZOOM_MAX = 25.0f; @@ -92,7 +93,7 @@ const float MIN_SCALE_CHANGED_DELTA = 0.001f; const int MODE_READINGS_RING_BUFFER_SIZE = 500; const float CENTIMETERS_PER_METER = 100.0f; -const QString AVATAR_SETTINGS_GROUP_NAME { "Avatar" }; +const QString AVATAR_SETTINGS_GROUP_NAME{ "Avatar" }; static const QString USER_RECENTER_MODEL_FORCE_SIT = QStringLiteral("ForceSit"); static const QString USER_RECENTER_MODEL_FORCE_STAND = QStringLiteral("ForceStand"); @@ -113,50 +114,33 @@ MyAvatar::SitStandModelType stringToUserRecenterModel(const QString& str) { QString userRecenterModelToString(MyAvatar::SitStandModelType model) { switch (model) { - case MyAvatar::ForceSit: - return USER_RECENTER_MODEL_FORCE_SIT; - case MyAvatar::ForceStand: - return USER_RECENTER_MODEL_FORCE_STAND; - case MyAvatar::DisableHMDLean: - return USER_RECENTER_MODEL_DISABLE_HMD_LEAN; - case MyAvatar::Auto: - default: - return USER_RECENTER_MODEL_AUTO; + case MyAvatar::ForceSit: + return USER_RECENTER_MODEL_FORCE_SIT; + case MyAvatar::ForceStand: + return USER_RECENTER_MODEL_FORCE_STAND; + case MyAvatar::DisableHMDLean: + return USER_RECENTER_MODEL_DISABLE_HMD_LEAN; + case MyAvatar::Auto: + default: + return USER_RECENTER_MODEL_AUTO; } } MyAvatar::MyAvatar(QThread* thread) : - Avatar(thread), - _yawSpeed(YAW_SPEED_DEFAULT), - _pitchSpeed(PITCH_SPEED_DEFAULT), - _scriptedMotorTimescale(DEFAULT_SCRIPTED_MOTOR_TIMESCALE), - _scriptedMotorFrame(SCRIPTED_MOTOR_CAMERA_FRAME), - _scriptedMotorMode(SCRIPTED_MOTOR_SIMPLE_MODE), - _motionBehaviors(AVATAR_MOTION_DEFAULTS), - _characterController(std::shared_ptr(this)), - _eyeContactTarget(LEFT_EYE), - _realWorldFieldOfView("realWorldFieldOfView", - DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES), - _useAdvancedMovementControls("advancedMovementForHandControllersIsChecked", true), - _showPlayArea("showPlayArea", true), - _smoothOrientationTimer(std::numeric_limits::max()), - _smoothOrientationInitial(), - _smoothOrientationTarget(), - _hmdSensorMatrix(), - _hmdSensorOrientation(), - _hmdSensorPosition(), - _recentModeReadings(MODE_READINGS_RING_BUFFER_SIZE), - _bodySensorMatrix(), - _goToPending(false), - _goToSafe(true), - _goToFeetAjustment(false), - _goToPosition(), - _goToOrientation(), - _prevShouldDrawHead(true), - _audioListenerMode(FROM_HEAD), + Avatar(thread), _yawSpeed(YAW_SPEED_DEFAULT), _pitchSpeed(PITCH_SPEED_DEFAULT), + _scriptedMotorTimescale(DEFAULT_SCRIPTED_MOTOR_TIMESCALE), _scriptedMotorFrame(SCRIPTED_MOTOR_CAMERA_FRAME), + _scriptedMotorMode(SCRIPTED_MOTOR_SIMPLE_MODE), _motionBehaviors(AVATAR_MOTION_DEFAULTS), + _characterController(std::shared_ptr(this)), _eyeContactTarget(LEFT_EYE), + _realWorldFieldOfView("realWorldFieldOfView", DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES), + _useAdvancedMovementControls("advancedMovementForHandControllersIsChecked", true), _showPlayArea("showPlayArea", true), + _smoothOrientationTimer(std::numeric_limits::max()), _smoothOrientationInitial(), _smoothOrientationTarget(), + _hmdSensorMatrix(), _hmdSensorOrientation(), _hmdSensorPosition(), _recentModeReadings(MODE_READINGS_RING_BUFFER_SIZE), + _bodySensorMatrix(), _goToPending(false), _goToSafe(true), _goToFeetAjustment(false), _goToPosition(), _goToOrientation(), + _prevShouldDrawHead(true), _audioListenerMode(FROM_HEAD), _dominantHandSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "dominantHand", DOMINANT_RIGHT_HAND), _strafeEnabledSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "strafeEnabled", DEFAULT_STRAFE_ENABLED), - _hmdAvatarAlignmentTypeSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "hmdAvatarAlignmentType", DEFAULT_HMD_AVATAR_ALIGNMENT_TYPE), + _hmdAvatarAlignmentTypeSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "hmdAvatarAlignmentType", + DEFAULT_HMD_AVATAR_ALIGNMENT_TYPE), _headPitchSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "", 0.0f), _scaleSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "scale", _targetScale), _yawSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "yawSpeed", _yawSpeed), @@ -172,17 +156,19 @@ MyAvatar::MyAvatar(QThread* thread) : _userHeightSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userHeight", DEFAULT_AVATAR_HEIGHT), _flyingHMDSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "flyingHMD", _flyingPrefHMD), _movementReferenceSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "movementReference", _movementReference), - _avatarEntityCountSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" << "size", 0), + _avatarEntityCountSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" + << "size", + 0), _driveGear1Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear1", _driveGear1), _driveGear2Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear2", _driveGear2), _driveGear3Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear3", _driveGear3), _driveGear4Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear4", _driveGear4), _driveGear5Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear5", _driveGear5), _analogWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogWalkSpeed", _analogWalkSpeed.get()), - _analogPlusWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogPlusWalkSpeed", _analogPlusWalkSpeed.get()), + _analogPlusWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogPlusWalkSpeed", + _analogPlusWalkSpeed.get()), _controlSchemeIndexSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "controlSchemeIndex", _controlSchemeIndex), - _userRecenterModelSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userRecenterModel", USER_RECENTER_MODEL_AUTO) -{ + _userRecenterModelSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userRecenterModel", USER_RECENTER_MODEL_AUTO) { _clientTraitsHandler.reset(new ClientTraitsHandler(this)); // give the pointer to our head to inherited _headData variable from AvatarData @@ -203,7 +189,7 @@ MyAvatar::MyAvatar(QThread* thread) : qApp->loadAvatarScripts(hfmModel.scripts); _shouldLoadScripts = false; } - // Load and convert old attachments to avatar entities + // Load and convert old attachments to avatar entities if (_oldAttachmentData.size() > 0) { setAttachmentData(_oldAttachmentData); _oldAttachmentData.clear(); @@ -220,11 +206,11 @@ MyAvatar::MyAvatar(QThread* thread) : clearDriveKeys(); // Necessary to select the correct slot - using SlotType = void(MyAvatar::*)(const glm::vec3&, bool, const glm::quat&, bool); + using SlotType = void (MyAvatar::*)(const glm::vec3&, bool, const glm::quat&, bool); // connect to AddressManager signal for location jumps - connect(DependencyManager::get().data(), &AddressManager::locationChangeRequired, - this, static_cast(&MyAvatar::goToFeetLocation)); + connect(DependencyManager::get().data(), &AddressManager::locationChangeRequired, this, + static_cast(&MyAvatar::goToFeetLocation)); // handle scale constraints imposed on us by the domain-server auto& domainHandler = DependencyManager::get()->getDomainHandler(); @@ -287,7 +273,6 @@ MyAvatar::MyAvatar(QThread* thread) : if (recordingInterface->getPlayerUseSkeletonModel() && dummyAvatar.getSkeletonModelURL().isValid() && (dummyAvatar.getSkeletonModelURL() != getSkeletonModelURL())) { - setSkeletonModelURL(dummyAvatar.getSkeletonModelURL()); } @@ -383,7 +368,8 @@ void MyAvatar::enableHandTouchForID(const QUuid& entityID) { } void MyAvatar::registerMetaTypes(ScriptEnginePointer engine) { - QScriptValue value = engine->newQObject(this, QScriptEngine::QtOwnership, QScriptEngine::ExcludeDeleteLater | QScriptEngine::ExcludeChildObjects); + QScriptValue value = engine->newQObject(this, QScriptEngine::QtOwnership, + QScriptEngine::ExcludeDeleteLater | QScriptEngine::ExcludeChildObjects); engine->globalObject().setProperty("MyAvatar", value); QScriptValue driveKeys = engine->newObject(); @@ -446,7 +432,6 @@ void MyAvatar::resetSensorsAndBody() { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "resetSensorsAndBody"); return; - } qApp->getActiveDisplayPlugin()->resetSensors(); @@ -460,7 +445,7 @@ void MyAvatar::centerBody() { } // derive the desired body orientation from the current hmd orientation, before the sensor reset. - auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. // transform this body into world space auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix; @@ -497,7 +482,6 @@ void MyAvatar::clearIKJointLimitHistory() { } void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { - assert(QThread::currentThread() == thread()); // Reset dynamic state. @@ -506,14 +490,14 @@ void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { if (andReload) { _skeletonModel->reset(); } - if (andHead) { // which drives camera in desktop + if (andHead) { // which drives camera in desktop getHead()->reset(); } setThrust(glm::vec3(0.0f)); if (andRecenter) { // derive the desired body orientation from the *old* hmd orientation, before the sensor reset. - auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. // transform this body into world space auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix; @@ -540,8 +524,8 @@ void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { void MyAvatar::updateSitStandState(float newHeightReading, float dt) { const float STANDING_HEIGHT_MULTIPLE = 1.2f; const float SITTING_HEIGHT_MULTIPLE = 0.833f; - const float SITTING_TIMEOUT = 4.0f; // 4 seconds - const float STANDING_TIMEOUT = 0.3333f; // 1/3 second + const float SITTING_TIMEOUT = 4.0f; // 4 seconds + const float STANDING_TIMEOUT = 0.3333f; // 1/3 second const float SITTING_UPPER_BOUND = 1.52f; if (!getIsSitStandStateLocked()) { if (!getIsAway() && getControllerPoseInAvatarFrame(controller::Action::HEAD).isValid()) { @@ -601,9 +585,9 @@ void MyAvatar::updateSitStandState(float newHeightReading, float dt) { void MyAvatar::update(float deltaTime) { // update moving average of HMD facing in xz plane. const float HMD_FACING_TIMESCALE = getRotationRecenterFilterLength(); - const float PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH = 0.0f; // 100 percent shoulders + const float PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH = 0.0f; // 100 percent shoulders const float COSINE_THIRTY_DEGREES = 0.866f; - const float SQUATTY_TIMEOUT = 30.0f; // 30 seconds + const float SQUATTY_TIMEOUT = 30.0f; // 30 seconds const float HEIGHT_FILTER_COEFFICIENT = 0.01f; float tau = deltaTime / HMD_FACING_TIMESCALE; @@ -612,8 +596,8 @@ void MyAvatar::update(float deltaTime) { // put the average hand azimuth into sensor space. // then mix it with head facing direction to determine rotation recenter int spine2Index = _skeletonModel->getRig().indexOfJoint("Spine2"); - if (getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND).isValid() && getControllerPoseInAvatarFrame(controller::Action::RIGHT_HAND).isValid() && !(spine2Index < 0)) { - + if (getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND).isValid() && + getControllerPoseInAvatarFrame(controller::Action::RIGHT_HAND).isValid() && !(spine2Index < 0)) { // use the spine for the azimuth origin. glm::quat spine2Rot = getAbsoluteJointRotationInObjectFrame(spine2Index); glm::vec3 handHipAzimuthAvatarSpace = spine2Rot * glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y); @@ -623,8 +607,10 @@ void MyAvatar::update(float deltaTime) { glm::vec3 handHipAzimuthSensorSpace = transformVectorFast(worldToSensorMat, handHipAzimuthWorldSpace); glm::vec2 normedHandHipAzimuthSensorSpace(0.0f, 1.0f); if (glm::length(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)) > 0.0f) { - normedHandHipAzimuthSensorSpace = glm::normalize(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)); - glm::vec2 headFacingPlusHandHipAzimuthMix = lerp(normedHandHipAzimuthSensorSpace, _headControllerFacing, PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH); + normedHandHipAzimuthSensorSpace = + glm::normalize(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)); + glm::vec2 headFacingPlusHandHipAzimuthMix = + lerp(normedHandHipAzimuthSensorSpace, _headControllerFacing, PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH); _headControllerFacingMovingAverage = lerp(_headControllerFacingMovingAverage, headFacingPlusHandHipAzimuthMix, tau); } else { // use head facing if the chest arms vector is up or down. @@ -642,7 +628,8 @@ void MyAvatar::update(float deltaTime) { controller::Pose newHeightReading = getControllerPoseInSensorFrame(controller::Action::HEAD); if (newHeightReading.isValid()) { int newHeightReadingInCentimeters = glm::floor(newHeightReading.getTranslation().y * CENTIMETERS_PER_METER); - _averageUserHeightSensorSpace = lerp(_averageUserHeightSensorSpace, newHeightReading.getTranslation().y, HEIGHT_FILTER_COEFFICIENT); + _averageUserHeightSensorSpace = + lerp(_averageUserHeightSensorSpace, newHeightReading.getTranslation().y, HEIGHT_FILTER_COEFFICIENT); _recentModeReadings.insert(newHeightReadingInCentimeters); setCurrentStandingHeight(computeStandingHeightMode(newHeightReading)); setAverageHeadRotation(computeAverageHeadRotation(getControllerPoseInAvatarFrame(controller::Action::HEAD))); @@ -658,10 +645,9 @@ void MyAvatar::update(float deltaTime) { } float angleSpine2 = glm::dot(upSpine2, glm::vec3(0.0f, 1.0f, 0.0f)); - if (getControllerPoseInAvatarFrame(controller::Action::HEAD).getTranslation().y < (headDefaultPositionAvatarSpace.y - SQUAT_THRESHOLD) && - (angleSpine2 > COSINE_THIRTY_DEGREES) && - (getUserRecenterModel() != MyAvatar::SitStandModelType::ForceStand)) { - + if (getControllerPoseInAvatarFrame(controller::Action::HEAD).getTranslation().y < + (headDefaultPositionAvatarSpace.y - SQUAT_THRESHOLD) && + (angleSpine2 > COSINE_THIRTY_DEGREES) && (getUserRecenterModel() != MyAvatar::SitStandModelType::ForceStand)) { _squatTimer += deltaTime; if (_squatTimer > SQUATTY_TIMEOUT) { _squatTimer = 0.0f; @@ -677,20 +663,24 @@ void MyAvatar::update(float deltaTime) { if (_drawAverageFacingEnabled) { auto sensorHeadPose = getControllerPoseInSensorFrame(controller::Action::HEAD); glm::vec3 worldHeadPos = transformPoint(getSensorToWorldMatrix(), sensorHeadPose.getTranslation()); - glm::vec3 worldFacingAverage = transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacingMovingAverage.x, 0.0f, _headControllerFacingMovingAverage.y)); - glm::vec3 worldFacing = transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacing.x, 0.0f, _headControllerFacing.y)); + glm::vec3 worldFacingAverage = + transformVectorFast(getSensorToWorldMatrix(), + glm::vec3(_headControllerFacingMovingAverage.x, 0.0f, _headControllerFacingMovingAverage.y)); + glm::vec3 worldFacing = + transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacing.x, 0.0f, _headControllerFacing.y)); DebugDraw::getInstance().drawRay(worldHeadPos, worldHeadPos + worldFacing, glm::vec4(0.0f, 1.0f, 0.0f, 1.0f)); DebugDraw::getInstance().drawRay(worldHeadPos, worldHeadPos + worldFacingAverage, glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)); // draw hand azimuth vector - glm::vec3 handAzimuthMidpoint = transformPoint(getTransform().getMatrix(), glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y)); + glm::vec3 handAzimuthMidpoint = + transformPoint(getTransform().getMatrix(), glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y)); DebugDraw::getInstance().drawRay(getWorldPosition(), handAzimuthMidpoint, glm::vec4(0.0f, 1.0f, 1.0f, 1.0f)); } if (_goToPending) { setWorldPosition(_goToPosition); setWorldOrientation(_goToOrientation); - _headControllerFacingMovingAverage = _headControllerFacing; // reset moving average + _headControllerFacingMovingAverage = _headControllerFacing; // reset moving average _goToPending = false; // updateFromHMDSensorMatrix (called from paintGL) expects that the sensorToWorldMatrix is updated for any position changes // that happen between render and Application::update (which calls updateSensorToWorldMatrix to do so). @@ -700,7 +690,7 @@ void MyAvatar::update(float deltaTime) { emit positionGoneTo(); // Run safety tests as soon as we can after goToLocation, or clear if we're not colliding. _physicsSafetyPending = getCollisionsEnabled(); - _characterController.recomputeFlying(); // In case we've gone to into the sky. + _characterController.recomputeFlying(); // In case we've gone to into the sky. } if (_goToFeetAjustment && _skeletonModelLoaded) { auto feetAjustment = getWorldPosition() - getWorldFeetPosition(); @@ -712,7 +702,7 @@ void MyAvatar::update(float deltaTime) { // When needed and ready, arrange to check and fix. _physicsSafetyPending = false; if (_goToSafe) { - safeLanding(_goToPosition); // no-op if already safe + safeLanding(_goToPosition); // no-op if already safe } } @@ -720,7 +710,8 @@ void MyAvatar::update(float deltaTime) { head->relax(deltaTime); updateFromTrackers(deltaTime); - if (getIsInWalkingState() && glm::length(getControllerPoseInAvatarFrame(controller::Action::HEAD).getVelocity()) < DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { + if (getIsInWalkingState() && glm::length(getControllerPoseInAvatarFrame(controller::Action::HEAD).getVelocity()) < + DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { setIsInWalkingState(false); } @@ -731,12 +722,13 @@ void MyAvatar::update(float deltaTime) { setAudioLoudness(audio->getLastInputLoudness()); setAudioAverageLoudness(audio->getAudioAverageInputLoudness()); - glm::vec3 halfBoundingBoxDimensions(_characterController.getCapsuleRadius(), _characterController.getCapsuleHalfHeight(), _characterController.getCapsuleRadius()); + glm::vec3 halfBoundingBoxDimensions(_characterController.getCapsuleRadius(), _characterController.getCapsuleHalfHeight(), + _characterController.getCapsuleRadius()); // This might not be right! Isn't the capsule local offset in avatar space? -HRS 5/26/17 halfBoundingBoxDimensions += _characterController.getCapsuleLocalOffset(); QMetaObject::invokeMethod(audio, "setAvatarBoundingBoxParameters", - Q_ARG(glm::vec3, (getWorldPosition() - halfBoundingBoxDimensions)), - Q_ARG(glm::vec3, (halfBoundingBoxDimensions*2.0f))); + Q_ARG(glm::vec3, (getWorldPosition() - halfBoundingBoxDimensions)), + Q_ARG(glm::vec3, (halfBoundingBoxDimensions * 2.0f))); simulate(deltaTime, true); @@ -744,23 +736,20 @@ void MyAvatar::update(float deltaTime) { currentEnergy -= getAccelerationEnergy(); currentEnergy -= getAudioEnergy(); - if(didTeleport()) { + if (didTeleport()) { currentEnergy = 0.0f; } - currentEnergy = max(0.0f, min(currentEnergy,1.0f)); + currentEnergy = max(0.0f, min(currentEnergy, 1.0f)); emit energyChanged(currentEnergy); updateEyeContactTarget(deltaTime); } void MyAvatar::updateEyeContactTarget(float deltaTime) { - _eyeContactTargetTimer -= deltaTime; if (_eyeContactTargetTimer < 0.0f) { - const float CHANCE_OF_CHANGING_TARGET = 0.01f; if (randFloat() < CHANCE_OF_CHANGING_TARGET) { - float const FIFTY_FIFTY_CHANCE = 0.5f; float const EYE_TO_MOUTH_CHANCE = 0.25f; switch (_eyeContactTarget) { @@ -828,21 +817,20 @@ void MyAvatar::simulate(float deltaTime, bool inView) { if (isChildOfHead && !object->hasGrabs()) { // Cauterize or display children of head per head drawing state. updateChildCauterization(object, !_prevShouldDrawHead); - object->forEachDescendant([&](SpatiallyNestablePointer descendant) { - updateChildCauterization(descendant, !_prevShouldDrawHead); - }); + object->forEachDescendant( + [&](SpatiallyNestablePointer descendant) { updateChildCauterization(descendant, !_prevShouldDrawHead); }); _cauterizedChildrenOfHead.insert(object); objectsToUncauterize.erase(object); } else if (objectsToUncauterize.find(object) == objectsToUncauterize.end()) { objectsToUncauterize.insert(object); - object->forEachDescendant([&](SpatiallyNestablePointer descendant) { - objectsToUncauterize.insert(descendant); - }); + object->forEachDescendant( + [&](SpatiallyNestablePointer descendant) { objectsToUncauterize.insert(descendant); }); } }); // Redisplay cauterized entities that are no longer children of the avatar. - for (auto cauterizedChild = objectsToUncauterize.begin(); cauterizedChild != objectsToUncauterize.end(); cauterizedChild++) { + for (auto cauterizedChild = objectsToUncauterize.begin(); cauterizedChild != objectsToUncauterize.end(); + cauterizedChild++) { updateChildCauterization(*cauterizedChild, false); } } @@ -886,7 +874,7 @@ void MyAvatar::simulate(float deltaTime, bool inView) { if (!_skeletonModel->hasSkeleton()) { // All the simulation that can be done has been done - getHead()->setPosition(getWorldPosition()); // so audio-position isn't 0,0,0 + getHead()->setPosition(getWorldPosition()); // so audio-position isn't 0,0,0 return; } @@ -967,8 +955,7 @@ void MyAvatar::updateFromHMDSensorMatrix(const glm::mat4& hmdSensorMatrix) { _hmdSensorMatrix = hmdSensorMatrix; auto newHmdSensorPosition = extractTranslation(hmdSensorMatrix); - if (newHmdSensorPosition != getHMDSensorPosition() && - glm::length(newHmdSensorPosition) > MAX_HMD_ORIGIN_DISTANCE) { + if (newHmdSensorPosition != getHMDSensorPosition() && glm::length(newHmdSensorPosition) > MAX_HMD_ORIGIN_DISTANCE) { qWarning() << "Invalid HMD sensor position " << newHmdSensorPosition; // Ignore unreasonable HMD sensor data return; @@ -996,8 +983,8 @@ glm::vec2 MyAvatar::computeHandAzimuth() const { glm::vec2 latestHipToHandController = _hipToHandController; int spine2Index = _skeletonModel->getRig().indexOfJoint("Spine2"); - if (leftHandPoseAvatarSpace.isValid() && rightHandPoseAvatarSpace.isValid() && headPoseAvatarSpace.isValid() && !(spine2Index < 0)) { - + if (leftHandPoseAvatarSpace.isValid() && rightHandPoseAvatarSpace.isValid() && headPoseAvatarSpace.isValid() && + !(spine2Index < 0)) { glm::vec3 spine2Position = getAbsoluteJointTranslationInObjectFrame(spine2Index); glm::quat spine2Rotation = getAbsoluteJointRotationInObjectFrame(spine2Index); @@ -1009,8 +996,10 @@ glm::vec2 MyAvatar::computeHandAzimuth() const { // we need the old azimuth reading to prevent flipping the facing direction 180 // in the case where the hands go from being slightly less than 180 apart to slightly more than 180 apart. glm::vec2 oldAzimuthReading = _hipToHandController; - if ((glm::length(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)) > 0.0f) && (glm::length(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)) > 0.0f)) { - latestHipToHandController = lerp(glm::normalize(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)), glm::normalize(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)), HALFWAY); + if ((glm::length(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)) > 0.0f) && + (glm::length(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)) > 0.0f)) { + latestHipToHandController = lerp(glm::normalize(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)), + glm::normalize(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)), HALFWAY); } else { latestHipToHandController = glm::vec2(0.0f, 1.0f); } @@ -1058,11 +1047,11 @@ void MyAvatar::updateJointFromController(controller::Action poseKey, ThreadSafeV // update sensor to world matrix from current body position and hmd sensor. // This is so the correct camera can be used for rendering. void MyAvatar::updateSensorToWorldMatrix() { - // update the sensor mat so that the body position will end up in the desired // position when driven from the head. float sensorToWorldScale = getEyeHeight() / getUserEyeHeight(); - glm::mat4 desiredMat = createMatFromScaleQuatAndPos(glm::vec3(sensorToWorldScale), getWorldOrientation(), getWorldPosition()); + glm::mat4 desiredMat = + createMatFromScaleQuatAndPos(glm::vec3(sensorToWorldScale), getWorldOrientation(), getWorldPosition()); _sensorToWorldMatrix = desiredMat * glm::inverse(_bodySensorMatrix); bool hasSensorToWorldScaleChanged = false; @@ -1080,11 +1069,10 @@ void MyAvatar::updateSensorToWorldMatrix() { _sensorToWorldMatrixCache.set(_sensorToWorldMatrix); updateJointFromController(controller::Action::LEFT_HAND, _controllerLeftHandMatrixCache); updateJointFromController(controller::Action::RIGHT_HAND, _controllerRightHandMatrixCache); - + if (hasSensorToWorldScaleChanged) { emit sensorToWorldScaleChanged(sensorToWorldScale); } - } // Update avatar head rotation with sensor data @@ -1109,8 +1097,7 @@ void MyAvatar::updateFromTrackers(float deltaTime) { const float TRACKER_YAW_TURN_SENSITIVITY = 0.5f; const float TRACKER_MIN_YAW_TURN = 15.0f; const float TRACKER_MAX_YAW_TURN = 50.0f; - if ( (fabs(estimatedRotation.y) > TRACKER_MIN_YAW_TURN) && - (fabs(estimatedRotation.y) < TRACKER_MAX_YAW_TURN) ) { + if ((fabs(estimatedRotation.y) > TRACKER_MIN_YAW_TURN) && (fabs(estimatedRotation.y) < TRACKER_MAX_YAW_TURN)) { if (estimatedRotation.y > 0.0f) { _bodyYawDelta += (estimatedRotation.y - TRACKER_MIN_YAW_TURN) * TRACKER_YAW_TURN_SENSITIVITY; } else { @@ -1125,7 +1112,6 @@ void MyAvatar::updateFromTrackers(float deltaTime) { // their head only 30 degrees or so, this may correspond to a 90 degree field of view. // Note that roll is magnified by a constant because it is not related to field of view. - Head* head = getHead(); if (hasHead || playing) { head->setDeltaPitch(estimatedRotation.x); @@ -1191,15 +1177,15 @@ controller::Pose MyAvatar::getRightHandTipPose() const { void MyAvatar::render(RenderArgs* renderArgs) { // don't render if we've been asked to disable local rendering if (!_shouldRender) { - return; // exit early + return; // exit early } Avatar::render(renderArgs); } void MyAvatar::overrideAnimation(const QString& url, float fps, bool loop, float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "overrideAnimation", Q_ARG(const QString&, url), Q_ARG(float, fps), - Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); + QMetaObject::invokeMethod(this, "overrideAnimation", Q_ARG(const QString&, url), Q_ARG(float, fps), Q_ARG(bool, loop), + Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); return; } _skeletonModel->getRig().overrideAnimation(url, fps, loop, firstFrame, lastFrame); @@ -1207,8 +1193,8 @@ void MyAvatar::overrideAnimation(const QString& url, float fps, bool loop, float void MyAvatar::overrideHandAnimation(bool isLeft, const QString& url, float fps, bool loop, float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "overrideHandAnimation", Q_ARG(bool, isLeft), Q_ARG(const QString&, url), Q_ARG(float, fps), - Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); + QMetaObject::invokeMethod(this, "overrideHandAnimation", Q_ARG(bool, isLeft), Q_ARG(const QString&, url), + Q_ARG(float, fps), Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); return; } _skeletonModel->getRig().overrideHandAnimation(isLeft, url, fps, loop, firstFrame, lastFrame); @@ -1239,8 +1225,12 @@ QStringList MyAvatar::getAnimationRoles() { return _skeletonModel->getRig().getAnimationRoles(); } -void MyAvatar::overrideRoleAnimation(const QString& role, const QString& url, float fps, bool loop, - float firstFrame, float lastFrame) { +void MyAvatar::overrideRoleAnimation(const QString& role, + const QString& url, + float fps, + bool loop, + float firstFrame, + float lastFrame) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "overrideRoleAnimation", Q_ARG(const QString&, role), Q_ARG(const QString&, url), Q_ARG(float, fps), Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); @@ -1259,9 +1249,9 @@ void MyAvatar::restoreRoleAnimation(const QString& role) { void MyAvatar::saveAvatarUrl() { if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid()) { - _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() ? - "" : - _fullAvatarURLFromPreferences.toString()); + _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() + ? "" + : _fullAvatarURLFromPreferences.toString()); } } @@ -1278,10 +1268,12 @@ void MyAvatar::resizeAvatarEntitySettingHandles(uint32_t maxIndex) { uint32_t settingsIndex = (uint32_t)_avatarEntityIDSettings.size() + 1; while (settingsIndex <= maxIndex) { Setting::Handle idHandle(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" - << QString::number(settingsIndex) << "id", QUuid()); + << QString::number(settingsIndex) << "id", + QUuid()); _avatarEntityIDSettings.push_back(idHandle); Setting::Handle dataHandle(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" - << QString::number(settingsIndex) << "properties", QByteArray()); + << QString::number(settingsIndex) << "properties", + QByteArray()); _avatarEntityDataSettings.push_back(dataHandle); settingsIndex++; } @@ -1299,10 +1291,10 @@ void MyAvatar::saveData() { // only save the fullAvatarURL if it has not been overwritten on command line // (so the overrideURL is not valid), or it was overridden _and_ we specified // --replaceAvatarURL (so _saveAvatarOverrideUrl is true) - if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid() ) { - _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() ? - "" : - _fullAvatarURLFromPreferences.toString()); + if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid()) { + _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() + ? "" + : _fullAvatarURLFromPreferences.toString()); } _fullAvatarModelNameSetting.set(_fullAvatarModelName); @@ -1472,16 +1464,12 @@ void MyAvatar::setEnableInverseKinematics(bool isEnabled) { void MyAvatar::storeAvatarEntityDataPayload(const QUuid& entityID, const QByteArray& payload) { AvatarData::storeAvatarEntityDataPayload(entityID, payload); - _avatarEntitiesLock.withWriteLock([&] { - _cachedAvatarEntityBlobsToAddOrUpdate.push_back(entityID); - }); + _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobsToAddOrUpdate.push_back(entityID); }); } void MyAvatar::clearAvatarEntity(const QUuid& entityID, bool requiresRemovalFromTree) { AvatarData::clearAvatarEntity(entityID, requiresRemovalFromTree); - _avatarEntitiesLock.withWriteLock([&] { - _cachedAvatarEntityBlobsToDelete.push_back(entityID); - }); + _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobsToDelete.push_back(entityID); }); } void MyAvatar::sanitizeAvatarEntityProperties(EntityItemProperties& properties) const { @@ -1506,9 +1494,7 @@ void MyAvatar::sanitizeAvatarEntityProperties(EntityItemProperties& properties) void MyAvatar::handleChangedAvatarEntityData() { // NOTE: this is a per-frame update - if (getID().isNull() || - getID() == AVATAR_SELF_ID || - DependencyManager::get()->getSessionUUID() == QUuid()) { + if (getID().isNull() || getID() == AVATAR_SELF_ID || DependencyManager::get()->getSessionUUID() == QUuid()) { // wait until MyAvatar and this Node gets an ID before doing this. Otherwise, various things go wrong: // things get their parent fixed up from AVATAR_SELF_ID to a null uuid which means "no parent". return; @@ -1554,7 +1540,7 @@ void MyAvatar::handleChangedAvatarEntityData() { entitiesToUpdate = std::move(_entitiesToUpdate); }); - auto removeAllInstancesHelper = [] (const QUuid& id, std::vector& v) { + auto removeAllInstancesHelper = [](const QUuid& id, std::vector& v) { uint32_t i = 0; while (i < v.size()) { if (id == v[i]) { @@ -1582,9 +1568,7 @@ void MyAvatar::handleChangedAvatarEntityData() { // DELETE real entities for (const auto& id : entitiesToDelete) { - entityTree->withWriteLock([&] { - entityTree->deleteEntity(id); - }); + entityTree->withWriteLock([&] { entityTree->deleteEntity(id); }); } // ADD real entities @@ -1595,21 +1579,19 @@ void MyAvatar::handleChangedAvatarEntityData() { _avatarEntitiesLock.withReadLock([&] { AvatarEntityMap::iterator itr = _cachedAvatarEntityBlobs.find(id); if (itr == _cachedAvatarEntityBlobs.end()) { - blobFailed = true; // blob doesn't exist + blobFailed = true; // blob doesn't exist return; } std::lock_guard guard(_scriptEngineLock); if (!EntityItemProperties::blobToProperties(*_scriptEngine, itr.value(), properties)) { - blobFailed = true; // blob is corrupt + blobFailed = true; // blob is corrupt } }); if (blobFailed) { // remove from _cachedAvatarEntityBlobUpdatesToSkip just in case: // avoids a resource leak when blob updates to be skipped are never actually skipped // when the blob fails to result in a real EntityItem - _avatarEntitiesLock.withWriteLock([&] { - removeAllInstancesHelper(id, _cachedAvatarEntityBlobUpdatesToSkip); - }); + _avatarEntitiesLock.withWriteLock([&] { removeAllInstancesHelper(id, _cachedAvatarEntityBlobUpdatesToSkip); }); continue; } sanitizeAvatarEntityProperties(properties); @@ -1679,7 +1661,7 @@ void MyAvatar::handleChangedAvatarEntityData() { _cachedAvatarEntityBlobUpdatesToSkip[i] = _cachedAvatarEntityBlobUpdatesToSkip.back(); _cachedAvatarEntityBlobUpdatesToSkip.pop_back(); skip = true; - break; // assume no duplicates + break; // assume no duplicates } else { ++i; } @@ -1743,9 +1725,7 @@ bool MyAvatar::updateStaleAvatarEntityBlobs() const { std::lock_guard guard(_scriptEngineLock); EntityItemProperties::propertiesToBlob(*_scriptEngine, getID(), properties, blob); } - _avatarEntitiesLock.withWriteLock([&] { - _cachedAvatarEntityBlobs[id] = blob; - }); + _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobs[id] = blob; }); } } return true; @@ -1772,9 +1752,7 @@ AvatarEntityMap MyAvatar::getAvatarEntityData() const { // NOTE: the return value is expected to be a map of unfortunately-formatted-binary-blobs updateStaleAvatarEntityBlobs(); AvatarEntityMap result; - _avatarEntitiesLock.withReadLock([&] { - result = _cachedAvatarEntityBlobs; - }); + _avatarEntitiesLock.withReadLock([&] { result = _cachedAvatarEntityBlobs; }); return result; } @@ -1875,7 +1853,9 @@ void MyAvatar::avatarEntityDataToJson(QJsonObject& root) const { AvatarEntityMap::const_iterator itr = _cachedAvatarEntityBlobs.begin(); while (itr != _cachedAvatarEntityBlobs.end()) { QVariantMap entityData; - QUuid id = _avatarEntityForRecording.size() == _cachedAvatarEntityBlobs.size() ? _avatarEntityForRecording.values()[entityCount++] : itr.key(); + QUuid id = _avatarEntityForRecording.size() == _cachedAvatarEntityBlobs.size() + ? _avatarEntityForRecording.values()[entityCount++] + : itr.key(); entityData.insert("id", id); entityData.insert("properties", itr.value().toBase64()); avatarEntityJson.push_back(QVariant(entityData).toJsonObject()); @@ -1905,7 +1885,7 @@ void MyAvatar::loadData() { loadAvatarEntityDataFromSettings(); // Flying preferences must be loaded before calling setFlyingEnabled() - Setting::Handle firstRunVal { Settings::firstRun, true }; + Setting::Handle firstRunVal{ Settings::firstRun, true }; setFlyingHMDPref(firstRunVal.get() ? false : _flyingHMDSetting.get()); setMovementReference(firstRunVal.get() ? false : _movementReferenceSetting.get()); setDriveGear1(firstRunVal.get() ? DEFAULT_GEAR_1 : _driveGear1Setting.get()); @@ -1931,7 +1911,7 @@ void MyAvatar::loadData() { setUserRecenterModel(stringToUserRecenterModel(_userRecenterModelSetting.get(USER_RECENTER_MODEL_AUTO))); setEnableMeshVisible(Menu::getInstance()->isOptionChecked(MenuOption::MeshVisible)); - _follow.setToggleHipsFollowing (Menu::getInstance()->isOptionChecked(MenuOption::ToggleHipsFollowing)); + _follow.setToggleHipsFollowing(Menu::getInstance()->isOptionChecked(MenuOption::ToggleHipsFollowing)); setEnableDebugDrawBaseOfSupport(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawBaseOfSupport)); setEnableDebugDrawDefaultPose(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawDefaultPose)); setEnableDebugDrawAnimPose(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawAnimPose)); @@ -1959,7 +1939,7 @@ void MyAvatar::loadAvatarEntityDataFromSettings() { _entitiesToAdd.reserve(numEntities); // TODO: build map between old and new IDs so we can restitch parent-child relationships for (int i = 0; i < numEntities; i++) { - QUuid id = QUuid::createUuid(); // generate a new ID + QUuid id = QUuid::createUuid(); // generate a new ID _cachedAvatarEntityBlobs[id] = _avatarEntityDataSettings[i].get(); _entitiesToAdd.push_back(id); // this blob is the "authoritative source" for this AvatarEntity and we want to avoid overwriting it @@ -2029,10 +2009,9 @@ AttachmentData MyAvatar::loadAttachmentData(const QUrl& modelURL, const QString& return attachment; } - int MyAvatar::parseDataFromBuffer(const QByteArray& buffer) { qCDebug(interfaceapp) << "Error: ignoring update packet for MyAvatar" - << " packetLength = " << buffer.size(); + << " packetLength = " << buffer.size(); // this packet is just bad, so we pretend that we unpacked it ALL return buffer.size(); } @@ -2046,8 +2025,12 @@ ScriptAvatarData* MyAvatar::getTargetAvatar() const { } } -static float lookAtCostFunction(const glm::vec3& myForward, const glm::vec3& myPosition, const glm::vec3& otherForward, const glm::vec3& otherPosition, - bool otherIsTalking, bool lookingAtOtherAlready) { +static float lookAtCostFunction(const glm::vec3& myForward, + const glm::vec3& myPosition, + const glm::vec3& otherForward, + const glm::vec3& otherPosition, + bool otherIsTalking, + bool lookingAtOtherAlready) { const float DISTANCE_FACTOR = 3.14f; const float MY_ANGLE_FACTOR = 1.0f; const float OTHER_ANGLE_FACTOR = 1.0f; @@ -2055,7 +2038,7 @@ static float lookAtCostFunction(const glm::vec3& myForward, const glm::vec3& myP const float LOOKING_AT_OTHER_ALREADY_TERM = lookingAtOtherAlready ? -0.2f : 0.0f; const float GREATEST_LOOKING_AT_DISTANCE = 10.0f; // meters - const float MAX_MY_ANGLE = PI / 8.0f; // 22.5 degrees, Don't look too far away from the head facing. + const float MAX_MY_ANGLE = PI / 8.0f; // 22.5 degrees, Don't look too far away from the head facing. const float MAX_OTHER_ANGLE = (3.0f * PI) / 4.0f; // 135 degrees, Don't stare at the back of another avatars head. glm::vec3 d = otherPosition - myPosition; @@ -2067,11 +2050,8 @@ static float lookAtCostFunction(const glm::vec3& myForward, const glm::vec3& myP if (distance > GREATEST_LOOKING_AT_DISTANCE || myAngle > MAX_MY_ANGLE || otherAngle > MAX_OTHER_ANGLE) { return FLT_MAX; } else { - return (DISTANCE_FACTOR * distance + - MY_ANGLE_FACTOR * myAngle + - OTHER_ANGLE_FACTOR * otherAngle + - OTHER_IS_TALKING_TERM + - LOOKING_AT_OTHER_ALREADY_TERM); + return (DISTANCE_FACTOR * distance + MY_ANGLE_FACTOR * myAngle + OTHER_ANGLE_FACTOR * otherAngle + + OTHER_IS_TALKING_TERM + LOOKING_AT_OTHER_ALREADY_TERM); } } @@ -2094,7 +2074,8 @@ void MyAvatar::computeMyLookAtTarget(const AvatarHash& hash) { const float TIME_WITHOUT_TALKING_THRESHOLD = 1.0f; bool otherIsTalking = avatar->getHead()->getTimeWithoutTalking() <= TIME_WITHOUT_TALKING_THRESHOLD; bool lookingAtOtherAlready = _lookAtTargetAvatar.lock().get() == avatar.get(); - float cost = lookAtCostFunction(myForward, myPosition, otherForward, otherPosition, otherIsTalking, lookingAtOtherAlready); + float cost = + lookAtCostFunction(myForward, myPosition, otherForward, otherPosition, otherIsTalking, lookingAtOtherAlready); if (cost < bestCost) { bestCost = cost; bestAvatar = avatar; @@ -2115,9 +2096,8 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { std::shared_ptr avatar = std::static_pointer_cast(avatarData); if (!avatar->isMyAvatar() && avatar->isInitialized()) { if (_lookAtSnappingEnabled && avatar->getLookAtSnappingEnabled() && isLookingAtMe(avatar)) { - // Alter their gaze to look directly at my camera; this looks more natural than looking at my avatar's face. - glm::vec3 lookAtPosition = avatar->getHead()->getLookAtPosition(); // A position, in world space, on my avatar. + glm::vec3 lookAtPosition = avatar->getHead()->getLookAtPosition(); // A position, in world space, on my avatar. // The camera isn't at the point midway between the avatar eyes. (Even without an HMD, the head can be offset a bit.) // Let's get everything to world space: @@ -2128,12 +2108,12 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { // (We will be adding that offset to the camera position, after making some other adjustments.) glm::vec3 gazeOffset = lookAtPosition - getHead()->getEyePosition(); - ViewFrustum viewFrustum; - qApp->copyViewFrustum(viewFrustum); + ViewFrustum viewFrustum; + qApp->copyViewFrustum(viewFrustum); - glm::vec3 viewPosition = viewFrustum.getPosition(); + glm::vec3 viewPosition = viewFrustum.getPosition(); #if DEBUG_ALWAYS_LOOKAT_EYES_NOT_CAMERA - viewPosition = (avatarLeftEye + avatarRightEye) / 2.0f; + viewPosition = (avatarLeftEye + avatarRightEye) / 2.0f; #endif // scale gazeOffset by IPD, if wearing an HMD. if (qApp->isHMDMode()) { @@ -2171,7 +2151,6 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { } void MyAvatar::updateLookAtTargetAvatar() { - // The AvatarManager is a mutable class shared by many threads. We make a thread-safe deep copy of it, // to avoid having to hold a lock while we iterate over all the avatars within. AvatarHash hash = DependencyManager::get()->getHashCopy(); @@ -2285,8 +2264,7 @@ void MyAvatar::setJointTranslation(int index, const glm::vec3& translation) { } default: { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "setJointTranslation", - Q_ARG(int, index), Q_ARG(const glm::vec3&, translation)); + QMetaObject::invokeMethod(this, "setJointTranslation", Q_ARG(int, index), Q_ARG(const glm::vec3&, translation)); return; } // HACK: ATM only JS scripts call setJointData() on MyAvatar so we hardcode the priority @@ -2325,9 +2303,7 @@ void MyAvatar::setJointData(const QString& name, const glm::quat& rotation, cons Q_ARG(const glm::vec3&, translation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { - setJointData(index, rotation, translation); - }); + writeLockWithNamedJointIndex(name, [&](int index) { setJointData(index, rotation, translation); }); } void MyAvatar::setJointRotation(const QString& name, const glm::quat& rotation) { @@ -2335,9 +2311,7 @@ void MyAvatar::setJointRotation(const QString& name, const glm::quat& rotation) QMetaObject::invokeMethod(this, "setJointRotation", Q_ARG(QString, name), Q_ARG(const glm::quat&, rotation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { - setJointRotation(index, rotation); - }); + writeLockWithNamedJointIndex(name, [&](int index) { setJointRotation(index, rotation); }); } void MyAvatar::setJointTranslation(const QString& name, const glm::vec3& translation) { @@ -2345,9 +2319,7 @@ void MyAvatar::setJointTranslation(const QString& name, const glm::vec3& transla QMetaObject::invokeMethod(this, "setJointTranslation", Q_ARG(QString, name), Q_ARG(const glm::vec3&, translation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { - setJointTranslation(index, translation); - }); + writeLockWithNamedJointIndex(name, [&](int index) { setJointTranslation(index, translation); }); } void MyAvatar::clearJointData(const QString& name) { @@ -2355,9 +2327,7 @@ void MyAvatar::clearJointData(const QString& name) { QMetaObject::invokeMethod(this, "clearJointData", Q_ARG(QString, name)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { - clearJointData(index); - }); + writeLockWithNamedJointIndex(name, [&](int index) { clearJointData(index); }); } void MyAvatar::clearJointsData() { @@ -2392,36 +2362,36 @@ void MyAvatar::setSkeletonModelURL(const QUrl& skeletonModelURL) { _skeletonModelLoaded = false; std::shared_ptr skeletonConnection = std::make_shared(); - *skeletonConnection = QObject::connect(_skeletonModel.get(), &SkeletonModel::skeletonLoaded, [this, skeletonModelChangeCount, skeletonConnection]() { - if (skeletonModelChangeCount == _skeletonModelChangeCount) { + *skeletonConnection = QObject::connect(_skeletonModel.get(), &SkeletonModel::skeletonLoaded, + [this, skeletonModelChangeCount, skeletonConnection]() { + if (skeletonModelChangeCount == _skeletonModelChangeCount) { + if (_fullAvatarModelName.isEmpty()) { + // Store the FST file name into preferences + const auto& mapping = _skeletonModel->getGeometry()->getMapping(); + if (mapping.value("name").isValid()) { + _fullAvatarModelName = mapping.value("name").toString(); + } + } - if (_fullAvatarModelName.isEmpty()) { - // Store the FST file name into preferences - const auto& mapping = _skeletonModel->getGeometry()->getMapping(); - if (mapping.value("name").isValid()) { - _fullAvatarModelName = mapping.value("name").toString(); - } - } + initHeadBones(); + _skeletonModel->setCauterizeBoneSet(_headBoneSet); + _fstAnimGraphOverrideUrl = + _skeletonModel->getGeometry()->getAnimGraphOverrideUrl(); + initAnimGraph(); + initFlowFromFST(); - initHeadBones(); - _skeletonModel->setCauterizeBoneSet(_headBoneSet); - _fstAnimGraphOverrideUrl = _skeletonModel->getGeometry()->getAnimGraphOverrideUrl(); - initAnimGraph(); - initFlowFromFST(); + _skeletonModelLoaded = true; + } + QObject::disconnect(*skeletonConnection); + }); - _skeletonModelLoaded = true; - } - QObject::disconnect(*skeletonConnection); - }); - saveAvatarUrl(); emit skeletonChanged(); } bool isWearableEntity(const EntityItemPointer& entity) { - return entity->isVisible() - && (entity->getParentID() == DependencyManager::get()->getSessionUUID() - || entity->getParentID() == AVATAR_SELF_ID); + return entity->isVisible() && (entity->getParentID() == DependencyManager::get()->getSessionUUID() || + entity->getParentID() == AVATAR_SELF_ID); } void MyAvatar::removeWornAvatarEntity(const EntityItemID& entityID) { @@ -2445,9 +2415,7 @@ void MyAvatar::removeWornAvatarEntity(const EntityItemID& entityID) { void MyAvatar::clearWornAvatarEntities() { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { - avatarEntityIDs = _packedAvatarEntityData.keys(); - }); + _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); for (auto entityID : avatarEntityIDs) { removeWornAvatarEntity(entityID); } @@ -2473,9 +2441,7 @@ QVariantList MyAvatar::getAvatarEntitiesVariant() { EntityTreePointer entityTree = treeRenderer ? treeRenderer->getTree() : nullptr; if (entityTree) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { - avatarEntityIDs = _packedAvatarEntityData.keys(); - }); + _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); for (const auto& entityID : avatarEntityIDs) { auto entity = entityTree->findEntityByID(entityID); if (!entity) { @@ -2500,7 +2466,6 @@ QVariantList MyAvatar::getAvatarEntitiesVariant() { return avatarEntitiesData; } - void MyAvatar::resetFullAvatarURL() { auto lastAvatarURL = getFullAvatarURLFromPreferences(); auto lastAvatarName = getFullAvatarModelName(); @@ -2509,11 +2474,8 @@ void MyAvatar::resetFullAvatarURL() { } void MyAvatar::useFullAvatarURL(const QUrl& fullAvatarURL, const QString& modelName) { - if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "useFullAvatarURL", - Q_ARG(const QUrl&, fullAvatarURL), - Q_ARG(const QString&, modelName)); + BLOCKING_INVOKE_METHOD(this, "useFullAvatarURL", Q_ARG(const QUrl&, fullAvatarURL), Q_ARG(const QString&, modelName)); return; } @@ -2567,7 +2529,7 @@ controller::Pose MyAvatar::getControllerPoseInSensorFrame(controller::Action act if (iter != _controllerPoseMap.end()) { return iter->second; } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2576,7 +2538,7 @@ controller::Pose MyAvatar::getControllerPoseInWorldFrame(controller::Action acti if (pose.valid) { return pose.transform(getSensorToWorldMatrix()); } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2586,7 +2548,7 @@ controller::Pose MyAvatar::getControllerPoseInAvatarFrame(controller::Action act glm::mat4 invAvatarMatrix = glm::inverse(createMatFromQuatAndPos(getWorldOrientation(), getWorldPosition())); return pose.transform(invAvatarMatrix); } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2608,7 +2570,7 @@ void MyAvatar::updateMotors() { float verticalMotorTimescale; if (_characterController.getState() == CharacterController::State::Hover || - _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { + _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { horizontalMotorTimescale = FLYING_MOTOR_TIMESCALE; verticalMotorTimescale = FLYING_MOTOR_TIMESCALE; } else { @@ -2618,7 +2580,7 @@ void MyAvatar::updateMotors() { if (_motionBehaviors & AVATAR_MOTION_ACTION_MOTOR_ENABLED) { if (_characterController.getState() == CharacterController::State::Hover || - _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { + _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { motorRotation = getMyHead()->getHeadOrientation(); } else { // non-hovering = walking: follow camera twist about vertical but not lift @@ -2626,14 +2588,15 @@ void MyAvatar::updateMotors() { // however, we need to perform the decomposition in the avatar-frame // using the local UP axis and then transform back into world-frame glm::quat orientation = getWorldOrientation(); - glm::quat headOrientation = glm::inverse(orientation) * getMyHead()->getHeadOrientation(); // avatar-frame + glm::quat headOrientation = glm::inverse(orientation) * getMyHead()->getHeadOrientation(); // avatar-frame glm::quat liftRotation; swingTwistDecomposition(headOrientation, Vectors::UNIT_Y, liftRotation, motorRotation); motorRotation = orientation * motorRotation; } if (_isPushing || _isBraking || !_isBeingPushed) { - _characterController.addMotor(_actionMotorVelocity, motorRotation, horizontalMotorTimescale, verticalMotorTimescale); + _characterController.addMotor(_actionMotorVelocity, motorRotation, horizontalMotorTimescale, + verticalMotorTimescale); } else { // _isBeingPushed must be true --> disable action motor by giving it a long timescale, // otherwise it's attempt to "stand in in place" could defeat scripted motor/thrusts @@ -2653,7 +2616,8 @@ void MyAvatar::updateMotors() { _characterController.addMotor(_scriptedMotorVelocity, motorRotation, _scriptedMotorTimescale); } else { // dynamic mode - _characterController.addMotor(_scriptedMotorVelocity, motorRotation, horizontalMotorTimescale, verticalMotorTimescale); + _characterController.addMotor(_scriptedMotorVelocity, motorRotation, horizontalMotorTimescale, + verticalMotorTimescale); } } @@ -2758,8 +2722,7 @@ void MyAvatar::setScriptedMotorVelocity(const glm::vec3& velocity) { void MyAvatar::setScriptedMotorTimescale(float timescale) { // we clamp the timescale on the large side (instead of just the low side) to prevent // obnoxiously large values from introducing NaN into avatar's velocity - _scriptedMotorTimescale = glm::clamp(timescale, MIN_SCRIPTED_MOTOR_TIMESCALE, - DEFAULT_SCRIPTED_MOTOR_TIMESCALE); + _scriptedMotorTimescale = glm::clamp(timescale, MIN_SCRIPTED_MOTOR_TIMESCALE, DEFAULT_SCRIPTED_MOTOR_TIMESCALE); } void MyAvatar::setScriptedMotorFrame(QString frame) { @@ -2800,21 +2763,18 @@ SharedSoundPointer MyAvatar::getCollisionSound() { return _collisionSound; } -void MyAvatar::attach(const QString& modelURL, const QString& jointName, - const glm::vec3& translation, const glm::quat& rotation, - float scale, bool isSoft, - bool allowDuplicates, bool useSaved) { +void MyAvatar::attach(const QString& modelURL, + const QString& jointName, + const glm::vec3& translation, + const glm::quat& rotation, + float scale, + bool isSoft, + bool allowDuplicates, + bool useSaved) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "attach", - Q_ARG(const QString&, modelURL), - Q_ARG(const QString&, jointName), - Q_ARG(const glm::vec3&, translation), - Q_ARG(const glm::quat&, rotation), - Q_ARG(float, scale), - Q_ARG(bool, isSoft), - Q_ARG(bool, allowDuplicates), - Q_ARG(bool, useSaved) - ); + BLOCKING_INVOKE_METHOD(this, "attach", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName), + Q_ARG(const glm::vec3&, translation), Q_ARG(const glm::quat&, rotation), Q_ARG(float, scale), + Q_ARG(bool, isSoft), Q_ARG(bool, allowDuplicates), Q_ARG(bool, useSaved)); return; } AttachmentData data; @@ -2832,10 +2792,7 @@ void MyAvatar::attach(const QString& modelURL, const QString& jointName, void MyAvatar::detachOne(const QString& modelURL, const QString& jointName) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "detachOne", - Q_ARG(const QString&, modelURL), - Q_ARG(const QString&, jointName) - ); + BLOCKING_INVOKE_METHOD(this, "detachOne", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName)); return; } QUuid entityID; @@ -2847,10 +2804,7 @@ void MyAvatar::detachOne(const QString& modelURL, const QString& jointName) { void MyAvatar::detachAll(const QString& modelURL, const QString& jointName) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "detachAll", - Q_ARG(const QString&, modelURL), - Q_ARG(const QString&, jointName) - ); + BLOCKING_INVOKE_METHOD(this, "detachAll", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName)); return; } QUuid entityID; @@ -2862,8 +2816,7 @@ void MyAvatar::detachAll(const QString& modelURL, const QString& jointName) { void MyAvatar::setAttachmentData(const QVector& attachmentData) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "setAttachmentData", - Q_ARG(const QVector&, attachmentData)); + BLOCKING_INVOKE_METHOD(this, "setAttachmentData", Q_ARG(const QVector&, attachmentData)); return; } std::vector newEntitiesProperties; @@ -2886,12 +2839,10 @@ void MyAvatar::setAttachmentData(const QVector& attachmentData) emit attachmentsChanged(); } -QVector MyAvatar::getAttachmentData() const { +QVector MyAvatar::getAttachmentData() const { QVector attachmentData; QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { - avatarEntityIDs = _packedAvatarEntityData.keys(); - }); + _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); for (const auto& entityID : avatarEntityIDs) { auto properties = DependencyManager::get()->getEntityProperties(entityID); AttachmentData data = entityPropertiesToAttachmentData(properties); @@ -2910,8 +2861,7 @@ QVariantList MyAvatar::getAttachmentsVariant() const { void MyAvatar::setAttachmentsVariant(const QVariantList& variant) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "setAttachmentsVariant", - Q_ARG(const QVariantList&, variant)); + BLOCKING_INVOKE_METHOD(this, "setAttachmentsVariant", Q_ARG(const QVariantList&, variant)); return; } QVector newAttachments; @@ -2922,14 +2872,12 @@ void MyAvatar::setAttachmentsVariant(const QVariantList& variant) { newAttachments.append(attachment); } } - setAttachmentData(newAttachments); + setAttachmentData(newAttachments); } bool MyAvatar::findAvatarEntity(const QString& modelURL, const QString& jointName, QUuid& entityID) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { - avatarEntityIDs = _packedAvatarEntityData.keys(); - }); + _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); for (const auto& entityID : avatarEntityIDs) { auto props = DependencyManager::get()->getEntityProperties(entityID); if (props.getModelURL() == modelURL && @@ -3030,7 +2978,7 @@ void MyAvatar::setAnimGraphUrl(const QUrl& url) { emit animGraphUrlChanged(url); destroyAnimGraph(); - _skeletonModel->reset(); // Why is this necessary? Without this, we crash in the next render. + _skeletonModel->reset(); // Why is this necessary? Without this, we crash in the next render. _currentAnimGraphUrl.set(url); _skeletonModel->getRig().initAnimGraph(url); @@ -3063,18 +3011,16 @@ void MyAvatar::destroyAnimGraph() { } void MyAvatar::animGraphLoaded() { - _bodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. - updateSensorToWorldMatrix(); // Uses updated position/orientation and _bodySensorMatrix changes + _bodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + updateSensorToWorldMatrix(); // Uses updated position/orientation and _bodySensorMatrix changes _isAnimatingScale = true; _cauterizationNeedsUpdate = true; disconnect(&(_skeletonModel->getRig()), SIGNAL(onLoadComplete()), this, SLOT(animGraphLoaded())); } void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { - Avatar::postUpdate(deltaTime, scene); if (_enableDebugDrawDefaultPose || _enableDebugDrawAnimPose) { - auto animSkeleton = _skeletonModel->getRig().getAnimSkeleton(); // the rig is in the skeletonModel frame @@ -3082,7 +3028,8 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { if (_enableDebugDrawDefaultPose && animSkeleton) { glm::vec4 gray(0.2f, 0.2f, 0.2f, 0.2f); - AnimDebugDraw::getInstance().addAbsolutePoses("myAvatarDefaultPoses", animSkeleton, _skeletonModel->getRig().getAbsoluteDefaultPoses(), xform, gray); + AnimDebugDraw::getInstance().addAbsolutePoses("myAvatarDefaultPoses", animSkeleton, + _skeletonModel->getRig().getAbsoluteDefaultPoses(), xform, gray); } if (_enableDebugDrawAnimPose && animSkeleton) { @@ -3103,13 +3050,15 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { auto rightHandPose = getControllerPoseInWorldFrame(controller::Action::RIGHT_HAND); if (leftHandPose.isValid()) { - DebugDraw::getInstance().addMarker("leftHandController", leftHandPose.getRotation(), leftHandPose.getTranslation(), glm::vec4(1)); + DebugDraw::getInstance().addMarker("leftHandController", leftHandPose.getRotation(), leftHandPose.getTranslation(), + glm::vec4(1)); } else { DebugDraw::getInstance().removeMarker("leftHandController"); } if (rightHandPose.isValid()) { - DebugDraw::getInstance().addMarker("rightHandController", rightHandPose.getRotation(), rightHandPose.getTranslation(), glm::vec4(1)); + DebugDraw::getInstance().addMarker("rightHandController", rightHandPose.getRotation(), + rightHandPose.getTranslation(), glm::vec4(1)); } else { DebugDraw::getInstance().removeMarker("rightHandController"); } @@ -3126,14 +3075,9 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { AnimPose rigToWorldPose(glm::vec3(1.0f), getWorldOrientation() * Quaternions::Y_180, getWorldPosition()); const int NUM_DEBUG_COLORS = 8; const glm::vec4 DEBUG_COLORS[NUM_DEBUG_COLORS] = { - glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), - glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), - glm::vec4(0.0f, 1.0f, 0.0f, 1.0f), - glm::vec4(0.25f, 0.25f, 1.0f, 1.0f), - glm::vec4(1.0f, 1.0f, 0.0f, 1.0f), - glm::vec4(0.25f, 1.0f, 1.0f, 1.0f), - glm::vec4(1.0f, 0.25f, 1.0f, 1.0f), - glm::vec4(1.0f, 0.65f, 0.0f, 1.0f) // Orange you glad I added this color? + glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 1.0f), + glm::vec4(0.25f, 0.25f, 1.0f, 1.0f), glm::vec4(1.0f, 1.0f, 0.0f, 1.0f), glm::vec4(0.25f, 1.0f, 1.0f, 1.0f), + glm::vec4(1.0f, 0.25f, 1.0f, 1.0f), glm::vec4(1.0f, 0.65f, 0.0f, 1.0f) // Orange you glad I added this color? }; if (_skeletonModel && _skeletonModel->isLoaded()) { @@ -3144,7 +3088,7 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { AnimPose jointPose; rig.getAbsoluteJointPoseInRigFrame(i, jointPose); const AnimPose pose = rigToWorldPose * jointPose; - auto &multiSphere = _multiSphereShapes[i]; + auto& multiSphere = _multiSphereShapes[i]; auto debugLines = multiSphere.getDebugLines(); DebugDraw::getInstance().drawRays(debugLines, DEBUG_COLORS[i % NUM_DEBUG_COLORS], pose.trans(), pose.rot()); } @@ -3154,7 +3098,6 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { } void MyAvatar::preDisplaySide(const RenderArgs* renderArgs) { - // toggle using the cauterizedBones depending on where the camera is and the rendering pass type. const bool shouldDrawHead = shouldRenderHead(renderArgs); if (shouldDrawHead != _prevShouldDrawHead) { @@ -3199,7 +3142,7 @@ int MyAvatar::sendAvatarDataPacket(bool sendAll) { // Compute the next send window based on how much data we sent and what // data rate we're trying to max at. - milliseconds timeUntilNextSend { bytesSent / maxDataRateBytesPerMilliseconds }; + milliseconds timeUntilNextSend{ bytesSent / maxDataRateBytesPerMilliseconds }; _nextTraitsSendWindow += timeUntilNextSend; // Don't let the next send window lag behind if we're not sending a lot of data. @@ -3284,7 +3227,6 @@ void MyAvatar::setRotationThreshold(float angleRadians) { } void MyAvatar::updateOrientation(float deltaTime) { - // Smoothly rotate body with arrow keys float targetSpeed = getDriveKey(YAW) * _yawSpeed; if (targetSpeed != 0.0f) { @@ -3323,8 +3265,8 @@ void MyAvatar::updateOrientation(float deltaTime) { } // Use head/HMD roll to turn while flying, but not when standing still. - if (qApp->isHMDMode() && getCharacterController()->getState() == CharacterController::State::Hover && _hmdRollControlEnabled && hasDriveInput()) { - + if (qApp->isHMDMode() && getCharacterController()->getState() == CharacterController::State::Hover && + _hmdRollControlEnabled && hasDriveInput()) { // Turn with head roll. const float MIN_CONTROL_SPEED = 2.0f * getSensorToWorldScale(); // meters / sec const glm::vec3 characterForward = getWorldOrientation() * Vectors::UNIT_NEG_Z; @@ -3332,7 +3274,6 @@ void MyAvatar::updateOrientation(float deltaTime) { // only enable roll-turns if we are moving forward or backward at greater then MIN_CONTROL_SPEED if (fabsf(forwardSpeed) >= MIN_CONTROL_SPEED) { - float direction = forwardSpeed > 0.0f ? 1.0f : -1.0f; float rollAngle = glm::degrees(asinf(glm::dot(IDENTITY_UP, _hmdSensorOrientation * IDENTITY_RIGHT))); float rollSign = rollAngle < 0.0f ? -1.0f : 1.0f; @@ -3379,8 +3320,8 @@ void MyAvatar::updateOrientation(float deltaTime) { head->setBaseRoll(ROLL(euler)); } else { head->setBaseYaw(0.0f); - head->setBasePitch(getHead()->getBasePitch() + getDriveKey(PITCH) * _pitchSpeed * deltaTime - + getDriveKey(DELTA_PITCH) * _pitchSpeed / PITCH_SPEED_DEFAULT); + head->setBasePitch(getHead()->getBasePitch() + getDriveKey(PITCH) * _pitchSpeed * deltaTime + + getDriveKey(DELTA_PITCH) * _pitchSpeed / PITCH_SPEED_DEFAULT); head->setBaseRoll(0.0f); } } @@ -3390,20 +3331,15 @@ float MyAvatar::calculateGearedSpeed(const float driveKey) { float sign = (driveKey < 0.0f) ? -1.0f : 1.0f; if (absDriveKey > getDriveGear5()) { return sign * 1.0f; - } - else if (absDriveKey > getDriveGear4()) { + } else if (absDriveKey > getDriveGear4()) { return sign * 0.8f; - } - else if (absDriveKey > getDriveGear3()) { + } else if (absDriveKey > getDriveGear3()) { return sign * 0.6f; - } - else if (absDriveKey > getDriveGear2()) { + } else if (absDriveKey > getDriveGear2()) { return sign * 0.4f; - } - else if (absDriveKey > getDriveGear1()) { + } else if (absDriveKey > getDriveGear1()) { return sign * 0.2f; - } - else { + } else { return sign * 0.0f; } } @@ -3435,8 +3371,10 @@ glm::vec3 MyAvatar::scaleMotorSpeed(const glm::vec3 forward, const glm::vec3 rig case LocomotionControlsMode::CONTROLS_ANALOG: case LocomotionControlsMode::CONTROLS_ANALOG_PLUS: if (zSpeed || xSpeed) { - glm::vec3 scaledForward = getSensorToWorldScale() * calculateGearedSpeed(zSpeed) * _walkSpeedScalar * ((zSpeed >= stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * forward; - glm::vec3 scaledRight = getSensorToWorldScale() * calculateGearedSpeed(xSpeed) * _walkSpeedScalar * ((xSpeed > stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * right; + glm::vec3 scaledForward = getSensorToWorldScale() * calculateGearedSpeed(zSpeed) * _walkSpeedScalar * + ((zSpeed >= stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * forward; + glm::vec3 scaledRight = getSensorToWorldScale() * calculateGearedSpeed(xSpeed) * _walkSpeedScalar * + ((xSpeed > stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * right; direction = scaledForward + scaledRight; return direction; } else { @@ -3458,7 +3396,7 @@ glm::vec3 MyAvatar::scaleMotorSpeed(const glm::vec3 forward, const glm::vec3 rig } } -glm::vec3 MyAvatar::calculateScaledDirection(){ +glm::vec3 MyAvatar::calculateScaledDirection() { CharacterController::State state = _characterController.getState(); // compute action input @@ -3514,8 +3452,8 @@ glm::vec3 MyAvatar::calculateScaledDirection(){ void MyAvatar::updateActionMotor(float deltaTime) { bool thrustIsPushing = (glm::length2(_thrust) > EPSILON); - bool scriptedMotorIsPushing = (_motionBehaviors & AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED) - && _scriptedMotorTimescale < MAX_CHARACTER_MOTOR_TIMESCALE; + bool scriptedMotorIsPushing = + (_motionBehaviors & AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED) && _scriptedMotorTimescale < MAX_CHARACTER_MOTOR_TIMESCALE; _isBeingPushed = thrustIsPushing || scriptedMotorIsPushing; if (_isPushing || _isBeingPushed) { // we don't want the motor to brake if a script is pushing the avatar around @@ -3545,7 +3483,7 @@ void MyAvatar::updateActionMotor(float deltaTime) { float motorSpeed = glm::length(_actionMotorVelocity); float finalMaxMotorSpeed = sensorToWorldScale * DEFAULT_AVATAR_MAX_FLYING_SPEED * _walkSpeedScalar; - float speedGrowthTimescale = 2.0f; + float speedGrowthTimescale = 2.0f; float speedIncreaseFactor = 1.8f * _walkSpeedScalar; motorSpeed *= 1.0f + glm::clamp(deltaTime / speedGrowthTimescale, 0.0f, 1.0f) * speedIncreaseFactor; const float maxBoostSpeed = sensorToWorldScale * MAX_BOOST_SPEED; @@ -3585,7 +3523,7 @@ void MyAvatar::updatePosition(float deltaTime) { float sensorToWorldScale2 = sensorToWorldScale * sensorToWorldScale; vec3 velocity = getWorldVelocity(); float speed2 = glm::length2(velocity); - const float MOVING_SPEED_THRESHOLD_SQUARED = 0.0001f; // 0.01 m/s + const float MOVING_SPEED_THRESHOLD_SQUARED = 0.0001f; // 0.01 m/s _moving = speed2 > sensorToWorldScale2 * MOVING_SPEED_THRESHOLD_SQUARED; if (_moving) { // scan for walkability @@ -3610,12 +3548,17 @@ void MyAvatar::updateViewBoom() { } } -void MyAvatar::updateCollisionSound(const glm::vec3 &penetration, float deltaTime, float frequency) { +void MyAvatar::updateCollisionSound(const glm::vec3& penetration, float deltaTime, float frequency) { // COLLISION SOUND API in Audio has been removed } -bool findAvatarAvatarPenetration(const glm::vec3 positionA, float radiusA, float heightA, - const glm::vec3 positionB, float radiusB, float heightB, glm::vec3& penetration) { +bool findAvatarAvatarPenetration(const glm::vec3 positionA, + float radiusA, + float heightA, + const glm::vec3 positionB, + float radiusB, + float heightB, + glm::vec3& penetration) { glm::vec3 positionBA = positionB - positionA; float xzDistance = sqrt(positionBA.x * positionBA.x + positionBA.z * positionBA.z); if (xzDistance < (radiusA + radiusB)) { @@ -3677,9 +3620,7 @@ void MyAvatar::setSessionUUID(const QUuid& sessionUUID) { EntityTreePointer entityTree = treeRenderer ? treeRenderer->getTree() : nullptr; if (entityTree) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { - avatarEntityIDs = _packedAvatarEntityData.keys(); - }); + _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); bool sendPackets = !DependencyManager::get()->getSessionUUID().isNull(); EntityEditPacketSender* packetSender = qApp->getEntityEditPacketSender(); entityTree->withWriteLock([&] { @@ -3823,16 +3764,18 @@ void MyAvatar::goToLocation(const QVariant& propertiesVar) { } void MyAvatar::goToFeetLocation(const glm::vec3& newPosition, - bool hasOrientation, const glm::quat& newOrientation, + bool hasOrientation, + const glm::quat& newOrientation, bool shouldFaceLocation) { _goToFeetAjustment = true; goToLocation(newPosition, hasOrientation, newOrientation, shouldFaceLocation); } void MyAvatar::goToLocation(const glm::vec3& newPosition, - bool hasOrientation, const glm::quat& newOrientation, - bool shouldFaceLocation, bool withSafeLanding) { - + bool hasOrientation, + const glm::quat& newOrientation, + bool shouldFaceLocation, + bool withSafeLanding) { // Most cases of going to a place or user go through this now. Some possible improvements to think about in the future: // - It would be nice if this used the same teleport steps and smoothing as in the teleport.js script, as long as it // still worked if the target is in the air. @@ -3846,16 +3789,16 @@ void MyAvatar::goToLocation(const glm::vec3& newPosition, // compute the position (e.g., so that if I'm on stage, going to me would compute an available seat in the audience rather than // being in my face on-stage). Note that this could work for going to an entity as well as to a person. - qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - moving to " << newPosition.x << ", " - << newPosition.y << ", " << newPosition.z; + qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - moving to " << newPosition.x << ", " << newPosition.y << ", " + << newPosition.z; _goToPending = true; _goToPosition = newPosition; _goToSafe = withSafeLanding; _goToOrientation = getWorldOrientation(); if (hasOrientation) { - qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - new orientation is " - << newOrientation.x << ", " << newOrientation.y << ", " << newOrientation.z << ", " << newOrientation.w; + qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - new orientation is " << newOrientation.x << ", " + << newOrientation.y << ", " << newOrientation.z << ", " << newOrientation.w; // orient the user to face the target glm::quat quatOrientation = cancelOutRollAndPitch(newOrientation); @@ -3874,7 +3817,7 @@ void MyAvatar::goToLocation(const glm::vec3& newPosition, emit transformChanged(); } -void MyAvatar::goToLocationAndEnableCollisions(const glm::vec3& position) { // See use case in safeLanding. +void MyAvatar::goToLocationAndEnableCollisions(const glm::vec3& position) { // See use case in safeLanding. goToLocation(position); QMetaObject::invokeMethod(this, "setCollisionsEnabled", Qt::QueuedConnection, Q_ARG(bool, true)); } @@ -3900,29 +3843,29 @@ bool MyAvatar::safeLanding(const glm::vec3& position) { } if (!getCollisionsEnabled()) { goToLocation(better); // recurses on next update - } else { // If you try to go while stuck, physics will keep you stuck. + } else { // If you try to go while stuck, physics will keep you stuck. setCollisionsEnabled(false); // Don't goToLocation just yet. Yield so that physics can act on the above. - QMetaObject::invokeMethod(this, "goToLocationAndEnableCollisions", Qt::QueuedConnection, // The equivalent of javascript nextTick - Q_ARG(glm::vec3, better)); - } - return true; + QMetaObject::invokeMethod(this, "goToLocationAndEnableCollisions", + Qt::QueuedConnection, // The equivalent of javascript nextTick + Q_ARG(glm::vec3, better)); + } + return true; } // If position is not reliably safe from being stuck by physics, answer true and place a candidate better position in betterPositionOut. bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& betterPositionOut) { - // We begin with utilities and tests. The Algorithm in four parts is below. // NOTE: we use estimated avatar height here instead of the bullet capsule halfHeight, because // the domain avatar height limiting might not have taken effect yet on the actual bullet shape. auto halfHeight = 0.5f * getHeight(); if (halfHeight == 0) { - return false; // zero height avatar + return false; // zero height avatar } auto entityTree = DependencyManager::get()->getTree(); if (!entityTree) { - return false; // no entity tree + return false; // no entity tree } // More utilities. const auto capsuleCenter = positionIn; @@ -3934,21 +3877,26 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette betterPositionOut = upperIntersection + (up * halfHeight); return true; }; - auto findIntersection = [&](const glm::vec3& startPointIn, const glm::vec3& directionIn, glm::vec3& intersectionOut, EntityItemID& entityIdOut, glm::vec3& normalOut) { + auto findIntersection = [&](const glm::vec3& startPointIn, const glm::vec3& directionIn, glm::vec3& intersectionOut, + EntityItemID& entityIdOut, glm::vec3& normalOut) { OctreeElementPointer element; float distance; BoxFace face; - const auto lockType = Octree::Lock; // Should we refactor to take a lock just once? + const auto lockType = Octree::Lock; // Should we refactor to take a lock just once? bool* accurateResult = NULL; // This isn't quite what we really want here. findRayIntersection always works on mesh, skipping entirely based on collidable. // What we really want is to use the collision hull! // See https://highfidelity.fogbugz.com/f/cases/5003/findRayIntersection-has-option-to-use-collidableOnly-but-doesn-t-actually-use-colliders QVariantMap extraInfo; - EntityItemID entityID = entityTree->evalRayIntersection(startPointIn, directionIn, include, ignore, - PickFilter(PickFilter::getBitMask(PickFilter::FlagBit::COLLIDABLE) | PickFilter::getBitMask(PickFilter::FlagBit::PRECISE) - | PickFilter::getBitMask(PickFilter::FlagBit::DOMAIN_ENTITIES) | PickFilter::getBitMask(PickFilter::FlagBit::AVATAR_ENTITIES)), // exclude Local entities - element, distance, face, normalOut, extraInfo, lockType, accurateResult); + EntityItemID entityID = + entityTree->evalRayIntersection(startPointIn, directionIn, include, ignore, + PickFilter(PickFilter::getBitMask(PickFilter::FlagBit::COLLIDABLE) | + PickFilter::getBitMask(PickFilter::FlagBit::PRECISE) | + PickFilter::getBitMask(PickFilter::FlagBit::DOMAIN_ENTITIES) | + PickFilter::getBitMask( + PickFilter::FlagBit::AVATAR_ENTITIES)), // exclude Local entities + element, distance, face, normalOut, extraInfo, lockType, accurateResult); if (entityID.isNull()) { return false; } @@ -3963,12 +3911,12 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette // We currently believe that physics will reliably push us out if our feet are embedded, // as long as our capsule center is out and there's room above us. Here we have those // conditions, so no need to check our feet below. - return false; // nothing above + return false; // nothing above } if (!findIntersection(capsuleCenter, down, lowerIntersection, lowerId, lowerNormal)) { // Our head may be embedded, but our center is out and there's room below. See corresponding comment above. - return false; // nothing below + return false; // nothing below } // See if we have room between entities above and below, but that we are not contained. @@ -3976,7 +3924,8 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette // I.e., we are in a clearing between two objects. if (isDown(upperNormal) && isUp(lowerNormal)) { auto spaceBetween = glm::distance(upperIntersection, lowerIntersection); - const float halfHeightFactor = 2.25f; // Until case 5003 is fixed (and maybe after?), we need a fudge factor. Also account for content modelers not being precise. + const float halfHeightFactor = + 2.25f; // Until case 5003 is fixed (and maybe after?), we need a fudge factor. Also account for content modelers not being precise. if (spaceBetween > (halfHeightFactor * halfHeight)) { // There is room for us to fit in that clearing. If there wasn't, physics would oscilate us between the objects above and below. // We're now going to iterate upwards through successive upperIntersections, testing to see if we're contained within the top surface of some entity. @@ -3988,7 +3937,7 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette ignore.push_back(upperId); if (!findIntersection(upperIntersection, up, upperIntersection, upperId, upperNormal)) { // We're not inside an entity, and from the nested tests, we have room between what is above and below. So position is good! - return false; // enough room + return false; // enough room } if (isUp(upperNormal)) { // This new intersection is the top surface of an entity that we have not yet seen, which means we're contained within it. @@ -4003,19 +3952,18 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette } } - include.push_back(upperId); // We're now looking for the intersection from above onto this entity. + include.push_back(upperId); // We're now looking for the intersection from above onto this entity. const float big = (float)TREE_SCALE; const auto skyHigh = up * big; auto fromAbove = capsuleCenter + skyHigh; if (!findIntersection(fromAbove, down, upperIntersection, upperId, upperNormal)) { - return false; // Unable to find a landing + return false; // Unable to find a landing } // Our arbitrary rule is to always go up. There's no need to look down or sideways for a "closer" safe candidate. return mustMove(); } void MyAvatar::updateMotionBehaviorFromMenu() { - if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "updateMotionBehaviorFromMenu"); return; @@ -4099,7 +4047,7 @@ int MyAvatar::getMovementReference() { return _movementReference; } -void MyAvatar::setControlSchemeIndex(int index){ +void MyAvatar::setControlSchemeIndex(int index) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setControlSchemeIndex", Q_ARG(int, index)); return; @@ -4117,7 +4065,8 @@ void MyAvatar::setDriveGear1(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear1", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) + return; _driveGear1 = (shiftPoint < _driveGear2) ? shiftPoint : _driveGear1; } @@ -4138,7 +4087,8 @@ void MyAvatar::setDriveGear2(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear2", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) + return; _driveGear2 = (shiftPoint < _driveGear3 && shiftPoint >= _driveGear1) ? shiftPoint : _driveGear2; } @@ -4159,7 +4109,8 @@ void MyAvatar::setDriveGear3(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear3", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) + return; _driveGear3 = (shiftPoint < _driveGear4 && shiftPoint >= _driveGear2) ? shiftPoint : _driveGear3; } @@ -4180,7 +4131,8 @@ void MyAvatar::setDriveGear4(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear4", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) + return; _driveGear4 = (shiftPoint < _driveGear5 && shiftPoint >= _driveGear3) ? shiftPoint : _driveGear4; } @@ -4201,7 +4153,8 @@ void MyAvatar::setDriveGear5(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear5", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) + return; _driveGear5 = (shiftPoint > _driveGear4) ? shiftPoint : _driveGear5; } @@ -4227,7 +4180,6 @@ float MyAvatar::getAvatarScale() { } void MyAvatar::setAvatarScale(float val) { - if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setAvatarScale", Q_ARG(float, val)); return; @@ -4237,7 +4189,6 @@ void MyAvatar::setAvatarScale(float val) { } void MyAvatar::setCollisionsEnabled(bool enabled) { - if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setCollisionsEnabled", Q_ARG(bool, enabled)); return; @@ -4253,7 +4204,6 @@ bool MyAvatar::getCollisionsEnabled() { } void MyAvatar::setOtherAvatarsCollisionsEnabled(bool enabled) { - if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setOtherAvatarsCollisionsEnabled", Q_ARG(bool, enabled)); return; @@ -4409,7 +4359,7 @@ glm::mat4 MyAvatar::deriveBodyFromHMDSensor() const { // AJT: TODO: can remove this Y_180, if we remove the higher level one. glm::vec3 headToNeck = headOrientation * Quaternions::Y_180 * (localNeck - localHead); - glm::vec3 neckToRoot = headOrientationYawOnly * Quaternions::Y_180 * -localNeck; + glm::vec3 neckToRoot = headOrientationYawOnly * Quaternions::Y_180 * -localNeck; float invSensorToWorldScale = getUserEyeHeight() / getEyeHeight(); glm::vec3 bodyPos = headPosition + invSensorToWorldScale * (headToNeck + neckToRoot); @@ -4445,7 +4395,8 @@ glm::mat4 MyAvatar::getSpine2RotationRigSpace() const { spine2UpRigSpace = glm::vec3(0.0f, 1.0f, 0.0f); } generateBasisVectors(spine2UpRigSpace, spine2FwdRigSpace, u, v, w); - glm::mat4 spine2RigSpace(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), glm::vec4(glm::vec3(0.0f, 0.0f, 0.0f), 1.0f)); + glm::mat4 spine2RigSpace(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), + glm::vec4(glm::vec3(0.0f, 0.0f, 0.0f), 1.0f)); return spine2RigSpace; } @@ -4502,7 +4453,7 @@ glm::vec3 MyAvatar::computeCounterBalance() { QString name; float weight; glm::vec3 position; - JointMass() {}; + JointMass(){}; JointMass(QString n, float w, glm::vec3 p) { name = n; weight = w; @@ -4523,12 +4474,14 @@ glm::vec3 MyAvatar::computeCounterBalance() { tposeHead = getAbsoluteDefaultJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgHeadMass.name)); } if (_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name) != -1) { - cgLeftHandMass.position = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name)); + cgLeftHandMass.position = + getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name)); } else { cgLeftHandMass.position = DEFAULT_AVATAR_LEFTHAND_POS; } if (_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name) != -1) { - cgRightHandMass.position = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name)); + cgRightHandMass.position = + getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name)); } else { cgRightHandMass.position = DEFAULT_AVATAR_RIGHTHAND_POS; } @@ -4540,7 +4493,8 @@ glm::vec3 MyAvatar::computeCounterBalance() { } // find the current center of gravity position based on head and hand moments - glm::vec3 sumOfMoments = (cgHeadMass.weight * cgHeadMass.position) + (cgLeftHandMass.weight * cgLeftHandMass.position) + (cgRightHandMass.weight * cgRightHandMass.position); + glm::vec3 sumOfMoments = (cgHeadMass.weight * cgHeadMass.position) + (cgLeftHandMass.weight * cgLeftHandMass.position) + + (cgRightHandMass.weight * cgRightHandMass.position); float totalMass = cgHeadMass.weight + cgLeftHandMass.weight + cgRightHandMass.weight; glm::vec3 currentCg = (1.0f / totalMass) * sumOfMoments; @@ -4580,7 +4534,6 @@ glm::vec3 MyAvatar::computeCounterBalance() { // headOrientation, headPosition and hipsPosition are in avatar space // returns the matrix of the hips in Avatar space static glm::mat4 computeNewHipsMatrix(glm::quat headOrientation, glm::vec3 headPosition, glm::vec3 hipsPosition) { - glm::quat bodyOrientation = computeBodyFacingFromHead(headOrientation, Vectors::UNIT_Y); const float MIX_RATIO = 0.3f; @@ -4590,10 +4543,7 @@ static glm::mat4 computeNewHipsMatrix(glm::quat headOrientation, glm::vec3 headP glm::vec3 spineVec = headPosition - hipsPosition; glm::vec3 u, v, w; generateBasisVectors(glm::normalize(spineVec), hipsFacing, u, v, w); - return glm::mat4(glm::vec4(w, 0.0f), - glm::vec4(u, 0.0f), - glm::vec4(v, 0.0f), - glm::vec4(hipsPosition, 1.0f)); + return glm::mat4(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), glm::vec4(hipsPosition, 1.0f)); } static void drawBaseOfSupport(float baseOfSupportScale, float footLocal, glm::mat4 avatarToWorld) { @@ -4634,7 +4584,8 @@ glm::mat4 MyAvatar::deriveBodyUsingCgModel() { if (_enableDebugDrawBaseOfSupport) { float scaleBaseOfSupport = getUserEyeHeight() / DEFAULT_AVATAR_EYE_HEIGHT; - glm::vec3 rightFootPositionLocal = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint("RightFoot")); + glm::vec3 rightFootPositionLocal = + getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint("RightFoot")); drawBaseOfSupport(scaleBaseOfSupport, rightFootPositionLocal.y, avatarToWorldMat); } @@ -4642,7 +4593,8 @@ glm::mat4 MyAvatar::deriveBodyUsingCgModel() { glm::vec3 cgHipsPosition = computeCounterBalance(); // find the new hips rotation using the new head-hips axis as the up axis - glm::mat4 avatarHipsMat = computeNewHipsMatrix(glmExtractRotation(avatarHeadMat), extractTranslation(avatarHeadMat), cgHipsPosition); + glm::mat4 avatarHipsMat = + computeNewHipsMatrix(glmExtractRotation(avatarHeadMat), extractTranslation(avatarHeadMat), cgHipsPosition); // convert hips from avatar to sensor space // The Y_180 is to convert from z forward to -z forward. @@ -4666,7 +4618,7 @@ static bool withinBaseOfSupport(const controller::Pose& head) { bool withinFrontBase = isInsideLine(userScale * frontLeft, userScale * frontRight, head.getTranslation()); bool withinBackBase = isInsideLine(userScale * backRight, userScale * backLeft, head.getTranslation()); bool withinLateralBase = (isInsideLine(userScale * frontRight, userScale * backRight, head.getTranslation()) && - isInsideLine(userScale * backLeft, userScale * frontLeft, head.getTranslation())); + isInsideLine(userScale * backLeft, userScale * frontLeft, head.getTranslation())); isWithinSupport = (withinFrontBase && withinBackBase && withinLateralBase); } return isWithinSupport; @@ -4700,7 +4652,8 @@ float MyAvatar::computeStandingHeightMode(const controller::Pose& head) { float modeInMeters = getCurrentStandingHeight(); if (head.isValid()) { std::map freq; - for(auto recentModeReadingsIterator = _recentModeReadings.begin(); recentModeReadingsIterator != _recentModeReadings.end(); ++recentModeReadingsIterator) { + for (auto recentModeReadingsIterator = _recentModeReadings.begin(); + recentModeReadingsIterator != _recentModeReadings.end(); ++recentModeReadingsIterator) { freq[*recentModeReadingsIterator] += 1; if (freq[*recentModeReadingsIterator] > greatestFrequency) { greatestFrequency = freq[*recentModeReadingsIterator]; @@ -4713,21 +4666,23 @@ float MyAvatar::computeStandingHeightMode(const controller::Pose& head) { // if not greater check for a reset if (getResetMode() && getControllerPoseInAvatarFrame(controller::Action::HEAD).isValid()) { setResetMode(false); - float resetModeInCentimeters = glm::floor((head.getTranslation().y - MODE_CORRECTION_FACTOR)*CENTIMETERS_PER_METER); + float resetModeInCentimeters = + glm::floor((head.getTranslation().y - MODE_CORRECTION_FACTOR) * CENTIMETERS_PER_METER); modeInMeters = (resetModeInCentimeters / CENTIMETERS_PER_METER); _recentModeReadings.clear(); } else { // if not greater and no reset, keep the mode as it is modeInMeters = getCurrentStandingHeight(); - } } } return modeInMeters; } -static bool handDirectionMatchesHeadDirection(const controller::Pose& leftHand, const controller::Pose& rightHand, const controller::Pose& head) { +static bool handDirectionMatchesHeadDirection(const controller::Pose& leftHand, + const controller::Pose& rightHand, + const controller::Pose& head) { const float VELOCITY_EPSILON = 0.02f; bool leftHandDirectionMatchesHead = true; bool rightHandDirectionMatchesHead = true; @@ -4765,7 +4720,7 @@ static bool handAngularVelocityBelowThreshold(const controller::Pose& leftHand, rightHandXZAngularVelocity = glm::length(xzRightHandAngularVelocity); } return ((leftHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD) && - (rightHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD)); + (rightHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD)); } static bool headVelocityGreaterThanThreshold(const controller::Pose& head) { @@ -4788,7 +4743,8 @@ static bool isHeadLevel(const controller::Pose& head, const glm::quat& averageHe glm::vec3 currentHeadEulers = glm::degrees(safeEulerAngles(head.getRotation())); diffFromAverageEulers = averageHeadEulers - currentHeadEulers; } - return ((fabs(diffFromAverageEulers.x) < DEFAULT_HEAD_PITCH_STEPPING_TOLERANCE) && (fabs(diffFromAverageEulers.z) < DEFAULT_HEAD_ROLL_STEPPING_TOLERANCE)); + return ((fabs(diffFromAverageEulers.x) < DEFAULT_HEAD_PITCH_STEPPING_TOLERANCE) && + (fabs(diffFromAverageEulers.z) < DEFAULT_HEAD_ROLL_STEPPING_TOLERANCE)); } float MyAvatar::getUserHeight() const { @@ -4838,7 +4794,6 @@ float MyAvatar::getWalkSpeed() const { } else { return _defaultWalkSpeed.get(); } - } float MyAvatar::getWalkBackwardSpeed() const { @@ -4855,7 +4810,6 @@ float MyAvatar::getWalkBackwardSpeed() const { } else { return _defaultWalkBackwardSpeed.get(); } - } bool MyAvatar::isReadyForPhysics() const { @@ -4865,8 +4819,7 @@ bool MyAvatar::isReadyForPhysics() const { void MyAvatar::setSprintMode(bool sprint) { if (qApp->isHMDMode()) { _walkSpeedScalar = sprint ? AVATAR_DESKTOP_SPRINT_SPEED_SCALAR : AVATAR_WALK_SPEED_SCALAR; - } - else { + } else { _walkSpeedScalar = sprint ? AVATAR_HMD_SPRINT_SPEED_SCALAR : AVATAR_WALK_SPEED_SCALAR; } } @@ -4890,7 +4843,6 @@ void MyAvatar::setIsInSittingState(bool isSitting) { } void MyAvatar::setUserRecenterModel(MyAvatar::SitStandModelType modelName) { - _userRecenterModel.set(modelName); switch (modelName) { @@ -4966,7 +4918,7 @@ void MyAvatar::setWalkBackwardSpeed(float value) { changed = false; break; } - + if (changed && prevVal != value) { emit walkBackwardSpeedChanged(value); } @@ -4993,7 +4945,7 @@ void MyAvatar::setSprintSpeed(float value) { } if (changed && prevVal != value) { - emit walkBackwardSpeedChanged(value); + emit analogPlusSprintSpeedChanged(value); } } @@ -5032,10 +4984,12 @@ float MyAvatar::getAnalogSprintSpeed() const { } void MyAvatar::setAnalogPlusWalkSpeed(float value) { - _analogPlusWalkSpeed.set(value); - emit analogPlusWalkSpeedChanged(value); - // Sprint speed for Analog Plus should be double walk speed. - _analogPlusSprintSpeed.set(value * 2.0f); + if (_analogPlusWalkSpeed.get() != value) { + _analogPlusWalkSpeed.set(value); + emit analogPlusWalkSpeedChanged(value); + // Sprint speed for Analog Plus should be double walk speed. + _analogPlusSprintSpeed.set(value * 2.0f); + } } float MyAvatar::getAnalogPlusWalkSpeed() const { @@ -5043,8 +4997,10 @@ float MyAvatar::getAnalogPlusWalkSpeed() const { } void MyAvatar::setAnalogPlusSprintSpeed(float value) { - _analogPlusSprintSpeed.set(value); - emit analogPlusSprintSpeedChanged(value); + if (_analogPlusSprintSpeed.get() != value) { + _analogPlusSprintSpeed.set(value); + emit analogPlusSprintSpeedChanged(value); + } } float MyAvatar::getAnalogPlusSprintSpeed() const { @@ -5132,7 +5088,6 @@ void driveKeysFromScriptValue(const QScriptValue& object, MyAvatar::DriveKeys& d driveKeys = static_cast(object.toUInt16()); } - void MyAvatar::lateUpdatePalms() { Avatar::updatePalms(); } @@ -5190,13 +5145,17 @@ void MyAvatar::FollowHelper::decrementTimeRemaining(float dt) { } } -bool MyAvatar::FollowHelper::shouldActivateRotation(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateRotation(const MyAvatar& myAvatar, + const glm::mat4& desiredBodyMatrix, + const glm::mat4& currentBodyMatrix) const { const float FOLLOW_ROTATION_THRESHOLD = cosf(myAvatar.getRotationThreshold()); glm::vec2 bodyFacing = getFacingDir2D(currentBodyMatrix); return glm::dot(-myAvatar.getHeadControllerFacingMovingAverage(), bodyFacing) < FOLLOW_ROTATION_THRESHOLD; } -bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, + const glm::mat4& desiredBodyMatrix, + const glm::mat4& currentBodyMatrix) const { // -z axis of currentBodyMatrix in world space. glm::vec3 forward = glm::normalize(glm::vec3(-currentBodyMatrix[0][2], -currentBodyMatrix[1][2], -currentBodyMatrix[2][2])); // x axis of currentBodyMatrix in world space. @@ -5227,7 +5186,6 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, } bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) const { - // get the current readings controller::Pose currentHeadPose = myAvatar.getControllerPoseInAvatarFrame(controller::Action::HEAD); controller::Pose currentLeftHandPose = myAvatar.getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND); @@ -5240,8 +5198,7 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons if (myAvatar.getIsInWalkingState()) { stepDetected = true; } else { - if (!withinBaseOfSupport(currentHeadPose) && - headAngularVelocityBelowThreshold(currentHeadPose) && + if (!withinBaseOfSupport(currentHeadPose) && headAngularVelocityBelowThreshold(currentHeadPose) && isWithinThresholdHeightMode(currentHeadSensorPose, myAvatar.getCurrentStandingHeight(), myScale) && handDirectionMatchesHeadDirection(currentLeftHandPose, currentRightHandPose, currentHeadPose) && handAngularVelocityBelowThreshold(currentLeftHandPose, currentRightHandPose) && @@ -5253,13 +5210,15 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons myAvatar.setIsInWalkingState(true); } } else { - glm::vec3 defaultHipsPosition = myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Hips")); - glm::vec3 defaultHeadPosition = myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Head")); + glm::vec3 defaultHipsPosition = + myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Hips")); + glm::vec3 defaultHeadPosition = + myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Head")); glm::vec3 currentHeadPosition = currentHeadPose.getTranslation(); float anatomicalHeadToHipsDistance = glm::length(defaultHeadPosition - defaultHipsPosition); - if (!isActive(Horizontal) && - (!isActive(Vertical)) && - (glm::length(currentHeadPosition - defaultHipsPosition) > (anatomicalHeadToHipsDistance + (DEFAULT_AVATAR_SPINE_STRETCH_LIMIT * anatomicalHeadToHipsDistance)))) { + if (!isActive(Horizontal) && (!isActive(Vertical)) && + (glm::length(currentHeadPosition - defaultHipsPosition) > + (anatomicalHeadToHipsDistance + (DEFAULT_AVATAR_SPINE_STRETCH_LIMIT * anatomicalHeadToHipsDistance)))) { myAvatar.setResetMode(true); stepDetected = true; if (glm::length(currentHeadPose.velocity) > DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { @@ -5271,7 +5230,9 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons return stepDetected; } -bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, + const glm::mat4& desiredBodyMatrix, + const glm::mat4& currentBodyMatrix) const { const float CYLINDER_TOP = 2.0f; const float CYLINDER_BOTTOM = -1.5f; const float SITTING_BOTTOM = -0.02f; @@ -5302,11 +5263,11 @@ bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, co return returnValue; } -void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, - const glm::mat4& currentBodyMatrix, bool hasDriveInput) { - - if (myAvatar.getHMDLeanRecenterEnabled() && - qApp->getCamera().getMode() != CAMERA_MODE_MIRROR) { +void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, + const glm::mat4& desiredBodyMatrix, + const glm::mat4& currentBodyMatrix, + bool hasDriveInput) { + if (myAvatar.getHMDLeanRecenterEnabled() && qApp->getCamera().getMode() != CAMERA_MODE_MIRROR) { if (!isActive(Rotation) && (shouldActivateRotation(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { activate(Rotation); myAvatar.setHeadControllerFacingMovingAverage(myAvatar.getHeadControllerFacing()); @@ -5321,7 +5282,8 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat } } else { // center of gravity model is not enabled - if (!isActive(Horizontal) && (shouldActivateHorizontal(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { + if (!isActive(Horizontal) && + (shouldActivateHorizontal(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { activate(Horizontal); if (myAvatar.getEnableStepResetRotation() && !myAvatar.getIsInSittingState()) { activate(Rotation); @@ -5358,7 +5320,7 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat glm::quat currentHipsLocal = myAvatar.getAbsoluteJointRotationInObjectFrame(myAvatar.getJointIndex("Hips")); const glm::quat hipsinWorldSpace = followWorldPose.rot() * (Quaternions::Y_180 * (currentHipsLocal)); - const glm::vec3 avatarUpWorld = glm::normalize(followWorldPose.rot()*(Vectors::UP)); + const glm::vec3 avatarUpWorld = glm::normalize(followWorldPose.rot() * (Vectors::UP)); glm::quat resultingSwingInWorld; glm::quat resultingTwistInWorld; swingTwistDecomposition(hipsinWorldSpace, avatarUpWorld, resultingSwingInWorld, resultingTwistInWorld); @@ -5367,8 +5329,8 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat followWorldPose.scale() = glm::vec3(1.0f); if (isActive(Rotation)) { - //use the hmd reading for the hips follow - followWorldPose.rot() = glmExtractRotation(desiredWorldMatrix); + //use the hmd reading for the hips follow + followWorldPose.rot() = glmExtractRotation(desiredWorldMatrix); } if (isActive(Horizontal)) { glm::vec3 desiredTranslation = extractTranslation(desiredWorldMatrix); @@ -5396,7 +5358,8 @@ glm::mat4 MyAvatar::FollowHelper::postPhysicsUpdate(MyAvatar& myAvatar, const gl glm::mat4 worldToSensorMatrix = glm::inverse(sensorToWorldMatrix); glm::vec3 sensorLinearDisplacement = transformVectorFast(worldToSensorMatrix, worldLinearDisplacement); - glm::quat sensorAngularDisplacement = glmExtractRotation(worldToSensorMatrix) * worldAngularDisplacement * glmExtractRotation(sensorToWorldMatrix); + glm::quat sensorAngularDisplacement = + glmExtractRotation(worldToSensorMatrix) * worldAngularDisplacement * glmExtractRotation(sensorToWorldMatrix); glm::mat4 newBodyMat = createMatFromQuatAndPos(sensorAngularDisplacement * glmExtractRotation(currentBodyMatrix), sensorLinearDisplacement + extractTranslation(currentBodyMatrix)); @@ -5464,7 +5427,8 @@ bool MyAvatar::didTeleport() { } bool MyAvatar::hasDriveInput() const { - return fabsf(getDriveKey(TRANSLATE_X)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Y)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Z)) > 0.0f; + return fabsf(getDriveKey(TRANSLATE_X)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Y)) > 0.0f || + fabsf(getDriveKey(TRANSLATE_Z)) > 0.0f; } void MyAvatar::setAway(bool value) { @@ -5480,7 +5444,6 @@ void MyAvatar::setAway(bool value) { // Specificly, if we are rendering using a third person camera. We would like to render the hand controllers in front of the camera, // not in front of the avatar. glm::mat4 MyAvatar::computeCameraRelativeHandControllerMatrix(const glm::mat4& controllerSensorMatrix) const { - // Fetch the current camera transform. glm::mat4 cameraWorldMatrix = qApp->getCamera().getTransform(); if (qApp->getCamera().getMode() == CAMERA_MODE_MIRROR) { @@ -5507,7 +5470,7 @@ glm::mat4 MyAvatar::computeCameraRelativeHandControllerMatrix(const glm::mat4& c glm::quat MyAvatar::getAbsoluteJointRotationInObjectFrame(int index) const { if (index < 0) { - index += numeric_limits::max() + 1; // 65536 + index += numeric_limits::max() + 1; // 65536 } switch (index) { @@ -5536,15 +5499,13 @@ glm::quat MyAvatar::getAbsoluteJointRotationInObjectFrame(int index) const { glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix(); return glmExtractRotation(invAvatarMat * qApp->getCamera().getTransform()); } - default: { - return Avatar::getAbsoluteJointRotationInObjectFrame(index); - } + default: { return Avatar::getAbsoluteJointRotationInObjectFrame(index); } } } glm::vec3 MyAvatar::getAbsoluteJointTranslationInObjectFrame(int index) const { if (index < 0) { - index += numeric_limits::max() + 1; // 65536 + index += numeric_limits::max() + 1; // 65536 } switch (index) { @@ -5573,9 +5534,7 @@ glm::vec3 MyAvatar::getAbsoluteJointTranslationInObjectFrame(int index) const { glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix(); return extractTranslation(invAvatarMat * qApp->getCamera().getTransform()); } - default: { - return Avatar::getAbsoluteJointTranslationInObjectFrame(index); - } + default: { return Avatar::getAbsoluteJointTranslationInObjectFrame(index); } } } @@ -5584,12 +5543,15 @@ glm::mat4 MyAvatar::getCenterEyeCalibrationMat() const { int rightEyeIndex = _skeletonModel->getRig().indexOfJoint("RightEye"); int leftEyeIndex = _skeletonModel->getRig().indexOfJoint("LeftEye"); if (rightEyeIndex >= 0 && leftEyeIndex >= 0) { - auto centerEyePos = (getAbsoluteDefaultJointTranslationInObjectFrame(rightEyeIndex) + getAbsoluteDefaultJointTranslationInObjectFrame(leftEyeIndex)) * 0.5f; + auto centerEyePos = (getAbsoluteDefaultJointTranslationInObjectFrame(rightEyeIndex) + + getAbsoluteDefaultJointTranslationInObjectFrame(leftEyeIndex)) * + 0.5f; auto centerEyeRot = Quaternions::Y_180; return createMatFromQuatAndPos(centerEyeRot, centerEyePos / getSensorToWorldScale()); } else { glm::mat4 headMat = getHeadCalibrationMat(); - return createMatFromQuatAndPos(DEFAULT_AVATAR_MIDDLE_EYE_ROT, extractTranslation(headMat) + DEFAULT_AVATAR_HEAD_TO_MIDDLE_EYE_OFFSET); + return createMatFromQuatAndPos(DEFAULT_AVATAR_MIDDLE_EYE_ROT, + extractTranslation(headMat) + DEFAULT_AVATAR_HEAD_TO_MIDDLE_EYE_OFFSET); } } @@ -5758,7 +5720,6 @@ void MyAvatar::updateHoldActions(const AnimPose& prePhysicsPose, const AnimPose& if (entityTree) { // lateAvatarUpdate will modify entity position & orientation, so we need an entity write lock entityTree->withWriteLock([&] { - // to prevent actions from adding or removing themselves from the _holdActions vector // while we are iterating, we need to enter a critical section. std::lock_guard guard(_holdActionsMutex); @@ -5794,26 +5755,24 @@ SpatialParentTree* MyAvatar::getParentTree() const { return entityTree.get(); } -const QUuid MyAvatar::grab(const QUuid& targetID, int parentJointIndex, - glm::vec3 positionalOffset, glm::quat rotationalOffset) { +const QUuid MyAvatar::grab(const QUuid& targetID, + int parentJointIndex, + glm::vec3 positionalOffset, + glm::quat rotationalOffset) { auto grabID = QUuid::createUuid(); // create a temporary grab object to get grabData QString hand = "none"; - if (parentJointIndex == CONTROLLER_RIGHTHAND_INDEX || - parentJointIndex == CAMERA_RELATIVE_CONTROLLER_RIGHTHAND_INDEX || - parentJointIndex == FARGRAB_RIGHTHAND_INDEX || - parentJointIndex == getJointIndex("RightHand")) { + if (parentJointIndex == CONTROLLER_RIGHTHAND_INDEX || parentJointIndex == CAMERA_RELATIVE_CONTROLLER_RIGHTHAND_INDEX || + parentJointIndex == FARGRAB_RIGHTHAND_INDEX || parentJointIndex == getJointIndex("RightHand")) { hand = "right"; - } else if (parentJointIndex == CONTROLLER_LEFTHAND_INDEX || - parentJointIndex == CAMERA_RELATIVE_CONTROLLER_LEFTHAND_INDEX || - parentJointIndex == FARGRAB_LEFTHAND_INDEX || - parentJointIndex == getJointIndex("LeftHand")) { + } else if (parentJointIndex == CONTROLLER_LEFTHAND_INDEX || parentJointIndex == CAMERA_RELATIVE_CONTROLLER_LEFTHAND_INDEX || + parentJointIndex == FARGRAB_LEFTHAND_INDEX || parentJointIndex == getJointIndex("LeftHand")) { hand = "left"; } - Grab tmpGrab(DependencyManager::get()->getSessionUUID(), - targetID, parentJointIndex, hand, positionalOffset, rotationalOffset); + Grab tmpGrab(DependencyManager::get()->getSessionUUID(), targetID, parentJointIndex, hand, positionalOffset, + rotationalOffset); QByteArray grabData = tmpGrab.toByteArray(); bool dataChanged = updateAvatarGrabData(grabID, grabData); @@ -5826,10 +5785,9 @@ const QUuid MyAvatar::grab(const QUuid& targetID, int parentJointIndex, } void MyAvatar::releaseGrab(const QUuid& grabID) { - bool tellHandler { false }; + bool tellHandler{ false }; _avatarGrabsLock.withWriteLock([&] { - std::map::iterator itr; itr = _avatarGrabs.find(grabID); if (itr != _avatarGrabs.end()) { @@ -5858,13 +5816,12 @@ void MyAvatar::releaseGrab(const QUuid& grabID) { void MyAvatar::addAvatarHandsToFlow(const std::shared_ptr& otherAvatar) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "addAvatarHandsToFlow", - Q_ARG(const std::shared_ptr&, otherAvatar)); + QMetaObject::invokeMethod(this, "addAvatarHandsToFlow", Q_ARG(const std::shared_ptr&, otherAvatar)); return; } - auto &flow = _skeletonModel->getRig().getFlow(); + auto& flow = _skeletonModel->getRig().getFlow(); if (otherAvatar != nullptr && flow.getActive()) { - for (auto &handJointName : HAND_COLLISION_JOINTS) { + for (auto& handJointName : HAND_COLLISION_JOINTS) { int jointIndex = otherAvatar->getJointIndex(handJointName); if (jointIndex != -1) { glm::vec3 position = otherAvatar->getJointPosition(jointIndex); @@ -5892,18 +5849,18 @@ void MyAvatar::addAvatarHandsToFlow(const std::shared_ptr& otherAvatar) * @property {number} [radius=0.05] - Collision sphere radius. * @property {number} [offset=Vec3.ZERO] - Offset of the collision sphere from the joint. */ -void MyAvatar::useFlow(bool isActive, bool isCollidable, const QVariantMap& physicsConfig, const QVariantMap& collisionsConfig) { +void MyAvatar::useFlow(bool isActive, + bool isCollidable, + const QVariantMap& physicsConfig, + const QVariantMap& collisionsConfig) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "useFlow", - Q_ARG(bool, isActive), - Q_ARG(bool, isCollidable), - Q_ARG(const QVariantMap&, physicsConfig), - Q_ARG(const QVariantMap&, collisionsConfig)); + QMetaObject::invokeMethod(this, "useFlow", Q_ARG(bool, isActive), Q_ARG(bool, isCollidable), + Q_ARG(const QVariantMap&, physicsConfig), Q_ARG(const QVariantMap&, collisionsConfig)); return; } if (_skeletonModel->isLoaded()) { - auto &flow = _skeletonModel->getRig().getFlow(); - auto &collisionSystem = flow.getCollisionSystem(); + auto& flow = _skeletonModel->getRig().getFlow(); + auto& collisionSystem = flow.getCollisionSystem(); if (!flow.isInitialized() && isActive) { _skeletonModel->getRig().initFlow(true); } else { @@ -5912,7 +5869,7 @@ void MyAvatar::useFlow(bool isActive, bool isCollidable, const QVariantMap& phys collisionSystem.setActive(isCollidable); auto physicsGroups = physicsConfig.keys(); if (physicsGroups.size() > 0) { - for (auto &groupName : physicsGroups) { + for (auto& groupName : physicsGroups) { auto settings = physicsConfig[groupName].toMap(); FlowPhysicsSettings physicsSettings; if (settings.contains("active")) { @@ -5942,7 +5899,7 @@ void MyAvatar::useFlow(bool isActive, bool isCollidable, const QVariantMap& phys auto collisionJoints = collisionsConfig.keys(); if (collisionJoints.size() > 0) { collisionSystem.clearSelfCollisions(); - for (auto &jointName : collisionJoints) { + for (auto& jointName : collisionJoints) { int jointIndex = getJointIndex(jointName); FlowCollisionSettings collisionsSettings; auto settings = collisionsConfig[jointName].toMap(); @@ -5996,14 +5953,13 @@ void MyAvatar::useFlow(bool isActive, bool isCollidable, const QVariantMap& phys QVariantMap MyAvatar::getFlowData() { QVariantMap result; if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "getFlowData", - Q_RETURN_ARG(QVariantMap, result)); + BLOCKING_INVOKE_METHOD(this, "getFlowData", Q_RETURN_ARG(QVariantMap, result)); return result; } if (_skeletonModel->isLoaded()) { auto jointNames = getJointNames(); - auto &flow = _skeletonModel->getRig().getFlow(); - auto &collisionSystem = flow.getCollisionSystem(); + auto& flow = _skeletonModel->getRig().getFlow(); + auto& collisionSystem = flow.getCollisionSystem(); bool initialized = flow.isInitialized(); result.insert("initialized", initialized); result.insert("active", flow.getActive()); @@ -6013,17 +5969,17 @@ QVariantMap MyAvatar::getFlowData() { QVariantMap threadData; std::map groupJointsMap; QVariantList jointCollisionData; - auto &groups = flow.getGroupSettings(); - for (auto &joint : flow.getJoints()) { - auto &groupName = joint.second.getGroup(); + auto& groups = flow.getGroupSettings(); + for (auto& joint : flow.getJoints()) { + auto& groupName = joint.second.getGroup(); if (groups.find(groupName) != groups.end()) { if (groupJointsMap.find(groupName) == groupJointsMap.end()) { groupJointsMap.insert(std::pair(groupName, QVariantList())); } groupJointsMap[groupName].push_back(joint.second.getIndex()); } - } - for (auto &group : groups) { + } + for (auto& group : groups) { QVariantMap settingsObject; QString groupName = group.first; FlowPhysicsSettings groupSettings = group.second; @@ -6038,8 +5994,8 @@ QVariantMap MyAvatar::getFlowData() { physicsData.insert(groupName, settingsObject); } - auto &collisions = collisionSystem.getCollisions(); - for (auto &collision : collisions) { + auto& collisions = collisionSystem.getCollisions(); + for (auto& collision : collisions) { QVariantMap collisionObject; collisionObject.insert("offset", vec3toVariant(collision._offset)); collisionObject.insert("radius", collision._radius); @@ -6047,7 +6003,7 @@ QVariantMap MyAvatar::getFlowData() { QString jointName = jointNames.size() > collision._jointIndex ? jointNames[collision._jointIndex] : "unknown"; collisionsData.insert(jointName, collisionObject); } - for (auto &thread : flow.getThreads()) { + for (auto& thread : flow.getThreads()) { QVariantList indices; for (int index : thread._joints) { indices.append(index); @@ -6064,14 +6020,13 @@ QVariantMap MyAvatar::getFlowData() { QVariantList MyAvatar::getCollidingFlowJoints() { QVariantList result; if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "getCollidingFlowJoints", - Q_RETURN_ARG(QVariantList, result)); + BLOCKING_INVOKE_METHOD(this, "getCollidingFlowJoints", Q_RETURN_ARG(QVariantList, result)); return result; } if (_skeletonModel->isLoaded()) { auto& flow = _skeletonModel->getRig().getFlow(); - for (auto &joint : flow.getJoints()) { + for (auto& joint : flow.getJoints()) { if (joint.second.isColliding()) { result.append(joint.second.getIndex()); } @@ -6082,7 +6037,7 @@ QVariantList MyAvatar::getCollidingFlowJoints() { void MyAvatar::initFlowFromFST() { if (_skeletonModel->isLoaded()) { - auto &flowData = _skeletonModel->getHFMModel().flowData; + auto& flowData = _skeletonModel->getHFMModel().flowData; if (flowData.shouldInitFlow()) { useFlow(true, flowData.shouldInitCollisions(), flowData._physicsConfig, flowData._collisionsConfig); } @@ -6100,4 +6055,3 @@ void MyAvatar::sendPacket(const QUuid& entityID) const { }); } } - diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index 1bd4f10944..e87aa87bd1 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -2164,7 +2164,7 @@ signals: /**jsdoc * Notifies when the analogPlusWalkSpeed value is changed. * @function MyAvatar.analogPlusWalkSpeedChanged - * @param {float} speed - the new avatar walk speed + * @param {float} value - the new avatar walk speed * @returns {Signal} */ void analogPlusWalkSpeedChanged(float value); @@ -2172,7 +2172,7 @@ signals: /**jsdoc * Notifies when the analogPlusSprintSpeed value is changed. * @function MyAvatar.analogPlusSprintSpeedChanged - * @param {float} speed - the new avatar sprint speed + * @param {float} value - the new avatar sprint speed * @returns {Signal} */ void analogPlusSprintSpeedChanged(float value); @@ -2180,7 +2180,7 @@ signals: /**jsdoc * Notifies when the sprintSpeed value is changed. * @function MyAvatar.sprintSpeedChanged - * @param {float} speed - the new avatar sprint speed + * @param {float} value - the new avatar sprint speed * @returns {Signal} */ void sprintSpeedChanged(float value); @@ -2188,7 +2188,7 @@ signals: /**jsdoc * Notifies when the walkBackwardSpeed value is changed. * @function MyAvatar.walkBackwardSpeedChanged - * @param {float} speed - the new avatar walk backward speed + * @param {float} value - the new avatar walk backward speed * @returns {Signal} */ void walkBackwardSpeedChanged(float value); From 21966fe3452e6b68ec6203452cbb6441dce3660d Mon Sep 17 00:00:00 2001 From: sabrina-shanman Date: Fri, 7 Jun 2019 11:14:07 -0700 Subject: [PATCH 15/31] Fix stuck transition due to removing sub render items before parent --- libraries/render/src/render/Scene.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/libraries/render/src/render/Scene.cpp b/libraries/render/src/render/Scene.cpp index c516a833de..bea111edb5 100644 --- a/libraries/render/src/render/Scene.cpp +++ b/libraries/render/src/render/Scene.cpp @@ -558,14 +558,20 @@ void Scene::removeItemTransition(ItemID itemId) { auto& item = _items[itemId]; TransitionStage::Index transitionId = item.getTransitionId(); if (!render::TransitionStage::isIndexInvalid(transitionId)) { - auto finishedOperators = _transitionFinishedOperatorMap[transitionId]; - for (auto finishedOperator : finishedOperators) { - if (finishedOperator) { - finishedOperator(); + const auto& transition = transitionStage->getTransition(transitionId); + const auto transitionOwner = transition.itemId; + if (transitionOwner == itemId) { + // No more items will be using this transition. Clean it up. + auto finishedOperators = _transitionFinishedOperatorMap[transitionId]; + for (auto finishedOperator : finishedOperators) { + if (finishedOperator) { + finishedOperator(); + } } + _transitionFinishedOperatorMap.erase(transitionId); + transitionStage->removeTransition(transitionId); } - _transitionFinishedOperatorMap.erase(transitionId); - transitionStage->removeTransition(transitionId); + setItemTransition(itemId, render::TransitionStage::INVALID_INDEX); } } From ad562b8f9176ec630d338fa6ec8749949d871e3e Mon Sep 17 00:00:00 2001 From: Preston Bezos Date: Fri, 7 Jun 2019 11:22:11 -0700 Subject: [PATCH 16/31] really need to stop clanging myself --- interface/src/avatar/MyAvatar.cpp | 856 ++++++++++++++++-------------- 1 file changed, 453 insertions(+), 403 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 3f921fd469..b60bfd3f29 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -71,9 +71,9 @@ using namespace std; const float DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES = 30.0f; const float YAW_SPEED_DEFAULT = 100.0f; // degrees/sec -const float PITCH_SPEED_DEFAULT = 75.0f; // degrees/sec +const float PITCH_SPEED_DEFAULT = 75.0f; // degrees/sec -const float MAX_BOOST_SPEED = 0.5f * DEFAULT_AVATAR_MAX_WALKING_SPEED; // action motor gets additive boost below this speed +const float MAX_BOOST_SPEED = 0.5f * DEFAULT_AVATAR_MAX_WALKING_SPEED; // action motor gets additive boost below this speed const float MIN_AVATAR_SPEED = 0.05f; float MIN_SCRIPTED_MOTOR_TIMESCALE = 0.005f; @@ -83,8 +83,7 @@ const int SCRIPTED_MOTOR_AVATAR_FRAME = 1; const int SCRIPTED_MOTOR_WORLD_FRAME = 2; const int SCRIPTED_MOTOR_SIMPLE_MODE = 0; const int SCRIPTED_MOTOR_DYNAMIC_MODE = 1; -const QString& DEFAULT_AVATAR_COLLISION_SOUND_URL = - "https://hifi-public.s3.amazonaws.com/sounds/Collisions-otherorganic/Body_Hits_Impact.wav"; +const QString& DEFAULT_AVATAR_COLLISION_SOUND_URL = "https://hifi-public.s3.amazonaws.com/sounds/Collisions-otherorganic/Body_Hits_Impact.wav"; const float MyAvatar::ZOOM_MIN = 0.5f; const float MyAvatar::ZOOM_MAX = 25.0f; @@ -93,7 +92,7 @@ const float MIN_SCALE_CHANGED_DELTA = 0.001f; const int MODE_READINGS_RING_BUFFER_SIZE = 500; const float CENTIMETERS_PER_METER = 100.0f; -const QString AVATAR_SETTINGS_GROUP_NAME{ "Avatar" }; +const QString AVATAR_SETTINGS_GROUP_NAME { "Avatar" }; static const QString USER_RECENTER_MODEL_FORCE_SIT = QStringLiteral("ForceSit"); static const QString USER_RECENTER_MODEL_FORCE_STAND = QStringLiteral("ForceStand"); @@ -114,33 +113,50 @@ MyAvatar::SitStandModelType stringToUserRecenterModel(const QString& str) { QString userRecenterModelToString(MyAvatar::SitStandModelType model) { switch (model) { - case MyAvatar::ForceSit: - return USER_RECENTER_MODEL_FORCE_SIT; - case MyAvatar::ForceStand: - return USER_RECENTER_MODEL_FORCE_STAND; - case MyAvatar::DisableHMDLean: - return USER_RECENTER_MODEL_DISABLE_HMD_LEAN; - case MyAvatar::Auto: - default: - return USER_RECENTER_MODEL_AUTO; + case MyAvatar::ForceSit: + return USER_RECENTER_MODEL_FORCE_SIT; + case MyAvatar::ForceStand: + return USER_RECENTER_MODEL_FORCE_STAND; + case MyAvatar::DisableHMDLean: + return USER_RECENTER_MODEL_DISABLE_HMD_LEAN; + case MyAvatar::Auto: + default: + return USER_RECENTER_MODEL_AUTO; } } MyAvatar::MyAvatar(QThread* thread) : - Avatar(thread), _yawSpeed(YAW_SPEED_DEFAULT), _pitchSpeed(PITCH_SPEED_DEFAULT), - _scriptedMotorTimescale(DEFAULT_SCRIPTED_MOTOR_TIMESCALE), _scriptedMotorFrame(SCRIPTED_MOTOR_CAMERA_FRAME), - _scriptedMotorMode(SCRIPTED_MOTOR_SIMPLE_MODE), _motionBehaviors(AVATAR_MOTION_DEFAULTS), - _characterController(std::shared_ptr(this)), _eyeContactTarget(LEFT_EYE), - _realWorldFieldOfView("realWorldFieldOfView", DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES), - _useAdvancedMovementControls("advancedMovementForHandControllersIsChecked", true), _showPlayArea("showPlayArea", true), - _smoothOrientationTimer(std::numeric_limits::max()), _smoothOrientationInitial(), _smoothOrientationTarget(), - _hmdSensorMatrix(), _hmdSensorOrientation(), _hmdSensorPosition(), _recentModeReadings(MODE_READINGS_RING_BUFFER_SIZE), - _bodySensorMatrix(), _goToPending(false), _goToSafe(true), _goToFeetAjustment(false), _goToPosition(), _goToOrientation(), - _prevShouldDrawHead(true), _audioListenerMode(FROM_HEAD), + Avatar(thread), + _yawSpeed(YAW_SPEED_DEFAULT), + _pitchSpeed(PITCH_SPEED_DEFAULT), + _scriptedMotorTimescale(DEFAULT_SCRIPTED_MOTOR_TIMESCALE), + _scriptedMotorFrame(SCRIPTED_MOTOR_CAMERA_FRAME), + _scriptedMotorMode(SCRIPTED_MOTOR_SIMPLE_MODE), + _motionBehaviors(AVATAR_MOTION_DEFAULTS), + _characterController(std::shared_ptr(this)), + _eyeContactTarget(LEFT_EYE), + _realWorldFieldOfView("realWorldFieldOfView", + DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES), + _useAdvancedMovementControls("advancedMovementForHandControllersIsChecked", true), + _showPlayArea("showPlayArea", true), + _smoothOrientationTimer(std::numeric_limits::max()), + _smoothOrientationInitial(), + _smoothOrientationTarget(), + _hmdSensorMatrix(), + _hmdSensorOrientation(), + _hmdSensorPosition(), + _recentModeReadings(MODE_READINGS_RING_BUFFER_SIZE), + _bodySensorMatrix(), + _goToPending(false), + _goToSafe(true), + _goToFeetAjustment(false), + _goToPosition(), + _goToOrientation(), + _prevShouldDrawHead(true), + _audioListenerMode(FROM_HEAD), _dominantHandSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "dominantHand", DOMINANT_RIGHT_HAND), _strafeEnabledSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "strafeEnabled", DEFAULT_STRAFE_ENABLED), - _hmdAvatarAlignmentTypeSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "hmdAvatarAlignmentType", - DEFAULT_HMD_AVATAR_ALIGNMENT_TYPE), + _hmdAvatarAlignmentTypeSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "hmdAvatarAlignmentType", DEFAULT_HMD_AVATAR_ALIGNMENT_TYPE), _headPitchSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "", 0.0f), _scaleSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "scale", _targetScale), _yawSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "yawSpeed", _yawSpeed), @@ -156,19 +172,17 @@ MyAvatar::MyAvatar(QThread* thread) : _userHeightSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userHeight", DEFAULT_AVATAR_HEIGHT), _flyingHMDSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "flyingHMD", _flyingPrefHMD), _movementReferenceSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "movementReference", _movementReference), - _avatarEntityCountSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" - << "size", - 0), + _avatarEntityCountSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" << "size", 0), _driveGear1Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear1", _driveGear1), _driveGear2Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear2", _driveGear2), _driveGear3Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear3", _driveGear3), _driveGear4Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear4", _driveGear4), _driveGear5Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear5", _driveGear5), _analogWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogWalkSpeed", _analogWalkSpeed.get()), - _analogPlusWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogPlusWalkSpeed", - _analogPlusWalkSpeed.get()), + _analogPlusWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogPlusWalkSpeed", _analogPlusWalkSpeed.get()), _controlSchemeIndexSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "controlSchemeIndex", _controlSchemeIndex), - _userRecenterModelSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userRecenterModel", USER_RECENTER_MODEL_AUTO) { + _userRecenterModelSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userRecenterModel", USER_RECENTER_MODEL_AUTO) +{ _clientTraitsHandler.reset(new ClientTraitsHandler(this)); // give the pointer to our head to inherited _headData variable from AvatarData @@ -189,7 +203,7 @@ MyAvatar::MyAvatar(QThread* thread) : qApp->loadAvatarScripts(hfmModel.scripts); _shouldLoadScripts = false; } - // Load and convert old attachments to avatar entities + // Load and convert old attachments to avatar entities if (_oldAttachmentData.size() > 0) { setAttachmentData(_oldAttachmentData); _oldAttachmentData.clear(); @@ -206,11 +220,11 @@ MyAvatar::MyAvatar(QThread* thread) : clearDriveKeys(); // Necessary to select the correct slot - using SlotType = void (MyAvatar::*)(const glm::vec3&, bool, const glm::quat&, bool); + using SlotType = void(MyAvatar::*)(const glm::vec3&, bool, const glm::quat&, bool); // connect to AddressManager signal for location jumps - connect(DependencyManager::get().data(), &AddressManager::locationChangeRequired, this, - static_cast(&MyAvatar::goToFeetLocation)); + connect(DependencyManager::get().data(), &AddressManager::locationChangeRequired, + this, static_cast(&MyAvatar::goToFeetLocation)); // handle scale constraints imposed on us by the domain-server auto& domainHandler = DependencyManager::get()->getDomainHandler(); @@ -273,6 +287,7 @@ MyAvatar::MyAvatar(QThread* thread) : if (recordingInterface->getPlayerUseSkeletonModel() && dummyAvatar.getSkeletonModelURL().isValid() && (dummyAvatar.getSkeletonModelURL() != getSkeletonModelURL())) { + setSkeletonModelURL(dummyAvatar.getSkeletonModelURL()); } @@ -368,8 +383,7 @@ void MyAvatar::enableHandTouchForID(const QUuid& entityID) { } void MyAvatar::registerMetaTypes(ScriptEnginePointer engine) { - QScriptValue value = engine->newQObject(this, QScriptEngine::QtOwnership, - QScriptEngine::ExcludeDeleteLater | QScriptEngine::ExcludeChildObjects); + QScriptValue value = engine->newQObject(this, QScriptEngine::QtOwnership, QScriptEngine::ExcludeDeleteLater | QScriptEngine::ExcludeChildObjects); engine->globalObject().setProperty("MyAvatar", value); QScriptValue driveKeys = engine->newObject(); @@ -432,6 +446,7 @@ void MyAvatar::resetSensorsAndBody() { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "resetSensorsAndBody"); return; + } qApp->getActiveDisplayPlugin()->resetSensors(); @@ -445,7 +460,7 @@ void MyAvatar::centerBody() { } // derive the desired body orientation from the current hmd orientation, before the sensor reset. - auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. // transform this body into world space auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix; @@ -482,6 +497,7 @@ void MyAvatar::clearIKJointLimitHistory() { } void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { + assert(QThread::currentThread() == thread()); // Reset dynamic state. @@ -490,14 +506,14 @@ void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { if (andReload) { _skeletonModel->reset(); } - if (andHead) { // which drives camera in desktop + if (andHead) { // which drives camera in desktop getHead()->reset(); } setThrust(glm::vec3(0.0f)); if (andRecenter) { // derive the desired body orientation from the *old* hmd orientation, before the sensor reset. - auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. // transform this body into world space auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix; @@ -524,8 +540,8 @@ void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { void MyAvatar::updateSitStandState(float newHeightReading, float dt) { const float STANDING_HEIGHT_MULTIPLE = 1.2f; const float SITTING_HEIGHT_MULTIPLE = 0.833f; - const float SITTING_TIMEOUT = 4.0f; // 4 seconds - const float STANDING_TIMEOUT = 0.3333f; // 1/3 second + const float SITTING_TIMEOUT = 4.0f; // 4 seconds + const float STANDING_TIMEOUT = 0.3333f; // 1/3 second const float SITTING_UPPER_BOUND = 1.52f; if (!getIsSitStandStateLocked()) { if (!getIsAway() && getControllerPoseInAvatarFrame(controller::Action::HEAD).isValid()) { @@ -585,9 +601,9 @@ void MyAvatar::updateSitStandState(float newHeightReading, float dt) { void MyAvatar::update(float deltaTime) { // update moving average of HMD facing in xz plane. const float HMD_FACING_TIMESCALE = getRotationRecenterFilterLength(); - const float PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH = 0.0f; // 100 percent shoulders + const float PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH = 0.0f; // 100 percent shoulders const float COSINE_THIRTY_DEGREES = 0.866f; - const float SQUATTY_TIMEOUT = 30.0f; // 30 seconds + const float SQUATTY_TIMEOUT = 30.0f; // 30 seconds const float HEIGHT_FILTER_COEFFICIENT = 0.01f; float tau = deltaTime / HMD_FACING_TIMESCALE; @@ -596,8 +612,8 @@ void MyAvatar::update(float deltaTime) { // put the average hand azimuth into sensor space. // then mix it with head facing direction to determine rotation recenter int spine2Index = _skeletonModel->getRig().indexOfJoint("Spine2"); - if (getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND).isValid() && - getControllerPoseInAvatarFrame(controller::Action::RIGHT_HAND).isValid() && !(spine2Index < 0)) { + if (getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND).isValid() && getControllerPoseInAvatarFrame(controller::Action::RIGHT_HAND).isValid() && !(spine2Index < 0)) { + // use the spine for the azimuth origin. glm::quat spine2Rot = getAbsoluteJointRotationInObjectFrame(spine2Index); glm::vec3 handHipAzimuthAvatarSpace = spine2Rot * glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y); @@ -607,10 +623,8 @@ void MyAvatar::update(float deltaTime) { glm::vec3 handHipAzimuthSensorSpace = transformVectorFast(worldToSensorMat, handHipAzimuthWorldSpace); glm::vec2 normedHandHipAzimuthSensorSpace(0.0f, 1.0f); if (glm::length(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)) > 0.0f) { - normedHandHipAzimuthSensorSpace = - glm::normalize(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)); - glm::vec2 headFacingPlusHandHipAzimuthMix = - lerp(normedHandHipAzimuthSensorSpace, _headControllerFacing, PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH); + normedHandHipAzimuthSensorSpace = glm::normalize(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)); + glm::vec2 headFacingPlusHandHipAzimuthMix = lerp(normedHandHipAzimuthSensorSpace, _headControllerFacing, PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH); _headControllerFacingMovingAverage = lerp(_headControllerFacingMovingAverage, headFacingPlusHandHipAzimuthMix, tau); } else { // use head facing if the chest arms vector is up or down. @@ -628,8 +642,7 @@ void MyAvatar::update(float deltaTime) { controller::Pose newHeightReading = getControllerPoseInSensorFrame(controller::Action::HEAD); if (newHeightReading.isValid()) { int newHeightReadingInCentimeters = glm::floor(newHeightReading.getTranslation().y * CENTIMETERS_PER_METER); - _averageUserHeightSensorSpace = - lerp(_averageUserHeightSensorSpace, newHeightReading.getTranslation().y, HEIGHT_FILTER_COEFFICIENT); + _averageUserHeightSensorSpace = lerp(_averageUserHeightSensorSpace, newHeightReading.getTranslation().y, HEIGHT_FILTER_COEFFICIENT); _recentModeReadings.insert(newHeightReadingInCentimeters); setCurrentStandingHeight(computeStandingHeightMode(newHeightReading)); setAverageHeadRotation(computeAverageHeadRotation(getControllerPoseInAvatarFrame(controller::Action::HEAD))); @@ -645,9 +658,10 @@ void MyAvatar::update(float deltaTime) { } float angleSpine2 = glm::dot(upSpine2, glm::vec3(0.0f, 1.0f, 0.0f)); - if (getControllerPoseInAvatarFrame(controller::Action::HEAD).getTranslation().y < - (headDefaultPositionAvatarSpace.y - SQUAT_THRESHOLD) && - (angleSpine2 > COSINE_THIRTY_DEGREES) && (getUserRecenterModel() != MyAvatar::SitStandModelType::ForceStand)) { + if (getControllerPoseInAvatarFrame(controller::Action::HEAD).getTranslation().y < (headDefaultPositionAvatarSpace.y - SQUAT_THRESHOLD) && + (angleSpine2 > COSINE_THIRTY_DEGREES) && + (getUserRecenterModel() != MyAvatar::SitStandModelType::ForceStand)) { + _squatTimer += deltaTime; if (_squatTimer > SQUATTY_TIMEOUT) { _squatTimer = 0.0f; @@ -663,24 +677,20 @@ void MyAvatar::update(float deltaTime) { if (_drawAverageFacingEnabled) { auto sensorHeadPose = getControllerPoseInSensorFrame(controller::Action::HEAD); glm::vec3 worldHeadPos = transformPoint(getSensorToWorldMatrix(), sensorHeadPose.getTranslation()); - glm::vec3 worldFacingAverage = - transformVectorFast(getSensorToWorldMatrix(), - glm::vec3(_headControllerFacingMovingAverage.x, 0.0f, _headControllerFacingMovingAverage.y)); - glm::vec3 worldFacing = - transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacing.x, 0.0f, _headControllerFacing.y)); + glm::vec3 worldFacingAverage = transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacingMovingAverage.x, 0.0f, _headControllerFacingMovingAverage.y)); + glm::vec3 worldFacing = transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacing.x, 0.0f, _headControllerFacing.y)); DebugDraw::getInstance().drawRay(worldHeadPos, worldHeadPos + worldFacing, glm::vec4(0.0f, 1.0f, 0.0f, 1.0f)); DebugDraw::getInstance().drawRay(worldHeadPos, worldHeadPos + worldFacingAverage, glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)); // draw hand azimuth vector - glm::vec3 handAzimuthMidpoint = - transformPoint(getTransform().getMatrix(), glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y)); + glm::vec3 handAzimuthMidpoint = transformPoint(getTransform().getMatrix(), glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y)); DebugDraw::getInstance().drawRay(getWorldPosition(), handAzimuthMidpoint, glm::vec4(0.0f, 1.0f, 1.0f, 1.0f)); } if (_goToPending) { setWorldPosition(_goToPosition); setWorldOrientation(_goToOrientation); - _headControllerFacingMovingAverage = _headControllerFacing; // reset moving average + _headControllerFacingMovingAverage = _headControllerFacing; // reset moving average _goToPending = false; // updateFromHMDSensorMatrix (called from paintGL) expects that the sensorToWorldMatrix is updated for any position changes // that happen between render and Application::update (which calls updateSensorToWorldMatrix to do so). @@ -690,7 +700,7 @@ void MyAvatar::update(float deltaTime) { emit positionGoneTo(); // Run safety tests as soon as we can after goToLocation, or clear if we're not colliding. _physicsSafetyPending = getCollisionsEnabled(); - _characterController.recomputeFlying(); // In case we've gone to into the sky. + _characterController.recomputeFlying(); // In case we've gone to into the sky. } if (_goToFeetAjustment && _skeletonModelLoaded) { auto feetAjustment = getWorldPosition() - getWorldFeetPosition(); @@ -702,7 +712,7 @@ void MyAvatar::update(float deltaTime) { // When needed and ready, arrange to check and fix. _physicsSafetyPending = false; if (_goToSafe) { - safeLanding(_goToPosition); // no-op if already safe + safeLanding(_goToPosition); // no-op if already safe } } @@ -710,8 +720,7 @@ void MyAvatar::update(float deltaTime) { head->relax(deltaTime); updateFromTrackers(deltaTime); - if (getIsInWalkingState() && glm::length(getControllerPoseInAvatarFrame(controller::Action::HEAD).getVelocity()) < - DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { + if (getIsInWalkingState() && glm::length(getControllerPoseInAvatarFrame(controller::Action::HEAD).getVelocity()) < DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { setIsInWalkingState(false); } @@ -722,13 +731,12 @@ void MyAvatar::update(float deltaTime) { setAudioLoudness(audio->getLastInputLoudness()); setAudioAverageLoudness(audio->getAudioAverageInputLoudness()); - glm::vec3 halfBoundingBoxDimensions(_characterController.getCapsuleRadius(), _characterController.getCapsuleHalfHeight(), - _characterController.getCapsuleRadius()); + glm::vec3 halfBoundingBoxDimensions(_characterController.getCapsuleRadius(), _characterController.getCapsuleHalfHeight(), _characterController.getCapsuleRadius()); // This might not be right! Isn't the capsule local offset in avatar space? -HRS 5/26/17 halfBoundingBoxDimensions += _characterController.getCapsuleLocalOffset(); QMetaObject::invokeMethod(audio, "setAvatarBoundingBoxParameters", - Q_ARG(glm::vec3, (getWorldPosition() - halfBoundingBoxDimensions)), - Q_ARG(glm::vec3, (halfBoundingBoxDimensions * 2.0f))); + Q_ARG(glm::vec3, (getWorldPosition() - halfBoundingBoxDimensions)), + Q_ARG(glm::vec3, (halfBoundingBoxDimensions*2.0f))); simulate(deltaTime, true); @@ -736,20 +744,23 @@ void MyAvatar::update(float deltaTime) { currentEnergy -= getAccelerationEnergy(); currentEnergy -= getAudioEnergy(); - if (didTeleport()) { + if(didTeleport()) { currentEnergy = 0.0f; } - currentEnergy = max(0.0f, min(currentEnergy, 1.0f)); + currentEnergy = max(0.0f, min(currentEnergy,1.0f)); emit energyChanged(currentEnergy); updateEyeContactTarget(deltaTime); } void MyAvatar::updateEyeContactTarget(float deltaTime) { + _eyeContactTargetTimer -= deltaTime; if (_eyeContactTargetTimer < 0.0f) { + const float CHANCE_OF_CHANGING_TARGET = 0.01f; if (randFloat() < CHANCE_OF_CHANGING_TARGET) { + float const FIFTY_FIFTY_CHANCE = 0.5f; float const EYE_TO_MOUTH_CHANCE = 0.25f; switch (_eyeContactTarget) { @@ -817,20 +828,21 @@ void MyAvatar::simulate(float deltaTime, bool inView) { if (isChildOfHead && !object->hasGrabs()) { // Cauterize or display children of head per head drawing state. updateChildCauterization(object, !_prevShouldDrawHead); - object->forEachDescendant( - [&](SpatiallyNestablePointer descendant) { updateChildCauterization(descendant, !_prevShouldDrawHead); }); + object->forEachDescendant([&](SpatiallyNestablePointer descendant) { + updateChildCauterization(descendant, !_prevShouldDrawHead); + }); _cauterizedChildrenOfHead.insert(object); objectsToUncauterize.erase(object); } else if (objectsToUncauterize.find(object) == objectsToUncauterize.end()) { objectsToUncauterize.insert(object); - object->forEachDescendant( - [&](SpatiallyNestablePointer descendant) { objectsToUncauterize.insert(descendant); }); + object->forEachDescendant([&](SpatiallyNestablePointer descendant) { + objectsToUncauterize.insert(descendant); + }); } }); // Redisplay cauterized entities that are no longer children of the avatar. - for (auto cauterizedChild = objectsToUncauterize.begin(); cauterizedChild != objectsToUncauterize.end(); - cauterizedChild++) { + for (auto cauterizedChild = objectsToUncauterize.begin(); cauterizedChild != objectsToUncauterize.end(); cauterizedChild++) { updateChildCauterization(*cauterizedChild, false); } } @@ -874,7 +886,7 @@ void MyAvatar::simulate(float deltaTime, bool inView) { if (!_skeletonModel->hasSkeleton()) { // All the simulation that can be done has been done - getHead()->setPosition(getWorldPosition()); // so audio-position isn't 0,0,0 + getHead()->setPosition(getWorldPosition()); // so audio-position isn't 0,0,0 return; } @@ -955,7 +967,8 @@ void MyAvatar::updateFromHMDSensorMatrix(const glm::mat4& hmdSensorMatrix) { _hmdSensorMatrix = hmdSensorMatrix; auto newHmdSensorPosition = extractTranslation(hmdSensorMatrix); - if (newHmdSensorPosition != getHMDSensorPosition() && glm::length(newHmdSensorPosition) > MAX_HMD_ORIGIN_DISTANCE) { + if (newHmdSensorPosition != getHMDSensorPosition() && + glm::length(newHmdSensorPosition) > MAX_HMD_ORIGIN_DISTANCE) { qWarning() << "Invalid HMD sensor position " << newHmdSensorPosition; // Ignore unreasonable HMD sensor data return; @@ -983,8 +996,8 @@ glm::vec2 MyAvatar::computeHandAzimuth() const { glm::vec2 latestHipToHandController = _hipToHandController; int spine2Index = _skeletonModel->getRig().indexOfJoint("Spine2"); - if (leftHandPoseAvatarSpace.isValid() && rightHandPoseAvatarSpace.isValid() && headPoseAvatarSpace.isValid() && - !(spine2Index < 0)) { + if (leftHandPoseAvatarSpace.isValid() && rightHandPoseAvatarSpace.isValid() && headPoseAvatarSpace.isValid() && !(spine2Index < 0)) { + glm::vec3 spine2Position = getAbsoluteJointTranslationInObjectFrame(spine2Index); glm::quat spine2Rotation = getAbsoluteJointRotationInObjectFrame(spine2Index); @@ -996,10 +1009,8 @@ glm::vec2 MyAvatar::computeHandAzimuth() const { // we need the old azimuth reading to prevent flipping the facing direction 180 // in the case where the hands go from being slightly less than 180 apart to slightly more than 180 apart. glm::vec2 oldAzimuthReading = _hipToHandController; - if ((glm::length(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)) > 0.0f) && - (glm::length(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)) > 0.0f)) { - latestHipToHandController = lerp(glm::normalize(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)), - glm::normalize(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)), HALFWAY); + if ((glm::length(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)) > 0.0f) && (glm::length(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)) > 0.0f)) { + latestHipToHandController = lerp(glm::normalize(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)), glm::normalize(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)), HALFWAY); } else { latestHipToHandController = glm::vec2(0.0f, 1.0f); } @@ -1047,11 +1058,11 @@ void MyAvatar::updateJointFromController(controller::Action poseKey, ThreadSafeV // update sensor to world matrix from current body position and hmd sensor. // This is so the correct camera can be used for rendering. void MyAvatar::updateSensorToWorldMatrix() { + // update the sensor mat so that the body position will end up in the desired // position when driven from the head. float sensorToWorldScale = getEyeHeight() / getUserEyeHeight(); - glm::mat4 desiredMat = - createMatFromScaleQuatAndPos(glm::vec3(sensorToWorldScale), getWorldOrientation(), getWorldPosition()); + glm::mat4 desiredMat = createMatFromScaleQuatAndPos(glm::vec3(sensorToWorldScale), getWorldOrientation(), getWorldPosition()); _sensorToWorldMatrix = desiredMat * glm::inverse(_bodySensorMatrix); bool hasSensorToWorldScaleChanged = false; @@ -1069,10 +1080,11 @@ void MyAvatar::updateSensorToWorldMatrix() { _sensorToWorldMatrixCache.set(_sensorToWorldMatrix); updateJointFromController(controller::Action::LEFT_HAND, _controllerLeftHandMatrixCache); updateJointFromController(controller::Action::RIGHT_HAND, _controllerRightHandMatrixCache); - + if (hasSensorToWorldScaleChanged) { emit sensorToWorldScaleChanged(sensorToWorldScale); } + } // Update avatar head rotation with sensor data @@ -1097,7 +1109,8 @@ void MyAvatar::updateFromTrackers(float deltaTime) { const float TRACKER_YAW_TURN_SENSITIVITY = 0.5f; const float TRACKER_MIN_YAW_TURN = 15.0f; const float TRACKER_MAX_YAW_TURN = 50.0f; - if ((fabs(estimatedRotation.y) > TRACKER_MIN_YAW_TURN) && (fabs(estimatedRotation.y) < TRACKER_MAX_YAW_TURN)) { + if ( (fabs(estimatedRotation.y) > TRACKER_MIN_YAW_TURN) && + (fabs(estimatedRotation.y) < TRACKER_MAX_YAW_TURN) ) { if (estimatedRotation.y > 0.0f) { _bodyYawDelta += (estimatedRotation.y - TRACKER_MIN_YAW_TURN) * TRACKER_YAW_TURN_SENSITIVITY; } else { @@ -1112,6 +1125,7 @@ void MyAvatar::updateFromTrackers(float deltaTime) { // their head only 30 degrees or so, this may correspond to a 90 degree field of view. // Note that roll is magnified by a constant because it is not related to field of view. + Head* head = getHead(); if (hasHead || playing) { head->setDeltaPitch(estimatedRotation.x); @@ -1177,15 +1191,15 @@ controller::Pose MyAvatar::getRightHandTipPose() const { void MyAvatar::render(RenderArgs* renderArgs) { // don't render if we've been asked to disable local rendering if (!_shouldRender) { - return; // exit early + return; // exit early } Avatar::render(renderArgs); } void MyAvatar::overrideAnimation(const QString& url, float fps, bool loop, float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "overrideAnimation", Q_ARG(const QString&, url), Q_ARG(float, fps), Q_ARG(bool, loop), - Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); + QMetaObject::invokeMethod(this, "overrideAnimation", Q_ARG(const QString&, url), Q_ARG(float, fps), + Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); return; } _skeletonModel->getRig().overrideAnimation(url, fps, loop, firstFrame, lastFrame); @@ -1193,8 +1207,8 @@ void MyAvatar::overrideAnimation(const QString& url, float fps, bool loop, float void MyAvatar::overrideHandAnimation(bool isLeft, const QString& url, float fps, bool loop, float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "overrideHandAnimation", Q_ARG(bool, isLeft), Q_ARG(const QString&, url), - Q_ARG(float, fps), Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); + QMetaObject::invokeMethod(this, "overrideHandAnimation", Q_ARG(bool, isLeft), Q_ARG(const QString&, url), Q_ARG(float, fps), + Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); return; } _skeletonModel->getRig().overrideHandAnimation(isLeft, url, fps, loop, firstFrame, lastFrame); @@ -1225,12 +1239,8 @@ QStringList MyAvatar::getAnimationRoles() { return _skeletonModel->getRig().getAnimationRoles(); } -void MyAvatar::overrideRoleAnimation(const QString& role, - const QString& url, - float fps, - bool loop, - float firstFrame, - float lastFrame) { +void MyAvatar::overrideRoleAnimation(const QString& role, const QString& url, float fps, bool loop, + float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "overrideRoleAnimation", Q_ARG(const QString&, role), Q_ARG(const QString&, url), Q_ARG(float, fps), Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); @@ -1249,9 +1259,9 @@ void MyAvatar::restoreRoleAnimation(const QString& role) { void MyAvatar::saveAvatarUrl() { if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid()) { - _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() - ? "" - : _fullAvatarURLFromPreferences.toString()); + _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() ? + "" : + _fullAvatarURLFromPreferences.toString()); } } @@ -1268,12 +1278,10 @@ void MyAvatar::resizeAvatarEntitySettingHandles(uint32_t maxIndex) { uint32_t settingsIndex = (uint32_t)_avatarEntityIDSettings.size() + 1; while (settingsIndex <= maxIndex) { Setting::Handle idHandle(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" - << QString::number(settingsIndex) << "id", - QUuid()); + << QString::number(settingsIndex) << "id", QUuid()); _avatarEntityIDSettings.push_back(idHandle); Setting::Handle dataHandle(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" - << QString::number(settingsIndex) << "properties", - QByteArray()); + << QString::number(settingsIndex) << "properties", QByteArray()); _avatarEntityDataSettings.push_back(dataHandle); settingsIndex++; } @@ -1291,10 +1299,10 @@ void MyAvatar::saveData() { // only save the fullAvatarURL if it has not been overwritten on command line // (so the overrideURL is not valid), or it was overridden _and_ we specified // --replaceAvatarURL (so _saveAvatarOverrideUrl is true) - if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid()) { - _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() - ? "" - : _fullAvatarURLFromPreferences.toString()); + if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid() ) { + _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() ? + "" : + _fullAvatarURLFromPreferences.toString()); } _fullAvatarModelNameSetting.set(_fullAvatarModelName); @@ -1464,12 +1472,16 @@ void MyAvatar::setEnableInverseKinematics(bool isEnabled) { void MyAvatar::storeAvatarEntityDataPayload(const QUuid& entityID, const QByteArray& payload) { AvatarData::storeAvatarEntityDataPayload(entityID, payload); - _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobsToAddOrUpdate.push_back(entityID); }); + _avatarEntitiesLock.withWriteLock([&] { + _cachedAvatarEntityBlobsToAddOrUpdate.push_back(entityID); + }); } void MyAvatar::clearAvatarEntity(const QUuid& entityID, bool requiresRemovalFromTree) { AvatarData::clearAvatarEntity(entityID, requiresRemovalFromTree); - _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobsToDelete.push_back(entityID); }); + _avatarEntitiesLock.withWriteLock([&] { + _cachedAvatarEntityBlobsToDelete.push_back(entityID); + }); } void MyAvatar::sanitizeAvatarEntityProperties(EntityItemProperties& properties) const { @@ -1494,7 +1506,9 @@ void MyAvatar::sanitizeAvatarEntityProperties(EntityItemProperties& properties) void MyAvatar::handleChangedAvatarEntityData() { // NOTE: this is a per-frame update - if (getID().isNull() || getID() == AVATAR_SELF_ID || DependencyManager::get()->getSessionUUID() == QUuid()) { + if (getID().isNull() || + getID() == AVATAR_SELF_ID || + DependencyManager::get()->getSessionUUID() == QUuid()) { // wait until MyAvatar and this Node gets an ID before doing this. Otherwise, various things go wrong: // things get their parent fixed up from AVATAR_SELF_ID to a null uuid which means "no parent". return; @@ -1540,7 +1554,7 @@ void MyAvatar::handleChangedAvatarEntityData() { entitiesToUpdate = std::move(_entitiesToUpdate); }); - auto removeAllInstancesHelper = [](const QUuid& id, std::vector& v) { + auto removeAllInstancesHelper = [] (const QUuid& id, std::vector& v) { uint32_t i = 0; while (i < v.size()) { if (id == v[i]) { @@ -1568,7 +1582,9 @@ void MyAvatar::handleChangedAvatarEntityData() { // DELETE real entities for (const auto& id : entitiesToDelete) { - entityTree->withWriteLock([&] { entityTree->deleteEntity(id); }); + entityTree->withWriteLock([&] { + entityTree->deleteEntity(id); + }); } // ADD real entities @@ -1579,19 +1595,21 @@ void MyAvatar::handleChangedAvatarEntityData() { _avatarEntitiesLock.withReadLock([&] { AvatarEntityMap::iterator itr = _cachedAvatarEntityBlobs.find(id); if (itr == _cachedAvatarEntityBlobs.end()) { - blobFailed = true; // blob doesn't exist + blobFailed = true; // blob doesn't exist return; } std::lock_guard guard(_scriptEngineLock); if (!EntityItemProperties::blobToProperties(*_scriptEngine, itr.value(), properties)) { - blobFailed = true; // blob is corrupt + blobFailed = true; // blob is corrupt } }); if (blobFailed) { // remove from _cachedAvatarEntityBlobUpdatesToSkip just in case: // avoids a resource leak when blob updates to be skipped are never actually skipped // when the blob fails to result in a real EntityItem - _avatarEntitiesLock.withWriteLock([&] { removeAllInstancesHelper(id, _cachedAvatarEntityBlobUpdatesToSkip); }); + _avatarEntitiesLock.withWriteLock([&] { + removeAllInstancesHelper(id, _cachedAvatarEntityBlobUpdatesToSkip); + }); continue; } sanitizeAvatarEntityProperties(properties); @@ -1661,7 +1679,7 @@ void MyAvatar::handleChangedAvatarEntityData() { _cachedAvatarEntityBlobUpdatesToSkip[i] = _cachedAvatarEntityBlobUpdatesToSkip.back(); _cachedAvatarEntityBlobUpdatesToSkip.pop_back(); skip = true; - break; // assume no duplicates + break; // assume no duplicates } else { ++i; } @@ -1725,7 +1743,9 @@ bool MyAvatar::updateStaleAvatarEntityBlobs() const { std::lock_guard guard(_scriptEngineLock); EntityItemProperties::propertiesToBlob(*_scriptEngine, getID(), properties, blob); } - _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobs[id] = blob; }); + _avatarEntitiesLock.withWriteLock([&] { + _cachedAvatarEntityBlobs[id] = blob; + }); } } return true; @@ -1752,7 +1772,9 @@ AvatarEntityMap MyAvatar::getAvatarEntityData() const { // NOTE: the return value is expected to be a map of unfortunately-formatted-binary-blobs updateStaleAvatarEntityBlobs(); AvatarEntityMap result; - _avatarEntitiesLock.withReadLock([&] { result = _cachedAvatarEntityBlobs; }); + _avatarEntitiesLock.withReadLock([&] { + result = _cachedAvatarEntityBlobs; + }); return result; } @@ -1853,9 +1875,7 @@ void MyAvatar::avatarEntityDataToJson(QJsonObject& root) const { AvatarEntityMap::const_iterator itr = _cachedAvatarEntityBlobs.begin(); while (itr != _cachedAvatarEntityBlobs.end()) { QVariantMap entityData; - QUuid id = _avatarEntityForRecording.size() == _cachedAvatarEntityBlobs.size() - ? _avatarEntityForRecording.values()[entityCount++] - : itr.key(); + QUuid id = _avatarEntityForRecording.size() == _cachedAvatarEntityBlobs.size() ? _avatarEntityForRecording.values()[entityCount++] : itr.key(); entityData.insert("id", id); entityData.insert("properties", itr.value().toBase64()); avatarEntityJson.push_back(QVariant(entityData).toJsonObject()); @@ -1885,7 +1905,7 @@ void MyAvatar::loadData() { loadAvatarEntityDataFromSettings(); // Flying preferences must be loaded before calling setFlyingEnabled() - Setting::Handle firstRunVal{ Settings::firstRun, true }; + Setting::Handle firstRunVal { Settings::firstRun, true }; setFlyingHMDPref(firstRunVal.get() ? false : _flyingHMDSetting.get()); setMovementReference(firstRunVal.get() ? false : _movementReferenceSetting.get()); setDriveGear1(firstRunVal.get() ? DEFAULT_GEAR_1 : _driveGear1Setting.get()); @@ -1911,7 +1931,7 @@ void MyAvatar::loadData() { setUserRecenterModel(stringToUserRecenterModel(_userRecenterModelSetting.get(USER_RECENTER_MODEL_AUTO))); setEnableMeshVisible(Menu::getInstance()->isOptionChecked(MenuOption::MeshVisible)); - _follow.setToggleHipsFollowing(Menu::getInstance()->isOptionChecked(MenuOption::ToggleHipsFollowing)); + _follow.setToggleHipsFollowing (Menu::getInstance()->isOptionChecked(MenuOption::ToggleHipsFollowing)); setEnableDebugDrawBaseOfSupport(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawBaseOfSupport)); setEnableDebugDrawDefaultPose(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawDefaultPose)); setEnableDebugDrawAnimPose(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawAnimPose)); @@ -1939,7 +1959,7 @@ void MyAvatar::loadAvatarEntityDataFromSettings() { _entitiesToAdd.reserve(numEntities); // TODO: build map between old and new IDs so we can restitch parent-child relationships for (int i = 0; i < numEntities; i++) { - QUuid id = QUuid::createUuid(); // generate a new ID + QUuid id = QUuid::createUuid(); // generate a new ID _cachedAvatarEntityBlobs[id] = _avatarEntityDataSettings[i].get(); _entitiesToAdd.push_back(id); // this blob is the "authoritative source" for this AvatarEntity and we want to avoid overwriting it @@ -2009,9 +2029,10 @@ AttachmentData MyAvatar::loadAttachmentData(const QUrl& modelURL, const QString& return attachment; } + int MyAvatar::parseDataFromBuffer(const QByteArray& buffer) { qCDebug(interfaceapp) << "Error: ignoring update packet for MyAvatar" - << " packetLength = " << buffer.size(); + << " packetLength = " << buffer.size(); // this packet is just bad, so we pretend that we unpacked it ALL return buffer.size(); } @@ -2025,12 +2046,8 @@ ScriptAvatarData* MyAvatar::getTargetAvatar() const { } } -static float lookAtCostFunction(const glm::vec3& myForward, - const glm::vec3& myPosition, - const glm::vec3& otherForward, - const glm::vec3& otherPosition, - bool otherIsTalking, - bool lookingAtOtherAlready) { +static float lookAtCostFunction(const glm::vec3& myForward, const glm::vec3& myPosition, const glm::vec3& otherForward, const glm::vec3& otherPosition, + bool otherIsTalking, bool lookingAtOtherAlready) { const float DISTANCE_FACTOR = 3.14f; const float MY_ANGLE_FACTOR = 1.0f; const float OTHER_ANGLE_FACTOR = 1.0f; @@ -2038,7 +2055,7 @@ static float lookAtCostFunction(const glm::vec3& myForward, const float LOOKING_AT_OTHER_ALREADY_TERM = lookingAtOtherAlready ? -0.2f : 0.0f; const float GREATEST_LOOKING_AT_DISTANCE = 10.0f; // meters - const float MAX_MY_ANGLE = PI / 8.0f; // 22.5 degrees, Don't look too far away from the head facing. + const float MAX_MY_ANGLE = PI / 8.0f; // 22.5 degrees, Don't look too far away from the head facing. const float MAX_OTHER_ANGLE = (3.0f * PI) / 4.0f; // 135 degrees, Don't stare at the back of another avatars head. glm::vec3 d = otherPosition - myPosition; @@ -2050,8 +2067,11 @@ static float lookAtCostFunction(const glm::vec3& myForward, if (distance > GREATEST_LOOKING_AT_DISTANCE || myAngle > MAX_MY_ANGLE || otherAngle > MAX_OTHER_ANGLE) { return FLT_MAX; } else { - return (DISTANCE_FACTOR * distance + MY_ANGLE_FACTOR * myAngle + OTHER_ANGLE_FACTOR * otherAngle + - OTHER_IS_TALKING_TERM + LOOKING_AT_OTHER_ALREADY_TERM); + return (DISTANCE_FACTOR * distance + + MY_ANGLE_FACTOR * myAngle + + OTHER_ANGLE_FACTOR * otherAngle + + OTHER_IS_TALKING_TERM + + LOOKING_AT_OTHER_ALREADY_TERM); } } @@ -2074,8 +2094,7 @@ void MyAvatar::computeMyLookAtTarget(const AvatarHash& hash) { const float TIME_WITHOUT_TALKING_THRESHOLD = 1.0f; bool otherIsTalking = avatar->getHead()->getTimeWithoutTalking() <= TIME_WITHOUT_TALKING_THRESHOLD; bool lookingAtOtherAlready = _lookAtTargetAvatar.lock().get() == avatar.get(); - float cost = - lookAtCostFunction(myForward, myPosition, otherForward, otherPosition, otherIsTalking, lookingAtOtherAlready); + float cost = lookAtCostFunction(myForward, myPosition, otherForward, otherPosition, otherIsTalking, lookingAtOtherAlready); if (cost < bestCost) { bestCost = cost; bestAvatar = avatar; @@ -2096,8 +2115,9 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { std::shared_ptr avatar = std::static_pointer_cast(avatarData); if (!avatar->isMyAvatar() && avatar->isInitialized()) { if (_lookAtSnappingEnabled && avatar->getLookAtSnappingEnabled() && isLookingAtMe(avatar)) { + // Alter their gaze to look directly at my camera; this looks more natural than looking at my avatar's face. - glm::vec3 lookAtPosition = avatar->getHead()->getLookAtPosition(); // A position, in world space, on my avatar. + glm::vec3 lookAtPosition = avatar->getHead()->getLookAtPosition(); // A position, in world space, on my avatar. // The camera isn't at the point midway between the avatar eyes. (Even without an HMD, the head can be offset a bit.) // Let's get everything to world space: @@ -2108,12 +2128,12 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { // (We will be adding that offset to the camera position, after making some other adjustments.) glm::vec3 gazeOffset = lookAtPosition - getHead()->getEyePosition(); - ViewFrustum viewFrustum; - qApp->copyViewFrustum(viewFrustum); + ViewFrustum viewFrustum; + qApp->copyViewFrustum(viewFrustum); - glm::vec3 viewPosition = viewFrustum.getPosition(); + glm::vec3 viewPosition = viewFrustum.getPosition(); #if DEBUG_ALWAYS_LOOKAT_EYES_NOT_CAMERA - viewPosition = (avatarLeftEye + avatarRightEye) / 2.0f; + viewPosition = (avatarLeftEye + avatarRightEye) / 2.0f; #endif // scale gazeOffset by IPD, if wearing an HMD. if (qApp->isHMDMode()) { @@ -2151,6 +2171,7 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { } void MyAvatar::updateLookAtTargetAvatar() { + // The AvatarManager is a mutable class shared by many threads. We make a thread-safe deep copy of it, // to avoid having to hold a lock while we iterate over all the avatars within. AvatarHash hash = DependencyManager::get()->getHashCopy(); @@ -2264,7 +2285,8 @@ void MyAvatar::setJointTranslation(int index, const glm::vec3& translation) { } default: { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "setJointTranslation", Q_ARG(int, index), Q_ARG(const glm::vec3&, translation)); + QMetaObject::invokeMethod(this, "setJointTranslation", + Q_ARG(int, index), Q_ARG(const glm::vec3&, translation)); return; } // HACK: ATM only JS scripts call setJointData() on MyAvatar so we hardcode the priority @@ -2303,7 +2325,9 @@ void MyAvatar::setJointData(const QString& name, const glm::quat& rotation, cons Q_ARG(const glm::vec3&, translation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { setJointData(index, rotation, translation); }); + writeLockWithNamedJointIndex(name, [&](int index) { + setJointData(index, rotation, translation); + }); } void MyAvatar::setJointRotation(const QString& name, const glm::quat& rotation) { @@ -2311,7 +2335,9 @@ void MyAvatar::setJointRotation(const QString& name, const glm::quat& rotation) QMetaObject::invokeMethod(this, "setJointRotation", Q_ARG(QString, name), Q_ARG(const glm::quat&, rotation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { setJointRotation(index, rotation); }); + writeLockWithNamedJointIndex(name, [&](int index) { + setJointRotation(index, rotation); + }); } void MyAvatar::setJointTranslation(const QString& name, const glm::vec3& translation) { @@ -2319,7 +2345,9 @@ void MyAvatar::setJointTranslation(const QString& name, const glm::vec3& transla QMetaObject::invokeMethod(this, "setJointTranslation", Q_ARG(QString, name), Q_ARG(const glm::vec3&, translation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { setJointTranslation(index, translation); }); + writeLockWithNamedJointIndex(name, [&](int index) { + setJointTranslation(index, translation); + }); } void MyAvatar::clearJointData(const QString& name) { @@ -2327,7 +2355,9 @@ void MyAvatar::clearJointData(const QString& name) { QMetaObject::invokeMethod(this, "clearJointData", Q_ARG(QString, name)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { clearJointData(index); }); + writeLockWithNamedJointIndex(name, [&](int index) { + clearJointData(index); + }); } void MyAvatar::clearJointsData() { @@ -2362,36 +2392,36 @@ void MyAvatar::setSkeletonModelURL(const QUrl& skeletonModelURL) { _skeletonModelLoaded = false; std::shared_ptr skeletonConnection = std::make_shared(); - *skeletonConnection = QObject::connect(_skeletonModel.get(), &SkeletonModel::skeletonLoaded, - [this, skeletonModelChangeCount, skeletonConnection]() { - if (skeletonModelChangeCount == _skeletonModelChangeCount) { - if (_fullAvatarModelName.isEmpty()) { - // Store the FST file name into preferences - const auto& mapping = _skeletonModel->getGeometry()->getMapping(); - if (mapping.value("name").isValid()) { - _fullAvatarModelName = mapping.value("name").toString(); - } - } + *skeletonConnection = QObject::connect(_skeletonModel.get(), &SkeletonModel::skeletonLoaded, [this, skeletonModelChangeCount, skeletonConnection]() { + if (skeletonModelChangeCount == _skeletonModelChangeCount) { - initHeadBones(); - _skeletonModel->setCauterizeBoneSet(_headBoneSet); - _fstAnimGraphOverrideUrl = - _skeletonModel->getGeometry()->getAnimGraphOverrideUrl(); - initAnimGraph(); - initFlowFromFST(); + if (_fullAvatarModelName.isEmpty()) { + // Store the FST file name into preferences + const auto& mapping = _skeletonModel->getGeometry()->getMapping(); + if (mapping.value("name").isValid()) { + _fullAvatarModelName = mapping.value("name").toString(); + } + } - _skeletonModelLoaded = true; - } - QObject::disconnect(*skeletonConnection); - }); + initHeadBones(); + _skeletonModel->setCauterizeBoneSet(_headBoneSet); + _fstAnimGraphOverrideUrl = _skeletonModel->getGeometry()->getAnimGraphOverrideUrl(); + initAnimGraph(); + initFlowFromFST(); + _skeletonModelLoaded = true; + } + QObject::disconnect(*skeletonConnection); + }); + saveAvatarUrl(); emit skeletonChanged(); } bool isWearableEntity(const EntityItemPointer& entity) { - return entity->isVisible() && (entity->getParentID() == DependencyManager::get()->getSessionUUID() || - entity->getParentID() == AVATAR_SELF_ID); + return entity->isVisible() + && (entity->getParentID() == DependencyManager::get()->getSessionUUID() + || entity->getParentID() == AVATAR_SELF_ID); } void MyAvatar::removeWornAvatarEntity(const EntityItemID& entityID) { @@ -2415,7 +2445,9 @@ void MyAvatar::removeWornAvatarEntity(const EntityItemID& entityID) { void MyAvatar::clearWornAvatarEntities() { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); + _avatarEntitiesLock.withReadLock([&] { + avatarEntityIDs = _packedAvatarEntityData.keys(); + }); for (auto entityID : avatarEntityIDs) { removeWornAvatarEntity(entityID); } @@ -2441,7 +2473,9 @@ QVariantList MyAvatar::getAvatarEntitiesVariant() { EntityTreePointer entityTree = treeRenderer ? treeRenderer->getTree() : nullptr; if (entityTree) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); + _avatarEntitiesLock.withReadLock([&] { + avatarEntityIDs = _packedAvatarEntityData.keys(); + }); for (const auto& entityID : avatarEntityIDs) { auto entity = entityTree->findEntityByID(entityID); if (!entity) { @@ -2466,6 +2500,7 @@ QVariantList MyAvatar::getAvatarEntitiesVariant() { return avatarEntitiesData; } + void MyAvatar::resetFullAvatarURL() { auto lastAvatarURL = getFullAvatarURLFromPreferences(); auto lastAvatarName = getFullAvatarModelName(); @@ -2474,8 +2509,11 @@ void MyAvatar::resetFullAvatarURL() { } void MyAvatar::useFullAvatarURL(const QUrl& fullAvatarURL, const QString& modelName) { + if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "useFullAvatarURL", Q_ARG(const QUrl&, fullAvatarURL), Q_ARG(const QString&, modelName)); + BLOCKING_INVOKE_METHOD(this, "useFullAvatarURL", + Q_ARG(const QUrl&, fullAvatarURL), + Q_ARG(const QString&, modelName)); return; } @@ -2529,7 +2567,7 @@ controller::Pose MyAvatar::getControllerPoseInSensorFrame(controller::Action act if (iter != _controllerPoseMap.end()) { return iter->second; } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2538,7 +2576,7 @@ controller::Pose MyAvatar::getControllerPoseInWorldFrame(controller::Action acti if (pose.valid) { return pose.transform(getSensorToWorldMatrix()); } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2548,7 +2586,7 @@ controller::Pose MyAvatar::getControllerPoseInAvatarFrame(controller::Action act glm::mat4 invAvatarMatrix = glm::inverse(createMatFromQuatAndPos(getWorldOrientation(), getWorldPosition())); return pose.transform(invAvatarMatrix); } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2570,7 +2608,7 @@ void MyAvatar::updateMotors() { float verticalMotorTimescale; if (_characterController.getState() == CharacterController::State::Hover || - _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { + _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { horizontalMotorTimescale = FLYING_MOTOR_TIMESCALE; verticalMotorTimescale = FLYING_MOTOR_TIMESCALE; } else { @@ -2580,7 +2618,7 @@ void MyAvatar::updateMotors() { if (_motionBehaviors & AVATAR_MOTION_ACTION_MOTOR_ENABLED) { if (_characterController.getState() == CharacterController::State::Hover || - _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { + _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { motorRotation = getMyHead()->getHeadOrientation(); } else { // non-hovering = walking: follow camera twist about vertical but not lift @@ -2588,15 +2626,14 @@ void MyAvatar::updateMotors() { // however, we need to perform the decomposition in the avatar-frame // using the local UP axis and then transform back into world-frame glm::quat orientation = getWorldOrientation(); - glm::quat headOrientation = glm::inverse(orientation) * getMyHead()->getHeadOrientation(); // avatar-frame + glm::quat headOrientation = glm::inverse(orientation) * getMyHead()->getHeadOrientation(); // avatar-frame glm::quat liftRotation; swingTwistDecomposition(headOrientation, Vectors::UNIT_Y, liftRotation, motorRotation); motorRotation = orientation * motorRotation; } if (_isPushing || _isBraking || !_isBeingPushed) { - _characterController.addMotor(_actionMotorVelocity, motorRotation, horizontalMotorTimescale, - verticalMotorTimescale); + _characterController.addMotor(_actionMotorVelocity, motorRotation, horizontalMotorTimescale, verticalMotorTimescale); } else { // _isBeingPushed must be true --> disable action motor by giving it a long timescale, // otherwise it's attempt to "stand in in place" could defeat scripted motor/thrusts @@ -2616,8 +2653,7 @@ void MyAvatar::updateMotors() { _characterController.addMotor(_scriptedMotorVelocity, motorRotation, _scriptedMotorTimescale); } else { // dynamic mode - _characterController.addMotor(_scriptedMotorVelocity, motorRotation, horizontalMotorTimescale, - verticalMotorTimescale); + _characterController.addMotor(_scriptedMotorVelocity, motorRotation, horizontalMotorTimescale, verticalMotorTimescale); } } @@ -2722,7 +2758,8 @@ void MyAvatar::setScriptedMotorVelocity(const glm::vec3& velocity) { void MyAvatar::setScriptedMotorTimescale(float timescale) { // we clamp the timescale on the large side (instead of just the low side) to prevent // obnoxiously large values from introducing NaN into avatar's velocity - _scriptedMotorTimescale = glm::clamp(timescale, MIN_SCRIPTED_MOTOR_TIMESCALE, DEFAULT_SCRIPTED_MOTOR_TIMESCALE); + _scriptedMotorTimescale = glm::clamp(timescale, MIN_SCRIPTED_MOTOR_TIMESCALE, + DEFAULT_SCRIPTED_MOTOR_TIMESCALE); } void MyAvatar::setScriptedMotorFrame(QString frame) { @@ -2763,18 +2800,21 @@ SharedSoundPointer MyAvatar::getCollisionSound() { return _collisionSound; } -void MyAvatar::attach(const QString& modelURL, - const QString& jointName, - const glm::vec3& translation, - const glm::quat& rotation, - float scale, - bool isSoft, - bool allowDuplicates, - bool useSaved) { +void MyAvatar::attach(const QString& modelURL, const QString& jointName, + const glm::vec3& translation, const glm::quat& rotation, + float scale, bool isSoft, + bool allowDuplicates, bool useSaved) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "attach", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName), - Q_ARG(const glm::vec3&, translation), Q_ARG(const glm::quat&, rotation), Q_ARG(float, scale), - Q_ARG(bool, isSoft), Q_ARG(bool, allowDuplicates), Q_ARG(bool, useSaved)); + BLOCKING_INVOKE_METHOD(this, "attach", + Q_ARG(const QString&, modelURL), + Q_ARG(const QString&, jointName), + Q_ARG(const glm::vec3&, translation), + Q_ARG(const glm::quat&, rotation), + Q_ARG(float, scale), + Q_ARG(bool, isSoft), + Q_ARG(bool, allowDuplicates), + Q_ARG(bool, useSaved) + ); return; } AttachmentData data; @@ -2792,7 +2832,10 @@ void MyAvatar::attach(const QString& modelURL, void MyAvatar::detachOne(const QString& modelURL, const QString& jointName) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "detachOne", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName)); + BLOCKING_INVOKE_METHOD(this, "detachOne", + Q_ARG(const QString&, modelURL), + Q_ARG(const QString&, jointName) + ); return; } QUuid entityID; @@ -2804,7 +2847,10 @@ void MyAvatar::detachOne(const QString& modelURL, const QString& jointName) { void MyAvatar::detachAll(const QString& modelURL, const QString& jointName) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "detachAll", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName)); + BLOCKING_INVOKE_METHOD(this, "detachAll", + Q_ARG(const QString&, modelURL), + Q_ARG(const QString&, jointName) + ); return; } QUuid entityID; @@ -2816,7 +2862,8 @@ void MyAvatar::detachAll(const QString& modelURL, const QString& jointName) { void MyAvatar::setAttachmentData(const QVector& attachmentData) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "setAttachmentData", Q_ARG(const QVector&, attachmentData)); + BLOCKING_INVOKE_METHOD(this, "setAttachmentData", + Q_ARG(const QVector&, attachmentData)); return; } std::vector newEntitiesProperties; @@ -2839,10 +2886,12 @@ void MyAvatar::setAttachmentData(const QVector& attachmentData) emit attachmentsChanged(); } -QVector MyAvatar::getAttachmentData() const { +QVector MyAvatar::getAttachmentData() const { QVector attachmentData; QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); + _avatarEntitiesLock.withReadLock([&] { + avatarEntityIDs = _packedAvatarEntityData.keys(); + }); for (const auto& entityID : avatarEntityIDs) { auto properties = DependencyManager::get()->getEntityProperties(entityID); AttachmentData data = entityPropertiesToAttachmentData(properties); @@ -2861,7 +2910,8 @@ QVariantList MyAvatar::getAttachmentsVariant() const { void MyAvatar::setAttachmentsVariant(const QVariantList& variant) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "setAttachmentsVariant", Q_ARG(const QVariantList&, variant)); + BLOCKING_INVOKE_METHOD(this, "setAttachmentsVariant", + Q_ARG(const QVariantList&, variant)); return; } QVector newAttachments; @@ -2872,12 +2922,14 @@ void MyAvatar::setAttachmentsVariant(const QVariantList& variant) { newAttachments.append(attachment); } } - setAttachmentData(newAttachments); + setAttachmentData(newAttachments); } bool MyAvatar::findAvatarEntity(const QString& modelURL, const QString& jointName, QUuid& entityID) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); + _avatarEntitiesLock.withReadLock([&] { + avatarEntityIDs = _packedAvatarEntityData.keys(); + }); for (const auto& entityID : avatarEntityIDs) { auto props = DependencyManager::get()->getEntityProperties(entityID); if (props.getModelURL() == modelURL && @@ -2978,7 +3030,7 @@ void MyAvatar::setAnimGraphUrl(const QUrl& url) { emit animGraphUrlChanged(url); destroyAnimGraph(); - _skeletonModel->reset(); // Why is this necessary? Without this, we crash in the next render. + _skeletonModel->reset(); // Why is this necessary? Without this, we crash in the next render. _currentAnimGraphUrl.set(url); _skeletonModel->getRig().initAnimGraph(url); @@ -3011,16 +3063,18 @@ void MyAvatar::destroyAnimGraph() { } void MyAvatar::animGraphLoaded() { - _bodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. - updateSensorToWorldMatrix(); // Uses updated position/orientation and _bodySensorMatrix changes + _bodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + updateSensorToWorldMatrix(); // Uses updated position/orientation and _bodySensorMatrix changes _isAnimatingScale = true; _cauterizationNeedsUpdate = true; disconnect(&(_skeletonModel->getRig()), SIGNAL(onLoadComplete()), this, SLOT(animGraphLoaded())); } void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { + Avatar::postUpdate(deltaTime, scene); if (_enableDebugDrawDefaultPose || _enableDebugDrawAnimPose) { + auto animSkeleton = _skeletonModel->getRig().getAnimSkeleton(); // the rig is in the skeletonModel frame @@ -3028,8 +3082,7 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { if (_enableDebugDrawDefaultPose && animSkeleton) { glm::vec4 gray(0.2f, 0.2f, 0.2f, 0.2f); - AnimDebugDraw::getInstance().addAbsolutePoses("myAvatarDefaultPoses", animSkeleton, - _skeletonModel->getRig().getAbsoluteDefaultPoses(), xform, gray); + AnimDebugDraw::getInstance().addAbsolutePoses("myAvatarDefaultPoses", animSkeleton, _skeletonModel->getRig().getAbsoluteDefaultPoses(), xform, gray); } if (_enableDebugDrawAnimPose && animSkeleton) { @@ -3050,15 +3103,13 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { auto rightHandPose = getControllerPoseInWorldFrame(controller::Action::RIGHT_HAND); if (leftHandPose.isValid()) { - DebugDraw::getInstance().addMarker("leftHandController", leftHandPose.getRotation(), leftHandPose.getTranslation(), - glm::vec4(1)); + DebugDraw::getInstance().addMarker("leftHandController", leftHandPose.getRotation(), leftHandPose.getTranslation(), glm::vec4(1)); } else { DebugDraw::getInstance().removeMarker("leftHandController"); } if (rightHandPose.isValid()) { - DebugDraw::getInstance().addMarker("rightHandController", rightHandPose.getRotation(), - rightHandPose.getTranslation(), glm::vec4(1)); + DebugDraw::getInstance().addMarker("rightHandController", rightHandPose.getRotation(), rightHandPose.getTranslation(), glm::vec4(1)); } else { DebugDraw::getInstance().removeMarker("rightHandController"); } @@ -3075,9 +3126,14 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { AnimPose rigToWorldPose(glm::vec3(1.0f), getWorldOrientation() * Quaternions::Y_180, getWorldPosition()); const int NUM_DEBUG_COLORS = 8; const glm::vec4 DEBUG_COLORS[NUM_DEBUG_COLORS] = { - glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 1.0f), - glm::vec4(0.25f, 0.25f, 1.0f, 1.0f), glm::vec4(1.0f, 1.0f, 0.0f, 1.0f), glm::vec4(0.25f, 1.0f, 1.0f, 1.0f), - glm::vec4(1.0f, 0.25f, 1.0f, 1.0f), glm::vec4(1.0f, 0.65f, 0.0f, 1.0f) // Orange you glad I added this color? + glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), + glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), + glm::vec4(0.0f, 1.0f, 0.0f, 1.0f), + glm::vec4(0.25f, 0.25f, 1.0f, 1.0f), + glm::vec4(1.0f, 1.0f, 0.0f, 1.0f), + glm::vec4(0.25f, 1.0f, 1.0f, 1.0f), + glm::vec4(1.0f, 0.25f, 1.0f, 1.0f), + glm::vec4(1.0f, 0.65f, 0.0f, 1.0f) // Orange you glad I added this color? }; if (_skeletonModel && _skeletonModel->isLoaded()) { @@ -3088,7 +3144,7 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { AnimPose jointPose; rig.getAbsoluteJointPoseInRigFrame(i, jointPose); const AnimPose pose = rigToWorldPose * jointPose; - auto& multiSphere = _multiSphereShapes[i]; + auto &multiSphere = _multiSphereShapes[i]; auto debugLines = multiSphere.getDebugLines(); DebugDraw::getInstance().drawRays(debugLines, DEBUG_COLORS[i % NUM_DEBUG_COLORS], pose.trans(), pose.rot()); } @@ -3098,6 +3154,7 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { } void MyAvatar::preDisplaySide(const RenderArgs* renderArgs) { + // toggle using the cauterizedBones depending on where the camera is and the rendering pass type. const bool shouldDrawHead = shouldRenderHead(renderArgs); if (shouldDrawHead != _prevShouldDrawHead) { @@ -3142,7 +3199,7 @@ int MyAvatar::sendAvatarDataPacket(bool sendAll) { // Compute the next send window based on how much data we sent and what // data rate we're trying to max at. - milliseconds timeUntilNextSend{ bytesSent / maxDataRateBytesPerMilliseconds }; + milliseconds timeUntilNextSend { bytesSent / maxDataRateBytesPerMilliseconds }; _nextTraitsSendWindow += timeUntilNextSend; // Don't let the next send window lag behind if we're not sending a lot of data. @@ -3227,6 +3284,7 @@ void MyAvatar::setRotationThreshold(float angleRadians) { } void MyAvatar::updateOrientation(float deltaTime) { + // Smoothly rotate body with arrow keys float targetSpeed = getDriveKey(YAW) * _yawSpeed; if (targetSpeed != 0.0f) { @@ -3265,8 +3323,8 @@ void MyAvatar::updateOrientation(float deltaTime) { } // Use head/HMD roll to turn while flying, but not when standing still. - if (qApp->isHMDMode() && getCharacterController()->getState() == CharacterController::State::Hover && - _hmdRollControlEnabled && hasDriveInput()) { + if (qApp->isHMDMode() && getCharacterController()->getState() == CharacterController::State::Hover && _hmdRollControlEnabled && hasDriveInput()) { + // Turn with head roll. const float MIN_CONTROL_SPEED = 2.0f * getSensorToWorldScale(); // meters / sec const glm::vec3 characterForward = getWorldOrientation() * Vectors::UNIT_NEG_Z; @@ -3274,6 +3332,7 @@ void MyAvatar::updateOrientation(float deltaTime) { // only enable roll-turns if we are moving forward or backward at greater then MIN_CONTROL_SPEED if (fabsf(forwardSpeed) >= MIN_CONTROL_SPEED) { + float direction = forwardSpeed > 0.0f ? 1.0f : -1.0f; float rollAngle = glm::degrees(asinf(glm::dot(IDENTITY_UP, _hmdSensorOrientation * IDENTITY_RIGHT))); float rollSign = rollAngle < 0.0f ? -1.0f : 1.0f; @@ -3320,8 +3379,8 @@ void MyAvatar::updateOrientation(float deltaTime) { head->setBaseRoll(ROLL(euler)); } else { head->setBaseYaw(0.0f); - head->setBasePitch(getHead()->getBasePitch() + getDriveKey(PITCH) * _pitchSpeed * deltaTime + - getDriveKey(DELTA_PITCH) * _pitchSpeed / PITCH_SPEED_DEFAULT); + head->setBasePitch(getHead()->getBasePitch() + getDriveKey(PITCH) * _pitchSpeed * deltaTime + + getDriveKey(DELTA_PITCH) * _pitchSpeed / PITCH_SPEED_DEFAULT); head->setBaseRoll(0.0f); } } @@ -3331,15 +3390,20 @@ float MyAvatar::calculateGearedSpeed(const float driveKey) { float sign = (driveKey < 0.0f) ? -1.0f : 1.0f; if (absDriveKey > getDriveGear5()) { return sign * 1.0f; - } else if (absDriveKey > getDriveGear4()) { + } + else if (absDriveKey > getDriveGear4()) { return sign * 0.8f; - } else if (absDriveKey > getDriveGear3()) { + } + else if (absDriveKey > getDriveGear3()) { return sign * 0.6f; - } else if (absDriveKey > getDriveGear2()) { + } + else if (absDriveKey > getDriveGear2()) { return sign * 0.4f; - } else if (absDriveKey > getDriveGear1()) { + } + else if (absDriveKey > getDriveGear1()) { return sign * 0.2f; - } else { + } + else { return sign * 0.0f; } } @@ -3371,10 +3435,8 @@ glm::vec3 MyAvatar::scaleMotorSpeed(const glm::vec3 forward, const glm::vec3 rig case LocomotionControlsMode::CONTROLS_ANALOG: case LocomotionControlsMode::CONTROLS_ANALOG_PLUS: if (zSpeed || xSpeed) { - glm::vec3 scaledForward = getSensorToWorldScale() * calculateGearedSpeed(zSpeed) * _walkSpeedScalar * - ((zSpeed >= stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * forward; - glm::vec3 scaledRight = getSensorToWorldScale() * calculateGearedSpeed(xSpeed) * _walkSpeedScalar * - ((xSpeed > stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * right; + glm::vec3 scaledForward = getSensorToWorldScale() * calculateGearedSpeed(zSpeed) * _walkSpeedScalar * ((zSpeed >= stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * forward; + glm::vec3 scaledRight = getSensorToWorldScale() * calculateGearedSpeed(xSpeed) * _walkSpeedScalar * ((xSpeed > stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * right; direction = scaledForward + scaledRight; return direction; } else { @@ -3396,7 +3458,7 @@ glm::vec3 MyAvatar::scaleMotorSpeed(const glm::vec3 forward, const glm::vec3 rig } } -glm::vec3 MyAvatar::calculateScaledDirection() { +glm::vec3 MyAvatar::calculateScaledDirection(){ CharacterController::State state = _characterController.getState(); // compute action input @@ -3452,8 +3514,8 @@ glm::vec3 MyAvatar::calculateScaledDirection() { void MyAvatar::updateActionMotor(float deltaTime) { bool thrustIsPushing = (glm::length2(_thrust) > EPSILON); - bool scriptedMotorIsPushing = - (_motionBehaviors & AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED) && _scriptedMotorTimescale < MAX_CHARACTER_MOTOR_TIMESCALE; + bool scriptedMotorIsPushing = (_motionBehaviors & AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED) + && _scriptedMotorTimescale < MAX_CHARACTER_MOTOR_TIMESCALE; _isBeingPushed = thrustIsPushing || scriptedMotorIsPushing; if (_isPushing || _isBeingPushed) { // we don't want the motor to brake if a script is pushing the avatar around @@ -3483,7 +3545,7 @@ void MyAvatar::updateActionMotor(float deltaTime) { float motorSpeed = glm::length(_actionMotorVelocity); float finalMaxMotorSpeed = sensorToWorldScale * DEFAULT_AVATAR_MAX_FLYING_SPEED * _walkSpeedScalar; - float speedGrowthTimescale = 2.0f; + float speedGrowthTimescale = 2.0f; float speedIncreaseFactor = 1.8f * _walkSpeedScalar; motorSpeed *= 1.0f + glm::clamp(deltaTime / speedGrowthTimescale, 0.0f, 1.0f) * speedIncreaseFactor; const float maxBoostSpeed = sensorToWorldScale * MAX_BOOST_SPEED; @@ -3523,7 +3585,7 @@ void MyAvatar::updatePosition(float deltaTime) { float sensorToWorldScale2 = sensorToWorldScale * sensorToWorldScale; vec3 velocity = getWorldVelocity(); float speed2 = glm::length2(velocity); - const float MOVING_SPEED_THRESHOLD_SQUARED = 0.0001f; // 0.01 m/s + const float MOVING_SPEED_THRESHOLD_SQUARED = 0.0001f; // 0.01 m/s _moving = speed2 > sensorToWorldScale2 * MOVING_SPEED_THRESHOLD_SQUARED; if (_moving) { // scan for walkability @@ -3548,17 +3610,12 @@ void MyAvatar::updateViewBoom() { } } -void MyAvatar::updateCollisionSound(const glm::vec3& penetration, float deltaTime, float frequency) { +void MyAvatar::updateCollisionSound(const glm::vec3 &penetration, float deltaTime, float frequency) { // COLLISION SOUND API in Audio has been removed } -bool findAvatarAvatarPenetration(const glm::vec3 positionA, - float radiusA, - float heightA, - const glm::vec3 positionB, - float radiusB, - float heightB, - glm::vec3& penetration) { +bool findAvatarAvatarPenetration(const glm::vec3 positionA, float radiusA, float heightA, + const glm::vec3 positionB, float radiusB, float heightB, glm::vec3& penetration) { glm::vec3 positionBA = positionB - positionA; float xzDistance = sqrt(positionBA.x * positionBA.x + positionBA.z * positionBA.z); if (xzDistance < (radiusA + radiusB)) { @@ -3620,7 +3677,9 @@ void MyAvatar::setSessionUUID(const QUuid& sessionUUID) { EntityTreePointer entityTree = treeRenderer ? treeRenderer->getTree() : nullptr; if (entityTree) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); + _avatarEntitiesLock.withReadLock([&] { + avatarEntityIDs = _packedAvatarEntityData.keys(); + }); bool sendPackets = !DependencyManager::get()->getSessionUUID().isNull(); EntityEditPacketSender* packetSender = qApp->getEntityEditPacketSender(); entityTree->withWriteLock([&] { @@ -3764,18 +3823,16 @@ void MyAvatar::goToLocation(const QVariant& propertiesVar) { } void MyAvatar::goToFeetLocation(const glm::vec3& newPosition, - bool hasOrientation, - const glm::quat& newOrientation, + bool hasOrientation, const glm::quat& newOrientation, bool shouldFaceLocation) { _goToFeetAjustment = true; goToLocation(newPosition, hasOrientation, newOrientation, shouldFaceLocation); } void MyAvatar::goToLocation(const glm::vec3& newPosition, - bool hasOrientation, - const glm::quat& newOrientation, - bool shouldFaceLocation, - bool withSafeLanding) { + bool hasOrientation, const glm::quat& newOrientation, + bool shouldFaceLocation, bool withSafeLanding) { + // Most cases of going to a place or user go through this now. Some possible improvements to think about in the future: // - It would be nice if this used the same teleport steps and smoothing as in the teleport.js script, as long as it // still worked if the target is in the air. @@ -3789,16 +3846,16 @@ void MyAvatar::goToLocation(const glm::vec3& newPosition, // compute the position (e.g., so that if I'm on stage, going to me would compute an available seat in the audience rather than // being in my face on-stage). Note that this could work for going to an entity as well as to a person. - qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - moving to " << newPosition.x << ", " << newPosition.y << ", " - << newPosition.z; + qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - moving to " << newPosition.x << ", " + << newPosition.y << ", " << newPosition.z; _goToPending = true; _goToPosition = newPosition; _goToSafe = withSafeLanding; _goToOrientation = getWorldOrientation(); if (hasOrientation) { - qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - new orientation is " << newOrientation.x << ", " - << newOrientation.y << ", " << newOrientation.z << ", " << newOrientation.w; + qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - new orientation is " + << newOrientation.x << ", " << newOrientation.y << ", " << newOrientation.z << ", " << newOrientation.w; // orient the user to face the target glm::quat quatOrientation = cancelOutRollAndPitch(newOrientation); @@ -3817,7 +3874,7 @@ void MyAvatar::goToLocation(const glm::vec3& newPosition, emit transformChanged(); } -void MyAvatar::goToLocationAndEnableCollisions(const glm::vec3& position) { // See use case in safeLanding. +void MyAvatar::goToLocationAndEnableCollisions(const glm::vec3& position) { // See use case in safeLanding. goToLocation(position); QMetaObject::invokeMethod(this, "setCollisionsEnabled", Qt::QueuedConnection, Q_ARG(bool, true)); } @@ -3843,29 +3900,29 @@ bool MyAvatar::safeLanding(const glm::vec3& position) { } if (!getCollisionsEnabled()) { goToLocation(better); // recurses on next update - } else { // If you try to go while stuck, physics will keep you stuck. + } else { // If you try to go while stuck, physics will keep you stuck. setCollisionsEnabled(false); // Don't goToLocation just yet. Yield so that physics can act on the above. - QMetaObject::invokeMethod(this, "goToLocationAndEnableCollisions", - Qt::QueuedConnection, // The equivalent of javascript nextTick - Q_ARG(glm::vec3, better)); - } - return true; + QMetaObject::invokeMethod(this, "goToLocationAndEnableCollisions", Qt::QueuedConnection, // The equivalent of javascript nextTick + Q_ARG(glm::vec3, better)); + } + return true; } // If position is not reliably safe from being stuck by physics, answer true and place a candidate better position in betterPositionOut. bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& betterPositionOut) { + // We begin with utilities and tests. The Algorithm in four parts is below. // NOTE: we use estimated avatar height here instead of the bullet capsule halfHeight, because // the domain avatar height limiting might not have taken effect yet on the actual bullet shape. auto halfHeight = 0.5f * getHeight(); if (halfHeight == 0) { - return false; // zero height avatar + return false; // zero height avatar } auto entityTree = DependencyManager::get()->getTree(); if (!entityTree) { - return false; // no entity tree + return false; // no entity tree } // More utilities. const auto capsuleCenter = positionIn; @@ -3877,26 +3934,21 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette betterPositionOut = upperIntersection + (up * halfHeight); return true; }; - auto findIntersection = [&](const glm::vec3& startPointIn, const glm::vec3& directionIn, glm::vec3& intersectionOut, - EntityItemID& entityIdOut, glm::vec3& normalOut) { + auto findIntersection = [&](const glm::vec3& startPointIn, const glm::vec3& directionIn, glm::vec3& intersectionOut, EntityItemID& entityIdOut, glm::vec3& normalOut) { OctreeElementPointer element; float distance; BoxFace face; - const auto lockType = Octree::Lock; // Should we refactor to take a lock just once? + const auto lockType = Octree::Lock; // Should we refactor to take a lock just once? bool* accurateResult = NULL; // This isn't quite what we really want here. findRayIntersection always works on mesh, skipping entirely based on collidable. // What we really want is to use the collision hull! // See https://highfidelity.fogbugz.com/f/cases/5003/findRayIntersection-has-option-to-use-collidableOnly-but-doesn-t-actually-use-colliders QVariantMap extraInfo; - EntityItemID entityID = - entityTree->evalRayIntersection(startPointIn, directionIn, include, ignore, - PickFilter(PickFilter::getBitMask(PickFilter::FlagBit::COLLIDABLE) | - PickFilter::getBitMask(PickFilter::FlagBit::PRECISE) | - PickFilter::getBitMask(PickFilter::FlagBit::DOMAIN_ENTITIES) | - PickFilter::getBitMask( - PickFilter::FlagBit::AVATAR_ENTITIES)), // exclude Local entities - element, distance, face, normalOut, extraInfo, lockType, accurateResult); + EntityItemID entityID = entityTree->evalRayIntersection(startPointIn, directionIn, include, ignore, + PickFilter(PickFilter::getBitMask(PickFilter::FlagBit::COLLIDABLE) | PickFilter::getBitMask(PickFilter::FlagBit::PRECISE) + | PickFilter::getBitMask(PickFilter::FlagBit::DOMAIN_ENTITIES) | PickFilter::getBitMask(PickFilter::FlagBit::AVATAR_ENTITIES)), // exclude Local entities + element, distance, face, normalOut, extraInfo, lockType, accurateResult); if (entityID.isNull()) { return false; } @@ -3911,12 +3963,12 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette // We currently believe that physics will reliably push us out if our feet are embedded, // as long as our capsule center is out and there's room above us. Here we have those // conditions, so no need to check our feet below. - return false; // nothing above + return false; // nothing above } if (!findIntersection(capsuleCenter, down, lowerIntersection, lowerId, lowerNormal)) { // Our head may be embedded, but our center is out and there's room below. See corresponding comment above. - return false; // nothing below + return false; // nothing below } // See if we have room between entities above and below, but that we are not contained. @@ -3924,8 +3976,7 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette // I.e., we are in a clearing between two objects. if (isDown(upperNormal) && isUp(lowerNormal)) { auto spaceBetween = glm::distance(upperIntersection, lowerIntersection); - const float halfHeightFactor = - 2.25f; // Until case 5003 is fixed (and maybe after?), we need a fudge factor. Also account for content modelers not being precise. + const float halfHeightFactor = 2.25f; // Until case 5003 is fixed (and maybe after?), we need a fudge factor. Also account for content modelers not being precise. if (spaceBetween > (halfHeightFactor * halfHeight)) { // There is room for us to fit in that clearing. If there wasn't, physics would oscilate us between the objects above and below. // We're now going to iterate upwards through successive upperIntersections, testing to see if we're contained within the top surface of some entity. @@ -3937,7 +3988,7 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette ignore.push_back(upperId); if (!findIntersection(upperIntersection, up, upperIntersection, upperId, upperNormal)) { // We're not inside an entity, and from the nested tests, we have room between what is above and below. So position is good! - return false; // enough room + return false; // enough room } if (isUp(upperNormal)) { // This new intersection is the top surface of an entity that we have not yet seen, which means we're contained within it. @@ -3952,18 +4003,19 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette } } - include.push_back(upperId); // We're now looking for the intersection from above onto this entity. + include.push_back(upperId); // We're now looking for the intersection from above onto this entity. const float big = (float)TREE_SCALE; const auto skyHigh = up * big; auto fromAbove = capsuleCenter + skyHigh; if (!findIntersection(fromAbove, down, upperIntersection, upperId, upperNormal)) { - return false; // Unable to find a landing + return false; // Unable to find a landing } // Our arbitrary rule is to always go up. There's no need to look down or sideways for a "closer" safe candidate. return mustMove(); } void MyAvatar::updateMotionBehaviorFromMenu() { + if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "updateMotionBehaviorFromMenu"); return; @@ -4047,7 +4099,7 @@ int MyAvatar::getMovementReference() { return _movementReference; } -void MyAvatar::setControlSchemeIndex(int index) { +void MyAvatar::setControlSchemeIndex(int index){ if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setControlSchemeIndex", Q_ARG(int, index)); return; @@ -4065,8 +4117,7 @@ void MyAvatar::setDriveGear1(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear1", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) - return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; _driveGear1 = (shiftPoint < _driveGear2) ? shiftPoint : _driveGear1; } @@ -4087,8 +4138,7 @@ void MyAvatar::setDriveGear2(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear2", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) - return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; _driveGear2 = (shiftPoint < _driveGear3 && shiftPoint >= _driveGear1) ? shiftPoint : _driveGear2; } @@ -4109,8 +4159,7 @@ void MyAvatar::setDriveGear3(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear3", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) - return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; _driveGear3 = (shiftPoint < _driveGear4 && shiftPoint >= _driveGear2) ? shiftPoint : _driveGear3; } @@ -4131,8 +4180,7 @@ void MyAvatar::setDriveGear4(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear4", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) - return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; _driveGear4 = (shiftPoint < _driveGear5 && shiftPoint >= _driveGear3) ? shiftPoint : _driveGear4; } @@ -4153,8 +4201,7 @@ void MyAvatar::setDriveGear5(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear5", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) - return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; _driveGear5 = (shiftPoint > _driveGear4) ? shiftPoint : _driveGear5; } @@ -4180,6 +4227,7 @@ float MyAvatar::getAvatarScale() { } void MyAvatar::setAvatarScale(float val) { + if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setAvatarScale", Q_ARG(float, val)); return; @@ -4189,6 +4237,7 @@ void MyAvatar::setAvatarScale(float val) { } void MyAvatar::setCollisionsEnabled(bool enabled) { + if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setCollisionsEnabled", Q_ARG(bool, enabled)); return; @@ -4204,6 +4253,7 @@ bool MyAvatar::getCollisionsEnabled() { } void MyAvatar::setOtherAvatarsCollisionsEnabled(bool enabled) { + if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setOtherAvatarsCollisionsEnabled", Q_ARG(bool, enabled)); return; @@ -4359,7 +4409,7 @@ glm::mat4 MyAvatar::deriveBodyFromHMDSensor() const { // AJT: TODO: can remove this Y_180, if we remove the higher level one. glm::vec3 headToNeck = headOrientation * Quaternions::Y_180 * (localNeck - localHead); - glm::vec3 neckToRoot = headOrientationYawOnly * Quaternions::Y_180 * -localNeck; + glm::vec3 neckToRoot = headOrientationYawOnly * Quaternions::Y_180 * -localNeck; float invSensorToWorldScale = getUserEyeHeight() / getEyeHeight(); glm::vec3 bodyPos = headPosition + invSensorToWorldScale * (headToNeck + neckToRoot); @@ -4395,8 +4445,7 @@ glm::mat4 MyAvatar::getSpine2RotationRigSpace() const { spine2UpRigSpace = glm::vec3(0.0f, 1.0f, 0.0f); } generateBasisVectors(spine2UpRigSpace, spine2FwdRigSpace, u, v, w); - glm::mat4 spine2RigSpace(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), - glm::vec4(glm::vec3(0.0f, 0.0f, 0.0f), 1.0f)); + glm::mat4 spine2RigSpace(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), glm::vec4(glm::vec3(0.0f, 0.0f, 0.0f), 1.0f)); return spine2RigSpace; } @@ -4453,7 +4502,7 @@ glm::vec3 MyAvatar::computeCounterBalance() { QString name; float weight; glm::vec3 position; - JointMass(){}; + JointMass() {}; JointMass(QString n, float w, glm::vec3 p) { name = n; weight = w; @@ -4474,14 +4523,12 @@ glm::vec3 MyAvatar::computeCounterBalance() { tposeHead = getAbsoluteDefaultJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgHeadMass.name)); } if (_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name) != -1) { - cgLeftHandMass.position = - getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name)); + cgLeftHandMass.position = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name)); } else { cgLeftHandMass.position = DEFAULT_AVATAR_LEFTHAND_POS; } if (_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name) != -1) { - cgRightHandMass.position = - getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name)); + cgRightHandMass.position = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name)); } else { cgRightHandMass.position = DEFAULT_AVATAR_RIGHTHAND_POS; } @@ -4493,8 +4540,7 @@ glm::vec3 MyAvatar::computeCounterBalance() { } // find the current center of gravity position based on head and hand moments - glm::vec3 sumOfMoments = (cgHeadMass.weight * cgHeadMass.position) + (cgLeftHandMass.weight * cgLeftHandMass.position) + - (cgRightHandMass.weight * cgRightHandMass.position); + glm::vec3 sumOfMoments = (cgHeadMass.weight * cgHeadMass.position) + (cgLeftHandMass.weight * cgLeftHandMass.position) + (cgRightHandMass.weight * cgRightHandMass.position); float totalMass = cgHeadMass.weight + cgLeftHandMass.weight + cgRightHandMass.weight; glm::vec3 currentCg = (1.0f / totalMass) * sumOfMoments; @@ -4534,6 +4580,7 @@ glm::vec3 MyAvatar::computeCounterBalance() { // headOrientation, headPosition and hipsPosition are in avatar space // returns the matrix of the hips in Avatar space static glm::mat4 computeNewHipsMatrix(glm::quat headOrientation, glm::vec3 headPosition, glm::vec3 hipsPosition) { + glm::quat bodyOrientation = computeBodyFacingFromHead(headOrientation, Vectors::UNIT_Y); const float MIX_RATIO = 0.3f; @@ -4543,7 +4590,10 @@ static glm::mat4 computeNewHipsMatrix(glm::quat headOrientation, glm::vec3 headP glm::vec3 spineVec = headPosition - hipsPosition; glm::vec3 u, v, w; generateBasisVectors(glm::normalize(spineVec), hipsFacing, u, v, w); - return glm::mat4(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), glm::vec4(hipsPosition, 1.0f)); + return glm::mat4(glm::vec4(w, 0.0f), + glm::vec4(u, 0.0f), + glm::vec4(v, 0.0f), + glm::vec4(hipsPosition, 1.0f)); } static void drawBaseOfSupport(float baseOfSupportScale, float footLocal, glm::mat4 avatarToWorld) { @@ -4584,8 +4634,7 @@ glm::mat4 MyAvatar::deriveBodyUsingCgModel() { if (_enableDebugDrawBaseOfSupport) { float scaleBaseOfSupport = getUserEyeHeight() / DEFAULT_AVATAR_EYE_HEIGHT; - glm::vec3 rightFootPositionLocal = - getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint("RightFoot")); + glm::vec3 rightFootPositionLocal = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint("RightFoot")); drawBaseOfSupport(scaleBaseOfSupport, rightFootPositionLocal.y, avatarToWorldMat); } @@ -4593,8 +4642,7 @@ glm::mat4 MyAvatar::deriveBodyUsingCgModel() { glm::vec3 cgHipsPosition = computeCounterBalance(); // find the new hips rotation using the new head-hips axis as the up axis - glm::mat4 avatarHipsMat = - computeNewHipsMatrix(glmExtractRotation(avatarHeadMat), extractTranslation(avatarHeadMat), cgHipsPosition); + glm::mat4 avatarHipsMat = computeNewHipsMatrix(glmExtractRotation(avatarHeadMat), extractTranslation(avatarHeadMat), cgHipsPosition); // convert hips from avatar to sensor space // The Y_180 is to convert from z forward to -z forward. @@ -4618,7 +4666,7 @@ static bool withinBaseOfSupport(const controller::Pose& head) { bool withinFrontBase = isInsideLine(userScale * frontLeft, userScale * frontRight, head.getTranslation()); bool withinBackBase = isInsideLine(userScale * backRight, userScale * backLeft, head.getTranslation()); bool withinLateralBase = (isInsideLine(userScale * frontRight, userScale * backRight, head.getTranslation()) && - isInsideLine(userScale * backLeft, userScale * frontLeft, head.getTranslation())); + isInsideLine(userScale * backLeft, userScale * frontLeft, head.getTranslation())); isWithinSupport = (withinFrontBase && withinBackBase && withinLateralBase); } return isWithinSupport; @@ -4652,8 +4700,7 @@ float MyAvatar::computeStandingHeightMode(const controller::Pose& head) { float modeInMeters = getCurrentStandingHeight(); if (head.isValid()) { std::map freq; - for (auto recentModeReadingsIterator = _recentModeReadings.begin(); - recentModeReadingsIterator != _recentModeReadings.end(); ++recentModeReadingsIterator) { + for(auto recentModeReadingsIterator = _recentModeReadings.begin(); recentModeReadingsIterator != _recentModeReadings.end(); ++recentModeReadingsIterator) { freq[*recentModeReadingsIterator] += 1; if (freq[*recentModeReadingsIterator] > greatestFrequency) { greatestFrequency = freq[*recentModeReadingsIterator]; @@ -4666,23 +4713,21 @@ float MyAvatar::computeStandingHeightMode(const controller::Pose& head) { // if not greater check for a reset if (getResetMode() && getControllerPoseInAvatarFrame(controller::Action::HEAD).isValid()) { setResetMode(false); - float resetModeInCentimeters = - glm::floor((head.getTranslation().y - MODE_CORRECTION_FACTOR) * CENTIMETERS_PER_METER); + float resetModeInCentimeters = glm::floor((head.getTranslation().y - MODE_CORRECTION_FACTOR)*CENTIMETERS_PER_METER); modeInMeters = (resetModeInCentimeters / CENTIMETERS_PER_METER); _recentModeReadings.clear(); } else { // if not greater and no reset, keep the mode as it is modeInMeters = getCurrentStandingHeight(); + } } } return modeInMeters; } -static bool handDirectionMatchesHeadDirection(const controller::Pose& leftHand, - const controller::Pose& rightHand, - const controller::Pose& head) { +static bool handDirectionMatchesHeadDirection(const controller::Pose& leftHand, const controller::Pose& rightHand, const controller::Pose& head) { const float VELOCITY_EPSILON = 0.02f; bool leftHandDirectionMatchesHead = true; bool rightHandDirectionMatchesHead = true; @@ -4720,7 +4765,7 @@ static bool handAngularVelocityBelowThreshold(const controller::Pose& leftHand, rightHandXZAngularVelocity = glm::length(xzRightHandAngularVelocity); } return ((leftHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD) && - (rightHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD)); + (rightHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD)); } static bool headVelocityGreaterThanThreshold(const controller::Pose& head) { @@ -4743,8 +4788,7 @@ static bool isHeadLevel(const controller::Pose& head, const glm::quat& averageHe glm::vec3 currentHeadEulers = glm::degrees(safeEulerAngles(head.getRotation())); diffFromAverageEulers = averageHeadEulers - currentHeadEulers; } - return ((fabs(diffFromAverageEulers.x) < DEFAULT_HEAD_PITCH_STEPPING_TOLERANCE) && - (fabs(diffFromAverageEulers.z) < DEFAULT_HEAD_ROLL_STEPPING_TOLERANCE)); + return ((fabs(diffFromAverageEulers.x) < DEFAULT_HEAD_PITCH_STEPPING_TOLERANCE) && (fabs(diffFromAverageEulers.z) < DEFAULT_HEAD_ROLL_STEPPING_TOLERANCE)); } float MyAvatar::getUserHeight() const { @@ -4794,6 +4838,7 @@ float MyAvatar::getWalkSpeed() const { } else { return _defaultWalkSpeed.get(); } + } float MyAvatar::getWalkBackwardSpeed() const { @@ -4810,6 +4855,7 @@ float MyAvatar::getWalkBackwardSpeed() const { } else { return _defaultWalkBackwardSpeed.get(); } + } bool MyAvatar::isReadyForPhysics() const { @@ -4819,7 +4865,8 @@ bool MyAvatar::isReadyForPhysics() const { void MyAvatar::setSprintMode(bool sprint) { if (qApp->isHMDMode()) { _walkSpeedScalar = sprint ? AVATAR_DESKTOP_SPRINT_SPEED_SCALAR : AVATAR_WALK_SPEED_SCALAR; - } else { + } + else { _walkSpeedScalar = sprint ? AVATAR_HMD_SPRINT_SPEED_SCALAR : AVATAR_WALK_SPEED_SCALAR; } } @@ -4843,6 +4890,7 @@ void MyAvatar::setIsInSittingState(bool isSitting) { } void MyAvatar::setUserRecenterModel(MyAvatar::SitStandModelType modelName) { + _userRecenterModel.set(modelName); switch (modelName) { @@ -4918,7 +4966,7 @@ void MyAvatar::setWalkBackwardSpeed(float value) { changed = false; break; } - + if (changed && prevVal != value) { emit walkBackwardSpeedChanged(value); } @@ -5088,6 +5136,7 @@ void driveKeysFromScriptValue(const QScriptValue& object, MyAvatar::DriveKeys& d driveKeys = static_cast(object.toUInt16()); } + void MyAvatar::lateUpdatePalms() { Avatar::updatePalms(); } @@ -5145,17 +5194,13 @@ void MyAvatar::FollowHelper::decrementTimeRemaining(float dt) { } } -bool MyAvatar::FollowHelper::shouldActivateRotation(const MyAvatar& myAvatar, - const glm::mat4& desiredBodyMatrix, - const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateRotation(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { const float FOLLOW_ROTATION_THRESHOLD = cosf(myAvatar.getRotationThreshold()); glm::vec2 bodyFacing = getFacingDir2D(currentBodyMatrix); return glm::dot(-myAvatar.getHeadControllerFacingMovingAverage(), bodyFacing) < FOLLOW_ROTATION_THRESHOLD; } -bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, - const glm::mat4& desiredBodyMatrix, - const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { // -z axis of currentBodyMatrix in world space. glm::vec3 forward = glm::normalize(glm::vec3(-currentBodyMatrix[0][2], -currentBodyMatrix[1][2], -currentBodyMatrix[2][2])); // x axis of currentBodyMatrix in world space. @@ -5186,6 +5231,7 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, } bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) const { + // get the current readings controller::Pose currentHeadPose = myAvatar.getControllerPoseInAvatarFrame(controller::Action::HEAD); controller::Pose currentLeftHandPose = myAvatar.getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND); @@ -5198,7 +5244,8 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons if (myAvatar.getIsInWalkingState()) { stepDetected = true; } else { - if (!withinBaseOfSupport(currentHeadPose) && headAngularVelocityBelowThreshold(currentHeadPose) && + if (!withinBaseOfSupport(currentHeadPose) && + headAngularVelocityBelowThreshold(currentHeadPose) && isWithinThresholdHeightMode(currentHeadSensorPose, myAvatar.getCurrentStandingHeight(), myScale) && handDirectionMatchesHeadDirection(currentLeftHandPose, currentRightHandPose, currentHeadPose) && handAngularVelocityBelowThreshold(currentLeftHandPose, currentRightHandPose) && @@ -5210,15 +5257,13 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons myAvatar.setIsInWalkingState(true); } } else { - glm::vec3 defaultHipsPosition = - myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Hips")); - glm::vec3 defaultHeadPosition = - myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Head")); + glm::vec3 defaultHipsPosition = myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Hips")); + glm::vec3 defaultHeadPosition = myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Head")); glm::vec3 currentHeadPosition = currentHeadPose.getTranslation(); float anatomicalHeadToHipsDistance = glm::length(defaultHeadPosition - defaultHipsPosition); - if (!isActive(Horizontal) && (!isActive(Vertical)) && - (glm::length(currentHeadPosition - defaultHipsPosition) > - (anatomicalHeadToHipsDistance + (DEFAULT_AVATAR_SPINE_STRETCH_LIMIT * anatomicalHeadToHipsDistance)))) { + if (!isActive(Horizontal) && + (!isActive(Vertical)) && + (glm::length(currentHeadPosition - defaultHipsPosition) > (anatomicalHeadToHipsDistance + (DEFAULT_AVATAR_SPINE_STRETCH_LIMIT * anatomicalHeadToHipsDistance)))) { myAvatar.setResetMode(true); stepDetected = true; if (glm::length(currentHeadPose.velocity) > DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { @@ -5230,9 +5275,7 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons return stepDetected; } -bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, - const glm::mat4& desiredBodyMatrix, - const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { const float CYLINDER_TOP = 2.0f; const float CYLINDER_BOTTOM = -1.5f; const float SITTING_BOTTOM = -0.02f; @@ -5263,11 +5306,11 @@ bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, return returnValue; } -void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, - const glm::mat4& desiredBodyMatrix, - const glm::mat4& currentBodyMatrix, - bool hasDriveInput) { - if (myAvatar.getHMDLeanRecenterEnabled() && qApp->getCamera().getMode() != CAMERA_MODE_MIRROR) { +void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, + const glm::mat4& currentBodyMatrix, bool hasDriveInput) { + + if (myAvatar.getHMDLeanRecenterEnabled() && + qApp->getCamera().getMode() != CAMERA_MODE_MIRROR) { if (!isActive(Rotation) && (shouldActivateRotation(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { activate(Rotation); myAvatar.setHeadControllerFacingMovingAverage(myAvatar.getHeadControllerFacing()); @@ -5282,8 +5325,7 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, } } else { // center of gravity model is not enabled - if (!isActive(Horizontal) && - (shouldActivateHorizontal(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { + if (!isActive(Horizontal) && (shouldActivateHorizontal(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { activate(Horizontal); if (myAvatar.getEnableStepResetRotation() && !myAvatar.getIsInSittingState()) { activate(Rotation); @@ -5320,7 +5362,7 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, glm::quat currentHipsLocal = myAvatar.getAbsoluteJointRotationInObjectFrame(myAvatar.getJointIndex("Hips")); const glm::quat hipsinWorldSpace = followWorldPose.rot() * (Quaternions::Y_180 * (currentHipsLocal)); - const glm::vec3 avatarUpWorld = glm::normalize(followWorldPose.rot() * (Vectors::UP)); + const glm::vec3 avatarUpWorld = glm::normalize(followWorldPose.rot()*(Vectors::UP)); glm::quat resultingSwingInWorld; glm::quat resultingTwistInWorld; swingTwistDecomposition(hipsinWorldSpace, avatarUpWorld, resultingSwingInWorld, resultingTwistInWorld); @@ -5329,8 +5371,8 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, followWorldPose.scale() = glm::vec3(1.0f); if (isActive(Rotation)) { - //use the hmd reading for the hips follow - followWorldPose.rot() = glmExtractRotation(desiredWorldMatrix); + //use the hmd reading for the hips follow + followWorldPose.rot() = glmExtractRotation(desiredWorldMatrix); } if (isActive(Horizontal)) { glm::vec3 desiredTranslation = extractTranslation(desiredWorldMatrix); @@ -5358,8 +5400,7 @@ glm::mat4 MyAvatar::FollowHelper::postPhysicsUpdate(MyAvatar& myAvatar, const gl glm::mat4 worldToSensorMatrix = glm::inverse(sensorToWorldMatrix); glm::vec3 sensorLinearDisplacement = transformVectorFast(worldToSensorMatrix, worldLinearDisplacement); - glm::quat sensorAngularDisplacement = - glmExtractRotation(worldToSensorMatrix) * worldAngularDisplacement * glmExtractRotation(sensorToWorldMatrix); + glm::quat sensorAngularDisplacement = glmExtractRotation(worldToSensorMatrix) * worldAngularDisplacement * glmExtractRotation(sensorToWorldMatrix); glm::mat4 newBodyMat = createMatFromQuatAndPos(sensorAngularDisplacement * glmExtractRotation(currentBodyMatrix), sensorLinearDisplacement + extractTranslation(currentBodyMatrix)); @@ -5427,8 +5468,7 @@ bool MyAvatar::didTeleport() { } bool MyAvatar::hasDriveInput() const { - return fabsf(getDriveKey(TRANSLATE_X)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Y)) > 0.0f || - fabsf(getDriveKey(TRANSLATE_Z)) > 0.0f; + return fabsf(getDriveKey(TRANSLATE_X)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Y)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Z)) > 0.0f; } void MyAvatar::setAway(bool value) { @@ -5444,6 +5484,7 @@ void MyAvatar::setAway(bool value) { // Specificly, if we are rendering using a third person camera. We would like to render the hand controllers in front of the camera, // not in front of the avatar. glm::mat4 MyAvatar::computeCameraRelativeHandControllerMatrix(const glm::mat4& controllerSensorMatrix) const { + // Fetch the current camera transform. glm::mat4 cameraWorldMatrix = qApp->getCamera().getTransform(); if (qApp->getCamera().getMode() == CAMERA_MODE_MIRROR) { @@ -5470,7 +5511,7 @@ glm::mat4 MyAvatar::computeCameraRelativeHandControllerMatrix(const glm::mat4& c glm::quat MyAvatar::getAbsoluteJointRotationInObjectFrame(int index) const { if (index < 0) { - index += numeric_limits::max() + 1; // 65536 + index += numeric_limits::max() + 1; // 65536 } switch (index) { @@ -5499,13 +5540,15 @@ glm::quat MyAvatar::getAbsoluteJointRotationInObjectFrame(int index) const { glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix(); return glmExtractRotation(invAvatarMat * qApp->getCamera().getTransform()); } - default: { return Avatar::getAbsoluteJointRotationInObjectFrame(index); } + default: { + return Avatar::getAbsoluteJointRotationInObjectFrame(index); + } } } glm::vec3 MyAvatar::getAbsoluteJointTranslationInObjectFrame(int index) const { if (index < 0) { - index += numeric_limits::max() + 1; // 65536 + index += numeric_limits::max() + 1; // 65536 } switch (index) { @@ -5534,7 +5577,9 @@ glm::vec3 MyAvatar::getAbsoluteJointTranslationInObjectFrame(int index) const { glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix(); return extractTranslation(invAvatarMat * qApp->getCamera().getTransform()); } - default: { return Avatar::getAbsoluteJointTranslationInObjectFrame(index); } + default: { + return Avatar::getAbsoluteJointTranslationInObjectFrame(index); + } } } @@ -5543,15 +5588,12 @@ glm::mat4 MyAvatar::getCenterEyeCalibrationMat() const { int rightEyeIndex = _skeletonModel->getRig().indexOfJoint("RightEye"); int leftEyeIndex = _skeletonModel->getRig().indexOfJoint("LeftEye"); if (rightEyeIndex >= 0 && leftEyeIndex >= 0) { - auto centerEyePos = (getAbsoluteDefaultJointTranslationInObjectFrame(rightEyeIndex) + - getAbsoluteDefaultJointTranslationInObjectFrame(leftEyeIndex)) * - 0.5f; + auto centerEyePos = (getAbsoluteDefaultJointTranslationInObjectFrame(rightEyeIndex) + getAbsoluteDefaultJointTranslationInObjectFrame(leftEyeIndex)) * 0.5f; auto centerEyeRot = Quaternions::Y_180; return createMatFromQuatAndPos(centerEyeRot, centerEyePos / getSensorToWorldScale()); } else { glm::mat4 headMat = getHeadCalibrationMat(); - return createMatFromQuatAndPos(DEFAULT_AVATAR_MIDDLE_EYE_ROT, - extractTranslation(headMat) + DEFAULT_AVATAR_HEAD_TO_MIDDLE_EYE_OFFSET); + return createMatFromQuatAndPos(DEFAULT_AVATAR_MIDDLE_EYE_ROT, extractTranslation(headMat) + DEFAULT_AVATAR_HEAD_TO_MIDDLE_EYE_OFFSET); } } @@ -5720,6 +5762,7 @@ void MyAvatar::updateHoldActions(const AnimPose& prePhysicsPose, const AnimPose& if (entityTree) { // lateAvatarUpdate will modify entity position & orientation, so we need an entity write lock entityTree->withWriteLock([&] { + // to prevent actions from adding or removing themselves from the _holdActions vector // while we are iterating, we need to enter a critical section. std::lock_guard guard(_holdActionsMutex); @@ -5755,24 +5798,26 @@ SpatialParentTree* MyAvatar::getParentTree() const { return entityTree.get(); } -const QUuid MyAvatar::grab(const QUuid& targetID, - int parentJointIndex, - glm::vec3 positionalOffset, - glm::quat rotationalOffset) { +const QUuid MyAvatar::grab(const QUuid& targetID, int parentJointIndex, + glm::vec3 positionalOffset, glm::quat rotationalOffset) { auto grabID = QUuid::createUuid(); // create a temporary grab object to get grabData QString hand = "none"; - if (parentJointIndex == CONTROLLER_RIGHTHAND_INDEX || parentJointIndex == CAMERA_RELATIVE_CONTROLLER_RIGHTHAND_INDEX || - parentJointIndex == FARGRAB_RIGHTHAND_INDEX || parentJointIndex == getJointIndex("RightHand")) { + if (parentJointIndex == CONTROLLER_RIGHTHAND_INDEX || + parentJointIndex == CAMERA_RELATIVE_CONTROLLER_RIGHTHAND_INDEX || + parentJointIndex == FARGRAB_RIGHTHAND_INDEX || + parentJointIndex == getJointIndex("RightHand")) { hand = "right"; - } else if (parentJointIndex == CONTROLLER_LEFTHAND_INDEX || parentJointIndex == CAMERA_RELATIVE_CONTROLLER_LEFTHAND_INDEX || - parentJointIndex == FARGRAB_LEFTHAND_INDEX || parentJointIndex == getJointIndex("LeftHand")) { + } else if (parentJointIndex == CONTROLLER_LEFTHAND_INDEX || + parentJointIndex == CAMERA_RELATIVE_CONTROLLER_LEFTHAND_INDEX || + parentJointIndex == FARGRAB_LEFTHAND_INDEX || + parentJointIndex == getJointIndex("LeftHand")) { hand = "left"; } - Grab tmpGrab(DependencyManager::get()->getSessionUUID(), targetID, parentJointIndex, hand, positionalOffset, - rotationalOffset); + Grab tmpGrab(DependencyManager::get()->getSessionUUID(), + targetID, parentJointIndex, hand, positionalOffset, rotationalOffset); QByteArray grabData = tmpGrab.toByteArray(); bool dataChanged = updateAvatarGrabData(grabID, grabData); @@ -5785,9 +5830,10 @@ const QUuid MyAvatar::grab(const QUuid& targetID, } void MyAvatar::releaseGrab(const QUuid& grabID) { - bool tellHandler{ false }; + bool tellHandler { false }; _avatarGrabsLock.withWriteLock([&] { + std::map::iterator itr; itr = _avatarGrabs.find(grabID); if (itr != _avatarGrabs.end()) { @@ -5816,12 +5862,13 @@ void MyAvatar::releaseGrab(const QUuid& grabID) { void MyAvatar::addAvatarHandsToFlow(const std::shared_ptr& otherAvatar) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "addAvatarHandsToFlow", Q_ARG(const std::shared_ptr&, otherAvatar)); + QMetaObject::invokeMethod(this, "addAvatarHandsToFlow", + Q_ARG(const std::shared_ptr&, otherAvatar)); return; } - auto& flow = _skeletonModel->getRig().getFlow(); + auto &flow = _skeletonModel->getRig().getFlow(); if (otherAvatar != nullptr && flow.getActive()) { - for (auto& handJointName : HAND_COLLISION_JOINTS) { + for (auto &handJointName : HAND_COLLISION_JOINTS) { int jointIndex = otherAvatar->getJointIndex(handJointName); if (jointIndex != -1) { glm::vec3 position = otherAvatar->getJointPosition(jointIndex); @@ -5849,18 +5896,18 @@ void MyAvatar::addAvatarHandsToFlow(const std::shared_ptr& otherAvatar) * @property {number} [radius=0.05] - Collision sphere radius. * @property {number} [offset=Vec3.ZERO] - Offset of the collision sphere from the joint. */ -void MyAvatar::useFlow(bool isActive, - bool isCollidable, - const QVariantMap& physicsConfig, - const QVariantMap& collisionsConfig) { +void MyAvatar::useFlow(bool isActive, bool isCollidable, const QVariantMap& physicsConfig, const QVariantMap& collisionsConfig) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "useFlow", Q_ARG(bool, isActive), Q_ARG(bool, isCollidable), - Q_ARG(const QVariantMap&, physicsConfig), Q_ARG(const QVariantMap&, collisionsConfig)); + QMetaObject::invokeMethod(this, "useFlow", + Q_ARG(bool, isActive), + Q_ARG(bool, isCollidable), + Q_ARG(const QVariantMap&, physicsConfig), + Q_ARG(const QVariantMap&, collisionsConfig)); return; } if (_skeletonModel->isLoaded()) { - auto& flow = _skeletonModel->getRig().getFlow(); - auto& collisionSystem = flow.getCollisionSystem(); + auto &flow = _skeletonModel->getRig().getFlow(); + auto &collisionSystem = flow.getCollisionSystem(); if (!flow.isInitialized() && isActive) { _skeletonModel->getRig().initFlow(true); } else { @@ -5869,7 +5916,7 @@ void MyAvatar::useFlow(bool isActive, collisionSystem.setActive(isCollidable); auto physicsGroups = physicsConfig.keys(); if (physicsGroups.size() > 0) { - for (auto& groupName : physicsGroups) { + for (auto &groupName : physicsGroups) { auto settings = physicsConfig[groupName].toMap(); FlowPhysicsSettings physicsSettings; if (settings.contains("active")) { @@ -5899,7 +5946,7 @@ void MyAvatar::useFlow(bool isActive, auto collisionJoints = collisionsConfig.keys(); if (collisionJoints.size() > 0) { collisionSystem.clearSelfCollisions(); - for (auto& jointName : collisionJoints) { + for (auto &jointName : collisionJoints) { int jointIndex = getJointIndex(jointName); FlowCollisionSettings collisionsSettings; auto settings = collisionsConfig[jointName].toMap(); @@ -5953,13 +6000,14 @@ void MyAvatar::useFlow(bool isActive, QVariantMap MyAvatar::getFlowData() { QVariantMap result; if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "getFlowData", Q_RETURN_ARG(QVariantMap, result)); + BLOCKING_INVOKE_METHOD(this, "getFlowData", + Q_RETURN_ARG(QVariantMap, result)); return result; } if (_skeletonModel->isLoaded()) { auto jointNames = getJointNames(); - auto& flow = _skeletonModel->getRig().getFlow(); - auto& collisionSystem = flow.getCollisionSystem(); + auto &flow = _skeletonModel->getRig().getFlow(); + auto &collisionSystem = flow.getCollisionSystem(); bool initialized = flow.isInitialized(); result.insert("initialized", initialized); result.insert("active", flow.getActive()); @@ -5969,17 +6017,17 @@ QVariantMap MyAvatar::getFlowData() { QVariantMap threadData; std::map groupJointsMap; QVariantList jointCollisionData; - auto& groups = flow.getGroupSettings(); - for (auto& joint : flow.getJoints()) { - auto& groupName = joint.second.getGroup(); + auto &groups = flow.getGroupSettings(); + for (auto &joint : flow.getJoints()) { + auto &groupName = joint.second.getGroup(); if (groups.find(groupName) != groups.end()) { if (groupJointsMap.find(groupName) == groupJointsMap.end()) { groupJointsMap.insert(std::pair(groupName, QVariantList())); } groupJointsMap[groupName].push_back(joint.second.getIndex()); } - } - for (auto& group : groups) { + } + for (auto &group : groups) { QVariantMap settingsObject; QString groupName = group.first; FlowPhysicsSettings groupSettings = group.second; @@ -5994,8 +6042,8 @@ QVariantMap MyAvatar::getFlowData() { physicsData.insert(groupName, settingsObject); } - auto& collisions = collisionSystem.getCollisions(); - for (auto& collision : collisions) { + auto &collisions = collisionSystem.getCollisions(); + for (auto &collision : collisions) { QVariantMap collisionObject; collisionObject.insert("offset", vec3toVariant(collision._offset)); collisionObject.insert("radius", collision._radius); @@ -6003,7 +6051,7 @@ QVariantMap MyAvatar::getFlowData() { QString jointName = jointNames.size() > collision._jointIndex ? jointNames[collision._jointIndex] : "unknown"; collisionsData.insert(jointName, collisionObject); } - for (auto& thread : flow.getThreads()) { + for (auto &thread : flow.getThreads()) { QVariantList indices; for (int index : thread._joints) { indices.append(index); @@ -6020,13 +6068,14 @@ QVariantMap MyAvatar::getFlowData() { QVariantList MyAvatar::getCollidingFlowJoints() { QVariantList result; if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "getCollidingFlowJoints", Q_RETURN_ARG(QVariantList, result)); + BLOCKING_INVOKE_METHOD(this, "getCollidingFlowJoints", + Q_RETURN_ARG(QVariantList, result)); return result; } if (_skeletonModel->isLoaded()) { auto& flow = _skeletonModel->getRig().getFlow(); - for (auto& joint : flow.getJoints()) { + for (auto &joint : flow.getJoints()) { if (joint.second.isColliding()) { result.append(joint.second.getIndex()); } @@ -6037,7 +6086,7 @@ QVariantList MyAvatar::getCollidingFlowJoints() { void MyAvatar::initFlowFromFST() { if (_skeletonModel->isLoaded()) { - auto& flowData = _skeletonModel->getHFMModel().flowData; + auto &flowData = _skeletonModel->getHFMModel().flowData; if (flowData.shouldInitFlow()) { useFlow(true, flowData.shouldInitCollisions(), flowData._physicsConfig, flowData._collisionsConfig); } @@ -6055,3 +6104,4 @@ void MyAvatar::sendPacket(const QUuid& entityID) const { }); } } + From e7255298de9c7d38bc05be468677ff1b7949fd98 Mon Sep 17 00:00:00 2001 From: Preston Bezos Date: Fri, 7 Jun 2019 11:59:26 -0700 Subject: [PATCH 17/31] made one more change to get rid of ubuntu warning --- interface/src/avatar/MyAvatar.cpp | 857 ++++++++++++++---------------- 1 file changed, 404 insertions(+), 453 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index b60bfd3f29..55ae1a8423 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -71,9 +71,9 @@ using namespace std; const float DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES = 30.0f; const float YAW_SPEED_DEFAULT = 100.0f; // degrees/sec -const float PITCH_SPEED_DEFAULT = 75.0f; // degrees/sec +const float PITCH_SPEED_DEFAULT = 75.0f; // degrees/sec -const float MAX_BOOST_SPEED = 0.5f * DEFAULT_AVATAR_MAX_WALKING_SPEED; // action motor gets additive boost below this speed +const float MAX_BOOST_SPEED = 0.5f * DEFAULT_AVATAR_MAX_WALKING_SPEED; // action motor gets additive boost below this speed const float MIN_AVATAR_SPEED = 0.05f; float MIN_SCRIPTED_MOTOR_TIMESCALE = 0.005f; @@ -83,7 +83,8 @@ const int SCRIPTED_MOTOR_AVATAR_FRAME = 1; const int SCRIPTED_MOTOR_WORLD_FRAME = 2; const int SCRIPTED_MOTOR_SIMPLE_MODE = 0; const int SCRIPTED_MOTOR_DYNAMIC_MODE = 1; -const QString& DEFAULT_AVATAR_COLLISION_SOUND_URL = "https://hifi-public.s3.amazonaws.com/sounds/Collisions-otherorganic/Body_Hits_Impact.wav"; +const QString& DEFAULT_AVATAR_COLLISION_SOUND_URL = + "https://hifi-public.s3.amazonaws.com/sounds/Collisions-otherorganic/Body_Hits_Impact.wav"; const float MyAvatar::ZOOM_MIN = 0.5f; const float MyAvatar::ZOOM_MAX = 25.0f; @@ -92,7 +93,7 @@ const float MIN_SCALE_CHANGED_DELTA = 0.001f; const int MODE_READINGS_RING_BUFFER_SIZE = 500; const float CENTIMETERS_PER_METER = 100.0f; -const QString AVATAR_SETTINGS_GROUP_NAME { "Avatar" }; +const QString AVATAR_SETTINGS_GROUP_NAME{ "Avatar" }; static const QString USER_RECENTER_MODEL_FORCE_SIT = QStringLiteral("ForceSit"); static const QString USER_RECENTER_MODEL_FORCE_STAND = QStringLiteral("ForceStand"); @@ -113,50 +114,33 @@ MyAvatar::SitStandModelType stringToUserRecenterModel(const QString& str) { QString userRecenterModelToString(MyAvatar::SitStandModelType model) { switch (model) { - case MyAvatar::ForceSit: - return USER_RECENTER_MODEL_FORCE_SIT; - case MyAvatar::ForceStand: - return USER_RECENTER_MODEL_FORCE_STAND; - case MyAvatar::DisableHMDLean: - return USER_RECENTER_MODEL_DISABLE_HMD_LEAN; - case MyAvatar::Auto: - default: - return USER_RECENTER_MODEL_AUTO; + case MyAvatar::ForceSit: + return USER_RECENTER_MODEL_FORCE_SIT; + case MyAvatar::ForceStand: + return USER_RECENTER_MODEL_FORCE_STAND; + case MyAvatar::DisableHMDLean: + return USER_RECENTER_MODEL_DISABLE_HMD_LEAN; + case MyAvatar::Auto: + default: + return USER_RECENTER_MODEL_AUTO; } } MyAvatar::MyAvatar(QThread* thread) : - Avatar(thread), - _yawSpeed(YAW_SPEED_DEFAULT), - _pitchSpeed(PITCH_SPEED_DEFAULT), - _scriptedMotorTimescale(DEFAULT_SCRIPTED_MOTOR_TIMESCALE), - _scriptedMotorFrame(SCRIPTED_MOTOR_CAMERA_FRAME), - _scriptedMotorMode(SCRIPTED_MOTOR_SIMPLE_MODE), - _motionBehaviors(AVATAR_MOTION_DEFAULTS), - _characterController(std::shared_ptr(this)), - _eyeContactTarget(LEFT_EYE), - _realWorldFieldOfView("realWorldFieldOfView", - DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES), - _useAdvancedMovementControls("advancedMovementForHandControllersIsChecked", true), - _showPlayArea("showPlayArea", true), - _smoothOrientationTimer(std::numeric_limits::max()), - _smoothOrientationInitial(), - _smoothOrientationTarget(), - _hmdSensorMatrix(), - _hmdSensorOrientation(), - _hmdSensorPosition(), - _recentModeReadings(MODE_READINGS_RING_BUFFER_SIZE), - _bodySensorMatrix(), - _goToPending(false), - _goToSafe(true), - _goToFeetAjustment(false), - _goToPosition(), - _goToOrientation(), - _prevShouldDrawHead(true), - _audioListenerMode(FROM_HEAD), + Avatar(thread), _yawSpeed(YAW_SPEED_DEFAULT), _pitchSpeed(PITCH_SPEED_DEFAULT), + _scriptedMotorTimescale(DEFAULT_SCRIPTED_MOTOR_TIMESCALE), _scriptedMotorFrame(SCRIPTED_MOTOR_CAMERA_FRAME), + _scriptedMotorMode(SCRIPTED_MOTOR_SIMPLE_MODE), _motionBehaviors(AVATAR_MOTION_DEFAULTS), + _characterController(std::shared_ptr(this)), _eyeContactTarget(LEFT_EYE), + _realWorldFieldOfView("realWorldFieldOfView", DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES), + _useAdvancedMovementControls("advancedMovementForHandControllersIsChecked", true), _showPlayArea("showPlayArea", true), + _smoothOrientationTimer(std::numeric_limits::max()), _smoothOrientationInitial(), _smoothOrientationTarget(), + _hmdSensorMatrix(), _hmdSensorOrientation(), _hmdSensorPosition(), _recentModeReadings(MODE_READINGS_RING_BUFFER_SIZE), + _bodySensorMatrix(), _goToPending(false), _goToSafe(true), _goToFeetAjustment(false), _goToPosition(), _goToOrientation(), + _prevShouldDrawHead(true), _audioListenerMode(FROM_HEAD), _dominantHandSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "dominantHand", DOMINANT_RIGHT_HAND), _strafeEnabledSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "strafeEnabled", DEFAULT_STRAFE_ENABLED), - _hmdAvatarAlignmentTypeSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "hmdAvatarAlignmentType", DEFAULT_HMD_AVATAR_ALIGNMENT_TYPE), + _hmdAvatarAlignmentTypeSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "hmdAvatarAlignmentType", + DEFAULT_HMD_AVATAR_ALIGNMENT_TYPE), _headPitchSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "", 0.0f), _scaleSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "scale", _targetScale), _yawSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "yawSpeed", _yawSpeed), @@ -172,17 +156,19 @@ MyAvatar::MyAvatar(QThread* thread) : _userHeightSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userHeight", DEFAULT_AVATAR_HEIGHT), _flyingHMDSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "flyingHMD", _flyingPrefHMD), _movementReferenceSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "movementReference", _movementReference), - _avatarEntityCountSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" << "size", 0), + _avatarEntityCountSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" + << "size", + 0), _driveGear1Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear1", _driveGear1), _driveGear2Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear2", _driveGear2), _driveGear3Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear3", _driveGear3), _driveGear4Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear4", _driveGear4), _driveGear5Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear5", _driveGear5), _analogWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogWalkSpeed", _analogWalkSpeed.get()), - _analogPlusWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogPlusWalkSpeed", _analogPlusWalkSpeed.get()), + _analogPlusWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogPlusWalkSpeed", + _analogPlusWalkSpeed.get()), _controlSchemeIndexSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "controlSchemeIndex", _controlSchemeIndex), - _userRecenterModelSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userRecenterModel", USER_RECENTER_MODEL_AUTO) -{ + _userRecenterModelSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userRecenterModel", USER_RECENTER_MODEL_AUTO) { _clientTraitsHandler.reset(new ClientTraitsHandler(this)); // give the pointer to our head to inherited _headData variable from AvatarData @@ -203,7 +189,7 @@ MyAvatar::MyAvatar(QThread* thread) : qApp->loadAvatarScripts(hfmModel.scripts); _shouldLoadScripts = false; } - // Load and convert old attachments to avatar entities + // Load and convert old attachments to avatar entities if (_oldAttachmentData.size() > 0) { setAttachmentData(_oldAttachmentData); _oldAttachmentData.clear(); @@ -220,11 +206,11 @@ MyAvatar::MyAvatar(QThread* thread) : clearDriveKeys(); // Necessary to select the correct slot - using SlotType = void(MyAvatar::*)(const glm::vec3&, bool, const glm::quat&, bool); + using SlotType = void (MyAvatar::*)(const glm::vec3&, bool, const glm::quat&, bool); // connect to AddressManager signal for location jumps - connect(DependencyManager::get().data(), &AddressManager::locationChangeRequired, - this, static_cast(&MyAvatar::goToFeetLocation)); + connect(DependencyManager::get().data(), &AddressManager::locationChangeRequired, this, + static_cast(&MyAvatar::goToFeetLocation)); // handle scale constraints imposed on us by the domain-server auto& domainHandler = DependencyManager::get()->getDomainHandler(); @@ -287,7 +273,6 @@ MyAvatar::MyAvatar(QThread* thread) : if (recordingInterface->getPlayerUseSkeletonModel() && dummyAvatar.getSkeletonModelURL().isValid() && (dummyAvatar.getSkeletonModelURL() != getSkeletonModelURL())) { - setSkeletonModelURL(dummyAvatar.getSkeletonModelURL()); } @@ -383,7 +368,8 @@ void MyAvatar::enableHandTouchForID(const QUuid& entityID) { } void MyAvatar::registerMetaTypes(ScriptEnginePointer engine) { - QScriptValue value = engine->newQObject(this, QScriptEngine::QtOwnership, QScriptEngine::ExcludeDeleteLater | QScriptEngine::ExcludeChildObjects); + QScriptValue value = engine->newQObject(this, QScriptEngine::QtOwnership, + QScriptEngine::ExcludeDeleteLater | QScriptEngine::ExcludeChildObjects); engine->globalObject().setProperty("MyAvatar", value); QScriptValue driveKeys = engine->newObject(); @@ -446,7 +432,6 @@ void MyAvatar::resetSensorsAndBody() { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "resetSensorsAndBody"); return; - } qApp->getActiveDisplayPlugin()->resetSensors(); @@ -460,7 +445,7 @@ void MyAvatar::centerBody() { } // derive the desired body orientation from the current hmd orientation, before the sensor reset. - auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. // transform this body into world space auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix; @@ -497,7 +482,6 @@ void MyAvatar::clearIKJointLimitHistory() { } void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { - assert(QThread::currentThread() == thread()); // Reset dynamic state. @@ -506,14 +490,14 @@ void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { if (andReload) { _skeletonModel->reset(); } - if (andHead) { // which drives camera in desktop + if (andHead) { // which drives camera in desktop getHead()->reset(); } setThrust(glm::vec3(0.0f)); if (andRecenter) { // derive the desired body orientation from the *old* hmd orientation, before the sensor reset. - auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. // transform this body into world space auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix; @@ -540,8 +524,8 @@ void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { void MyAvatar::updateSitStandState(float newHeightReading, float dt) { const float STANDING_HEIGHT_MULTIPLE = 1.2f; const float SITTING_HEIGHT_MULTIPLE = 0.833f; - const float SITTING_TIMEOUT = 4.0f; // 4 seconds - const float STANDING_TIMEOUT = 0.3333f; // 1/3 second + const float SITTING_TIMEOUT = 4.0f; // 4 seconds + const float STANDING_TIMEOUT = 0.3333f; // 1/3 second const float SITTING_UPPER_BOUND = 1.52f; if (!getIsSitStandStateLocked()) { if (!getIsAway() && getControllerPoseInAvatarFrame(controller::Action::HEAD).isValid()) { @@ -601,9 +585,9 @@ void MyAvatar::updateSitStandState(float newHeightReading, float dt) { void MyAvatar::update(float deltaTime) { // update moving average of HMD facing in xz plane. const float HMD_FACING_TIMESCALE = getRotationRecenterFilterLength(); - const float PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH = 0.0f; // 100 percent shoulders + const float PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH = 0.0f; // 100 percent shoulders const float COSINE_THIRTY_DEGREES = 0.866f; - const float SQUATTY_TIMEOUT = 30.0f; // 30 seconds + const float SQUATTY_TIMEOUT = 30.0f; // 30 seconds const float HEIGHT_FILTER_COEFFICIENT = 0.01f; float tau = deltaTime / HMD_FACING_TIMESCALE; @@ -612,8 +596,8 @@ void MyAvatar::update(float deltaTime) { // put the average hand azimuth into sensor space. // then mix it with head facing direction to determine rotation recenter int spine2Index = _skeletonModel->getRig().indexOfJoint("Spine2"); - if (getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND).isValid() && getControllerPoseInAvatarFrame(controller::Action::RIGHT_HAND).isValid() && !(spine2Index < 0)) { - + if (getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND).isValid() && + getControllerPoseInAvatarFrame(controller::Action::RIGHT_HAND).isValid() && !(spine2Index < 0)) { // use the spine for the azimuth origin. glm::quat spine2Rot = getAbsoluteJointRotationInObjectFrame(spine2Index); glm::vec3 handHipAzimuthAvatarSpace = spine2Rot * glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y); @@ -623,8 +607,10 @@ void MyAvatar::update(float deltaTime) { glm::vec3 handHipAzimuthSensorSpace = transformVectorFast(worldToSensorMat, handHipAzimuthWorldSpace); glm::vec2 normedHandHipAzimuthSensorSpace(0.0f, 1.0f); if (glm::length(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)) > 0.0f) { - normedHandHipAzimuthSensorSpace = glm::normalize(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)); - glm::vec2 headFacingPlusHandHipAzimuthMix = lerp(normedHandHipAzimuthSensorSpace, _headControllerFacing, PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH); + normedHandHipAzimuthSensorSpace = + glm::normalize(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)); + glm::vec2 headFacingPlusHandHipAzimuthMix = + lerp(normedHandHipAzimuthSensorSpace, _headControllerFacing, PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH); _headControllerFacingMovingAverage = lerp(_headControllerFacingMovingAverage, headFacingPlusHandHipAzimuthMix, tau); } else { // use head facing if the chest arms vector is up or down. @@ -642,7 +628,8 @@ void MyAvatar::update(float deltaTime) { controller::Pose newHeightReading = getControllerPoseInSensorFrame(controller::Action::HEAD); if (newHeightReading.isValid()) { int newHeightReadingInCentimeters = glm::floor(newHeightReading.getTranslation().y * CENTIMETERS_PER_METER); - _averageUserHeightSensorSpace = lerp(_averageUserHeightSensorSpace, newHeightReading.getTranslation().y, HEIGHT_FILTER_COEFFICIENT); + _averageUserHeightSensorSpace = + lerp(_averageUserHeightSensorSpace, newHeightReading.getTranslation().y, HEIGHT_FILTER_COEFFICIENT); _recentModeReadings.insert(newHeightReadingInCentimeters); setCurrentStandingHeight(computeStandingHeightMode(newHeightReading)); setAverageHeadRotation(computeAverageHeadRotation(getControllerPoseInAvatarFrame(controller::Action::HEAD))); @@ -658,10 +645,9 @@ void MyAvatar::update(float deltaTime) { } float angleSpine2 = glm::dot(upSpine2, glm::vec3(0.0f, 1.0f, 0.0f)); - if (getControllerPoseInAvatarFrame(controller::Action::HEAD).getTranslation().y < (headDefaultPositionAvatarSpace.y - SQUAT_THRESHOLD) && - (angleSpine2 > COSINE_THIRTY_DEGREES) && - (getUserRecenterModel() != MyAvatar::SitStandModelType::ForceStand)) { - + if (getControllerPoseInAvatarFrame(controller::Action::HEAD).getTranslation().y < + (headDefaultPositionAvatarSpace.y - SQUAT_THRESHOLD) && + (angleSpine2 > COSINE_THIRTY_DEGREES) && (getUserRecenterModel() != MyAvatar::SitStandModelType::ForceStand)) { _squatTimer += deltaTime; if (_squatTimer > SQUATTY_TIMEOUT) { _squatTimer = 0.0f; @@ -677,20 +663,24 @@ void MyAvatar::update(float deltaTime) { if (_drawAverageFacingEnabled) { auto sensorHeadPose = getControllerPoseInSensorFrame(controller::Action::HEAD); glm::vec3 worldHeadPos = transformPoint(getSensorToWorldMatrix(), sensorHeadPose.getTranslation()); - glm::vec3 worldFacingAverage = transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacingMovingAverage.x, 0.0f, _headControllerFacingMovingAverage.y)); - glm::vec3 worldFacing = transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacing.x, 0.0f, _headControllerFacing.y)); + glm::vec3 worldFacingAverage = + transformVectorFast(getSensorToWorldMatrix(), + glm::vec3(_headControllerFacingMovingAverage.x, 0.0f, _headControllerFacingMovingAverage.y)); + glm::vec3 worldFacing = + transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacing.x, 0.0f, _headControllerFacing.y)); DebugDraw::getInstance().drawRay(worldHeadPos, worldHeadPos + worldFacing, glm::vec4(0.0f, 1.0f, 0.0f, 1.0f)); DebugDraw::getInstance().drawRay(worldHeadPos, worldHeadPos + worldFacingAverage, glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)); // draw hand azimuth vector - glm::vec3 handAzimuthMidpoint = transformPoint(getTransform().getMatrix(), glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y)); + glm::vec3 handAzimuthMidpoint = + transformPoint(getTransform().getMatrix(), glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y)); DebugDraw::getInstance().drawRay(getWorldPosition(), handAzimuthMidpoint, glm::vec4(0.0f, 1.0f, 1.0f, 1.0f)); } if (_goToPending) { setWorldPosition(_goToPosition); setWorldOrientation(_goToOrientation); - _headControllerFacingMovingAverage = _headControllerFacing; // reset moving average + _headControllerFacingMovingAverage = _headControllerFacing; // reset moving average _goToPending = false; // updateFromHMDSensorMatrix (called from paintGL) expects that the sensorToWorldMatrix is updated for any position changes // that happen between render and Application::update (which calls updateSensorToWorldMatrix to do so). @@ -700,7 +690,7 @@ void MyAvatar::update(float deltaTime) { emit positionGoneTo(); // Run safety tests as soon as we can after goToLocation, or clear if we're not colliding. _physicsSafetyPending = getCollisionsEnabled(); - _characterController.recomputeFlying(); // In case we've gone to into the sky. + _characterController.recomputeFlying(); // In case we've gone to into the sky. } if (_goToFeetAjustment && _skeletonModelLoaded) { auto feetAjustment = getWorldPosition() - getWorldFeetPosition(); @@ -712,7 +702,7 @@ void MyAvatar::update(float deltaTime) { // When needed and ready, arrange to check and fix. _physicsSafetyPending = false; if (_goToSafe) { - safeLanding(_goToPosition); // no-op if already safe + safeLanding(_goToPosition); // no-op if already safe } } @@ -720,7 +710,8 @@ void MyAvatar::update(float deltaTime) { head->relax(deltaTime); updateFromTrackers(deltaTime); - if (getIsInWalkingState() && glm::length(getControllerPoseInAvatarFrame(controller::Action::HEAD).getVelocity()) < DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { + if (getIsInWalkingState() && glm::length(getControllerPoseInAvatarFrame(controller::Action::HEAD).getVelocity()) < + DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { setIsInWalkingState(false); } @@ -731,12 +722,13 @@ void MyAvatar::update(float deltaTime) { setAudioLoudness(audio->getLastInputLoudness()); setAudioAverageLoudness(audio->getAudioAverageInputLoudness()); - glm::vec3 halfBoundingBoxDimensions(_characterController.getCapsuleRadius(), _characterController.getCapsuleHalfHeight(), _characterController.getCapsuleRadius()); + glm::vec3 halfBoundingBoxDimensions(_characterController.getCapsuleRadius(), _characterController.getCapsuleHalfHeight(), + _characterController.getCapsuleRadius()); // This might not be right! Isn't the capsule local offset in avatar space? -HRS 5/26/17 halfBoundingBoxDimensions += _characterController.getCapsuleLocalOffset(); QMetaObject::invokeMethod(audio, "setAvatarBoundingBoxParameters", - Q_ARG(glm::vec3, (getWorldPosition() - halfBoundingBoxDimensions)), - Q_ARG(glm::vec3, (halfBoundingBoxDimensions*2.0f))); + Q_ARG(glm::vec3, (getWorldPosition() - halfBoundingBoxDimensions)), + Q_ARG(glm::vec3, (halfBoundingBoxDimensions * 2.0f))); simulate(deltaTime, true); @@ -744,23 +736,20 @@ void MyAvatar::update(float deltaTime) { currentEnergy -= getAccelerationEnergy(); currentEnergy -= getAudioEnergy(); - if(didTeleport()) { + if (didTeleport()) { currentEnergy = 0.0f; } - currentEnergy = max(0.0f, min(currentEnergy,1.0f)); + currentEnergy = max(0.0f, min(currentEnergy, 1.0f)); emit energyChanged(currentEnergy); updateEyeContactTarget(deltaTime); } void MyAvatar::updateEyeContactTarget(float deltaTime) { - _eyeContactTargetTimer -= deltaTime; if (_eyeContactTargetTimer < 0.0f) { - const float CHANCE_OF_CHANGING_TARGET = 0.01f; if (randFloat() < CHANCE_OF_CHANGING_TARGET) { - float const FIFTY_FIFTY_CHANCE = 0.5f; float const EYE_TO_MOUTH_CHANCE = 0.25f; switch (_eyeContactTarget) { @@ -828,21 +817,20 @@ void MyAvatar::simulate(float deltaTime, bool inView) { if (isChildOfHead && !object->hasGrabs()) { // Cauterize or display children of head per head drawing state. updateChildCauterization(object, !_prevShouldDrawHead); - object->forEachDescendant([&](SpatiallyNestablePointer descendant) { - updateChildCauterization(descendant, !_prevShouldDrawHead); - }); + object->forEachDescendant( + [&](SpatiallyNestablePointer descendant) { updateChildCauterization(descendant, !_prevShouldDrawHead); }); _cauterizedChildrenOfHead.insert(object); objectsToUncauterize.erase(object); } else if (objectsToUncauterize.find(object) == objectsToUncauterize.end()) { objectsToUncauterize.insert(object); - object->forEachDescendant([&](SpatiallyNestablePointer descendant) { - objectsToUncauterize.insert(descendant); - }); + object->forEachDescendant( + [&](SpatiallyNestablePointer descendant) { objectsToUncauterize.insert(descendant); }); } }); // Redisplay cauterized entities that are no longer children of the avatar. - for (auto cauterizedChild = objectsToUncauterize.begin(); cauterizedChild != objectsToUncauterize.end(); cauterizedChild++) { + for (auto cauterizedChild = objectsToUncauterize.begin(); cauterizedChild != objectsToUncauterize.end(); + cauterizedChild++) { updateChildCauterization(*cauterizedChild, false); } } @@ -886,7 +874,7 @@ void MyAvatar::simulate(float deltaTime, bool inView) { if (!_skeletonModel->hasSkeleton()) { // All the simulation that can be done has been done - getHead()->setPosition(getWorldPosition()); // so audio-position isn't 0,0,0 + getHead()->setPosition(getWorldPosition()); // so audio-position isn't 0,0,0 return; } @@ -967,8 +955,7 @@ void MyAvatar::updateFromHMDSensorMatrix(const glm::mat4& hmdSensorMatrix) { _hmdSensorMatrix = hmdSensorMatrix; auto newHmdSensorPosition = extractTranslation(hmdSensorMatrix); - if (newHmdSensorPosition != getHMDSensorPosition() && - glm::length(newHmdSensorPosition) > MAX_HMD_ORIGIN_DISTANCE) { + if (newHmdSensorPosition != getHMDSensorPosition() && glm::length(newHmdSensorPosition) > MAX_HMD_ORIGIN_DISTANCE) { qWarning() << "Invalid HMD sensor position " << newHmdSensorPosition; // Ignore unreasonable HMD sensor data return; @@ -996,8 +983,8 @@ glm::vec2 MyAvatar::computeHandAzimuth() const { glm::vec2 latestHipToHandController = _hipToHandController; int spine2Index = _skeletonModel->getRig().indexOfJoint("Spine2"); - if (leftHandPoseAvatarSpace.isValid() && rightHandPoseAvatarSpace.isValid() && headPoseAvatarSpace.isValid() && !(spine2Index < 0)) { - + if (leftHandPoseAvatarSpace.isValid() && rightHandPoseAvatarSpace.isValid() && headPoseAvatarSpace.isValid() && + !(spine2Index < 0)) { glm::vec3 spine2Position = getAbsoluteJointTranslationInObjectFrame(spine2Index); glm::quat spine2Rotation = getAbsoluteJointRotationInObjectFrame(spine2Index); @@ -1009,8 +996,10 @@ glm::vec2 MyAvatar::computeHandAzimuth() const { // we need the old azimuth reading to prevent flipping the facing direction 180 // in the case where the hands go from being slightly less than 180 apart to slightly more than 180 apart. glm::vec2 oldAzimuthReading = _hipToHandController; - if ((glm::length(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)) > 0.0f) && (glm::length(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)) > 0.0f)) { - latestHipToHandController = lerp(glm::normalize(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)), glm::normalize(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)), HALFWAY); + if ((glm::length(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)) > 0.0f) && + (glm::length(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)) > 0.0f)) { + latestHipToHandController = lerp(glm::normalize(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)), + glm::normalize(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)), HALFWAY); } else { latestHipToHandController = glm::vec2(0.0f, 1.0f); } @@ -1058,11 +1047,11 @@ void MyAvatar::updateJointFromController(controller::Action poseKey, ThreadSafeV // update sensor to world matrix from current body position and hmd sensor. // This is so the correct camera can be used for rendering. void MyAvatar::updateSensorToWorldMatrix() { - // update the sensor mat so that the body position will end up in the desired // position when driven from the head. float sensorToWorldScale = getEyeHeight() / getUserEyeHeight(); - glm::mat4 desiredMat = createMatFromScaleQuatAndPos(glm::vec3(sensorToWorldScale), getWorldOrientation(), getWorldPosition()); + glm::mat4 desiredMat = + createMatFromScaleQuatAndPos(glm::vec3(sensorToWorldScale), getWorldOrientation(), getWorldPosition()); _sensorToWorldMatrix = desiredMat * glm::inverse(_bodySensorMatrix); bool hasSensorToWorldScaleChanged = false; @@ -1080,11 +1069,10 @@ void MyAvatar::updateSensorToWorldMatrix() { _sensorToWorldMatrixCache.set(_sensorToWorldMatrix); updateJointFromController(controller::Action::LEFT_HAND, _controllerLeftHandMatrixCache); updateJointFromController(controller::Action::RIGHT_HAND, _controllerRightHandMatrixCache); - + if (hasSensorToWorldScaleChanged) { emit sensorToWorldScaleChanged(sensorToWorldScale); } - } // Update avatar head rotation with sensor data @@ -1109,8 +1097,7 @@ void MyAvatar::updateFromTrackers(float deltaTime) { const float TRACKER_YAW_TURN_SENSITIVITY = 0.5f; const float TRACKER_MIN_YAW_TURN = 15.0f; const float TRACKER_MAX_YAW_TURN = 50.0f; - if ( (fabs(estimatedRotation.y) > TRACKER_MIN_YAW_TURN) && - (fabs(estimatedRotation.y) < TRACKER_MAX_YAW_TURN) ) { + if ((fabs(estimatedRotation.y) > TRACKER_MIN_YAW_TURN) && (fabs(estimatedRotation.y) < TRACKER_MAX_YAW_TURN)) { if (estimatedRotation.y > 0.0f) { _bodyYawDelta += (estimatedRotation.y - TRACKER_MIN_YAW_TURN) * TRACKER_YAW_TURN_SENSITIVITY; } else { @@ -1125,7 +1112,6 @@ void MyAvatar::updateFromTrackers(float deltaTime) { // their head only 30 degrees or so, this may correspond to a 90 degree field of view. // Note that roll is magnified by a constant because it is not related to field of view. - Head* head = getHead(); if (hasHead || playing) { head->setDeltaPitch(estimatedRotation.x); @@ -1191,15 +1177,15 @@ controller::Pose MyAvatar::getRightHandTipPose() const { void MyAvatar::render(RenderArgs* renderArgs) { // don't render if we've been asked to disable local rendering if (!_shouldRender) { - return; // exit early + return; // exit early } Avatar::render(renderArgs); } void MyAvatar::overrideAnimation(const QString& url, float fps, bool loop, float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "overrideAnimation", Q_ARG(const QString&, url), Q_ARG(float, fps), - Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); + QMetaObject::invokeMethod(this, "overrideAnimation", Q_ARG(const QString&, url), Q_ARG(float, fps), Q_ARG(bool, loop), + Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); return; } _skeletonModel->getRig().overrideAnimation(url, fps, loop, firstFrame, lastFrame); @@ -1207,8 +1193,8 @@ void MyAvatar::overrideAnimation(const QString& url, float fps, bool loop, float void MyAvatar::overrideHandAnimation(bool isLeft, const QString& url, float fps, bool loop, float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "overrideHandAnimation", Q_ARG(bool, isLeft), Q_ARG(const QString&, url), Q_ARG(float, fps), - Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); + QMetaObject::invokeMethod(this, "overrideHandAnimation", Q_ARG(bool, isLeft), Q_ARG(const QString&, url), + Q_ARG(float, fps), Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); return; } _skeletonModel->getRig().overrideHandAnimation(isLeft, url, fps, loop, firstFrame, lastFrame); @@ -1239,8 +1225,12 @@ QStringList MyAvatar::getAnimationRoles() { return _skeletonModel->getRig().getAnimationRoles(); } -void MyAvatar::overrideRoleAnimation(const QString& role, const QString& url, float fps, bool loop, - float firstFrame, float lastFrame) { +void MyAvatar::overrideRoleAnimation(const QString& role, + const QString& url, + float fps, + bool loop, + float firstFrame, + float lastFrame) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "overrideRoleAnimation", Q_ARG(const QString&, role), Q_ARG(const QString&, url), Q_ARG(float, fps), Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); @@ -1259,9 +1249,9 @@ void MyAvatar::restoreRoleAnimation(const QString& role) { void MyAvatar::saveAvatarUrl() { if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid()) { - _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() ? - "" : - _fullAvatarURLFromPreferences.toString()); + _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() + ? "" + : _fullAvatarURLFromPreferences.toString()); } } @@ -1278,10 +1268,12 @@ void MyAvatar::resizeAvatarEntitySettingHandles(uint32_t maxIndex) { uint32_t settingsIndex = (uint32_t)_avatarEntityIDSettings.size() + 1; while (settingsIndex <= maxIndex) { Setting::Handle idHandle(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" - << QString::number(settingsIndex) << "id", QUuid()); + << QString::number(settingsIndex) << "id", + QUuid()); _avatarEntityIDSettings.push_back(idHandle); Setting::Handle dataHandle(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" - << QString::number(settingsIndex) << "properties", QByteArray()); + << QString::number(settingsIndex) << "properties", + QByteArray()); _avatarEntityDataSettings.push_back(dataHandle); settingsIndex++; } @@ -1299,10 +1291,10 @@ void MyAvatar::saveData() { // only save the fullAvatarURL if it has not been overwritten on command line // (so the overrideURL is not valid), or it was overridden _and_ we specified // --replaceAvatarURL (so _saveAvatarOverrideUrl is true) - if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid() ) { - _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() ? - "" : - _fullAvatarURLFromPreferences.toString()); + if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid()) { + _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() + ? "" + : _fullAvatarURLFromPreferences.toString()); } _fullAvatarModelNameSetting.set(_fullAvatarModelName); @@ -1472,16 +1464,12 @@ void MyAvatar::setEnableInverseKinematics(bool isEnabled) { void MyAvatar::storeAvatarEntityDataPayload(const QUuid& entityID, const QByteArray& payload) { AvatarData::storeAvatarEntityDataPayload(entityID, payload); - _avatarEntitiesLock.withWriteLock([&] { - _cachedAvatarEntityBlobsToAddOrUpdate.push_back(entityID); - }); + _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobsToAddOrUpdate.push_back(entityID); }); } void MyAvatar::clearAvatarEntity(const QUuid& entityID, bool requiresRemovalFromTree) { AvatarData::clearAvatarEntity(entityID, requiresRemovalFromTree); - _avatarEntitiesLock.withWriteLock([&] { - _cachedAvatarEntityBlobsToDelete.push_back(entityID); - }); + _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobsToDelete.push_back(entityID); }); } void MyAvatar::sanitizeAvatarEntityProperties(EntityItemProperties& properties) const { @@ -1506,9 +1494,7 @@ void MyAvatar::sanitizeAvatarEntityProperties(EntityItemProperties& properties) void MyAvatar::handleChangedAvatarEntityData() { // NOTE: this is a per-frame update - if (getID().isNull() || - getID() == AVATAR_SELF_ID || - DependencyManager::get()->getSessionUUID() == QUuid()) { + if (getID().isNull() || getID() == AVATAR_SELF_ID || DependencyManager::get()->getSessionUUID() == QUuid()) { // wait until MyAvatar and this Node gets an ID before doing this. Otherwise, various things go wrong: // things get their parent fixed up from AVATAR_SELF_ID to a null uuid which means "no parent". return; @@ -1554,7 +1540,7 @@ void MyAvatar::handleChangedAvatarEntityData() { entitiesToUpdate = std::move(_entitiesToUpdate); }); - auto removeAllInstancesHelper = [] (const QUuid& id, std::vector& v) { + auto removeAllInstancesHelper = [](const QUuid& id, std::vector& v) { uint32_t i = 0; while (i < v.size()) { if (id == v[i]) { @@ -1582,9 +1568,7 @@ void MyAvatar::handleChangedAvatarEntityData() { // DELETE real entities for (const auto& id : entitiesToDelete) { - entityTree->withWriteLock([&] { - entityTree->deleteEntity(id); - }); + entityTree->withWriteLock([&] { entityTree->deleteEntity(id); }); } // ADD real entities @@ -1595,21 +1579,19 @@ void MyAvatar::handleChangedAvatarEntityData() { _avatarEntitiesLock.withReadLock([&] { AvatarEntityMap::iterator itr = _cachedAvatarEntityBlobs.find(id); if (itr == _cachedAvatarEntityBlobs.end()) { - blobFailed = true; // blob doesn't exist + blobFailed = true; // blob doesn't exist return; } std::lock_guard guard(_scriptEngineLock); if (!EntityItemProperties::blobToProperties(*_scriptEngine, itr.value(), properties)) { - blobFailed = true; // blob is corrupt + blobFailed = true; // blob is corrupt } }); if (blobFailed) { // remove from _cachedAvatarEntityBlobUpdatesToSkip just in case: // avoids a resource leak when blob updates to be skipped are never actually skipped // when the blob fails to result in a real EntityItem - _avatarEntitiesLock.withWriteLock([&] { - removeAllInstancesHelper(id, _cachedAvatarEntityBlobUpdatesToSkip); - }); + _avatarEntitiesLock.withWriteLock([&] { removeAllInstancesHelper(id, _cachedAvatarEntityBlobUpdatesToSkip); }); continue; } sanitizeAvatarEntityProperties(properties); @@ -1679,7 +1661,7 @@ void MyAvatar::handleChangedAvatarEntityData() { _cachedAvatarEntityBlobUpdatesToSkip[i] = _cachedAvatarEntityBlobUpdatesToSkip.back(); _cachedAvatarEntityBlobUpdatesToSkip.pop_back(); skip = true; - break; // assume no duplicates + break; // assume no duplicates } else { ++i; } @@ -1743,9 +1725,7 @@ bool MyAvatar::updateStaleAvatarEntityBlobs() const { std::lock_guard guard(_scriptEngineLock); EntityItemProperties::propertiesToBlob(*_scriptEngine, getID(), properties, blob); } - _avatarEntitiesLock.withWriteLock([&] { - _cachedAvatarEntityBlobs[id] = blob; - }); + _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobs[id] = blob; }); } } return true; @@ -1772,9 +1752,7 @@ AvatarEntityMap MyAvatar::getAvatarEntityData() const { // NOTE: the return value is expected to be a map of unfortunately-formatted-binary-blobs updateStaleAvatarEntityBlobs(); AvatarEntityMap result; - _avatarEntitiesLock.withReadLock([&] { - result = _cachedAvatarEntityBlobs; - }); + _avatarEntitiesLock.withReadLock([&] { result = _cachedAvatarEntityBlobs; }); return result; } @@ -1875,7 +1853,9 @@ void MyAvatar::avatarEntityDataToJson(QJsonObject& root) const { AvatarEntityMap::const_iterator itr = _cachedAvatarEntityBlobs.begin(); while (itr != _cachedAvatarEntityBlobs.end()) { QVariantMap entityData; - QUuid id = _avatarEntityForRecording.size() == _cachedAvatarEntityBlobs.size() ? _avatarEntityForRecording.values()[entityCount++] : itr.key(); + QUuid id = _avatarEntityForRecording.size() == _cachedAvatarEntityBlobs.size() + ? _avatarEntityForRecording.values()[entityCount++] + : itr.key(); entityData.insert("id", id); entityData.insert("properties", itr.value().toBase64()); avatarEntityJson.push_back(QVariant(entityData).toJsonObject()); @@ -1905,7 +1885,7 @@ void MyAvatar::loadData() { loadAvatarEntityDataFromSettings(); // Flying preferences must be loaded before calling setFlyingEnabled() - Setting::Handle firstRunVal { Settings::firstRun, true }; + Setting::Handle firstRunVal{ Settings::firstRun, true }; setFlyingHMDPref(firstRunVal.get() ? false : _flyingHMDSetting.get()); setMovementReference(firstRunVal.get() ? false : _movementReferenceSetting.get()); setDriveGear1(firstRunVal.get() ? DEFAULT_GEAR_1 : _driveGear1Setting.get()); @@ -1931,7 +1911,7 @@ void MyAvatar::loadData() { setUserRecenterModel(stringToUserRecenterModel(_userRecenterModelSetting.get(USER_RECENTER_MODEL_AUTO))); setEnableMeshVisible(Menu::getInstance()->isOptionChecked(MenuOption::MeshVisible)); - _follow.setToggleHipsFollowing (Menu::getInstance()->isOptionChecked(MenuOption::ToggleHipsFollowing)); + _follow.setToggleHipsFollowing(Menu::getInstance()->isOptionChecked(MenuOption::ToggleHipsFollowing)); setEnableDebugDrawBaseOfSupport(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawBaseOfSupport)); setEnableDebugDrawDefaultPose(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawDefaultPose)); setEnableDebugDrawAnimPose(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawAnimPose)); @@ -1959,7 +1939,7 @@ void MyAvatar::loadAvatarEntityDataFromSettings() { _entitiesToAdd.reserve(numEntities); // TODO: build map between old and new IDs so we can restitch parent-child relationships for (int i = 0; i < numEntities; i++) { - QUuid id = QUuid::createUuid(); // generate a new ID + QUuid id = QUuid::createUuid(); // generate a new ID _cachedAvatarEntityBlobs[id] = _avatarEntityDataSettings[i].get(); _entitiesToAdd.push_back(id); // this blob is the "authoritative source" for this AvatarEntity and we want to avoid overwriting it @@ -2029,10 +2009,9 @@ AttachmentData MyAvatar::loadAttachmentData(const QUrl& modelURL, const QString& return attachment; } - int MyAvatar::parseDataFromBuffer(const QByteArray& buffer) { qCDebug(interfaceapp) << "Error: ignoring update packet for MyAvatar" - << " packetLength = " << buffer.size(); + << " packetLength = " << buffer.size(); // this packet is just bad, so we pretend that we unpacked it ALL return buffer.size(); } @@ -2046,8 +2025,12 @@ ScriptAvatarData* MyAvatar::getTargetAvatar() const { } } -static float lookAtCostFunction(const glm::vec3& myForward, const glm::vec3& myPosition, const glm::vec3& otherForward, const glm::vec3& otherPosition, - bool otherIsTalking, bool lookingAtOtherAlready) { +static float lookAtCostFunction(const glm::vec3& myForward, + const glm::vec3& myPosition, + const glm::vec3& otherForward, + const glm::vec3& otherPosition, + bool otherIsTalking, + bool lookingAtOtherAlready) { const float DISTANCE_FACTOR = 3.14f; const float MY_ANGLE_FACTOR = 1.0f; const float OTHER_ANGLE_FACTOR = 1.0f; @@ -2055,7 +2038,7 @@ static float lookAtCostFunction(const glm::vec3& myForward, const glm::vec3& myP const float LOOKING_AT_OTHER_ALREADY_TERM = lookingAtOtherAlready ? -0.2f : 0.0f; const float GREATEST_LOOKING_AT_DISTANCE = 10.0f; // meters - const float MAX_MY_ANGLE = PI / 8.0f; // 22.5 degrees, Don't look too far away from the head facing. + const float MAX_MY_ANGLE = PI / 8.0f; // 22.5 degrees, Don't look too far away from the head facing. const float MAX_OTHER_ANGLE = (3.0f * PI) / 4.0f; // 135 degrees, Don't stare at the back of another avatars head. glm::vec3 d = otherPosition - myPosition; @@ -2067,11 +2050,8 @@ static float lookAtCostFunction(const glm::vec3& myForward, const glm::vec3& myP if (distance > GREATEST_LOOKING_AT_DISTANCE || myAngle > MAX_MY_ANGLE || otherAngle > MAX_OTHER_ANGLE) { return FLT_MAX; } else { - return (DISTANCE_FACTOR * distance + - MY_ANGLE_FACTOR * myAngle + - OTHER_ANGLE_FACTOR * otherAngle + - OTHER_IS_TALKING_TERM + - LOOKING_AT_OTHER_ALREADY_TERM); + return (DISTANCE_FACTOR * distance + MY_ANGLE_FACTOR * myAngle + OTHER_ANGLE_FACTOR * otherAngle + + OTHER_IS_TALKING_TERM + LOOKING_AT_OTHER_ALREADY_TERM); } } @@ -2094,7 +2074,8 @@ void MyAvatar::computeMyLookAtTarget(const AvatarHash& hash) { const float TIME_WITHOUT_TALKING_THRESHOLD = 1.0f; bool otherIsTalking = avatar->getHead()->getTimeWithoutTalking() <= TIME_WITHOUT_TALKING_THRESHOLD; bool lookingAtOtherAlready = _lookAtTargetAvatar.lock().get() == avatar.get(); - float cost = lookAtCostFunction(myForward, myPosition, otherForward, otherPosition, otherIsTalking, lookingAtOtherAlready); + float cost = + lookAtCostFunction(myForward, myPosition, otherForward, otherPosition, otherIsTalking, lookingAtOtherAlready); if (cost < bestCost) { bestCost = cost; bestAvatar = avatar; @@ -2115,9 +2096,8 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { std::shared_ptr avatar = std::static_pointer_cast(avatarData); if (!avatar->isMyAvatar() && avatar->isInitialized()) { if (_lookAtSnappingEnabled && avatar->getLookAtSnappingEnabled() && isLookingAtMe(avatar)) { - // Alter their gaze to look directly at my camera; this looks more natural than looking at my avatar's face. - glm::vec3 lookAtPosition = avatar->getHead()->getLookAtPosition(); // A position, in world space, on my avatar. + glm::vec3 lookAtPosition = avatar->getHead()->getLookAtPosition(); // A position, in world space, on my avatar. // The camera isn't at the point midway between the avatar eyes. (Even without an HMD, the head can be offset a bit.) // Let's get everything to world space: @@ -2128,12 +2108,12 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { // (We will be adding that offset to the camera position, after making some other adjustments.) glm::vec3 gazeOffset = lookAtPosition - getHead()->getEyePosition(); - ViewFrustum viewFrustum; - qApp->copyViewFrustum(viewFrustum); + ViewFrustum viewFrustum; + qApp->copyViewFrustum(viewFrustum); - glm::vec3 viewPosition = viewFrustum.getPosition(); + glm::vec3 viewPosition = viewFrustum.getPosition(); #if DEBUG_ALWAYS_LOOKAT_EYES_NOT_CAMERA - viewPosition = (avatarLeftEye + avatarRightEye) / 2.0f; + viewPosition = (avatarLeftEye + avatarRightEye) / 2.0f; #endif // scale gazeOffset by IPD, if wearing an HMD. if (qApp->isHMDMode()) { @@ -2171,7 +2151,6 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { } void MyAvatar::updateLookAtTargetAvatar() { - // The AvatarManager is a mutable class shared by many threads. We make a thread-safe deep copy of it, // to avoid having to hold a lock while we iterate over all the avatars within. AvatarHash hash = DependencyManager::get()->getHashCopy(); @@ -2285,8 +2264,7 @@ void MyAvatar::setJointTranslation(int index, const glm::vec3& translation) { } default: { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "setJointTranslation", - Q_ARG(int, index), Q_ARG(const glm::vec3&, translation)); + QMetaObject::invokeMethod(this, "setJointTranslation", Q_ARG(int, index), Q_ARG(const glm::vec3&, translation)); return; } // HACK: ATM only JS scripts call setJointData() on MyAvatar so we hardcode the priority @@ -2325,9 +2303,7 @@ void MyAvatar::setJointData(const QString& name, const glm::quat& rotation, cons Q_ARG(const glm::vec3&, translation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { - setJointData(index, rotation, translation); - }); + writeLockWithNamedJointIndex(name, [&](int index) { setJointData(index, rotation, translation); }); } void MyAvatar::setJointRotation(const QString& name, const glm::quat& rotation) { @@ -2335,9 +2311,7 @@ void MyAvatar::setJointRotation(const QString& name, const glm::quat& rotation) QMetaObject::invokeMethod(this, "setJointRotation", Q_ARG(QString, name), Q_ARG(const glm::quat&, rotation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { - setJointRotation(index, rotation); - }); + writeLockWithNamedJointIndex(name, [&](int index) { setJointRotation(index, rotation); }); } void MyAvatar::setJointTranslation(const QString& name, const glm::vec3& translation) { @@ -2345,9 +2319,7 @@ void MyAvatar::setJointTranslation(const QString& name, const glm::vec3& transla QMetaObject::invokeMethod(this, "setJointTranslation", Q_ARG(QString, name), Q_ARG(const glm::vec3&, translation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { - setJointTranslation(index, translation); - }); + writeLockWithNamedJointIndex(name, [&](int index) { setJointTranslation(index, translation); }); } void MyAvatar::clearJointData(const QString& name) { @@ -2355,9 +2327,7 @@ void MyAvatar::clearJointData(const QString& name) { QMetaObject::invokeMethod(this, "clearJointData", Q_ARG(QString, name)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { - clearJointData(index); - }); + writeLockWithNamedJointIndex(name, [&](int index) { clearJointData(index); }); } void MyAvatar::clearJointsData() { @@ -2392,36 +2362,36 @@ void MyAvatar::setSkeletonModelURL(const QUrl& skeletonModelURL) { _skeletonModelLoaded = false; std::shared_ptr skeletonConnection = std::make_shared(); - *skeletonConnection = QObject::connect(_skeletonModel.get(), &SkeletonModel::skeletonLoaded, [this, skeletonModelChangeCount, skeletonConnection]() { - if (skeletonModelChangeCount == _skeletonModelChangeCount) { + *skeletonConnection = QObject::connect(_skeletonModel.get(), &SkeletonModel::skeletonLoaded, + [this, skeletonModelChangeCount, skeletonConnection]() { + if (skeletonModelChangeCount == _skeletonModelChangeCount) { + if (_fullAvatarModelName.isEmpty()) { + // Store the FST file name into preferences + const auto& mapping = _skeletonModel->getGeometry()->getMapping(); + if (mapping.value("name").isValid()) { + _fullAvatarModelName = mapping.value("name").toString(); + } + } - if (_fullAvatarModelName.isEmpty()) { - // Store the FST file name into preferences - const auto& mapping = _skeletonModel->getGeometry()->getMapping(); - if (mapping.value("name").isValid()) { - _fullAvatarModelName = mapping.value("name").toString(); - } - } + initHeadBones(); + _skeletonModel->setCauterizeBoneSet(_headBoneSet); + _fstAnimGraphOverrideUrl = + _skeletonModel->getGeometry()->getAnimGraphOverrideUrl(); + initAnimGraph(); + initFlowFromFST(); - initHeadBones(); - _skeletonModel->setCauterizeBoneSet(_headBoneSet); - _fstAnimGraphOverrideUrl = _skeletonModel->getGeometry()->getAnimGraphOverrideUrl(); - initAnimGraph(); - initFlowFromFST(); + _skeletonModelLoaded = true; + } + QObject::disconnect(*skeletonConnection); + }); - _skeletonModelLoaded = true; - } - QObject::disconnect(*skeletonConnection); - }); - saveAvatarUrl(); emit skeletonChanged(); } bool isWearableEntity(const EntityItemPointer& entity) { - return entity->isVisible() - && (entity->getParentID() == DependencyManager::get()->getSessionUUID() - || entity->getParentID() == AVATAR_SELF_ID); + return entity->isVisible() && (entity->getParentID() == DependencyManager::get()->getSessionUUID() || + entity->getParentID() == AVATAR_SELF_ID); } void MyAvatar::removeWornAvatarEntity(const EntityItemID& entityID) { @@ -2445,9 +2415,7 @@ void MyAvatar::removeWornAvatarEntity(const EntityItemID& entityID) { void MyAvatar::clearWornAvatarEntities() { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { - avatarEntityIDs = _packedAvatarEntityData.keys(); - }); + _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); for (auto entityID : avatarEntityIDs) { removeWornAvatarEntity(entityID); } @@ -2473,9 +2441,7 @@ QVariantList MyAvatar::getAvatarEntitiesVariant() { EntityTreePointer entityTree = treeRenderer ? treeRenderer->getTree() : nullptr; if (entityTree) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { - avatarEntityIDs = _packedAvatarEntityData.keys(); - }); + _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); for (const auto& entityID : avatarEntityIDs) { auto entity = entityTree->findEntityByID(entityID); if (!entity) { @@ -2500,7 +2466,6 @@ QVariantList MyAvatar::getAvatarEntitiesVariant() { return avatarEntitiesData; } - void MyAvatar::resetFullAvatarURL() { auto lastAvatarURL = getFullAvatarURLFromPreferences(); auto lastAvatarName = getFullAvatarModelName(); @@ -2509,11 +2474,8 @@ void MyAvatar::resetFullAvatarURL() { } void MyAvatar::useFullAvatarURL(const QUrl& fullAvatarURL, const QString& modelName) { - if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "useFullAvatarURL", - Q_ARG(const QUrl&, fullAvatarURL), - Q_ARG(const QString&, modelName)); + BLOCKING_INVOKE_METHOD(this, "useFullAvatarURL", Q_ARG(const QUrl&, fullAvatarURL), Q_ARG(const QString&, modelName)); return; } @@ -2567,7 +2529,7 @@ controller::Pose MyAvatar::getControllerPoseInSensorFrame(controller::Action act if (iter != _controllerPoseMap.end()) { return iter->second; } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2576,7 +2538,7 @@ controller::Pose MyAvatar::getControllerPoseInWorldFrame(controller::Action acti if (pose.valid) { return pose.transform(getSensorToWorldMatrix()); } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2586,7 +2548,7 @@ controller::Pose MyAvatar::getControllerPoseInAvatarFrame(controller::Action act glm::mat4 invAvatarMatrix = glm::inverse(createMatFromQuatAndPos(getWorldOrientation(), getWorldPosition())); return pose.transform(invAvatarMatrix); } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2608,7 +2570,7 @@ void MyAvatar::updateMotors() { float verticalMotorTimescale; if (_characterController.getState() == CharacterController::State::Hover || - _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { + _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { horizontalMotorTimescale = FLYING_MOTOR_TIMESCALE; verticalMotorTimescale = FLYING_MOTOR_TIMESCALE; } else { @@ -2618,7 +2580,7 @@ void MyAvatar::updateMotors() { if (_motionBehaviors & AVATAR_MOTION_ACTION_MOTOR_ENABLED) { if (_characterController.getState() == CharacterController::State::Hover || - _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { + _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { motorRotation = getMyHead()->getHeadOrientation(); } else { // non-hovering = walking: follow camera twist about vertical but not lift @@ -2626,14 +2588,15 @@ void MyAvatar::updateMotors() { // however, we need to perform the decomposition in the avatar-frame // using the local UP axis and then transform back into world-frame glm::quat orientation = getWorldOrientation(); - glm::quat headOrientation = glm::inverse(orientation) * getMyHead()->getHeadOrientation(); // avatar-frame + glm::quat headOrientation = glm::inverse(orientation) * getMyHead()->getHeadOrientation(); // avatar-frame glm::quat liftRotation; swingTwistDecomposition(headOrientation, Vectors::UNIT_Y, liftRotation, motorRotation); motorRotation = orientation * motorRotation; } if (_isPushing || _isBraking || !_isBeingPushed) { - _characterController.addMotor(_actionMotorVelocity, motorRotation, horizontalMotorTimescale, verticalMotorTimescale); + _characterController.addMotor(_actionMotorVelocity, motorRotation, horizontalMotorTimescale, + verticalMotorTimescale); } else { // _isBeingPushed must be true --> disable action motor by giving it a long timescale, // otherwise it's attempt to "stand in in place" could defeat scripted motor/thrusts @@ -2653,7 +2616,8 @@ void MyAvatar::updateMotors() { _characterController.addMotor(_scriptedMotorVelocity, motorRotation, _scriptedMotorTimescale); } else { // dynamic mode - _characterController.addMotor(_scriptedMotorVelocity, motorRotation, horizontalMotorTimescale, verticalMotorTimescale); + _characterController.addMotor(_scriptedMotorVelocity, motorRotation, horizontalMotorTimescale, + verticalMotorTimescale); } } @@ -2758,8 +2722,7 @@ void MyAvatar::setScriptedMotorVelocity(const glm::vec3& velocity) { void MyAvatar::setScriptedMotorTimescale(float timescale) { // we clamp the timescale on the large side (instead of just the low side) to prevent // obnoxiously large values from introducing NaN into avatar's velocity - _scriptedMotorTimescale = glm::clamp(timescale, MIN_SCRIPTED_MOTOR_TIMESCALE, - DEFAULT_SCRIPTED_MOTOR_TIMESCALE); + _scriptedMotorTimescale = glm::clamp(timescale, MIN_SCRIPTED_MOTOR_TIMESCALE, DEFAULT_SCRIPTED_MOTOR_TIMESCALE); } void MyAvatar::setScriptedMotorFrame(QString frame) { @@ -2800,21 +2763,18 @@ SharedSoundPointer MyAvatar::getCollisionSound() { return _collisionSound; } -void MyAvatar::attach(const QString& modelURL, const QString& jointName, - const glm::vec3& translation, const glm::quat& rotation, - float scale, bool isSoft, - bool allowDuplicates, bool useSaved) { +void MyAvatar::attach(const QString& modelURL, + const QString& jointName, + const glm::vec3& translation, + const glm::quat& rotation, + float scale, + bool isSoft, + bool allowDuplicates, + bool useSaved) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "attach", - Q_ARG(const QString&, modelURL), - Q_ARG(const QString&, jointName), - Q_ARG(const glm::vec3&, translation), - Q_ARG(const glm::quat&, rotation), - Q_ARG(float, scale), - Q_ARG(bool, isSoft), - Q_ARG(bool, allowDuplicates), - Q_ARG(bool, useSaved) - ); + BLOCKING_INVOKE_METHOD(this, "attach", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName), + Q_ARG(const glm::vec3&, translation), Q_ARG(const glm::quat&, rotation), Q_ARG(float, scale), + Q_ARG(bool, isSoft), Q_ARG(bool, allowDuplicates), Q_ARG(bool, useSaved)); return; } AttachmentData data; @@ -2832,10 +2792,7 @@ void MyAvatar::attach(const QString& modelURL, const QString& jointName, void MyAvatar::detachOne(const QString& modelURL, const QString& jointName) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "detachOne", - Q_ARG(const QString&, modelURL), - Q_ARG(const QString&, jointName) - ); + BLOCKING_INVOKE_METHOD(this, "detachOne", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName)); return; } QUuid entityID; @@ -2847,10 +2804,7 @@ void MyAvatar::detachOne(const QString& modelURL, const QString& jointName) { void MyAvatar::detachAll(const QString& modelURL, const QString& jointName) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "detachAll", - Q_ARG(const QString&, modelURL), - Q_ARG(const QString&, jointName) - ); + BLOCKING_INVOKE_METHOD(this, "detachAll", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName)); return; } QUuid entityID; @@ -2862,8 +2816,7 @@ void MyAvatar::detachAll(const QString& modelURL, const QString& jointName) { void MyAvatar::setAttachmentData(const QVector& attachmentData) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "setAttachmentData", - Q_ARG(const QVector&, attachmentData)); + BLOCKING_INVOKE_METHOD(this, "setAttachmentData", Q_ARG(const QVector&, attachmentData)); return; } std::vector newEntitiesProperties; @@ -2886,12 +2839,10 @@ void MyAvatar::setAttachmentData(const QVector& attachmentData) emit attachmentsChanged(); } -QVector MyAvatar::getAttachmentData() const { +QVector MyAvatar::getAttachmentData() const { QVector attachmentData; QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { - avatarEntityIDs = _packedAvatarEntityData.keys(); - }); + _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); for (const auto& entityID : avatarEntityIDs) { auto properties = DependencyManager::get()->getEntityProperties(entityID); AttachmentData data = entityPropertiesToAttachmentData(properties); @@ -2910,8 +2861,7 @@ QVariantList MyAvatar::getAttachmentsVariant() const { void MyAvatar::setAttachmentsVariant(const QVariantList& variant) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "setAttachmentsVariant", - Q_ARG(const QVariantList&, variant)); + BLOCKING_INVOKE_METHOD(this, "setAttachmentsVariant", Q_ARG(const QVariantList&, variant)); return; } QVector newAttachments; @@ -2922,14 +2872,12 @@ void MyAvatar::setAttachmentsVariant(const QVariantList& variant) { newAttachments.append(attachment); } } - setAttachmentData(newAttachments); + setAttachmentData(newAttachments); } bool MyAvatar::findAvatarEntity(const QString& modelURL, const QString& jointName, QUuid& entityID) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { - avatarEntityIDs = _packedAvatarEntityData.keys(); - }); + _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); for (const auto& entityID : avatarEntityIDs) { auto props = DependencyManager::get()->getEntityProperties(entityID); if (props.getModelURL() == modelURL && @@ -3030,7 +2978,7 @@ void MyAvatar::setAnimGraphUrl(const QUrl& url) { emit animGraphUrlChanged(url); destroyAnimGraph(); - _skeletonModel->reset(); // Why is this necessary? Without this, we crash in the next render. + _skeletonModel->reset(); // Why is this necessary? Without this, we crash in the next render. _currentAnimGraphUrl.set(url); _skeletonModel->getRig().initAnimGraph(url); @@ -3063,18 +3011,16 @@ void MyAvatar::destroyAnimGraph() { } void MyAvatar::animGraphLoaded() { - _bodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. - updateSensorToWorldMatrix(); // Uses updated position/orientation and _bodySensorMatrix changes + _bodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + updateSensorToWorldMatrix(); // Uses updated position/orientation and _bodySensorMatrix changes _isAnimatingScale = true; _cauterizationNeedsUpdate = true; disconnect(&(_skeletonModel->getRig()), SIGNAL(onLoadComplete()), this, SLOT(animGraphLoaded())); } void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { - Avatar::postUpdate(deltaTime, scene); if (_enableDebugDrawDefaultPose || _enableDebugDrawAnimPose) { - auto animSkeleton = _skeletonModel->getRig().getAnimSkeleton(); // the rig is in the skeletonModel frame @@ -3082,7 +3028,8 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { if (_enableDebugDrawDefaultPose && animSkeleton) { glm::vec4 gray(0.2f, 0.2f, 0.2f, 0.2f); - AnimDebugDraw::getInstance().addAbsolutePoses("myAvatarDefaultPoses", animSkeleton, _skeletonModel->getRig().getAbsoluteDefaultPoses(), xform, gray); + AnimDebugDraw::getInstance().addAbsolutePoses("myAvatarDefaultPoses", animSkeleton, + _skeletonModel->getRig().getAbsoluteDefaultPoses(), xform, gray); } if (_enableDebugDrawAnimPose && animSkeleton) { @@ -3103,13 +3050,15 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { auto rightHandPose = getControllerPoseInWorldFrame(controller::Action::RIGHT_HAND); if (leftHandPose.isValid()) { - DebugDraw::getInstance().addMarker("leftHandController", leftHandPose.getRotation(), leftHandPose.getTranslation(), glm::vec4(1)); + DebugDraw::getInstance().addMarker("leftHandController", leftHandPose.getRotation(), leftHandPose.getTranslation(), + glm::vec4(1)); } else { DebugDraw::getInstance().removeMarker("leftHandController"); } if (rightHandPose.isValid()) { - DebugDraw::getInstance().addMarker("rightHandController", rightHandPose.getRotation(), rightHandPose.getTranslation(), glm::vec4(1)); + DebugDraw::getInstance().addMarker("rightHandController", rightHandPose.getRotation(), + rightHandPose.getTranslation(), glm::vec4(1)); } else { DebugDraw::getInstance().removeMarker("rightHandController"); } @@ -3126,14 +3075,9 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { AnimPose rigToWorldPose(glm::vec3(1.0f), getWorldOrientation() * Quaternions::Y_180, getWorldPosition()); const int NUM_DEBUG_COLORS = 8; const glm::vec4 DEBUG_COLORS[NUM_DEBUG_COLORS] = { - glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), - glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), - glm::vec4(0.0f, 1.0f, 0.0f, 1.0f), - glm::vec4(0.25f, 0.25f, 1.0f, 1.0f), - glm::vec4(1.0f, 1.0f, 0.0f, 1.0f), - glm::vec4(0.25f, 1.0f, 1.0f, 1.0f), - glm::vec4(1.0f, 0.25f, 1.0f, 1.0f), - glm::vec4(1.0f, 0.65f, 0.0f, 1.0f) // Orange you glad I added this color? + glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 1.0f), + glm::vec4(0.25f, 0.25f, 1.0f, 1.0f), glm::vec4(1.0f, 1.0f, 0.0f, 1.0f), glm::vec4(0.25f, 1.0f, 1.0f, 1.0f), + glm::vec4(1.0f, 0.25f, 1.0f, 1.0f), glm::vec4(1.0f, 0.65f, 0.0f, 1.0f) // Orange you glad I added this color? }; if (_skeletonModel && _skeletonModel->isLoaded()) { @@ -3144,7 +3088,7 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { AnimPose jointPose; rig.getAbsoluteJointPoseInRigFrame(i, jointPose); const AnimPose pose = rigToWorldPose * jointPose; - auto &multiSphere = _multiSphereShapes[i]; + auto& multiSphere = _multiSphereShapes[i]; auto debugLines = multiSphere.getDebugLines(); DebugDraw::getInstance().drawRays(debugLines, DEBUG_COLORS[i % NUM_DEBUG_COLORS], pose.trans(), pose.rot()); } @@ -3154,7 +3098,6 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { } void MyAvatar::preDisplaySide(const RenderArgs* renderArgs) { - // toggle using the cauterizedBones depending on where the camera is and the rendering pass type. const bool shouldDrawHead = shouldRenderHead(renderArgs); if (shouldDrawHead != _prevShouldDrawHead) { @@ -3199,7 +3142,7 @@ int MyAvatar::sendAvatarDataPacket(bool sendAll) { // Compute the next send window based on how much data we sent and what // data rate we're trying to max at. - milliseconds timeUntilNextSend { bytesSent / maxDataRateBytesPerMilliseconds }; + milliseconds timeUntilNextSend{ bytesSent / maxDataRateBytesPerMilliseconds }; _nextTraitsSendWindow += timeUntilNextSend; // Don't let the next send window lag behind if we're not sending a lot of data. @@ -3284,7 +3227,6 @@ void MyAvatar::setRotationThreshold(float angleRadians) { } void MyAvatar::updateOrientation(float deltaTime) { - // Smoothly rotate body with arrow keys float targetSpeed = getDriveKey(YAW) * _yawSpeed; if (targetSpeed != 0.0f) { @@ -3323,8 +3265,8 @@ void MyAvatar::updateOrientation(float deltaTime) { } // Use head/HMD roll to turn while flying, but not when standing still. - if (qApp->isHMDMode() && getCharacterController()->getState() == CharacterController::State::Hover && _hmdRollControlEnabled && hasDriveInput()) { - + if (qApp->isHMDMode() && getCharacterController()->getState() == CharacterController::State::Hover && + _hmdRollControlEnabled && hasDriveInput()) { // Turn with head roll. const float MIN_CONTROL_SPEED = 2.0f * getSensorToWorldScale(); // meters / sec const glm::vec3 characterForward = getWorldOrientation() * Vectors::UNIT_NEG_Z; @@ -3332,7 +3274,6 @@ void MyAvatar::updateOrientation(float deltaTime) { // only enable roll-turns if we are moving forward or backward at greater then MIN_CONTROL_SPEED if (fabsf(forwardSpeed) >= MIN_CONTROL_SPEED) { - float direction = forwardSpeed > 0.0f ? 1.0f : -1.0f; float rollAngle = glm::degrees(asinf(glm::dot(IDENTITY_UP, _hmdSensorOrientation * IDENTITY_RIGHT))); float rollSign = rollAngle < 0.0f ? -1.0f : 1.0f; @@ -3379,8 +3320,8 @@ void MyAvatar::updateOrientation(float deltaTime) { head->setBaseRoll(ROLL(euler)); } else { head->setBaseYaw(0.0f); - head->setBasePitch(getHead()->getBasePitch() + getDriveKey(PITCH) * _pitchSpeed * deltaTime - + getDriveKey(DELTA_PITCH) * _pitchSpeed / PITCH_SPEED_DEFAULT); + head->setBasePitch(getHead()->getBasePitch() + getDriveKey(PITCH) * _pitchSpeed * deltaTime + + getDriveKey(DELTA_PITCH) * _pitchSpeed / PITCH_SPEED_DEFAULT); head->setBaseRoll(0.0f); } } @@ -3390,20 +3331,15 @@ float MyAvatar::calculateGearedSpeed(const float driveKey) { float sign = (driveKey < 0.0f) ? -1.0f : 1.0f; if (absDriveKey > getDriveGear5()) { return sign * 1.0f; - } - else if (absDriveKey > getDriveGear4()) { + } else if (absDriveKey > getDriveGear4()) { return sign * 0.8f; - } - else if (absDriveKey > getDriveGear3()) { + } else if (absDriveKey > getDriveGear3()) { return sign * 0.6f; - } - else if (absDriveKey > getDriveGear2()) { + } else if (absDriveKey > getDriveGear2()) { return sign * 0.4f; - } - else if (absDriveKey > getDriveGear1()) { + } else if (absDriveKey > getDriveGear1()) { return sign * 0.2f; - } - else { + } else { return sign * 0.0f; } } @@ -3435,8 +3371,10 @@ glm::vec3 MyAvatar::scaleMotorSpeed(const glm::vec3 forward, const glm::vec3 rig case LocomotionControlsMode::CONTROLS_ANALOG: case LocomotionControlsMode::CONTROLS_ANALOG_PLUS: if (zSpeed || xSpeed) { - glm::vec3 scaledForward = getSensorToWorldScale() * calculateGearedSpeed(zSpeed) * _walkSpeedScalar * ((zSpeed >= stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * forward; - glm::vec3 scaledRight = getSensorToWorldScale() * calculateGearedSpeed(xSpeed) * _walkSpeedScalar * ((xSpeed > stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * right; + glm::vec3 scaledForward = getSensorToWorldScale() * calculateGearedSpeed(zSpeed) * _walkSpeedScalar * + ((zSpeed >= stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * forward; + glm::vec3 scaledRight = getSensorToWorldScale() * calculateGearedSpeed(xSpeed) * _walkSpeedScalar * + ((xSpeed > stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * right; direction = scaledForward + scaledRight; return direction; } else { @@ -3458,7 +3396,7 @@ glm::vec3 MyAvatar::scaleMotorSpeed(const glm::vec3 forward, const glm::vec3 rig } } -glm::vec3 MyAvatar::calculateScaledDirection(){ +glm::vec3 MyAvatar::calculateScaledDirection() { CharacterController::State state = _characterController.getState(); // compute action input @@ -3514,8 +3452,8 @@ glm::vec3 MyAvatar::calculateScaledDirection(){ void MyAvatar::updateActionMotor(float deltaTime) { bool thrustIsPushing = (glm::length2(_thrust) > EPSILON); - bool scriptedMotorIsPushing = (_motionBehaviors & AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED) - && _scriptedMotorTimescale < MAX_CHARACTER_MOTOR_TIMESCALE; + bool scriptedMotorIsPushing = + (_motionBehaviors & AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED) && _scriptedMotorTimescale < MAX_CHARACTER_MOTOR_TIMESCALE; _isBeingPushed = thrustIsPushing || scriptedMotorIsPushing; if (_isPushing || _isBeingPushed) { // we don't want the motor to brake if a script is pushing the avatar around @@ -3545,7 +3483,7 @@ void MyAvatar::updateActionMotor(float deltaTime) { float motorSpeed = glm::length(_actionMotorVelocity); float finalMaxMotorSpeed = sensorToWorldScale * DEFAULT_AVATAR_MAX_FLYING_SPEED * _walkSpeedScalar; - float speedGrowthTimescale = 2.0f; + float speedGrowthTimescale = 2.0f; float speedIncreaseFactor = 1.8f * _walkSpeedScalar; motorSpeed *= 1.0f + glm::clamp(deltaTime / speedGrowthTimescale, 0.0f, 1.0f) * speedIncreaseFactor; const float maxBoostSpeed = sensorToWorldScale * MAX_BOOST_SPEED; @@ -3585,7 +3523,7 @@ void MyAvatar::updatePosition(float deltaTime) { float sensorToWorldScale2 = sensorToWorldScale * sensorToWorldScale; vec3 velocity = getWorldVelocity(); float speed2 = glm::length2(velocity); - const float MOVING_SPEED_THRESHOLD_SQUARED = 0.0001f; // 0.01 m/s + const float MOVING_SPEED_THRESHOLD_SQUARED = 0.0001f; // 0.01 m/s _moving = speed2 > sensorToWorldScale2 * MOVING_SPEED_THRESHOLD_SQUARED; if (_moving) { // scan for walkability @@ -3610,12 +3548,17 @@ void MyAvatar::updateViewBoom() { } } -void MyAvatar::updateCollisionSound(const glm::vec3 &penetration, float deltaTime, float frequency) { +void MyAvatar::updateCollisionSound(const glm::vec3& penetration, float deltaTime, float frequency) { // COLLISION SOUND API in Audio has been removed } -bool findAvatarAvatarPenetration(const glm::vec3 positionA, float radiusA, float heightA, - const glm::vec3 positionB, float radiusB, float heightB, glm::vec3& penetration) { +bool findAvatarAvatarPenetration(const glm::vec3 positionA, + float radiusA, + float heightA, + const glm::vec3 positionB, + float radiusB, + float heightB, + glm::vec3& penetration) { glm::vec3 positionBA = positionB - positionA; float xzDistance = sqrt(positionBA.x * positionBA.x + positionBA.z * positionBA.z); if (xzDistance < (radiusA + radiusB)) { @@ -3677,9 +3620,7 @@ void MyAvatar::setSessionUUID(const QUuid& sessionUUID) { EntityTreePointer entityTree = treeRenderer ? treeRenderer->getTree() : nullptr; if (entityTree) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { - avatarEntityIDs = _packedAvatarEntityData.keys(); - }); + _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); bool sendPackets = !DependencyManager::get()->getSessionUUID().isNull(); EntityEditPacketSender* packetSender = qApp->getEntityEditPacketSender(); entityTree->withWriteLock([&] { @@ -3823,16 +3764,18 @@ void MyAvatar::goToLocation(const QVariant& propertiesVar) { } void MyAvatar::goToFeetLocation(const glm::vec3& newPosition, - bool hasOrientation, const glm::quat& newOrientation, + bool hasOrientation, + const glm::quat& newOrientation, bool shouldFaceLocation) { _goToFeetAjustment = true; goToLocation(newPosition, hasOrientation, newOrientation, shouldFaceLocation); } void MyAvatar::goToLocation(const glm::vec3& newPosition, - bool hasOrientation, const glm::quat& newOrientation, - bool shouldFaceLocation, bool withSafeLanding) { - + bool hasOrientation, + const glm::quat& newOrientation, + bool shouldFaceLocation, + bool withSafeLanding) { // Most cases of going to a place or user go through this now. Some possible improvements to think about in the future: // - It would be nice if this used the same teleport steps and smoothing as in the teleport.js script, as long as it // still worked if the target is in the air. @@ -3846,16 +3789,16 @@ void MyAvatar::goToLocation(const glm::vec3& newPosition, // compute the position (e.g., so that if I'm on stage, going to me would compute an available seat in the audience rather than // being in my face on-stage). Note that this could work for going to an entity as well as to a person. - qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - moving to " << newPosition.x << ", " - << newPosition.y << ", " << newPosition.z; + qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - moving to " << newPosition.x << ", " << newPosition.y << ", " + << newPosition.z; _goToPending = true; _goToPosition = newPosition; _goToSafe = withSafeLanding; _goToOrientation = getWorldOrientation(); if (hasOrientation) { - qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - new orientation is " - << newOrientation.x << ", " << newOrientation.y << ", " << newOrientation.z << ", " << newOrientation.w; + qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - new orientation is " << newOrientation.x << ", " + << newOrientation.y << ", " << newOrientation.z << ", " << newOrientation.w; // orient the user to face the target glm::quat quatOrientation = cancelOutRollAndPitch(newOrientation); @@ -3874,7 +3817,7 @@ void MyAvatar::goToLocation(const glm::vec3& newPosition, emit transformChanged(); } -void MyAvatar::goToLocationAndEnableCollisions(const glm::vec3& position) { // See use case in safeLanding. +void MyAvatar::goToLocationAndEnableCollisions(const glm::vec3& position) { // See use case in safeLanding. goToLocation(position); QMetaObject::invokeMethod(this, "setCollisionsEnabled", Qt::QueuedConnection, Q_ARG(bool, true)); } @@ -3900,29 +3843,29 @@ bool MyAvatar::safeLanding(const glm::vec3& position) { } if (!getCollisionsEnabled()) { goToLocation(better); // recurses on next update - } else { // If you try to go while stuck, physics will keep you stuck. + } else { // If you try to go while stuck, physics will keep you stuck. setCollisionsEnabled(false); // Don't goToLocation just yet. Yield so that physics can act on the above. - QMetaObject::invokeMethod(this, "goToLocationAndEnableCollisions", Qt::QueuedConnection, // The equivalent of javascript nextTick - Q_ARG(glm::vec3, better)); - } - return true; + QMetaObject::invokeMethod(this, "goToLocationAndEnableCollisions", + Qt::QueuedConnection, // The equivalent of javascript nextTick + Q_ARG(glm::vec3, better)); + } + return true; } // If position is not reliably safe from being stuck by physics, answer true and place a candidate better position in betterPositionOut. bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& betterPositionOut) { - // We begin with utilities and tests. The Algorithm in four parts is below. // NOTE: we use estimated avatar height here instead of the bullet capsule halfHeight, because // the domain avatar height limiting might not have taken effect yet on the actual bullet shape. auto halfHeight = 0.5f * getHeight(); if (halfHeight == 0) { - return false; // zero height avatar + return false; // zero height avatar } auto entityTree = DependencyManager::get()->getTree(); if (!entityTree) { - return false; // no entity tree + return false; // no entity tree } // More utilities. const auto capsuleCenter = positionIn; @@ -3934,21 +3877,26 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette betterPositionOut = upperIntersection + (up * halfHeight); return true; }; - auto findIntersection = [&](const glm::vec3& startPointIn, const glm::vec3& directionIn, glm::vec3& intersectionOut, EntityItemID& entityIdOut, glm::vec3& normalOut) { + auto findIntersection = [&](const glm::vec3& startPointIn, const glm::vec3& directionIn, glm::vec3& intersectionOut, + EntityItemID& entityIdOut, glm::vec3& normalOut) { OctreeElementPointer element; float distance; BoxFace face; - const auto lockType = Octree::Lock; // Should we refactor to take a lock just once? + const auto lockType = Octree::Lock; // Should we refactor to take a lock just once? bool* accurateResult = NULL; // This isn't quite what we really want here. findRayIntersection always works on mesh, skipping entirely based on collidable. // What we really want is to use the collision hull! // See https://highfidelity.fogbugz.com/f/cases/5003/findRayIntersection-has-option-to-use-collidableOnly-but-doesn-t-actually-use-colliders QVariantMap extraInfo; - EntityItemID entityID = entityTree->evalRayIntersection(startPointIn, directionIn, include, ignore, - PickFilter(PickFilter::getBitMask(PickFilter::FlagBit::COLLIDABLE) | PickFilter::getBitMask(PickFilter::FlagBit::PRECISE) - | PickFilter::getBitMask(PickFilter::FlagBit::DOMAIN_ENTITIES) | PickFilter::getBitMask(PickFilter::FlagBit::AVATAR_ENTITIES)), // exclude Local entities - element, distance, face, normalOut, extraInfo, lockType, accurateResult); + EntityItemID entityID = + entityTree->evalRayIntersection(startPointIn, directionIn, include, ignore, + PickFilter(PickFilter::getBitMask(PickFilter::FlagBit::COLLIDABLE) | + PickFilter::getBitMask(PickFilter::FlagBit::PRECISE) | + PickFilter::getBitMask(PickFilter::FlagBit::DOMAIN_ENTITIES) | + PickFilter::getBitMask( + PickFilter::FlagBit::AVATAR_ENTITIES)), // exclude Local entities + element, distance, face, normalOut, extraInfo, lockType, accurateResult); if (entityID.isNull()) { return false; } @@ -3963,12 +3911,12 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette // We currently believe that physics will reliably push us out if our feet are embedded, // as long as our capsule center is out and there's room above us. Here we have those // conditions, so no need to check our feet below. - return false; // nothing above + return false; // nothing above } if (!findIntersection(capsuleCenter, down, lowerIntersection, lowerId, lowerNormal)) { // Our head may be embedded, but our center is out and there's room below. See corresponding comment above. - return false; // nothing below + return false; // nothing below } // See if we have room between entities above and below, but that we are not contained. @@ -3976,7 +3924,8 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette // I.e., we are in a clearing between two objects. if (isDown(upperNormal) && isUp(lowerNormal)) { auto spaceBetween = glm::distance(upperIntersection, lowerIntersection); - const float halfHeightFactor = 2.25f; // Until case 5003 is fixed (and maybe after?), we need a fudge factor. Also account for content modelers not being precise. + const float halfHeightFactor = + 2.25f; // Until case 5003 is fixed (and maybe after?), we need a fudge factor. Also account for content modelers not being precise. if (spaceBetween > (halfHeightFactor * halfHeight)) { // There is room for us to fit in that clearing. If there wasn't, physics would oscilate us between the objects above and below. // We're now going to iterate upwards through successive upperIntersections, testing to see if we're contained within the top surface of some entity. @@ -3988,7 +3937,7 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette ignore.push_back(upperId); if (!findIntersection(upperIntersection, up, upperIntersection, upperId, upperNormal)) { // We're not inside an entity, and from the nested tests, we have room between what is above and below. So position is good! - return false; // enough room + return false; // enough room } if (isUp(upperNormal)) { // This new intersection is the top surface of an entity that we have not yet seen, which means we're contained within it. @@ -4003,19 +3952,18 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette } } - include.push_back(upperId); // We're now looking for the intersection from above onto this entity. + include.push_back(upperId); // We're now looking for the intersection from above onto this entity. const float big = (float)TREE_SCALE; const auto skyHigh = up * big; auto fromAbove = capsuleCenter + skyHigh; if (!findIntersection(fromAbove, down, upperIntersection, upperId, upperNormal)) { - return false; // Unable to find a landing + return false; // Unable to find a landing } // Our arbitrary rule is to always go up. There's no need to look down or sideways for a "closer" safe candidate. return mustMove(); } void MyAvatar::updateMotionBehaviorFromMenu() { - if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "updateMotionBehaviorFromMenu"); return; @@ -4099,7 +4047,7 @@ int MyAvatar::getMovementReference() { return _movementReference; } -void MyAvatar::setControlSchemeIndex(int index){ +void MyAvatar::setControlSchemeIndex(int index) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setControlSchemeIndex", Q_ARG(int, index)); return; @@ -4117,7 +4065,8 @@ void MyAvatar::setDriveGear1(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear1", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) + return; _driveGear1 = (shiftPoint < _driveGear2) ? shiftPoint : _driveGear1; } @@ -4138,7 +4087,8 @@ void MyAvatar::setDriveGear2(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear2", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) + return; _driveGear2 = (shiftPoint < _driveGear3 && shiftPoint >= _driveGear1) ? shiftPoint : _driveGear2; } @@ -4159,7 +4109,8 @@ void MyAvatar::setDriveGear3(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear3", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) + return; _driveGear3 = (shiftPoint < _driveGear4 && shiftPoint >= _driveGear2) ? shiftPoint : _driveGear3; } @@ -4180,7 +4131,8 @@ void MyAvatar::setDriveGear4(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear4", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) + return; _driveGear4 = (shiftPoint < _driveGear5 && shiftPoint >= _driveGear3) ? shiftPoint : _driveGear4; } @@ -4201,7 +4153,8 @@ void MyAvatar::setDriveGear5(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear5", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) + return; _driveGear5 = (shiftPoint > _driveGear4) ? shiftPoint : _driveGear5; } @@ -4227,7 +4180,6 @@ float MyAvatar::getAvatarScale() { } void MyAvatar::setAvatarScale(float val) { - if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setAvatarScale", Q_ARG(float, val)); return; @@ -4237,7 +4189,6 @@ void MyAvatar::setAvatarScale(float val) { } void MyAvatar::setCollisionsEnabled(bool enabled) { - if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setCollisionsEnabled", Q_ARG(bool, enabled)); return; @@ -4253,7 +4204,6 @@ bool MyAvatar::getCollisionsEnabled() { } void MyAvatar::setOtherAvatarsCollisionsEnabled(bool enabled) { - if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setOtherAvatarsCollisionsEnabled", Q_ARG(bool, enabled)); return; @@ -4409,7 +4359,7 @@ glm::mat4 MyAvatar::deriveBodyFromHMDSensor() const { // AJT: TODO: can remove this Y_180, if we remove the higher level one. glm::vec3 headToNeck = headOrientation * Quaternions::Y_180 * (localNeck - localHead); - glm::vec3 neckToRoot = headOrientationYawOnly * Quaternions::Y_180 * -localNeck; + glm::vec3 neckToRoot = headOrientationYawOnly * Quaternions::Y_180 * -localNeck; float invSensorToWorldScale = getUserEyeHeight() / getEyeHeight(); glm::vec3 bodyPos = headPosition + invSensorToWorldScale * (headToNeck + neckToRoot); @@ -4445,7 +4395,8 @@ glm::mat4 MyAvatar::getSpine2RotationRigSpace() const { spine2UpRigSpace = glm::vec3(0.0f, 1.0f, 0.0f); } generateBasisVectors(spine2UpRigSpace, spine2FwdRigSpace, u, v, w); - glm::mat4 spine2RigSpace(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), glm::vec4(glm::vec3(0.0f, 0.0f, 0.0f), 1.0f)); + glm::mat4 spine2RigSpace(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), + glm::vec4(glm::vec3(0.0f, 0.0f, 0.0f), 1.0f)); return spine2RigSpace; } @@ -4502,7 +4453,7 @@ glm::vec3 MyAvatar::computeCounterBalance() { QString name; float weight; glm::vec3 position; - JointMass() {}; + JointMass(){}; JointMass(QString n, float w, glm::vec3 p) { name = n; weight = w; @@ -4523,12 +4474,14 @@ glm::vec3 MyAvatar::computeCounterBalance() { tposeHead = getAbsoluteDefaultJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgHeadMass.name)); } if (_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name) != -1) { - cgLeftHandMass.position = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name)); + cgLeftHandMass.position = + getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name)); } else { cgLeftHandMass.position = DEFAULT_AVATAR_LEFTHAND_POS; } if (_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name) != -1) { - cgRightHandMass.position = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name)); + cgRightHandMass.position = + getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name)); } else { cgRightHandMass.position = DEFAULT_AVATAR_RIGHTHAND_POS; } @@ -4540,7 +4493,8 @@ glm::vec3 MyAvatar::computeCounterBalance() { } // find the current center of gravity position based on head and hand moments - glm::vec3 sumOfMoments = (cgHeadMass.weight * cgHeadMass.position) + (cgLeftHandMass.weight * cgLeftHandMass.position) + (cgRightHandMass.weight * cgRightHandMass.position); + glm::vec3 sumOfMoments = (cgHeadMass.weight * cgHeadMass.position) + (cgLeftHandMass.weight * cgLeftHandMass.position) + + (cgRightHandMass.weight * cgRightHandMass.position); float totalMass = cgHeadMass.weight + cgLeftHandMass.weight + cgRightHandMass.weight; glm::vec3 currentCg = (1.0f / totalMass) * sumOfMoments; @@ -4580,7 +4534,6 @@ glm::vec3 MyAvatar::computeCounterBalance() { // headOrientation, headPosition and hipsPosition are in avatar space // returns the matrix of the hips in Avatar space static glm::mat4 computeNewHipsMatrix(glm::quat headOrientation, glm::vec3 headPosition, glm::vec3 hipsPosition) { - glm::quat bodyOrientation = computeBodyFacingFromHead(headOrientation, Vectors::UNIT_Y); const float MIX_RATIO = 0.3f; @@ -4590,10 +4543,7 @@ static glm::mat4 computeNewHipsMatrix(glm::quat headOrientation, glm::vec3 headP glm::vec3 spineVec = headPosition - hipsPosition; glm::vec3 u, v, w; generateBasisVectors(glm::normalize(spineVec), hipsFacing, u, v, w); - return glm::mat4(glm::vec4(w, 0.0f), - glm::vec4(u, 0.0f), - glm::vec4(v, 0.0f), - glm::vec4(hipsPosition, 1.0f)); + return glm::mat4(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), glm::vec4(hipsPosition, 1.0f)); } static void drawBaseOfSupport(float baseOfSupportScale, float footLocal, glm::mat4 avatarToWorld) { @@ -4634,7 +4584,8 @@ glm::mat4 MyAvatar::deriveBodyUsingCgModel() { if (_enableDebugDrawBaseOfSupport) { float scaleBaseOfSupport = getUserEyeHeight() / DEFAULT_AVATAR_EYE_HEIGHT; - glm::vec3 rightFootPositionLocal = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint("RightFoot")); + glm::vec3 rightFootPositionLocal = + getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint("RightFoot")); drawBaseOfSupport(scaleBaseOfSupport, rightFootPositionLocal.y, avatarToWorldMat); } @@ -4642,7 +4593,8 @@ glm::mat4 MyAvatar::deriveBodyUsingCgModel() { glm::vec3 cgHipsPosition = computeCounterBalance(); // find the new hips rotation using the new head-hips axis as the up axis - glm::mat4 avatarHipsMat = computeNewHipsMatrix(glmExtractRotation(avatarHeadMat), extractTranslation(avatarHeadMat), cgHipsPosition); + glm::mat4 avatarHipsMat = + computeNewHipsMatrix(glmExtractRotation(avatarHeadMat), extractTranslation(avatarHeadMat), cgHipsPosition); // convert hips from avatar to sensor space // The Y_180 is to convert from z forward to -z forward. @@ -4666,7 +4618,7 @@ static bool withinBaseOfSupport(const controller::Pose& head) { bool withinFrontBase = isInsideLine(userScale * frontLeft, userScale * frontRight, head.getTranslation()); bool withinBackBase = isInsideLine(userScale * backRight, userScale * backLeft, head.getTranslation()); bool withinLateralBase = (isInsideLine(userScale * frontRight, userScale * backRight, head.getTranslation()) && - isInsideLine(userScale * backLeft, userScale * frontLeft, head.getTranslation())); + isInsideLine(userScale * backLeft, userScale * frontLeft, head.getTranslation())); isWithinSupport = (withinFrontBase && withinBackBase && withinLateralBase); } return isWithinSupport; @@ -4700,7 +4652,8 @@ float MyAvatar::computeStandingHeightMode(const controller::Pose& head) { float modeInMeters = getCurrentStandingHeight(); if (head.isValid()) { std::map freq; - for(auto recentModeReadingsIterator = _recentModeReadings.begin(); recentModeReadingsIterator != _recentModeReadings.end(); ++recentModeReadingsIterator) { + for (auto recentModeReadingsIterator = _recentModeReadings.begin(); + recentModeReadingsIterator != _recentModeReadings.end(); ++recentModeReadingsIterator) { freq[*recentModeReadingsIterator] += 1; if (freq[*recentModeReadingsIterator] > greatestFrequency) { greatestFrequency = freq[*recentModeReadingsIterator]; @@ -4713,21 +4666,23 @@ float MyAvatar::computeStandingHeightMode(const controller::Pose& head) { // if not greater check for a reset if (getResetMode() && getControllerPoseInAvatarFrame(controller::Action::HEAD).isValid()) { setResetMode(false); - float resetModeInCentimeters = glm::floor((head.getTranslation().y - MODE_CORRECTION_FACTOR)*CENTIMETERS_PER_METER); + float resetModeInCentimeters = + glm::floor((head.getTranslation().y - MODE_CORRECTION_FACTOR) * CENTIMETERS_PER_METER); modeInMeters = (resetModeInCentimeters / CENTIMETERS_PER_METER); _recentModeReadings.clear(); } else { // if not greater and no reset, keep the mode as it is modeInMeters = getCurrentStandingHeight(); - } } } return modeInMeters; } -static bool handDirectionMatchesHeadDirection(const controller::Pose& leftHand, const controller::Pose& rightHand, const controller::Pose& head) { +static bool handDirectionMatchesHeadDirection(const controller::Pose& leftHand, + const controller::Pose& rightHand, + const controller::Pose& head) { const float VELOCITY_EPSILON = 0.02f; bool leftHandDirectionMatchesHead = true; bool rightHandDirectionMatchesHead = true; @@ -4765,7 +4720,7 @@ static bool handAngularVelocityBelowThreshold(const controller::Pose& leftHand, rightHandXZAngularVelocity = glm::length(xzRightHandAngularVelocity); } return ((leftHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD) && - (rightHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD)); + (rightHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD)); } static bool headVelocityGreaterThanThreshold(const controller::Pose& head) { @@ -4788,7 +4743,8 @@ static bool isHeadLevel(const controller::Pose& head, const glm::quat& averageHe glm::vec3 currentHeadEulers = glm::degrees(safeEulerAngles(head.getRotation())); diffFromAverageEulers = averageHeadEulers - currentHeadEulers; } - return ((fabs(diffFromAverageEulers.x) < DEFAULT_HEAD_PITCH_STEPPING_TOLERANCE) && (fabs(diffFromAverageEulers.z) < DEFAULT_HEAD_ROLL_STEPPING_TOLERANCE)); + return ((fabs(diffFromAverageEulers.x) < DEFAULT_HEAD_PITCH_STEPPING_TOLERANCE) && + (fabs(diffFromAverageEulers.z) < DEFAULT_HEAD_ROLL_STEPPING_TOLERANCE)); } float MyAvatar::getUserHeight() const { @@ -4838,7 +4794,6 @@ float MyAvatar::getWalkSpeed() const { } else { return _defaultWalkSpeed.get(); } - } float MyAvatar::getWalkBackwardSpeed() const { @@ -4855,7 +4810,6 @@ float MyAvatar::getWalkBackwardSpeed() const { } else { return _defaultWalkBackwardSpeed.get(); } - } bool MyAvatar::isReadyForPhysics() const { @@ -4865,8 +4819,7 @@ bool MyAvatar::isReadyForPhysics() const { void MyAvatar::setSprintMode(bool sprint) { if (qApp->isHMDMode()) { _walkSpeedScalar = sprint ? AVATAR_DESKTOP_SPRINT_SPEED_SCALAR : AVATAR_WALK_SPEED_SCALAR; - } - else { + } else { _walkSpeedScalar = sprint ? AVATAR_HMD_SPRINT_SPEED_SCALAR : AVATAR_WALK_SPEED_SCALAR; } } @@ -4890,7 +4843,6 @@ void MyAvatar::setIsInSittingState(bool isSitting) { } void MyAvatar::setUserRecenterModel(MyAvatar::SitStandModelType modelName) { - _userRecenterModel.set(modelName); switch (modelName) { @@ -4966,7 +4918,7 @@ void MyAvatar::setWalkBackwardSpeed(float value) { changed = false; break; } - + if (changed && prevVal != value) { emit walkBackwardSpeedChanged(value); } @@ -4989,6 +4941,7 @@ void MyAvatar::setSprintSpeed(float value) { _analogPlusSprintSpeed.set(value); break; default: + changed = false; break; } @@ -5136,7 +5089,6 @@ void driveKeysFromScriptValue(const QScriptValue& object, MyAvatar::DriveKeys& d driveKeys = static_cast(object.toUInt16()); } - void MyAvatar::lateUpdatePalms() { Avatar::updatePalms(); } @@ -5194,13 +5146,17 @@ void MyAvatar::FollowHelper::decrementTimeRemaining(float dt) { } } -bool MyAvatar::FollowHelper::shouldActivateRotation(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateRotation(const MyAvatar& myAvatar, + const glm::mat4& desiredBodyMatrix, + const glm::mat4& currentBodyMatrix) const { const float FOLLOW_ROTATION_THRESHOLD = cosf(myAvatar.getRotationThreshold()); glm::vec2 bodyFacing = getFacingDir2D(currentBodyMatrix); return glm::dot(-myAvatar.getHeadControllerFacingMovingAverage(), bodyFacing) < FOLLOW_ROTATION_THRESHOLD; } -bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, + const glm::mat4& desiredBodyMatrix, + const glm::mat4& currentBodyMatrix) const { // -z axis of currentBodyMatrix in world space. glm::vec3 forward = glm::normalize(glm::vec3(-currentBodyMatrix[0][2], -currentBodyMatrix[1][2], -currentBodyMatrix[2][2])); // x axis of currentBodyMatrix in world space. @@ -5231,7 +5187,6 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, } bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) const { - // get the current readings controller::Pose currentHeadPose = myAvatar.getControllerPoseInAvatarFrame(controller::Action::HEAD); controller::Pose currentLeftHandPose = myAvatar.getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND); @@ -5244,8 +5199,7 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons if (myAvatar.getIsInWalkingState()) { stepDetected = true; } else { - if (!withinBaseOfSupport(currentHeadPose) && - headAngularVelocityBelowThreshold(currentHeadPose) && + if (!withinBaseOfSupport(currentHeadPose) && headAngularVelocityBelowThreshold(currentHeadPose) && isWithinThresholdHeightMode(currentHeadSensorPose, myAvatar.getCurrentStandingHeight(), myScale) && handDirectionMatchesHeadDirection(currentLeftHandPose, currentRightHandPose, currentHeadPose) && handAngularVelocityBelowThreshold(currentLeftHandPose, currentRightHandPose) && @@ -5257,13 +5211,15 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons myAvatar.setIsInWalkingState(true); } } else { - glm::vec3 defaultHipsPosition = myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Hips")); - glm::vec3 defaultHeadPosition = myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Head")); + glm::vec3 defaultHipsPosition = + myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Hips")); + glm::vec3 defaultHeadPosition = + myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Head")); glm::vec3 currentHeadPosition = currentHeadPose.getTranslation(); float anatomicalHeadToHipsDistance = glm::length(defaultHeadPosition - defaultHipsPosition); - if (!isActive(Horizontal) && - (!isActive(Vertical)) && - (glm::length(currentHeadPosition - defaultHipsPosition) > (anatomicalHeadToHipsDistance + (DEFAULT_AVATAR_SPINE_STRETCH_LIMIT * anatomicalHeadToHipsDistance)))) { + if (!isActive(Horizontal) && (!isActive(Vertical)) && + (glm::length(currentHeadPosition - defaultHipsPosition) > + (anatomicalHeadToHipsDistance + (DEFAULT_AVATAR_SPINE_STRETCH_LIMIT * anatomicalHeadToHipsDistance)))) { myAvatar.setResetMode(true); stepDetected = true; if (glm::length(currentHeadPose.velocity) > DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { @@ -5275,7 +5231,9 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons return stepDetected; } -bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, + const glm::mat4& desiredBodyMatrix, + const glm::mat4& currentBodyMatrix) const { const float CYLINDER_TOP = 2.0f; const float CYLINDER_BOTTOM = -1.5f; const float SITTING_BOTTOM = -0.02f; @@ -5306,11 +5264,11 @@ bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, co return returnValue; } -void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, - const glm::mat4& currentBodyMatrix, bool hasDriveInput) { - - if (myAvatar.getHMDLeanRecenterEnabled() && - qApp->getCamera().getMode() != CAMERA_MODE_MIRROR) { +void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, + const glm::mat4& desiredBodyMatrix, + const glm::mat4& currentBodyMatrix, + bool hasDriveInput) { + if (myAvatar.getHMDLeanRecenterEnabled() && qApp->getCamera().getMode() != CAMERA_MODE_MIRROR) { if (!isActive(Rotation) && (shouldActivateRotation(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { activate(Rotation); myAvatar.setHeadControllerFacingMovingAverage(myAvatar.getHeadControllerFacing()); @@ -5325,7 +5283,8 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat } } else { // center of gravity model is not enabled - if (!isActive(Horizontal) && (shouldActivateHorizontal(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { + if (!isActive(Horizontal) && + (shouldActivateHorizontal(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { activate(Horizontal); if (myAvatar.getEnableStepResetRotation() && !myAvatar.getIsInSittingState()) { activate(Rotation); @@ -5362,7 +5321,7 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat glm::quat currentHipsLocal = myAvatar.getAbsoluteJointRotationInObjectFrame(myAvatar.getJointIndex("Hips")); const glm::quat hipsinWorldSpace = followWorldPose.rot() * (Quaternions::Y_180 * (currentHipsLocal)); - const glm::vec3 avatarUpWorld = glm::normalize(followWorldPose.rot()*(Vectors::UP)); + const glm::vec3 avatarUpWorld = glm::normalize(followWorldPose.rot() * (Vectors::UP)); glm::quat resultingSwingInWorld; glm::quat resultingTwistInWorld; swingTwistDecomposition(hipsinWorldSpace, avatarUpWorld, resultingSwingInWorld, resultingTwistInWorld); @@ -5371,8 +5330,8 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat followWorldPose.scale() = glm::vec3(1.0f); if (isActive(Rotation)) { - //use the hmd reading for the hips follow - followWorldPose.rot() = glmExtractRotation(desiredWorldMatrix); + //use the hmd reading for the hips follow + followWorldPose.rot() = glmExtractRotation(desiredWorldMatrix); } if (isActive(Horizontal)) { glm::vec3 desiredTranslation = extractTranslation(desiredWorldMatrix); @@ -5400,7 +5359,8 @@ glm::mat4 MyAvatar::FollowHelper::postPhysicsUpdate(MyAvatar& myAvatar, const gl glm::mat4 worldToSensorMatrix = glm::inverse(sensorToWorldMatrix); glm::vec3 sensorLinearDisplacement = transformVectorFast(worldToSensorMatrix, worldLinearDisplacement); - glm::quat sensorAngularDisplacement = glmExtractRotation(worldToSensorMatrix) * worldAngularDisplacement * glmExtractRotation(sensorToWorldMatrix); + glm::quat sensorAngularDisplacement = + glmExtractRotation(worldToSensorMatrix) * worldAngularDisplacement * glmExtractRotation(sensorToWorldMatrix); glm::mat4 newBodyMat = createMatFromQuatAndPos(sensorAngularDisplacement * glmExtractRotation(currentBodyMatrix), sensorLinearDisplacement + extractTranslation(currentBodyMatrix)); @@ -5468,7 +5428,8 @@ bool MyAvatar::didTeleport() { } bool MyAvatar::hasDriveInput() const { - return fabsf(getDriveKey(TRANSLATE_X)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Y)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Z)) > 0.0f; + return fabsf(getDriveKey(TRANSLATE_X)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Y)) > 0.0f || + fabsf(getDriveKey(TRANSLATE_Z)) > 0.0f; } void MyAvatar::setAway(bool value) { @@ -5484,7 +5445,6 @@ void MyAvatar::setAway(bool value) { // Specificly, if we are rendering using a third person camera. We would like to render the hand controllers in front of the camera, // not in front of the avatar. glm::mat4 MyAvatar::computeCameraRelativeHandControllerMatrix(const glm::mat4& controllerSensorMatrix) const { - // Fetch the current camera transform. glm::mat4 cameraWorldMatrix = qApp->getCamera().getTransform(); if (qApp->getCamera().getMode() == CAMERA_MODE_MIRROR) { @@ -5511,7 +5471,7 @@ glm::mat4 MyAvatar::computeCameraRelativeHandControllerMatrix(const glm::mat4& c glm::quat MyAvatar::getAbsoluteJointRotationInObjectFrame(int index) const { if (index < 0) { - index += numeric_limits::max() + 1; // 65536 + index += numeric_limits::max() + 1; // 65536 } switch (index) { @@ -5540,15 +5500,13 @@ glm::quat MyAvatar::getAbsoluteJointRotationInObjectFrame(int index) const { glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix(); return glmExtractRotation(invAvatarMat * qApp->getCamera().getTransform()); } - default: { - return Avatar::getAbsoluteJointRotationInObjectFrame(index); - } + default: { return Avatar::getAbsoluteJointRotationInObjectFrame(index); } } } glm::vec3 MyAvatar::getAbsoluteJointTranslationInObjectFrame(int index) const { if (index < 0) { - index += numeric_limits::max() + 1; // 65536 + index += numeric_limits::max() + 1; // 65536 } switch (index) { @@ -5577,9 +5535,7 @@ glm::vec3 MyAvatar::getAbsoluteJointTranslationInObjectFrame(int index) const { glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix(); return extractTranslation(invAvatarMat * qApp->getCamera().getTransform()); } - default: { - return Avatar::getAbsoluteJointTranslationInObjectFrame(index); - } + default: { return Avatar::getAbsoluteJointTranslationInObjectFrame(index); } } } @@ -5588,12 +5544,15 @@ glm::mat4 MyAvatar::getCenterEyeCalibrationMat() const { int rightEyeIndex = _skeletonModel->getRig().indexOfJoint("RightEye"); int leftEyeIndex = _skeletonModel->getRig().indexOfJoint("LeftEye"); if (rightEyeIndex >= 0 && leftEyeIndex >= 0) { - auto centerEyePos = (getAbsoluteDefaultJointTranslationInObjectFrame(rightEyeIndex) + getAbsoluteDefaultJointTranslationInObjectFrame(leftEyeIndex)) * 0.5f; + auto centerEyePos = (getAbsoluteDefaultJointTranslationInObjectFrame(rightEyeIndex) + + getAbsoluteDefaultJointTranslationInObjectFrame(leftEyeIndex)) * + 0.5f; auto centerEyeRot = Quaternions::Y_180; return createMatFromQuatAndPos(centerEyeRot, centerEyePos / getSensorToWorldScale()); } else { glm::mat4 headMat = getHeadCalibrationMat(); - return createMatFromQuatAndPos(DEFAULT_AVATAR_MIDDLE_EYE_ROT, extractTranslation(headMat) + DEFAULT_AVATAR_HEAD_TO_MIDDLE_EYE_OFFSET); + return createMatFromQuatAndPos(DEFAULT_AVATAR_MIDDLE_EYE_ROT, + extractTranslation(headMat) + DEFAULT_AVATAR_HEAD_TO_MIDDLE_EYE_OFFSET); } } @@ -5762,7 +5721,6 @@ void MyAvatar::updateHoldActions(const AnimPose& prePhysicsPose, const AnimPose& if (entityTree) { // lateAvatarUpdate will modify entity position & orientation, so we need an entity write lock entityTree->withWriteLock([&] { - // to prevent actions from adding or removing themselves from the _holdActions vector // while we are iterating, we need to enter a critical section. std::lock_guard guard(_holdActionsMutex); @@ -5798,26 +5756,24 @@ SpatialParentTree* MyAvatar::getParentTree() const { return entityTree.get(); } -const QUuid MyAvatar::grab(const QUuid& targetID, int parentJointIndex, - glm::vec3 positionalOffset, glm::quat rotationalOffset) { +const QUuid MyAvatar::grab(const QUuid& targetID, + int parentJointIndex, + glm::vec3 positionalOffset, + glm::quat rotationalOffset) { auto grabID = QUuid::createUuid(); // create a temporary grab object to get grabData QString hand = "none"; - if (parentJointIndex == CONTROLLER_RIGHTHAND_INDEX || - parentJointIndex == CAMERA_RELATIVE_CONTROLLER_RIGHTHAND_INDEX || - parentJointIndex == FARGRAB_RIGHTHAND_INDEX || - parentJointIndex == getJointIndex("RightHand")) { + if (parentJointIndex == CONTROLLER_RIGHTHAND_INDEX || parentJointIndex == CAMERA_RELATIVE_CONTROLLER_RIGHTHAND_INDEX || + parentJointIndex == FARGRAB_RIGHTHAND_INDEX || parentJointIndex == getJointIndex("RightHand")) { hand = "right"; - } else if (parentJointIndex == CONTROLLER_LEFTHAND_INDEX || - parentJointIndex == CAMERA_RELATIVE_CONTROLLER_LEFTHAND_INDEX || - parentJointIndex == FARGRAB_LEFTHAND_INDEX || - parentJointIndex == getJointIndex("LeftHand")) { + } else if (parentJointIndex == CONTROLLER_LEFTHAND_INDEX || parentJointIndex == CAMERA_RELATIVE_CONTROLLER_LEFTHAND_INDEX || + parentJointIndex == FARGRAB_LEFTHAND_INDEX || parentJointIndex == getJointIndex("LeftHand")) { hand = "left"; } - Grab tmpGrab(DependencyManager::get()->getSessionUUID(), - targetID, parentJointIndex, hand, positionalOffset, rotationalOffset); + Grab tmpGrab(DependencyManager::get()->getSessionUUID(), targetID, parentJointIndex, hand, positionalOffset, + rotationalOffset); QByteArray grabData = tmpGrab.toByteArray(); bool dataChanged = updateAvatarGrabData(grabID, grabData); @@ -5830,10 +5786,9 @@ const QUuid MyAvatar::grab(const QUuid& targetID, int parentJointIndex, } void MyAvatar::releaseGrab(const QUuid& grabID) { - bool tellHandler { false }; + bool tellHandler{ false }; _avatarGrabsLock.withWriteLock([&] { - std::map::iterator itr; itr = _avatarGrabs.find(grabID); if (itr != _avatarGrabs.end()) { @@ -5862,13 +5817,12 @@ void MyAvatar::releaseGrab(const QUuid& grabID) { void MyAvatar::addAvatarHandsToFlow(const std::shared_ptr& otherAvatar) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "addAvatarHandsToFlow", - Q_ARG(const std::shared_ptr&, otherAvatar)); + QMetaObject::invokeMethod(this, "addAvatarHandsToFlow", Q_ARG(const std::shared_ptr&, otherAvatar)); return; } - auto &flow = _skeletonModel->getRig().getFlow(); + auto& flow = _skeletonModel->getRig().getFlow(); if (otherAvatar != nullptr && flow.getActive()) { - for (auto &handJointName : HAND_COLLISION_JOINTS) { + for (auto& handJointName : HAND_COLLISION_JOINTS) { int jointIndex = otherAvatar->getJointIndex(handJointName); if (jointIndex != -1) { glm::vec3 position = otherAvatar->getJointPosition(jointIndex); @@ -5896,18 +5850,18 @@ void MyAvatar::addAvatarHandsToFlow(const std::shared_ptr& otherAvatar) * @property {number} [radius=0.05] - Collision sphere radius. * @property {number} [offset=Vec3.ZERO] - Offset of the collision sphere from the joint. */ -void MyAvatar::useFlow(bool isActive, bool isCollidable, const QVariantMap& physicsConfig, const QVariantMap& collisionsConfig) { +void MyAvatar::useFlow(bool isActive, + bool isCollidable, + const QVariantMap& physicsConfig, + const QVariantMap& collisionsConfig) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "useFlow", - Q_ARG(bool, isActive), - Q_ARG(bool, isCollidable), - Q_ARG(const QVariantMap&, physicsConfig), - Q_ARG(const QVariantMap&, collisionsConfig)); + QMetaObject::invokeMethod(this, "useFlow", Q_ARG(bool, isActive), Q_ARG(bool, isCollidable), + Q_ARG(const QVariantMap&, physicsConfig), Q_ARG(const QVariantMap&, collisionsConfig)); return; } if (_skeletonModel->isLoaded()) { - auto &flow = _skeletonModel->getRig().getFlow(); - auto &collisionSystem = flow.getCollisionSystem(); + auto& flow = _skeletonModel->getRig().getFlow(); + auto& collisionSystem = flow.getCollisionSystem(); if (!flow.isInitialized() && isActive) { _skeletonModel->getRig().initFlow(true); } else { @@ -5916,7 +5870,7 @@ void MyAvatar::useFlow(bool isActive, bool isCollidable, const QVariantMap& phys collisionSystem.setActive(isCollidable); auto physicsGroups = physicsConfig.keys(); if (physicsGroups.size() > 0) { - for (auto &groupName : physicsGroups) { + for (auto& groupName : physicsGroups) { auto settings = physicsConfig[groupName].toMap(); FlowPhysicsSettings physicsSettings; if (settings.contains("active")) { @@ -5946,7 +5900,7 @@ void MyAvatar::useFlow(bool isActive, bool isCollidable, const QVariantMap& phys auto collisionJoints = collisionsConfig.keys(); if (collisionJoints.size() > 0) { collisionSystem.clearSelfCollisions(); - for (auto &jointName : collisionJoints) { + for (auto& jointName : collisionJoints) { int jointIndex = getJointIndex(jointName); FlowCollisionSettings collisionsSettings; auto settings = collisionsConfig[jointName].toMap(); @@ -6000,14 +5954,13 @@ void MyAvatar::useFlow(bool isActive, bool isCollidable, const QVariantMap& phys QVariantMap MyAvatar::getFlowData() { QVariantMap result; if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "getFlowData", - Q_RETURN_ARG(QVariantMap, result)); + BLOCKING_INVOKE_METHOD(this, "getFlowData", Q_RETURN_ARG(QVariantMap, result)); return result; } if (_skeletonModel->isLoaded()) { auto jointNames = getJointNames(); - auto &flow = _skeletonModel->getRig().getFlow(); - auto &collisionSystem = flow.getCollisionSystem(); + auto& flow = _skeletonModel->getRig().getFlow(); + auto& collisionSystem = flow.getCollisionSystem(); bool initialized = flow.isInitialized(); result.insert("initialized", initialized); result.insert("active", flow.getActive()); @@ -6017,17 +5970,17 @@ QVariantMap MyAvatar::getFlowData() { QVariantMap threadData; std::map groupJointsMap; QVariantList jointCollisionData; - auto &groups = flow.getGroupSettings(); - for (auto &joint : flow.getJoints()) { - auto &groupName = joint.second.getGroup(); + auto& groups = flow.getGroupSettings(); + for (auto& joint : flow.getJoints()) { + auto& groupName = joint.second.getGroup(); if (groups.find(groupName) != groups.end()) { if (groupJointsMap.find(groupName) == groupJointsMap.end()) { groupJointsMap.insert(std::pair(groupName, QVariantList())); } groupJointsMap[groupName].push_back(joint.second.getIndex()); } - } - for (auto &group : groups) { + } + for (auto& group : groups) { QVariantMap settingsObject; QString groupName = group.first; FlowPhysicsSettings groupSettings = group.second; @@ -6042,8 +5995,8 @@ QVariantMap MyAvatar::getFlowData() { physicsData.insert(groupName, settingsObject); } - auto &collisions = collisionSystem.getCollisions(); - for (auto &collision : collisions) { + auto& collisions = collisionSystem.getCollisions(); + for (auto& collision : collisions) { QVariantMap collisionObject; collisionObject.insert("offset", vec3toVariant(collision._offset)); collisionObject.insert("radius", collision._radius); @@ -6051,7 +6004,7 @@ QVariantMap MyAvatar::getFlowData() { QString jointName = jointNames.size() > collision._jointIndex ? jointNames[collision._jointIndex] : "unknown"; collisionsData.insert(jointName, collisionObject); } - for (auto &thread : flow.getThreads()) { + for (auto& thread : flow.getThreads()) { QVariantList indices; for (int index : thread._joints) { indices.append(index); @@ -6068,14 +6021,13 @@ QVariantMap MyAvatar::getFlowData() { QVariantList MyAvatar::getCollidingFlowJoints() { QVariantList result; if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "getCollidingFlowJoints", - Q_RETURN_ARG(QVariantList, result)); + BLOCKING_INVOKE_METHOD(this, "getCollidingFlowJoints", Q_RETURN_ARG(QVariantList, result)); return result; } if (_skeletonModel->isLoaded()) { auto& flow = _skeletonModel->getRig().getFlow(); - for (auto &joint : flow.getJoints()) { + for (auto& joint : flow.getJoints()) { if (joint.second.isColliding()) { result.append(joint.second.getIndex()); } @@ -6086,7 +6038,7 @@ QVariantList MyAvatar::getCollidingFlowJoints() { void MyAvatar::initFlowFromFST() { if (_skeletonModel->isLoaded()) { - auto &flowData = _skeletonModel->getHFMModel().flowData; + auto& flowData = _skeletonModel->getHFMModel().flowData; if (flowData.shouldInitFlow()) { useFlow(true, flowData.shouldInitCollisions(), flowData._physicsConfig, flowData._collisionsConfig); } @@ -6104,4 +6056,3 @@ void MyAvatar::sendPacket(const QUuid& entityID) const { }); } } - From 4eccb7a124677ed6548ced5770ff80cb3065573a Mon Sep 17 00:00:00 2001 From: Preston Bezos Date: Fri, 7 Jun 2019 12:00:36 -0700 Subject: [PATCH 18/31] Revert "made one more change to get rid of ubuntu warning" This reverts commit e7255298de9c7d38bc05be468677ff1b7949fd98. --- interface/src/avatar/MyAvatar.cpp | 857 ++++++++++++++++-------------- 1 file changed, 453 insertions(+), 404 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 55ae1a8423..b60bfd3f29 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -71,9 +71,9 @@ using namespace std; const float DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES = 30.0f; const float YAW_SPEED_DEFAULT = 100.0f; // degrees/sec -const float PITCH_SPEED_DEFAULT = 75.0f; // degrees/sec +const float PITCH_SPEED_DEFAULT = 75.0f; // degrees/sec -const float MAX_BOOST_SPEED = 0.5f * DEFAULT_AVATAR_MAX_WALKING_SPEED; // action motor gets additive boost below this speed +const float MAX_BOOST_SPEED = 0.5f * DEFAULT_AVATAR_MAX_WALKING_SPEED; // action motor gets additive boost below this speed const float MIN_AVATAR_SPEED = 0.05f; float MIN_SCRIPTED_MOTOR_TIMESCALE = 0.005f; @@ -83,8 +83,7 @@ const int SCRIPTED_MOTOR_AVATAR_FRAME = 1; const int SCRIPTED_MOTOR_WORLD_FRAME = 2; const int SCRIPTED_MOTOR_SIMPLE_MODE = 0; const int SCRIPTED_MOTOR_DYNAMIC_MODE = 1; -const QString& DEFAULT_AVATAR_COLLISION_SOUND_URL = - "https://hifi-public.s3.amazonaws.com/sounds/Collisions-otherorganic/Body_Hits_Impact.wav"; +const QString& DEFAULT_AVATAR_COLLISION_SOUND_URL = "https://hifi-public.s3.amazonaws.com/sounds/Collisions-otherorganic/Body_Hits_Impact.wav"; const float MyAvatar::ZOOM_MIN = 0.5f; const float MyAvatar::ZOOM_MAX = 25.0f; @@ -93,7 +92,7 @@ const float MIN_SCALE_CHANGED_DELTA = 0.001f; const int MODE_READINGS_RING_BUFFER_SIZE = 500; const float CENTIMETERS_PER_METER = 100.0f; -const QString AVATAR_SETTINGS_GROUP_NAME{ "Avatar" }; +const QString AVATAR_SETTINGS_GROUP_NAME { "Avatar" }; static const QString USER_RECENTER_MODEL_FORCE_SIT = QStringLiteral("ForceSit"); static const QString USER_RECENTER_MODEL_FORCE_STAND = QStringLiteral("ForceStand"); @@ -114,33 +113,50 @@ MyAvatar::SitStandModelType stringToUserRecenterModel(const QString& str) { QString userRecenterModelToString(MyAvatar::SitStandModelType model) { switch (model) { - case MyAvatar::ForceSit: - return USER_RECENTER_MODEL_FORCE_SIT; - case MyAvatar::ForceStand: - return USER_RECENTER_MODEL_FORCE_STAND; - case MyAvatar::DisableHMDLean: - return USER_RECENTER_MODEL_DISABLE_HMD_LEAN; - case MyAvatar::Auto: - default: - return USER_RECENTER_MODEL_AUTO; + case MyAvatar::ForceSit: + return USER_RECENTER_MODEL_FORCE_SIT; + case MyAvatar::ForceStand: + return USER_RECENTER_MODEL_FORCE_STAND; + case MyAvatar::DisableHMDLean: + return USER_RECENTER_MODEL_DISABLE_HMD_LEAN; + case MyAvatar::Auto: + default: + return USER_RECENTER_MODEL_AUTO; } } MyAvatar::MyAvatar(QThread* thread) : - Avatar(thread), _yawSpeed(YAW_SPEED_DEFAULT), _pitchSpeed(PITCH_SPEED_DEFAULT), - _scriptedMotorTimescale(DEFAULT_SCRIPTED_MOTOR_TIMESCALE), _scriptedMotorFrame(SCRIPTED_MOTOR_CAMERA_FRAME), - _scriptedMotorMode(SCRIPTED_MOTOR_SIMPLE_MODE), _motionBehaviors(AVATAR_MOTION_DEFAULTS), - _characterController(std::shared_ptr(this)), _eyeContactTarget(LEFT_EYE), - _realWorldFieldOfView("realWorldFieldOfView", DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES), - _useAdvancedMovementControls("advancedMovementForHandControllersIsChecked", true), _showPlayArea("showPlayArea", true), - _smoothOrientationTimer(std::numeric_limits::max()), _smoothOrientationInitial(), _smoothOrientationTarget(), - _hmdSensorMatrix(), _hmdSensorOrientation(), _hmdSensorPosition(), _recentModeReadings(MODE_READINGS_RING_BUFFER_SIZE), - _bodySensorMatrix(), _goToPending(false), _goToSafe(true), _goToFeetAjustment(false), _goToPosition(), _goToOrientation(), - _prevShouldDrawHead(true), _audioListenerMode(FROM_HEAD), + Avatar(thread), + _yawSpeed(YAW_SPEED_DEFAULT), + _pitchSpeed(PITCH_SPEED_DEFAULT), + _scriptedMotorTimescale(DEFAULT_SCRIPTED_MOTOR_TIMESCALE), + _scriptedMotorFrame(SCRIPTED_MOTOR_CAMERA_FRAME), + _scriptedMotorMode(SCRIPTED_MOTOR_SIMPLE_MODE), + _motionBehaviors(AVATAR_MOTION_DEFAULTS), + _characterController(std::shared_ptr(this)), + _eyeContactTarget(LEFT_EYE), + _realWorldFieldOfView("realWorldFieldOfView", + DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES), + _useAdvancedMovementControls("advancedMovementForHandControllersIsChecked", true), + _showPlayArea("showPlayArea", true), + _smoothOrientationTimer(std::numeric_limits::max()), + _smoothOrientationInitial(), + _smoothOrientationTarget(), + _hmdSensorMatrix(), + _hmdSensorOrientation(), + _hmdSensorPosition(), + _recentModeReadings(MODE_READINGS_RING_BUFFER_SIZE), + _bodySensorMatrix(), + _goToPending(false), + _goToSafe(true), + _goToFeetAjustment(false), + _goToPosition(), + _goToOrientation(), + _prevShouldDrawHead(true), + _audioListenerMode(FROM_HEAD), _dominantHandSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "dominantHand", DOMINANT_RIGHT_HAND), _strafeEnabledSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "strafeEnabled", DEFAULT_STRAFE_ENABLED), - _hmdAvatarAlignmentTypeSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "hmdAvatarAlignmentType", - DEFAULT_HMD_AVATAR_ALIGNMENT_TYPE), + _hmdAvatarAlignmentTypeSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "hmdAvatarAlignmentType", DEFAULT_HMD_AVATAR_ALIGNMENT_TYPE), _headPitchSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "", 0.0f), _scaleSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "scale", _targetScale), _yawSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "yawSpeed", _yawSpeed), @@ -156,19 +172,17 @@ MyAvatar::MyAvatar(QThread* thread) : _userHeightSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userHeight", DEFAULT_AVATAR_HEIGHT), _flyingHMDSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "flyingHMD", _flyingPrefHMD), _movementReferenceSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "movementReference", _movementReference), - _avatarEntityCountSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" - << "size", - 0), + _avatarEntityCountSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" << "size", 0), _driveGear1Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear1", _driveGear1), _driveGear2Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear2", _driveGear2), _driveGear3Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear3", _driveGear3), _driveGear4Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear4", _driveGear4), _driveGear5Setting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "driveGear5", _driveGear5), _analogWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogWalkSpeed", _analogWalkSpeed.get()), - _analogPlusWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogPlusWalkSpeed", - _analogPlusWalkSpeed.get()), + _analogPlusWalkSpeedSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "analogPlusWalkSpeed", _analogPlusWalkSpeed.get()), _controlSchemeIndexSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "controlSchemeIndex", _controlSchemeIndex), - _userRecenterModelSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userRecenterModel", USER_RECENTER_MODEL_AUTO) { + _userRecenterModelSetting(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "userRecenterModel", USER_RECENTER_MODEL_AUTO) +{ _clientTraitsHandler.reset(new ClientTraitsHandler(this)); // give the pointer to our head to inherited _headData variable from AvatarData @@ -189,7 +203,7 @@ MyAvatar::MyAvatar(QThread* thread) : qApp->loadAvatarScripts(hfmModel.scripts); _shouldLoadScripts = false; } - // Load and convert old attachments to avatar entities + // Load and convert old attachments to avatar entities if (_oldAttachmentData.size() > 0) { setAttachmentData(_oldAttachmentData); _oldAttachmentData.clear(); @@ -206,11 +220,11 @@ MyAvatar::MyAvatar(QThread* thread) : clearDriveKeys(); // Necessary to select the correct slot - using SlotType = void (MyAvatar::*)(const glm::vec3&, bool, const glm::quat&, bool); + using SlotType = void(MyAvatar::*)(const glm::vec3&, bool, const glm::quat&, bool); // connect to AddressManager signal for location jumps - connect(DependencyManager::get().data(), &AddressManager::locationChangeRequired, this, - static_cast(&MyAvatar::goToFeetLocation)); + connect(DependencyManager::get().data(), &AddressManager::locationChangeRequired, + this, static_cast(&MyAvatar::goToFeetLocation)); // handle scale constraints imposed on us by the domain-server auto& domainHandler = DependencyManager::get()->getDomainHandler(); @@ -273,6 +287,7 @@ MyAvatar::MyAvatar(QThread* thread) : if (recordingInterface->getPlayerUseSkeletonModel() && dummyAvatar.getSkeletonModelURL().isValid() && (dummyAvatar.getSkeletonModelURL() != getSkeletonModelURL())) { + setSkeletonModelURL(dummyAvatar.getSkeletonModelURL()); } @@ -368,8 +383,7 @@ void MyAvatar::enableHandTouchForID(const QUuid& entityID) { } void MyAvatar::registerMetaTypes(ScriptEnginePointer engine) { - QScriptValue value = engine->newQObject(this, QScriptEngine::QtOwnership, - QScriptEngine::ExcludeDeleteLater | QScriptEngine::ExcludeChildObjects); + QScriptValue value = engine->newQObject(this, QScriptEngine::QtOwnership, QScriptEngine::ExcludeDeleteLater | QScriptEngine::ExcludeChildObjects); engine->globalObject().setProperty("MyAvatar", value); QScriptValue driveKeys = engine->newObject(); @@ -432,6 +446,7 @@ void MyAvatar::resetSensorsAndBody() { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "resetSensorsAndBody"); return; + } qApp->getActiveDisplayPlugin()->resetSensors(); @@ -445,7 +460,7 @@ void MyAvatar::centerBody() { } // derive the desired body orientation from the current hmd orientation, before the sensor reset. - auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. // transform this body into world space auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix; @@ -482,6 +497,7 @@ void MyAvatar::clearIKJointLimitHistory() { } void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { + assert(QThread::currentThread() == thread()); // Reset dynamic state. @@ -490,14 +506,14 @@ void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { if (andReload) { _skeletonModel->reset(); } - if (andHead) { // which drives camera in desktop + if (andHead) { // which drives camera in desktop getHead()->reset(); } setThrust(glm::vec3(0.0f)); if (andRecenter) { // derive the desired body orientation from the *old* hmd orientation, before the sensor reset. - auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. // transform this body into world space auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix; @@ -524,8 +540,8 @@ void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { void MyAvatar::updateSitStandState(float newHeightReading, float dt) { const float STANDING_HEIGHT_MULTIPLE = 1.2f; const float SITTING_HEIGHT_MULTIPLE = 0.833f; - const float SITTING_TIMEOUT = 4.0f; // 4 seconds - const float STANDING_TIMEOUT = 0.3333f; // 1/3 second + const float SITTING_TIMEOUT = 4.0f; // 4 seconds + const float STANDING_TIMEOUT = 0.3333f; // 1/3 second const float SITTING_UPPER_BOUND = 1.52f; if (!getIsSitStandStateLocked()) { if (!getIsAway() && getControllerPoseInAvatarFrame(controller::Action::HEAD).isValid()) { @@ -585,9 +601,9 @@ void MyAvatar::updateSitStandState(float newHeightReading, float dt) { void MyAvatar::update(float deltaTime) { // update moving average of HMD facing in xz plane. const float HMD_FACING_TIMESCALE = getRotationRecenterFilterLength(); - const float PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH = 0.0f; // 100 percent shoulders + const float PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH = 0.0f; // 100 percent shoulders const float COSINE_THIRTY_DEGREES = 0.866f; - const float SQUATTY_TIMEOUT = 30.0f; // 30 seconds + const float SQUATTY_TIMEOUT = 30.0f; // 30 seconds const float HEIGHT_FILTER_COEFFICIENT = 0.01f; float tau = deltaTime / HMD_FACING_TIMESCALE; @@ -596,8 +612,8 @@ void MyAvatar::update(float deltaTime) { // put the average hand azimuth into sensor space. // then mix it with head facing direction to determine rotation recenter int spine2Index = _skeletonModel->getRig().indexOfJoint("Spine2"); - if (getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND).isValid() && - getControllerPoseInAvatarFrame(controller::Action::RIGHT_HAND).isValid() && !(spine2Index < 0)) { + if (getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND).isValid() && getControllerPoseInAvatarFrame(controller::Action::RIGHT_HAND).isValid() && !(spine2Index < 0)) { + // use the spine for the azimuth origin. glm::quat spine2Rot = getAbsoluteJointRotationInObjectFrame(spine2Index); glm::vec3 handHipAzimuthAvatarSpace = spine2Rot * glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y); @@ -607,10 +623,8 @@ void MyAvatar::update(float deltaTime) { glm::vec3 handHipAzimuthSensorSpace = transformVectorFast(worldToSensorMat, handHipAzimuthWorldSpace); glm::vec2 normedHandHipAzimuthSensorSpace(0.0f, 1.0f); if (glm::length(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)) > 0.0f) { - normedHandHipAzimuthSensorSpace = - glm::normalize(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)); - glm::vec2 headFacingPlusHandHipAzimuthMix = - lerp(normedHandHipAzimuthSensorSpace, _headControllerFacing, PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH); + normedHandHipAzimuthSensorSpace = glm::normalize(glm::vec2(handHipAzimuthSensorSpace.x, handHipAzimuthSensorSpace.z)); + glm::vec2 headFacingPlusHandHipAzimuthMix = lerp(normedHandHipAzimuthSensorSpace, _headControllerFacing, PERCENTAGE_WEIGHT_HEAD_VS_SHOULDERS_AZIMUTH); _headControllerFacingMovingAverage = lerp(_headControllerFacingMovingAverage, headFacingPlusHandHipAzimuthMix, tau); } else { // use head facing if the chest arms vector is up or down. @@ -628,8 +642,7 @@ void MyAvatar::update(float deltaTime) { controller::Pose newHeightReading = getControllerPoseInSensorFrame(controller::Action::HEAD); if (newHeightReading.isValid()) { int newHeightReadingInCentimeters = glm::floor(newHeightReading.getTranslation().y * CENTIMETERS_PER_METER); - _averageUserHeightSensorSpace = - lerp(_averageUserHeightSensorSpace, newHeightReading.getTranslation().y, HEIGHT_FILTER_COEFFICIENT); + _averageUserHeightSensorSpace = lerp(_averageUserHeightSensorSpace, newHeightReading.getTranslation().y, HEIGHT_FILTER_COEFFICIENT); _recentModeReadings.insert(newHeightReadingInCentimeters); setCurrentStandingHeight(computeStandingHeightMode(newHeightReading)); setAverageHeadRotation(computeAverageHeadRotation(getControllerPoseInAvatarFrame(controller::Action::HEAD))); @@ -645,9 +658,10 @@ void MyAvatar::update(float deltaTime) { } float angleSpine2 = glm::dot(upSpine2, glm::vec3(0.0f, 1.0f, 0.0f)); - if (getControllerPoseInAvatarFrame(controller::Action::HEAD).getTranslation().y < - (headDefaultPositionAvatarSpace.y - SQUAT_THRESHOLD) && - (angleSpine2 > COSINE_THIRTY_DEGREES) && (getUserRecenterModel() != MyAvatar::SitStandModelType::ForceStand)) { + if (getControllerPoseInAvatarFrame(controller::Action::HEAD).getTranslation().y < (headDefaultPositionAvatarSpace.y - SQUAT_THRESHOLD) && + (angleSpine2 > COSINE_THIRTY_DEGREES) && + (getUserRecenterModel() != MyAvatar::SitStandModelType::ForceStand)) { + _squatTimer += deltaTime; if (_squatTimer > SQUATTY_TIMEOUT) { _squatTimer = 0.0f; @@ -663,24 +677,20 @@ void MyAvatar::update(float deltaTime) { if (_drawAverageFacingEnabled) { auto sensorHeadPose = getControllerPoseInSensorFrame(controller::Action::HEAD); glm::vec3 worldHeadPos = transformPoint(getSensorToWorldMatrix(), sensorHeadPose.getTranslation()); - glm::vec3 worldFacingAverage = - transformVectorFast(getSensorToWorldMatrix(), - glm::vec3(_headControllerFacingMovingAverage.x, 0.0f, _headControllerFacingMovingAverage.y)); - glm::vec3 worldFacing = - transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacing.x, 0.0f, _headControllerFacing.y)); + glm::vec3 worldFacingAverage = transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacingMovingAverage.x, 0.0f, _headControllerFacingMovingAverage.y)); + glm::vec3 worldFacing = transformVectorFast(getSensorToWorldMatrix(), glm::vec3(_headControllerFacing.x, 0.0f, _headControllerFacing.y)); DebugDraw::getInstance().drawRay(worldHeadPos, worldHeadPos + worldFacing, glm::vec4(0.0f, 1.0f, 0.0f, 1.0f)); DebugDraw::getInstance().drawRay(worldHeadPos, worldHeadPos + worldFacingAverage, glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)); // draw hand azimuth vector - glm::vec3 handAzimuthMidpoint = - transformPoint(getTransform().getMatrix(), glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y)); + glm::vec3 handAzimuthMidpoint = transformPoint(getTransform().getMatrix(), glm::vec3(_hipToHandController.x, 0.0f, _hipToHandController.y)); DebugDraw::getInstance().drawRay(getWorldPosition(), handAzimuthMidpoint, glm::vec4(0.0f, 1.0f, 1.0f, 1.0f)); } if (_goToPending) { setWorldPosition(_goToPosition); setWorldOrientation(_goToOrientation); - _headControllerFacingMovingAverage = _headControllerFacing; // reset moving average + _headControllerFacingMovingAverage = _headControllerFacing; // reset moving average _goToPending = false; // updateFromHMDSensorMatrix (called from paintGL) expects that the sensorToWorldMatrix is updated for any position changes // that happen between render and Application::update (which calls updateSensorToWorldMatrix to do so). @@ -690,7 +700,7 @@ void MyAvatar::update(float deltaTime) { emit positionGoneTo(); // Run safety tests as soon as we can after goToLocation, or clear if we're not colliding. _physicsSafetyPending = getCollisionsEnabled(); - _characterController.recomputeFlying(); // In case we've gone to into the sky. + _characterController.recomputeFlying(); // In case we've gone to into the sky. } if (_goToFeetAjustment && _skeletonModelLoaded) { auto feetAjustment = getWorldPosition() - getWorldFeetPosition(); @@ -702,7 +712,7 @@ void MyAvatar::update(float deltaTime) { // When needed and ready, arrange to check and fix. _physicsSafetyPending = false; if (_goToSafe) { - safeLanding(_goToPosition); // no-op if already safe + safeLanding(_goToPosition); // no-op if already safe } } @@ -710,8 +720,7 @@ void MyAvatar::update(float deltaTime) { head->relax(deltaTime); updateFromTrackers(deltaTime); - if (getIsInWalkingState() && glm::length(getControllerPoseInAvatarFrame(controller::Action::HEAD).getVelocity()) < - DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { + if (getIsInWalkingState() && glm::length(getControllerPoseInAvatarFrame(controller::Action::HEAD).getVelocity()) < DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { setIsInWalkingState(false); } @@ -722,13 +731,12 @@ void MyAvatar::update(float deltaTime) { setAudioLoudness(audio->getLastInputLoudness()); setAudioAverageLoudness(audio->getAudioAverageInputLoudness()); - glm::vec3 halfBoundingBoxDimensions(_characterController.getCapsuleRadius(), _characterController.getCapsuleHalfHeight(), - _characterController.getCapsuleRadius()); + glm::vec3 halfBoundingBoxDimensions(_characterController.getCapsuleRadius(), _characterController.getCapsuleHalfHeight(), _characterController.getCapsuleRadius()); // This might not be right! Isn't the capsule local offset in avatar space? -HRS 5/26/17 halfBoundingBoxDimensions += _characterController.getCapsuleLocalOffset(); QMetaObject::invokeMethod(audio, "setAvatarBoundingBoxParameters", - Q_ARG(glm::vec3, (getWorldPosition() - halfBoundingBoxDimensions)), - Q_ARG(glm::vec3, (halfBoundingBoxDimensions * 2.0f))); + Q_ARG(glm::vec3, (getWorldPosition() - halfBoundingBoxDimensions)), + Q_ARG(glm::vec3, (halfBoundingBoxDimensions*2.0f))); simulate(deltaTime, true); @@ -736,20 +744,23 @@ void MyAvatar::update(float deltaTime) { currentEnergy -= getAccelerationEnergy(); currentEnergy -= getAudioEnergy(); - if (didTeleport()) { + if(didTeleport()) { currentEnergy = 0.0f; } - currentEnergy = max(0.0f, min(currentEnergy, 1.0f)); + currentEnergy = max(0.0f, min(currentEnergy,1.0f)); emit energyChanged(currentEnergy); updateEyeContactTarget(deltaTime); } void MyAvatar::updateEyeContactTarget(float deltaTime) { + _eyeContactTargetTimer -= deltaTime; if (_eyeContactTargetTimer < 0.0f) { + const float CHANCE_OF_CHANGING_TARGET = 0.01f; if (randFloat() < CHANCE_OF_CHANGING_TARGET) { + float const FIFTY_FIFTY_CHANCE = 0.5f; float const EYE_TO_MOUTH_CHANCE = 0.25f; switch (_eyeContactTarget) { @@ -817,20 +828,21 @@ void MyAvatar::simulate(float deltaTime, bool inView) { if (isChildOfHead && !object->hasGrabs()) { // Cauterize or display children of head per head drawing state. updateChildCauterization(object, !_prevShouldDrawHead); - object->forEachDescendant( - [&](SpatiallyNestablePointer descendant) { updateChildCauterization(descendant, !_prevShouldDrawHead); }); + object->forEachDescendant([&](SpatiallyNestablePointer descendant) { + updateChildCauterization(descendant, !_prevShouldDrawHead); + }); _cauterizedChildrenOfHead.insert(object); objectsToUncauterize.erase(object); } else if (objectsToUncauterize.find(object) == objectsToUncauterize.end()) { objectsToUncauterize.insert(object); - object->forEachDescendant( - [&](SpatiallyNestablePointer descendant) { objectsToUncauterize.insert(descendant); }); + object->forEachDescendant([&](SpatiallyNestablePointer descendant) { + objectsToUncauterize.insert(descendant); + }); } }); // Redisplay cauterized entities that are no longer children of the avatar. - for (auto cauterizedChild = objectsToUncauterize.begin(); cauterizedChild != objectsToUncauterize.end(); - cauterizedChild++) { + for (auto cauterizedChild = objectsToUncauterize.begin(); cauterizedChild != objectsToUncauterize.end(); cauterizedChild++) { updateChildCauterization(*cauterizedChild, false); } } @@ -874,7 +886,7 @@ void MyAvatar::simulate(float deltaTime, bool inView) { if (!_skeletonModel->hasSkeleton()) { // All the simulation that can be done has been done - getHead()->setPosition(getWorldPosition()); // so audio-position isn't 0,0,0 + getHead()->setPosition(getWorldPosition()); // so audio-position isn't 0,0,0 return; } @@ -955,7 +967,8 @@ void MyAvatar::updateFromHMDSensorMatrix(const glm::mat4& hmdSensorMatrix) { _hmdSensorMatrix = hmdSensorMatrix; auto newHmdSensorPosition = extractTranslation(hmdSensorMatrix); - if (newHmdSensorPosition != getHMDSensorPosition() && glm::length(newHmdSensorPosition) > MAX_HMD_ORIGIN_DISTANCE) { + if (newHmdSensorPosition != getHMDSensorPosition() && + glm::length(newHmdSensorPosition) > MAX_HMD_ORIGIN_DISTANCE) { qWarning() << "Invalid HMD sensor position " << newHmdSensorPosition; // Ignore unreasonable HMD sensor data return; @@ -983,8 +996,8 @@ glm::vec2 MyAvatar::computeHandAzimuth() const { glm::vec2 latestHipToHandController = _hipToHandController; int spine2Index = _skeletonModel->getRig().indexOfJoint("Spine2"); - if (leftHandPoseAvatarSpace.isValid() && rightHandPoseAvatarSpace.isValid() && headPoseAvatarSpace.isValid() && - !(spine2Index < 0)) { + if (leftHandPoseAvatarSpace.isValid() && rightHandPoseAvatarSpace.isValid() && headPoseAvatarSpace.isValid() && !(spine2Index < 0)) { + glm::vec3 spine2Position = getAbsoluteJointTranslationInObjectFrame(spine2Index); glm::quat spine2Rotation = getAbsoluteJointRotationInObjectFrame(spine2Index); @@ -996,10 +1009,8 @@ glm::vec2 MyAvatar::computeHandAzimuth() const { // we need the old azimuth reading to prevent flipping the facing direction 180 // in the case where the hands go from being slightly less than 180 apart to slightly more than 180 apart. glm::vec2 oldAzimuthReading = _hipToHandController; - if ((glm::length(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)) > 0.0f) && - (glm::length(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)) > 0.0f)) { - latestHipToHandController = lerp(glm::normalize(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)), - glm::normalize(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)), HALFWAY); + if ((glm::length(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)) > 0.0f) && (glm::length(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)) > 0.0f)) { + latestHipToHandController = lerp(glm::normalize(glm::vec2(rightHandSpine2Space.x, rightHandSpine2Space.z)), glm::normalize(glm::vec2(leftHandSpine2Space.x, leftHandSpine2Space.z)), HALFWAY); } else { latestHipToHandController = glm::vec2(0.0f, 1.0f); } @@ -1047,11 +1058,11 @@ void MyAvatar::updateJointFromController(controller::Action poseKey, ThreadSafeV // update sensor to world matrix from current body position and hmd sensor. // This is so the correct camera can be used for rendering. void MyAvatar::updateSensorToWorldMatrix() { + // update the sensor mat so that the body position will end up in the desired // position when driven from the head. float sensorToWorldScale = getEyeHeight() / getUserEyeHeight(); - glm::mat4 desiredMat = - createMatFromScaleQuatAndPos(glm::vec3(sensorToWorldScale), getWorldOrientation(), getWorldPosition()); + glm::mat4 desiredMat = createMatFromScaleQuatAndPos(glm::vec3(sensorToWorldScale), getWorldOrientation(), getWorldPosition()); _sensorToWorldMatrix = desiredMat * glm::inverse(_bodySensorMatrix); bool hasSensorToWorldScaleChanged = false; @@ -1069,10 +1080,11 @@ void MyAvatar::updateSensorToWorldMatrix() { _sensorToWorldMatrixCache.set(_sensorToWorldMatrix); updateJointFromController(controller::Action::LEFT_HAND, _controllerLeftHandMatrixCache); updateJointFromController(controller::Action::RIGHT_HAND, _controllerRightHandMatrixCache); - + if (hasSensorToWorldScaleChanged) { emit sensorToWorldScaleChanged(sensorToWorldScale); } + } // Update avatar head rotation with sensor data @@ -1097,7 +1109,8 @@ void MyAvatar::updateFromTrackers(float deltaTime) { const float TRACKER_YAW_TURN_SENSITIVITY = 0.5f; const float TRACKER_MIN_YAW_TURN = 15.0f; const float TRACKER_MAX_YAW_TURN = 50.0f; - if ((fabs(estimatedRotation.y) > TRACKER_MIN_YAW_TURN) && (fabs(estimatedRotation.y) < TRACKER_MAX_YAW_TURN)) { + if ( (fabs(estimatedRotation.y) > TRACKER_MIN_YAW_TURN) && + (fabs(estimatedRotation.y) < TRACKER_MAX_YAW_TURN) ) { if (estimatedRotation.y > 0.0f) { _bodyYawDelta += (estimatedRotation.y - TRACKER_MIN_YAW_TURN) * TRACKER_YAW_TURN_SENSITIVITY; } else { @@ -1112,6 +1125,7 @@ void MyAvatar::updateFromTrackers(float deltaTime) { // their head only 30 degrees or so, this may correspond to a 90 degree field of view. // Note that roll is magnified by a constant because it is not related to field of view. + Head* head = getHead(); if (hasHead || playing) { head->setDeltaPitch(estimatedRotation.x); @@ -1177,15 +1191,15 @@ controller::Pose MyAvatar::getRightHandTipPose() const { void MyAvatar::render(RenderArgs* renderArgs) { // don't render if we've been asked to disable local rendering if (!_shouldRender) { - return; // exit early + return; // exit early } Avatar::render(renderArgs); } void MyAvatar::overrideAnimation(const QString& url, float fps, bool loop, float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "overrideAnimation", Q_ARG(const QString&, url), Q_ARG(float, fps), Q_ARG(bool, loop), - Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); + QMetaObject::invokeMethod(this, "overrideAnimation", Q_ARG(const QString&, url), Q_ARG(float, fps), + Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); return; } _skeletonModel->getRig().overrideAnimation(url, fps, loop, firstFrame, lastFrame); @@ -1193,8 +1207,8 @@ void MyAvatar::overrideAnimation(const QString& url, float fps, bool loop, float void MyAvatar::overrideHandAnimation(bool isLeft, const QString& url, float fps, bool loop, float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "overrideHandAnimation", Q_ARG(bool, isLeft), Q_ARG(const QString&, url), - Q_ARG(float, fps), Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); + QMetaObject::invokeMethod(this, "overrideHandAnimation", Q_ARG(bool, isLeft), Q_ARG(const QString&, url), Q_ARG(float, fps), + Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); return; } _skeletonModel->getRig().overrideHandAnimation(isLeft, url, fps, loop, firstFrame, lastFrame); @@ -1225,12 +1239,8 @@ QStringList MyAvatar::getAnimationRoles() { return _skeletonModel->getRig().getAnimationRoles(); } -void MyAvatar::overrideRoleAnimation(const QString& role, - const QString& url, - float fps, - bool loop, - float firstFrame, - float lastFrame) { +void MyAvatar::overrideRoleAnimation(const QString& role, const QString& url, float fps, bool loop, + float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "overrideRoleAnimation", Q_ARG(const QString&, role), Q_ARG(const QString&, url), Q_ARG(float, fps), Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); @@ -1249,9 +1259,9 @@ void MyAvatar::restoreRoleAnimation(const QString& role) { void MyAvatar::saveAvatarUrl() { if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid()) { - _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() - ? "" - : _fullAvatarURLFromPreferences.toString()); + _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() ? + "" : + _fullAvatarURLFromPreferences.toString()); } } @@ -1268,12 +1278,10 @@ void MyAvatar::resizeAvatarEntitySettingHandles(uint32_t maxIndex) { uint32_t settingsIndex = (uint32_t)_avatarEntityIDSettings.size() + 1; while (settingsIndex <= maxIndex) { Setting::Handle idHandle(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" - << QString::number(settingsIndex) << "id", - QUuid()); + << QString::number(settingsIndex) << "id", QUuid()); _avatarEntityIDSettings.push_back(idHandle); Setting::Handle dataHandle(QStringList() << AVATAR_SETTINGS_GROUP_NAME << "avatarEntityData" - << QString::number(settingsIndex) << "properties", - QByteArray()); + << QString::number(settingsIndex) << "properties", QByteArray()); _avatarEntityDataSettings.push_back(dataHandle); settingsIndex++; } @@ -1291,10 +1299,10 @@ void MyAvatar::saveData() { // only save the fullAvatarURL if it has not been overwritten on command line // (so the overrideURL is not valid), or it was overridden _and_ we specified // --replaceAvatarURL (so _saveAvatarOverrideUrl is true) - if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid()) { - _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() - ? "" - : _fullAvatarURLFromPreferences.toString()); + if (qApp->getSaveAvatarOverrideUrl() || !qApp->getAvatarOverrideUrl().isValid() ) { + _fullAvatarURLSetting.set(_fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() ? + "" : + _fullAvatarURLFromPreferences.toString()); } _fullAvatarModelNameSetting.set(_fullAvatarModelName); @@ -1464,12 +1472,16 @@ void MyAvatar::setEnableInverseKinematics(bool isEnabled) { void MyAvatar::storeAvatarEntityDataPayload(const QUuid& entityID, const QByteArray& payload) { AvatarData::storeAvatarEntityDataPayload(entityID, payload); - _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobsToAddOrUpdate.push_back(entityID); }); + _avatarEntitiesLock.withWriteLock([&] { + _cachedAvatarEntityBlobsToAddOrUpdate.push_back(entityID); + }); } void MyAvatar::clearAvatarEntity(const QUuid& entityID, bool requiresRemovalFromTree) { AvatarData::clearAvatarEntity(entityID, requiresRemovalFromTree); - _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobsToDelete.push_back(entityID); }); + _avatarEntitiesLock.withWriteLock([&] { + _cachedAvatarEntityBlobsToDelete.push_back(entityID); + }); } void MyAvatar::sanitizeAvatarEntityProperties(EntityItemProperties& properties) const { @@ -1494,7 +1506,9 @@ void MyAvatar::sanitizeAvatarEntityProperties(EntityItemProperties& properties) void MyAvatar::handleChangedAvatarEntityData() { // NOTE: this is a per-frame update - if (getID().isNull() || getID() == AVATAR_SELF_ID || DependencyManager::get()->getSessionUUID() == QUuid()) { + if (getID().isNull() || + getID() == AVATAR_SELF_ID || + DependencyManager::get()->getSessionUUID() == QUuid()) { // wait until MyAvatar and this Node gets an ID before doing this. Otherwise, various things go wrong: // things get their parent fixed up from AVATAR_SELF_ID to a null uuid which means "no parent". return; @@ -1540,7 +1554,7 @@ void MyAvatar::handleChangedAvatarEntityData() { entitiesToUpdate = std::move(_entitiesToUpdate); }); - auto removeAllInstancesHelper = [](const QUuid& id, std::vector& v) { + auto removeAllInstancesHelper = [] (const QUuid& id, std::vector& v) { uint32_t i = 0; while (i < v.size()) { if (id == v[i]) { @@ -1568,7 +1582,9 @@ void MyAvatar::handleChangedAvatarEntityData() { // DELETE real entities for (const auto& id : entitiesToDelete) { - entityTree->withWriteLock([&] { entityTree->deleteEntity(id); }); + entityTree->withWriteLock([&] { + entityTree->deleteEntity(id); + }); } // ADD real entities @@ -1579,19 +1595,21 @@ void MyAvatar::handleChangedAvatarEntityData() { _avatarEntitiesLock.withReadLock([&] { AvatarEntityMap::iterator itr = _cachedAvatarEntityBlobs.find(id); if (itr == _cachedAvatarEntityBlobs.end()) { - blobFailed = true; // blob doesn't exist + blobFailed = true; // blob doesn't exist return; } std::lock_guard guard(_scriptEngineLock); if (!EntityItemProperties::blobToProperties(*_scriptEngine, itr.value(), properties)) { - blobFailed = true; // blob is corrupt + blobFailed = true; // blob is corrupt } }); if (blobFailed) { // remove from _cachedAvatarEntityBlobUpdatesToSkip just in case: // avoids a resource leak when blob updates to be skipped are never actually skipped // when the blob fails to result in a real EntityItem - _avatarEntitiesLock.withWriteLock([&] { removeAllInstancesHelper(id, _cachedAvatarEntityBlobUpdatesToSkip); }); + _avatarEntitiesLock.withWriteLock([&] { + removeAllInstancesHelper(id, _cachedAvatarEntityBlobUpdatesToSkip); + }); continue; } sanitizeAvatarEntityProperties(properties); @@ -1661,7 +1679,7 @@ void MyAvatar::handleChangedAvatarEntityData() { _cachedAvatarEntityBlobUpdatesToSkip[i] = _cachedAvatarEntityBlobUpdatesToSkip.back(); _cachedAvatarEntityBlobUpdatesToSkip.pop_back(); skip = true; - break; // assume no duplicates + break; // assume no duplicates } else { ++i; } @@ -1725,7 +1743,9 @@ bool MyAvatar::updateStaleAvatarEntityBlobs() const { std::lock_guard guard(_scriptEngineLock); EntityItemProperties::propertiesToBlob(*_scriptEngine, getID(), properties, blob); } - _avatarEntitiesLock.withWriteLock([&] { _cachedAvatarEntityBlobs[id] = blob; }); + _avatarEntitiesLock.withWriteLock([&] { + _cachedAvatarEntityBlobs[id] = blob; + }); } } return true; @@ -1752,7 +1772,9 @@ AvatarEntityMap MyAvatar::getAvatarEntityData() const { // NOTE: the return value is expected to be a map of unfortunately-formatted-binary-blobs updateStaleAvatarEntityBlobs(); AvatarEntityMap result; - _avatarEntitiesLock.withReadLock([&] { result = _cachedAvatarEntityBlobs; }); + _avatarEntitiesLock.withReadLock([&] { + result = _cachedAvatarEntityBlobs; + }); return result; } @@ -1853,9 +1875,7 @@ void MyAvatar::avatarEntityDataToJson(QJsonObject& root) const { AvatarEntityMap::const_iterator itr = _cachedAvatarEntityBlobs.begin(); while (itr != _cachedAvatarEntityBlobs.end()) { QVariantMap entityData; - QUuid id = _avatarEntityForRecording.size() == _cachedAvatarEntityBlobs.size() - ? _avatarEntityForRecording.values()[entityCount++] - : itr.key(); + QUuid id = _avatarEntityForRecording.size() == _cachedAvatarEntityBlobs.size() ? _avatarEntityForRecording.values()[entityCount++] : itr.key(); entityData.insert("id", id); entityData.insert("properties", itr.value().toBase64()); avatarEntityJson.push_back(QVariant(entityData).toJsonObject()); @@ -1885,7 +1905,7 @@ void MyAvatar::loadData() { loadAvatarEntityDataFromSettings(); // Flying preferences must be loaded before calling setFlyingEnabled() - Setting::Handle firstRunVal{ Settings::firstRun, true }; + Setting::Handle firstRunVal { Settings::firstRun, true }; setFlyingHMDPref(firstRunVal.get() ? false : _flyingHMDSetting.get()); setMovementReference(firstRunVal.get() ? false : _movementReferenceSetting.get()); setDriveGear1(firstRunVal.get() ? DEFAULT_GEAR_1 : _driveGear1Setting.get()); @@ -1911,7 +1931,7 @@ void MyAvatar::loadData() { setUserRecenterModel(stringToUserRecenterModel(_userRecenterModelSetting.get(USER_RECENTER_MODEL_AUTO))); setEnableMeshVisible(Menu::getInstance()->isOptionChecked(MenuOption::MeshVisible)); - _follow.setToggleHipsFollowing(Menu::getInstance()->isOptionChecked(MenuOption::ToggleHipsFollowing)); + _follow.setToggleHipsFollowing (Menu::getInstance()->isOptionChecked(MenuOption::ToggleHipsFollowing)); setEnableDebugDrawBaseOfSupport(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawBaseOfSupport)); setEnableDebugDrawDefaultPose(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawDefaultPose)); setEnableDebugDrawAnimPose(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawAnimPose)); @@ -1939,7 +1959,7 @@ void MyAvatar::loadAvatarEntityDataFromSettings() { _entitiesToAdd.reserve(numEntities); // TODO: build map between old and new IDs so we can restitch parent-child relationships for (int i = 0; i < numEntities; i++) { - QUuid id = QUuid::createUuid(); // generate a new ID + QUuid id = QUuid::createUuid(); // generate a new ID _cachedAvatarEntityBlobs[id] = _avatarEntityDataSettings[i].get(); _entitiesToAdd.push_back(id); // this blob is the "authoritative source" for this AvatarEntity and we want to avoid overwriting it @@ -2009,9 +2029,10 @@ AttachmentData MyAvatar::loadAttachmentData(const QUrl& modelURL, const QString& return attachment; } + int MyAvatar::parseDataFromBuffer(const QByteArray& buffer) { qCDebug(interfaceapp) << "Error: ignoring update packet for MyAvatar" - << " packetLength = " << buffer.size(); + << " packetLength = " << buffer.size(); // this packet is just bad, so we pretend that we unpacked it ALL return buffer.size(); } @@ -2025,12 +2046,8 @@ ScriptAvatarData* MyAvatar::getTargetAvatar() const { } } -static float lookAtCostFunction(const glm::vec3& myForward, - const glm::vec3& myPosition, - const glm::vec3& otherForward, - const glm::vec3& otherPosition, - bool otherIsTalking, - bool lookingAtOtherAlready) { +static float lookAtCostFunction(const glm::vec3& myForward, const glm::vec3& myPosition, const glm::vec3& otherForward, const glm::vec3& otherPosition, + bool otherIsTalking, bool lookingAtOtherAlready) { const float DISTANCE_FACTOR = 3.14f; const float MY_ANGLE_FACTOR = 1.0f; const float OTHER_ANGLE_FACTOR = 1.0f; @@ -2038,7 +2055,7 @@ static float lookAtCostFunction(const glm::vec3& myForward, const float LOOKING_AT_OTHER_ALREADY_TERM = lookingAtOtherAlready ? -0.2f : 0.0f; const float GREATEST_LOOKING_AT_DISTANCE = 10.0f; // meters - const float MAX_MY_ANGLE = PI / 8.0f; // 22.5 degrees, Don't look too far away from the head facing. + const float MAX_MY_ANGLE = PI / 8.0f; // 22.5 degrees, Don't look too far away from the head facing. const float MAX_OTHER_ANGLE = (3.0f * PI) / 4.0f; // 135 degrees, Don't stare at the back of another avatars head. glm::vec3 d = otherPosition - myPosition; @@ -2050,8 +2067,11 @@ static float lookAtCostFunction(const glm::vec3& myForward, if (distance > GREATEST_LOOKING_AT_DISTANCE || myAngle > MAX_MY_ANGLE || otherAngle > MAX_OTHER_ANGLE) { return FLT_MAX; } else { - return (DISTANCE_FACTOR * distance + MY_ANGLE_FACTOR * myAngle + OTHER_ANGLE_FACTOR * otherAngle + - OTHER_IS_TALKING_TERM + LOOKING_AT_OTHER_ALREADY_TERM); + return (DISTANCE_FACTOR * distance + + MY_ANGLE_FACTOR * myAngle + + OTHER_ANGLE_FACTOR * otherAngle + + OTHER_IS_TALKING_TERM + + LOOKING_AT_OTHER_ALREADY_TERM); } } @@ -2074,8 +2094,7 @@ void MyAvatar::computeMyLookAtTarget(const AvatarHash& hash) { const float TIME_WITHOUT_TALKING_THRESHOLD = 1.0f; bool otherIsTalking = avatar->getHead()->getTimeWithoutTalking() <= TIME_WITHOUT_TALKING_THRESHOLD; bool lookingAtOtherAlready = _lookAtTargetAvatar.lock().get() == avatar.get(); - float cost = - lookAtCostFunction(myForward, myPosition, otherForward, otherPosition, otherIsTalking, lookingAtOtherAlready); + float cost = lookAtCostFunction(myForward, myPosition, otherForward, otherPosition, otherIsTalking, lookingAtOtherAlready); if (cost < bestCost) { bestCost = cost; bestAvatar = avatar; @@ -2096,8 +2115,9 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { std::shared_ptr avatar = std::static_pointer_cast(avatarData); if (!avatar->isMyAvatar() && avatar->isInitialized()) { if (_lookAtSnappingEnabled && avatar->getLookAtSnappingEnabled() && isLookingAtMe(avatar)) { + // Alter their gaze to look directly at my camera; this looks more natural than looking at my avatar's face. - glm::vec3 lookAtPosition = avatar->getHead()->getLookAtPosition(); // A position, in world space, on my avatar. + glm::vec3 lookAtPosition = avatar->getHead()->getLookAtPosition(); // A position, in world space, on my avatar. // The camera isn't at the point midway between the avatar eyes. (Even without an HMD, the head can be offset a bit.) // Let's get everything to world space: @@ -2108,12 +2128,12 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { // (We will be adding that offset to the camera position, after making some other adjustments.) glm::vec3 gazeOffset = lookAtPosition - getHead()->getEyePosition(); - ViewFrustum viewFrustum; - qApp->copyViewFrustum(viewFrustum); + ViewFrustum viewFrustum; + qApp->copyViewFrustum(viewFrustum); - glm::vec3 viewPosition = viewFrustum.getPosition(); + glm::vec3 viewPosition = viewFrustum.getPosition(); #if DEBUG_ALWAYS_LOOKAT_EYES_NOT_CAMERA - viewPosition = (avatarLeftEye + avatarRightEye) / 2.0f; + viewPosition = (avatarLeftEye + avatarRightEye) / 2.0f; #endif // scale gazeOffset by IPD, if wearing an HMD. if (qApp->isHMDMode()) { @@ -2151,6 +2171,7 @@ void MyAvatar::snapOtherAvatarLookAtTargetsToMe(const AvatarHash& hash) { } void MyAvatar::updateLookAtTargetAvatar() { + // The AvatarManager is a mutable class shared by many threads. We make a thread-safe deep copy of it, // to avoid having to hold a lock while we iterate over all the avatars within. AvatarHash hash = DependencyManager::get()->getHashCopy(); @@ -2264,7 +2285,8 @@ void MyAvatar::setJointTranslation(int index, const glm::vec3& translation) { } default: { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "setJointTranslation", Q_ARG(int, index), Q_ARG(const glm::vec3&, translation)); + QMetaObject::invokeMethod(this, "setJointTranslation", + Q_ARG(int, index), Q_ARG(const glm::vec3&, translation)); return; } // HACK: ATM only JS scripts call setJointData() on MyAvatar so we hardcode the priority @@ -2303,7 +2325,9 @@ void MyAvatar::setJointData(const QString& name, const glm::quat& rotation, cons Q_ARG(const glm::vec3&, translation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { setJointData(index, rotation, translation); }); + writeLockWithNamedJointIndex(name, [&](int index) { + setJointData(index, rotation, translation); + }); } void MyAvatar::setJointRotation(const QString& name, const glm::quat& rotation) { @@ -2311,7 +2335,9 @@ void MyAvatar::setJointRotation(const QString& name, const glm::quat& rotation) QMetaObject::invokeMethod(this, "setJointRotation", Q_ARG(QString, name), Q_ARG(const glm::quat&, rotation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { setJointRotation(index, rotation); }); + writeLockWithNamedJointIndex(name, [&](int index) { + setJointRotation(index, rotation); + }); } void MyAvatar::setJointTranslation(const QString& name, const glm::vec3& translation) { @@ -2319,7 +2345,9 @@ void MyAvatar::setJointTranslation(const QString& name, const glm::vec3& transla QMetaObject::invokeMethod(this, "setJointTranslation", Q_ARG(QString, name), Q_ARG(const glm::vec3&, translation)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { setJointTranslation(index, translation); }); + writeLockWithNamedJointIndex(name, [&](int index) { + setJointTranslation(index, translation); + }); } void MyAvatar::clearJointData(const QString& name) { @@ -2327,7 +2355,9 @@ void MyAvatar::clearJointData(const QString& name) { QMetaObject::invokeMethod(this, "clearJointData", Q_ARG(QString, name)); return; } - writeLockWithNamedJointIndex(name, [&](int index) { clearJointData(index); }); + writeLockWithNamedJointIndex(name, [&](int index) { + clearJointData(index); + }); } void MyAvatar::clearJointsData() { @@ -2362,36 +2392,36 @@ void MyAvatar::setSkeletonModelURL(const QUrl& skeletonModelURL) { _skeletonModelLoaded = false; std::shared_ptr skeletonConnection = std::make_shared(); - *skeletonConnection = QObject::connect(_skeletonModel.get(), &SkeletonModel::skeletonLoaded, - [this, skeletonModelChangeCount, skeletonConnection]() { - if (skeletonModelChangeCount == _skeletonModelChangeCount) { - if (_fullAvatarModelName.isEmpty()) { - // Store the FST file name into preferences - const auto& mapping = _skeletonModel->getGeometry()->getMapping(); - if (mapping.value("name").isValid()) { - _fullAvatarModelName = mapping.value("name").toString(); - } - } + *skeletonConnection = QObject::connect(_skeletonModel.get(), &SkeletonModel::skeletonLoaded, [this, skeletonModelChangeCount, skeletonConnection]() { + if (skeletonModelChangeCount == _skeletonModelChangeCount) { - initHeadBones(); - _skeletonModel->setCauterizeBoneSet(_headBoneSet); - _fstAnimGraphOverrideUrl = - _skeletonModel->getGeometry()->getAnimGraphOverrideUrl(); - initAnimGraph(); - initFlowFromFST(); + if (_fullAvatarModelName.isEmpty()) { + // Store the FST file name into preferences + const auto& mapping = _skeletonModel->getGeometry()->getMapping(); + if (mapping.value("name").isValid()) { + _fullAvatarModelName = mapping.value("name").toString(); + } + } - _skeletonModelLoaded = true; - } - QObject::disconnect(*skeletonConnection); - }); + initHeadBones(); + _skeletonModel->setCauterizeBoneSet(_headBoneSet); + _fstAnimGraphOverrideUrl = _skeletonModel->getGeometry()->getAnimGraphOverrideUrl(); + initAnimGraph(); + initFlowFromFST(); + _skeletonModelLoaded = true; + } + QObject::disconnect(*skeletonConnection); + }); + saveAvatarUrl(); emit skeletonChanged(); } bool isWearableEntity(const EntityItemPointer& entity) { - return entity->isVisible() && (entity->getParentID() == DependencyManager::get()->getSessionUUID() || - entity->getParentID() == AVATAR_SELF_ID); + return entity->isVisible() + && (entity->getParentID() == DependencyManager::get()->getSessionUUID() + || entity->getParentID() == AVATAR_SELF_ID); } void MyAvatar::removeWornAvatarEntity(const EntityItemID& entityID) { @@ -2415,7 +2445,9 @@ void MyAvatar::removeWornAvatarEntity(const EntityItemID& entityID) { void MyAvatar::clearWornAvatarEntities() { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); + _avatarEntitiesLock.withReadLock([&] { + avatarEntityIDs = _packedAvatarEntityData.keys(); + }); for (auto entityID : avatarEntityIDs) { removeWornAvatarEntity(entityID); } @@ -2441,7 +2473,9 @@ QVariantList MyAvatar::getAvatarEntitiesVariant() { EntityTreePointer entityTree = treeRenderer ? treeRenderer->getTree() : nullptr; if (entityTree) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); + _avatarEntitiesLock.withReadLock([&] { + avatarEntityIDs = _packedAvatarEntityData.keys(); + }); for (const auto& entityID : avatarEntityIDs) { auto entity = entityTree->findEntityByID(entityID); if (!entity) { @@ -2466,6 +2500,7 @@ QVariantList MyAvatar::getAvatarEntitiesVariant() { return avatarEntitiesData; } + void MyAvatar::resetFullAvatarURL() { auto lastAvatarURL = getFullAvatarURLFromPreferences(); auto lastAvatarName = getFullAvatarModelName(); @@ -2474,8 +2509,11 @@ void MyAvatar::resetFullAvatarURL() { } void MyAvatar::useFullAvatarURL(const QUrl& fullAvatarURL, const QString& modelName) { + if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "useFullAvatarURL", Q_ARG(const QUrl&, fullAvatarURL), Q_ARG(const QString&, modelName)); + BLOCKING_INVOKE_METHOD(this, "useFullAvatarURL", + Q_ARG(const QUrl&, fullAvatarURL), + Q_ARG(const QString&, modelName)); return; } @@ -2529,7 +2567,7 @@ controller::Pose MyAvatar::getControllerPoseInSensorFrame(controller::Action act if (iter != _controllerPoseMap.end()) { return iter->second; } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2538,7 +2576,7 @@ controller::Pose MyAvatar::getControllerPoseInWorldFrame(controller::Action acti if (pose.valid) { return pose.transform(getSensorToWorldMatrix()); } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2548,7 +2586,7 @@ controller::Pose MyAvatar::getControllerPoseInAvatarFrame(controller::Action act glm::mat4 invAvatarMatrix = glm::inverse(createMatFromQuatAndPos(getWorldOrientation(), getWorldPosition())); return pose.transform(invAvatarMatrix); } else { - return controller::Pose(); // invalid pose + return controller::Pose(); // invalid pose } } @@ -2570,7 +2608,7 @@ void MyAvatar::updateMotors() { float verticalMotorTimescale; if (_characterController.getState() == CharacterController::State::Hover || - _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { + _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { horizontalMotorTimescale = FLYING_MOTOR_TIMESCALE; verticalMotorTimescale = FLYING_MOTOR_TIMESCALE; } else { @@ -2580,7 +2618,7 @@ void MyAvatar::updateMotors() { if (_motionBehaviors & AVATAR_MOTION_ACTION_MOTOR_ENABLED) { if (_characterController.getState() == CharacterController::State::Hover || - _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { + _characterController.computeCollisionMask() == BULLET_COLLISION_MASK_COLLISIONLESS) { motorRotation = getMyHead()->getHeadOrientation(); } else { // non-hovering = walking: follow camera twist about vertical but not lift @@ -2588,15 +2626,14 @@ void MyAvatar::updateMotors() { // however, we need to perform the decomposition in the avatar-frame // using the local UP axis and then transform back into world-frame glm::quat orientation = getWorldOrientation(); - glm::quat headOrientation = glm::inverse(orientation) * getMyHead()->getHeadOrientation(); // avatar-frame + glm::quat headOrientation = glm::inverse(orientation) * getMyHead()->getHeadOrientation(); // avatar-frame glm::quat liftRotation; swingTwistDecomposition(headOrientation, Vectors::UNIT_Y, liftRotation, motorRotation); motorRotation = orientation * motorRotation; } if (_isPushing || _isBraking || !_isBeingPushed) { - _characterController.addMotor(_actionMotorVelocity, motorRotation, horizontalMotorTimescale, - verticalMotorTimescale); + _characterController.addMotor(_actionMotorVelocity, motorRotation, horizontalMotorTimescale, verticalMotorTimescale); } else { // _isBeingPushed must be true --> disable action motor by giving it a long timescale, // otherwise it's attempt to "stand in in place" could defeat scripted motor/thrusts @@ -2616,8 +2653,7 @@ void MyAvatar::updateMotors() { _characterController.addMotor(_scriptedMotorVelocity, motorRotation, _scriptedMotorTimescale); } else { // dynamic mode - _characterController.addMotor(_scriptedMotorVelocity, motorRotation, horizontalMotorTimescale, - verticalMotorTimescale); + _characterController.addMotor(_scriptedMotorVelocity, motorRotation, horizontalMotorTimescale, verticalMotorTimescale); } } @@ -2722,7 +2758,8 @@ void MyAvatar::setScriptedMotorVelocity(const glm::vec3& velocity) { void MyAvatar::setScriptedMotorTimescale(float timescale) { // we clamp the timescale on the large side (instead of just the low side) to prevent // obnoxiously large values from introducing NaN into avatar's velocity - _scriptedMotorTimescale = glm::clamp(timescale, MIN_SCRIPTED_MOTOR_TIMESCALE, DEFAULT_SCRIPTED_MOTOR_TIMESCALE); + _scriptedMotorTimescale = glm::clamp(timescale, MIN_SCRIPTED_MOTOR_TIMESCALE, + DEFAULT_SCRIPTED_MOTOR_TIMESCALE); } void MyAvatar::setScriptedMotorFrame(QString frame) { @@ -2763,18 +2800,21 @@ SharedSoundPointer MyAvatar::getCollisionSound() { return _collisionSound; } -void MyAvatar::attach(const QString& modelURL, - const QString& jointName, - const glm::vec3& translation, - const glm::quat& rotation, - float scale, - bool isSoft, - bool allowDuplicates, - bool useSaved) { +void MyAvatar::attach(const QString& modelURL, const QString& jointName, + const glm::vec3& translation, const glm::quat& rotation, + float scale, bool isSoft, + bool allowDuplicates, bool useSaved) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "attach", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName), - Q_ARG(const glm::vec3&, translation), Q_ARG(const glm::quat&, rotation), Q_ARG(float, scale), - Q_ARG(bool, isSoft), Q_ARG(bool, allowDuplicates), Q_ARG(bool, useSaved)); + BLOCKING_INVOKE_METHOD(this, "attach", + Q_ARG(const QString&, modelURL), + Q_ARG(const QString&, jointName), + Q_ARG(const glm::vec3&, translation), + Q_ARG(const glm::quat&, rotation), + Q_ARG(float, scale), + Q_ARG(bool, isSoft), + Q_ARG(bool, allowDuplicates), + Q_ARG(bool, useSaved) + ); return; } AttachmentData data; @@ -2792,7 +2832,10 @@ void MyAvatar::attach(const QString& modelURL, void MyAvatar::detachOne(const QString& modelURL, const QString& jointName) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "detachOne", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName)); + BLOCKING_INVOKE_METHOD(this, "detachOne", + Q_ARG(const QString&, modelURL), + Q_ARG(const QString&, jointName) + ); return; } QUuid entityID; @@ -2804,7 +2847,10 @@ void MyAvatar::detachOne(const QString& modelURL, const QString& jointName) { void MyAvatar::detachAll(const QString& modelURL, const QString& jointName) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "detachAll", Q_ARG(const QString&, modelURL), Q_ARG(const QString&, jointName)); + BLOCKING_INVOKE_METHOD(this, "detachAll", + Q_ARG(const QString&, modelURL), + Q_ARG(const QString&, jointName) + ); return; } QUuid entityID; @@ -2816,7 +2862,8 @@ void MyAvatar::detachAll(const QString& modelURL, const QString& jointName) { void MyAvatar::setAttachmentData(const QVector& attachmentData) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "setAttachmentData", Q_ARG(const QVector&, attachmentData)); + BLOCKING_INVOKE_METHOD(this, "setAttachmentData", + Q_ARG(const QVector&, attachmentData)); return; } std::vector newEntitiesProperties; @@ -2839,10 +2886,12 @@ void MyAvatar::setAttachmentData(const QVector& attachmentData) emit attachmentsChanged(); } -QVector MyAvatar::getAttachmentData() const { +QVector MyAvatar::getAttachmentData() const { QVector attachmentData; QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); + _avatarEntitiesLock.withReadLock([&] { + avatarEntityIDs = _packedAvatarEntityData.keys(); + }); for (const auto& entityID : avatarEntityIDs) { auto properties = DependencyManager::get()->getEntityProperties(entityID); AttachmentData data = entityPropertiesToAttachmentData(properties); @@ -2861,7 +2910,8 @@ QVariantList MyAvatar::getAttachmentsVariant() const { void MyAvatar::setAttachmentsVariant(const QVariantList& variant) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "setAttachmentsVariant", Q_ARG(const QVariantList&, variant)); + BLOCKING_INVOKE_METHOD(this, "setAttachmentsVariant", + Q_ARG(const QVariantList&, variant)); return; } QVector newAttachments; @@ -2872,12 +2922,14 @@ void MyAvatar::setAttachmentsVariant(const QVariantList& variant) { newAttachments.append(attachment); } } - setAttachmentData(newAttachments); + setAttachmentData(newAttachments); } bool MyAvatar::findAvatarEntity(const QString& modelURL, const QString& jointName, QUuid& entityID) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); + _avatarEntitiesLock.withReadLock([&] { + avatarEntityIDs = _packedAvatarEntityData.keys(); + }); for (const auto& entityID : avatarEntityIDs) { auto props = DependencyManager::get()->getEntityProperties(entityID); if (props.getModelURL() == modelURL && @@ -2978,7 +3030,7 @@ void MyAvatar::setAnimGraphUrl(const QUrl& url) { emit animGraphUrlChanged(url); destroyAnimGraph(); - _skeletonModel->reset(); // Why is this necessary? Without this, we crash in the next render. + _skeletonModel->reset(); // Why is this necessary? Without this, we crash in the next render. _currentAnimGraphUrl.set(url); _skeletonModel->getRig().initAnimGraph(url); @@ -3011,16 +3063,18 @@ void MyAvatar::destroyAnimGraph() { } void MyAvatar::animGraphLoaded() { - _bodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. - updateSensorToWorldMatrix(); // Uses updated position/orientation and _bodySensorMatrix changes + _bodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. + updateSensorToWorldMatrix(); // Uses updated position/orientation and _bodySensorMatrix changes _isAnimatingScale = true; _cauterizationNeedsUpdate = true; disconnect(&(_skeletonModel->getRig()), SIGNAL(onLoadComplete()), this, SLOT(animGraphLoaded())); } void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { + Avatar::postUpdate(deltaTime, scene); if (_enableDebugDrawDefaultPose || _enableDebugDrawAnimPose) { + auto animSkeleton = _skeletonModel->getRig().getAnimSkeleton(); // the rig is in the skeletonModel frame @@ -3028,8 +3082,7 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { if (_enableDebugDrawDefaultPose && animSkeleton) { glm::vec4 gray(0.2f, 0.2f, 0.2f, 0.2f); - AnimDebugDraw::getInstance().addAbsolutePoses("myAvatarDefaultPoses", animSkeleton, - _skeletonModel->getRig().getAbsoluteDefaultPoses(), xform, gray); + AnimDebugDraw::getInstance().addAbsolutePoses("myAvatarDefaultPoses", animSkeleton, _skeletonModel->getRig().getAbsoluteDefaultPoses(), xform, gray); } if (_enableDebugDrawAnimPose && animSkeleton) { @@ -3050,15 +3103,13 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { auto rightHandPose = getControllerPoseInWorldFrame(controller::Action::RIGHT_HAND); if (leftHandPose.isValid()) { - DebugDraw::getInstance().addMarker("leftHandController", leftHandPose.getRotation(), leftHandPose.getTranslation(), - glm::vec4(1)); + DebugDraw::getInstance().addMarker("leftHandController", leftHandPose.getRotation(), leftHandPose.getTranslation(), glm::vec4(1)); } else { DebugDraw::getInstance().removeMarker("leftHandController"); } if (rightHandPose.isValid()) { - DebugDraw::getInstance().addMarker("rightHandController", rightHandPose.getRotation(), - rightHandPose.getTranslation(), glm::vec4(1)); + DebugDraw::getInstance().addMarker("rightHandController", rightHandPose.getRotation(), rightHandPose.getTranslation(), glm::vec4(1)); } else { DebugDraw::getInstance().removeMarker("rightHandController"); } @@ -3075,9 +3126,14 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { AnimPose rigToWorldPose(glm::vec3(1.0f), getWorldOrientation() * Quaternions::Y_180, getWorldPosition()); const int NUM_DEBUG_COLORS = 8; const glm::vec4 DEBUG_COLORS[NUM_DEBUG_COLORS] = { - glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 1.0f), - glm::vec4(0.25f, 0.25f, 1.0f, 1.0f), glm::vec4(1.0f, 1.0f, 0.0f, 1.0f), glm::vec4(0.25f, 1.0f, 1.0f, 1.0f), - glm::vec4(1.0f, 0.25f, 1.0f, 1.0f), glm::vec4(1.0f, 0.65f, 0.0f, 1.0f) // Orange you glad I added this color? + glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), + glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), + glm::vec4(0.0f, 1.0f, 0.0f, 1.0f), + glm::vec4(0.25f, 0.25f, 1.0f, 1.0f), + glm::vec4(1.0f, 1.0f, 0.0f, 1.0f), + glm::vec4(0.25f, 1.0f, 1.0f, 1.0f), + glm::vec4(1.0f, 0.25f, 1.0f, 1.0f), + glm::vec4(1.0f, 0.65f, 0.0f, 1.0f) // Orange you glad I added this color? }; if (_skeletonModel && _skeletonModel->isLoaded()) { @@ -3088,7 +3144,7 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { AnimPose jointPose; rig.getAbsoluteJointPoseInRigFrame(i, jointPose); const AnimPose pose = rigToWorldPose * jointPose; - auto& multiSphere = _multiSphereShapes[i]; + auto &multiSphere = _multiSphereShapes[i]; auto debugLines = multiSphere.getDebugLines(); DebugDraw::getInstance().drawRays(debugLines, DEBUG_COLORS[i % NUM_DEBUG_COLORS], pose.trans(), pose.rot()); } @@ -3098,6 +3154,7 @@ void MyAvatar::postUpdate(float deltaTime, const render::ScenePointer& scene) { } void MyAvatar::preDisplaySide(const RenderArgs* renderArgs) { + // toggle using the cauterizedBones depending on where the camera is and the rendering pass type. const bool shouldDrawHead = shouldRenderHead(renderArgs); if (shouldDrawHead != _prevShouldDrawHead) { @@ -3142,7 +3199,7 @@ int MyAvatar::sendAvatarDataPacket(bool sendAll) { // Compute the next send window based on how much data we sent and what // data rate we're trying to max at. - milliseconds timeUntilNextSend{ bytesSent / maxDataRateBytesPerMilliseconds }; + milliseconds timeUntilNextSend { bytesSent / maxDataRateBytesPerMilliseconds }; _nextTraitsSendWindow += timeUntilNextSend; // Don't let the next send window lag behind if we're not sending a lot of data. @@ -3227,6 +3284,7 @@ void MyAvatar::setRotationThreshold(float angleRadians) { } void MyAvatar::updateOrientation(float deltaTime) { + // Smoothly rotate body with arrow keys float targetSpeed = getDriveKey(YAW) * _yawSpeed; if (targetSpeed != 0.0f) { @@ -3265,8 +3323,8 @@ void MyAvatar::updateOrientation(float deltaTime) { } // Use head/HMD roll to turn while flying, but not when standing still. - if (qApp->isHMDMode() && getCharacterController()->getState() == CharacterController::State::Hover && - _hmdRollControlEnabled && hasDriveInput()) { + if (qApp->isHMDMode() && getCharacterController()->getState() == CharacterController::State::Hover && _hmdRollControlEnabled && hasDriveInput()) { + // Turn with head roll. const float MIN_CONTROL_SPEED = 2.0f * getSensorToWorldScale(); // meters / sec const glm::vec3 characterForward = getWorldOrientation() * Vectors::UNIT_NEG_Z; @@ -3274,6 +3332,7 @@ void MyAvatar::updateOrientation(float deltaTime) { // only enable roll-turns if we are moving forward or backward at greater then MIN_CONTROL_SPEED if (fabsf(forwardSpeed) >= MIN_CONTROL_SPEED) { + float direction = forwardSpeed > 0.0f ? 1.0f : -1.0f; float rollAngle = glm::degrees(asinf(glm::dot(IDENTITY_UP, _hmdSensorOrientation * IDENTITY_RIGHT))); float rollSign = rollAngle < 0.0f ? -1.0f : 1.0f; @@ -3320,8 +3379,8 @@ void MyAvatar::updateOrientation(float deltaTime) { head->setBaseRoll(ROLL(euler)); } else { head->setBaseYaw(0.0f); - head->setBasePitch(getHead()->getBasePitch() + getDriveKey(PITCH) * _pitchSpeed * deltaTime + - getDriveKey(DELTA_PITCH) * _pitchSpeed / PITCH_SPEED_DEFAULT); + head->setBasePitch(getHead()->getBasePitch() + getDriveKey(PITCH) * _pitchSpeed * deltaTime + + getDriveKey(DELTA_PITCH) * _pitchSpeed / PITCH_SPEED_DEFAULT); head->setBaseRoll(0.0f); } } @@ -3331,15 +3390,20 @@ float MyAvatar::calculateGearedSpeed(const float driveKey) { float sign = (driveKey < 0.0f) ? -1.0f : 1.0f; if (absDriveKey > getDriveGear5()) { return sign * 1.0f; - } else if (absDriveKey > getDriveGear4()) { + } + else if (absDriveKey > getDriveGear4()) { return sign * 0.8f; - } else if (absDriveKey > getDriveGear3()) { + } + else if (absDriveKey > getDriveGear3()) { return sign * 0.6f; - } else if (absDriveKey > getDriveGear2()) { + } + else if (absDriveKey > getDriveGear2()) { return sign * 0.4f; - } else if (absDriveKey > getDriveGear1()) { + } + else if (absDriveKey > getDriveGear1()) { return sign * 0.2f; - } else { + } + else { return sign * 0.0f; } } @@ -3371,10 +3435,8 @@ glm::vec3 MyAvatar::scaleMotorSpeed(const glm::vec3 forward, const glm::vec3 rig case LocomotionControlsMode::CONTROLS_ANALOG: case LocomotionControlsMode::CONTROLS_ANALOG_PLUS: if (zSpeed || xSpeed) { - glm::vec3 scaledForward = getSensorToWorldScale() * calculateGearedSpeed(zSpeed) * _walkSpeedScalar * - ((zSpeed >= stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * forward; - glm::vec3 scaledRight = getSensorToWorldScale() * calculateGearedSpeed(xSpeed) * _walkSpeedScalar * - ((xSpeed > stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * right; + glm::vec3 scaledForward = getSensorToWorldScale() * calculateGearedSpeed(zSpeed) * _walkSpeedScalar * ((zSpeed >= stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * forward; + glm::vec3 scaledRight = getSensorToWorldScale() * calculateGearedSpeed(xSpeed) * _walkSpeedScalar * ((xSpeed > stickFullOn) ? getSprintSpeed() : getWalkSpeed()) * right; direction = scaledForward + scaledRight; return direction; } else { @@ -3396,7 +3458,7 @@ glm::vec3 MyAvatar::scaleMotorSpeed(const glm::vec3 forward, const glm::vec3 rig } } -glm::vec3 MyAvatar::calculateScaledDirection() { +glm::vec3 MyAvatar::calculateScaledDirection(){ CharacterController::State state = _characterController.getState(); // compute action input @@ -3452,8 +3514,8 @@ glm::vec3 MyAvatar::calculateScaledDirection() { void MyAvatar::updateActionMotor(float deltaTime) { bool thrustIsPushing = (glm::length2(_thrust) > EPSILON); - bool scriptedMotorIsPushing = - (_motionBehaviors & AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED) && _scriptedMotorTimescale < MAX_CHARACTER_MOTOR_TIMESCALE; + bool scriptedMotorIsPushing = (_motionBehaviors & AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED) + && _scriptedMotorTimescale < MAX_CHARACTER_MOTOR_TIMESCALE; _isBeingPushed = thrustIsPushing || scriptedMotorIsPushing; if (_isPushing || _isBeingPushed) { // we don't want the motor to brake if a script is pushing the avatar around @@ -3483,7 +3545,7 @@ void MyAvatar::updateActionMotor(float deltaTime) { float motorSpeed = glm::length(_actionMotorVelocity); float finalMaxMotorSpeed = sensorToWorldScale * DEFAULT_AVATAR_MAX_FLYING_SPEED * _walkSpeedScalar; - float speedGrowthTimescale = 2.0f; + float speedGrowthTimescale = 2.0f; float speedIncreaseFactor = 1.8f * _walkSpeedScalar; motorSpeed *= 1.0f + glm::clamp(deltaTime / speedGrowthTimescale, 0.0f, 1.0f) * speedIncreaseFactor; const float maxBoostSpeed = sensorToWorldScale * MAX_BOOST_SPEED; @@ -3523,7 +3585,7 @@ void MyAvatar::updatePosition(float deltaTime) { float sensorToWorldScale2 = sensorToWorldScale * sensorToWorldScale; vec3 velocity = getWorldVelocity(); float speed2 = glm::length2(velocity); - const float MOVING_SPEED_THRESHOLD_SQUARED = 0.0001f; // 0.01 m/s + const float MOVING_SPEED_THRESHOLD_SQUARED = 0.0001f; // 0.01 m/s _moving = speed2 > sensorToWorldScale2 * MOVING_SPEED_THRESHOLD_SQUARED; if (_moving) { // scan for walkability @@ -3548,17 +3610,12 @@ void MyAvatar::updateViewBoom() { } } -void MyAvatar::updateCollisionSound(const glm::vec3& penetration, float deltaTime, float frequency) { +void MyAvatar::updateCollisionSound(const glm::vec3 &penetration, float deltaTime, float frequency) { // COLLISION SOUND API in Audio has been removed } -bool findAvatarAvatarPenetration(const glm::vec3 positionA, - float radiusA, - float heightA, - const glm::vec3 positionB, - float radiusB, - float heightB, - glm::vec3& penetration) { +bool findAvatarAvatarPenetration(const glm::vec3 positionA, float radiusA, float heightA, + const glm::vec3 positionB, float radiusB, float heightB, glm::vec3& penetration) { glm::vec3 positionBA = positionB - positionA; float xzDistance = sqrt(positionBA.x * positionBA.x + positionBA.z * positionBA.z); if (xzDistance < (radiusA + radiusB)) { @@ -3620,7 +3677,9 @@ void MyAvatar::setSessionUUID(const QUuid& sessionUUID) { EntityTreePointer entityTree = treeRenderer ? treeRenderer->getTree() : nullptr; if (entityTree) { QList avatarEntityIDs; - _avatarEntitiesLock.withReadLock([&] { avatarEntityIDs = _packedAvatarEntityData.keys(); }); + _avatarEntitiesLock.withReadLock([&] { + avatarEntityIDs = _packedAvatarEntityData.keys(); + }); bool sendPackets = !DependencyManager::get()->getSessionUUID().isNull(); EntityEditPacketSender* packetSender = qApp->getEntityEditPacketSender(); entityTree->withWriteLock([&] { @@ -3764,18 +3823,16 @@ void MyAvatar::goToLocation(const QVariant& propertiesVar) { } void MyAvatar::goToFeetLocation(const glm::vec3& newPosition, - bool hasOrientation, - const glm::quat& newOrientation, + bool hasOrientation, const glm::quat& newOrientation, bool shouldFaceLocation) { _goToFeetAjustment = true; goToLocation(newPosition, hasOrientation, newOrientation, shouldFaceLocation); } void MyAvatar::goToLocation(const glm::vec3& newPosition, - bool hasOrientation, - const glm::quat& newOrientation, - bool shouldFaceLocation, - bool withSafeLanding) { + bool hasOrientation, const glm::quat& newOrientation, + bool shouldFaceLocation, bool withSafeLanding) { + // Most cases of going to a place or user go through this now. Some possible improvements to think about in the future: // - It would be nice if this used the same teleport steps and smoothing as in the teleport.js script, as long as it // still worked if the target is in the air. @@ -3789,16 +3846,16 @@ void MyAvatar::goToLocation(const glm::vec3& newPosition, // compute the position (e.g., so that if I'm on stage, going to me would compute an available seat in the audience rather than // being in my face on-stage). Note that this could work for going to an entity as well as to a person. - qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - moving to " << newPosition.x << ", " << newPosition.y << ", " - << newPosition.z; + qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - moving to " << newPosition.x << ", " + << newPosition.y << ", " << newPosition.z; _goToPending = true; _goToPosition = newPosition; _goToSafe = withSafeLanding; _goToOrientation = getWorldOrientation(); if (hasOrientation) { - qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - new orientation is " << newOrientation.x << ", " - << newOrientation.y << ", " << newOrientation.z << ", " << newOrientation.w; + qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - new orientation is " + << newOrientation.x << ", " << newOrientation.y << ", " << newOrientation.z << ", " << newOrientation.w; // orient the user to face the target glm::quat quatOrientation = cancelOutRollAndPitch(newOrientation); @@ -3817,7 +3874,7 @@ void MyAvatar::goToLocation(const glm::vec3& newPosition, emit transformChanged(); } -void MyAvatar::goToLocationAndEnableCollisions(const glm::vec3& position) { // See use case in safeLanding. +void MyAvatar::goToLocationAndEnableCollisions(const glm::vec3& position) { // See use case in safeLanding. goToLocation(position); QMetaObject::invokeMethod(this, "setCollisionsEnabled", Qt::QueuedConnection, Q_ARG(bool, true)); } @@ -3843,29 +3900,29 @@ bool MyAvatar::safeLanding(const glm::vec3& position) { } if (!getCollisionsEnabled()) { goToLocation(better); // recurses on next update - } else { // If you try to go while stuck, physics will keep you stuck. + } else { // If you try to go while stuck, physics will keep you stuck. setCollisionsEnabled(false); // Don't goToLocation just yet. Yield so that physics can act on the above. - QMetaObject::invokeMethod(this, "goToLocationAndEnableCollisions", - Qt::QueuedConnection, // The equivalent of javascript nextTick - Q_ARG(glm::vec3, better)); - } - return true; + QMetaObject::invokeMethod(this, "goToLocationAndEnableCollisions", Qt::QueuedConnection, // The equivalent of javascript nextTick + Q_ARG(glm::vec3, better)); + } + return true; } // If position is not reliably safe from being stuck by physics, answer true and place a candidate better position in betterPositionOut. bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& betterPositionOut) { + // We begin with utilities and tests. The Algorithm in four parts is below. // NOTE: we use estimated avatar height here instead of the bullet capsule halfHeight, because // the domain avatar height limiting might not have taken effect yet on the actual bullet shape. auto halfHeight = 0.5f * getHeight(); if (halfHeight == 0) { - return false; // zero height avatar + return false; // zero height avatar } auto entityTree = DependencyManager::get()->getTree(); if (!entityTree) { - return false; // no entity tree + return false; // no entity tree } // More utilities. const auto capsuleCenter = positionIn; @@ -3877,26 +3934,21 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette betterPositionOut = upperIntersection + (up * halfHeight); return true; }; - auto findIntersection = [&](const glm::vec3& startPointIn, const glm::vec3& directionIn, glm::vec3& intersectionOut, - EntityItemID& entityIdOut, glm::vec3& normalOut) { + auto findIntersection = [&](const glm::vec3& startPointIn, const glm::vec3& directionIn, glm::vec3& intersectionOut, EntityItemID& entityIdOut, glm::vec3& normalOut) { OctreeElementPointer element; float distance; BoxFace face; - const auto lockType = Octree::Lock; // Should we refactor to take a lock just once? + const auto lockType = Octree::Lock; // Should we refactor to take a lock just once? bool* accurateResult = NULL; // This isn't quite what we really want here. findRayIntersection always works on mesh, skipping entirely based on collidable. // What we really want is to use the collision hull! // See https://highfidelity.fogbugz.com/f/cases/5003/findRayIntersection-has-option-to-use-collidableOnly-but-doesn-t-actually-use-colliders QVariantMap extraInfo; - EntityItemID entityID = - entityTree->evalRayIntersection(startPointIn, directionIn, include, ignore, - PickFilter(PickFilter::getBitMask(PickFilter::FlagBit::COLLIDABLE) | - PickFilter::getBitMask(PickFilter::FlagBit::PRECISE) | - PickFilter::getBitMask(PickFilter::FlagBit::DOMAIN_ENTITIES) | - PickFilter::getBitMask( - PickFilter::FlagBit::AVATAR_ENTITIES)), // exclude Local entities - element, distance, face, normalOut, extraInfo, lockType, accurateResult); + EntityItemID entityID = entityTree->evalRayIntersection(startPointIn, directionIn, include, ignore, + PickFilter(PickFilter::getBitMask(PickFilter::FlagBit::COLLIDABLE) | PickFilter::getBitMask(PickFilter::FlagBit::PRECISE) + | PickFilter::getBitMask(PickFilter::FlagBit::DOMAIN_ENTITIES) | PickFilter::getBitMask(PickFilter::FlagBit::AVATAR_ENTITIES)), // exclude Local entities + element, distance, face, normalOut, extraInfo, lockType, accurateResult); if (entityID.isNull()) { return false; } @@ -3911,12 +3963,12 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette // We currently believe that physics will reliably push us out if our feet are embedded, // as long as our capsule center is out and there's room above us. Here we have those // conditions, so no need to check our feet below. - return false; // nothing above + return false; // nothing above } if (!findIntersection(capsuleCenter, down, lowerIntersection, lowerId, lowerNormal)) { // Our head may be embedded, but our center is out and there's room below. See corresponding comment above. - return false; // nothing below + return false; // nothing below } // See if we have room between entities above and below, but that we are not contained. @@ -3924,8 +3976,7 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette // I.e., we are in a clearing between two objects. if (isDown(upperNormal) && isUp(lowerNormal)) { auto spaceBetween = glm::distance(upperIntersection, lowerIntersection); - const float halfHeightFactor = - 2.25f; // Until case 5003 is fixed (and maybe after?), we need a fudge factor. Also account for content modelers not being precise. + const float halfHeightFactor = 2.25f; // Until case 5003 is fixed (and maybe after?), we need a fudge factor. Also account for content modelers not being precise. if (spaceBetween > (halfHeightFactor * halfHeight)) { // There is room for us to fit in that clearing. If there wasn't, physics would oscilate us between the objects above and below. // We're now going to iterate upwards through successive upperIntersections, testing to see if we're contained within the top surface of some entity. @@ -3937,7 +3988,7 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette ignore.push_back(upperId); if (!findIntersection(upperIntersection, up, upperIntersection, upperId, upperNormal)) { // We're not inside an entity, and from the nested tests, we have room between what is above and below. So position is good! - return false; // enough room + return false; // enough room } if (isUp(upperNormal)) { // This new intersection is the top surface of an entity that we have not yet seen, which means we're contained within it. @@ -3952,18 +4003,19 @@ bool MyAvatar::requiresSafeLanding(const glm::vec3& positionIn, glm::vec3& bette } } - include.push_back(upperId); // We're now looking for the intersection from above onto this entity. + include.push_back(upperId); // We're now looking for the intersection from above onto this entity. const float big = (float)TREE_SCALE; const auto skyHigh = up * big; auto fromAbove = capsuleCenter + skyHigh; if (!findIntersection(fromAbove, down, upperIntersection, upperId, upperNormal)) { - return false; // Unable to find a landing + return false; // Unable to find a landing } // Our arbitrary rule is to always go up. There's no need to look down or sideways for a "closer" safe candidate. return mustMove(); } void MyAvatar::updateMotionBehaviorFromMenu() { + if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "updateMotionBehaviorFromMenu"); return; @@ -4047,7 +4099,7 @@ int MyAvatar::getMovementReference() { return _movementReference; } -void MyAvatar::setControlSchemeIndex(int index) { +void MyAvatar::setControlSchemeIndex(int index){ if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setControlSchemeIndex", Q_ARG(int, index)); return; @@ -4065,8 +4117,7 @@ void MyAvatar::setDriveGear1(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear1", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) - return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; _driveGear1 = (shiftPoint < _driveGear2) ? shiftPoint : _driveGear1; } @@ -4087,8 +4138,7 @@ void MyAvatar::setDriveGear2(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear2", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) - return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; _driveGear2 = (shiftPoint < _driveGear3 && shiftPoint >= _driveGear1) ? shiftPoint : _driveGear2; } @@ -4109,8 +4159,7 @@ void MyAvatar::setDriveGear3(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear3", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) - return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; _driveGear3 = (shiftPoint < _driveGear4 && shiftPoint >= _driveGear2) ? shiftPoint : _driveGear3; } @@ -4131,8 +4180,7 @@ void MyAvatar::setDriveGear4(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear4", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) - return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; _driveGear4 = (shiftPoint < _driveGear5 && shiftPoint >= _driveGear3) ? shiftPoint : _driveGear4; } @@ -4153,8 +4201,7 @@ void MyAvatar::setDriveGear5(float shiftPoint) { QMetaObject::invokeMethod(this, "setDriveGear5", Q_ARG(float, shiftPoint)); return; } - if (shiftPoint > 1.0f || shiftPoint < 0.0f) - return; + if (shiftPoint > 1.0f || shiftPoint < 0.0f) return; _driveGear5 = (shiftPoint > _driveGear4) ? shiftPoint : _driveGear5; } @@ -4180,6 +4227,7 @@ float MyAvatar::getAvatarScale() { } void MyAvatar::setAvatarScale(float val) { + if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setAvatarScale", Q_ARG(float, val)); return; @@ -4189,6 +4237,7 @@ void MyAvatar::setAvatarScale(float val) { } void MyAvatar::setCollisionsEnabled(bool enabled) { + if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setCollisionsEnabled", Q_ARG(bool, enabled)); return; @@ -4204,6 +4253,7 @@ bool MyAvatar::getCollisionsEnabled() { } void MyAvatar::setOtherAvatarsCollisionsEnabled(bool enabled) { + if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setOtherAvatarsCollisionsEnabled", Q_ARG(bool, enabled)); return; @@ -4359,7 +4409,7 @@ glm::mat4 MyAvatar::deriveBodyFromHMDSensor() const { // AJT: TODO: can remove this Y_180, if we remove the higher level one. glm::vec3 headToNeck = headOrientation * Quaternions::Y_180 * (localNeck - localHead); - glm::vec3 neckToRoot = headOrientationYawOnly * Quaternions::Y_180 * -localNeck; + glm::vec3 neckToRoot = headOrientationYawOnly * Quaternions::Y_180 * -localNeck; float invSensorToWorldScale = getUserEyeHeight() / getEyeHeight(); glm::vec3 bodyPos = headPosition + invSensorToWorldScale * (headToNeck + neckToRoot); @@ -4395,8 +4445,7 @@ glm::mat4 MyAvatar::getSpine2RotationRigSpace() const { spine2UpRigSpace = glm::vec3(0.0f, 1.0f, 0.0f); } generateBasisVectors(spine2UpRigSpace, spine2FwdRigSpace, u, v, w); - glm::mat4 spine2RigSpace(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), - glm::vec4(glm::vec3(0.0f, 0.0f, 0.0f), 1.0f)); + glm::mat4 spine2RigSpace(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), glm::vec4(glm::vec3(0.0f, 0.0f, 0.0f), 1.0f)); return spine2RigSpace; } @@ -4453,7 +4502,7 @@ glm::vec3 MyAvatar::computeCounterBalance() { QString name; float weight; glm::vec3 position; - JointMass(){}; + JointMass() {}; JointMass(QString n, float w, glm::vec3 p) { name = n; weight = w; @@ -4474,14 +4523,12 @@ glm::vec3 MyAvatar::computeCounterBalance() { tposeHead = getAbsoluteDefaultJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgHeadMass.name)); } if (_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name) != -1) { - cgLeftHandMass.position = - getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name)); + cgLeftHandMass.position = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgLeftHandMass.name)); } else { cgLeftHandMass.position = DEFAULT_AVATAR_LEFTHAND_POS; } if (_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name) != -1) { - cgRightHandMass.position = - getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name)); + cgRightHandMass.position = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint(cgRightHandMass.name)); } else { cgRightHandMass.position = DEFAULT_AVATAR_RIGHTHAND_POS; } @@ -4493,8 +4540,7 @@ glm::vec3 MyAvatar::computeCounterBalance() { } // find the current center of gravity position based on head and hand moments - glm::vec3 sumOfMoments = (cgHeadMass.weight * cgHeadMass.position) + (cgLeftHandMass.weight * cgLeftHandMass.position) + - (cgRightHandMass.weight * cgRightHandMass.position); + glm::vec3 sumOfMoments = (cgHeadMass.weight * cgHeadMass.position) + (cgLeftHandMass.weight * cgLeftHandMass.position) + (cgRightHandMass.weight * cgRightHandMass.position); float totalMass = cgHeadMass.weight + cgLeftHandMass.weight + cgRightHandMass.weight; glm::vec3 currentCg = (1.0f / totalMass) * sumOfMoments; @@ -4534,6 +4580,7 @@ glm::vec3 MyAvatar::computeCounterBalance() { // headOrientation, headPosition and hipsPosition are in avatar space // returns the matrix of the hips in Avatar space static glm::mat4 computeNewHipsMatrix(glm::quat headOrientation, glm::vec3 headPosition, glm::vec3 hipsPosition) { + glm::quat bodyOrientation = computeBodyFacingFromHead(headOrientation, Vectors::UNIT_Y); const float MIX_RATIO = 0.3f; @@ -4543,7 +4590,10 @@ static glm::mat4 computeNewHipsMatrix(glm::quat headOrientation, glm::vec3 headP glm::vec3 spineVec = headPosition - hipsPosition; glm::vec3 u, v, w; generateBasisVectors(glm::normalize(spineVec), hipsFacing, u, v, w); - return glm::mat4(glm::vec4(w, 0.0f), glm::vec4(u, 0.0f), glm::vec4(v, 0.0f), glm::vec4(hipsPosition, 1.0f)); + return glm::mat4(glm::vec4(w, 0.0f), + glm::vec4(u, 0.0f), + glm::vec4(v, 0.0f), + glm::vec4(hipsPosition, 1.0f)); } static void drawBaseOfSupport(float baseOfSupportScale, float footLocal, glm::mat4 avatarToWorld) { @@ -4584,8 +4634,7 @@ glm::mat4 MyAvatar::deriveBodyUsingCgModel() { if (_enableDebugDrawBaseOfSupport) { float scaleBaseOfSupport = getUserEyeHeight() / DEFAULT_AVATAR_EYE_HEIGHT; - glm::vec3 rightFootPositionLocal = - getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint("RightFoot")); + glm::vec3 rightFootPositionLocal = getAbsoluteJointTranslationInObjectFrame(_skeletonModel->getRig().indexOfJoint("RightFoot")); drawBaseOfSupport(scaleBaseOfSupport, rightFootPositionLocal.y, avatarToWorldMat); } @@ -4593,8 +4642,7 @@ glm::mat4 MyAvatar::deriveBodyUsingCgModel() { glm::vec3 cgHipsPosition = computeCounterBalance(); // find the new hips rotation using the new head-hips axis as the up axis - glm::mat4 avatarHipsMat = - computeNewHipsMatrix(glmExtractRotation(avatarHeadMat), extractTranslation(avatarHeadMat), cgHipsPosition); + glm::mat4 avatarHipsMat = computeNewHipsMatrix(glmExtractRotation(avatarHeadMat), extractTranslation(avatarHeadMat), cgHipsPosition); // convert hips from avatar to sensor space // The Y_180 is to convert from z forward to -z forward. @@ -4618,7 +4666,7 @@ static bool withinBaseOfSupport(const controller::Pose& head) { bool withinFrontBase = isInsideLine(userScale * frontLeft, userScale * frontRight, head.getTranslation()); bool withinBackBase = isInsideLine(userScale * backRight, userScale * backLeft, head.getTranslation()); bool withinLateralBase = (isInsideLine(userScale * frontRight, userScale * backRight, head.getTranslation()) && - isInsideLine(userScale * backLeft, userScale * frontLeft, head.getTranslation())); + isInsideLine(userScale * backLeft, userScale * frontLeft, head.getTranslation())); isWithinSupport = (withinFrontBase && withinBackBase && withinLateralBase); } return isWithinSupport; @@ -4652,8 +4700,7 @@ float MyAvatar::computeStandingHeightMode(const controller::Pose& head) { float modeInMeters = getCurrentStandingHeight(); if (head.isValid()) { std::map freq; - for (auto recentModeReadingsIterator = _recentModeReadings.begin(); - recentModeReadingsIterator != _recentModeReadings.end(); ++recentModeReadingsIterator) { + for(auto recentModeReadingsIterator = _recentModeReadings.begin(); recentModeReadingsIterator != _recentModeReadings.end(); ++recentModeReadingsIterator) { freq[*recentModeReadingsIterator] += 1; if (freq[*recentModeReadingsIterator] > greatestFrequency) { greatestFrequency = freq[*recentModeReadingsIterator]; @@ -4666,23 +4713,21 @@ float MyAvatar::computeStandingHeightMode(const controller::Pose& head) { // if not greater check for a reset if (getResetMode() && getControllerPoseInAvatarFrame(controller::Action::HEAD).isValid()) { setResetMode(false); - float resetModeInCentimeters = - glm::floor((head.getTranslation().y - MODE_CORRECTION_FACTOR) * CENTIMETERS_PER_METER); + float resetModeInCentimeters = glm::floor((head.getTranslation().y - MODE_CORRECTION_FACTOR)*CENTIMETERS_PER_METER); modeInMeters = (resetModeInCentimeters / CENTIMETERS_PER_METER); _recentModeReadings.clear(); } else { // if not greater and no reset, keep the mode as it is modeInMeters = getCurrentStandingHeight(); + } } } return modeInMeters; } -static bool handDirectionMatchesHeadDirection(const controller::Pose& leftHand, - const controller::Pose& rightHand, - const controller::Pose& head) { +static bool handDirectionMatchesHeadDirection(const controller::Pose& leftHand, const controller::Pose& rightHand, const controller::Pose& head) { const float VELOCITY_EPSILON = 0.02f; bool leftHandDirectionMatchesHead = true; bool rightHandDirectionMatchesHead = true; @@ -4720,7 +4765,7 @@ static bool handAngularVelocityBelowThreshold(const controller::Pose& leftHand, rightHandXZAngularVelocity = glm::length(xzRightHandAngularVelocity); } return ((leftHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD) && - (rightHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD)); + (rightHandXZAngularVelocity < DEFAULT_HANDS_ANGULAR_VELOCITY_STEPPING_THRESHOLD)); } static bool headVelocityGreaterThanThreshold(const controller::Pose& head) { @@ -4743,8 +4788,7 @@ static bool isHeadLevel(const controller::Pose& head, const glm::quat& averageHe glm::vec3 currentHeadEulers = glm::degrees(safeEulerAngles(head.getRotation())); diffFromAverageEulers = averageHeadEulers - currentHeadEulers; } - return ((fabs(diffFromAverageEulers.x) < DEFAULT_HEAD_PITCH_STEPPING_TOLERANCE) && - (fabs(diffFromAverageEulers.z) < DEFAULT_HEAD_ROLL_STEPPING_TOLERANCE)); + return ((fabs(diffFromAverageEulers.x) < DEFAULT_HEAD_PITCH_STEPPING_TOLERANCE) && (fabs(diffFromAverageEulers.z) < DEFAULT_HEAD_ROLL_STEPPING_TOLERANCE)); } float MyAvatar::getUserHeight() const { @@ -4794,6 +4838,7 @@ float MyAvatar::getWalkSpeed() const { } else { return _defaultWalkSpeed.get(); } + } float MyAvatar::getWalkBackwardSpeed() const { @@ -4810,6 +4855,7 @@ float MyAvatar::getWalkBackwardSpeed() const { } else { return _defaultWalkBackwardSpeed.get(); } + } bool MyAvatar::isReadyForPhysics() const { @@ -4819,7 +4865,8 @@ bool MyAvatar::isReadyForPhysics() const { void MyAvatar::setSprintMode(bool sprint) { if (qApp->isHMDMode()) { _walkSpeedScalar = sprint ? AVATAR_DESKTOP_SPRINT_SPEED_SCALAR : AVATAR_WALK_SPEED_SCALAR; - } else { + } + else { _walkSpeedScalar = sprint ? AVATAR_HMD_SPRINT_SPEED_SCALAR : AVATAR_WALK_SPEED_SCALAR; } } @@ -4843,6 +4890,7 @@ void MyAvatar::setIsInSittingState(bool isSitting) { } void MyAvatar::setUserRecenterModel(MyAvatar::SitStandModelType modelName) { + _userRecenterModel.set(modelName); switch (modelName) { @@ -4918,7 +4966,7 @@ void MyAvatar::setWalkBackwardSpeed(float value) { changed = false; break; } - + if (changed && prevVal != value) { emit walkBackwardSpeedChanged(value); } @@ -4941,7 +4989,6 @@ void MyAvatar::setSprintSpeed(float value) { _analogPlusSprintSpeed.set(value); break; default: - changed = false; break; } @@ -5089,6 +5136,7 @@ void driveKeysFromScriptValue(const QScriptValue& object, MyAvatar::DriveKeys& d driveKeys = static_cast(object.toUInt16()); } + void MyAvatar::lateUpdatePalms() { Avatar::updatePalms(); } @@ -5146,17 +5194,13 @@ void MyAvatar::FollowHelper::decrementTimeRemaining(float dt) { } } -bool MyAvatar::FollowHelper::shouldActivateRotation(const MyAvatar& myAvatar, - const glm::mat4& desiredBodyMatrix, - const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateRotation(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { const float FOLLOW_ROTATION_THRESHOLD = cosf(myAvatar.getRotationThreshold()); glm::vec2 bodyFacing = getFacingDir2D(currentBodyMatrix); return glm::dot(-myAvatar.getHeadControllerFacingMovingAverage(), bodyFacing) < FOLLOW_ROTATION_THRESHOLD; } -bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, - const glm::mat4& desiredBodyMatrix, - const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { // -z axis of currentBodyMatrix in world space. glm::vec3 forward = glm::normalize(glm::vec3(-currentBodyMatrix[0][2], -currentBodyMatrix[1][2], -currentBodyMatrix[2][2])); // x axis of currentBodyMatrix in world space. @@ -5187,6 +5231,7 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, } bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) const { + // get the current readings controller::Pose currentHeadPose = myAvatar.getControllerPoseInAvatarFrame(controller::Action::HEAD); controller::Pose currentLeftHandPose = myAvatar.getControllerPoseInAvatarFrame(controller::Action::LEFT_HAND); @@ -5199,7 +5244,8 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons if (myAvatar.getIsInWalkingState()) { stepDetected = true; } else { - if (!withinBaseOfSupport(currentHeadPose) && headAngularVelocityBelowThreshold(currentHeadPose) && + if (!withinBaseOfSupport(currentHeadPose) && + headAngularVelocityBelowThreshold(currentHeadPose) && isWithinThresholdHeightMode(currentHeadSensorPose, myAvatar.getCurrentStandingHeight(), myScale) && handDirectionMatchesHeadDirection(currentLeftHandPose, currentRightHandPose, currentHeadPose) && handAngularVelocityBelowThreshold(currentLeftHandPose, currentRightHandPose) && @@ -5211,15 +5257,13 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons myAvatar.setIsInWalkingState(true); } } else { - glm::vec3 defaultHipsPosition = - myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Hips")); - glm::vec3 defaultHeadPosition = - myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Head")); + glm::vec3 defaultHipsPosition = myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Hips")); + glm::vec3 defaultHeadPosition = myAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(myAvatar.getJointIndex("Head")); glm::vec3 currentHeadPosition = currentHeadPose.getTranslation(); float anatomicalHeadToHipsDistance = glm::length(defaultHeadPosition - defaultHipsPosition); - if (!isActive(Horizontal) && (!isActive(Vertical)) && - (glm::length(currentHeadPosition - defaultHipsPosition) > - (anatomicalHeadToHipsDistance + (DEFAULT_AVATAR_SPINE_STRETCH_LIMIT * anatomicalHeadToHipsDistance)))) { + if (!isActive(Horizontal) && + (!isActive(Vertical)) && + (glm::length(currentHeadPosition - defaultHipsPosition) > (anatomicalHeadToHipsDistance + (DEFAULT_AVATAR_SPINE_STRETCH_LIMIT * anatomicalHeadToHipsDistance)))) { myAvatar.setResetMode(true); stepDetected = true; if (glm::length(currentHeadPose.velocity) > DEFAULT_AVATAR_WALK_SPEED_THRESHOLD) { @@ -5231,9 +5275,7 @@ bool MyAvatar::FollowHelper::shouldActivateHorizontalCG(MyAvatar& myAvatar) cons return stepDetected; } -bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, - const glm::mat4& desiredBodyMatrix, - const glm::mat4& currentBodyMatrix) const { +bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { const float CYLINDER_TOP = 2.0f; const float CYLINDER_BOTTOM = -1.5f; const float SITTING_BOTTOM = -0.02f; @@ -5264,11 +5306,11 @@ bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, return returnValue; } -void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, - const glm::mat4& desiredBodyMatrix, - const glm::mat4& currentBodyMatrix, - bool hasDriveInput) { - if (myAvatar.getHMDLeanRecenterEnabled() && qApp->getCamera().getMode() != CAMERA_MODE_MIRROR) { +void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, + const glm::mat4& currentBodyMatrix, bool hasDriveInput) { + + if (myAvatar.getHMDLeanRecenterEnabled() && + qApp->getCamera().getMode() != CAMERA_MODE_MIRROR) { if (!isActive(Rotation) && (shouldActivateRotation(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { activate(Rotation); myAvatar.setHeadControllerFacingMovingAverage(myAvatar.getHeadControllerFacing()); @@ -5283,8 +5325,7 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, } } else { // center of gravity model is not enabled - if (!isActive(Horizontal) && - (shouldActivateHorizontal(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { + if (!isActive(Horizontal) && (shouldActivateHorizontal(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { activate(Horizontal); if (myAvatar.getEnableStepResetRotation() && !myAvatar.getIsInSittingState()) { activate(Rotation); @@ -5321,7 +5362,7 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, glm::quat currentHipsLocal = myAvatar.getAbsoluteJointRotationInObjectFrame(myAvatar.getJointIndex("Hips")); const glm::quat hipsinWorldSpace = followWorldPose.rot() * (Quaternions::Y_180 * (currentHipsLocal)); - const glm::vec3 avatarUpWorld = glm::normalize(followWorldPose.rot() * (Vectors::UP)); + const glm::vec3 avatarUpWorld = glm::normalize(followWorldPose.rot()*(Vectors::UP)); glm::quat resultingSwingInWorld; glm::quat resultingTwistInWorld; swingTwistDecomposition(hipsinWorldSpace, avatarUpWorld, resultingSwingInWorld, resultingTwistInWorld); @@ -5330,8 +5371,8 @@ void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, followWorldPose.scale() = glm::vec3(1.0f); if (isActive(Rotation)) { - //use the hmd reading for the hips follow - followWorldPose.rot() = glmExtractRotation(desiredWorldMatrix); + //use the hmd reading for the hips follow + followWorldPose.rot() = glmExtractRotation(desiredWorldMatrix); } if (isActive(Horizontal)) { glm::vec3 desiredTranslation = extractTranslation(desiredWorldMatrix); @@ -5359,8 +5400,7 @@ glm::mat4 MyAvatar::FollowHelper::postPhysicsUpdate(MyAvatar& myAvatar, const gl glm::mat4 worldToSensorMatrix = glm::inverse(sensorToWorldMatrix); glm::vec3 sensorLinearDisplacement = transformVectorFast(worldToSensorMatrix, worldLinearDisplacement); - glm::quat sensorAngularDisplacement = - glmExtractRotation(worldToSensorMatrix) * worldAngularDisplacement * glmExtractRotation(sensorToWorldMatrix); + glm::quat sensorAngularDisplacement = glmExtractRotation(worldToSensorMatrix) * worldAngularDisplacement * glmExtractRotation(sensorToWorldMatrix); glm::mat4 newBodyMat = createMatFromQuatAndPos(sensorAngularDisplacement * glmExtractRotation(currentBodyMatrix), sensorLinearDisplacement + extractTranslation(currentBodyMatrix)); @@ -5428,8 +5468,7 @@ bool MyAvatar::didTeleport() { } bool MyAvatar::hasDriveInput() const { - return fabsf(getDriveKey(TRANSLATE_X)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Y)) > 0.0f || - fabsf(getDriveKey(TRANSLATE_Z)) > 0.0f; + return fabsf(getDriveKey(TRANSLATE_X)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Y)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Z)) > 0.0f; } void MyAvatar::setAway(bool value) { @@ -5445,6 +5484,7 @@ void MyAvatar::setAway(bool value) { // Specificly, if we are rendering using a third person camera. We would like to render the hand controllers in front of the camera, // not in front of the avatar. glm::mat4 MyAvatar::computeCameraRelativeHandControllerMatrix(const glm::mat4& controllerSensorMatrix) const { + // Fetch the current camera transform. glm::mat4 cameraWorldMatrix = qApp->getCamera().getTransform(); if (qApp->getCamera().getMode() == CAMERA_MODE_MIRROR) { @@ -5471,7 +5511,7 @@ glm::mat4 MyAvatar::computeCameraRelativeHandControllerMatrix(const glm::mat4& c glm::quat MyAvatar::getAbsoluteJointRotationInObjectFrame(int index) const { if (index < 0) { - index += numeric_limits::max() + 1; // 65536 + index += numeric_limits::max() + 1; // 65536 } switch (index) { @@ -5500,13 +5540,15 @@ glm::quat MyAvatar::getAbsoluteJointRotationInObjectFrame(int index) const { glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix(); return glmExtractRotation(invAvatarMat * qApp->getCamera().getTransform()); } - default: { return Avatar::getAbsoluteJointRotationInObjectFrame(index); } + default: { + return Avatar::getAbsoluteJointRotationInObjectFrame(index); + } } } glm::vec3 MyAvatar::getAbsoluteJointTranslationInObjectFrame(int index) const { if (index < 0) { - index += numeric_limits::max() + 1; // 65536 + index += numeric_limits::max() + 1; // 65536 } switch (index) { @@ -5535,7 +5577,9 @@ glm::vec3 MyAvatar::getAbsoluteJointTranslationInObjectFrame(int index) const { glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix(); return extractTranslation(invAvatarMat * qApp->getCamera().getTransform()); } - default: { return Avatar::getAbsoluteJointTranslationInObjectFrame(index); } + default: { + return Avatar::getAbsoluteJointTranslationInObjectFrame(index); + } } } @@ -5544,15 +5588,12 @@ glm::mat4 MyAvatar::getCenterEyeCalibrationMat() const { int rightEyeIndex = _skeletonModel->getRig().indexOfJoint("RightEye"); int leftEyeIndex = _skeletonModel->getRig().indexOfJoint("LeftEye"); if (rightEyeIndex >= 0 && leftEyeIndex >= 0) { - auto centerEyePos = (getAbsoluteDefaultJointTranslationInObjectFrame(rightEyeIndex) + - getAbsoluteDefaultJointTranslationInObjectFrame(leftEyeIndex)) * - 0.5f; + auto centerEyePos = (getAbsoluteDefaultJointTranslationInObjectFrame(rightEyeIndex) + getAbsoluteDefaultJointTranslationInObjectFrame(leftEyeIndex)) * 0.5f; auto centerEyeRot = Quaternions::Y_180; return createMatFromQuatAndPos(centerEyeRot, centerEyePos / getSensorToWorldScale()); } else { glm::mat4 headMat = getHeadCalibrationMat(); - return createMatFromQuatAndPos(DEFAULT_AVATAR_MIDDLE_EYE_ROT, - extractTranslation(headMat) + DEFAULT_AVATAR_HEAD_TO_MIDDLE_EYE_OFFSET); + return createMatFromQuatAndPos(DEFAULT_AVATAR_MIDDLE_EYE_ROT, extractTranslation(headMat) + DEFAULT_AVATAR_HEAD_TO_MIDDLE_EYE_OFFSET); } } @@ -5721,6 +5762,7 @@ void MyAvatar::updateHoldActions(const AnimPose& prePhysicsPose, const AnimPose& if (entityTree) { // lateAvatarUpdate will modify entity position & orientation, so we need an entity write lock entityTree->withWriteLock([&] { + // to prevent actions from adding or removing themselves from the _holdActions vector // while we are iterating, we need to enter a critical section. std::lock_guard guard(_holdActionsMutex); @@ -5756,24 +5798,26 @@ SpatialParentTree* MyAvatar::getParentTree() const { return entityTree.get(); } -const QUuid MyAvatar::grab(const QUuid& targetID, - int parentJointIndex, - glm::vec3 positionalOffset, - glm::quat rotationalOffset) { +const QUuid MyAvatar::grab(const QUuid& targetID, int parentJointIndex, + glm::vec3 positionalOffset, glm::quat rotationalOffset) { auto grabID = QUuid::createUuid(); // create a temporary grab object to get grabData QString hand = "none"; - if (parentJointIndex == CONTROLLER_RIGHTHAND_INDEX || parentJointIndex == CAMERA_RELATIVE_CONTROLLER_RIGHTHAND_INDEX || - parentJointIndex == FARGRAB_RIGHTHAND_INDEX || parentJointIndex == getJointIndex("RightHand")) { + if (parentJointIndex == CONTROLLER_RIGHTHAND_INDEX || + parentJointIndex == CAMERA_RELATIVE_CONTROLLER_RIGHTHAND_INDEX || + parentJointIndex == FARGRAB_RIGHTHAND_INDEX || + parentJointIndex == getJointIndex("RightHand")) { hand = "right"; - } else if (parentJointIndex == CONTROLLER_LEFTHAND_INDEX || parentJointIndex == CAMERA_RELATIVE_CONTROLLER_LEFTHAND_INDEX || - parentJointIndex == FARGRAB_LEFTHAND_INDEX || parentJointIndex == getJointIndex("LeftHand")) { + } else if (parentJointIndex == CONTROLLER_LEFTHAND_INDEX || + parentJointIndex == CAMERA_RELATIVE_CONTROLLER_LEFTHAND_INDEX || + parentJointIndex == FARGRAB_LEFTHAND_INDEX || + parentJointIndex == getJointIndex("LeftHand")) { hand = "left"; } - Grab tmpGrab(DependencyManager::get()->getSessionUUID(), targetID, parentJointIndex, hand, positionalOffset, - rotationalOffset); + Grab tmpGrab(DependencyManager::get()->getSessionUUID(), + targetID, parentJointIndex, hand, positionalOffset, rotationalOffset); QByteArray grabData = tmpGrab.toByteArray(); bool dataChanged = updateAvatarGrabData(grabID, grabData); @@ -5786,9 +5830,10 @@ const QUuid MyAvatar::grab(const QUuid& targetID, } void MyAvatar::releaseGrab(const QUuid& grabID) { - bool tellHandler{ false }; + bool tellHandler { false }; _avatarGrabsLock.withWriteLock([&] { + std::map::iterator itr; itr = _avatarGrabs.find(grabID); if (itr != _avatarGrabs.end()) { @@ -5817,12 +5862,13 @@ void MyAvatar::releaseGrab(const QUuid& grabID) { void MyAvatar::addAvatarHandsToFlow(const std::shared_ptr& otherAvatar) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "addAvatarHandsToFlow", Q_ARG(const std::shared_ptr&, otherAvatar)); + QMetaObject::invokeMethod(this, "addAvatarHandsToFlow", + Q_ARG(const std::shared_ptr&, otherAvatar)); return; } - auto& flow = _skeletonModel->getRig().getFlow(); + auto &flow = _skeletonModel->getRig().getFlow(); if (otherAvatar != nullptr && flow.getActive()) { - for (auto& handJointName : HAND_COLLISION_JOINTS) { + for (auto &handJointName : HAND_COLLISION_JOINTS) { int jointIndex = otherAvatar->getJointIndex(handJointName); if (jointIndex != -1) { glm::vec3 position = otherAvatar->getJointPosition(jointIndex); @@ -5850,18 +5896,18 @@ void MyAvatar::addAvatarHandsToFlow(const std::shared_ptr& otherAvatar) * @property {number} [radius=0.05] - Collision sphere radius. * @property {number} [offset=Vec3.ZERO] - Offset of the collision sphere from the joint. */ -void MyAvatar::useFlow(bool isActive, - bool isCollidable, - const QVariantMap& physicsConfig, - const QVariantMap& collisionsConfig) { +void MyAvatar::useFlow(bool isActive, bool isCollidable, const QVariantMap& physicsConfig, const QVariantMap& collisionsConfig) { if (QThread::currentThread() != thread()) { - QMetaObject::invokeMethod(this, "useFlow", Q_ARG(bool, isActive), Q_ARG(bool, isCollidable), - Q_ARG(const QVariantMap&, physicsConfig), Q_ARG(const QVariantMap&, collisionsConfig)); + QMetaObject::invokeMethod(this, "useFlow", + Q_ARG(bool, isActive), + Q_ARG(bool, isCollidable), + Q_ARG(const QVariantMap&, physicsConfig), + Q_ARG(const QVariantMap&, collisionsConfig)); return; } if (_skeletonModel->isLoaded()) { - auto& flow = _skeletonModel->getRig().getFlow(); - auto& collisionSystem = flow.getCollisionSystem(); + auto &flow = _skeletonModel->getRig().getFlow(); + auto &collisionSystem = flow.getCollisionSystem(); if (!flow.isInitialized() && isActive) { _skeletonModel->getRig().initFlow(true); } else { @@ -5870,7 +5916,7 @@ void MyAvatar::useFlow(bool isActive, collisionSystem.setActive(isCollidable); auto physicsGroups = physicsConfig.keys(); if (physicsGroups.size() > 0) { - for (auto& groupName : physicsGroups) { + for (auto &groupName : physicsGroups) { auto settings = physicsConfig[groupName].toMap(); FlowPhysicsSettings physicsSettings; if (settings.contains("active")) { @@ -5900,7 +5946,7 @@ void MyAvatar::useFlow(bool isActive, auto collisionJoints = collisionsConfig.keys(); if (collisionJoints.size() > 0) { collisionSystem.clearSelfCollisions(); - for (auto& jointName : collisionJoints) { + for (auto &jointName : collisionJoints) { int jointIndex = getJointIndex(jointName); FlowCollisionSettings collisionsSettings; auto settings = collisionsConfig[jointName].toMap(); @@ -5954,13 +6000,14 @@ void MyAvatar::useFlow(bool isActive, QVariantMap MyAvatar::getFlowData() { QVariantMap result; if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "getFlowData", Q_RETURN_ARG(QVariantMap, result)); + BLOCKING_INVOKE_METHOD(this, "getFlowData", + Q_RETURN_ARG(QVariantMap, result)); return result; } if (_skeletonModel->isLoaded()) { auto jointNames = getJointNames(); - auto& flow = _skeletonModel->getRig().getFlow(); - auto& collisionSystem = flow.getCollisionSystem(); + auto &flow = _skeletonModel->getRig().getFlow(); + auto &collisionSystem = flow.getCollisionSystem(); bool initialized = flow.isInitialized(); result.insert("initialized", initialized); result.insert("active", flow.getActive()); @@ -5970,17 +6017,17 @@ QVariantMap MyAvatar::getFlowData() { QVariantMap threadData; std::map groupJointsMap; QVariantList jointCollisionData; - auto& groups = flow.getGroupSettings(); - for (auto& joint : flow.getJoints()) { - auto& groupName = joint.second.getGroup(); + auto &groups = flow.getGroupSettings(); + for (auto &joint : flow.getJoints()) { + auto &groupName = joint.second.getGroup(); if (groups.find(groupName) != groups.end()) { if (groupJointsMap.find(groupName) == groupJointsMap.end()) { groupJointsMap.insert(std::pair(groupName, QVariantList())); } groupJointsMap[groupName].push_back(joint.second.getIndex()); } - } - for (auto& group : groups) { + } + for (auto &group : groups) { QVariantMap settingsObject; QString groupName = group.first; FlowPhysicsSettings groupSettings = group.second; @@ -5995,8 +6042,8 @@ QVariantMap MyAvatar::getFlowData() { physicsData.insert(groupName, settingsObject); } - auto& collisions = collisionSystem.getCollisions(); - for (auto& collision : collisions) { + auto &collisions = collisionSystem.getCollisions(); + for (auto &collision : collisions) { QVariantMap collisionObject; collisionObject.insert("offset", vec3toVariant(collision._offset)); collisionObject.insert("radius", collision._radius); @@ -6004,7 +6051,7 @@ QVariantMap MyAvatar::getFlowData() { QString jointName = jointNames.size() > collision._jointIndex ? jointNames[collision._jointIndex] : "unknown"; collisionsData.insert(jointName, collisionObject); } - for (auto& thread : flow.getThreads()) { + for (auto &thread : flow.getThreads()) { QVariantList indices; for (int index : thread._joints) { indices.append(index); @@ -6021,13 +6068,14 @@ QVariantMap MyAvatar::getFlowData() { QVariantList MyAvatar::getCollidingFlowJoints() { QVariantList result; if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "getCollidingFlowJoints", Q_RETURN_ARG(QVariantList, result)); + BLOCKING_INVOKE_METHOD(this, "getCollidingFlowJoints", + Q_RETURN_ARG(QVariantList, result)); return result; } if (_skeletonModel->isLoaded()) { auto& flow = _skeletonModel->getRig().getFlow(); - for (auto& joint : flow.getJoints()) { + for (auto &joint : flow.getJoints()) { if (joint.second.isColliding()) { result.append(joint.second.getIndex()); } @@ -6038,7 +6086,7 @@ QVariantList MyAvatar::getCollidingFlowJoints() { void MyAvatar::initFlowFromFST() { if (_skeletonModel->isLoaded()) { - auto& flowData = _skeletonModel->getHFMModel().flowData; + auto &flowData = _skeletonModel->getHFMModel().flowData; if (flowData.shouldInitFlow()) { useFlow(true, flowData.shouldInitCollisions(), flowData._physicsConfig, flowData._collisionsConfig); } @@ -6056,3 +6104,4 @@ void MyAvatar::sendPacket(const QUuid& entityID) const { }); } } + From e89f499c1a6a00edca6f62537691cf3c0fb64bde Mon Sep 17 00:00:00 2001 From: Preston Bezos Date: Fri, 7 Jun 2019 12:02:15 -0700 Subject: [PATCH 19/31] this should work --- interface/src/avatar/MyAvatar.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index b60bfd3f29..b91217da63 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -4989,6 +4989,7 @@ void MyAvatar::setSprintSpeed(float value) { _analogPlusSprintSpeed.set(value); break; default: + changed = false; break; } From 9498e0a462ec3590a74403ef63ea03b1ad12c552 Mon Sep 17 00:00:00 2001 From: amer cerkic Date: Fri, 7 Jun 2019 12:47:04 -0700 Subject: [PATCH 20/31] addressing comment concerning preferences --- interface/src/ui/PreferencesDialog.cpp | 215 ++++++++++++++----------- 1 file changed, 124 insertions(+), 91 deletions(-) diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index fb7b0ef993..380035fcb4 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -30,9 +30,9 @@ void setupPreferences() { auto preferences = DependencyManager::get(); auto myAvatar = DependencyManager::get()->getMyAvatar(); - static const QString AVATAR_BASICS { "Avatar Basics" }; + static const QString AVATAR_BASICS{ "Avatar Basics" }; { - auto getter = [myAvatar]()->QString { return myAvatar->getDisplayName(); }; + auto getter = [myAvatar]() -> QString { return myAvatar->getDisplayName(); }; auto setter = [myAvatar](const QString& value) { myAvatar->setDisplayName(value); }; auto preference = new EditPreference(AVATAR_BASICS, "Avatar display name (optional)", getter, setter); preference->setPlaceholderText("Not showing a name"); @@ -40,7 +40,7 @@ void setupPreferences() { } { - auto getter = [myAvatar]()->QString { return myAvatar->getCollisionSoundURL(); }; + auto getter = [myAvatar]() -> QString { return myAvatar->getCollisionSoundURL(); }; auto setter = [myAvatar](const QString& value) { myAvatar->setCollisionSoundURL(value); }; auto preference = new EditPreference(AVATAR_BASICS, "Avatar collision sound URL (optional)", getter, setter); preference->setPlaceholderText("Enter the URL of a sound to play when you bump into something"); @@ -48,22 +48,21 @@ void setupPreferences() { } { - auto getter = [myAvatar]()->QString { return myAvatar->getFullAvatarURLFromPreferences().toString(); }; - auto setter = [myAvatar](const QString& value) { myAvatar->useFullAvatarURL(value, ""); qApp->clearAvatarOverrideUrl(); }; + auto getter = [myAvatar]() -> QString { return myAvatar->getFullAvatarURLFromPreferences().toString(); }; + auto setter = [myAvatar](const QString& value) { + myAvatar->useFullAvatarURL(value, ""); + qApp->clearAvatarOverrideUrl(); + }; auto preference = new AvatarPreference(AVATAR_BASICS, "Appearance", getter, setter); preferences->addPreference(preference); } // Graphics quality - static const QString GRAPHICS_QUALITY { "Graphics Quality" }; + static const QString GRAPHICS_QUALITY{ "Graphics Quality" }; { - auto getter = []()->float { - return DependencyManager::get()->getWorldDetailQuality(); - }; + auto getter = []() -> float { return DependencyManager::get()->getWorldDetailQuality(); }; - auto setter = [](float value) { - DependencyManager::get()->setWorldDetailQuality(value); - }; + auto setter = [](float value) { DependencyManager::get()->setWorldDetailQuality(value); }; auto wodSlider = new SliderPreference(GRAPHICS_QUALITY, "World Detail", getter, setter); wodSlider->setMin(0.25f); @@ -71,7 +70,7 @@ void setupPreferences() { wodSlider->setStep(0.25f); preferences->addPreference(wodSlider); - auto getterShadow = []()->bool { + auto getterShadow = []() -> bool { auto menu = Menu::getInstance(); return menu->isOptionChecked(MenuOption::Shadows); }; @@ -83,43 +82,48 @@ void setupPreferences() { } { - auto getter = []()->QString { + auto getter = []() -> QString { RefreshRateManager::RefreshRateProfile refreshRateProfile = qApp->getRefreshRateManager().getRefreshRateProfile(); return QString::fromStdString(RefreshRateManager::refreshRateProfileToString(refreshRateProfile)); }; auto setter = [](QString value) { std::string profileName = value.toStdString(); - RefreshRateManager::RefreshRateProfile refreshRateProfile = RefreshRateManager::refreshRateProfileFromString(profileName); + RefreshRateManager::RefreshRateProfile refreshRateProfile = + RefreshRateManager::refreshRateProfileFromString(profileName); qApp->getRefreshRateManager().setRefreshRateProfile(refreshRateProfile); }; auto preference = new ComboBoxPreference(GRAPHICS_QUALITY, "Refresh Rate", getter, setter); - QStringList refreshRateProfiles - { QString::fromStdString(RefreshRateManager::refreshRateProfileToString(RefreshRateManager::RefreshRateProfile::ECO)), - QString::fromStdString(RefreshRateManager::refreshRateProfileToString(RefreshRateManager::RefreshRateProfile::INTERACTIVE)), - QString::fromStdString(RefreshRateManager::refreshRateProfileToString(RefreshRateManager::RefreshRateProfile::REALTIME)) }; + QStringList refreshRateProfiles{ QString::fromStdString(RefreshRateManager::refreshRateProfileToString( + RefreshRateManager::RefreshRateProfile::ECO)), + QString::fromStdString(RefreshRateManager::refreshRateProfileToString( + RefreshRateManager::RefreshRateProfile::INTERACTIVE)), + QString::fromStdString(RefreshRateManager::refreshRateProfileToString( + RefreshRateManager::RefreshRateProfile::REALTIME)) }; preference->setItems(refreshRateProfiles); preferences->addPreference(preference); } // UI - static const QString UI_CATEGORY { "User Interface" }; + static const QString UI_CATEGORY{ "User Interface" }; { - auto getter = []()->bool { return qApp->getSettingConstrainToolbarPosition(); }; + auto getter = []() -> bool { return qApp->getSettingConstrainToolbarPosition(); }; auto setter = [](bool value) { qApp->setSettingConstrainToolbarPosition(value); }; - preferences->addPreference(new CheckPreference(UI_CATEGORY, "Constrain Toolbar Position to Horizontal Center", getter, setter)); - } - - { - auto getter = []()->bool { return qApp->getAwayStateWhenFocusLostInVREnabled(); }; - auto setter = [](bool value) { qApp->setAwayStateWhenFocusLostInVREnabled(value); }; - preferences->addPreference(new CheckPreference(UI_CATEGORY, "Go into away state when interface window loses focus in VR", getter, setter)); + preferences->addPreference( + new CheckPreference(UI_CATEGORY, "Constrain Toolbar Position to Horizontal Center", getter, setter)); } { - auto getter = []()->float { return qApp->getDesktopTabletScale(); }; + auto getter = []() -> bool { return qApp->getAwayStateWhenFocusLostInVREnabled(); }; + auto setter = [](bool value) { qApp->setAwayStateWhenFocusLostInVREnabled(value); }; + preferences->addPreference( + new CheckPreference(UI_CATEGORY, "Go into away state when interface window loses focus in VR", getter, setter)); + } + + { + auto getter = []() -> float { return qApp->getDesktopTabletScale(); }; auto setter = [](float value) { qApp->setDesktopTabletScale(value); }; auto preference = new SpinnerPreference(UI_CATEGORY, "Desktop Tablet Scale %", getter, setter); preference->setMin(20); @@ -128,7 +132,7 @@ void setupPreferences() { } { - auto getter = []()->float { return qApp->getHMDTabletScale(); }; + auto getter = []() -> float { return qApp->getHMDTabletScale(); }; auto setter = [](float value) { qApp->setHMDTabletScale(value); }; auto preference = new SpinnerPreference(UI_CATEGORY, "VR Tablet Scale %", getter, setter); preference->setMin(20); @@ -138,41 +142,42 @@ void setupPreferences() { { static const QString RETICLE_ICON_NAME = { Cursor::Manager::getIconName(Cursor::Icon::RETICLE) }; - auto getter = []()->bool { return qApp->getPreferredCursor() == RETICLE_ICON_NAME; }; + auto getter = []() -> bool { return qApp->getPreferredCursor() == RETICLE_ICON_NAME; }; auto setter = [](bool value) { qApp->setPreferredCursor(value ? RETICLE_ICON_NAME : QString()); }; preferences->addPreference(new CheckPreference(UI_CATEGORY, "Use reticle cursor instead of arrow", getter, setter)); } { - auto getter = []()->bool { return qApp->getMiniTabletEnabled(); }; + auto getter = []() -> bool { return qApp->getMiniTabletEnabled(); }; auto setter = [](bool value) { qApp->setMiniTabletEnabled(value); }; preferences->addPreference(new CheckPreference(UI_CATEGORY, "Use mini tablet", getter, setter)); } { - auto getter = []()->int { return DependencyManager::get()->getUse3DKeyboard(); }; + auto getter = []() -> int { return DependencyManager::get()->getUse3DKeyboard(); }; auto setter = [](int value) { DependencyManager::get()->setUse3DKeyboard(value); }; preferences->addPreference(new CheckPreference(UI_CATEGORY, "Use Virtual Keyboard", getter, setter)); } { - auto getter = []()->bool { return DependencyManager::get()->getPreferMalletsOverLasers() ? 1 : 0; }; + auto getter = []() -> bool { return DependencyManager::get()->getPreferMalletsOverLasers() ? 1 : 0; }; auto setter = [](bool value) { return DependencyManager::get()->setPreferMalletsOverLasers((bool)value); }; auto preference = new RadioButtonsPreference(UI_CATEGORY, "Keyboard laser / mallets", getter, setter); QStringList items; - items << "Lasers" << "Mallets"; + items << "Lasers" + << "Mallets"; preference->setItems(items); preference->setIndented(true); preferences->addPreference(preference); } - { - auto getter = []()->int { return qApp->getPreferStylusOverLaser() ? 1 : 0; }; + auto getter = []() -> int { return qApp->getPreferStylusOverLaser() ? 1 : 0; }; auto setter = [](int value) { qApp->setPreferStylusOverLaser((bool)value); }; auto preference = new RadioButtonsPreference(UI_CATEGORY, "Tablet stylys / laser", getter, setter); QStringList items; - items << "Lasers" << "Stylus"; + items << "Lasers" + << "Stylus"; preference->setHeading("Tablet Input Mechanism"); preference->setItems(items); preferences->addPreference(preference); @@ -180,15 +185,16 @@ void setupPreferences() { static const QString VIEW_CATEGORY{ "View" }; { - auto getter = [myAvatar]()->float { return myAvatar->getRealWorldFieldOfView(); }; + auto getter = [myAvatar]() -> float { return myAvatar->getRealWorldFieldOfView(); }; auto setter = [myAvatar](float value) { myAvatar->setRealWorldFieldOfView(value); }; - auto preference = new SpinnerPreference(VIEW_CATEGORY, "Real world vertical field of view (angular size of monitor)", getter, setter); + auto preference = + new SpinnerPreference(VIEW_CATEGORY, "Real world vertical field of view (angular size of monitor)", getter, setter); preference->setMin(1); preference->setMax(180); preferences->addPreference(preference); } { - auto getter = []()->float { return qApp->getFieldOfView(); }; + auto getter = []() -> float { return qApp->getFieldOfView(); }; auto setter = [](float value) { qApp->setFieldOfView(value); }; auto preference = new SpinnerPreference(VIEW_CATEGORY, "Vertical field of view", getter, setter); preference->setMin(1); @@ -206,15 +212,18 @@ void setupPreferences() { }*/ // Snapshots - static const QString SNAPSHOTS { "Snapshots" }; + static const QString SNAPSHOTS{ "Snapshots" }; { - auto getter = []()->QString { return DependencyManager::get()->_snapshotsLocation.get(); }; - auto setter = [](const QString& value) { DependencyManager::get()->_snapshotsLocation.set(value); emit DependencyManager::get()->snapshotLocationSet(value); }; + auto getter = []() -> QString { return DependencyManager::get()->_snapshotsLocation.get(); }; + auto setter = [](const QString& value) { + DependencyManager::get()->_snapshotsLocation.set(value); + emit DependencyManager::get()->snapshotLocationSet(value); + }; auto preference = new BrowsePreference(SNAPSHOTS, "Put my snapshots here", getter, setter); preferences->addPreference(preference); } { - auto getter = []()->float { return SnapshotAnimated::snapshotAnimatedDuration.get(); }; + auto getter = []() -> float { return SnapshotAnimated::snapshotAnimatedDuration.get(); }; auto setter = [](float value) { SnapshotAnimated::snapshotAnimatedDuration.set(value); }; auto preference = new SpinnerPreference(SNAPSHOTS, "Animated Snapshot Duration", getter, setter); preference->setMin(1); @@ -224,22 +233,25 @@ void setupPreferences() { } { - auto getter = []()->bool { return !Menu::getInstance()->isOptionChecked(MenuOption::DisableActivityLogger); }; + auto getter = []() -> bool { return !Menu::getInstance()->isOptionChecked(MenuOption::DisableActivityLogger); }; auto setter = [](bool value) { Menu::getInstance()->setIsOptionChecked(MenuOption::DisableActivityLogger, !value); }; - preferences->addPreference(new CheckPreference("Privacy", "Send data - High Fidelity uses information provided by your " + preferences->addPreference( + new CheckPreference("Privacy", + "Send data - High Fidelity uses information provided by your " "client to improve the product through the logging of errors, tracking of usage patterns, " "installation and system details, and crash events. By allowing High Fidelity to collect " - "this information you are helping to improve the product. ", getter, setter)); + "this information you are helping to improve the product. ", + getter, setter)); } - - static const QString AVATAR_TUNING { "Avatar Tuning" }; + + static const QString AVATAR_TUNING{ "Avatar Tuning" }; { - auto getter = [myAvatar]()->QString { return myAvatar->getDominantHand(); }; + auto getter = [myAvatar]() -> QString { return myAvatar->getDominantHand(); }; auto setter = [myAvatar](const QString& value) { myAvatar->setDominantHand(value); }; preferences->addPreference(new PrimaryHandPreference(AVATAR_TUNING, "Dominant Hand", getter, setter)); } { - auto getter = [myAvatar]()->float { return myAvatar->getTargetScale(); }; + auto getter = [myAvatar]() -> float { return myAvatar->getTargetScale(); }; auto setter = [myAvatar](float value) { myAvatar->setTargetScale(value); }; auto preference = new SpinnerSliderPreference(AVATAR_TUNING, "Avatar Scale", getter, setter); preference->setMin(0.25); @@ -247,15 +259,15 @@ void setupPreferences() { preference->setStep(0.05f); preference->setDecimals(2); preferences->addPreference(preference); - - // When the Interface is first loaded, this section setupPreferences(); is loaded - + + // When the Interface is first loaded, this section setupPreferences(); is loaded - // causing the myAvatar->getDomainMinScale() and myAvatar->getDomainMaxScale() to get set to incorrect values // which can't be changed across domain switches. Having these values loaded up when you load the Dialog each time // is a way around this, therefore they're not specified here but in the QML. } { - auto getter = [myAvatar]()->QString { return myAvatar->getAnimGraphOverrideUrl().toString(); }; + auto getter = [myAvatar]() -> QString { return myAvatar->getAnimGraphOverrideUrl().toString(); }; auto setter = [myAvatar](const QString& value) { myAvatar->setAnimGraphOverrideUrl(QUrl(value)); }; auto preference = new EditPreference(AVATAR_TUNING, "Avatar animation JSON", getter, setter); preference->setPlaceholderText("default"); @@ -263,44 +275,49 @@ void setupPreferences() { } { - auto getter = [myAvatar]()->bool { return myAvatar->getCollisionsEnabled(); }; + auto getter = [myAvatar]() -> bool { return myAvatar->getCollisionsEnabled(); }; auto setter = [myAvatar](bool value) { myAvatar->setCollisionsEnabled(value); }; auto preference = new CheckPreference(AVATAR_TUNING, "Enable Avatar collisions", getter, setter); preferences->addPreference(preference); } + static const QString FACE_TRACKING{ "Face Tracking" }; { - auto getter = []()->float { return DependencyManager::get()->getEyeClosingThreshold(); }; +#ifdef HAVE_DDE + auto getter = []() -> float { return DependencyManager::get()->getEyeClosingThreshold(); }; auto setter = [](float value) { DependencyManager::get()->setEyeClosingThreshold(value); }; preferences->addPreference(new SliderPreference(FACE_TRACKING, "Eye Closing Threshold", getter, setter)); +#endif } + + { - auto getter = []()->float { return FaceTracker::getEyeDeflection(); }; + auto getter = []() -> float { return FaceTracker::getEyeDeflection(); }; auto setter = [](float value) { FaceTracker::setEyeDeflection(value); }; preferences->addPreference(new SliderPreference(FACE_TRACKING, "Eye Deflection", getter, setter)); } static const QString VR_MOVEMENT{ "VR Movement" }; { - auto getter = [myAvatar]()->bool { return myAvatar->getAllowTeleporting(); }; + auto getter = [myAvatar]() -> bool { return myAvatar->getAllowTeleporting(); }; auto setter = [myAvatar](bool value) { myAvatar->setAllowTeleporting(value); }; auto preference = new CheckPreference(VR_MOVEMENT, "Teleporting", getter, setter); preferences->addPreference(preference); } { - auto getter = [myAvatar]()->bool { return myAvatar->useAdvancedMovementControls(); }; + auto getter = [myAvatar]() -> bool { return myAvatar->useAdvancedMovementControls(); }; auto setter = [myAvatar](bool value) { myAvatar->setUseAdvancedMovementControls(value); }; auto preference = new CheckPreference(VR_MOVEMENT, "Walking", getter, setter); preferences->addPreference(preference); } { - auto getter = [myAvatar]()->bool { return myAvatar->getStrafeEnabled(); }; + auto getter = [myAvatar]() -> bool { return myAvatar->getStrafeEnabled(); }; auto setter = [myAvatar](bool value) { myAvatar->setStrafeEnabled(value); }; preferences->addPreference(new CheckPreference(VR_MOVEMENT, "Strafing", getter, setter)); } { - auto getter = [myAvatar]()->bool { return myAvatar->getFlyingHMDPref(); }; + auto getter = [myAvatar]() -> bool { return myAvatar->getFlyingHMDPref(); }; auto setter = [myAvatar](bool value) { myAvatar->setFlyingHMDPref(value); }; auto preference = new CheckPreference(VR_MOVEMENT, "Jumping and flying", getter, setter); preference->setIndented(true); @@ -313,43 +330,48 @@ void setupPreferences() { preferences->addPreference(preference); } { - auto getter = [myAvatar]()->int { return myAvatar->getMovementReference(); }; - auto setter = [myAvatar](int value) { myAvatar->setMovementReference(value); }; + auto getter = [myAvatar]() -> int { return myAvatar->getMovementReference(); }; + auto setter = [myAvatar](int value) { myAvatar->setMovementReference(value); }; //auto preference = new CheckPreference(VR_MOVEMENT, "Hand-Relative Movement", getter, setter); auto preference = new RadioButtonsPreference(VR_MOVEMENT, "Movement Direction", getter, setter); QStringList items; - items << "HMD-Relative" << "Hand-Relative" << "Hand-Relative (Leveled)"; + items << "HMD-Relative" + << "Hand-Relative" + << "Hand-Relative (Leveled)"; preference->setHeading("Movement Direction"); preference->setItems(items); preferences->addPreference(preference); } { - auto getter = [myAvatar]()->QString { return myAvatar->getDominantHand(); }; + auto getter = [myAvatar]() -> QString { return myAvatar->getDominantHand(); }; auto setter = [myAvatar](const QString& value) { myAvatar->setDominantHand(value); }; preferences->addPreference(new PrimaryHandPreference(VR_MOVEMENT, "Dominant Hand", getter, setter)); } { - auto getter = [myAvatar]()->int { return myAvatar->getSnapTurn() ? 0 : 1; }; + auto getter = [myAvatar]() -> int { return myAvatar->getSnapTurn() ? 0 : 1; }; auto setter = [myAvatar](int value) { myAvatar->setSnapTurn(value == 0); }; auto preference = new RadioButtonsPreference(VR_MOVEMENT, "Snap turn / Smooth turn", getter, setter); QStringList items; - items << "Snap turn" << "Smooth turn"; + items << "Snap turn" + << "Smooth turn"; preference->setHeading("Rotation mode"); preference->setItems(items); preferences->addPreference(preference); } { - auto getter = [myAvatar]()->int { return myAvatar->getControlScheme(); }; + auto getter = [myAvatar]() -> int { return myAvatar->getControlScheme(); }; auto setter = [myAvatar](int index) { myAvatar->setControlScheme(index); }; auto preference = new RadioButtonsPreference(VR_MOVEMENT, "Control Scheme", getter, setter); QStringList items; - items << "Default" << "Analog" << "Analog++"; + items << "Default" + << "Analog" + << "Analog++"; preference->setHeading("Control Scheme Selection"); preference->setItems(items); preferences->addPreference(preference); } { - auto getter = [myAvatar]()->float { return myAvatar->getAnalogPlusWalkSpeed(); }; + auto getter = [myAvatar]() -> float { return myAvatar->getAnalogPlusWalkSpeed(); }; auto setter = [myAvatar](float value) { myAvatar->setAnalogPlusWalkSpeed(value); }; auto preference = new SpinnerSliderPreference(VR_MOVEMENT, "Analog++ Walk Speed", getter, setter); preference->setMin(6.0f); @@ -359,16 +381,16 @@ void setupPreferences() { preferences->addPreference(preference); } { - auto getter = [myAvatar]()->bool { return myAvatar->getShowPlayArea(); }; + auto getter = [myAvatar]() -> bool { return myAvatar->getShowPlayArea(); }; auto setter = [myAvatar](bool value) { myAvatar->setShowPlayArea(value); }; auto preference = new CheckPreference(VR_MOVEMENT, "Show room boundaries while teleporting", getter, setter); preferences->addPreference(preference); } { - auto getter = [myAvatar]()->int { + auto getter = [myAvatar]() -> int { switch (myAvatar->getUserRecenterModel()) { case MyAvatar::SitStandModelType::Auto: - default: + default: return 0; case MyAvatar::SitStandModelType::ForceSit: return 1; @@ -395,15 +417,19 @@ void setupPreferences() { break; } }; - auto preference = new RadioButtonsPreference(VR_MOVEMENT, "Auto / Force Sit / Force Stand / Disable Recenter", getter, setter); + auto preference = + new RadioButtonsPreference(VR_MOVEMENT, "Auto / Force Sit / Force Stand / Disable Recenter", getter, setter); QStringList items; - items << "Auto - turns on avatar leaning when standing in real world" << "Seated - disables all avatar leaning while sitting in real world" << "Standing - enables avatar leaning while sitting in real world" << "Disabled - allows avatar sitting on the floor [Experimental]"; + items << "Auto - turns on avatar leaning when standing in real world" + << "Seated - disables all avatar leaning while sitting in real world" + << "Standing - enables avatar leaning while sitting in real world" + << "Disabled - allows avatar sitting on the floor [Experimental]"; preference->setHeading("Avatar leaning behavior"); preference->setItems(items); preferences->addPreference(preference); } { - auto getter = [=]()->float { return myAvatar->getUserHeight(); }; + auto getter = [=]() -> float { return myAvatar->getUserHeight(); }; auto setter = [=](float value) { myAvatar->setUserHeight(value); }; auto preference = new SpinnerPreference(VR_MOVEMENT, "User real-world height (meters)", getter, setter); preference->setMin(1.0f); @@ -415,7 +441,7 @@ void setupPreferences() { static const QString AVATAR_CAMERA{ "Mouse Sensitivity" }; { - auto getter = [myAvatar]()->float { return myAvatar->getPitchSpeed(); }; + auto getter = [myAvatar]() -> float { return myAvatar->getPitchSpeed(); }; auto setter = [myAvatar](float value) { myAvatar->setPitchSpeed(value); }; auto preference = new SpinnerSliderPreference(AVATAR_CAMERA, "Y input:", getter, setter); preference->setMin(1.0f); @@ -425,7 +451,7 @@ void setupPreferences() { preferences->addPreference(preference); } { - auto getter = [myAvatar]()->float { return myAvatar->getYawSpeed(); }; + auto getter = [myAvatar]() -> float { return myAvatar->getYawSpeed(); }; auto setter = [myAvatar](float value) { myAvatar->setYawSpeed(value); }; auto preference = new SpinnerSliderPreference(AVATAR_CAMERA, "X input:", getter, setter); preference->setMin(1.0f); @@ -437,14 +463,22 @@ void setupPreferences() { static const QString AUDIO_BUFFERS("Audio Buffers"); { - auto getter = []()->bool { return !DependencyManager::get()->getReceivedAudioStream().dynamicJitterBufferEnabled(); }; - auto setter = [](bool value) { DependencyManager::get()->getReceivedAudioStream().setDynamicJitterBufferEnabled(!value); }; + auto getter = []() -> bool { + return !DependencyManager::get()->getReceivedAudioStream().dynamicJitterBufferEnabled(); + }; + auto setter = [](bool value) { + DependencyManager::get()->getReceivedAudioStream().setDynamicJitterBufferEnabled(!value); + }; auto preference = new CheckPreference(AUDIO_BUFFERS, "Disable dynamic jitter buffer", getter, setter); preferences->addPreference(preference); } { - auto getter = []()->float { return DependencyManager::get()->getReceivedAudioStream().getStaticJitterBufferFrames(); }; - auto setter = [](float value) { DependencyManager::get()->getReceivedAudioStream().setStaticJitterBufferFrames(value); }; + auto getter = []() -> float { + return DependencyManager::get()->getReceivedAudioStream().getStaticJitterBufferFrames(); + }; + auto setter = [](float value) { + DependencyManager::get()->getReceivedAudioStream().setStaticJitterBufferFrames(value); + }; auto preference = new SpinnerPreference(AUDIO_BUFFERS, "Static jitter buffer frames", getter, setter); preference->setMin(0); preference->setMax(2000); @@ -452,13 +486,13 @@ void setupPreferences() { preferences->addPreference(preference); } { - auto getter = []()->bool { return !DependencyManager::get()->getOutputStarveDetectionEnabled(); }; + auto getter = []() -> bool { return !DependencyManager::get()->getOutputStarveDetectionEnabled(); }; auto setter = [](bool value) { DependencyManager::get()->setOutputStarveDetectionEnabled(!value); }; auto preference = new CheckPreference(AUDIO_BUFFERS, "Disable output starve detection", getter, setter); preferences->addPreference(preference); } { - auto getter = []()->float { return DependencyManager::get()->getOutputBufferSize(); }; + auto getter = []() -> float { return DependencyManager::get()->getOutputBufferSize(); }; auto setter = [](float value) { DependencyManager::get()->setOutputBufferSize(value); }; auto preference = new SpinnerPreference(AUDIO_BUFFERS, "Output buffer initial frames", getter, setter); preference->setMin(AudioClient::MIN_BUFFER_FRAMES); @@ -468,13 +502,13 @@ void setupPreferences() { } #if DEV_BUILD || PR_BUILD { - auto getter = []()->bool { return DependencyManager::get()->isSimulatingJitter(); }; + auto getter = []() -> bool { return DependencyManager::get()->isSimulatingJitter(); }; auto setter = [](bool value) { return DependencyManager::get()->setIsSimulatingJitter(value); }; auto preference = new CheckPreference(AUDIO_BUFFERS, "Packet jitter simulator", getter, setter); preferences->addPreference(preference); } { - auto getter = []()->float { return DependencyManager::get()->getGateThreshold(); }; + auto getter = []() -> float { return DependencyManager::get()->getGateThreshold(); }; auto setter = [](float value) { return DependencyManager::get()->setGateThreshold(value); }; auto preference = new SpinnerPreference(AUDIO_BUFFERS, "Packet throttle threshold", getter, setter); preference->setMin(1); @@ -489,8 +523,8 @@ void setupPreferences() { QWeakPointer nodeListWeak = DependencyManager::get(); { - static const int MIN_PORT_NUMBER { 0 }; - static const int MAX_PORT_NUMBER { 65535 }; + static const int MIN_PORT_NUMBER{ 0 }; + static const int MAX_PORT_NUMBER{ 65535 }; auto getter = [nodeListWeak] { auto nodeList = nodeListWeak.lock(); if (nodeList) { @@ -512,7 +546,7 @@ void setupPreferences() { } { - auto getter = []()->float { return qApp->getMaxOctreePacketsPerSecond(); }; + auto getter = []() -> float { return qApp->getMaxOctreePacketsPerSecond(); }; auto setter = [](float value) { qApp->setMaxOctreePacketsPerSecond(value); }; auto preference = new SpinnerPreference(NETWORKING, "Max entities packets sent each second", getter, setter); preference->setMin(60); @@ -520,6 +554,5 @@ void setupPreferences() { preference->setStep(10); preferences->addPreference(preference); } - } } From fd7dd7948f0e2d80fd888c278fc18a05a452c5cc Mon Sep 17 00:00:00 2001 From: amer cerkic Date: Fri, 7 Jun 2019 13:41:14 -0700 Subject: [PATCH 21/31] reverted vs spacing changes --- interface/src/Application.cpp | 8 +-- interface/src/ui/PreferencesDialog.cpp | 87 +++++++++----------------- 2 files changed, 33 insertions(+), 62 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 7efa17cb8c..eaaf9502cf 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -5182,11 +5182,11 @@ ivec2 Application::getMouse() const { FaceTracker* Application::getActiveFaceTracker() { auto dde = DependencyManager::get(); - if(dde){ - return dde->isActive() ? static_cast(dde.data()) : nullptr; - }else{ - return nullptr; + if(dde && dde->isActive()){ + return static_cast(dde.data()); } + + return nullptr; } FaceTracker* Application::getSelectedFaceTracker() { diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index 380035fcb4..a13d19741d 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -49,10 +49,7 @@ void setupPreferences() { { auto getter = [myAvatar]() -> QString { return myAvatar->getFullAvatarURLFromPreferences().toString(); }; - auto setter = [myAvatar](const QString& value) { - myAvatar->useFullAvatarURL(value, ""); - qApp->clearAvatarOverrideUrl(); - }; + auto setter = [myAvatar](const QString& value) { myAvatar->useFullAvatarURL(value, ""); qApp->clearAvatarOverrideUrl(); }; auto preference = new AvatarPreference(AVATAR_BASICS, "Appearance", getter, setter); preferences->addPreference(preference); } @@ -60,9 +57,13 @@ void setupPreferences() { // Graphics quality static const QString GRAPHICS_QUALITY{ "Graphics Quality" }; { - auto getter = []() -> float { return DependencyManager::get()->getWorldDetailQuality(); }; + auto getter = []()->float { + return DependencyManager::get()->getWorldDetailQuality(); + }; - auto setter = [](float value) { DependencyManager::get()->setWorldDetailQuality(value); }; + auto setter = [](float value) { + DependencyManager::get()->setWorldDetailQuality(value); + }; auto wodSlider = new SliderPreference(GRAPHICS_QUALITY, "World Detail", getter, setter); wodSlider->setMin(0.25f); @@ -95,12 +96,10 @@ void setupPreferences() { }; auto preference = new ComboBoxPreference(GRAPHICS_QUALITY, "Refresh Rate", getter, setter); - QStringList refreshRateProfiles{ QString::fromStdString(RefreshRateManager::refreshRateProfileToString( - RefreshRateManager::RefreshRateProfile::ECO)), - QString::fromStdString(RefreshRateManager::refreshRateProfileToString( - RefreshRateManager::RefreshRateProfile::INTERACTIVE)), - QString::fromStdString(RefreshRateManager::refreshRateProfileToString( - RefreshRateManager::RefreshRateProfile::REALTIME)) }; + QStringList refreshRateProfiles + { QString::fromStdString(RefreshRateManager::refreshRateProfileToString(RefreshRateManager::RefreshRateProfile::ECO)), + QString::fromStdString(RefreshRateManager::refreshRateProfileToString(RefreshRateManager::RefreshRateProfile::INTERACTIVE)), + QString::fromStdString(RefreshRateManager::refreshRateProfileToString(RefreshRateManager::RefreshRateProfile::REALTIME)) }; preference->setItems(refreshRateProfiles); preferences->addPreference(preference); @@ -111,15 +110,13 @@ void setupPreferences() { { auto getter = []() -> bool { return qApp->getSettingConstrainToolbarPosition(); }; auto setter = [](bool value) { qApp->setSettingConstrainToolbarPosition(value); }; - preferences->addPreference( - new CheckPreference(UI_CATEGORY, "Constrain Toolbar Position to Horizontal Center", getter, setter)); + preferences->addPreference(new CheckPreference(UI_CATEGORY, "Constrain Toolbar Position to Horizontal Center", getter, setter)); } { auto getter = []() -> bool { return qApp->getAwayStateWhenFocusLostInVREnabled(); }; auto setter = [](bool value) { qApp->setAwayStateWhenFocusLostInVREnabled(value); }; - preferences->addPreference( - new CheckPreference(UI_CATEGORY, "Go into away state when interface window loses focus in VR", getter, setter)); + preferences->addPreference(new CheckPreference(UI_CATEGORY, "Go into away state when interface window loses focus in VR", getter, setter)); } { @@ -164,20 +161,19 @@ void setupPreferences() { auto setter = [](bool value) { return DependencyManager::get()->setPreferMalletsOverLasers((bool)value); }; auto preference = new RadioButtonsPreference(UI_CATEGORY, "Keyboard laser / mallets", getter, setter); QStringList items; - items << "Lasers" - << "Mallets"; + items << "Lasers" << "Mallets"; preference->setItems(items); preference->setIndented(true); preferences->addPreference(preference); } + { auto getter = []() -> int { return qApp->getPreferStylusOverLaser() ? 1 : 0; }; auto setter = [](int value) { qApp->setPreferStylusOverLaser((bool)value); }; auto preference = new RadioButtonsPreference(UI_CATEGORY, "Tablet stylys / laser", getter, setter); QStringList items; - items << "Lasers" - << "Stylus"; + items << "Lasers" << "Stylus"; preference->setHeading("Tablet Input Mechanism"); preference->setItems(items); preferences->addPreference(preference); @@ -187,8 +183,7 @@ void setupPreferences() { { auto getter = [myAvatar]() -> float { return myAvatar->getRealWorldFieldOfView(); }; auto setter = [myAvatar](float value) { myAvatar->setRealWorldFieldOfView(value); }; - auto preference = - new SpinnerPreference(VIEW_CATEGORY, "Real world vertical field of view (angular size of monitor)", getter, setter); + auto preference = new SpinnerPreference(VIEW_CATEGORY, "Real world vertical field of view (angular size of monitor)", getter, setter); preference->setMin(1); preference->setMax(180); preferences->addPreference(preference); @@ -215,10 +210,7 @@ void setupPreferences() { static const QString SNAPSHOTS{ "Snapshots" }; { auto getter = []() -> QString { return DependencyManager::get()->_snapshotsLocation.get(); }; - auto setter = [](const QString& value) { - DependencyManager::get()->_snapshotsLocation.set(value); - emit DependencyManager::get()->snapshotLocationSet(value); - }; + auto setter = [](const QString& value) { DependencyManager::get()->_snapshotsLocation.set(value); emit DependencyManager::get()->snapshotLocationSet(value); }; auto preference = new BrowsePreference(SNAPSHOTS, "Put my snapshots here", getter, setter); preferences->addPreference(preference); } @@ -235,13 +227,10 @@ void setupPreferences() { { auto getter = []() -> bool { return !Menu::getInstance()->isOptionChecked(MenuOption::DisableActivityLogger); }; auto setter = [](bool value) { Menu::getInstance()->setIsOptionChecked(MenuOption::DisableActivityLogger, !value); }; - preferences->addPreference( - new CheckPreference("Privacy", - "Send data - High Fidelity uses information provided by your " + preferences->addPreference(new CheckPreference("Privacy", "Send data - High Fidelity uses information provided by your " "client to improve the product through the logging of errors, tracking of usage patterns, " "installation and system details, and crash events. By allowing High Fidelity to collect " - "this information you are helping to improve the product. ", - getter, setter)); + "this information you are helping to improve the product. ", getter, setter)); } static const QString AVATAR_TUNING{ "Avatar Tuning" }; @@ -281,7 +270,6 @@ void setupPreferences() { preferences->addPreference(preference); } - static const QString FACE_TRACKING{ "Face Tracking" }; { #ifdef HAVE_DDE @@ -335,9 +323,7 @@ void setupPreferences() { //auto preference = new CheckPreference(VR_MOVEMENT, "Hand-Relative Movement", getter, setter); auto preference = new RadioButtonsPreference(VR_MOVEMENT, "Movement Direction", getter, setter); QStringList items; - items << "HMD-Relative" - << "Hand-Relative" - << "Hand-Relative (Leveled)"; + items << "HMD-Relative" << "Hand-Relative" << "Hand-Relative (Leveled)"; preference->setHeading("Movement Direction"); preference->setItems(items); preferences->addPreference(preference); @@ -352,8 +338,7 @@ void setupPreferences() { auto setter = [myAvatar](int value) { myAvatar->setSnapTurn(value == 0); }; auto preference = new RadioButtonsPreference(VR_MOVEMENT, "Snap turn / Smooth turn", getter, setter); QStringList items; - items << "Snap turn" - << "Smooth turn"; + items << "Snap turn" << "Smooth turn"; preference->setHeading("Rotation mode"); preference->setItems(items); preferences->addPreference(preference); @@ -363,9 +348,7 @@ void setupPreferences() { auto setter = [myAvatar](int index) { myAvatar->setControlScheme(index); }; auto preference = new RadioButtonsPreference(VR_MOVEMENT, "Control Scheme", getter, setter); QStringList items; - items << "Default" - << "Analog" - << "Analog++"; + items << "Default" << "Analog" << "Analog++"; preference->setHeading("Control Scheme Selection"); preference->setItems(items); preferences->addPreference(preference); @@ -417,13 +400,9 @@ void setupPreferences() { break; } }; - auto preference = - new RadioButtonsPreference(VR_MOVEMENT, "Auto / Force Sit / Force Stand / Disable Recenter", getter, setter); + auto preference = new RadioButtonsPreference(VR_MOVEMENT, "Auto / Force Sit / Force Stand / Disable Recenter", getter, setter); QStringList items; - items << "Auto - turns on avatar leaning when standing in real world" - << "Seated - disables all avatar leaning while sitting in real world" - << "Standing - enables avatar leaning while sitting in real world" - << "Disabled - allows avatar sitting on the floor [Experimental]"; + items << "Auto - turns on avatar leaning when standing in real world" << "Seated - disables all avatar leaning while sitting in real world" << "Standing - enables avatar leaning while sitting in real world" << "Disabled - allows avatar sitting on the floor [Experimental]"; preference->setHeading("Avatar leaning behavior"); preference->setItems(items); preferences->addPreference(preference); @@ -463,22 +442,14 @@ void setupPreferences() { static const QString AUDIO_BUFFERS("Audio Buffers"); { - auto getter = []() -> bool { - return !DependencyManager::get()->getReceivedAudioStream().dynamicJitterBufferEnabled(); - }; - auto setter = [](bool value) { - DependencyManager::get()->getReceivedAudioStream().setDynamicJitterBufferEnabled(!value); - }; + auto getter = []()->bool { return !DependencyManager::get()->getReceivedAudioStream().dynamicJitterBufferEnabled(); }; + auto setter = [](bool value) { DependencyManager::get()->getReceivedAudioStream().setDynamicJitterBufferEnabled(!value); }; auto preference = new CheckPreference(AUDIO_BUFFERS, "Disable dynamic jitter buffer", getter, setter); preferences->addPreference(preference); } { - auto getter = []() -> float { - return DependencyManager::get()->getReceivedAudioStream().getStaticJitterBufferFrames(); - }; - auto setter = [](float value) { - DependencyManager::get()->getReceivedAudioStream().setStaticJitterBufferFrames(value); - }; + auto getter = []()->float { return DependencyManager::get()->getReceivedAudioStream().getStaticJitterBufferFrames(); }; + auto setter = [](float value) { DependencyManager::get()->getReceivedAudioStream().setStaticJitterBufferFrames(value); }; auto preference = new SpinnerPreference(AUDIO_BUFFERS, "Static jitter buffer frames", getter, setter); preference->setMin(0); preference->setMax(2000); From 64534913af8edf5e7eeb07b9990508b036be1963 Mon Sep 17 00:00:00 2001 From: amer cerkic Date: Fri, 7 Jun 2019 13:59:18 -0700 Subject: [PATCH 22/31] more vs changes udo --- interface/src/ui/PreferencesDialog.cpp | 101 ++++++++++++------------- 1 file changed, 50 insertions(+), 51 deletions(-) diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index a13d19741d..65595bac95 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -32,7 +32,7 @@ void setupPreferences() { auto myAvatar = DependencyManager::get()->getMyAvatar(); static const QString AVATAR_BASICS{ "Avatar Basics" }; { - auto getter = [myAvatar]() -> QString { return myAvatar->getDisplayName(); }; + auto getter = [myAvatar]()->QString { return myAvatar->getDisplayName(); }; auto setter = [myAvatar](const QString& value) { myAvatar->setDisplayName(value); }; auto preference = new EditPreference(AVATAR_BASICS, "Avatar display name (optional)", getter, setter); preference->setPlaceholderText("Not showing a name"); @@ -40,7 +40,7 @@ void setupPreferences() { } { - auto getter = [myAvatar]() -> QString { return myAvatar->getCollisionSoundURL(); }; + auto getter = [myAvatar]()->QString { return myAvatar->getCollisionSoundURL(); }; auto setter = [myAvatar](const QString& value) { myAvatar->setCollisionSoundURL(value); }; auto preference = new EditPreference(AVATAR_BASICS, "Avatar collision sound URL (optional)", getter, setter); preference->setPlaceholderText("Enter the URL of a sound to play when you bump into something"); @@ -48,7 +48,7 @@ void setupPreferences() { } { - auto getter = [myAvatar]() -> QString { return myAvatar->getFullAvatarURLFromPreferences().toString(); }; + auto getter = [myAvatar]()->QString { return myAvatar->getFullAvatarURLFromPreferences().toString(); }; auto setter = [myAvatar](const QString& value) { myAvatar->useFullAvatarURL(value, ""); qApp->clearAvatarOverrideUrl(); }; auto preference = new AvatarPreference(AVATAR_BASICS, "Appearance", getter, setter); preferences->addPreference(preference); @@ -71,7 +71,7 @@ void setupPreferences() { wodSlider->setStep(0.25f); preferences->addPreference(wodSlider); - auto getterShadow = []() -> bool { + auto getterShadow = []()->bool { auto menu = Menu::getInstance(); return menu->isOptionChecked(MenuOption::Shadows); }; @@ -83,15 +83,14 @@ void setupPreferences() { } { - auto getter = []() -> QString { + auto getter = []()->QString { RefreshRateManager::RefreshRateProfile refreshRateProfile = qApp->getRefreshRateManager().getRefreshRateProfile(); return QString::fromStdString(RefreshRateManager::refreshRateProfileToString(refreshRateProfile)); }; auto setter = [](QString value) { std::string profileName = value.toStdString(); - RefreshRateManager::RefreshRateProfile refreshRateProfile = - RefreshRateManager::refreshRateProfileFromString(profileName); + RefreshRateManager::RefreshRateProfile refreshRateProfile = RefreshRateManager::refreshRateProfileFromString(profileName); qApp->getRefreshRateManager().setRefreshRateProfile(refreshRateProfile); }; @@ -108,19 +107,19 @@ void setupPreferences() { // UI static const QString UI_CATEGORY{ "User Interface" }; { - auto getter = []() -> bool { return qApp->getSettingConstrainToolbarPosition(); }; + auto getter = []()->bool { return qApp->getSettingConstrainToolbarPosition(); }; auto setter = [](bool value) { qApp->setSettingConstrainToolbarPosition(value); }; preferences->addPreference(new CheckPreference(UI_CATEGORY, "Constrain Toolbar Position to Horizontal Center", getter, setter)); } { - auto getter = []() -> bool { return qApp->getAwayStateWhenFocusLostInVREnabled(); }; + auto getter = []()->bool { return qApp->getAwayStateWhenFocusLostInVREnabled(); }; auto setter = [](bool value) { qApp->setAwayStateWhenFocusLostInVREnabled(value); }; preferences->addPreference(new CheckPreference(UI_CATEGORY, "Go into away state when interface window loses focus in VR", getter, setter)); } { - auto getter = []() -> float { return qApp->getDesktopTabletScale(); }; + auto getter = []()->float { return qApp->getDesktopTabletScale(); }; auto setter = [](float value) { qApp->setDesktopTabletScale(value); }; auto preference = new SpinnerPreference(UI_CATEGORY, "Desktop Tablet Scale %", getter, setter); preference->setMin(20); @@ -129,7 +128,7 @@ void setupPreferences() { } { - auto getter = []() -> float { return qApp->getHMDTabletScale(); }; + auto getter = []()->float { return qApp->getHMDTabletScale(); }; auto setter = [](float value) { qApp->setHMDTabletScale(value); }; auto preference = new SpinnerPreference(UI_CATEGORY, "VR Tablet Scale %", getter, setter); preference->setMin(20); @@ -139,25 +138,25 @@ void setupPreferences() { { static const QString RETICLE_ICON_NAME = { Cursor::Manager::getIconName(Cursor::Icon::RETICLE) }; - auto getter = []() -> bool { return qApp->getPreferredCursor() == RETICLE_ICON_NAME; }; + auto getter = []()->bool { return qApp->getPreferredCursor() == RETICLE_ICON_NAME; }; auto setter = [](bool value) { qApp->setPreferredCursor(value ? RETICLE_ICON_NAME : QString()); }; preferences->addPreference(new CheckPreference(UI_CATEGORY, "Use reticle cursor instead of arrow", getter, setter)); } { - auto getter = []() -> bool { return qApp->getMiniTabletEnabled(); }; + auto getter = []()->bool { return qApp->getMiniTabletEnabled(); }; auto setter = [](bool value) { qApp->setMiniTabletEnabled(value); }; preferences->addPreference(new CheckPreference(UI_CATEGORY, "Use mini tablet", getter, setter)); } { - auto getter = []() -> int { return DependencyManager::get()->getUse3DKeyboard(); }; + auto getter = []()->int { return DependencyManager::get()->getUse3DKeyboard(); }; auto setter = [](int value) { DependencyManager::get()->setUse3DKeyboard(value); }; preferences->addPreference(new CheckPreference(UI_CATEGORY, "Use Virtual Keyboard", getter, setter)); } { - auto getter = []() -> bool { return DependencyManager::get()->getPreferMalletsOverLasers() ? 1 : 0; }; + auto getter = []()->bool { return DependencyManager::get()->getPreferMalletsOverLasers() ? 1 : 0; }; auto setter = [](bool value) { return DependencyManager::get()->setPreferMalletsOverLasers((bool)value); }; auto preference = new RadioButtonsPreference(UI_CATEGORY, "Keyboard laser / mallets", getter, setter); QStringList items; @@ -169,7 +168,7 @@ void setupPreferences() { { - auto getter = []() -> int { return qApp->getPreferStylusOverLaser() ? 1 : 0; }; + auto getter = []()->int { return qApp->getPreferStylusOverLaser() ? 1 : 0; }; auto setter = [](int value) { qApp->setPreferStylusOverLaser((bool)value); }; auto preference = new RadioButtonsPreference(UI_CATEGORY, "Tablet stylys / laser", getter, setter); QStringList items; @@ -181,7 +180,7 @@ void setupPreferences() { static const QString VIEW_CATEGORY{ "View" }; { - auto getter = [myAvatar]() -> float { return myAvatar->getRealWorldFieldOfView(); }; + auto getter = [myAvatar]()->float { return myAvatar->getRealWorldFieldOfView(); }; auto setter = [myAvatar](float value) { myAvatar->setRealWorldFieldOfView(value); }; auto preference = new SpinnerPreference(VIEW_CATEGORY, "Real world vertical field of view (angular size of monitor)", getter, setter); preference->setMin(1); @@ -189,7 +188,7 @@ void setupPreferences() { preferences->addPreference(preference); } { - auto getter = []() -> float { return qApp->getFieldOfView(); }; + auto getter = []()->float { return qApp->getFieldOfView(); }; auto setter = [](float value) { qApp->setFieldOfView(value); }; auto preference = new SpinnerPreference(VIEW_CATEGORY, "Vertical field of view", getter, setter); preference->setMin(1); @@ -209,13 +208,13 @@ void setupPreferences() { // Snapshots static const QString SNAPSHOTS{ "Snapshots" }; { - auto getter = []() -> QString { return DependencyManager::get()->_snapshotsLocation.get(); }; + auto getter = []()->QString { return DependencyManager::get()->_snapshotsLocation.get(); }; auto setter = [](const QString& value) { DependencyManager::get()->_snapshotsLocation.set(value); emit DependencyManager::get()->snapshotLocationSet(value); }; auto preference = new BrowsePreference(SNAPSHOTS, "Put my snapshots here", getter, setter); preferences->addPreference(preference); } { - auto getter = []() -> float { return SnapshotAnimated::snapshotAnimatedDuration.get(); }; + auto getter = []()->float { return SnapshotAnimated::snapshotAnimatedDuration.get(); }; auto setter = [](float value) { SnapshotAnimated::snapshotAnimatedDuration.set(value); }; auto preference = new SpinnerPreference(SNAPSHOTS, "Animated Snapshot Duration", getter, setter); preference->setMin(1); @@ -225,7 +224,7 @@ void setupPreferences() { } { - auto getter = []() -> bool { return !Menu::getInstance()->isOptionChecked(MenuOption::DisableActivityLogger); }; + auto getter = []()->bool { return !Menu::getInstance()->isOptionChecked(MenuOption::DisableActivityLogger); }; auto setter = [](bool value) { Menu::getInstance()->setIsOptionChecked(MenuOption::DisableActivityLogger, !value); }; preferences->addPreference(new CheckPreference("Privacy", "Send data - High Fidelity uses information provided by your " "client to improve the product through the logging of errors, tracking of usage patterns, " @@ -233,14 +232,14 @@ void setupPreferences() { "this information you are helping to improve the product. ", getter, setter)); } - static const QString AVATAR_TUNING{ "Avatar Tuning" }; + static const QString AVATAR_TUNING { "Avatar Tuning" }; { - auto getter = [myAvatar]() -> QString { return myAvatar->getDominantHand(); }; + auto getter = [myAvatar]()->QString { return myAvatar->getDominantHand(); }; auto setter = [myAvatar](const QString& value) { myAvatar->setDominantHand(value); }; preferences->addPreference(new PrimaryHandPreference(AVATAR_TUNING, "Dominant Hand", getter, setter)); } { - auto getter = [myAvatar]() -> float { return myAvatar->getTargetScale(); }; + auto getter = [myAvatar]()->float { return myAvatar->getTargetScale(); }; auto setter = [myAvatar](float value) { myAvatar->setTargetScale(value); }; auto preference = new SpinnerSliderPreference(AVATAR_TUNING, "Avatar Scale", getter, setter); preference->setMin(0.25); @@ -256,7 +255,7 @@ void setupPreferences() { } { - auto getter = [myAvatar]() -> QString { return myAvatar->getAnimGraphOverrideUrl().toString(); }; + auto getter = [myAvatar]()->QString { return myAvatar->getAnimGraphOverrideUrl().toString(); }; auto setter = [myAvatar](const QString& value) { myAvatar->setAnimGraphOverrideUrl(QUrl(value)); }; auto preference = new EditPreference(AVATAR_TUNING, "Avatar animation JSON", getter, setter); preference->setPlaceholderText("default"); @@ -264,7 +263,7 @@ void setupPreferences() { } { - auto getter = [myAvatar]() -> bool { return myAvatar->getCollisionsEnabled(); }; + auto getter = [myAvatar]()->bool { return myAvatar->getCollisionsEnabled(); }; auto setter = [myAvatar](bool value) { myAvatar->setCollisionsEnabled(value); }; auto preference = new CheckPreference(AVATAR_TUNING, "Enable Avatar collisions", getter, setter); preferences->addPreference(preference); @@ -273,7 +272,7 @@ void setupPreferences() { static const QString FACE_TRACKING{ "Face Tracking" }; { #ifdef HAVE_DDE - auto getter = []() -> float { return DependencyManager::get()->getEyeClosingThreshold(); }; + auto getter = []()->float { return DependencyManager::get()->getEyeClosingThreshold(); }; auto setter = [](float value) { DependencyManager::get()->setEyeClosingThreshold(value); }; preferences->addPreference(new SliderPreference(FACE_TRACKING, "Eye Closing Threshold", getter, setter)); #endif @@ -281,44 +280,44 @@ void setupPreferences() { { - auto getter = []() -> float { return FaceTracker::getEyeDeflection(); }; + auto getter = []()->float { return FaceTracker::getEyeDeflection(); }; auto setter = [](float value) { FaceTracker::setEyeDeflection(value); }; preferences->addPreference(new SliderPreference(FACE_TRACKING, "Eye Deflection", getter, setter)); } static const QString VR_MOVEMENT{ "VR Movement" }; { - auto getter = [myAvatar]() -> bool { return myAvatar->getAllowTeleporting(); }; + auto getter = [myAvatar]()->bool { return myAvatar->getAllowTeleporting(); }; auto setter = [myAvatar](bool value) { myAvatar->setAllowTeleporting(value); }; auto preference = new CheckPreference(VR_MOVEMENT, "Teleporting", getter, setter); preferences->addPreference(preference); } { - auto getter = [myAvatar]() -> bool { return myAvatar->useAdvancedMovementControls(); }; + auto getter = [myAvatar]()->bool { return myAvatar->useAdvancedMovementControls(); }; auto setter = [myAvatar](bool value) { myAvatar->setUseAdvancedMovementControls(value); }; auto preference = new CheckPreference(VR_MOVEMENT, "Walking", getter, setter); preferences->addPreference(preference); } { - auto getter = [myAvatar]() -> bool { return myAvatar->getStrafeEnabled(); }; + auto getter = [myAvatar]()->bool { return myAvatar->getStrafeEnabled(); }; auto setter = [myAvatar](bool value) { myAvatar->setStrafeEnabled(value); }; preferences->addPreference(new CheckPreference(VR_MOVEMENT, "Strafing", getter, setter)); } { - auto getter = [myAvatar]() -> bool { return myAvatar->getFlyingHMDPref(); }; + auto getter = [myAvatar]()->bool { return myAvatar->getFlyingHMDPref(); }; auto setter = [myAvatar](bool value) { myAvatar->setFlyingHMDPref(value); }; auto preference = new CheckPreference(VR_MOVEMENT, "Jumping and flying", getter, setter); preference->setIndented(true); preferences->addPreference(preference); } { - auto getter = [myAvatar]() -> bool { return myAvatar->hoverWhenUnsupported(); }; + auto getter = [myAvatar]()->bool { return myAvatar->hoverWhenUnsupported(); }; auto setter = [myAvatar](bool value) { myAvatar->setHoverWhenUnsupported(value); }; auto preference = new CheckPreference(VR_MOVEMENT, "Hover When Unsupported", getter, setter); preferences->addPreference(preference); } { - auto getter = [myAvatar]() -> int { return myAvatar->getMovementReference(); }; + auto getter = [myAvatar]()->int { return myAvatar->getMovementReference(); }; auto setter = [myAvatar](int value) { myAvatar->setMovementReference(value); }; //auto preference = new CheckPreference(VR_MOVEMENT, "Hand-Relative Movement", getter, setter); auto preference = new RadioButtonsPreference(VR_MOVEMENT, "Movement Direction", getter, setter); @@ -329,12 +328,12 @@ void setupPreferences() { preferences->addPreference(preference); } { - auto getter = [myAvatar]() -> QString { return myAvatar->getDominantHand(); }; + auto getter = [myAvatar]()->QString { return myAvatar->getDominantHand(); }; auto setter = [myAvatar](const QString& value) { myAvatar->setDominantHand(value); }; preferences->addPreference(new PrimaryHandPreference(VR_MOVEMENT, "Dominant Hand", getter, setter)); } { - auto getter = [myAvatar]() -> int { return myAvatar->getSnapTurn() ? 0 : 1; }; + auto getter = [myAvatar]()->int { return myAvatar->getSnapTurn() ? 0 : 1; }; auto setter = [myAvatar](int value) { myAvatar->setSnapTurn(value == 0); }; auto preference = new RadioButtonsPreference(VR_MOVEMENT, "Snap turn / Smooth turn", getter, setter); QStringList items; @@ -344,7 +343,7 @@ void setupPreferences() { preferences->addPreference(preference); } { - auto getter = [myAvatar]() -> int { return myAvatar->getControlScheme(); }; + auto getter = [myAvatar]()->int { return myAvatar->getControlScheme(); }; auto setter = [myAvatar](int index) { myAvatar->setControlScheme(index); }; auto preference = new RadioButtonsPreference(VR_MOVEMENT, "Control Scheme", getter, setter); QStringList items; @@ -354,7 +353,7 @@ void setupPreferences() { preferences->addPreference(preference); } { - auto getter = [myAvatar]() -> float { return myAvatar->getAnalogPlusWalkSpeed(); }; + auto getter = [myAvatar]()->float { return myAvatar->getAnalogPlusWalkSpeed(); }; auto setter = [myAvatar](float value) { myAvatar->setAnalogPlusWalkSpeed(value); }; auto preference = new SpinnerSliderPreference(VR_MOVEMENT, "Analog++ Walk Speed", getter, setter); preference->setMin(6.0f); @@ -364,16 +363,16 @@ void setupPreferences() { preferences->addPreference(preference); } { - auto getter = [myAvatar]() -> bool { return myAvatar->getShowPlayArea(); }; + auto getter = [myAvatar]()->bool { return myAvatar->getShowPlayArea(); }; auto setter = [myAvatar](bool value) { myAvatar->setShowPlayArea(value); }; auto preference = new CheckPreference(VR_MOVEMENT, "Show room boundaries while teleporting", getter, setter); preferences->addPreference(preference); } { - auto getter = [myAvatar]() -> int { + auto getter = [myAvatar]()->int { switch (myAvatar->getUserRecenterModel()) { case MyAvatar::SitStandModelType::Auto: - default: + default: return 0; case MyAvatar::SitStandModelType::ForceSit: return 1; @@ -408,7 +407,7 @@ void setupPreferences() { preferences->addPreference(preference); } { - auto getter = [=]() -> float { return myAvatar->getUserHeight(); }; + auto getter = [=]()->float { return myAvatar->getUserHeight(); }; auto setter = [=](float value) { myAvatar->setUserHeight(value); }; auto preference = new SpinnerPreference(VR_MOVEMENT, "User real-world height (meters)", getter, setter); preference->setMin(1.0f); @@ -420,7 +419,7 @@ void setupPreferences() { static const QString AVATAR_CAMERA{ "Mouse Sensitivity" }; { - auto getter = [myAvatar]() -> float { return myAvatar->getPitchSpeed(); }; + auto getter = [myAvatar]()->float { return myAvatar->getPitchSpeed(); }; auto setter = [myAvatar](float value) { myAvatar->setPitchSpeed(value); }; auto preference = new SpinnerSliderPreference(AVATAR_CAMERA, "Y input:", getter, setter); preference->setMin(1.0f); @@ -430,7 +429,7 @@ void setupPreferences() { preferences->addPreference(preference); } { - auto getter = [myAvatar]() -> float { return myAvatar->getYawSpeed(); }; + auto getter = [myAvatar]()->float { return myAvatar->getYawSpeed(); }; auto setter = [myAvatar](float value) { myAvatar->setYawSpeed(value); }; auto preference = new SpinnerSliderPreference(AVATAR_CAMERA, "X input:", getter, setter); preference->setMin(1.0f); @@ -457,13 +456,13 @@ void setupPreferences() { preferences->addPreference(preference); } { - auto getter = []() -> bool { return !DependencyManager::get()->getOutputStarveDetectionEnabled(); }; + auto getter = []()->bool { return !DependencyManager::get()->getOutputStarveDetectionEnabled(); }; auto setter = [](bool value) { DependencyManager::get()->setOutputStarveDetectionEnabled(!value); }; auto preference = new CheckPreference(AUDIO_BUFFERS, "Disable output starve detection", getter, setter); preferences->addPreference(preference); } { - auto getter = []() -> float { return DependencyManager::get()->getOutputBufferSize(); }; + auto getter = []()->float { return DependencyManager::get()->getOutputBufferSize(); }; auto setter = [](float value) { DependencyManager::get()->setOutputBufferSize(value); }; auto preference = new SpinnerPreference(AUDIO_BUFFERS, "Output buffer initial frames", getter, setter); preference->setMin(AudioClient::MIN_BUFFER_FRAMES); @@ -473,13 +472,13 @@ void setupPreferences() { } #if DEV_BUILD || PR_BUILD { - auto getter = []() -> bool { return DependencyManager::get()->isSimulatingJitter(); }; + auto getter = []()->bool { return DependencyManager::get()->isSimulatingJitter(); }; auto setter = [](bool value) { return DependencyManager::get()->setIsSimulatingJitter(value); }; auto preference = new CheckPreference(AUDIO_BUFFERS, "Packet jitter simulator", getter, setter); preferences->addPreference(preference); } { - auto getter = []() -> float { return DependencyManager::get()->getGateThreshold(); }; + auto getter = []()->float { return DependencyManager::get()->getGateThreshold(); }; auto setter = [](float value) { return DependencyManager::get()->setGateThreshold(value); }; auto preference = new SpinnerPreference(AUDIO_BUFFERS, "Packet throttle threshold", getter, setter); preference->setMin(1); @@ -494,8 +493,8 @@ void setupPreferences() { QWeakPointer nodeListWeak = DependencyManager::get(); { - static const int MIN_PORT_NUMBER{ 0 }; - static const int MAX_PORT_NUMBER{ 65535 }; + static const int MIN_PORT_NUMBER { 0 }; + static const int MAX_PORT_NUMBER { 65535 }; auto getter = [nodeListWeak] { auto nodeList = nodeListWeak.lock(); if (nodeList) { @@ -517,7 +516,7 @@ void setupPreferences() { } { - auto getter = []() -> float { return qApp->getMaxOctreePacketsPerSecond(); }; + auto getter = []()->float { return qApp->getMaxOctreePacketsPerSecond(); }; auto setter = [](float value) { qApp->setMaxOctreePacketsPerSecond(value); }; auto preference = new SpinnerPreference(NETWORKING, "Max entities packets sent each second", getter, setter); preference->setMin(60); From c61f0bcf3ec38ba7fd30f5768fc632629673ae3c Mon Sep 17 00:00:00 2001 From: amer cerkic Date: Fri, 7 Jun 2019 14:07:06 -0700 Subject: [PATCH 23/31] more vs cleanup --- interface/src/ui/PreferencesDialog.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index 65595bac95..9149762fa4 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -55,7 +55,7 @@ void setupPreferences() { } // Graphics quality - static const QString GRAPHICS_QUALITY{ "Graphics Quality" }; + static const QString GRAPHICS_QUALITY { "Graphics Quality" }; { auto getter = []()->float { return DependencyManager::get()->getWorldDetailQuality(); @@ -105,7 +105,7 @@ void setupPreferences() { } // UI - static const QString UI_CATEGORY{ "User Interface" }; + static const QString UI_CATEGORY { "User Interface" }; { auto getter = []()->bool { return qApp->getSettingConstrainToolbarPosition(); }; auto setter = [](bool value) { qApp->setSettingConstrainToolbarPosition(value); }; @@ -206,7 +206,7 @@ void setupPreferences() { }*/ // Snapshots - static const QString SNAPSHOTS{ "Snapshots" }; + static const QString SNAPSHOTS { "Snapshots" }; { auto getter = []()->QString { return DependencyManager::get()->_snapshotsLocation.get(); }; auto setter = [](const QString& value) { DependencyManager::get()->_snapshotsLocation.set(value); emit DependencyManager::get()->snapshotLocationSet(value); }; From 049ff8e618f1584c8fa45c7e89ceec29d0bdf9e8 Mon Sep 17 00:00:00 2001 From: amer cerkic Date: Fri, 7 Jun 2019 14:11:13 -0700 Subject: [PATCH 24/31] fixed last space --- interface/src/ui/PreferencesDialog.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index 9149762fa4..e0505770f5 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -30,7 +30,7 @@ void setupPreferences() { auto preferences = DependencyManager::get(); auto myAvatar = DependencyManager::get()->getMyAvatar(); - static const QString AVATAR_BASICS{ "Avatar Basics" }; + static const QString AVATAR_BASICS { "Avatar Basics" }; { auto getter = [myAvatar]()->QString { return myAvatar->getDisplayName(); }; auto setter = [myAvatar](const QString& value) { myAvatar->setDisplayName(value); }; From f2c6cb79f74900597aa21289e8e2acf77fad1489 Mon Sep 17 00:00:00 2001 From: amer cerkic Date: Fri, 7 Jun 2019 14:17:49 -0700 Subject: [PATCH 25/31] if formatting --- interface/src/Application.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index eaaf9502cf..0e873cbb70 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -5182,7 +5182,7 @@ ivec2 Application::getMouse() const { FaceTracker* Application::getActiveFaceTracker() { auto dde = DependencyManager::get(); - if(dde && dde->isActive()){ + if (dde && dde->isActive()) { return static_cast(dde.data()); } From 129d96a997d0557e89de76c8aa0322e53382dede Mon Sep 17 00:00:00 2001 From: SamGondelman Date: Fri, 7 Jun 2019 14:51:24 -0700 Subject: [PATCH 26/31] get rid of lightmapMap --- .../src/RenderableMaterialEntityItem.cpp | 4 +-- .../src/RenderableShapeEntityItem.cpp | 4 +-- libraries/entities/src/MaterialEntityItem.h | 2 +- .../src/graphics-scripting/Forward.h | 4 +-- .../GraphicsScriptingInterface.cpp | 8 ++--- .../graphics-scripting/ScriptableModel.cpp | 6 ++-- libraries/graphics/src/graphics/Material.cpp | 2 +- libraries/graphics/src/graphics/Material.h | 14 ++++---- .../src/graphics/MaterialTextures.slh | 4 +-- .../src/material-networking/MaterialCache.cpp | 20 +++++------ .../src/material-networking/MaterialCache.h | 2 +- .../render-utils/src/MeshPartPayload.cpp | 8 ++--- .../render-utils/src/RenderPipelines.cpp | 36 +++++++++---------- libraries/render/src/render/ShapePipeline.h | 10 +++--- 14 files changed, 62 insertions(+), 62 deletions(-) diff --git a/libraries/entities-renderer/src/RenderableMaterialEntityItem.cpp b/libraries/entities-renderer/src/RenderableMaterialEntityItem.cpp index 9a634a85ad..01eac7b203 100644 --- a/libraries/entities-renderer/src/RenderableMaterialEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderableMaterialEntityItem.cpp @@ -257,7 +257,7 @@ ShapeKey MaterialEntityRenderer::getShapeKey() { bool isTranslucent = drawMaterialKey.isTranslucent(); bool hasTangents = drawMaterialKey.isNormalMap(); - bool hasLightmap = drawMaterialKey.isLightmapMap(); + bool hasLightmap = drawMaterialKey.isLightMap(); bool isUnlit = drawMaterialKey.isUnlit(); ShapeKey::Builder builder; @@ -270,7 +270,7 @@ ShapeKey MaterialEntityRenderer::getShapeKey() { builder.withTangents(); } if (hasLightmap) { - builder.withLightmap(); + builder.withLightMap(); } if (isUnlit) { builder.withUnlit(); diff --git a/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp b/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp index fbc24cb4a5..7faebfdf56 100644 --- a/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp @@ -197,7 +197,7 @@ ShapeKey ShapeEntityRenderer::getShapeKey() { bool isTranslucent = drawMaterialKey.isTranslucent(); bool hasTangents = drawMaterialKey.isNormalMap(); - bool hasLightmap = drawMaterialKey.isLightmapMap(); + bool hasLightmap = drawMaterialKey.isLightMap(); bool isUnlit = drawMaterialKey.isUnlit(); ShapeKey::Builder builder; @@ -210,7 +210,7 @@ ShapeKey ShapeEntityRenderer::getShapeKey() { builder.withTangents(); } if (hasLightmap) { - builder.withLightmap(); + builder.withLightMap(); } if (isUnlit) { builder.withUnlit(); diff --git a/libraries/entities/src/MaterialEntityItem.h b/libraries/entities/src/MaterialEntityItem.h index b9e83a7fe5..717ceb4ee0 100644 --- a/libraries/entities/src/MaterialEntityItem.h +++ b/libraries/entities/src/MaterialEntityItem.h @@ -88,7 +88,7 @@ private: // emissive, albedo // urls to textures: // emissiveMap, albedoMap (set opacityMap = albedoMap for transparency), metallicMap or specularMap, roughnessMap or glossMap, - // normalMap or bumpMap, occlusionMap, lightmapMap (broken, FIXME), scatteringMap (only works if normal mapped) + // normalMap or bumpMap, occlusionMap, lightMap (broken, FIXME), scatteringMap (only works if normal mapped) QString _materialURL; // Type of material. "uv" or "projected". MaterialMappingMode _materialMappingMode { UV }; diff --git a/libraries/graphics-scripting/src/graphics-scripting/Forward.h b/libraries/graphics-scripting/src/graphics-scripting/Forward.h index 6d1b9d83d2..428c08e9f6 100644 --- a/libraries/graphics-scripting/src/graphics-scripting/Forward.h +++ b/libraries/graphics-scripting/src/graphics-scripting/Forward.h @@ -57,7 +57,7 @@ namespace scriptable { * @property {string} normalMap * @property {string} bumpMap * @property {string} occlusionMap - * @property {string} lightmapMap + * @property {string} lightMap * @property {string} scatteringMap * @property {Mat4|string} texCoordTransform0 * @property {Mat4|string} texCoordTransform1 @@ -91,7 +91,7 @@ namespace scriptable { QString normalMap; QString bumpMap; QString occlusionMap; - QString lightmapMap; + QString lightMap; QString scatteringMap; std::array texCoordTransforms; diff --git a/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingInterface.cpp b/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingInterface.cpp index eb4bfa197c..404e2d3ac6 100644 --- a/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingInterface.cpp +++ b/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingInterface.cpp @@ -430,10 +430,10 @@ namespace scriptable { obj.setProperty("occlusionMap", material.occlusionMap); } - if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::LIGHTMAP_MAP_BIT)) { - obj.setProperty("lightmapMap", FALLTHROUGH); - } else if (!material.lightmapMap.isEmpty()) { - obj.setProperty("lightmapMap", material.lightmapMap); + if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::LIGHT_MAP_BIT)) { + obj.setProperty("lightMap", FALLTHROUGH); + } else if (!material.lightMap.isEmpty()) { + obj.setProperty("lightMap", material.lightMap); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::SCATTERING_MAP_BIT)) { diff --git a/libraries/graphics-scripting/src/graphics-scripting/ScriptableModel.cpp b/libraries/graphics-scripting/src/graphics-scripting/ScriptableModel.cpp index 8825a26bfe..e9cc7930ae 100644 --- a/libraries/graphics-scripting/src/graphics-scripting/ScriptableModel.cpp +++ b/libraries/graphics-scripting/src/graphics-scripting/ScriptableModel.cpp @@ -39,7 +39,7 @@ scriptable::ScriptableMaterial& scriptable::ScriptableMaterial::operator=(const normalMap = material.normalMap; bumpMap = material.bumpMap; occlusionMap = material.occlusionMap; - lightmapMap = material.lightmapMap; + lightMap = material.lightMap; scatteringMap = material.scatteringMap; defaultFallthrough = material.defaultFallthrough; @@ -110,9 +110,9 @@ scriptable::ScriptableMaterial::ScriptableMaterial(const graphics::MaterialPoint occlusionMap = map->getTextureSource()->getUrl().toString(); } - map = material->getTextureMap(graphics::Material::MapChannel::LIGHTMAP_MAP); + map = material->getTextureMap(graphics::Material::MapChannel::LIGHT_MAP); if (map && map->getTextureSource()) { - lightmapMap = map->getTextureSource()->getUrl().toString(); + lightMap = map->getTextureSource()->getUrl().toString(); } map = material->getTextureMap(graphics::Material::MapChannel::SCATTERING_MAP); diff --git a/libraries/graphics/src/graphics/Material.cpp b/libraries/graphics/src/graphics/Material.cpp index 3ef407b7d9..6be8ec5f68 100755 --- a/libraries/graphics/src/graphics/Material.cpp +++ b/libraries/graphics/src/graphics/Material.cpp @@ -129,7 +129,7 @@ void Material::setTextureMap(MapChannel channel, const TextureMapPointer& textur _texcoordTransforms[1] = (textureMap ? textureMap->getTextureTransform().getMatrix() : glm::mat4()); } - if (channel == MaterialKey::LIGHTMAP_MAP) { + if (channel == MaterialKey::LIGHT_MAP) { // update the texcoord1 with lightmap _texcoordTransforms[1] = (textureMap ? textureMap->getTextureTransform().getMatrix() : glm::mat4()); _lightmapParams = (textureMap ? glm::vec2(textureMap->getLightmapOffsetScale()) : glm::vec2(0.0, 1.0)); diff --git a/libraries/graphics/src/graphics/Material.h b/libraries/graphics/src/graphics/Material.h index 330feaa61c..25601c5743 100755 --- a/libraries/graphics/src/graphics/Material.h +++ b/libraries/graphics/src/graphics/Material.h @@ -53,7 +53,7 @@ public: ROUGHNESS_MAP_BIT, NORMAL_MAP_BIT, OCCLUSION_MAP_BIT, - LIGHTMAP_MAP_BIT, + LIGHT_MAP_BIT, SCATTERING_MAP_BIT, NUM_FLAGS, @@ -67,7 +67,7 @@ public: ROUGHNESS_MAP, NORMAL_MAP, OCCLUSION_MAP, - LIGHTMAP_MAP, + LIGHT_MAP, SCATTERING_MAP, NUM_MAP_CHANNELS, @@ -107,7 +107,7 @@ public: Builder& withNormalMap() { _flags.set(NORMAL_MAP_BIT); return (*this); } Builder& withOcclusionMap() { _flags.set(OCCLUSION_MAP_BIT); return (*this); } - Builder& withLightmapMap() { _flags.set(LIGHTMAP_MAP_BIT); return (*this); } + Builder& withLightMap() { _flags.set(LIGHT_MAP_BIT); return (*this); } Builder& withScatteringMap() { _flags.set(SCATTERING_MAP_BIT); return (*this); } // Convenient standard keys that we will keep on using all over the place @@ -157,8 +157,8 @@ public: void setOcclusionMap(bool value) { _flags.set(OCCLUSION_MAP_BIT, value); } bool isOcclusionMap() const { return _flags[OCCLUSION_MAP_BIT]; } - void setLightmapMap(bool value) { _flags.set(LIGHTMAP_MAP_BIT, value); } - bool isLightmapMap() const { return _flags[LIGHTMAP_MAP_BIT]; } + void setLightMap(bool value) { _flags.set(LIGHT_MAP_BIT, value); } + bool isLightMap() const { return _flags[LIGHT_MAP_BIT]; } void setScattering(bool value) { _flags.set(SCATTERING_VAL_BIT, value); } bool isScattering() const { return _flags[SCATTERING_VAL_BIT]; } @@ -235,8 +235,8 @@ public: Builder& withoutOcclusionMap() { _value.reset(MaterialKey::OCCLUSION_MAP_BIT); _mask.set(MaterialKey::OCCLUSION_MAP_BIT); return (*this); } Builder& withOcclusionMap() { _value.set(MaterialKey::OCCLUSION_MAP_BIT); _mask.set(MaterialKey::OCCLUSION_MAP_BIT); return (*this); } - Builder& withoutLightmapMap() { _value.reset(MaterialKey::LIGHTMAP_MAP_BIT); _mask.set(MaterialKey::LIGHTMAP_MAP_BIT); return (*this); } - Builder& withLightmapMap() { _value.set(MaterialKey::LIGHTMAP_MAP_BIT); _mask.set(MaterialKey::LIGHTMAP_MAP_BIT); return (*this); } + Builder& withoutLightMap() { _value.reset(MaterialKey::LIGHT_MAP_BIT); _mask.set(MaterialKey::LIGHT_MAP_BIT); return (*this); } + Builder& withLightMap() { _value.set(MaterialKey::LIGHT_MAP_BIT); _mask.set(MaterialKey::LIGHT_MAP_BIT); return (*this); } Builder& withoutScattering() { _value.reset(MaterialKey::SCATTERING_VAL_BIT); _mask.set(MaterialKey::SCATTERING_VAL_BIT); return (*this); } Builder& withScattering() { _value.set(MaterialKey::SCATTERING_VAL_BIT); _mask.set(MaterialKey::SCATTERING_VAL_BIT); return (*this); } diff --git a/libraries/graphics/src/graphics/MaterialTextures.slh b/libraries/graphics/src/graphics/MaterialTextures.slh index 92e76e5736..bf0416c7bf 100644 --- a/libraries/graphics/src/graphics/MaterialTextures.slh +++ b/libraries/graphics/src/graphics/MaterialTextures.slh @@ -178,7 +178,7 @@ float fetchScatteringMap(vec2 uv) { float <$occlusion$> = mix(1.0, fetchOcclusionMap(<$texcoord1$>), float((<$matKey$> & OCCLUSION_MAP_BIT) != 0)); <@endif@> <@if lightmap@> - vec3 <$lightmap$> = fetchLightmapMap(<$texcoord1$>); + vec3 <$lightmap$> = fetchLightMap(<$texcoord1$>); <@endif@> <@endfunc@> @@ -189,7 +189,7 @@ float fetchScatteringMap(vec2 uv) { <$declareMaterialTexMapArrayBuffer()$> LAYOUT(binding=GRAPHICS_TEXTURE_MATERIAL_EMISSIVE_LIGHTMAP) uniform sampler2D emissiveMap; -vec3 fetchLightmapMap(vec2 uv) { +vec3 fetchLightMap(vec2 uv) { vec2 lightmapParams = getTexMapArray()._lightmapParams; return (vec3(lightmapParams.x) + lightmapParams.y * texture(emissiveMap, uv).rgb); } diff --git a/libraries/material-networking/src/material-networking/MaterialCache.cpp b/libraries/material-networking/src/material-networking/MaterialCache.cpp index 745504fb3d..5e86ea506a 100644 --- a/libraries/material-networking/src/material-networking/MaterialCache.cpp +++ b/libraries/material-networking/src/material-networking/MaterialCache.cpp @@ -362,9 +362,9 @@ std::pair> NetworkMaterialResource if (value.isString()) { auto valueString = value.toString(); if (valueString == FALLTHROUGH) { - material->setPropertyDoesFallthrough(graphics::MaterialKey::FlagBit::LIGHTMAP_MAP_BIT); + material->setPropertyDoesFallthrough(graphics::MaterialKey::FlagBit::LIGHT_MAP_BIT); } else { - material->setLightmapMap(baseUrl.resolved(valueString)); + material->setLightMap(baseUrl.resolved(valueString)); } } } else if (key == "texCoordTransform0") { @@ -567,12 +567,12 @@ void NetworkMaterial::setScatteringMap(const QUrl& url) { } } -void NetworkMaterial::setLightmapMap(const QUrl& url) { - auto map = fetchTextureMap(url, image::TextureUsage::LIGHTMAP_TEXTURE, MapChannel::LIGHTMAP_MAP); +void NetworkMaterial::setLightMap(const QUrl& url) { + auto map = fetchTextureMap(url, image::TextureUsage::LIGHTMAP_TEXTURE, MapChannel::LIGHT_MAP); if (map) { //map->setTextureTransform(_lightmapTransform); //map->setLightmapOffsetScale(_lightmapParams.x, _lightmapParams.y); - setTextureMap(MapChannel::LIGHTMAP_MAP, map); + setTextureMap(MapChannel::LIGHT_MAP, map); } } @@ -640,14 +640,14 @@ NetworkMaterial::NetworkMaterial(const HFMMaterial& material, const QUrl& textur } if (!material.lightmapTexture.filename.isEmpty()) { - auto map = fetchTextureMap(textureBaseUrl, material.lightmapTexture, image::TextureUsage::LIGHTMAP_TEXTURE, MapChannel::LIGHTMAP_MAP); + auto map = fetchTextureMap(textureBaseUrl, material.lightmapTexture, image::TextureUsage::LIGHTMAP_TEXTURE, MapChannel::LIGHT_MAP); if (map) { _lightmapTransform = material.lightmapTexture.transform; _lightmapParams = material.lightmapParams; map->setTextureTransform(_lightmapTransform); map->setLightmapOffsetScale(_lightmapParams.x, _lightmapParams.y); } - setTextureMap(MapChannel::LIGHTMAP_MAP, map); + setTextureMap(MapChannel::LIGHT_MAP, map); } } @@ -660,7 +660,7 @@ void NetworkMaterial::setTextures(const QVariantMap& textureMap) { const auto& metallicName = getTextureName(MapChannel::METALLIC_MAP); const auto& occlusionName = getTextureName(MapChannel::OCCLUSION_MAP); const auto& emissiveName = getTextureName(MapChannel::EMISSIVE_MAP); - const auto& lightmapName = getTextureName(MapChannel::LIGHTMAP_MAP); + const auto& lightmapName = getTextureName(MapChannel::LIGHT_MAP); const auto& scatteringName = getTextureName(MapChannel::SCATTERING_MAP); if (!albedoName.isEmpty()) { @@ -715,12 +715,12 @@ void NetworkMaterial::setTextures(const QVariantMap& textureMap) { if (!lightmapName.isEmpty()) { auto url = textureMap.contains(lightmapName) ? textureMap[lightmapName].toUrl() : QUrl(); - auto map = fetchTextureMap(url, image::TextureUsage::LIGHTMAP_TEXTURE, MapChannel::LIGHTMAP_MAP); + auto map = fetchTextureMap(url, image::TextureUsage::LIGHTMAP_TEXTURE, MapChannel::LIGHT_MAP); if (map) { map->setTextureTransform(_lightmapTransform); map->setLightmapOffsetScale(_lightmapParams.x, _lightmapParams.y); } - setTextureMap(MapChannel::LIGHTMAP_MAP, map); + setTextureMap(MapChannel::LIGHT_MAP, map); } } diff --git a/libraries/material-networking/src/material-networking/MaterialCache.h b/libraries/material-networking/src/material-networking/MaterialCache.h index 7ed0453187..66e6b8250b 100644 --- a/libraries/material-networking/src/material-networking/MaterialCache.h +++ b/libraries/material-networking/src/material-networking/MaterialCache.h @@ -31,7 +31,7 @@ public: void setOcclusionMap(const QUrl& url); void setEmissiveMap(const QUrl& url); void setScatteringMap(const QUrl& url); - void setLightmapMap(const QUrl& url); + void setLightMap(const QUrl& url); bool isMissingTexture(); void checkResetOpacityMap(); diff --git a/libraries/render-utils/src/MeshPartPayload.cpp b/libraries/render-utils/src/MeshPartPayload.cpp index cb3aa76468..1a6e5dbadc 100644 --- a/libraries/render-utils/src/MeshPartPayload.cpp +++ b/libraries/render-utils/src/MeshPartPayload.cpp @@ -115,8 +115,8 @@ ShapeKey MeshPartPayload::getShapeKey() const { if (drawMaterialKey.isNormalMap()) { builder.withTangents(); } - if (drawMaterialKey.isLightmapMap()) { - builder.withLightmap(); + if (drawMaterialKey.isLightMap()) { + builder.withLightMap(); } return builder.build(); } @@ -354,7 +354,7 @@ void ModelMeshPartPayload::setShapeKey(bool invalidateShapeKey, PrimitiveMode pr bool isTranslucent = drawMaterialKey.isTranslucent(); bool hasTangents = drawMaterialKey.isNormalMap() && _hasTangents; - bool hasLightmap = drawMaterialKey.isLightmapMap(); + bool hasLightmap = drawMaterialKey.isLightMap(); bool isUnlit = drawMaterialKey.isUnlit(); bool isDeformed = _isBlendShaped || _isSkinned; @@ -374,7 +374,7 @@ void ModelMeshPartPayload::setShapeKey(bool invalidateShapeKey, PrimitiveMode pr builder.withTangents(); } if (hasLightmap) { - builder.withLightmap(); + builder.withLightMap(); } if (isUnlit) { builder.withUnlit(); diff --git a/libraries/render-utils/src/RenderPipelines.cpp b/libraries/render-utils/src/RenderPipelines.cpp index 2817abb4a1..69a76cce00 100644 --- a/libraries/render-utils/src/RenderPipelines.cpp +++ b/libraries/render-utils/src/RenderPipelines.cpp @@ -107,7 +107,7 @@ void initDeferredPipelines(render::ShapePlumber& plumber, const render::ShapePip model_translucent_normal_map, nullptr, nullptr); addPipeline( // FIXME: Ignore lightmap for translucents meshpart - Key::Builder().withMaterial().withTranslucent().withLightmap(), + Key::Builder().withMaterial().withTranslucent().withLightMap(), model_translucent, nullptr, nullptr); // Same thing but with Fade on addPipeline( @@ -127,21 +127,21 @@ void initDeferredPipelines(render::ShapePlumber& plumber, const render::ShapePip model_translucent_normal_map_fade, batchSetter, itemSetter); addPipeline( // FIXME: Ignore lightmap for translucents meshpart - Key::Builder().withMaterial().withTranslucent().withLightmap().withFade(), + Key::Builder().withMaterial().withTranslucent().withLightMap().withFade(), model_translucent_fade, batchSetter, itemSetter); // Lightmapped addPipeline( - Key::Builder().withMaterial().withLightmap(), + Key::Builder().withMaterial().withLightMap(), model_lightmap, nullptr, nullptr); addPipeline( - Key::Builder().withMaterial().withLightmap().withTangents(), + Key::Builder().withMaterial().withLightMap().withTangents(), model_lightmap_normal_map, nullptr, nullptr); // Same thing but with Fade on addPipeline( - Key::Builder().withMaterial().withLightmap().withFade(), + Key::Builder().withMaterial().withLightMap().withFade(), model_lightmap_fade, batchSetter, itemSetter); addPipeline( - Key::Builder().withMaterial().withLightmap().withTangents().withFade(), + Key::Builder().withMaterial().withLightMap().withTangents().withFade(), model_lightmap_normal_map_fade, batchSetter, itemSetter); // matrix palette skinned @@ -228,10 +228,10 @@ void initForwardPipelines(ShapePlumber& plumber) { // Opaques addPipeline(Key::Builder().withMaterial(), program::forward_model); - addPipeline(Key::Builder().withMaterial().withLightmap(), program::forward_model_lightmap); + addPipeline(Key::Builder().withMaterial().withLightMap(), program::forward_model_lightmap); addPipeline(Key::Builder().withMaterial().withUnlit(), program::forward_model_unlit); addPipeline(Key::Builder().withMaterial().withTangents(), program::forward_model_normal_map); - addPipeline(Key::Builder().withMaterial().withTangents().withLightmap(), program::forward_model_normal_map_lightmap); + addPipeline(Key::Builder().withMaterial().withTangents().withLightMap(), program::forward_model_normal_map_lightmap); // Deformed Opaques addPipeline(Key::Builder().withMaterial().withDeformed(), program::forward_deformed_model); @@ -581,7 +581,7 @@ void RenderPipelines::updateMultiMaterial(graphics::MultiMaterial& multiMaterial break; case graphics::MaterialKey::EMISSIVE_MAP_BIT: // Lightmap takes precendence over emissive map for legacy reasons - if (materialKey.isEmissiveMap() && !materialKey.isLightmapMap()) { + if (materialKey.isEmissiveMap() && !materialKey.isLightMap()) { auto itr = textureMaps.find(graphics::MaterialKey::EMISSIVE_MAP); if (itr != textureMaps.end()) { if (itr->second->isDefined()) { @@ -595,14 +595,14 @@ void RenderPipelines::updateMultiMaterial(graphics::MultiMaterial& multiMaterial forceDefault = true; } schemaKey.setEmissiveMap(true); - } else if (materialKey.isLightmapMap()) { + } else if (materialKey.isLightMap()) { // We'll set this later when we check the lightmap wasSet = true; } break; - case graphics::MaterialKey::LIGHTMAP_MAP_BIT: - if (materialKey.isLightmapMap()) { - auto itr = textureMaps.find(graphics::MaterialKey::LIGHTMAP_MAP); + case graphics::MaterialKey::LIGHT_MAP_BIT: + if (materialKey.isLightMap()) { + auto itr = textureMaps.find(graphics::MaterialKey::LIGHT_MAP); if (itr != textureMaps.end()) { if (itr->second->isDefined()) { drawMaterialTextures->setTexture(gr::Texture::MaterialEmissiveLightmap, itr->second->getTextureView()); @@ -614,7 +614,7 @@ void RenderPipelines::updateMultiMaterial(graphics::MultiMaterial& multiMaterial } else { forceDefault = true; } - schemaKey.setLightmapMap(true); + schemaKey.setLightMap(true); } break; case graphics::Material::TEXCOORDTRANSFORM0: @@ -712,12 +712,12 @@ void RenderPipelines::updateMultiMaterial(graphics::MultiMaterial& multiMaterial } break; case graphics::MaterialKey::EMISSIVE_MAP_BIT: - if (schemaKey.isEmissiveMap() && !schemaKey.isLightmapMap()) { + if (schemaKey.isEmissiveMap() && !schemaKey.isLightMap()) { drawMaterialTextures->setTexture(gr::Texture::MaterialEmissiveLightmap, textureCache->getGrayTexture()); } break; - case graphics::MaterialKey::LIGHTMAP_MAP_BIT: - if (schemaKey.isLightmapMap()) { + case graphics::MaterialKey::LIGHT_MAP_BIT: + if (schemaKey.isLightMap()) { drawMaterialTextures->setTexture(gr::Texture::MaterialEmissiveLightmap, textureCache->getBlackTexture()); } break; @@ -765,7 +765,7 @@ bool RenderPipelines::bindMaterials(graphics::MultiMaterial& multiMaterial, gpu: batch.setResourceTextureTable(multiMaterial.getTextureTable()); } else { if (renderMode != render::Args::RenderMode::SHADOW_RENDER_MODE) { - if (key.isLightmapMap()) { + if (key.isLightMap()) { defaultMaterialTextures->setTexture(gr::Texture::MaterialEmissiveLightmap, textureCache->getBlackTexture()); } else if (key.isEmissiveMap()) { defaultMaterialTextures->setTexture(gr::Texture::MaterialEmissiveLightmap, textureCache->getGrayTexture()); diff --git a/libraries/render/src/render/ShapePipeline.h b/libraries/render/src/render/ShapePipeline.h index 159d2ba6f3..ad91ea61ef 100644 --- a/libraries/render/src/render/ShapePipeline.h +++ b/libraries/render/src/render/ShapePipeline.h @@ -74,7 +74,7 @@ public: Builder& withMaterial() { _flags.set(MATERIAL); return (*this); } Builder& withTranslucent() { _flags.set(TRANSLUCENT); return (*this); } - Builder& withLightmap() { _flags.set(LIGHTMAP); return (*this); } + Builder& withLightMap() { _flags.set(LIGHTMAP); return (*this); } Builder& withTangents() { _flags.set(TANGENTS); return (*this); } Builder& withUnlit() { _flags.set(UNLIT); return (*this); } Builder& withDeformed() { _flags.set(DEFORMED); return (*this); } @@ -116,8 +116,8 @@ public: Builder& withTranslucent() { _flags.set(TRANSLUCENT); _mask.set(TRANSLUCENT); return (*this); } Builder& withOpaque() { _flags.reset(TRANSLUCENT); _mask.set(TRANSLUCENT); return (*this); } - Builder& withLightmap() { _flags.set(LIGHTMAP); _mask.set(LIGHTMAP); return (*this); } - Builder& withoutLightmap() { _flags.reset(LIGHTMAP); _mask.set(LIGHTMAP); return (*this); } + Builder& withLightMap() { _flags.set(LIGHTMAP); _mask.set(LIGHTMAP); return (*this); } + Builder& withoutLightMap() { _flags.reset(LIGHTMAP); _mask.set(LIGHTMAP); return (*this); } Builder& withTangents() { _flags.set(TANGENTS); _mask.set(TANGENTS); return (*this); } Builder& withoutTangents() { _flags.reset(TANGENTS); _mask.set(TANGENTS); return (*this); } @@ -160,7 +160,7 @@ public: }; bool useMaterial() const { return _flags[MATERIAL]; } - bool hasLightmap() const { return _flags[LIGHTMAP]; } + bool hasLightMap() const { return _flags[LIGHTMAP]; } bool hasTangents() const { return _flags[TANGENTS]; } bool isUnlit() const { return _flags[UNLIT]; } bool isTranslucent() const { return _flags[TRANSLUCENT]; } @@ -199,7 +199,7 @@ inline QDebug operator<<(QDebug debug, const ShapeKey& key) { } else { debug << "[ShapeKey:" << "useMaterial:" << key.useMaterial() - << "hasLightmap:" << key.hasLightmap() + << "hasLightmap:" << key.hasLightMap() << "hasTangents:" << key.hasTangents() << "isUnlit:" << key.isUnlit() << "isTranslucent:" << key.isTranslucent() From a0753f6393313f0ffebce8439bd5e91917213d3a Mon Sep 17 00:00:00 2001 From: Preston Bezos Date: Fri, 7 Jun 2019 15:41:44 -0700 Subject: [PATCH 27/31] removed ctrl+b and ctrl+n as shortcuts --- interface/resources/qml/hifi/Desktop.qml | 1 - interface/src/Application.cpp | 11 +---------- 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/interface/resources/qml/hifi/Desktop.qml b/interface/resources/qml/hifi/Desktop.qml index a97d94d91c..5fa6234504 100644 --- a/interface/resources/qml/hifi/Desktop.qml +++ b/interface/resources/qml/hifi/Desktop.qml @@ -25,7 +25,6 @@ OriginalDesktop.Desktop { Action { text: "Open Browser" - shortcut: "Ctrl+B" onTriggered: { console.log("Open browser"); browserBuilder.createObject(desktop); diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 4a0bce5103..a2813eaa57 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -4303,10 +4303,7 @@ void Application::keyPressEvent(QKeyEvent* event) { break; case Qt::Key_B: - if (isMeta) { - auto offscreenUi = getOffscreenUI(); - offscreenUi->load("Browser.qml"); - } else if (isOption) { + if (isOption) { controller::InputRecorder* inputRecorder = controller::InputRecorder::getInstance(); inputRecorder->stopPlayback(); } @@ -4345,12 +4342,6 @@ void Application::keyPressEvent(QKeyEvent* event) { } break; - case Qt::Key_N: - if (!isOption && !isShifted && isMeta) { - DependencyManager::get()->toggleIgnoreRadius(); - } - break; - case Qt::Key_S: if (isShifted && isMeta && !isOption) { Menu::getInstance()->triggerOption(MenuOption::SuppressShortTimings); From da071abd8b56333983755d1f0d32b705a6df9316 Mon Sep 17 00:00:00 2001 From: amer cerkic Date: Fri, 7 Jun 2019 16:25:04 -0700 Subject: [PATCH 28/31] wrapping the dependencyManager::get<> call with ifdef to prevent the log from constantly spitting out that instance does not exist --- interface/src/Application.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 0e873cbb70..7807014dd6 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -274,6 +274,8 @@ static QTimer pingTimer; #if defined(Q_OS_ANDROID) static bool DISABLE_WATCHDOG = true; #else + + static const QString DISABLE_WATCHDOG_FLAG{ "HIFI_DISABLE_WATCHDOG" }; static bool DISABLE_WATCHDOG = nsightActive() || QProcessEnvironment::systemEnvironment().contains(DISABLE_WATCHDOG_FLAG); #endif @@ -5180,11 +5182,13 @@ ivec2 Application::getMouse() const { } FaceTracker* Application::getActiveFaceTracker() { +#ifdef HAVE_DDE auto dde = DependencyManager::get(); if (dde && dde->isActive()) { return static_cast(dde.data()); } +#endif return nullptr; } @@ -7228,6 +7232,9 @@ void Application::nodeKilled(SharedNodePointer node) { _entityEditSender.nodeKilled(node); + qDebug() << "NODE KIlled: " << node->getType() << "********************************************************"; + + if (node->getType() == NodeType::AudioMixer) { QMetaObject::invokeMethod(DependencyManager::get().data(), "audioMixerKilled"); } else if (node->getType() == NodeType::EntityServer) { From b57e4869c8b29f19c42e16db6e25b9daa1a1df44 Mon Sep 17 00:00:00 2001 From: amer cerkic Date: Fri, 7 Jun 2019 16:26:21 -0700 Subject: [PATCH 29/31] removed debug info --- interface/src/Application.cpp | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 7807014dd6..8286f73ff0 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -274,8 +274,6 @@ static QTimer pingTimer; #if defined(Q_OS_ANDROID) static bool DISABLE_WATCHDOG = true; #else - - static const QString DISABLE_WATCHDOG_FLAG{ "HIFI_DISABLE_WATCHDOG" }; static bool DISABLE_WATCHDOG = nsightActive() || QProcessEnvironment::systemEnvironment().contains(DISABLE_WATCHDOG_FLAG); #endif @@ -7231,10 +7229,7 @@ void Application::nodeKilled(SharedNodePointer node) { _octreeProcessor.nodeKilled(node); _entityEditSender.nodeKilled(node); - - qDebug() << "NODE KIlled: " << node->getType() << "********************************************************"; - - + if (node->getType() == NodeType::AudioMixer) { QMetaObject::invokeMethod(DependencyManager::get().data(), "audioMixerKilled"); } else if (node->getType() == NodeType::EntityServer) { From 00bba828ee12471249307bfdf7e5642358510918 Mon Sep 17 00:00:00 2001 From: "Anthony J. Thibault" Date: Fri, 7 Jun 2019 16:41:56 -0700 Subject: [PATCH 30/31] Fix crash using Settings in the Tablet in VR This was introduced in Qt5.12.3. There are several issues in their bug tracker about this issue. https://bugreports.qt.io/browse/QTBUG-75516 https://bugreports.qt.io/browse/QTBUG-75335 To workaround this, we call Qt.createComponent() manually, instead of letting StackView do it for us. --- interface/resources/qml/hifi/tablet/TabletMenuStack.qml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/interface/resources/qml/hifi/tablet/TabletMenuStack.qml b/interface/resources/qml/hifi/tablet/TabletMenuStack.qml index fe636dafa5..76d170cba8 100644 --- a/interface/resources/qml/hifi/tablet/TabletMenuStack.qml +++ b/interface/resources/qml/hifi/tablet/TabletMenuStack.qml @@ -49,7 +49,10 @@ Item { } function pushSource(path) { - d.push(Qt.resolvedUrl("../../" + path)); + // Workaround issue https://bugreports.qt.io/browse/QTBUG-75516 in Qt 5.12.3 + // by creating the manually, instead of letting StackView do it for us. + var item = Qt.createComponent(Qt.resolvedUrl("../../" + path)); + d.push(item); if (d.currentItem.sendToScript !== undefined) { d.currentItem.sendToScript.connect(tabletMenu.sendToScript); } From 9d57f5ac6295a6b7b8d69a7322d4713f4fdd8747 Mon Sep 17 00:00:00 2001 From: Ken Cooke Date: Fri, 7 Jun 2019 18:35:39 -0700 Subject: [PATCH 31/31] Defer DependencyManager::destroy() until all ScriptAudioInjectors have been destroyed --- interface/src/Application.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 4a0bce5103..106ecfc606 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2759,7 +2759,6 @@ void Application::cleanupBeforeQuit() { // this must happen after QML, as there are unexplained audio crashes originating in qtwebengine QMetaObject::invokeMethod(DependencyManager::get().data(), "stop"); DependencyManager::destroy(); - DependencyManager::destroy(); DependencyManager::destroy(); // The PointerManager must be destroyed before the PickManager because when a Pointer is deleted, @@ -2819,6 +2818,7 @@ Application::~Application() { DependencyManager::destroy(); + DependencyManager::destroy(); DependencyManager::destroy(); DependencyManager::destroy(); DependencyManager::destroy();